diff --git a/.github/codeql-exceptions.md b/.github/codeql-exceptions.md new file mode 100644 index 000000000..08df04c6a --- /dev/null +++ b/.github/codeql-exceptions.md @@ -0,0 +1,19 @@ +# CodeQL exceptions + +This file records the rationale for individual alert dismissals. It is not consumed by +CodeQL and does not disable any rule. Dismiss only the matching alert in GitHub. + +## Alert 40: In-memory connection fingerprint + +- **Finding:** [Alert 40](https://github.com/microsoft/vscode-documentdb/security/code-scanning/40), + `js/insufficient-password-hash`, in [connectionFingerprint.ts](../src/documentdb/connectionFingerprint.ts). +- **Disposition:** False positive for password verification. The fingerprint compares connection + identities inside one running extension host. It is not used to verify a password. The helper omits + the URI authority password; other URI options can still contain credentials. HMAC-SHA-256 uses a + random host-local key, and neither the fingerprint nor the key is persisted, logged, or sent outside + that host. +- **Revisit if:** The fingerprint or key is persisted or shared, or the fingerprint is used for + password verification. + +See [decision 0021](../docs/ai-and-plans/features/connection-lifecycle/decisions.md#0021-key-the-in-memory-connection-fingerprint-per-extension-host) +for the implementation rationale. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 6cf90f558..0de8cb886 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -228,6 +228,9 @@ activation, such as a development-only command, must be listed with its reason i - Never log passwords, tokens, or connection strings - Use VS Code's secure storage for credentials - Validate all user inputs +- Follow [the CodeQL dismissal process](../CONTRIBUTING.md#44-codeql-alert-dismissals). Only dismiss + individual alerts with maintainer approval, and record the rationale in + [the CodeQL exception register](codeql-exceptions.md). ## Cluster ID Architecture (Dual ID Pattern) diff --git a/.github/skills/error-translation/SKILL.md b/.github/skills/error-translation/SKILL.md index 692077e78..7a50151d9 100644 --- a/.github/skills/error-translation/SKILL.md +++ b/.github/skills/error-translation/SKILL.md @@ -28,6 +28,36 @@ for, and errors that are already obsolete by the time they appear. Anything with a side effect belongs at the call site, which alone knows whether the user is watching, whether the operation was a read or a write, and which surface is right. +## Connection-lifecycle errors + +The lifecycle uses four typed error families. Preserve their classes and original `cause`; C-2 +types are contracts, not prose to infer from a message: + +| Error | Meaning | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `EntraSignInRequiredError` | Silent acquisition returned no session or the configured authentication provider changed; `reason` is `noSession` or `providerChanged`. | +| `EntraIdentityMismatchError` | Interactive acquisition returned a different Microsoft account from the pinned one. | +| `TokenCallbackError` | Any other OIDC callback throw for Microsoft Entra ID or managed identity. Its bounded `authMethod` records which one, and `cause` retains the original failure. | +| `ConnectionUnavailableError { reason }` | A bound client cannot be used. The reason is `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, `unreachable`, or `sessionEnded`. | + +Register `EntraSignInRequiredErrorExplainer` with provider id `entraSignInRequired` before the +general Entra explainer because the first explanation wins. That provider follows cyclic-safe +`cause` links and `MongoServerSelectionError.reason.servers[*].error`, and recognizes only the +typed sign-in-required and identity-mismatch errors. It explains those failures without exposing +private causes and asks the user to sign in with the original account when identities differ. + +Do not translate `ConnectionUnavailableError` through an infrastructure provider. The call site +knows whether the right response is a tree recovery action, a disabled webview dialog, or bounded +shell or playground output. Preserve the `reason`. For recoverable operation failures, tell users +how to address the cause, then let them explicitly rerun the operation; there is no separate +view-unlock step and failed operations are never replayed automatically. For terminal retired +views, use +`isTerminalUnavailable()` from +[connectionUnavailable.ts](../../../src/webviews/_integration/connectionUnavailable.ts) to +classify the reason and show a dismissible **Close view** notice. **Close view** closes the tab; +**X** dismisses the notice so retained content can be selected and copied, but never restores +database access. + ## Adding a provider Implement `ErrorExplanationProvider` and register it in @@ -143,6 +173,11 @@ A cluster item's first-connect catch must render through `showClusterConnectFail it **before** evicting `CredentialCache` or deleting the client: the Entra and Atlas providers read the cached credentials. +The failure-row anonymous diagnostic Shell must not ask credential-backed explainers about a +different saved authentication context. Its pre-terminal failures use one modal directly at the +command call site; later driver failures stay in the terminal. Preserve the raw safe server +rejection, never reinterpret it as rejected saved credentials or fall back to saved authentication. + ### Do not call it from background paths Background work shows nothing, so translating there costs I/O for no benefit. Leave these alone: @@ -193,5 +228,6 @@ l10n.t('The container was removed outside VS Code.') - [errorExplanationService.ts](../../../src/services/errorExplanationService.ts) - [connectionReachabilityService.ts](../../../src/services/connectionReachabilityService.ts) prepares a connection _before_ connecting; this service explains a failure _afterwards_ +- [EntraSignInRequiredErrorExplainer.ts](../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts) - [tree-cluster-architecture](../tree-cluster-architecture/SKILL.md) for `clusterId` versus `treeId` - [telemetry-instrumentation](../telemetry-instrumentation/SKILL.md) diff --git a/.github/skills/lead/SKILL.md b/.github/skills/lead/SKILL.md index 34a7516a1..71ce2bdd2 100644 --- a/.github/skills/lead/SKILL.md +++ b/.github/skills/lead/SKILL.md @@ -69,6 +69,14 @@ and in the final report. Never resolve an always-ask question yourself. A step a work item states explicitly (for example `npm run l10n`) overrides the Case 1 limits. +**Endpoint.** At intake, identify what the operator asked to receive: local work, a draft PR, or a +review handoff. Finishing the work items, passing local verification, reporting CI and marking a PR +ready are separate endpoints; none implies the others. Wording such as "defer Case 2 until all work +items are complete" sets the earliest point Case 2 may start; it does not authorize starting it. +Ask only when the endpoint is genuinely unclear and the answer would change your next action. If +the operator cannot be asked, stop at the narrowest endpoint the request supports and say so. See +Checks for what each endpoint requires. + ## Delivery continuity The approved delivery plan remains the parent task until it is complete or the operator explicitly @@ -252,18 +260,31 @@ Use one subagent per work item, except for coupled follow-ups and chains (above) ## Advisor -**Initial planning consultation.** If the operator asks the advisor to analyze or revise the plan -and prepare work items, do that before coding. Include the source plan, accepted decisions, -constraints and the Models rules in the first packet. Ask for a numbered breakdown with each -item's goal, scope, dependencies, interfaces where needed, acceptance criteria, tests, and a -**recommended coding model (full model ID) with a short reason**. The advisor must assign a model -to every item, not leave model selection as a later leader-only step. - -Keep the response concise per item; the 250-word verdict limit below applies to ordinary decision -packets, not the whole planning breakdown. Present and record the proposed items and model -assignments with the plan. Preserve accepted decisions, operator-specified models, model permission -gates and the Input approval rules; asking for plan analysis alone is not approval to implement -new or changed scope. +**Initial planning consultation.** When the operator asks for one, or the item-breakdown gate below +applies, run it before coding. Include the source document, accepted decisions, constraints and the +Models rules in the first packet. Scale its depth to how settled the plan is: + +- **Accepted plan or review:** the document is the source of truth. Ask for a compact work-item + mapping: each item's scope, dependencies and file overlap, acceptance checks and the tests that + pin them, and a **recommended coding model (full model ID) with a short reason**. Ask for exact + interfaces only where they are needed. Ask for targeted source or dependency reads only where + the evidence could change the fix: uncertain driver or library behaviour, lifecycle or + concurrency invariants, cross-module contracts, or a real conflict with an accepted decision. + Spot-check straightforward items against the code without reopening their rationale. Blockers + and material assumptions need file:line evidence. Stop once the implementation questions are + answered. +- **Unapproved plan, conflicting decisions, or unsettled design:** ask for a full numbered + breakdown: each item's goal, scope, dependencies, interfaces where needed, acceptance criteria, + tests and recommended coding model with a short reason, plus options and a recommendation where + the design is open. Conflicts with recorded decisions go to the operator (see Decisions). + +The advisor must assign a model to every item, not leave model selection as a later leader-only +step. Keep the response concise per item; the 250-word verdict limit below applies to ordinary +decision packets, not the whole planning breakdown. Present and record the proposed items and model +assignments with the plan. A lighter consultation narrows the investigation, not the review +standard: the advisor stays read-only, and the advisor gates, logic reviews, accepted decisions, +operator-specified models, model permission gates and the Input approval rules all still apply. +Asking for plan analysis alone is not approval to implement new or changed scope. **Advisor gates.** Consult the advisor, whatever your confidence, for: @@ -402,8 +423,18 @@ Use the two verification cases in `copilot-instructions.md`. You decide when to run checks after every commit.** - **Case 1** (build plus focused Vitest runs): run it after larger items or after a batch of items. -- **Case 2:** run the full list **once, at the end**, when the work is being handed over for - review, or when the PR is already out of draft. + It is the only case for local work and for draft-only delivery. +- **Local or draft-only endpoint:** once the requested work passes Case 1, push the draft head if + the operator authorized it, report the CI status for that head and stop. Do not wait for CI + unless asked. Completing every work item does not authorize Case 2 or marking the PR ready. If + pushing was not authorized, stop after the last permitted local step. +- **Case 2:** only for an explicit review handoff, or when the PR is already out of draft. Run + the full list **once**, at the point `copilot-instructions.md` and the prepare-pull-request + skill specify, even if another handoff requirement is still missing. "Run Case 2 but leave the + PR in draft" is a valid endpoint: run it, report the results, and leave the PR in draft. + Marking a PR ready needs the operator's authorization (see Decisions) and every readiness gate: + Case 2 passed and the AI pre-review file committed with the author's decisions. Report manual, + workbench or live checks as pending unless they were actually performed. - Track `vscode.l10n.t` strings added or removed; if any, remind the operator that Case 2 needs `npm run l10n`. - If a check changes files (prettier, l10n), commit those changes separately (`chore: …`). @@ -416,9 +447,11 @@ Before the report, check that the user documentation and the feature README stil changed behaviour. Search them for statements about what the items changed, not only for quoted strings, and fix them in a docs-only commit. -End with a short report: +End with a short report, then stop: - items that still need a workbench check, listed first, with the steps to try; +- the endpoint reached (local, draft pushed, Case 2 run, ready) and, for a pushed head, its SHA + and CI status at report time; - each work item, its commit SHA, and its model; - the decisions made, who made each, with confidence; - the questions you escalated and the questions you parked; diff --git a/.github/skills/tree-cluster-architecture/SKILL.md b/.github/skills/tree-cluster-architecture/SKILL.md index fa8153e17..739d5def2 100644 --- a/.github/skills/tree-cluster-architecture/SKILL.md +++ b/.github/skills/tree-cluster-architecture/SKILL.md @@ -63,6 +63,38 @@ Rules: - Never assume a stable ID is also a tree path unless the provider explicitly guarantees `clusterId === treeId`. - Never change tree construction without checking reverse lookup from `clusterId`. +## Connection Binding Contract + +A long-lived surface binds to `{ clusterId, fingerprint, generation }`, not to a `ClustersClient` +instance. Resolve the client for every operation through that shared binding with +`ClustersClient.resolveBoundClient()` or `runWithClient()`. Never retain a `ClustersClient` in view, +router, shell, playground, task, or clipboard state. + +- A normal replacement advances the physical client generation while keeping the fingerprint. + An operation bound to the old generation must not attribute its late failure to the replacement, + but a later explicit operation may use the replacement for the same identity. +- Explicit Disconnect, Remove or Disconnect-before-update retires the logical host lifetime once. + That cutoff is one-way: same-account `Reconnect` creates a new live session but does not revive + retained views or canceled handoffs from the retired lifetime. +- A different fingerprint is an identity or settings change. Never rebind an existing surface. +- Use one shared per-operation resolution path. Assert binding/latch state after client resolution, + and capture the originating lifetime or cancellation signal across async handoffs. Check it + again immediately before external side effects, replies and Playground/model sends. +- An operation may hold the resolved client only for the duration of that operation. A stale reply + must not mutate the new connection or replay a failed write. +- Shell and Playground workers may keep their own connection, but pin the originating identity and + use equivalent renewal, cancellation and lifetime checks when they respawn. +- Ordinary token, sign-in or network repair is not retirement. Keep the same tab usable and show + an actionable error for a failed operation; require no Retry-to-unlock step and no automatic + replay. A retained tab after explicit teardown is permanently read-only: dismissing its notice + exposes only copyable contents, and closing it requires the normal dirty confirmation. + +The failure-row **Open shell without authentication** entry is separate from normal authenticated +Shell startup. It binds to a sanitized endpoint and re-reads it with epoch/latch checks, without +`CredentialCache`, an authentication pin or a token relay. Only credential-rejection/sign-in/missing +credential holds may be bypassed; Disconnect, removal and updates still block it. Keep local +completion behavior, but exclude shared authenticated metadata and credential-backed explainers. + ## Design Rendering and Lookup Together When adding a cluster hierarchy or a tree/list mode, specify these four functions before coding: @@ -187,17 +219,26 @@ If a command is intentionally unavailable, gate it explicitly with context value The tree shows **actions, never error or information rows**. When expanding a cluster fails, the reason goes in a **modal** (`showErrorMessage(..., { modal: true, detail })`, translated through `ErrorExplanationService` where available). The children are only recovery actions: -"Diagnose connection…", "Open shell" (on every failure, so experts can debug +"Diagnose connection…", "Open shell without authentication" (on every failure, so experts can debug in the shell even when connecting or sign-in failed), and provider-owned actions such as "Update credentials…" via `errorRecoveryActions` (`ClusterItemBase.createErrorRecoveryChildren`). Keep a fixed relative order: configuration/targeted repairs, diagnosis/inspection, shell, destructive recovery, and **Retry always last** (including "Retry setup…"). -Providers prepend repairs; Update connection string precedes Update credentials when both exist. +Providers prepend repairs; **Update connection string** precedes **Update credentials** when both +exist. Then `ClusterItemBase` renders **Retry sign-in** when a verified Entra identity can recover, +followed by **Diagnose connection…** and **Open shell without authentication**. **Retry** is last. When **Retry sign-in** or +the stored-credential rejection action replaces Retry, do not add an ordinary Retry row too. Failure classification changes availability, never ordering. When healthy resources coexist with recovery actions, render the healthy resources first and the recovery block last. +A connected cluster's `TreeItem.contextValue` includes the `connected` tag while a client exists +and no lifecycle latch blocks it. Preserve the base context value and use this tag to gate +Disconnect. A user-disconnected cluster renders its single **Reconnect** action instead of database +children; Remove and rejected credentials use their own states and must not be exposed as +user-disconnected. + Do not add a child whose purpose is to show a message (an error label, a "sign-in required" row, a tooltip-only info node), even with an icon. Better wording belongs in the modal and in the Diagnose connection panel, not in the tree. @@ -210,6 +251,10 @@ Before approving a cluster tree change, answer yes to all: - [ ] Base cluster context tag is preserved. - [ ] `clusterId`, `treeId`, and `viewId` have documented owners. - [ ] Credentials and clients use `clusterId` only. +- [ ] Long-lived surfaces retain bindings, not `ClustersClient` instances. +- [ ] Normal same-fingerprint generation replacement remains separate from one-way lifetime retirement. +- [ ] Per-operation resolution uses the shared path and checks the binding after resolution. +- [ ] Async handoffs fence external side effects with the captured lifetime or cancellation. - [ ] Every rendered layout has a reverse lookup strategy. - [ ] Cluster and collection lookup share one resolver. - [ ] Synthetic ownership is exact and isolated from stored lookup. @@ -217,3 +262,5 @@ Before approving a cluster tree change, answer yes to all: - [ ] A real render-to-lookup round-trip test covers every layout. - [ ] Standard cluster commands work or are explicitly gated off. - [ ] Failures show a modal; tree children are recovery actions only, never error or info rows. +- [ ] Recovery actions keep provider repairs first, diagnosis and shell next, and Retry last. +- [ ] The `connected` context tag gates Disconnect and disappears while a lifecycle latch applies. diff --git a/CHANGELOG.md b/CHANGELOG.md index 699a9e3e8..b6d3a3ddf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 1.2.0 (Unreleased) + +> Draft entries for an unpublished release. They may change before the release is finalized. + +### New Features & Improvements + +- **Resilient Connections**: Renews Microsoft Entra ID tokens silently, refreshes Azure discovery credentials, and replaces closed or transient failed clients with the same binding on a later foreground operation. [#990](https://github.com/microsoft/vscode-documentdb/issues/990), [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) +- **Explicit Connection Teardown**: Adds Disconnect and Reconnect, a shared disconnect and deletion flow, a Close all or Keep open choice, and protection for active copy, export, or import work. [#566](https://github.com/microsoft/vscode-documentdb/issues/566), [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) +- **Identity-Bound Open Views**: Keeps open views and editor state tied to the connection that created them. Expired sign-in or unavailable connections receive bounded recovery, while changed saved settings require a new view instead of changing identity behind it. [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) + ## 1.1.0 ### New Features diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 73a5c878c..a299a3f92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -551,6 +551,14 @@ Case 2 is also where the AI pre-review in [§6](#6-ai-assisted-review-workflow) - **`npm run typecheck:tests`** checks every participating workspace's tests with its own TypeScript configuration, including strict checks that the root build and Vitest runtime do not cover. - **`npm run package`** catches Vite host and webview bundling issues and missing assets that unit tests alone will not surface. +### 4.4. CodeQL alert dismissals + +Fix valid findings. With maintainer approval, dismiss a false positive individually in GitHub +and explain why it does not apply. Record the alert link, rule ID, affected code, rationale, and +conditions for revisiting it in [`.github/codeql-exceptions.md`](.github/codeql-exceptions.md). +The file is an audit record, not a CodeQL configuration file. Do not disable a rule or exclude a +source file to handle a single false positive. + ## 5. Documenting Work with AI This section is for new contributors, code maintainers, and AI agents. It describes where documentation about work done with AI lives so that decisions and reasoning stay discoverable long after a PR merges. diff --git a/build/verification/README.md b/build/verification/README.md index 8c8a090c3..7af0198d9 100644 --- a/build/verification/README.md +++ b/build/verification/README.md @@ -175,13 +175,13 @@ node build/verification/bson-identity/check.cjs # identity node build/verification/bson-identity/check.cjs --prove # identity, then the alias-removed control ``` -[`lowered-import/check.cjs`](./lowered-import/check.cjs) builds the same way (shared -[`vite-host-probe.cjs`](./vite-host-probe.cjs)) a CommonJS module containing azureauth's lowered -`Promise.resolve().then(() => require('@azure/arm-resources-subscriptions'))` and requires the -result to expose `SubscriptionClient` (G5-I01, [Vite rationale](../vite/README.md)). Its negative -control removes the package's CommonJS alias; Rolldown 1.0.3 then emits a call to the ESM -initializer, and the result must be `undefined`. Both run in `npm run test:verification`; add -`--prove` to the standalone command for the control. +### Azure ARM ESM (runtime) + +[`lowered-import/check.cjs`](./lowered-import/check.cjs) uses the same production host probe to +bundle the three ARM subscription subpaths azureauth v6 imports. It checks that the bundle +exports `createSubscription` and both list functions, and that the ARM modules in its graph +come from `dist/esm`. This runs in `npm run test:verification` and replaces the historical +G5-I01 alias-removal control, which no longer reproduced after the SDK upgrade. These probes build and run bundles instead of inspecting the packaged artifact, so they are not part of L1, which stays offline and build-free for the ADO release build. @@ -458,10 +458,11 @@ npm run test:vsix -- npm run prove:activation -- ``` -After activation, the probe requires the three registrations at the end of activation +After activation, the probe requires the two registrations at the end of activation (`LATE_COMMANDS` in [`activation/checks.cjs`](./activation/checks.cjs)) and every -`contributes.commands` entry of the installed extension. A command registered later belongs in -`LAZY_COMMANDS` with the reason; the list is empty, and an entry for an undeclared command fails. +`contributes.commands` entry of the installed extension unless it is listed in `LAZY_COMMANDS` +with a reason (for example, development-only survey and schema commands). An entry for an +undeclared command fails. GitHub Actions runs these under Xvfb and caches `.vscode-test/`. The isolated ADO build runs only L1 before signing; it must not download VS Code. Local L3 requires a display or operator-provided Xvfb, diff --git a/build/verification/activation/checks.cjs b/build/verification/activation/checks.cjs index 6e644ed97..60442f386 100644 --- a/build/verification/activation/checks.cjs +++ b/build/verification/activation/checks.cjs @@ -13,10 +13,9 @@ const TARGET_ID = 'ms-azuretools.vscode-documentdb'; const LATE_COMMANDS = [ 'vscode-documentdb.command.internal.exportDocuments', 'vscode-documentdb.command.exportDocuments', - 'vscode-documentdb.command.testing.startDemoTask', ]; const INJECTION_MARKER = 'L3_INJECTED_SWALLOWED_ACTIVATION_ERROR'; -const SURVEY_DEBUG_REASON = +const DEVELOPMENT_ONLY_REASON = 'By design registered only in ExtensionMode.Development (src/debug/registerDebugCommands.ts); hidden from the palette otherwise.'; /** * Contributed commands that an installed (production) activation does not register, by command id, @@ -24,9 +23,11 @@ const SURVEY_DEBUG_REASON = * @type {Readonly>} */ const LAZY_COMMANDS = Object.freeze({ - 'vscode-documentdb.debug.survey.showInvitation': SURVEY_DEBUG_REASON, - 'vscode-documentdb.debug.survey.simulateMilestone': SURVEY_DEBUG_REASON, - 'vscode-documentdb.debug.survey.resetState': SURVEY_DEBUG_REASON, + 'vscode-documentdb.debug.survey.showInvitation': DEVELOPMENT_ONLY_REASON, + 'vscode-documentdb.debug.survey.simulateMilestone': DEVELOPMENT_ONLY_REASON, + 'vscode-documentdb.debug.survey.resetState': DEVELOPMENT_ONLY_REASON, + 'vscode-documentdb.command.clearSchemaCache': DEVELOPMENT_ONLY_REASON, + 'vscode-documentdb.command.showSchemaStoreStats': DEVELOPMENT_ONLY_REASON, }); /** @param {string} engine @returns {string} */ diff --git a/build/verification/browser/collectionViewFixtures.ts b/build/verification/browser/collectionViewFixtures.ts index 926f2abf0..795574bdc 100644 --- a/build/verification/browser/collectionViewFixtures.ts +++ b/build/verification/browser/collectionViewFixtures.ts @@ -11,11 +11,13 @@ import { type TableRow, type TreeNode, } from '../../../src/utils/documentGrid/types'; +import { type ConnectionUnavailableResponse } from '../../../src/webviews/_integration/connectionUnavailable'; import { type CollectionViewWebviewConfigurationType } from '../../../src/webviews/documentdb/collectionView/collectionViewController'; import { type FixtureOutputs, type TypedRpcFixtures } from './core/fixtures'; type CollectionOutputs = FixtureOutputs['mongoClusters']['collectionView']; -type TablePageOutput = CollectionOutputs['getCurrentPageAsTable']; +type TablePageOutput = Exclude; +type TreeNodesOutput = Exclude; type CollectionViewFixture = { readonly config?: Partial; readonly rpc: TypedRpcFixtures; @@ -181,7 +183,7 @@ const deepRootKey = JSON.stringify([0]); const deepProfileKey = JSON.stringify([0, 'profile']); const deepAddressKey = JSON.stringify([0, 'profile', 'address']); const deepLocationKey = JSON.stringify([0, 'profile', 'address', 'location']); -const deepNestingNodes: CollectionOutputs['getCurrentPageAsTree'] = [ +const deepNestingNodes: TreeNodesOutput = [ { key: deepRootKey, parentKey: null, @@ -269,7 +271,7 @@ const arraysRootKey = JSON.stringify([0]); const emptyArrayKey = JSON.stringify([0, 'empty']); const tenArrayKey = JSON.stringify([0, 'ten']); const elevenArrayKey = JSON.stringify([0, 'eleven']); -const arrayNodes: CollectionOutputs['getCurrentPageAsTree'] = [ +const arrayNodes: TreeNodesOutput = [ { key: arraysRootKey, parentKey: null, @@ -527,8 +529,8 @@ const arrayJsonDocuments: CollectionOutputs['getCurrentPageAsJson'] = [ eleven: Array.from({ length: 11 }, (_, index): number => index), }), ]; -const heterogeneousTreeNodes: CollectionOutputs['getCurrentPageAsTree'] = heterogeneousPage.rows.flatMap( - (row): CollectionOutputs['getCurrentPageAsTree'] => [ +const heterogeneousTreeNodes: TreeNodesOutput = heterogeneousPage.rows.flatMap( + (row): TreeNodesOutput => [ { key: JSON.stringify([row.rowKey]), parentKey: null, diff --git a/build/verification/browser/core.test.ts b/build/verification/browser/core.test.ts index b8c47d39a..2424c19a2 100644 --- a/build/verification/browser/core.test.ts +++ b/build/verification/browser/core.test.ts @@ -66,6 +66,39 @@ describe('Shared browser fixture core', (): void => { ]); }); + it('answers later calls from afterFirst, holds them by tag and lets input cases take precedence', async (): Promise => { + const errors: string[] = []; + const messages = vi.spyOn(window, 'postMessage').mockImplementation((): void => {}); + const path = 'localQuickStart.checkPort'; + const api = fakeVsCodeApi( + { + [path]: { + ...rpc[path], + cases: [{ input: 'case', results: ['from case'] }], + afterFirst: { results: ['later'], hold: 'later' }, + }, + }, + errors, + )(); + api.postMessage({ id: 'first', op: { type: 'query', path } }); + api.postMessage({ id: 'second', op: { type: 'query', path } }); + api.postMessage({ id: 'case', op: { type: 'query', path, input: 'case' } }); + await Promise.resolve(); + + expect(window.__releaseScenarioReply?.isHeld?.('later')).toBe(true); + expect(window.__releaseScenarioReply?.('later')).toBe(true); + expect(window.__releaseScenarioReply?.isHeld?.('later')).toBe(false); + expect(errors).toEqual([]); + expect(messages.mock.calls.map((call): unknown => call[0])).toEqual([ + { id: 'first', result: port }, + { id: 'first', complete: true }, + { id: 'case', result: 'from case' }, + { id: 'case', complete: true }, + { id: 'second', result: 'later' }, + { 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 72a0f883f..1d4beb348 100644 --- a/build/verification/browser/core/fakeVsCodeApi.ts +++ b/build/verification/browser/core/fakeVsCodeApi.ts @@ -19,7 +19,10 @@ export interface HarnessCall { declare global { interface Window { __harnessCalls: HarnessCall[]; - __releaseScenarioReply?: (tag: string) => boolean; + __releaseScenarioReply?: ((tag: string) => boolean) & { + /** Reports whether a reply is held under `tag`, without recording an error. */ + readonly isHeld?: (tag: string) => boolean; + }; } } @@ -40,9 +43,10 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window window.__harnessCalls = calls; const subscriptions = new Set(); const held = new Map void }[]>(); + const seenPaths = new Set(); let acquired = false; - window.__releaseScenarioReply = (tag: string): boolean => { + const releaseScenarioReply = (tag: string): boolean => { const replies = held.get(tag); if (!replies?.length) { errors.push(`No held scenario reply: ${tag}`); @@ -52,6 +56,10 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window for (const { reply } of replies) reply(); return true; }; + // The probe belongs to this installation's release, so replacing the release replaces it too. + window.__releaseScenarioReply = Object.assign(releaseScenarioReply, { + isHeld: (tag: string): boolean => (held.get(tag)?.length ?? 0) > 0, + }); function send(message: VsCodeLinkResponseMessage): void { window.postMessage(message, window.location.origin); @@ -83,9 +91,10 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window if (response.keepOpen) { subscriptions.add(id); } - const selected = response.cases?.find( - (item): boolean => JSON.stringify(item.input) === JSON.stringify(op.input), - ); + const selected = + response.cases?.find((item): boolean => JSON.stringify(item.input) === JSON.stringify(op.input)) ?? + (seenPaths.has(op.path) ? response.afterFirst : undefined); + seenPaths.add(op.path); const reply = (): void => { if (response.keepOpen && !subscriptions.has(id)) { return; diff --git a/build/verification/browser/core/fixtures.ts b/build/verification/browser/core/fixtures.ts index 141b0db3e..68c42da52 100644 --- a/build/verification/browser/core/fixtures.ts +++ b/build/verification/browser/core/fixtures.ts @@ -3,7 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AnyProcedure, type AnyRouter, type inferRouterInputs, type inferRouterOutputs } from '@trpc/server'; +import { + type AnyProcedure, + type AnyRouter, + type inferProcedureOutput, + type inferRouterInputs, + type inferRouterOutputs, +} from '@trpc/server'; import { type AppRouter } from '../../../../src/webviews/_integration/appRouter'; export type FixtureInputs = inferRouterInputs; @@ -18,6 +24,16 @@ type ProcedurePaths = { : never; }[keyof T & string]; export type FixturePaths = ProcedurePaths; +type RawOutputs = { + [K in keyof T & string]: T[K] extends AnyProcedure + ? inferProcedureOutput + : T[K] extends AnyRouter + ? RawOutputs + : T[K] extends Record + ? RawOutputs + : never; +}; +type FixtureRawOutputs = RawOutputs; export interface RpcFixture { readonly type: 'query' | 'mutation' | 'subscription'; @@ -30,6 +46,8 @@ export interface RpcFixture { readonly hold?: string; }[]; readonly hold?: string; + /** Used for every call after the first to this path, unless an input case matches. */ + readonly afterFirst?: { readonly results: readonly unknown[]; readonly hold?: string }; } export type RpcFixtures = Readonly>>; @@ -45,15 +63,30 @@ export type FixtureAtPath = P extends `${infer Head}.${infe type StreamItem = T extends AsyncIterable ? Item : T; // tRPC's JSON-serialized output inference represents void procedures as never. The wire protocol // supports explicit undefined results and the host's null void replies. -type FixtureResult = [T] extends [void] ? void | null : StreamItem; +// Serialized inference also drops void from a union such as `void | ConnectionUnavailableResponse`, +// so the procedure's raw output decides whether its void reply (null) is allowed. +type FixtureResult = ([T] extends [void] ? void | null : StreamItem) | (void extends Raw ? null : never); export type TypedRpcFixtures = { - readonly [P in FixturePaths]?: Omit & { - readonly results: readonly FixtureResult>[]; + readonly [P in FixturePaths]?: Omit & { + readonly results: readonly FixtureResult< + FixtureAtPath, + FixtureAtPath + >[]; readonly cases?: readonly { readonly input: FixtureAtPath; - readonly results: readonly FixtureResult>[]; + readonly results: readonly FixtureResult< + FixtureAtPath, + FixtureAtPath + >[]; readonly hold?: string; }[]; + readonly afterFirst?: { + readonly results: readonly FixtureResult< + FixtureAtPath, + FixtureAtPath + >[]; + readonly hold?: string; + }; }; }; @@ -70,6 +103,15 @@ export function isRpcFixture(value: unknown): value is RpcFixture { value.undefinedResult === undefined || typeof value.undefinedResult === 'boolean') && (!('hold' in value) || value.hold === undefined || typeof value.hold === 'string') && + (!('afterFirst' in value) || + value.afterFirst === undefined || + (typeof value.afterFirst === 'object' && + value.afterFirst !== null && + 'results' in value.afterFirst && + Array.isArray(value.afterFirst.results) && + (!('hold' in value.afterFirst) || + value.afterFirst.hold === undefined || + typeof value.afterFirst.hold === 'string'))) && (!('cases' in value) || value.cases === undefined || (Array.isArray(value.cases) && diff --git a/build/verification/browser/fixtures.ts b/build/verification/browser/fixtures.ts index 463e45367..93e79c8a4 100644 --- a/build/verification/browser/fixtures.ts +++ b/build/verification/browser/fixtures.ts @@ -52,7 +52,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 }; } @@ -541,6 +541,7 @@ export const fixtures = { ], rpc: { ...common, + 'mongoClusters.documentView.reportDirty': reply('mutation', null), 'mongoClusters.documentView.getDocumentById': reply< Outputs['mongoClusters']['documentView']['getDocumentById'] >('query', JSON.stringify({ _id: 'stage0-1', name: 'Stage 0 document payload', quantity: 7 }, null, 2)), diff --git a/build/verification/browser/scenario-playwright.ts b/build/verification/browser/scenario-playwright.ts index 2cf53a6d9..452e7e929 100644 --- a/build/verification/browser/scenario-playwright.ts +++ b/build/verification/browser/scenario-playwright.ts @@ -66,16 +66,66 @@ export async function runScenario(page: IntegratedPage, origin: string, route: S } switch (step.action) { case 'releaseReply': { + // The held request can be sent asynchronously after the preceding step. + await wait( + (tag: string): boolean => window.__releaseScenarioReply?.isHeld?.(tag) ?? true, + step.tag, + `held scenario reply ${step.tag}`, + ); const released = await page.evaluate( (tag: string): boolean => window.__releaseScenarioReply?.(tag) ?? false, step.tag, ); if (!released) throw new Error(`No held scenario reply: ${step.tag}`); + if (step.waitForRender === true) { + // The reply is an asynchronous message. Give the app a render before reading the result. + await page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => resolve())), + ); + } break; } + case 'post': + await page.evaluate( + (message): void => window.postMessage(message, window.location.origin), + step.message, + ); + break; + case 'waitFor': + await wait((selector) => document.querySelector(selector) !== null, step.selector, step.name); + break; case 'press': - await page.keyboard.press(step.key); + if ('role' in step) { + await page.getByRole(step.role, { name: step.name, exact }).press(step.key, { timeout: 60000 }); + } else { + await page.keyboard.press(step.key); + } + break; + case 'replaceText': { + const locator = page.getByRole(step.role, { name: step.name, exact }); + 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', + ); break; + } case 'click': await page.getByRole(step.role, { name: step.name, exact }).click({ timeout: 60000 }); break; @@ -172,6 +222,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, }; @@ -182,7 +233,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 7678390e2..87b4810a2 100644 --- a/build/verification/browser/scenarios.test.ts +++ b/build/verification/browser/scenarios.test.ts @@ -196,6 +196,7 @@ describe('TDD: Collection View grid contracts', (): void => { const identity: readonly ScenarioAssertion[] = collectionViewContracts.identity; const targets = identity.flatMap((assertion): string[] => { if (assertion.kind !== 'calls') return []; + if (!('input' in assertion)) throw new Error('Identity fixture calls must check their input'); if (assertion.path === 'mongoClusters.collectionView.deleteDocumentsById') return assertion.input; if ( assertion.path === 'mongoClusters.collectionView.viewDocumentById' || @@ -578,8 +579,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(228); - expect(new Set(routes.map((route): string => route.path)).size).toBe(228); + expect(routes).toHaveLength(246); + expect(new Set(routes.map((route): string => route.path)).size).toBe(246); for (const route of routes) expect(parseScenarioRoute(route.path)).toEqual(route); }); @@ -699,7 +700,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(228); + expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(246); 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 c7709aa92..f7ed88f87 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -52,6 +52,7 @@ export type ScenarioTargetRole = | 'menuitem' | 'radio' | 'textbox' + | 'searchbox' | 'row' | 'gridcell' | 'columnheader' @@ -61,25 +62,36 @@ export type ScenarioTargetRole = | 'option'; export type ScenarioStep = - | { readonly action: 'releaseReply'; readonly tag: string } + | { + readonly action: 'releaseReply'; + readonly tag: string; + /** Wait one animation frame after releasing, so a following assertion sees the reply's render. */ + readonly waitForRender?: true; + } | { readonly action: 'click'; readonly role: ScenarioTargetRole; 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: 'press'; readonly key: string } | { readonly action: 'dblclick' | 'focus'; readonly role: ScenarioTargetRole; readonly name: string; - }; + } + | { readonly action: 'replaceText'; readonly role: 'textbox'; readonly name: string; readonly value: string } + | { readonly action: 'press'; readonly role: ScenarioTargetRole; readonly name: string; readonly key: string } + | { readonly action: 'waitFor'; readonly name: string; readonly selector: string } + | { readonly action: 'post'; readonly name: string; readonly message: unknown }; 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. */ @@ -3983,6 +3995,448 @@ const diagnosticsScenarios = { ), } as const satisfies Readonly>>; +const documentViewBase = defaultScenario('documentView'); +const documentEditReadiness = { ...documentViewBase.readiness, content: ['Save'] }; +const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; +const disconnectedDocument = { + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', +} 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, + add: { + ...documentViewBase, + config: { ...fixtures.documentView.config, mode: 'add' }, + readiness: { ...documentViewBase.readiness, content: ['Save', 'Reload'] }, + assertions: [ + { + kind: 'attribute', + name: 'Initial focus is Save with a visible Fluent indicator', + selector: 'button[aria-label="Save to the database"]:focus[data-fui-focus-visible]', + attribute: 'data-fui-focus-visible', + expected: '', + }, + ], + }, + view: { + ...documentViewBase, + config: { ...fixtures.documentView.config, mode: 'view' }, + assertions: [ + { + kind: 'attribute', + name: 'Initial focus is Reload with a visible Fluent indicator', + selector: 'button[aria-label="Reload document from the database"]:focus[data-fui-focus-visible]', + attribute: 'data-fui-focus-visible', + expected: '', + }, + ], + }, + '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', + hold: 'old-save', + results: [{ documentId: '"stage0-1"', documentStringified: '{"name":"Old save reply"}' }], + }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + 'mongoClusters.documentView.closeView': { + type: 'mutation', + results: [], + undefinedResult: true, + }, + }, + assertions: [ + { + kind: 'attribute', + name: 'a terminal notice preserves the editor and its draft', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [ + firstDocumentEdit, + saveDocumentStep, + { + ...firstDocumentEdit, + value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', + }, + { + action: 'post', + name: 'disable Document View', + message: { type: 'documentView.connectionUnavailable', unavailable: disconnectedDocument }, + }, + { action: 'click', role: 'button', name: 'Dismiss notice' }, + ], + }, + { + kind: 'stableText', + name: 'the old save reply cannot overwrite the newer edit', + selector: '.monaco-editor .view-lines', + steps: [{ action: 'releaseReply', tag: 'old-save', waitForRender: true }], + }, + { + kind: 'attribute', + name: 'the newer edit stays dirty and terminal Save stays disabled', + selector: 'button[aria-label="Save to the database"]', + attribute: 'disabled', + expected: '', + }, + { + kind: 'calls', + name: 'the terminal tab never calls recovery or submits the newer draft', + path: saveDocumentPath, + count: 1, + checkInput: false, + steps: [], + }, + { + kind: 'calls', + name: 'the terminal tab never calls the close RPC without confirmation', + path: 'mongoClusters.documentView.closeView', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, +} as const satisfies Readonly>>; + +const clusterDashboardBase = defaultScenario('clusterDashboard'); +const clusterDashboardScenarios = { + default: { + ...clusterDashboardBase, + assertions: [ + ...(clusterDashboardBase.assertions ?? []), + { + kind: 'text', + name: 'a healthy poll keeps the Dashboard connected', + selector: '.dashboardConnectionStatus', + includes: ['Connected'], + excludes: ['Disconnected'], + }, + ], + }, + 'recoverable-health-polls': { + ...clusterDashboardBase, + config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 25 }, + readiness: { ...clusterDashboardBase.readiness, content: ['Disconnected'] }, + rpc: { + ...clusterDashboardBase.rpc, + 'clusterDashboard.measureRtt': { + ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], + afterFirst: { + results: [ + { + unavailable: { + reason: 'unreachable', + title: 'Connection lost', + detail: 'Check the network or server.', + }, + }, + ], + }, + }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'text', + name: 'repeated failures are recorded in the connection status', + selector: '.dashboardConnectionStatus', + includes: ['Disconnected'], + excludes: [], + }, + { + kind: 'attribute', + name: 'recoverable poll failures do not show the terminal notice', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + }, + { + kind: 'calls', + name: 'background recoverable poll failures do not toast', + path: 'common.displayErrorMessage', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, + disconnected: { + ...clusterDashboardBase, + config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 2000 }, + readiness: { ...clusterDashboardBase.readiness, content: ['stage0_inventory'] }, + rpc: { + ...clusterDashboardBase.rpc, + 'clusterDashboard.measureRtt': { + ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], + hold: 'old-health-poll', + }, + 'clusterDashboard.closeView': { type: 'mutation', results: [], undefinedResult: true }, + }, + 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' }, + { action: 'releaseReply', tag: 'old-health-poll', waitForRender: true }, + ], + }, + { + 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', + }, + { + kind: 'attribute', + name: 'dismissing the notice exposes the retained inventory for copying only', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [{ action: 'click', role: 'button', name: 'Dismiss notice' }], + }, + { + kind: 'calls', + name: 'the retained Dashboard never calls close after reconnect', + path: 'clusterDashboard.closeView', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, +} as const satisfies Readonly>>; + +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.', +} as const; +const collectionViewLifecycleScenarios = { + 'disconnected-signInRequired': { + ...collectionViewBase, + rpc: { + ...collectionViewBase.rpc, + [collectionQueryPath]: { + ...fixtures.collectionView.rpc[collectionQueryPath], + afterFirst: { results: [{ unavailable: collectionSignInRequired }] }, + }, + 'mongoClusters.collectionView.closeView': { + type: 'mutation', + results: [], + undefinedResult: true, + }, + 'mongoClusters.collectionView.copyQueryToClipboard': { + type: 'mutation', + results: [null], + }, + 'common.confirm': { type: 'mutation', results: [{ confirmed: false }] }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'attribute', + name: 'a recoverable failure keeps the same query and controls live', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [ + collectionFilter, + runCollectionQuery, + { + action: 'waitFor', + name: 'actionable sign-in error reaches the host', + selector: '.collectionView', + }, + ], + }, + { + kind: 'text', + name: 'retains the filter text', + selector: collectionFilterSelector, + includes: ['"name":"Alpha"'], + excludes: [], + }, + { + kind: 'calls', + name: 'the failed query surfaces one actionable repair error', + path: 'common.displayErrorMessage', + count: 1, + checkInput: true, + input: { + message: 'Sign-in required', + modal: false, + cause: 'Sign in from the connection tree.', + }, + steps: [], + }, + { + 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: 'the next explicit query runs once in the same tab after repair', + path: collectionQueryPath, + count: 3, + checkInput: false, + steps: [runCollectionQuery], + }, + { + kind: 'calls', + name: 'recoverable failures never call the close RPC', + path: 'mongoClusters.collectionView.closeView', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, + 'stale-page-after-disconnect': { + ...collectionViewBase, + rpc: { + ...collectionViewBase.rpc, + [collectionTablePath]: { + ...fixtures.collectionView.rpc[collectionTablePath], + afterFirst: { + results: [{ ...fixtures.collectionView.rpc[collectionTablePath].results[0], rows: [] }], + hold: 'late-page', + }, + }, + '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', + requiresGrid: 'grid', + selector: '[role="grid"]', + steps: [ + { + action: 'post', + name: 'disable Collection View', + message: { type: 'collectionView.connectionUnavailable', unavailable: disconnectedDocument }, + }, + { action: 'waitFor', name: 'the disconnect overlay', selector: '.disconnectedOverlay' }, + { action: 'releaseReply', tag: 'late-page', waitForRender: true }, + ], + }, + { + kind: 'text', + name: 'the late reply does not change the displayed disconnect reason', + selector: '.disconnectedOverlay', + includes: ['Session ended', 'Copy what you need and open a new tab.'], + excludes: ['Retry sign-in'], + }, + ], + }, +} as const satisfies Readonly>>; + export const scenarios = { collectionView: { default: collectionViewBase, @@ -4006,41 +4460,10 @@ export const scenarios = { 'late-query': collectionViewScenario('late-query'), 'loading-to-results': collectionViewScenario('loading-to-results'), paging: collectionViewScenario('paging'), + ...collectionViewLifecycleScenarios, }, - documentView: { - default: defaultScenario('documentView'), - add: { - ...defaultScenario('documentView'), - config: { ...fixtures.documentView.config, mode: 'add' }, - readiness: { - ...defaultScenario('documentView').readiness, - content: ['Save', 'Reload'], - }, - assertions: [ - { - kind: 'attribute', - name: 'Initial focus is Save with a visible Fluent indicator', - selector: 'button[aria-label="Save to the database"]:focus[data-fui-focus-visible]', - attribute: 'data-fui-focus-visible', - expected: '', - }, - ], - }, - view: { - ...defaultScenario('documentView'), - config: { ...fixtures.documentView.config, mode: 'view' }, - assertions: [ - { - kind: 'attribute', - name: 'Initial focus is Reload with a visible Fluent indicator', - selector: 'button[aria-label="Reload document from the database"]:focus[data-fui-focus-visible]', - attribute: 'data-fui-focus-visible', - expected: '', - }, - ], - }, - }, - clusterDashboard: { default: defaultScenario('clusterDashboard') }, + documentView: documentViewScenarios, + clusterDashboard: clusterDashboardScenarios, atlasCredentials: { default: defaultScenario('atlasCredentials', atlasSteps) }, connectionDiagnostics: diagnosticsScenarios, localQuickStart: { diff --git a/build/verification/lowered-import/azureauthLowering.cjs b/build/verification/lowered-import/azureauthLowering.cjs deleted file mode 100644 index 2c0cdb0e1..000000000 --- a/build/verification/lowered-import/azureauthLowering.cjs +++ /dev/null @@ -1,14 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.loadArmSubscriptions = loadArmSubscriptions; - -// TypeScript's CommonJS lowering of `await import(...)`, character for character as in -// @microsoft/vscode-azext-azureauth's VSCodeAzureSubscriptionProvider.getSubscriptionClient. -function loadArmSubscriptions() { - return Promise.resolve().then(() => require('@azure/arm-resources-subscriptions')); -} diff --git a/build/verification/lowered-import/check.cjs b/build/verification/lowered-import/check.cjs index f846b8bf9..0fe760391 100644 --- a/build/verification/lowered-import/check.cjs +++ b/build/verification/lowered-import/check.cjs @@ -3,8 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// G5-I01: a lowered `import()` of @azure/arm-resources-subscriptions must yield its namespace -// when built with the shipped host config (production), which pins the package to CommonJS. +// Check azureauth's ARM subscription import routes with the shipped production host config. const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); @@ -14,42 +13,48 @@ const { buildHostProbes } = require('../vite-host-probe.cjs'); const specifier = '@azure/arm-resources-subscriptions'; -async function checkLoweredImport({ withoutAlias = false } = {}) { +async function checkAzureArmEsm() { const outputPath = fs.mkdtempSync(path.join(os.tmpdir(), 'documentdb-lowered-import-')); try { - await buildHostProbes({ + const chunks = await buildHostProbes({ input: { loweredImport: path.join(__dirname, 'probe.mjs') }, outputPath, - pinned: specifier, - withoutAlias, }); - const { loadArmSubscriptions } = await import(pathToFileURL(path.join(outputPath, 'loweredImport.mjs'))); - const namespace = await loadArmSubscriptions(); - assert.equal( - typeof namespace?.SubscriptionClient, - 'function', - `Lowered import() of ${specifier} returned ${namespace === undefined ? 'undefined' : 'an object without SubscriptionClient'}, not its namespace`, + const armModules = chunks + .flatMap((chunk) => chunk.moduleIds) + .flatMap((id) => { + const match = /\/node_modules\/@azure\/arm-resources-subscriptions\/(.+)$/.exec( + id.replaceAll('\\', '/'), + ); + return match ? [match[1]] : []; + }); + assert.ok(armModules.length > 0, `Host probe did not bundle any ${specifier} modules`); + assert.deepEqual( + armModules.filter((id) => !id.startsWith('dist/esm/')), + [], + `Host probe bundled ${specifier} modules outside dist/esm`, ); - return { exports: Object.keys(namespace).length }; + + const runtime = await import(pathToFileURL(path.join(outputPath, 'loweredImport.mjs'))); + for (const name of ['createSubscription', 'listSubscriptions', 'listTenants']) { + assert.equal(typeof runtime[name], 'function', `Bundled ${specifier} export ${name} is not a function`); + } + return armModules; } finally { fs.rmSync(outputPath, { recursive: true, force: true }); } } -async function main(args) { - const result = await checkLoweredImport({ withoutAlias: args.includes('--without-alias') }); - console.log(`PASS: lowered import() of ${specifier} returned its namespace (${result.exports} exports)`); - if (args.includes('--prove')) { - await assert.rejects(checkLoweredImport({ withoutAlias: true }), /returned undefined, not its namespace/); - console.log(`PASS: ${specifier}-alias-removed rejected for the expected reason`); - } +async function main() { + const armModules = await checkAzureArmEsm(); + console.log(`PASS: ${specifier} runtime exports are functions (${armModules.length} dist/esm modules)`); } if (require.main === module) { - main(process.argv.slice(2)).catch((error) => { + main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); } -module.exports = { checkLoweredImport }; +module.exports = { checkAzureArmEsm }; diff --git a/build/verification/lowered-import/lowered-import.test.cjs b/build/verification/lowered-import/lowered-import.test.cjs index 372f655d9..f61f8461b 100644 --- a/build/verification/lowered-import/lowered-import.test.cjs +++ b/build/verification/lowered-import/lowered-import.test.cjs @@ -3,17 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -const assert = require('node:assert/strict'); const test = require('node:test'); -const { checkLoweredImport } = require('./check.cjs'); +const { checkAzureArmEsm } = require('./check.cjs'); -test('azureauth-style lowered import() of @azure/arm-resources-subscriptions yields its namespace', async () => { - await checkLoweredImport(); -}); - -test('negative control: without the CommonJS alias, the lowered import() yields undefined (G5-I01)', async () => { - await assert.rejects( - checkLoweredImport({ withoutAlias: true }), - /Lowered import\(\) of @azure\/arm-resources-subscriptions returned undefined, not its namespace/, - ); +test('azureauth ARM subscription subpaths expose runtime functions and bundle only ESM modules', async () => { + await checkAzureArmEsm(); }); diff --git a/build/verification/lowered-import/probe.mjs b/build/verification/lowered-import/probe.mjs index 321b80039..2992a4c14 100644 --- a/build/verification/lowered-import/probe.mjs +++ b/build/verification/lowered-import/probe.mjs @@ -3,7 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// Built with `vite.config.ext.mjs` as a host entry, as the extension bundles azureauth's CommonJS. -import { loadArmSubscriptions } from './azureauthLowering.cjs'; +// Match the static imports in azureauth's ESM AzureSubscriptionProviderBase. +import { createSubscription } from '@azure/arm-resources-subscriptions/api'; +import { list as listSubscriptions } from '@azure/arm-resources-subscriptions/api/subscriptions'; +import { list as listTenants } from '@azure/arm-resources-subscriptions/api/tenants'; -export { loadArmSubscriptions }; +export { createSubscription, listSubscriptions, listTenants }; diff --git a/build/verification/vite-host-probe.cjs b/build/verification/vite-host-probe.cjs index 925993f9d..f5efb6565 100644 --- a/build/verification/vite-host-probe.cjs +++ b/build/verification/vite-host-probe.cjs @@ -11,15 +11,19 @@ const { pathToFileURL } = require('node:url'); const repository = path.resolve(__dirname, '../..'); /** - * @param {{ input: Record, outputPath: string, pinned: string, withoutAlias: boolean }} options - * `pinned` is a bare specifier that `vite.config.ext.mjs` must alias; `withoutAlias` drops that alias. + * @param {{ input: Record, outputPath: string, pinned?: string, withoutAlias?: boolean }} options + * When supplied, `pinned` must be aliased by `vite.config.ext.mjs`; `withoutAlias` drops that alias. */ async function buildHostProbes({ input, outputPath, pinned, withoutAlias }) { const { createBuilder } = await import('vite'); const { default: createConfig } = await import(pathToFileURL(path.join(repository, 'vite.config.ext.mjs'))); const config = await createConfig({ mode: 'production', command: 'build' }); - const pin = config.resolve.alias.find((alias) => alias.find instanceof RegExp && alias.find.test(pinned)); - assert.ok(pin, `vite.config.ext.mjs no longer pins ${pinned} (resolve.alias)`); + let aliases = config.resolve.alias; + if (pinned !== undefined) { + const pin = aliases.find((alias) => alias.find instanceof RegExp && alias.find.test(pinned)); + assert.ok(pin, `vite.config.ext.mjs no longer pins ${pinned} (resolve.alias)`); + if (withoutAlias) aliases = aliases.filter((alias) => alias !== pin); + } const host = config.environments.host; let chunks; const builder = await createBuilder({ @@ -29,7 +33,7 @@ async function buildHostProbes({ input, outputPath, pinned, withoutAlias }) { logLevel: 'silent', resolve: { ...config.resolve, - alias: config.resolve.alias.filter((alias) => !(withoutAlias && alias === pin)), + alias: aliases, }, environments: { host: { diff --git a/build/vite/README.md b/build/vite/README.md index adf57d98a..c8754024f 100644 --- a/build/vite/README.md +++ b/build/vite/README.md @@ -213,18 +213,13 @@ rather than reproducing webpack's CommonJS resolution globally. The `module` con `tslib.es6.mjs`, so no `tslib` alias is needed. Treat resolution changes as runtime changes, not just size optimizations. -One targeted exception is `resolve.alias` for `/^@azure\/arm-resources-subscriptions$/`, pointing -to `require.resolve('@azure/arm-resources-subscriptions')`, its CommonJS `dist/index.js`. -**G5-I01:** azureauth uses `Promise.resolve().then(() => require('x'))`, TypeScript's lowered -dynamic import. When `x` resolved to ESM, Rolldown 1.0.3 emitted a call to its ESM initializer -that returned `undefined`, not the module namespace; reading `SubscriptionClient` then failed. -Pinning this package to CommonJS restores the expected result without rewriting dependencies. -`TODO(#990)` tracks upgrading azureauth to real `import()` and removing the alias in -[#990](https://github.com/microsoft/vscode-documentdb/issues/990). There is no L1 invariant for -this lowering bug, and L3 does not call Azure discovery; the build-time -[lowered-import probe](../verification/README.md#bson-identity-runtime) bundles the same lowered -`require` with this config and fails without the alias. Re-test discovery and -both azureauth subscription-provider paths when removing the workaround. +The older azureauth CommonJS build needed an alias for `@azure/arm-resources-subscriptions` +because Rolldown could return `undefined` instead of its module namespace (G5-I01). +[#990](https://github.com/microsoft/vscode-documentdb/issues/990) removed that workaround: +azureauth v6 uses static ESM subpath imports. The +[Azure ARM ESM probe](../verification/README.md#azure-arm-esm-runtime) checks those exports +and their ESM provenance with the production host config. L3 activation does not exercise +live Azure Discovery. ### Externals: deliberate runtime requests @@ -316,20 +311,20 @@ for a downloaded VSIX; unrelated local reports cannot establish provenance. See [verification commands and limits](../verification/README.md) for complete recipes. -| Setting / boundary | Guard | -| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `views.js`, `preserveEntrySignatures`, relative chunk/asset URLs | L1 named `render`, packaged literal imports / `new URL(..., import.meta.url)` targets, report hashes; L2 network, CSP and preload diagnostics. | -| `cssCodeSplit`, CSS injection, fonts-as-files | L2 computed styles, font requests and marked-CSS removal negative control; L1 literal asset targets. | -| `React.lazy`, group priority, no catch-all vendor | L1 registry-backed lazy chunks and lightweight-view exclusions; L2 fetched chunks and grid interop. | -| Monaco worker format and Blob trampoline | L1 worker targets / nonliteral import budget; L2 actual editor worker responses; installed-VSIX real-origin check. | -| Dev origin, preamble, optimization/warmup, readiness hooks | L2-dev source scenarios; F5/HMR/rapid-save checks. L1 rejects the production dev-server strings; it does not test HMR. | -| Host ESM loader, strict exports, banner/global handling | L1 required entries, extension dynamic boundary and Kubernetes startup exclusion; L3 activation, late commands, clean logs and activation-error proof. | -| Host `keepNames` | L1 `keptClassName` (`UserCancelledError`) and `keepnames-class-name-lost` negative control. | -| BSON aliases | L1 implementation count per graph; runtime `bson-identity` probe with alias-removed control. | -| Azure alias / optional externals / default resolution conditions | L3 normal startup only; targeted discovery, auth, proxy and worker tests for paths it does not exercise. G5-I01 has no dedicated automated invariant. | -| CommonJS plugin and copied assets | L1 required `.cjs`, CommonJS `import.meta` rejection, manifest paths and `runtimeAssets`; TS-server completions/hover check separately. | -| Bundle-report ownership / `append` | L1 report-to-VSIX hashes and host-owned graph closure; proof controls reject missing/unowned chunks. | -| Overall loading cost | Warning-only [size report](../verification/README.md#size-report-warning-only): full host graphs, `mainStartup`, views entry/per-view JavaScript closures, `viewsAssets` for all report-owned non-script view assets, each worker and compressed VSIX, compared with the base branch on PRs. A smaller entry alone is not a smaller view. | +| Setting / boundary | Guard | +| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `views.js`, `preserveEntrySignatures`, relative chunk/asset URLs | L1 named `render`, packaged literal imports / `new URL(..., import.meta.url)` targets, report hashes; L2 network, CSP and preload diagnostics. | +| `cssCodeSplit`, CSS injection, fonts-as-files | L2 computed styles, font requests and marked-CSS removal negative control; L1 literal asset targets. | +| `React.lazy`, group priority, no catch-all vendor | L1 registry-backed lazy chunks and lightweight-view exclusions; L2 fetched chunks and grid interop. | +| Monaco worker format and Blob trampoline | L1 worker targets / nonliteral import budget; L2 actual editor worker responses; installed-VSIX real-origin check. | +| Dev origin, preamble, optimization/warmup, readiness hooks | L2-dev source scenarios; F5/HMR/rapid-save checks. L1 rejects the production dev-server strings; it does not test HMR. | +| Host ESM loader, strict exports, banner/global handling | L1 required entries, extension dynamic boundary and Kubernetes startup exclusion; L3 activation, late commands, clean logs and activation-error proof. | +| Host `keepNames` | L1 `keptClassName` (`UserCancelledError`) and `keepnames-class-name-lost` negative control. | +| BSON aliases | L1 implementation count per graph; runtime `bson-identity` probe with alias-removed control. | +| Azure ARM ESM / optional externals / default resolution conditions | Production host probe for ARM exports and ESM provenance; L3 activation; targeted discovery, auth, proxy and worker tests for paths activation does not exercise. | +| CommonJS plugin and copied assets | L1 required `.cjs`, CommonJS `import.meta` rejection, manifest paths and `runtimeAssets`; TS-server completions/hover check separately. | +| Bundle-report ownership / `append` | L1 report-to-VSIX hashes and host-owned graph closure; proof controls reject missing/unowned chunks. | +| Overall loading cost | Warning-only [size report](../verification/README.md#size-report-warning-only): full host graphs, `mainStartup`, views entry/per-view JavaScript closures, `viewsAssets` for all report-owned non-script view assets, each worker and compressed VSIX, compared with the base branch on PRs. A smaller entry alone is not a smaller view. | L2 and L2-dev use fixture backends and ordinary browser origins. L3 is installed-VSIX activation, not discovery, playground execution or a complete editor workflow suite. Do not weaken the CSP diff --git a/docs/ai-and-plans/README.md b/docs/ai-and-plans/README.md index 0f9aefedd..e4dfb3199 100644 --- a/docs/ai-and-plans/README.md +++ b/docs/ai-and-plans/README.md @@ -53,6 +53,7 @@ treat `status: historical` or `status: superseded` as current. | [sovereign-clouds](./features/sovereign-clouds/README.md) | Entra sign-in in Azure Government and China: per-cloud token audience, Entra error classifier | implemented; sovereign checks pending | | [Diagnose connection](./features/connectivity-troubleshooter/README.md) | Read-only connection diagnosis, a server summary and readable Markdown diagnostics (#100) | implemented; handover blocked on operator | | [deep-links](./features/deep-links/README.md) | `vscode://` links: action routing, `/connect`, `/local`, `/connect/azure` for Azure portal links | active; iteration 3 implemented | +| [connection-lifecycle](./features/connection-lifecycle/README.md) | Renewal, disconnect and identity-bound tabs, including permanently read-only retained views | feature branch; integration/live gates pending | Everything else is a single file at this root, such as: diff --git a/docs/ai-and-plans/features/completions-and-schema/README.md b/docs/ai-and-plans/features/completions-and-schema/README.md index 91b623de4..8f473b6c6 100644 --- a/docs/ai-and-plans/features/completions-and-schema/README.md +++ b/docs/ai-and-plans/features/completions-and-schema/README.md @@ -61,6 +61,9 @@ are preserved. Database/user field text remains escaped and untrusted. See the - **Schema is shared, not per-tab.** `SchemaStore` accumulates documents from the Collection View, the Playground, and the Shell against the same key. One surface feeding bad data degrades all of them. +- **Schema cache commands are development-only.** `_DocumentDB: Developer: Show Schema Store Stats` + and `_DocumentDB: Developer: Clear Schema Cache` are available in the Extension Development Host, not in an + installed extension. - **Schema teardown precedes output-channel disposal.** Activation registers the store with `SchemaStore.registerForDisposal`, which keeps its logging dependency alive through final statistics reporting and cache/timer cleanup. A closed-channel exception must not interrupt diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md new file mode 100644 index 000000000..38c3b59ee --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -0,0 +1,227 @@ +--- +feature: connection-lifecycle +kind: notes +status: active +created: 2026-11-19 +code: + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/runWithClient.ts + - src/documentdb/connectionTeardown.ts + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/webviews/components/DisconnectedOverlay.tsx +--- + +# Connection lifecycle + +Connections recover silently from Entra token expiry or an idle drop when the same account can +continue. An explicit Disconnect ends the session: retained tabs stay copyable but cannot run +database operations, even after reconnecting. + +**Landed on the feature branch, not yet on `main` (2026-12-02).** The open +[umbrella PR #1136](https://github.com/microsoft/vscode-documentdb/pull/1136) includes the +[recovery and retained-tab changes (#1149)](https://github.com/microsoft/vscode-documentdb/pull/1149), +their [review fixes (#1154)](https://github.com/microsoft/vscode-documentdb/pull/1154), and the +[simpler stale-action and ended-session handling (#1169)](https://github.com/microsoft/vscode-documentdb/pull/1169). +See the [decision log](./decisions.md), particularly 0031–0036, for what was chosen and why. +The [user guide](../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) describes what users see. + +**Verification still open.** [Automated checks passed for #1169](./iterations/04-pr1136-scope-and-test-review.md#case-2-follow-up-2026-12-02). +That does not establish real Entra expiry or sleep/wake recovery, dirty-tab copy after Disconnect, +or a Retry/sign-in overtaken by Disconnect in the workbench. Use the +[candidate verification runbook](./iterations/03-complexity-reduction-analysis.md#evidence-the-agent-collects-directly) +for the separate host, rendered, live-worker and telemetry checks. + +## Problem + +Before this work, connections could stop working after an hour or more and require restarting VS +Code. The original defects were: + +1. Interactive Entra ID returns a captured token from the OIDC callback forever. +2. Azure Discovery holds subscriptions whose ARM token is frozen, and the ARM 401 challenge crashes. +3. Nothing evicted or recreated a failed client, Retry reused it, and Collection View tabs held + the old instance. + +Evidence, telemetry and source pointers: [research-findings.md](./research-findings.md). + +Tracking: [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102), +[#1059](https://github.com/microsoft/vscode-documentdb/issues/1059), +[#566](https://github.com/microsoft/vscode-documentdb/issues/566) and +[#990](https://github.com/microsoft/vscode-documentdb/issues/990). Deferred: [Kubernetes tunnels +and network resilience](https://github.com/microsoft/vscode-documentdb/issues/1105), +[out-of-date results](https://github.com/microsoft/vscode-documentdb/issues/1106) and +[Microsoft account sign-out](https://github.com/microsoft/vscode-documentdb/issues/1119). + +## Code map + +| Area | Primary implementation | +| -------------------------------- | ------------------------------------------------------------------------------------------------------- | +| Client and binding lifecycle | `ClustersClient`, `ClusterSession`, `runWithClient` | +| Entra token renewal and errors | `MicrosoftEntraIDAuthHandler`, `entraSession`, `entraErrors/*`, `entraTokenFailures` | +| Shell and playground token relay | `ShellSessionManager`, `PlaygroundEvaluator`, `WorkerSessionManager`, `playgroundWorker` | +| Disconnect and removal | `connectionTeardown`, Disconnect command, connection and folder removal callers | +| Bound webviews and stale replies | `connectionSurfaces`, `DisconnectedOverlay`, bound-view routers and controllers | +| Tree recovery | `ClusterItemBase`, provider `errorRecoveryActions`, `showClusterConnectFailure` | +| Dashboard lifecycle polling | Cluster Dashboard controller, router and sampler | +| Measurement | [Renewal, blocked operations and subsequent same-tab reads](./telemetry.md); field verification pending | + +## WI-10 documentation choice + +The lifecycle manual stays in +[connecting-to-databases.md](../../../user-manual/connecting-to-databases.md) rather than adding a +separate page. The existing page already owns failed-connection recovery, so the continuation is +discoverable without another navigation level. The three requested workflow pages link to that +section. The operator chose no screenshots; no placeholders were added. Release notes and changelog +entries are unpublished drafts and do not represent a shipped release. + +## Intent + +- **Recover database connections silently** from token expiry and idle drops. For database + authentication, prompt only on a user click, never from a token callback. Separately, an Azure + Resource Manager challenge can prompt during Azure Discovery. Subscription listing keeps + successful results and records a sanitized diagnostic if an account or tenant cannot be listed. + A partial listing shows one warning with a **Show Output** action, and telemetry counts + skipped accounts and tenants without identifying them. +- **Keep one client per cluster.** Preserve same-identity physical-client replacement and its + internal generation check for late failures. Keep the fingerprint and identity checks where + async callers are not yet covered by an equivalent host lifetime. A one-way host lifetime ends + on explicit Disconnect; pending work from that lifetime must not adopt a later connection. +- **Change identity only while disconnected** (0003, 0026, 0027, 0030, 0033). **Update Credentials** and + **Update Connection String** offer **Disconnect and update**, perform the ordinary Disconnect + flow, and explain that edits require a disconnected connection. The command initiating Disconnect + waits for its own teardown; cancellation, a task conflict or failure in that flow does not fall + through to editing. C01's concurrent-edit edge remains accepted: another edit can observe the + disconnected latch before the driver close settles; no additional completion tracking is required + (0033). Disconnect and Remove Connection still offer Close, Keep open + and Cancel. A kept view stays open and copyable under a shaded, disabled dialog, but it is + permanently disabled for database access. **X** dismisses the notice so the user can select and copy existing text; + **Close view** closes the tab. Neither restores database access. Open fresh views from the tree. + Local Collection View query editing after dismissal is accepted at the user's discretion; + C08 does not require additional read-only gates. Document View's existing read-only and dirty + protections remain unchanged (0033). + **Sign in again** accepts only the pinned account and tenant. Credential repair stays in the tree. + **Close view** closes directly unless a dirty Document View needs an unsaved-changes warning. + By contrast, Disconnect/Remove **Close all** conservatively confirms every editable Document View, + even when reported clean; an editable tab not present when that confirmation opens is kept disabled. + Dashboard **Connection Diagnostics** stays available in a retained view; it opens a separate, + read-only diagnosis and restores no database access (0035). + On an ordinary recoverable operation failure, keep the + tab usable, retain its query, results or draft, and show a translated actionable error. After + repairing the cause, the user explicitly runs the operation again. There is no separate + Retry-to-unlock step and failed writes are never replayed automatically. A network drop or + same-account tree sign-in does not end the session or freeze its tabs (0032). +- After an explicit Disconnect, the tree offers **Reconnect**. Views kept open across the + Disconnect do not resume; **Reconnect** creates a new session and does not revive old tabs + (0027, 0032). New live views are opened from the tree. +- 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**. +- Failure rows offer **Open shell without authentication** as a separate diagnostic entry. + It never uses the failed saved authentication or shared authenticated metadata, and does not + promise that anonymous commands are authorized. Normal context-menu Shell startup is unchanged. + Pre-terminal failures use a tree modal; later failures stay in the terminal. + Extraction or a Connection Diagnostics panel entry is under evaluation, not approved (0036). +- **Obsolete recovery actions and ended sessions (0036):** one actionable explanation for a stale + explicit tree action, and one **Session ended** notice for a retired tab. The current connection + still reports its specific failure and repair steps. A single generation cutoff and the lifetime + abort signal keep old work from reaching a new session. Azure Discovery/ARM, retained views and + **DocumentDB Developer: Show Connection Client Sessions** stay in scope. +- **Session reports:** **Show Connection Client Sessions** covers the extension host, and + **Show Shell and Playground Sessions** covers workers. Both reports show counts followed by + separate session blocks with state in each heading. +- **Disconnect and Remove Connection** share a teardown and a tab choice. Saving a change to + connection details uses the disconnected edit flow (0026, 0030), subject to C01's accepted + concurrency limitation (0033). A connected edit starts with **Disconnect and update**; preserve + that flow's cancellation, task-conflict and failure handling. Retire the prior logical lifetime + at the edit boundary even when resource registries are empty (C02). Enforce the boundary across asynchronous + saves/reconnects; pending host work still needs cancellation at side-effect boundaries. Silent + token renewal and a network reconnect for the unchanged identity remain supported. Workers stay + pinned to their originating identity and do not replay interrupted work. +- A selected Playground displays **Disconnected** immediately after explicit Disconnect, without + requiring a failed Run first. Keep its file text and selected connection for Disconnect. + After Remove, clear the removed connection's Playground selection and reuse the existing + **Connect** affordance while preserving the file text (C06, 0033). Refreshing the indicator must + not start a worker or run a script. +- After a recoverable index-build poll failure, stop polling the table. Network or sign-in repair + does not resume it automatically; explicit manual **Refresh** is required. A successful manual + refresh may resume normal build polling, while a failed one leaves it paused (C10, 0033). +- 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. + +## Documents + +- **Why the design looks this way:** [operator decisions](./decisions.md), [original defect evidence](./research-findings.md), [telemetry definitions and queries](./telemetry.md). +- **Original delivery:** the [implementation plan](./iterations/01-implementation-plan.md) gives the proposal and dependencies; the [dev ledger](./iterations/01-dev-plan.md) records deviations, commits, operator checks and limits. +- **Stage reviews:** [Entra renewal](./iterations/01-pr1-entra-renewal-review.md), [Azure Discovery](./iterations/01-pr2-azureauth-review.md), [client identity](./iterations/01-pr3-client-identity-review.md), [recovery](./iterations/01-pr4-connection-recovery-review.md), [bound views](./iterations/01-pr5-bound-surfaces-review.md), [worker relays](./iterations/01-pr6a-worker-token-relays-review.md), [telemetry and docs](./iterations/01-pr7-telemetry-and-docs-review.md). +- **What users saw:** [hands-on UX review](./iterations/01-pr1136-ux-review.md), [resulting changes](./iterations/02-ux-implementation-plan.md), [#1146 review dispositions](./iterations/02-pr1146-copilot-review.md). +- **Umbrella review:** [initial combined review](./iterations/01-pr1136-final-review.md) and [#1136 inline findings and outcomes](./iterations/02-pr1136-copilot-review.md). +- **What was simplified or deliberately kept:** [design alternatives and live runbook](./iterations/03-complexity-reduction-analysis.md), [#1149 dispositions](./iterations/03-pr1149-copilot-review.md), [scope and test cuts delivered in #1169](./iterations/04-pr1136-scope-and-test-review.md). + +## Decisions index + +See [decisions.md](./decisions.md): + +- 0001 silent renewal, never prompt from the callback; +- 0002 a cached client with identity and generation; +- 0003 no silent identity change; restated by 0026 as a precondition (identity changes only while disconnected); +- 0004 the Disconnect tab choice; +- 0005 azureauth v6; +- 0006 delivery through a feature branch with stacked sub-PRs, shipped once; +- 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; +- 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; +- 0009 Kubernetes tunnel recovery, stable tunnel fingerprints, case handling and wider network-resilience testing move to #1105; +- 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent; +- 0011 Disconnect keeps the cached credentials and the verified identity; only Remove drops them; +- 0012 a minimal lifecycle design: no state machine, one epoch, no prompts in `getClient`, one-step teardown; +- 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 a notice on frozen webviews; 0031–0032 distinguish it from ordinary recoverable errors. +- 0017 view-level Retry and Close policy (superseded by 0031). +- 0018 saved connection edits permanently lock existing views (superseded by 0026 and 0027). +- 0019 require a fresh Dashboard delete after Disconnect and retain tree-only Paste. +- 0020 defer the late-failure comparison across releases and retain descriptive telemetry. +- 0021 key the in-memory connection fingerprint per extension host. +- 0022 separately unauthenticated Shell entry from failure rows only. +- 0023 retained-view Retry feedback (superseded by 0031). +- 0024 classify explicit stale recovery clicks without disturbing quiet background paths; 0036 simplifies their feedback. +- 0025 use modal feedback for tree-origin commands, leaving webview feedback unchanged; + descendant expansion is deferred to #1143 until foreground attribution is supported. +- 0026 Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin; A1 refusal replaced by A2 in 0030. +- 0027 views kept open after Disconnect are permanently disabled; Disconnect still asks Close or Keep open. +- 0028 broad binding removal rejected by 0031; keep internal generation and guarded host lifetimes. +- 0029 land the simplification inside #1136 before 1.2.0. +- 0030 offer Disconnect and update and perform the ordinary teardown before editing (A2). +- 0031 choose package P: A2, B2, C-balanced, D2 and guarded handoffs. +- 0032 same-account recovery keeps the tab live; only an explicit session end freezes it, and X + dismisses only the terminal notice. +- 0033 approve the PR #1149 review dispositions: accept C01's concurrency edge, clear removed + Playground selections for C06, leave C08's local editing unchanged, and require manual refresh + after a stopped index-build poll for C10; C12 remains a no-code disposition. +- 0036 simplify obsolete actions and ended bindings, retain useful features and trim duplicate tests; + isolated Shell extraction and placement remain open. +- 0037 reuse the Collection View tab ID to measure a later successful database read without a new recovery event. + +## Timeline + +| Date | Event | +| ---------- | ------------------------------------------------------------------------------------ | +| 2026-11-18 | Investigation: code read, telemetry attribution, vscode-cosmosdb comparison | +| 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | +| 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | +| 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | +| 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | +| 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | +| 2026-11-26 | WI-10 documentation draft, skill updates and unpublished 1.2.0 notes | +| 2026-11-27 | UX review findings organized into a draft implementation plan | +| 2026-11-29 | Complexity analysis (iteration 3); decisions 0026, 0027 and 0029; 0028 proposed | +| 2026-11-30 | A2 approved (0030); package P chosen (0031–0032); implementation partially committed | +| 2026-12-01 | PR #1149 review dispositions approved (0033); follow-up implementation pending | +| 2026-12-02 | #1136 includes the #1154 review fixes and #1169 scope reductions (0036) | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md new file mode 100644 index 000000000..993078954 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -0,0 +1,957 @@ +--- +feature: connection-lifecycle +kind: decisions +status: active +created: 2026-11-19 +--- + +# Connection lifecycle: decisions + +> 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 (modified by 0026) | 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 (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 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 (modified by 0022) | 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 0031–0032) | Dismissible notice for ended sessions, not for unlocking a recoverable view | 2026-11-24 | Yes; retains copy access | +| 0017 | Limit unavailable webview recovery to Retry and Close view | Superseded by 0031 | No view-level Retry; same-account repair stays in the tree | 2026-11-24 | See 0032 for notice dismissal versus closing a tab | +| 0018 | Saved connection edits permanently lock existing views | Superseded by 0026, 0027 | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | +| 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | +| 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | +| 0021 | Key the in-memory connection fingerprint per extension host | Accepted | Operator: use HMAC and verify CodeQL without dismissing a remaining alert | 2026-11-26 | Yes; replaces unkeyed SHA-256 without changing identity rules | +| 0022 | Offer a separately unauthenticated Shell from failure rows only | Accepted | Operator approved the bounded F1 policy in the iteration 2 lead run | 2026-11-27 | Modifies 0015 only for this explicit anonymous entry | +| 0023 | Keep retained-view Retry failure feedback inside the unavailable dialog | Superseded by 0031 | D2 removes the retained-view Retry episode | 2026-11-27 | No automatic operation replay | +| 0024 | Classify explicit stale recovery clicks and explain only failed actions | Accepted (modified by 0036) | Operator selected F5 option C; 0036 simplifies stale-click feedback | 2026-11-27 | Cancellation, disposed work and obsolete replies remain quiet | +| 0025 | Tree-origin failures use modals; webview-origin command feedback stays unchanged | Accepted | Operator confirmed F3 scope | 2026-11-27 | Shared command registrations must preserve origin | +| 0026 | Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin | Accepted (modified by 0030) | Operator initially chose A1; 0030 replaces it with A2 | 2026-11-29 | Yes; removes the edit-while-connected path | +| 0027 | Views kept open after Disconnect are permanently disabled; Disconnect still asks Close or Keep open | Accepted | Operator chose B2 over B1 (always close): "still ask the user" | 2026-11-29 | Yes; no rebinding or revival of retained views | +| 0028 | Surfaces hold only the cluster ID; remove the fingerprint, generation and binding carry-through | Rejected by 0031 | Operator chose C-balanced; preserve internal client generation and lifetime guards | 2026-11-29 | Broad removal weakens same-client failure and async lifetime checks | +| 0029 | Land the simplification inside #1136 before 1.2.0 | Accepted | Operator: before 1.2.0, as part of the feature PR | 2026-11-29 | — | +| 0030 | Offer Disconnect and update, performing the ordinary Disconnect flow before editing | Accepted (modified by 0033) | A2 remains; 0033 accepts C01's concurrent teardown/edit edge case | 2026-11-30 | Modifies 0026; pinned-account rule and pre-release timing remain | +| 0031 | Choose package P: A2, B2, C-balanced, D2 and guarded handoffs | Accepted (modified by 0033) | 0033 records the review dispositions and bounded complexity tradeoffs | 2026-11-30 | Lifecycle and worker guards remain; see C01/C08 exceptions | +| 0032 | Keep tabs live through same-account recovery; X on a frozen tab dismisses only its notice | Accepted (modified by 0033, 0038) | 0033 permits local query editing; 0038 changes Close all confirmation | 2026-11-30 | Database access stays permanently disabled on retained views | +| 0033 | Approve the PR1149 review dispositions with explicit complexity tradeoffs | Accepted | C01 option 3; C06 option 2 direction; C08 won't fix; C10 option 2 | 2026-12-01 | Nine code fixes; C01/C08/C12 are no-code dispositions | +| 0034 | Keep manual Refresh as the only way to resume paused index polling after Create | Accepted | Document the workaround; no code change | 2026-12-01 | Clarifies 0033 for pre-review finding N01 | +| 0035 | Keep Dashboard Connection Diagnostics available in disconnected views | Accepted | Not gated like the other tree-command actions | 2026-12-02 | Exception to 0031/0032: diagnosis opens a separate, read-only view | +| 0036 | Simplify obsolete actions and ended bindings without cutting useful features | Accepted | Operator accepted #2/#3 and duplicate-test trimming, not broad feature cuts | 2026-12-02 | Isolated Shell extraction or panel placement remains open | +| 0037 | Measure a later successful read in the same Collection View tab | Accepted | Reuse the tab ID on an existing RPC instead of adding a recovery event | 2026-12-02 | Extends 0020 within a version; no cross-release rate | +| 0038 | Confirm Close all for the exact editable Document Views it will close | Accepted | Operator selected the conservative fix for PR #1136 C06 | 2026-12-03 | Retained-view Close view stays dirty-only | + +> 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 +> written; a retitle means a new decision. + +**Status vocabulary:** `Proposed` · `Open` · `Accepted` · `Accepted (modified)` · `Deferred` · +`Superseded by D#` · `Rejected` + +--- + +## 0001. Entra tokens are renewed silently in every OIDC callback; the callback never prompts + +**Accepted** by the operator on 2026-11-19. + +The OIDC callback calls `getSession` with `silent: true` and pins the account and tenant that the +connection started with. VS Code's MSAL refreshes the access token from its refresh token, so the +normal case is silent. The driver already calls the callback again after a code 18 rejection +(`automated_callback_workflow.js`), so a callback that returns a fresh token is enough to recover. + +When silent renewal is impossible, the operation fails with a typed "sign-in required" error, and +the UI offers a single **Sign in again** action. Silent renewal is impossible when: + +- the refresh token has expired or been revoked; +- a Conditional Access sign-in frequency policy, an MFA challenge or a CAE event requires the user; +- the account was signed out of, or removed from, VS Code. + +The action calls `getSession` with `createIfNone` for the same account and tenant, then reconnects. + +Rejected: + +- **`createIfNone: true` inside the callback.** This is what vscode-cosmosdb does as a last resort, + and it is behind their open P1 microsoft/vscode-cosmosdb#3110 (repeated prompts, even after + dismissal). It is rejected for four reasons: + - The callback also runs for background work: pool reconnects, dashboard polling, tree refresh + and completions. Prompts would appear with no user action. + - The driver gives `OIDC_CALLBACK` a hard 60 s timeout, and an MFA sign-in can take longer. + - The callback runs under a driver lock, so every operation queues behind the modal. + - The prompt lets the user pick another account, which changes the identity behind open tabs + (see 0003). +- **Proactive refresh timers.** Unnecessary, because the driver's code 18 retry together with + silent acquisition covers expiry. + +## 0002. Keep one cached client per cluster; surfaces resolve it per operation with identity + generation + +**Accepted** by the operator on 2026-11-19 ("keeping versions or username/clusterid hash would be +sufficient/better"). + +`ClustersClient._clients` keeps one `MongoClient` per `clusterId`. Each client records: + +- an **identity fingerprint**: the existing `getConnectionAuthIdentity` plus the signed-in Entra + account; +- a **generation** that increases every time the client is replaced. + +Surfaces hold `{ clusterId, fingerprint, generation }` and resolve the client per operation: + +- same fingerprint and generation: proceed; +- same fingerprint, new generation: reconnect transparently, and re-run reads from the first page + because cursors are lost; +- different fingerprint, or no client: disconnected (0003). + +Rejected: + +- **A new client for each operation** (vscode-cosmosdb). Creating a client costs about 1.1 s (p50) + and 4.3 s (p90) for Native, and about 2.0 s and 9.0 s for Entra. It also loses cursors (pagination), + server sessions and monitoring. This fits Cosmos's stateless HTTP; it does not fit a `MongoClient`. +- **Caching by `clusterId` + identity.** Two clients for one cluster could coexist, and tabs opened + under the old credentials would keep working after Update Credentials. That is the permission + risk 0003 removes, and it also leaks pools. + +## 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): + +> we need to be careful about ensuring that a connection is tied to the user name, otherwise.. a +> user could change credentials and the user name, then the tabs would get a new permissions +> possibly, this is risky. so basically, when a user disconnects/updates credentials, we might need +> to "disconnect" the open tabs, like have valid disconnected state with discoverable info why no +> 'actions' are now allowed + +- Triggers: + - Disconnect; + - Remove Connection; + - Update Credentials or Update Connection String, when the fingerprint changes; + - sign-out or removal of the bound Entra account (`onDidChangeSessions`); + - silent renewal that is impossible (reason "Sign-in expired"). +- A disconnected surface disables every action that talks to the server. It keeps the query text, + filter, sort, projection, page position and unsaved document edits. It shows the reason and the + matching action: Reconnect, Sign in again, or Close. +- A password change for the **same** user keeps the fingerprint. Tabs continue on the new client, + because the permissions follow the user. +- Today, Document View, the index and Query Insights routers, and the Cluster Dashboard already + resolve a client per operation **without** an identity check. They would quietly continue under + the new identity, so they are in scope. + +## 0004. Disconnect lets the user choose: close all affected tabs, or keep them open and disabled + +**Accepted** in principle by the operator on 2026-11-19 ("we could give an option to the user: +close all, or keep open but disabled"). The default, and whether the choice is remembered, are +still open (plan Q2). The proposal is to keep tabs open and disabled by default, and to remember the +choice in `globalState`, the same way the Atlas and Kubernetes view modes are remembered. + +## 0005. Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim + +**Accepted.** The operator is open to updating dependencies, and the upgrade is already planned for +1.2.0 in #990. + +azureauth v6 calls `getSessionFromVSCode(..., { silent: true })` for every `getToken`. It also +satisfies the request-object contract that azureutils 4.2's `BearerChallengePolicy` already expects. + +Rejected: + +- **A local wrapper in `AzureSubscriptionProviderWithFilters`.** It would duplicate upstream v6 + logic, and it would be thrown away when #990 lands. +- **Staying on 5.1.1, the latest stable.** It still captures the token. + +## 0006. Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once + +**Accepted** by the operator on 2026-11-19. Source: operator input during planning. + +> I'm for 'one big PR', I had some bad experience with stacked PRs and the need of moving updates up +> the chain before being able to recover and in the end, I had to merge them individually anyway. so +> maybe a 'feature' branch for this and then PRs against it, sometimes on top of other PRs, but +> without the 'stack' feature from github. [...] it won't be a partial release, it all will go out +> at once. + +After the evaluation, the operator initially asked to reduce PRs opened on top of other open PRs: +"not required, just welcomed". + +**Amended by the operator on 2026-11-19:** Approvals will take time, so build and open each next +sub-PR on the preceding PR's branch without waiting for it to merge. The operator will follow up +with approvals and merges. This changes neither the explicit operator test gates nor the single +release from the feature branch. + +**Amended by the operator on 2026-11-20:** PR publication is pre-approved. Push the topic branch +and open its draft PR without asking for separate confirmation. This does not authorize merges +or remove review, verification, or operator test gates. + +- It follows CONTRIBUTING §1.4 (large features). +- It fits the repository's enforcement: + - CI runs on PRs to `feature/**`; + - the `feature/**` ruleset requires a reviewed PR and blocks force pushes; + - only merge commits are allowed, and head branches are deleted on merge. +- Merge commits keep the original commits. A PR opened on top of another one therefore shrinks to + its own diff once its base merges and GitHub retargets it. Verify the retargeting after each merge. +- The split and the rules are in [the plan's Delivery section](./iterations/01-implementation-plan.md#delivery). + +Rejected: + +- **One big PR to `main`:** + - The diff mixes a dependency migration, host lifecycle changes, three webviews and teardown, so + review and AI pre-review get worse. + - Each push dismisses the approval. + - There are no reviewed checkpoints, and conflicts with `main` are resolved only at the end. +- **GitHub's stack feature:** not needed; use ordinary PRs targeting the preceding branch. +- **Shipping WI-1 and WI-2 early as a patch (plan Q5):** no partial release. + +## 0007. The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default + +**Accepted** by the operator on 2026-11-19. It answers plan Q2, which decision 0004 left open. Source: +operator input on the dev plan's provisional answer A2. + +> this will be a modal dialog from vs code, so we can't preselect, we don't need to remember. we can add +> a setting for users to control their default if they want. + +- The Close all / Keep open (disabled) choice from 0004 is a VS Code modal. A modal has no pre-selected + button, and its built-in Cancel cancels the whole operation. +- The choice is **not remembered** between uses. +- A setting lets users pick a default: `ask` (the default) shows the modal; `closeAll` or + `keepOpenDisabled` skips it. The setting never skips the unsaved-edits confirmation. +- The choice applies to Disconnect and Remove Connection. Decision 0018 makes a saved identity or + settings edit close-only instead: existing views keep their contents but are not moved to the + new connection. + +Rejected: + +- **Pre-select Keep open and remember the last choice in `globalState`** (the earlier proposal): a modal + cannot pre-select a button, and a remembered answer that silently changes what the next Disconnect does + is less predictable than an explicit setting. + +## 0008. Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference + +**Accepted** by the operator on 2026-11-19. Source: operator input on the dev plan's provisional +answer A4. + +> check what 'azure resoruces' extension is using, that's the same team that's behind the auzreauth +> package, and that azure resources extnesion is heavily used., I'd update / upgrade as hihgh as viable +> and not breaking our fworkflows. + +- The #990 upgrade (0005) targets the highest versions of azureauth, azureutils, utils and + `@microsoft/vscode-azureresources-api` that keep our workflows working, with one installed copy of each. +- The Azure Resources extension is the reference, because the same team owns azureauth and the extension + is heavily used. On 2026-11-19 its `main` used azureauth `^6.1.0-alpha.2`, azureutils `^4.3.0` and + utils `^4.1.0`. +- The dev plan ([iterations/01-dev-plan.md](./iterations/01-dev-plan.md), WI-3 step 1) holds the version + ladder, the evidence and the workflow checks that define "not breaking". + +Rejected: + +- **The minimal set** (azureauth `6.0.0-alpha.8` with azureutils 4.2 and utils 4.1, the earlier + proposal): it stays behind the line the azureauth owners run, and it would mean a second migration + later. It remains only as the last fallback if a higher level breaks a workflow that cannot be fixed. + +## 0009. Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 + +**Accepted** by the operator on 2026-11-19. Source: operator input during dev planning. + +> I'd consider moving kubernetes fixes and the adding 'network resilience' as a new issue to work on +> once 1.2.0 ships, this would also simplify this dev plan. + +Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105), to be scheduled after +1.2.0: + +- re-creating Kubernetes port-forward tunnels outside the tree. Today only `beforeCachedClientConnect` + restores a tunnel, when a tree node expands; +- tunnel ownership on Disconnect and Remove, and running the teardown when a kubeconfig source is + removed; +- provider-specific cluster ID matching, which the approved plan had put in WI-7. Today + `CredentialCache` folds case, so Kubernetes `Prod` and `prod` collide, and task conflict matching does + not fold, so it misses Azure case aliases. Both behaviors already exist today; +- Kubernetes API credential expiry (the AKS exec plugin); +- a network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. + +**Amended by the operator on 2026-11-23:** Stable fingerprints across Kubernetes forwarded-port +changes also move to #1105. Until then, keep the identity check unchanged: if a closed binding +still exists and the forwarded port changes, automatic replacement can reject it as an identity +change. Do not ignore port changes for ordinary connections or bypass the fingerprint check. + +**Stays in iteration 1:** generic idle and network-drop recovery. That means closed-client and transient +classification, the cancelled-reuse fix, closed-client replacement and OT-4, which together are #1102's +"recover on the next operation without a restart". + +**Guard:** tunneled connections must not get worse. + +- Connection refused against a port-forward port is `transient`: the client is kept, not evicted. +- Per-operation resolution does no less than today's tree path. + +A tab whose tunnel died therefore behaves exactly as it does today. + +Rejected: + +- **Doing it in 1.2.0:** it adds a second layer (tunnels) to a release that is already the largest + connection change so far, for an authentication method that does not expire. The case-handling bugs + already exist and are rarely hit (two contexts that differ only in case). + +## 0010. Rely on the server to reject expired tokens; replacing a client for the same identity is transparent + +**Accepted** by the operator on 2026-11-19. It answers T-1 in the dev plan. It modifies 0002's "re-run +reads from the first page", and drops the approved plan's WI-1 requirement that a known-expired token is +never offered on a new socket. Source: operator input at planning. + +> I wouldn't worry about this guarantee, the server will tell us, then we can act, this is easier. sure +> we can have a local check for some expirations, but that's unreliable anyway. + +> no banners about out of date, this can be another future work issue [...] this is really an edge case. + +- **Expired tokens:** + - No proactive client rotation and no local expiry checks. + - The server rejects an expired token with code 18; the driver then calls the OIDC callback again, + which renews silently (0001). + - The operator test OP-1 in the dev plan confirms what the server actually returns. If it closes the + socket instead, the failure classifier acts on that: the next foreground operation gets a new client + with a fresh token cache. +- **Replacing a client for the same identity** (recovery from a closed client, Sign in again with the same + account) is **transparent**: open views continue on the new client, with no re-run of the query and no + notice. 0002's reason for re-running, lost cursors, does not apply: Collection View pages with offset + queries. +- **No "results may be out of date" notice anywhere in this iteration,** including when a view returns + from the disconnected state. Whether to indicate stale data (after a reconnect, a long idle, or writes) + is [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106). + +Rejected: + +- **Proactive rotation when the issued token expires:** it covers only host operations, not the pool's own + sockets or the shell and playground workers, unless rotation is coordinated across all of them. It + costs a reconnect about every hour, and local expiry checks are unreliable anyway. +- **Re-run page 1 with a "results are no longer current" notice** (0002 as written): it would appear after + every reconnect, for no correctness benefit. + +## 0011. Disconnect keeps the cached credentials and the verified identity; only Remove drops them + +**Accepted** by the operator on 2026-11-19. It answers plan Q3 (dev plan A3), reversing the #1059 +proposal that Disconnect drops `CredentialCache`. Source: operator input on the pre-hand-over review of +the dev plan. + +> we should not drop the credential cache, that was too premature + +- **Disconnect** closes the client, stops the shell and playground workers, latches the cluster and + handles open surfaces (0004, 0007). It keeps the `CredentialCache` entry and `lastVerifiedIdentity`. +- **Remove Connection** drops both. An identity-changing credential update keeps the new credentials and + replaces the verified identity on its next successful connect. +- Evidence from the review (the operator's reason is the quote above): `ClustersClient` can start a client only from a `CredentialCache` entry, and only the tree fills it + (dev plan F-20). Dropping it on Disconnect would leave a tab's Reconnect with nothing to connect from, + because surfaces never prompt. Keeping `lastVerifiedIdentity` makes that Reconnect silent and pinned to + the same identity. If the Entra session is gone, it fails with **Sign in again** (0001), never with a + prompt for another account. +- The same review found that the tree drops `CredentialCache` on **every** connect failure, including + network errors. The dev plan (WI-5 step 3) now keeps the entry for recoverable failures and evicts it + only when credentials were rejected. + +Rejected: + +- **Drop `CredentialCache` on Disconnect (#1059, the earlier provisional answer A3):** it needs a second + credential-loading path outside the tree for every provider (storage, ARM, Atlas, Kubernetes), and the + user must retype a password that was typed only for a discovery connection. + +## 0012. Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown + +**Accepted** by the operator on 2026-11-19, after a review of the dev plan for over-engineering. Source: +operator input. + +> the premise is simple, so I don't want to have too many managers, controllers, and reconcile tools +> processes in the plan. + +> apply all simplifications to the plan, and I approve all simplifications. + +The dev plan ([iterations/01-dev-plan.md](./iterations/01-dev-plan.md)) now follows these rules: + +- **No stored connection state.** There is no cluster state machine, no projected surface state, no state + service with change events, and no tRPC state subscription. A surface learns its state when it resolves + its binding; routers return a structured "unavailable" result. The only push is teardown calling + `disable(reason)` on each registered surface, and that registry is a plain list. +- **One staleness guard:** the per-client generation plus one per-cluster epoch. The separate startup, + lifecycle and surface epochs, the dashboard loop token and the worker instance IDs are gone. A stale + result is checked once on the host, before it changes anything; the webview ignores responses while its + banner shows. +- **`getClient` never prompts.** The `interaction` parameter and the audit of every call site are gone. + Only the tree's first connect and Sign in again may prompt. Background callers pass `background: true` + and never replace a client. +- **Teardown is two plain functions** (confirm, then commit), with a conflict recheck right before the + commit. No reservation in TaskService and no rollback. +- **No `onDidChangeSessions` listener.** This changes the approved plan's WI-5. The next operation's + silent lookup finds a signed-out account. +- **Four error classes:** `EntraSignInRequiredError`, `EntraIdentityMismatchError`, `TokenCallbackError` + for any other callback throw (all auth methods), and `ConnectionUnavailableError { reason }`. +- **The fingerprint hashes the stored connection string without its password, plus the principal.** No + normalization; any connection-string edit counts as an identity change. +- **Smaller removals:** the 30 s replacement backoff; startup abort only when every waiter aborted; + two Sign in again paths (it always uses `forceNewSession`); shells and the playground in the surface + registry; the changed-token telemetry, the remaining-validity measures and `connection.recovered` + (this changes the approved plan's WI-9); the "outcome unknown" wording for writes; checkpoints CP-1 and + CP-3, which become ordinary PR review. PR 5 stays one PR unless its diff becomes too large. + +Unchanged: everything that carries an accepted decision (0001 to 0011), the single-flight startup, the +cancelled-reuse fix, closed-client replacement, the failure classifier and the export and import lease. + +## 0013. Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks + +**Accepted** by the operator on 2026-11-19. It modifies 0012. Source: a review of the dev plan against the +code for omissions that could lose data, break reconnection or force a redesign; the operator agreed with +every finding and asked to "update the plan". + +The findings, each confirmed in the code, and the corrections now in the dev plan +([iterations/01-dev-plan.md](./iterations/01-dev-plan.md)): + +- **A credential change could be stored while teardown was refused**, and a failed save can still have + written the secrets (F-21). Correction: an identity-changing update sets the latch **before** it saves, + and new tasks and leases are refused while latched. After the save, the re-read stored connection + decides: a changed fingerprint commits the teardown, an unchanged one clears the latch. This keeps 0012's + "no reservation"; the latch is the only thing that can be undone. +- **An old reply could overwrite a newer edit after a Reconnect as the same user.** Correction: host-side + results check the per-cluster epoch, not only the fingerprint and the latch, and the Document View + applies a reply only if the editor has not changed since the request. +- **The binding was lost in handoffs** (F-23). Correction: a playground stores its fingerprint on the + document's connection, not on the shared evaluator; Collection View passes its fingerprint to import and + export, which check it before their first `getClient`. +- **Recovery was tied to tree expansion.** 0012 removed the operation wrapper. Correction: one stateless + function, `runWithClient`, reports failures that happen during an operation; the dashboard sampler + classifies errors before it turns them into strings (F-24). +- **Folder deletion bypassed teardown** (F-23). Correction: it runs the teardown for every connected + descendant, with one combined confirmation. +- **Gates.** OP-1 is split: before the handler change it can only tell code 18 apart from a socket close; + renewal is proven after it, on a new socket of the same client (`maxIdleTimeMS`). OT-7 no longer + requires in-flight saves to fail, because `close(force)` cancels nothing (F-22); it requires no new + submission, no replay, no stale UI update and no claim that an unacknowledged write was not applied. + +None of the corrections adds a state machine or a service; 0012's other rules stand. + +## 0014. Keep in-memory connection settings after a rejection for a verified Entra identity + +A final Entra database authentication rejection still evicts the client. If the connection has a +verified Entra identity, keep its existing in-memory connection settings so **Sign in again** can +start from that identity, including when invoked with only `clusterId`. The operator chose this +over deleting the settings and losing that recovery action, to keep recovery smooth. + +This does not retain the rejected token, write anything to persistent storage, change destination +checks, or start a silent retry. Native authentication and RU key handling are unchanged. The +explicit sign-in path still checks the epoch after prompting and never moves an open surface to a +different identity. + +## 0015. Use the existing latch to block startup after authentication rejection + +Evicting a rejected client is not enough: a subsequent operation could immediately start a new +one with the same settings. Set the existing in-memory latch to `credentialsRejected` before +evicting the rejected generation. The matching explicit recovery can clear that reason only if +the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a credential change. + +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. + +## 0020. Defer the cross-release comparison of late failures + +The operator chose to keep descriptive telemetry and defer the WI-9 before/after comparison +for 1.2.0. Auth and closed-client unavailability can now be returned as normal RPC responses, +which the SDK records as successes without a failure signature. An apparent drop across releases +could be a reporting change rather than improved recovery. + +Keep renewal, client age and entry generation, and ARM challenge queries for a single version. +Do not add an instrumentation path or keep a socket-only comparison in this release. CP-5 still +checks pre-release ingestion and records that the late-failure trend is unmeasured. + +**Bounded amendment (2026-11-26):** The operator accepted [final review F3](./iterations/01-pr1136-final-review.md#f3-blocked-webview-operations-look-like-successes-in-telemetry-medium). +A valid unavailable RPC response now adds only the allowlisted `unavailableReason` property to +the existing event. The SDK result does not change. The cross-release comparison stays +deferred; CP-5 checks ingestion of the new property for a single prerelease. + +## 0021. Key the in-memory connection fingerprint per extension host + +The operator chose HMAC-SHA-256 with a random key held only by the extension host. +Fingerprints are compared within one running host; they are not passwords or stored +verifiers. Keep the existing URI comparison, including exclusion of the database password +in its authority, and keep the verified principal in the fingerprint. The URI's other +options may contain credentials and are not treated as sanitized data. + +Do not retain historical connection strings in an identity map or persist the HMAC key. +Recheck [CodeQL alert 39](https://github.com/microsoft/vscode-documentdb/security/code-scanning/39). +If it still reports the HMAC call, leave it open for review rather than suppressing it. + +## 0022. Offer a separately unauthenticated Shell from failure rows only + +**Accepted** by the operator on 2026-11-27 during +[iteration 2](./iterations/02-ux-implementation-plan.md). + +Replace the failure-row Shell action with **Open shell without authentication**. +Normal context-menu Shell startup remains authenticated. The anonymous entry may bypass +rejected or missing authentication holds, but must honor removal, credential-update and +explicit Disconnect guards. It does not clear a latch, use or modify `CredentialCache`, +change saved credentials or connection identity, or fall back to saved authentication. + +Use an available model or stored endpoint stripped of credentials and authentication +options. Do not fetch an endpoint from ARM on this path; report an unavailable endpoint +honestly. Retain the existing host-gated TLS and emulator rules. Opening the terminal +does not promise that anonymous database operations are authorized. + +This is the operator's explicit approval of the proposed policy, including its authentication +boundary. No additional rationale was supplied. Implementation remains subject to verifying +the endpoint and lifecycle contracts against the current source. + +**Execution clarification (2026-11-27):** the operator approved a code-only internal command, +the missing-endpoint message **Cannot open a shell without authentication for "{0}": its +endpoint is not available.**, and stripping database, proxy and client-certificate +authentication credentials while preserving server TLS validation. + +**Completion boundary (2026-11-27):** the operator questioned disabling already-working +suggestions, then agreed to metadata-only isolation for the new diagnostic anonymous path. +Normal Shell behavior remains unchanged. An internal `includeClusterMetadata` capability, +defaulting to the existing behavior, preserves local methods, commands, operators, history and +bracket suggestions while excluding shared-client database/collection/field/schema lookups in +anonymous sessions. Prewarming, schema feeds and credential-backed error explanations are also +excluded there. No fake cluster IDs or blanket suggestion disablement are authorized. +The completion provider and its existing tests are directly dependent owned files for WI-6. + +**Parse-error clarification (2026-11-27):** the operator selected **1.A**: show +**Invalid connection string.** when anonymous endpoint parsing fails and discard the +original parser error/cause completely. Dependency parser errors can contain the credential-bearing +URI or username, so retaining the unsafe cause is not permitted. The bounded replacement applies +only to constructor parsing, not arbitrary startup errors. + +## 0023. Keep retained-view Retry failure feedback inside the unavailable dialog + +**Accepted** by the operator on 2026-11-27: F4 option B. + +Keep the original unavailable reason distinct from the latest failed attempt. Use the bounded +copy **Unable to recover the connection. Try Retry again, or close this view.** for an +unclassified failure, without exposing a raw exception or stack. Announce the failure in-view +and restore Retry, Close view and X after the attempt. Do not add a host modal, change the +bound identity, or replay the failed database operation. No additional rationale was supplied. + +**Runtime-control clarification (2026-11-27):** after a review found that Retry can return +a new Close-only unavailable reason, the operator selected **2.A**, qualified by: +**when a user had a Retry button visible, it should never be gone after a retry**. +The displayed reason must remain truthful without removing an already-visible Retry control +because state changes at runtime. Identity and lifecycle guards +continue to reject unsafe attempts; keeping a control visible does not authorize rebinding. + +**Episode scope (2026-11-27):** the operator explicitly selected **1A**. An unavailable episode +persists while its dialog is dismissed and reopened, and ends when recovery succeeds. Once Retry +has been offered, runtime reason changes or a failed attempt do not remove it within that episode. +After success, a later initially Close-only episode does not inherit Retry. + +This qualifies 0018's visible **Close view**-only policy only for an already-unavailable episode +that previously offered Retry. Saved edits still permanently block database operations and old +views never rebind to changed settings. The explicit Retry remains a guarded attempt, not a promise +that the current reason can recover. This records the operator's qualified instruction; no new +rationale is inferred. + +## 0024. Classify explicit stale recovery clicks and explain only failed actions + +**Accepted** by the operator on 2026-11-27: F5 option C. +The reason-specific modal copy below was superseded by [0036](#0036-simplify-obsolete-actions-and-ended-bindings-without-cutting-useful-features); the quiet paths still apply. + +Refresh current tree state and explain actually failed explicit clicks using their real reason: +**This connection was removed. Choose another connection.** or +**This connection changed. Refresh the tree and try again.** +Already-completed recovery refreshes or reveals current state without an error. +Cancellation, disposed work and obsolete background replies remain quiet. + +An explicit stale worker sign-in click uses its existing bounded worker surface when that +terminal or file still exists, not the tree's host-modal policy. Never connect another identity +or restart disposed work to make a stale action appear successful. No additional rationale +was supplied. + +## 0025. Tree-origin failures use modals; webview-origin command feedback stays unchanged + +**Accepted** by the operator on 2026-11-27. + +F3 covers explicit tree-origin actions, including tree expansion and commands, but does not +turn shared webview-origin command failures into host modals. One failed action gives one +modal with a translated heading and separate detail. Tree children remain recovery actions, +not error or information rows. Background replies and cancellations stay quiet. +No additional rationale was supplied. + +**Execution scope clarification (2026-11-27):** the operator selected descendant-expansion +alignment only for extension-owned Connections and Discovery TreeViews, leaving Azure Resources +unchanged. `getChildren` does not identify foreground versus background origin, and the Azure +Resources host owns its TreeView. The operator requested +[#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) to investigate Azure support, +with motivating scenarios and the trade-offs of consistent feedback versus background modal +noise and host coordination. The own-view origin/event-order contract still needs verification. + +**Disposition (2026-11-27):** after the advisor found no documented expansion-event ordering, +the operator selected **Ship tree-command alignment now; defer descendant expansion to #1143 +until foreground attribution is supported**. This supersedes the earlier own-view-only +expansion scope for this iteration. No descendant-expansion modal change is authorized here. + +## 0026. Update Credentials and Update Connection String require a closed connection + +**Accepted** by the operator on 2026-11-29: option **A1** (refuse) of +[iteration 3](./iterations/03-complexity-reduction-analysis.md) proposal A. Source: operator +input after the PR 1136 Copilot review showed that C01 to C03 were all missed identity fences. + +> why not say that to update credntials one needs to disconnect first. disconnect disables all +> surfaces. then a new connectin is a clear state. + +> updating credentials whiel haveing a query tab oben is a true edge case and a user can work +> around limitaitons we inmpose. + +> even 10 exra lines of code for a specific scenario is something ta has to maintained in the +> future and tested. this is a hidden cost that will stay with us. + +- **Update Credentials** and **Update Connection String** on a connection that has a client or a + pending startup are refused with a short message that says to Disconnect first. The refusal + changes nothing: no latch, no teardown, no wizard. A disconnected connection (0011 keeps its + cached credentials) can be edited. +- After Disconnect, the edit runs as on `main`: it saves, clears the cached credentials and the + verified identity, and the next connect is a new connection with a clear state. This replaces the + edit path of 0013 (latch before save, restore `previous`) and the `credentialsUpdating` and + `credentialsChanged` reasons. 0018's edit lock is superseded, because no edit can be saved while + a surface is bound to a live client. +- **Sign in again** accepts only the account and tenant the connection is pinned to. Switching + accounts means Disconnect, Update Credentials, and connect. This removes the account label + heuristic in `signInAgain.ts`. +- 0003 is restated: it stays a requirement, but it is met by a precondition that holds in one + place (identity changes only while disconnected) instead of a fence at every call site. + Disconnect, Remove, sign-out of the bound account and a rejected credential still disable + surfaces; the trigger "Update Credentials when the fingerprint changes" is gone. + +**Rejected:** A2, asking once and then running the Disconnect teardown before the wizard. It is +friendlier but adds a flow that every later change must keep working. No additional rationale was +supplied for choosing A1 beyond the quoted position. + +**Accepted risks** (analysis, section 7): one extra manual step to switch credentials on an open +connection, and a wizard that starts before Disconnect can finish after an edit and Reconnect, so +it would run as the new identity. Another window can still edit stored settings; the existing +identity guard (0018) stays until 0028 is decided. + +## 0027. Views kept open after Disconnect are permanently disabled; Disconnect still asks + +**Accepted** by the operator on 2026-11-29: option **B2** of +[iteration 3](./iterations/03-complexity-reduction-analysis.md) proposal B, with the qualification +**"but still ask the user"**. + +- Disconnect and Remove Connection keep the Close or Keep open choice, the dirty Document View + discard prompt, and the `documentDB.connections.openTabsOnDisconnect` default (0004, 0007). +- A view that was kept open becomes **permanently disabled**. It keeps its contents for copying + and offers **Close** only. It is never rebound, retried or revived: not after Reconnect, not + after a sign-in, not for the same identity. After reconnecting, open new views from the tree. + This replaces Retry on views retained across a Disconnect (0016, 0017) and the Reconnect that + retries the Dashboard. +- The state is a boolean "disabled", not a comparison of identity, fingerprint or generation. + A view cannot return from it, so the retirement map and the Reconnect resuming the Dashboard + are not needed. + +**Rejected:** B1, always closing the views and removing Keep open and its setting. The analysis +recommended B1 because Keep open is the one feature that forces permanent retired-view state, but +the operator chose to keep the user's ability to copy results out after Disconnect. + +**Not decided here:** whether the in-view recovery overlay for failures on a live connection +(sign-in required, unreachable; **Retry** in 0016, 0017, 0023, 0024) stays. That is proposal D of +the analysis. Those decisions remain in force until the operator decides it. + +## 0028. Surfaces hold only the cluster ID; remove the fingerprint, generation and binding carry-through + +**Proposed** on 2026-11-29. Not yet accepted by the operator. + +Once 0026 and 0027 hold, a live surface can no longer be bound to an identity that changed under +it. The analysis proposes to remove what only existed to detect that: the connection fingerprint +and its HMAC key (0021), the generation counter, `ConnectionBinding`, `resolveBoundClient`, +`connectionBindingRetirement`, `runBoundNamespaceCommand`, `boundViewOperations` and the Dashboard +delete epoch (0019). Views would carry a `clusterId`. Staleness would use one per-cluster epoch, +for startup races only, and a comparison of the failed client instance with the current one. + +This would modify 0002 and 0013 and supersede 0019 and 0021. It dissolves C01 to C03 of the +[PR 1136 Copilot review](./iterations/02-pr1136-copilot-review.md). It is **Proposed**, not +Accepted, because the analysis did not audit the Shell, Playground and router footprint line by +line, and the operator has not confirmed proposals C and E. Next step: that audit, then a +decision. + +## 0029. Land the simplification inside #1136 before 1.2.0 + +**Accepted** by the operator on 2026-11-29: "Before 1.2.0, as part of PR #1136". + +0026 and 0027 change behavior that would become a compatibility obligation once 1.2.0 ships (the +edit-while-connected flow, retained views that revive, the documented "Keep your place" +behavior). The work lands on `feature/connection-lifecycle` under 0006, in policy-first order: +refuse edits while connected, make retained views permanently disabled, then delete the +machinery that stops being reachable. No additional rationale was supplied. + +## 0030. Offer Disconnect and update, performing the ordinary Disconnect flow before editing + +**Accepted** by the operator on 2026-11-30: + +> I reconsidered 5A, and approve the option A2 (the user recieving the otiin to disconect and having that happen for them). + +This changes 0026's **A1 refusal** to **A2 assistance**. Update Credentials and Update Connection +String still require a disconnected connection, but the extension offers to perform Disconnect +instead of requiring the user to find and invoke it separately. Reuse the ordinary Disconnect +flow, including its Close/Keep choice, task-conflict guard and dirty-document confirmation. +Do not begin editing if that flow is cancelled, blocked or fails. A connection already safely +disconnected does not need a redundant Disconnect. + +The operator's stated distinction is that the user receives the option and has Disconnect +performed for them. No additional rationale is inferred. The pinned-account restriction on +Sign in again and 0029's pre-1.2.0 timing are unchanged. + +**Implementation implications, not implementation completed:** the deeper +[analysis, section 5A](./iterations/03-complexity-reduction-analysis.md#a-identity-changes-only-while-disconnected-s7-s9) +finds that the current Disconnect command can return without teardown when the client is absent +or held. A2 must also account for pending startup and surviving surfaces/workers, and distinguish +successful teardown from those early returns. Disconnected editing still needs exclusion against +concurrent reconnect/storage writes and explicit partial-save failure reporting. Reusing teardown +does not mean deleting every latch or checking only whether a cached client exists. + +**Scope clarification:** the previous analysis overstated what A/B policy choices establish. +Neither 0026/0027 nor this approval authorizes a pending write, AI request or Playground handoff +to adopt a replacement identity. Closing or freezing a view does not cancel already-running host +work automatically. The "accepted risks" wording in 0026 was not a separate operator approval of +unguarded handoffs. Broad deletion in 0028 remains unaccepted; the revised analysis recommends +keeping internal client generation, startup guards, source cancellation and worker identity pins. + +## 0031. Choose package P: A2, B2, C-balanced, D2 and guarded handoffs + +**Accepted** by the operator on 2026-11-30: + +> please record the proposals as choosen options. + +This selects **package P** in +[iteration 3, section 6](./iterations/03-complexity-reduction-analysis.md#6-packages-regenerated-2026-11-30). +It confirms B2 and chooses the recommended C-balanced and D2 proposals. This is a decision about +the target behavior and architecture; **no implementation is implied**. + +- **A2 (0030):** Offer Disconnect and update, and perform the ordinary Disconnect flow before + editing. Do not edit if Disconnect is cancelled, blocked or fails. +- **B2 (0027, reaffirmed):** Preserve the Close/Keep choice. Kept tabs retain copyable contents + but enter a permanent read-only state on explicit Disconnect/Remove; they never reconnect, + retry or resume. New operations use newly opened views. Ensure old Dashboard actions cannot + route to a newer live Dashboard. +- **C-balanced:** Keep the physical-client generation inside `ClustersClient` for attributing + late failures to the client that produced them; same-identity replacement remains supported. + Keep startup cancellation/epochs and a one-way host-side surface lifetime. Propagate that + lifetime/cancellation across async handoffs and check immediately before external side effects. + Do not add a second, general-purpose ID/lease framework alongside equivalent guards. Do not + remove the fingerprint or identity checks until their remaining callers are covered by an + equivalent host-side lifetime contract. Worker Entra pins remain. +- **D2:** Remove the separate Retry-to-unlock workflow for recoverable webview failures. Surface + translated, actionable operation errors; after the user repairs the cause, they explicitly + run the operation again. Do not automatically replay writes or prompt from background polling. + B2's permanent read-only notice still applies after an explicit Disconnect/Remove. Retain + authentication holds, cancellation, background restraint and stale-result protection. +- **Guarded handoffs:** Do not allow a wizard, schema/model request, command or Playground opened + from an old view to silently adopt a later connection. Preserve same-identity client recovery, + task-conflict checks, partial-save reporting and stale Dashboard-delete cancellation. + +**Rejected:** the broader 0028 proposal to reduce surfaces to `clusterId` alone and remove +fingerprint, generation and binding checks wholesale. A physical client generation and a logical +connection lifetime answer different questions; collapsing them would either invalidate ordinary +same-identity recovery or fail to stop async work across Disconnect. The chosen design keeps the +small internal generation and narrows its spread rather than adding a second universal generation +parameter to every caller. + +**Rationale:** package P keeps the user-valued ability to copy from retained tabs while dropping +their harder-to-maintain promise of revival. It removes an extra Retry/unlock step after the +connection has already been repaired, without mistaking UI simplification for cancellation of +work already running on the host. A2 improves the edit flow without restoring live credential +migration. + +**Implementation remains pending** on `feature/connection-lifecycle`, before 1.2.0 as required +by 0029. Follow the ordered work and required verification scenarios in iteration 3, section 6. + +## 0032. Keep tabs live through same-account recovery; X on a frozen tab dismisses only its notice + +**Accepted** on 2026-11-30 as a clarification of 0031. The operator selected: + +> Keep it live after same-account recovery, including tree sign-in; freeze only when the old session is explicitly ended (recommended). + +A token expiry, sleep/wake, socket drop, physical client replacement or sign-in requirement is +not Disconnect. If recovery is silent, leave the tab alone. If an action failed, keep the query, +results or draft and explain the next action. After repair with the pinned account the same tab +can be used again; there is no separate unlock or automatic replay of the failed operation. + +Explicit Disconnect, Remove, or the successful Disconnect step of **Disconnect and update** ends +the old session. A tab the user keeps is permanently read-only. Its notice explains that the tab +is finished. **X dismisses the notice**, exposing already-loaded contents for copying; **Close +view closes the tab**. Neither action reconnects it. A new connection opens fresh live views, +even for the same account. Freezing on every drop, or on same-account tree sign-in, was not chosen: +it would force users to reopen their work in precisely the recovery scenario they want to preserve. + +**Operator clarification after manual testing (2026-11-30):** **Close view** in the disconnected +notice closes Dashboard, Collection View and a clean Document View directly, without another modal. +Only a dirty Document View retains the unsaved-changes warning. This replaces the earlier blanket +close-confirmation implementation; it does not change X dismissal, permanent read-only state or +Disconnect's own Close/Keep/Cancel and dirty-document checks. + +## 0033. Approve the PR1149 review dispositions with explicit complexity tradeoffs + +**Accepted** by the operator on 2026-12-01: + +> record the recommended solutions as approved, except: + +The source is the [PR #1149 Copilot evaluation](./iterations/03-pr1149-copilot-review.md). +The operator approved its recommended options except for C01, C06, C08 and C10. This records +the choices and their stated reasoning; it does not claim that the fixes have been implemented. + +| Item | Approved choice | +| ---- | --------------------------------------------------------------------------------------------- | +| C01 | Option 3: retain the existing latch/idle eligibility check; accept the edge case | +| C02 | Option 1: retire the prior lifetime at the common edit boundary, including idle edits | +| C03 | Option 1: reject closed Shell origins, including callbacks captured before closure | +| C04 | Option 1: carry the Dashboard binding/lifetime through session creation and panel publication | +| C05 | Option 1: defer the full binding guard until after bound-client resolution | +| C06 | Option 2 direction: clear the removed connection's Playground selection and reuse Connect | +| C07 | Option 1: make a rejected Entra account recoverable through explicit same-account sign-in | +| C08 | Won't fix: retain the overlay and database guards without adding local query read-only gates | +| C09 | Option 1: settle an invalidated current collections read as interrupted | +| C10 | Option 2: stop failed index-build polling; require explicit manual Refresh to resume | +| C11 | Option 1: use the localized title and detail in the existing notification contract | +| C12 | Option 1: no standalone retained-state refactor | + +### Accepted exceptions and rejected alternatives + +- **C01:** the operator chose option 3 because "this is an edge case, and option 1 adds a lot of + complexity." Do not introduce the proposed teardown-completion record. A concurrent edit can + still observe the disconnected latch before another teardown's driver close settles, including + the reviewed close-failure case. This is an accepted limitation, not a fixed race. The command + initiating Disconnect still awaits its own teardown and retains its existing cancellation, + task-conflict and error handling. This qualifies 0030's absolute teardown-success wording; it + does not remove C02's separately approved lifetime retirement. +- **C06:** the operator preferred the simpler option 2 direction because the existing **Connect** + affordance already provides recovery. Clear the selected binding for a removed connection and + preserve the Playground file text. Do not add option 1's shared reason-aware presentation layer. + Ordinary Disconnect still retains its selection; removal uses the existing unbound Connect path. +- **C08:** the operator considers the existing overlay sufficient to show that the connection is + disabled, and local editing after dismissal is the user's responsibility. Do not add the + proposed query-editor read-only controls or treat the previous copy-only local-editing + requirement as a blocker. This narrowly qualifies 0031/0032: retained views still cannot regain + database access, while local Collection View query editing is accepted. Document View's + existing read-only/dirty protection and all host lifetime/identity guards remain unchanged. +- **C10:** the operator chose stopping the poll, not option 1's new foreground/background callback + policy. Once stopped after a recoverable failure, the table must not resume polling merely + because connectivity or sign-in has recovered. The user must explicitly refresh the table. + A successful manual refresh may resume normal build polling; a failed one leaves it paused. +- **C12:** the recommended no-standalone-refactor disposition is approved. The optional state + redesign is not another required fix in this round. + +The other seven recommended options are accepted as evaluated in the linked review; no additional +operator rationale is inferred. There are nine code-fix items and three no-code dispositions. +The [approved execution handoff](./iterations/03-pr1149-copilot-review.md#approved-execution-handoff) +records the separate branch/PR, model routing, advisor authority, per-fix commit/push/thread-reply +requirements and final verification iteration. + +## 0034. Keep manual Refresh as the only way to resume paused index polling after Create + +**Accepted** by the operator on 2026-12-01: keep Decision 0033's manual-Refresh-only rule and +document the workaround for [pre-review finding N01](./iterations/03-pr1149-copilot-review.md#n01-creating-an-index-while-polling-is-paused). +If polling was paused before a successful Create, its row can still say **Creating**. Select +**Refresh** to get the current status and resume polling if a build is still active. + +The operator did not select either resuming polling on successful Create or adding a +localized pause indicator. No runtime change or exception to Decision 0033 was approved. + +## 0035. Keep Dashboard Connection Diagnostics available in disconnected views + +**Accepted** by the operator on 2026-12-02 while merging `main` into the feature branch, which brought +the Dashboard **Connection Diagnostics** action from [#1150](https://github.com/microsoft/vscode-documentdb/pull/1150). +The merge initially guarded it like **Copy Connection String** and **Data Migration**, so a +retained or identity-changed Dashboard returned an unavailable response instead of diagnosing. +The operator rejected that: "connection diagnostics should not be blocked." + +Diagnosis is read-only and is most useful when the connection is unavailable. The Dashboard +procedure and button are therefore not bound to the view's connection lifetime; they run the tree's +existing diagnose command against the current saved node. If the connection was removed, the +missing-node error applies. This does not restore database access to a retained view, and the other +Dashboard tree-command actions keep their guards. + +## 0036. Simplify obsolete actions and ended bindings without cutting useful features + +**Accepted direction, not implemented by this decision.** In the [#1136 scope review](./iterations/04-pr1136-scope-and-test-review.md), the operator agreed to proposals 2 and 3 and to trimming duplicate tests. Their criterion was to keep beneficial features that are cheap to maintain. + +- Use one actionable explanation for an obsolete explicit recovery action. Keep real repair instructions specific, and keep cancellation and obsolete background work quiet. +- An old binding need only say that its session ended, not preserve each historical reason. Keep the current connection's precise state, cancellation before side effects, dirty-data protection, and recovery after failed removal. No particular replacement data structure was approved. +- Consolidate repeated command-state and dismissal matrices. Retain tests that prove different safety boundaries: wrong identity, command replay, stale work or lost drafts. +- Keep Azure Discovery/ARM in #1136: the operator considers it a good solution already in place. Reject #4 (always closing views) as too aggressive; preserve Close/Keep/Cancel. Reject #5: Show Connection Stats stays because it is useful for debugging. + +**Open, not a reversal of 0022:** the operator asked to evaluate extracting the isolated Shell as future work and exposing it in Connection Diagnostics, either instead of or alongside the tree entry. They see diagnostic value but substantial cost for an edge case. No removal, additional entry point or deletion of isolation tests is approved. + +## 0037. Measure a later successful read in the same Collection View tab + +The operator asked for fidelity without excessive tracking and approved recording this choice. +Reuse `collectionSessionId` on the existing first-page Find/Refresh RPC. It identifies the +original tab across physical client replacement, whereas `connectionCorrelationId` identifies +the physical client. A successful read in a fresh tab, a token returned, or a repair click is +not evidence that the affected tab is usable again. A new `connection.recovered` event, a +cluster-wide tracking ID and per-operation tracing are unnecessary for this question. + +Report [within-version counts](./telemetry.md#did-an-affected-collection-view-tab-complete-another-database-read) +with an explicit unknown group. This measures subsequent use, not the cause of recovery, +worker or write recovery, or a release-wide improvement. Keep 0020's cross-release deferral. + +## 0038. Confirm Close all for the exact editable Document Views it will close + +For [PR #1136 C06](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4777769769), +the operator selected the conservative fix: Disconnect and Remove Connection must confirm +discarding changes before closing editable Document Views, even if the host last heard that +they were clean. Only editable views covered by that confirmation can be closed. This changes +the teardown confirmation in 0032, not the dirty-only warning on a retained tab's **Close view**. 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 new file mode 100644 index 000000000..31eea0493 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -0,0 +1,1138 @@ +--- +feature: connection-lifecycle +kind: plan +status: historical +created: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/auth/connectionAuthIdentity.ts + - src/documentdb/auth/tokenExpiry.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/CredentialCache.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts + - src/documentdb/playground/playgroundWorker.ts + - src/documentdb/playground/workerTypes.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/commands/updateCredentials/updateCredentials.ts + - src/commands/removeConnection/removeConnection.ts + - src/services/taskService/resourceUsageHelper.ts + - src/webviews/documentdb/collectionView/collectionViewRouter.ts + - src/webviews/documentdb/documentView/documentsViewRouter.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Iteration 1, dev plan: how to execute the connection lifecycle work + +> This is the execution record for the approved [implementation plan](./01-implementation-plan.md). +> Read that plan for the original proposals and dependencies. Read the **Progress** blocks here for +> what actually landed, where it differed and what the operator verified. The +> [original execution recipes](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md) +> remain available at the reviewed revision. Work-item numbers (WI-n), PR numbers and OT-n acceptance tests are the same as in +> the approved plan. Decisions are in [../decisions.md](../decisions.md), evidence in +> [../research-findings.md](../research-findings.md). Neither is repeated here. + +Written at `4fe5a72c9` (branch `tnaum-ms/issue1102`). Line numbers will drift; function names are the +stable pointers. + +## 0. How to use this document + +### Authority and deviation + +Decisions 0001–0008 bound the original plan. Implementation details and the provisional answers +below were guidance, not approval to change intent. Conflicts went to the named checkpoint and, +for design changes, the operator; deviations and rejected alternatives are recorded against each WI. + +### Progress recording + +Each work item ends with a **Progress** block. When you commit a step, add a line there that names the +commit SHA, what landed, and anything that differed from the plan. Each checkpoint (§5) also writes its +verdict there. At the hand-over, add an `# Outcome` chapter to the end of this file: what was verified, +and just as plainly, what was not. + +### Operator tests: announce them clearly + +These are operator checks, not unit tests. Each needed the candidate, setup, expected result, +sanitized evidence and elapsed time. Only work depending on the check had to wait. + +| OP | When | Test | +| ---- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 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 | 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: first action a write after at least two hours idle, continuous use across expiry, and sleep/wake plus Shell and Playground after expiry (PR F step 3). | + +### Per-PR workflow + +The [implementation plan's delivery section](./01-implementation-plan.md#delivery) owns the stack +and verification rules. Sub-PRs could open before their predecessors merged; operator gates and +approvals still applied. Each PR reported its WIs, issues, provisional answers and verification level. + +### Issues: link them, and comment on partial fixes + +Every PR names the issues it may resolve, using the table below, and says for each one whether it +**resolves** it or is a **partial fix**. + +- **Closing keywords only in PR F.** GitHub closes an issue through `Fixes #n` only when the PR merges into + the default branch. Sub-PRs merge into `feature/connection-lifecycle`, so they write + `Resolves #n (closes with PR F)` or `Part of #n`. PR F carries `Fixes #n` for every issue that the + iteration resolves in full. +- **Partial fix → a comment on the issue.** When a PR merges with only part of an issue done, post a + dedicated comment on that issue (`gh issue comment --body-file `). It contains: + - the PR link and the WIs it implemented; + - what now works, in user terms; + - what is still open, and where it is planned (a later PR, or a follow-up issue); + - decisions taken on the way that change the issue's scope, linked to `decisions.md`; + - the tests or operator tests that cover it. + + Keep it factual and short. Never include tokens, account names, cluster names or connection strings. + Record the comment's link in the WI's Progress block. + +- **Work moved to a follow-up issue** (#1105, #1106, #1119): when a PR hands work over, comment on the + follow-up in the same way, so it can be planned from that comment alone. + +| Issue | Title (short) | PRs | Expected | +| ----- | ------------------------------------------------- | ------------- | -------------------------------------------------------------- | +| #1102 | Keep connections usable across expiry and idle | 1, 3, 4, 5, 7 | Partial in each sub-PR; resolved by PR F | +| #990 | Upgrade azureauth to v6 | 2 | Resolved by PR 2 (closes with PR F) | +| #626 | Upgrade azext-utils v3 → v4 | 2 | Check after CP-W3: likely superseded by the utils v5 upgrade | +| #1059 | Disconnect action that ends live sessions | 6 | Resolved by PR 6 (closes with PR F) | +| #566 | Unified disconnect/remove experience | 6 | Resolved or partial; decide against the issue text in PR 6 | +| #1091 | Dashboard health check: pause, back off, stop | 6 (WI-8) | Partial unless WI-8 also does the visibility pause and backoff | +| #1105 | Follow-up: Kubernetes tunnels, network resilience | — | Not resolved; comment when a PR moves work there | +| #1106 | Follow-up: indicate possibly out-of-date results | — | Not resolved; comment when a PR moves work there | +| #1119 | Follow-up: handle Microsoft sign-out promptly | — | Not in 1.2.0 | + +### Skills to load per work item + +| WI | Load before starting | +| ----- | -------------------------------------------------------------------------------------------- | +| WI-1 | error-translation, telemetry-instrumentation | +| WI-2 | error-translation | +| WI-3 | flagging-fresh-dependencies (lockfile audit), error-translation | +| WI-4 | tree-cluster-architecture, telemetry-instrumentation | +| WI-5 | tree-cluster-architecture, error-translation, telemetry-instrumentation | +| WI-6 | webview-trpc-messaging, react-webview-architecture, fluentui, detecting-accessibility-issues | +| WI-7 | tree-cluster-architecture, webview-trpc-messaging, telemetry-instrumentation | +| WI-8 | webview-trpc-messaging, react-webview-architecture | +| WI-9 | telemetry-instrumentation | +| WI-10 | writing-release-notes, documentation-screenshots, previewing-docs-site, skill-creator | + +--- + +## 1. Answers to the open questions + +The operator was not available on 2026-11-19 at first. They answered A2 to A6 later the same day; A1 is +still **provisional** under rule 4 above. + +| # | Question | Answer | Status | Where it lands | +| --- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------- | +| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | Provisional | WI-1, WI-2, WI-5, WI-6 | +| A2 | Plan Q2: Disconnect choice, default and memory | A **VS Code modal**, which has no pre-selected button and **remembers nothing**. A setting lets users choose a default: `ask` (the default) shows the modal; `closeAll` or `keepOpenDisabled` skips it. The unsaved-edits confirmation still appears when closing. See WI-7 step 3. | **Operator, 2026-11-19** (decision 0007) | WI-7 | +| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **No** (reverses the #1059 proposal). Disconnect keeps the `CredentialCache` entry **and** `lastVerifiedIdentity`, so Connect and a tab's Reconnect work without the tree and without retyping a discovery password. Only Remove Connection drops them; an identity-changing credential update replaces them. Keep `dropCredentials` as a teardown option. | **Operator, 2026-11-19** (decision 0011) | WI-7 | +| A4 | #990: which azext versions? | **As high as viable without breaking our workflows**, using the Azure Resources extension (same team as azureauth, heavily used) as the reference. Ladder and findings are in WI-3 step 1: target L2, fall back to L1, then L0. | **Operator policy, 2026-11-19** (decision 0008) | WI-3 (CP-W3) | +| A5 | How does Disconnect see an in-flight Export? | **Reuse the existing mechanism.** Delete Collection, Delete Database and Remove Connection already guard through `checkCanProceedAndInformUser` (`TaskService` resource tracking). Export **and Import** are the gap: neither is a task and neither registers anything, so even Delete Collection does not see a running export or import today. Close it with a small **resource lease** that feeds the same check. Every existing guard then sees them too, and the export and import logic is not touched. Copy/paste and copy-indexes are already tasks that register both endpoints (F-9). | Operator pointed at the existing check; lease is the recommendation; operator added Import (2026-11-19) | WI-7 | +| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | **Operator, 2026-11-19** | — | + +--- + +## 2. Facts established while writing this plan + +These were verified at `4fe5a72c9` with mongodb driver 7.2.0. They shape the steps below. If a dependency +upgrade changes any of them, stop and re-plan the affected WI. + +- **F-1. One failed OIDC callback breaks that `MongoClient`'s Entra authentication for good.** + - Where: `node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js`, `withLock`. It runs + `await lock` _before_ it reassigns `lock`, so after one rejection every later callback call throws the + same rejection again. + - This is the "same workflow reused the rejection" result of the earlier probe. + - Consequence: the only way to recover after the callback throws is a **new `MongoClient`**, that is, a + new generation. It applies to every throw, including transient Entra errors. +- **F-2. The driver ignores `expiresInSeconds` in the automated workflow.** + - `token_cache.js` stores the value, but `AutomatedCallbackWorkflow.execute` never reads it. + - `CallbackWorkflow.speculativeAuth` sends the cached token on **every new socket**. + - Code 18 drops the cached token and calls the callback again. A transport failure does not. + - Code 391 goes through `reauthenticate`. + - So no `OIDCResponse` value alone can stop an expired token from being offered. +- **F-3. `getSessionFromVSCode` reads the auth provider ID that is configured _at call time_.** + - Where: azureauth 4.1.1 `getSessionFromVSCode.js` calls `getConfiguredAuthProviderId()`. + - If the user changes their sovereign-cloud setting after connecting, a callback would ask a different + provider. That breaks the identity pin. + - The deep import path `@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode` does not exist + in v6; it moved to `dist/esm/src/utils/`. + - `vscode.authentication.getSession` supports `account` (engine `^1.109.0`). +- **F-4. Cluster ID equality differs by store.** + - `CredentialCache` and the Entra failure registry use case-insensitive maps. + - `ClustersClient._clients`, `ClusterSession._sessions` and `SchemaStore` (prefix `${clusterId}::`) match + exactly. + - Kubernetes IDs keep the context's case (`kubernetes_${source}_${context}__…`), so `Prod` and `prod` + already collide in `CredentialCache` today. + - **Out of scope for this iteration** (decision 0009, #1105). Every store keeps its current matching; + this iteration adds no case handling. +- **F-5. There is no per-cluster registry of open webview panels.** + - Only the Cluster Dashboard keeps its own `openPanels` map (`clusterDashboardController.ts`). + - Collection View and Document View open through `openAppWebview`, whose handle exposes `onDisposed`. +- **F-6. Collection View sessions.** + - `ClusterSession` sessions are keyed by a random session ID and **hold** a `ClustersClient`. + - `openCollectionView.ts` calls `closeSession` when the panel is disposed. + - Paging uses **offset queries**: `skip = querySkip + (page - 1) * pageSize`. No cursor is held between + pages. +- **F-7. The Cluster Dashboard health poll runs in the webview, not the host.** + - Where: `ClusterDashboard.tsx`, the interval effect around `refreshIntervalMs`. + - The host procedure `measureRtt` resolves the client for every tick, with trigger `clusterDashboardPoll`. +- **F-8. Worker IPC loses error types.** + - `tokenError` carries only a message, plus `errorName` for one value: destination rejection. + - `initResult` and `evalError` carry strings only. + - The playground rebuilds its init message from `CredentialCache` on **every run** + (`PlaygroundEvaluator.evaluate` → `buildInitMessage`), even when the worker is warm. +- **F-9. Task coverage.** + - Copy/paste and copy-indexes register both endpoints through `getUsedResources()`. + - **Export and Import are not tasks.** `exportDocuments.ts` and `importDocuments.ts` call `getClient` + directly and register nothing. Import calls `getClient` again for every insert batch, so a latch + during an import leaves a partial import, and running it again inserts duplicates. +- **F-10. Remove Connection does not close the client, shells, the playground or webviews.** It deletes + storage, `CredentialCache` and `SchemaStore` data only. +- **F-11. Credential updates.** + - Update Credentials saves first, then calls `deleteClient`, then shuts down the playground. It only warns + about shells (the D12 modal). + - Update Connection String deletes the client only when recovering a rejected destination. +- **F-12. Errors lose their identity at the tRPC boundary.** + - Errors arrive rebuilt as `{ code, name, message, stack, cause }`. + - Webview RPC telemetry records the tRPC code as `error` (`src/webviews/_integration/trpc.ts`). + - So a disconnected reason must reach a webview as **structured data**, never as an error that the + webview has to recognize. +- **F-13. About 35 other `getClient` call sites are not open surfaces, but some of them are background + work.** + - One-shot user commands: create/delete database and collection, import, index commands, LLM commands, + paste. They act on the current client, so WI-6 does not bind them. + - **Background callers:** playground completions (`CollectionNameCache.ts`, an explicit background + lookup), tree count badges and prefetches. + - Today **every** startup is interactive: `initializeClient` hardcodes `{ interactive: true }`. A + background caller can therefore reconnect, or even prompt, after an eviction or a Disconnect. + - So `getClient` must **never prompt**, and the latch must be enforced **inside `getClient`** (C-6), + not per caller. +- **F-15. A stopped worker respawns by itself.** + - `ShellSessionManager.evaluate` re-initializes a dead or stopped worker from the current + `CredentialCache`. `executePlaygroundCode.ts` recreates the evaluator in the same way. + - "Stop the worker" alone therefore keeps neither a shell nor a playground disconnected. Without a + latch, it silently adopts new credentials on the next command. +- **F-16. The host rebuilds worker errors as generic errors.** + - `WorkerSessionManager` turns `initResult` and `evalError` into a plain `Error`. Only + `EntraDestinationRejectedError` keeps its name. + - New IPC fields are lost unless this layer is changed too. +- **F-17. The native authentication database follows the driver's rules.** + - With no explicit `authSource`, the driver uses the URI's database path (`connection_string.js`, around + line 307). Only when there is none does it use `admin`. + - The same user on `/sales` and on `/admin` is therefore two different principals. + - The fingerprint hashes the stored connection string, which carries the database path and any + `authSource`, so this needs no special handling (WI-4 step 1). +- **F-18. Cluster ID matching is inconsistent across stores.** + - `CredentialCache.deleteCredentials` lowercases its key (`CaseInsensitiveMap`), so deleting Kubernetes + context `prod` also deletes `Prod`. + - Task conflict matching (`hasResourceConflict` in `taskServiceResourceTracking.ts`) compares IDs + exactly, so it misses Azure case aliases. + - Both problems exist today. They are **out of scope** for this iteration (decision 0009, #1105). +- **F-19. Credential saves can fail without the command knowing.** The Update Credentials `ExecuteStep` + catches save failures and returns normally, so the command cannot tell whether the save happened. +- **F-20. Only the tree fills `CredentialCache`, and the tree empties it on any connect failure.** + - `ClustersClient.initializeClient` starts only from a `CredentialCache` entry. Without one it throws + "No credentials found for id {clusterId}" and sets `startup.credentialsMissing`. + - Only the tree items' provider-specific `authenticateAndConnect` methods (and Update Credentials, + which reloads the entry from storage) fill the cache. + - Every `authenticateAndConnect` failure path calls `deleteClient` **and** + `CredentialCache.deleteCredentials`, whatever the cause: `DocumentDBClusterItem`, the Azure + Resources vCore and RU items, and the Atlas, Kubernetes, VM, vCore and RU discovery items. + - So a tree expand during a network outage leaves open surfaces with nothing to reconnect from. +- **F-21. Storage saves are not atomic.** `StorageService.push` writes the secrets to `SecretStorage` + first, then the metadata to `globalState`. A failure after the secret write leaves the new secrets beside + the old metadata, so "the save failed" does not mean "nothing changed". +- **F-22. `MongoClient.close(force)` does not cancel anything.** In the installed driver the `force` + argument is "currently an unused flag that has no effect". An operation already sent may still + complete, and a write the server accepted cannot be undone. +- **F-23. Handoffs that drop the binding.** + - Playground evaluators are shared per `clusterId` and deleted on shutdown + (`executePlaygroundCode.ts`). The per-document connection lives in `PlaygroundService` + (`getConnection(uri)`), and it has no fingerprint today. + - Collection View starts import and export by passing a tree node to a command + (`collectionViewRouter.ts`), so the work runs under whatever credentials the cluster has when it starts. + - Folder deletion (`deleteFolder/ExecuteStep.ts`) deletes descendant connections straight from storage. + It never touches their clients, credentials, shells or tabs. +- **F-24. The dashboard sampler turns errors into strings.** `getClusterHealth.ts` catches every command + separately and records `name: message` in `errors`. An authentication failure during a ping therefore + reaches the router as a partial sample, not as an error. +- **F-14. VS Code has no API to collapse one tree node.** + - The repository uses `reveal(..., { expand: false })`, which does not collapse a node. + - Collapsing through a changed `TreeItem.id` would conflict with the `treeId`/`clusterId` rules. + +--- + +## 3. Tensions between the approved plan and the code + +| # | Tension | Decided at | Recommendation | +| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| T-1 | WI-1 required that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires. Decision 0002 says a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. | CP-0 | **Resolved by the operator on 2026-11-19 (decision 0010).** (1) No proactive rotation and no local expiry checks: "the server will tell us, then we can act". An expired token is rejected by the server; the driver then calls the callback, which renews silently. If the server closes the socket instead, the classifier acts on that (WI-5). (2) Replacing a client for the same identity is **transparent**: no re-run and no "out of date" notice, including on return from the disconnected state. Stale-data indication is #1106. | +| T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | +| T-3 | WI-7 asked for provider-specific cluster ID equality (Azure case aliases match; Kubernetes contexts such as `Prod` and `prod` stay distinct). Today's stores disagree on this (F-4, F-18). | — | **Withdrawn 2026-11-19:** moved out of this iteration (decision 0009, #1105). Each store keeps its current matching. | +| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation replaces a generation. Background callers pass `background: true` and just fail (C-6, WI-8). No backoff: with no background replacement there is no loop to guard against (decision 0012). | +| T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | + +--- + +## 3a. Out of scope for this iteration + +Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) on 2026-11-19 (decision +0009), to be scheduled after 1.2.0: + +- re-creating Kubernetes port-forward tunnels outside the tree (per-operation resolution, recovery); +- tunnel ownership on Disconnect and Remove, and running the teardown when a kubeconfig source is removed; +- provider-specific cluster ID matching (the withdrawn T-3; F-4, F-18); +- Kubernetes API credential expiry (AKS exec plugin); +- a wider network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. + +Moved to [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (decision 0010): any +"results may be out of date" indication. That covers the return from the disconnected state, long idle, +and writes made from another view or another client. + +Prompt handling of Microsoft account sign-out is deferred to +[#1119](https://github.com/microsoft/vscode-documentdb/issues/1119), after 1.2.0. Under decisions +0001 and 0012, signing out of VS Code does not close an established database client. The client +can keep authenticating with a cached token while the server accepts it. When the driver requests +a new token and the pinned session is gone, recovery remains explicit through **Sign in again**. + +Generic idle and network-drop recovery **stays in scope**: closed-client and transient classification, +the cancelled-reuse fix, closed-client replacement and OT-4. It is #1102's "recover on the next +operation without a restart". The no-regression rules in WI-5 and WI-6 keep tunneled connections +working as they do today. + +--- + +## 4. Contracts that cross PRs + +These contracts define how PRs 1–3 share the verified account, provider and tenant while the +implementation PRs are stacked. The field names are illustrative; the semantics are binding unless +a checkpoint changes them. + +- **C-1. Verified identity.** + - WI-1 produces it on the first successful Entra acquisition: + `{ kind: 'entra', providerId, accountId, accountLabel, tenantId? }`. + - `providerId` is the provider that was **actually used**, never re-read later (F-3). + - It is returned on `AuthHandlerResponse` as an optional field. + - Native, managed identity and no-auth handlers return nothing; WI-4 derives their identity from the + credentials used. + - WI-2 builds the same shape at worker spawn. + - Never logged, never sent to telemetry, never persisted. +- **C-2. Typed errors: four classes in total.** + - `EntraSignInRequiredError`, reason `noSession | providerChanged`. + - `EntraIdentityMismatchError`: a different account came back. + - `TokenCallbackError`: wraps **any other** error thrown from an OIDC callback, for every auth method + (Entra and managed identity), with a bounded `authMethod`. The original is kept as `cause` and is + never rendered raw. + - `ConnectionUnavailableError { reason }`: the one error for a client the caller cannot use (the latch, + an identity change, missing credentials). `reason` is the C-5 enum. + - Messages are localized. Classification uses the `name` (walking `cause`), never the message. Existing + name checks that walk `cause`, such as destination rejection, keep working. + - The first three are "callback threw" for F-1. + - Keep the existing `AuthInputUnavailableError` for the non-interactive startup path (diagnostics). + Either make the new errors related to it or map between them explicitly, so the Entra failure registry + still skips silent misses (comment in `MicrosoftEntraIDAuthHandler.configureAuth`). +- **C-3. Token lookup observation.** + - Every **completed** post-startup token lookup notifies an optional host-only observer, whether it + succeeded or failed: `{ outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed', lifetimeSeconds? }`. + - `lifetimeSeconds` is the JWT `exp` minus `iat`, and is omitted when the token is opaque. + - Nothing about a token is retained between lookups. The observer never receives the token, a hash of it + or any other claim. + - WI-9 uses it for `connection.tokenRenewal`. +- **C-4. Binding.** + - Its form is `{ clusterId, fingerprint, generation }`. + - **`fingerprint`** is an opaque hash of the stored connection string without its password, plus the + principal (WI-4 step 1). It never contains a password and is never sent to telemetry. + - **`generation`** is a per-cluster number that only ever increases. It is **never reset**, not even + after teardown. A binding from before Disconnect therefore never matches a client created after + Reconnect. +- **C-5. Unavailable reasons, derived on demand.** + - There is **no stored connection state** and no state machine. A surface learns where it stands when it + resolves its binding (WI-6): it gets a client, or a `ConnectionUnavailableError { reason }`. A router + returns that to the webview as structured data (F-12). + - A surface whose fingerprint differs from the client the cluster would use now is unavailable with + `identityChanged` or `credentialsChanged`, **even while the tree works**. This is what lets the tree and + 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 `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). +- **C-6. `getClient` rules.** + - **It never prompts.** `getClient` is always silent. Only the tree's first connect + (`authenticateAndConnect`, through `ClustersClient.connectInteractive`) and the Sign in again command + may prompt (A1). Once an identity is verified (`lastVerifiedIdentity`, WI-4), a reconnect is silent and + pinned to it. + - **Background callers** (the dashboard poll, tree count badges, playground completions) pass + `background: true`. They never replace a client; they just fail (T-4). + - **Latch:** while a cluster is disconnected (Disconnect, Remove, an identity-changing credentials + update), `getClient` throws `ConnectionUnavailableError` with the latch's reason, for every caller. + Only the explicit Connect and Reconnect actions clear the latch, plus one internal case: an + identity-changing credential update whose save reached nothing clears the latch it set (WI-7 step 5). + New tasks and resource leases are refused while the latch is set. + A `credentialsRejected` latch blocks startup until the matching explicit recovery clears it + with an unchanged epoch (decision 0015). That recovery cannot clear a teardown latch. + - **One epoch:** a per-cluster counter that `invalidate` increases **synchronously** on every latch, + unlatch, eviction and teardown. A startup publishes only if the epoch is unchanged. Every recovery + command (Retry, Sign in again, Reconnect) captures the epoch **before** its first `await`, and applies + its result only if it is unchanged. With the per-client generation, it is the only staleness guard. + +--- + +## 5. Advisor checkpoints + +Each checkpoint is a short written verdict recorded in the Progress block of the WI named. Until the +verdict exists, do not start the work it gates. The fingerprint table (formerly CP-1) and the PR 5 split +(formerly CP-3) are ordinary PR review (decision 0012). + +| CP | When | Question | Evidence required | +| ----- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| CP-0 | WI-1, after step 1, before the handler is changed | What does the server do when an expired token reaches a new socket: does it answer code 18, or close the socket? The strategy itself is decided (0010); this only tells the WI-5 classifier what to act on. | Contract test output, and **OP-1a** (§0): one real waited session, never logging tokens. OP-1b, after step 5, proves renewal. | +| CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls` for each package, bundle scan for duplicate copies, build-error list per level, and the **packaged VSIX** loading and passing the WI-3 workflow checks. | +| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | +| CP-4 | Before WI-7 starts | Teardown order, T-2, the export and import lease (A5). | Teardown sequence diagram in the PR description. | +| CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | + +--- + +## 6. PR 0: plan, research, decisions + +1. **Carry over the planning commits first.** The plan, research and decisions were written as commits on + the local branch `tnaum-ms/issue1102` (from `e22a39b8d` "wip: initial plan" onward). PR 0 is made of + **those commits**. Do not re-create the files in a fresh commit, and do not squash or rebase them: the + repository merges with merge commits only, so the history stays intact. + - Check that the branch holds only docs: `git --no-pager diff --stat origin/main...tnaum-ms/issue1102`. + - Push it as the PR 0 head branch, either under its current name or as `dev/tnaum/connection-lifecycle-plan` + (`git push origin tnaum-ms/issue1102:refs/heads/dev/tnaum/connection-lifecycle-plan`). +2. Have the operator create `feature/connection-lifecycle` from `main`, or create it yourself if you + have permission: `git push origin origin/main:refs/heads/feature/connection-lifecycle`. Deletion and + force-push are blocked afterwards, so check the base commit first. It must contain the planning + branch's base commit (`git merge-base --is-ancestor $(git merge-base origin/main tnaum-ms/issue1102) origin/main`). +3. Open PR 0 from that head branch into `feature/connection-lifecycle`. It contains: + - `research-findings.md`, `decisions.md`, `README.md`; + - `01-implementation-plan.md` with the pointer to this file; + - **this file**; + - the index row in `docs/ai-and-plans/README.md` (already present). +4. Its description: + - states that §4 (C-1 to C-6) is the agreement that lets PRs 1–3 share the connection contracts; + - lists A1 as the one provisional answer for the operator to confirm; + - links the issues as `Part of #1102`, plus #1059, #566 and #990 (references only; PR 0 resolves + nothing, so it posts no issue comments). +5. Verification: docs only, so none, beyond `npm run prettier` on the changed Markdown. + +**Progress:** + +- **Published (2026-11-19):** [Draft PR 0 (#1107)](https://github.com/microsoft/vscode-documentdb/pull/1107) + targets `feature/connection-lifecycle` from `dev/tnaum/connection-lifecycle-plan`. The operator + removed the intermediate merge gate: PR 1 can build on PR 0 now. The operator will handle reviews + and merges; CP-0 and OP-1a still apply before any OIDC handler change. +- **Coding model assignments (2026-11-19), advised (`claude-opus-5.5`):** `gpt-6.1-sol` for WI-1 + (including the pre-OP-1a work), WI-2, the WI-3 version probe, WI-4, WI-5, the WI-6 host, and WI-7, + where auth, lifecycle or cross-module contracts dominate. `mai-code-2` for the WI-6 webviews and + WI-8, which consume those contracts; `gpt-6.1-terra` is the fallback. `gpt-6.1-terra` for WI-3 + follow-through after the version verdict, WI-9 and WI-10 prose; `gpt-6-luna` for WI-10 cross-links + and preview. If a webview design decision is needed, consult the advisor in a fresh session before + dispatch. These assignments do not move any operator gate. No coding workers have been started. +- **Model override (operator, 2026-11-19):** Use `gpt-6.2-sol` for the Sol assignments above. + Keep `gpt-6.1-terra` until a GPT-6.2 Terra model is available. The MAI Code 2, Luna, and advisor + assignments are unchanged. + +--- + +## WI-1: Entra ID, silent renewal on every OIDC callback (PR 1) + +**Outcome:** + +- Each OIDC callback returns a token that is valid for the account the connection started with, looked up + silently. +- A silent miss produces a typed error that every surface explains the same way. +- An expired token that the server rejects is renewed silently. The extension relies on the server's + answer, not on local expiry checks (decision 0010). + +**Done when:** + +- Case 1 is green; +- the contract test is committed; +- the CP-0 verdict is recorded; +- no `createIfNone` is reachable from the callback (a grep test or an assertion on the mock). + +**Progress:** + +- **Done (2026-11-19), commit `df0c22ade` (WI-1a, `gpt-6.2-sol`):** Added four MongoDB driver + contract tests for the pinned 7.2.0 workflow: callback rejection, cached-token speculation, + auth code 18 retry, and network error propagation without a retry. The accepted operator strategy + (decision 0010) is unchanged; the tests confirm the mocked driver behavior, not the live server's + response. All four focused tests and `npx tsc --noEmit -p .` passed. +- **Done (2026-11-19), commit `01c0d4846` (WI-1b, `gpt-6.2-sol`):** Added local callback, socket, + and final-error traces without changing token handling. The implementation and review were advised + (`claude-opus-5.5`, high confidence): the driver does not emit the initial code 18 it handles, + so infer that path from the callback and final numeric code. Four trace tests added; Case 1 build + and 92 focused tests passed. +- **OP-1a / CP-0 (2026-11-19), advised (`claude-opus-5.5`, 80%):** After about two hours idle, + the cached client opened two fresh sockets. Both called back with the original captured token + and closed before they became ready. The final error was `MongoNetworkError`, with no numeric + code exposed. A contemporaneous diagnostics run authenticated with its own client and separate + non-interactive session lookup; it did not measure token freshness. The pinned driver's + cached-token path calls back after code 18, but the live trace does not show that code directly. + Proceed with the accepted silent renewal plan. Keep WI-5 unchanged for now; carry the possible + network-error shape to CP-2. OP-1b must verify a post-idle callback and successful operation + without prompting, including if the driver has to retry the read on a second socket. +- **Done (2026-11-19), commit `d05b66909` (WI-1c, `gpt-6.2-sol`):** Added silent token lookup + for the originally verified provider and account, shared JWT time parsing, typed callback + failures, and bounded lookup observations. Kept the destination policy and Playground TTL + fallback. Added 15 focused tests and updated dependent test mocks for the new session API. + The advisor approved the OP-1b candidate (`claude-opus-5.5`, 85% confidence). `npm run build` + and all 254 targeted tests passed. +- **OP-1b evidence (2026-11-19):** After about 43 minutes idle, Refresh reused the same client. + A fresh socket triggered callback invocation 2 (`returned`) and then closed. The next socket + became ready without another callback; later sockets and a second Refresh also succeeded at + socket authentication on the same client. No `listDatabases.failed` was logged. This verifies + the post-idle renewal and retry path; no longer wait is needed for OP-1b. The trace cannot alone + confirm whether the database list was visible or whether a sign-in prompt appeared. +- **OP-1b passed (2026-11-19), operator verification:** The database list loaded and no sign-in + prompt appeared. Resume the remaining PR 1 work. The separate long-wait requirement for OP-6 + still applies. +- **Done (2026-11-19), commit `5ee98385c` (WI-1d, `gpt-6.2-sol`):** Added a localized, text-only + explanation for typed sign-in and identity mismatch errors, including errors wrapped by the + driver. Used “this connection” rather than introducing a display-name lookup, as allowed by + step 8. Four new tests; 51 focused tests and `npx tsc --noEmit -p .` passed. Localization + generation and the remaining PR checks are deferred to handoff. +- **PR 1 pre-review F2 (2026-11-20), operator decision:** Defer typed webview sign-in errors to + the WI-5 classifier and WI-6 structured unavailable response. PR 1 keeps the existing webview + error transport. See the [review finding](./01-pr1-entra-renewal-review.md#f2-typed-entra-explanations-do-not-yet-reach-webviews). + +--- + +## WI-2: Shell and Playground token relays (after WI-7) + +**Outcome:** + +- Worker token relays follow WI-1's policy, pinned to a snapshot taken at spawn. +- A miss reaches the host as a bounded reason, and the shell or playground shows one "sign in again" line + with an action. +- A healthy warm worker never reads `CredentialCache`. + +**Done when:** Case 1 is green, and the relay PR pre-review is committed. + +**Progress:** + +- **Deferred, escalated (2026-11-19), advised (`claude-opus-5.5`):** PR 1 does not yet have WI-4's + verified identity or fingerprint, or the disconnect latch. The worker IPC and session-local + pinning can be built independently, but delivering only those pieces in PR 1 would leave the + existing respawn behavior in place until the later guards land. Recommendation: keep WI-2 + together and deliver it after both prerequisites exist. Alternative: approve a split, with + IPC and session-local pinning in PR 1 and the identity and respawn guards later. Also confirm + whether A1's provisional **Sign in again** action should remain in the worker delivery. No + relay implementation has started. +- **Rescheduled (2026-11-20), operator decision:** Finish PR 1 with WI-1 only. Deliver WI-2 + intact after WI-4's verified identity and fingerprint and WI-7's disconnect latch exist, + retaining the planned **Sign in again** action. Do not implement the partial relay option. +- **PR6a ([#1133](https://github.com/microsoft/vscode-documentdb/pull/1133)):** The complete relay + and recovery flow is in a draft stacked on PR6. The operator approved all four fixes in the + [AI pre-review](./01-pr6a-worker-token-relays-review.md). All four are implemented; the combined + Case 1 build and 534 focused tests passed. Live Shell and Playground verification stays at OP-6. + +--- + +## WI-3: Azure discovery on azureauth v6 (#990) (PR 2) + +**Outcome:** + +- Discovery works after the ARM token expires, with no provider refresh. +- The ARM challenge works. +- Diagnostics reports "Azure sign-in needed" for ARM sign-in failures. + +**Done when:** + +- Case 1 is green; +- exactly one copy of azureauth is installed; +- the #990 manual checklist is recorded in Progress, with OT-6 still pending; +- the PR 2 pre-review is committed. + +**Fallback:** if PR 2 is not merged when WI-6 is ready, tell the operator (approved plan). Do not add a +shim (0005). + +**Progress:** + +- **Deferred, awaiting operator decisions (2026-11-20):** The L2 probe installed one copy of each + azext package and found no fresh versions among the 13 newly resolved packages. The partial + migration passed 402 focused tests; the build still has 19 diagnostics in the unconverted + subscription-listing paths. No draft or packaged candidate is ready. +- **ARM challenge prompts:** The advisor (`claude-opus-5.5`) verified that each planned v6 level + can prompt on a challenge during passive Discovery. The SDK has no supported option to limit + prompts to explicit actions. Recommended for operator consideration: preserve silent + Discovery, accepting that its own wizard and deep-link flows would also forgo step-up. The + alternatives are to accept the v6 prompt behavior or widen the design to distinguish passive + and explicit calls. +- **Partial subscription results:** The advisor verified that v6 can skip tenants after ARM + failures and return a partial list. Recommended for operator consideration: retain healthy + results with a sanitized output diagnostic for failed tenants. Preserving visible failure and + Retry instead would require a larger change to listing. Neither behavior change was adopted. + OP-2 and the final CP-W3 verdict remain pending. +- **Unblocked (2026-11-20), operator decisions:** Keep successful subscription results when an + account or tenant cannot be listed, and record a sanitized diagnostic in the Output channel. + Keep the SDK's default ARM challenge behavior. The operator allowed that fallback if keeping + browsing silent required more than a small update. A prompt override would have to cover + both the SDK listing pipeline and subscription authentication, so PR2 will not add one. + OP-2 should include checking where prompts appear and what happens when they are dismissed. +- **OP-2 candidate ready (2026-11-20):** [Draft PR2 #1111](https://github.com/microsoft/vscode-documentdb/pull/1111) + contains the L2 migration (`1869c22ab`) and local account-cache fix (`423c2e1b7`). The + [PR2 pre-review](./01-pr2-azureauth-review.md) records the findings and verification. The full + suite passed before the cache follow-up (9,682 passed, one skipped); 55 focused tests and + root type-check passed after it. The rebuilt VSIX passed inspection and its host graph has one + azureauth ESM copy, with no legacy lowered initializer call in the Azure auth chunk. + Automated activation did not run in this host because Electron's GUI libraries are missing. +- **OP-2 accepted by the operator (2026-11-20):** The packaged extension activated. Discovery, + filters, and Refresh/Retry passed. The operator signed out and back in with the same account + and accepted the untested account-switch, MFA, and cloud cases. New Connection via Azure + service discovery and the Azure Resources RU and vCore/DocumentDB nodes worked. Deep-link URLs + were not tested; the operator accepted the risk. Update Credentials and workspace-provider + results were not reported. Partial failures could not be reproduced live; focused tests cover + partial results and sanitized warnings. +- **CP-W3 (2026-11-20), advised (`claude-opus-5.5`, 85% confidence):** Retain L2: + azureauth `6.1.0-alpha.2`, azureutils and utils `5.1.0`, and Azure Resources API `3.1.1`. + The build, installed dependency tree, bundle inspection, and operator-accepted OP-2 support + this choice. L1 uses the same azureauth and Azure Resources API versions and does not reduce + the remaining risks. The untested OP-2 cases above remain unverified. +- **OP-2 repeat accepted (2026-11-23):** After the alias removal changed the packaged payload, + the operator tested the PR2 CI-built VSIX and cleared the gate. The + [PR2 review record](./01-pr2-azureauth-review.md#azure-esm-bundle-verification) lists what + passed and what was not tested. CP-W3 still retains L2. + +--- + +## WI-4: Client identity, generation and the two cache fixes (PR 3) + +**Outcome:** + +- Every cached client carries C-4. +- Concurrent cold starts share one startup. +- Teardown and late startups cannot publish stale clients. +- Cancelling a cached reuse never closes the shared client. +- A closed topology is replaced, never reconnected with old options. +- `getClient` never prompts (C-6). + +**Done when:** + +- Case 1 is green; +- every existing `ClustersClient` test still passes unchanged, or each change is justified in Progress. + +**Progress:** + +- **Done (2026-11-20), commit `0e2a89576` (WI-4a, `gpt-6.2-sol`):** Integrated the original + fingerprint comparison winner onto the actual PR3 base. The blind advisor scored it 94/100 + against 88/100 for `mai-code-2` (80% confidence). It hashes the stored URI without its password + and the principal, preserving all other URI bytes. The build and 13 fingerprint tests passed. +- **Done (2026-11-20), commit `a9a8d5103` (WI-4b, `gpt-6.2-sol`):** Integrated the client + generation, binding, isolated cached-waiter cancellation, and telemetry context helper. + The blind scores were 89/100 and 74/100; the selection was provisional until the advisor + (`claude-opus-5.5`) approved the staged winner on the actual PR3 base at 85% confidence. + The build and 121 focused tests passed. Generations advance only on successful establishment; + cancelling one waiter no longer closes the client shared by other callers. +- **WI-4c deferred, escalated (2026-11-20):** The plan allows one retry after a stale startup + and specifies the result when a latch is set. It does not specify the unlatched result when + that retry is also invalidated. Recommendation: use a neutral retryable error, “The connection + changed while it was opening. Try again.” The advisor suggested `credentialsChanged`, which + fits the existing enum but can imply a credential change after a plain eviction. Confirm + the changes to the existing cancellation tests as well: cancelling a wait must not cancel + or misreport the physical startup, and a real startup failure must still be logged and cleaned + up. Neither choice was assumed. The two worktrees are ready; no coding variants have run. +- **WI-4c operator decision (2026-11-20):** Use the neutral retryable error “The connection + changed while it was opening. Try again.” if the one retry is also superseded and no latch + is set. Do not add a new unavailable reason or a third attempt. A latch takes precedence. + Cancellation assertions continue to follow the approved waiter-only behavior and retain + coverage of actual startup failures, telemetry and cleanup. +- **Done (2026-11-20), commit `61e9cd4f5` (WI-4c, `gpt-6.2-astra`, High, large context):** + Integrated the top blind-review candidate with bounded follow-up changes. Concurrent callers + share a startup for the current epoch; cancellation only ends a caller's wait. A superseded + client cannot publish or delay a retry while closing. Added the stale-handshake failure and + latch regression; the build and 108 focused tests passed on the delivery branch. The operator + chose the neutral second-invalidation message. The advisor (`claude-opus-5.5`) approved the + corrected candidate for delivery at 85% confidence. Full Case 2 and localization generation + remain deferred to PR3 handoff. + + **WI-4c blind comparison:** Same baseline (`9a4d28dfa`), accepted behavior, build and focused + selectors. Scores describe the original candidates, not the corrected delivery commit. The + ranking had 60–65% confidence. Test counts differ because candidates authored their own tests. + Fusion ran alone via the Copilot CLI; its AI credits are reported separately from AIU. + + | Variant | Candidate | Score | Elapsed | Input / output tokens | Tool calls | Usage | + | ----------------------------------------- | --------------------- | ---------------: | -------------: | --------------------: | -----------: | ----------------: | + | `gpt-6.2-astra`, High, large context | `89d642e66` | 92 | 4m03s | 737k / 12k | 27 | 254.7 AIU | + | `gpt-6.1-sol`, High | `18e933d13` | 89 | 8m16s | 1.1M / 24k | 33 | 55.8 AIU | + | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | + | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | + | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | + | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | 40 | 184.43 AI credits | + | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | + | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | + | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | + | `gpt-6.1-sol`, Medium | `2cb904a18` | 73, fix required | 5m46s | 982k / 14k | 28 | 41.3 AIU | + | `claude-opus-5.5`, default, large context | `a0b581b07` | Disqualified | 7m53s | 2.5M / 44k | 29 | 201.1 AIU | + + The medium-effort candidate could replace a cached client without closing it. The Opus + candidate did not honor the retry or latch on an obsolete startup failure. Astra led on + simplicity among the correct candidates; Sol 6.1 High had the strongest tests. This was + one trial per configuration, not a general model ranking. + Fusion High ran alone on the same baseline and hit the 10-minute limit. It left partial + implementation changes but no test changes. The partial result was not verified or scored + and does not change the delivery selection. Fusion chose Critique mode but never finished + the Opus 5.5 draft. The first request took 5m15s and reached its 48,000-output-token limit. + The draft then made further requests until the timeout; the critic and revision never ran. + +- **WI-4d/e deferred, escalated (2026-11-20):** The advisor reviewed the split between silent + reconnect and closed-client replacement. Before implementing, confirm these reconnect rules: + 1. Reject a silent Entra startup without a verified account before asking VS Code for a + session. Only a deliberate first connect may prompt. + 2. Let background callers use a healthy cached client or join an existing startup, but not + start or replace one. + 3. Keep the verified account for Discovery and Azure Resources connections. Those items have + no Remove action, so switching accounts may require a reload until there is an explicit + account-switch flow. + 4. Reject a closed-client replacement with a different identity and retain the closed entry, + so the next ordinary call cannot start as the new identity. + 5. Pin account, provider, and tenant for automatic reconnect. Use changed tenant credentials + only after an explicit credentials change. + + The initial request went unanswered, so implementation did not start at that checkpoint. + +- **WI-4d/e approved (2026-11-20), operator decision:** The operator accepted all five rules above. + For rule 1, the operator preferred requiring an explicit first connect to silently picking + an account. For rule 3, the operator accepted the reload limitation as an edge case. Finish + silent reconnect first, then closed-client replacement. PR2's pre-review was signed off + separately and does not block this work. +- **Done (2026-11-20), commit `6a53cf19e` (WI-4d, `gpt-6.2-sol`):** Reconnect silently with the + verified provider, account and tenant. Only a deliberate first connect may prompt, and + background calls cannot start a client. The shared tree helper uses `connectInteractive`; + the positional `getClient` signature remains compatible, with an optional background flag. + The advisor (`claude-opus-5.5`, 85% confidence) approved the implementation. All 372 focused + tests across 13 files and the TypeScript check passed. WI-4e will handle closed topology. +- **Done (2026-11-20), commit `4680b459f` (WI-4e, `gpt-6.2-sol`):** Reuse open clients without + calling driver `connect()` again. A foreground caller can replace a closed client; concurrent + callers share that replacement, including background callers that join it. Reject a different + fingerprint before constructing a driver and retain the closed binding, as the operator + approved. The leader checked the topology event and caller, epoch, and latch checks against + the advised WI-4e contract. Build and 116 focused tests passed. The cancellation and stale + retry tests now exercise a pending replacement rather than an obsolete cached `connect()` call. +- **PR3 pre-review (2026-11-23):** The operator approved two scoped fixes: preserve the shared + startup when the decoded-password wait is canceled (`e751df24b`), and keep passive index counts + from starting a client (`db01f24a5`). Both used `gpt-6.2-sol`; build and 95 focused tests passed. + The operator also approved deferring stable Kubernetes tunnel fingerprints to #1105. See the + [review record](./01-pr3-client-identity-review.md) for advisor confidence and verification. +- **PR3 handoff:** Case 2 passed after syncing PR2 and updating the connection-string edit + fixture to mock the interactive entry point without changing behavior assertions. The full + rerun passed 9,735 tests with one skipped. See the + [verification record](./01-pr3-client-identity-review.md#case-2-handoff). PR3 stays stacked + on PR2; WI-5 starts with the classifier and stops at CP-2 before recovery wiring. + +--- + +## WI-5: Classify failures and recover: host and tree (PR 4) + +**Outcome:** + +- One pure classifier. +- The tree's Retry actually reconnects. +- **Sign in again** exists and prompts once per click. +- A token callback failure never leaves a broken client cached, for any auth method. + +**Done when:** + +- Case 1 is green; +- the CP-2 verdict is recorded; +- OT-2's tree part can be reproduced with the WI-4 hook. + +**Progress:** + +- **CP-2, advisor verdict: revise before wiring.** The classifier draft builds and 32 focused + tests pass. The pinned 7.2.0 workflow test shows that if a cached OIDC token receives code 18, + the driver calls the callback and propagates the final rejection unchanged if that token is + also refused. This does not prove that the callback returned newly issued token bytes. + Treat the final Entra authentication rejection as `credentialsRejected` and evict the client, + rather than adding callback-freshness fields with no reliable producer (85% advisor confidence). + Keep typed `noSession` distinct. Plain network failures (including the OP-1a shape and tunnel + refusal) and mixed per-server failures keep the client. Closed-client checks are typed only. + Plain callback errors do not reach the per-server descriptions through the pinned OIDC path, + so R5 does not require changing the Entra explainer now. Cancellation and destination handling + stay in place. +- **CP-2 / OC-1, accepted (2026-11-23):** The operator chose A for smoother recovery and asked + to record it in [decision 0014](../decisions.md#0014-keep-in-memory-connection-settings-after-a-rejection-for-a-verified-entra-identity). + Evict the rejected client, but keep the in-memory settings for a verified Entra identity. + Explicit **Sign in again** then works when invoked with just `clusterId`. No rejected token is + retained, no automatic retry is started, and Native/RU rejection and persistent storage are unchanged. +- **CP-2 revision verified:** Removed the unproducible freshness inputs. The contract test now + sends the exact final code 18 from the driver workflow through the classifier. Case 1 passed: + build and 31 focused tests across classification, the driver contract, and the Entra explainer. +- **CP-2 / OC-2, accepted:** Reuse the existing latch for `credentialsRejected` rather than + adding a separate hold. Eviction must not let an ordinary operation open another client with + rejected settings. Only the matching explicit recovery can clear the rejection, and only if + its epoch is current. The operator preferred the simpler option and asked to record + [decision 0015](../decisions.md#0015-use-the-existing-latch-to-block-startup-after-authentication-rejection). +- **OP-3 candidate:** Host and tree recovery, Retry and **Sign in again** are implemented + for [draft PR4 (#1117)](https://github.com/microsoft/vscode-documentdb/pull/1117). Case 1 passed: + the host batch passed 222 tests, the tree batch passed 367, and a final 127-test run covered + the Native discovery Retry correction and the core recovery paths. These counts overlap. + OP-3 requires a real Entra sign-out on the dev host and a fresh-socket callback. PR4 pre-review + and handoff checks remain; WI-6 does not start before OP-3 is cleared. +- **OP-3 UI clarification:** The operator accepted showing **Sign in again** instead of **Retry** + when Entra sign-in is the next useful step. Diagnose and Open shell remain. This follows decision + 0001's single sign-in action and preserves the original Retry behavior for transient failures. +- **Draft PR4 CI follow-up:** The VSIX built, passed inspection, and activated in VS Code. Static + checks exposed stale localization, formatting changes, and a type-only import lint error. The + full test run found 32 failures in three suites whose mocks did not expose the new lifecycle + methods. Update those fixtures without changing their assertions or runtime recovery behavior. + OP-3 remains the live Entra sign-out and dismissal gate. +- **OP-3 partial live run (2026-11-23):** A CI-built PR4 VSIX loaded databases and the dashboard. + After sign-out, idle sockets closed and fresh sockets became ready under the same client startup. + No post-sign-out OIDC callback appears in the supplied excerpt, and sign-in recovery and dismissal + were not reached. The run is inconclusive; OP-3 remains open. On resume, close the dashboard, + wait until the cached token is no longer accepted, and explicitly refresh the cluster node + without restarting the extension host. Collapse and re-expand can show cached children. +- **OP-3 resumed on the older VSIX (2026-11-23):** A refresh opened a new socket on the + same client. OIDC callback invocation 2 threw, and the database listing failed. + The operator confirmed that the initial failure showed an error modal, not a sign-in + prompt. Closing the modal revealed the recovery action. They confirmed dismissing the + actual Microsoft sign-in prompt as requested and that the recovery actions remained. + A later explicit sign-in restored the database list. **OP-3 passed** on the older CI VSIX. + The operator approved renaming the tree action to **Retry sign-in**, first before Diagnose + and Open shell, without a separate Retry row. Command ID and recovery behavior are unchanged. +- **Sign-out scope review (2026-11-23):** Claude Opus 5.5 recommended keeping the approved + 1.2.0 scope (80% confidence). Prompt sign-out handling would need account-specific session + checks, coordination with active tasks, and separate handling for Shell and Playground + clients. Track it in [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119). + OP-3 and its required evidence are unchanged. +- **Future operator VSIX builds:** Give each new test candidate a distinct extension version in + the root `package.json` and corresponding root lockfile entries. Verify the version in the + packaged manifest, and give the operator that version, the commit, and the CI artifact link. + Do not rebuild an unchanged candidate just to label the partial run. +- **Connection stats add-on:** Add a read-only **Show Connection Stats** command alongside + **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client + generation, age, auth method, startup correlation, pending or held state, and whether socket + events are traced. It contains no cluster or account identifiers and makes no service calls. + For Entra it shows the UTC expiry declared by the last token supplied to the driver, with + the remaining time at capture (`hh:mm:ss`), `expired`, or `unknown`. This local diagnostic + retains no token and does not predict server acceptance or force renewal. + Leave socket counts out rather than guessing. The operator requested restarting OP-3 on + the next CI-built candidate, `1.1.1-alpha.1`, which includes the diagnostics and worker fix. +- **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method + module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify + the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. +- **PR4 handoff verification:** OP-3 passed, author-approved pre-review fixes are in + [the review record](./01-pr4-connection-recovery-review.md), and local Case 2 passed + (9,796 runtime tests passed, one skipped). Full CI passed on `d422d065b`. + The operator confirmed both Shell and Playground on the CI-built `1.1.1-alpha.1` VSIX + on 2026-11-24. The worker smoke gate is cleared, and PR4 can move to operator review. + WI-6 continues on this base without waiting for PR4 to merge. + +--- + +## WI-6: Bind surfaces and add the unavailable state (PR 5) + +**Carry-forward from PR 1:** Verify that a typed sign-in error classified by WI-5 reaches the +webview as a structured unavailable result, not a generic query error. + +**Outcome:** + +- 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 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. + +### Host + +Capture a binding rather than a physical client; re-resolve for the same identity and reject +stale replies before mutating caches or issuing a write. Import/export from a view carries that +origin to the transfer's first operation; a tree command uses the selected current connection. + +### Webviews + +Keep the editor mounted. The original plan proposed a disabled overlay with repair actions; +an old save or page reply must never replace a newer draft or query. The Progress block below +records the operator's subsequent choices; the [feature README](../README.md#intent) describes today's policy. + +**Done when:** + +- Case 1 is green; +- the scenarios pass; +- OT-1 and OT-3(a) can be reproduced with the WI-4 hook. + +**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) + +**Outcome:** + +- Disconnect and Remove share teardown. Saved edits share the task fence and resource cleanup, + but keep old views locked without asking to close them (decision 0018). +- Task conflicts block teardown or saving an edit. Dirty editors are checked before Close all. +- It covers every per-cluster resource. +- **What it guarantees** (F-22: closing a client cancels nothing already sent): + - no **new** submission under the old binding after the latch is set; + - no automatic replay of anything; + - no stale reply changes host state or the UI (WI-6 step 6 and the webview rule); + - no message claims that an unacknowledged write was not applied. + + Operations already in flight may complete or fail; whatever happens is reported normally. Shell and + playground workers are stopped. Tasks, exports and imports are protected by the conflict check. + + This is the right level for an interactive tool; do not build per-operation admission control. + +**Done when:** Case 1 is green, and the OT-7 flows can be reproduced on a dev build. + +**Progress:** + +- **CP-4 verdict:** Opus 5.5 approved the teardown order, T-2 and A5 at about 85% confidence. + Register tasks and acquire export/import leases synchronously against the latch. Take a lease + before client resolution, release it in `finally`, and include it in folder-delete conflict + queries. Recheck conflicts immediately before latching; use the epoch bump already in + `ClustersClient.latch`. For saved edits, keep the fence through persistence and retirement, + then restore only the applicable prior hold. Enforce retirement on the host as well as in the + dialog: a password-only edit does not change the fingerprint. The proposed per-cluster + generation watermark is an implementation candidate to validate in the saved-edit slice, + not a new public contract. No operator decision is needed for the lease slice. +- **WI-7 S1:** Import and export hold a collection lease from client resolution through + completion. Task admission checks the same latch as client startup. Existing conflict queries + see leases, including the folder-delete check. The task, transfer and Dashboard-bound command + test suites passed together (18 tests). +- **WI-7 S2a:** Disconnect now checks task conflicts and dirty views before teardown, with a + synchronous conflict recheck before latching. It stops matching Shell and Playground workers, + keeps credentials and the verified identity, and refreshes the same tree node with one + **Connect** action. The integrated build and 225 focused tests passed. Remove and saved edits + are not wired into teardown yet. +- **WI-7 S2b:** Remove and folder deletion keep their existing deletion confirmation and share + one tab choice for the affected connections. The batch rechecks and fences the entire set + before disposal or deletion. A failed storage delete leaves the surviving connection + disconnected rather than stuck in the removed state. Build and 30 focused tests passed. +- **WI-7 S3:** The save fence reports a retryable update-in-progress state; only a changed + stored value permanently retires the older generations. This also covers password-only and + partial secret writes without adding passwords to the fingerprint. Existing views remain + copyable. Same-settings reconnect can still follow a newer generation. Build and 196 + focused tests passed. +- **OP-5 (`1.1.1-alpha.4`):** The operator reported that Keep open, Close all with a dirty + draft, Remove, and the saved-edit lock passed. Disconnect during import or export was + not tested live; it is checked in the real transfer-lease and teardown preflight paths + by automated tests. Operator feedback: label the tree action **Reconnect**, use the + default Fluent layout with an instant backdrop, and clarify that an old view is bound + to its previous connection settings. +- **PR6 review:** The operator kept the single dirty check at **Close all** confirmation + ([review thread](https://github.com/microsoft/vscode-documentdb/pull/1130#discussion_r4694258852)). + In a batch removal, a view edited after that check still closes; there is no second prompt. +- **Carry-forward from WI-4d:** An explicit Update Credentials that changes the tenant must + replace or clear the old verified Entra identity so the next connect can use the saved + tenant (decision 0011). Automatic reconnect remains pinned until that explicit update. + +--- + +## WI-8: Cluster Dashboard health polling (PR 6) + +**Outcome:** the poll stops when the cluster is unavailable, shows the overlay, and resumes with exactly +one loop. + +**Progress:** + +- The Dashboard polls with a background-only binding. Auth and closed-client errors from + inside the sampler return an unavailable result; unsupported `serverStatus` still returns a + partial sample. Build and 131 focused tests passed. The browser fixture showed no polls + during disconnect, copy mode or reveal; Retry restarted one loop. A held ping released + after disconnect did not clear the dialog. + +--- + +## WI-9: Token renewal telemetry (PR 7) + +**Outcome:** the release can be judged from events that need no joins and no persistent identifiers. + +**Steps:** + +1. **`connection.tokenRenewal`.** + - Emitted from the C-3 observer (host client) and from the host side of the shell and playground + relays. + - Once per completed post-startup Entra **database** token lookup. The initial acquisition is excluded. + - Properties: `surface` (`extension`, `shell`, `playground`) and `renewalOutcome` (`returned`, + `noSession`, `identityMismatch`, `failed`). + - One measurement: `tokenLifetimeSeconds`. Omit it when unknown; never send 0 or the worker's fallback + TTL. + - Never send a token, hash, claim, account, tenant, cluster ID, fingerprint or host name. +2. **Recovery, without a new event.** Existing `connect`, `rpc` and `getchildren` events carry + `connectionAgeMs` and `clientGeneration` (WI-4 `addEstablishedConnectionContext`). A successful + operation on a generation above 1 shows that a replacement worked, and late auth, socket and + closed-client failures should drop against the baseline. +3. **ARM.** Report challenge outcomes separately from database renewal. Confirm that the final ARM request + succeeded, not just that a token was acquired. +4. **Volume.** + - `connection.tokenRenewal` is a background event. If the dashboards keep an event-scope exclusion list + for "active users" totals, add it there. + - Check the expected volume (about one renewal per active Entra client per hour) against the + telemetry budget. +5. **Queries.** + - Commit runnable Kusto queries in a durable `../telemetry.md` at the feature root: + - daily renewal outcomes; + - p50/p90 of the token lifetime; + - successful operations on a replaced client (generation above 1); + - late auth, socket and closed-client failures against the pre-release baseline, using the same + exposure denominator. + - Show sample counts and missing timing data next to every percentile. + - If the operator's telemetry dashboards worktree is available, port the queries there too. +6. **Fake-clock test** for the sequence returned → returned → noSession: + - check counts and units; + - include an opaque token (no lifetime) and a database rejection after the lookup. + +**Done when:** + +- the tests are green; +- the queries have run once against pre-release ingestion (or they are marked "pending ingestion" in + `# Outcome`). + +**Progress:** + +- The WI-9 commit records only checked post-startup Entra database lookups. Host lookup eligibility + follows the published client; worker eligibility is captured when the ready or executing worker + requests the token. Neither uses the first callback as a startup proxy. +- Case 1 passed: `npm run build` and 349 focused tests in 8 files. Ingestion is **pending**; the + [telemetry queries](../telemetry.md) are ready to run. The dashboard worktree has unrelated + changes in progress and was left untouched. +- PR7 review superseded the before/after comparison in items 2 and 5. Auth and closed-client + unavailability are not measured equivalently across releases. The operator deferred the + comparison and kept descriptive telemetry for CP-5 ([decision 0020](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures)). + +--- + +## WI-10: Documentation (PR 7) + +1. **User manual:** + - add `docs/user-manual/connection-lifecycle.md`, or extend `connecting-to-databases.md` (choose one and + record the choice). It covers Disconnect, Sign in again, what a disconnected tab means and how to + resume, and what Update Credentials does to open sessions; + - link it from `interactive-shell.md`, `query-playground.md` and `managing-azure-discovery.md`; + - user-manual pages and release notes use **separate copies** of their images. +2. **Release notes** for 1.2.0 (writing-release-notes skill). Screenshots go through the + documentation-screenshots skill. +3. **Skills:** + - tree-cluster-architecture: "resolve the client per operation through a binding; never hold a + `ClustersClient`", the recovery-children order, and the `connected` context tag; + - error-translation: the C-2 errors and the `entraSignInRequired` provider. +4. **Feature docs:** + - feature `README.md`: status, code map and timeline; + - `decisions.md`: entries for A1–A6 once confirmed, T-1 and anything else the checkpoints decided; + - add `design.md` if the binding, state and teardown design outgrew the README. +5. **Preview** the docs site locally (previewing-docs-site skill). + +**Progress:** + +- The operator chose text-only 1.2.0 release notes. The user manual extends + `connecting-to-databases.md` rather than adding a second page. +- The local GitHub Pages build rendered the manual and draft release notes. The three + manual links and the release index link resolve, and the internal feature docs stay excluded. + +--- + +## PR F: `feature/connection-lifecycle` → `main` + +1. Sync `main` into the feature branch through a pure merge PR (approved plan rule 5). +2. Run Case 2 on the feature branch head. +3. Run OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more. Record each + result, and the evidence the approved plan requires, in `# Outcome`. In addition: + - **First write after expiry:** prepare an edit in Document View on a connection whose string + sets `retrywrites=false`. After at least two hours idle, make **Save** the first database + operation; do not run a read beforehand. Record the result and any message. Only if this + fails, fix the message to tell the user to try again without claiming the write was not + applied (F-22). Do not replay writes or add a pre-write probe in this PR; a probe would + require a separate decision next to [0010](../decisions.md). + - **Continuous use across expiry:** run a query every few minutes for about 90 minutes + spanning a token expiry. Record whether operations continue without an interactive prompt. + - **Sleep/wake and workers:** sleep and wake across a token expiry and exercise the connection + after waking. Exercise Shell and Playground after expiry as separate worker paths. + - **OT-1:** check the shell separately. After the wait, its worker's own connection must renew without + a prompt; record the token relay in the output channel, never the token. + - **OT-7:** also Disconnect while a query or save is in flight. Whatever its outcome, it is reported; + its reply does not change the open view; nothing new is submitted under the old connection; and no + message claims that an unacknowledged save was not applied (F-22). + - **OT-1 and OT-2 evidence:** a callback trace line after the wait or the sign-out, on a fresh socket + (`maxIdleTimeMS`), not only a successful query. Also Disconnect during an **import**: it must be + blocked before the Close/Keep prompt, and the import continues. +4. CP-5 verdict, then open PR F. Its description carries `Fixes #n` for every issue the iteration + resolves in full (see the §0 issue table), and `Part of #n` for the rest. +5. After the merge: for every linked issue that stays open, post the partial-fix comment (§0), summarizing + the whole iteration and what is left. Do the same on #1105 and #1106 for the work handed to them. +6. Watch telemetry for about one week after the merge (WI-9 queries). + +# Outcome + +- **WI-9 telemetry: pending ingestion.** Run the [feature queries](../telemetry.md) on + pre-release data before CP-5, including `unavailableReason` on a typed webview response. + The cross-release trend is unmeasured for 1.2.0. Record the + packaged operator validation here at OP-6. The additional first-write, continuous-use and + sleep/wake and worker scenarios are pending operator verification on a packaged build. 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 new file mode 100644 index 000000000..7a51a362f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -0,0 +1,558 @@ +--- +feature: connection-lifecycle +kind: plan +status: historical +created: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/auth/connectionAuthIdentity.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/commands/updateCredentials/updateCredentials.ts + - src/webviews/documentdb/collectionView/collectionViewRouter.ts + - src/webviews/documentdb/documentView/documentsViewRouter.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Iteration 1: keep connections usable across token expiry, idle drops and credential changes + +**Issues:** + +- [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) (this plan); +- folded in: [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) (Disconnect) and + [#566](https://github.com/microsoft/vscode-documentdb/issues/566) (one teardown for Remove and + Disconnect); +- executed as a dependency: [#990](https://github.com/microsoft/vscode-documentdb/issues/990) + (azureauth v6); +- coordinated: [#1091](https://github.com/microsoft/vscode-documentdb/issues/1091) (dashboard polling). + +**Branch:** `feature/connection-lifecycle` (sub-PRs from `dev/tnaum/*`; see [Delivery](#delivery)) · +**Milestone:** 1.2.0, shipped as one release + +The analysis, evidence and source pointers are in [../research-findings.md](../research-findings.md), +and the decisions in [../decisions.md](../decisions.md). Neither is repeated here. This plan orders the +work. **It deliberately does not specify interfaces**: a dedicated agent designs them per work item, +following the decisions. Progress is recorded **inline, against each work item**, when that item is +committed. + +This is the original proposal, not current product policy. The [dev ledger](./01-dev-plan.md) records +the cross-PR contracts, checkpoints, deviations and actual verification against each WI. See the +[feature README](../README.md) for what landed. + +## Goal + +A user who leaves VS Code open for hours, with tabs and shells open, **never has to restart VS Code** +and **never loses work** (query text, filters, sort, projection, unsaved document edits). + +- Token expiry and idle drops recover silently. +- When the user really has to act (sign in again, credentials changed, they disconnected), every + affected surface shows a clear disconnected state with the reason and one action. It never quietly + continues under a different identity. + +## Mapping to #1102 acceptance criteria + +| #1102 criterion | Work items | +| ------------------------------------------------------------------------------------------------------- | ---------- | +| Entra: renew without prompting; never reuse an expired token for a new connection | WI-1, WI-2 | +| Standard auth: reconnect with the configured credential; if invalid, prompt to update, no endless retry | WI-5 | +| Interactive sign-in keeps Collection View tabs and their state, then uses the recovered connection | WI-5, WI-6 | +| Recover on the next operation without a restart; never silently replay writes | WI-5, WI-6 | +| Discovery (signing in to Azure) is separate from database authentication | WI-3 | + +## Execution order + +``` +WI-1 ──┐ (Entra silent renewal) + │ +WI-3 ─┤ (azureauth v6 / #990, parallel track) + │ +WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disconnect, then dashboard) + └──> WI-2 (worker relays, after the disconnect guard) + └──> WI-9 (telemetry check) ─> WI-10 (docs) +``` + +- WI-1 and WI-3 are independent of the lifecycle core. WI-2 needs WI-4's verified identity and + fingerprint, and the disconnect latch used by WI-7. +- WI-1 and WI-2 remove most of the user impact (defect #1). They still ship with everything else; + there is no partial release (decision [0006](../decisions.md)). + +## Delivery + +**Model (decision [0006](../decisions.md)):** a `feature/` branch with sub-PRs, following +[CONTRIBUTING §1.4](../../../../../CONTRIBUTING.md#14-large-features). + +- `feature/connection-lifecycle` is created from `main`. +- Each sub-PR comes from a `dev/tnaum/` branch and ultimately merges into the feature + branch, where it gets its own review, AI pre-review and checks. The operator handles approvals + and merges. +- **One** final PR, `feature/connection-lifecycle` → `main`, ships everything in a single release. +- Use ordinary PRs targeting the preceding branch, not GitHub's stack feature. + +### Rules for stacking sub-PRs + +Branch from the preceding head while it is open; integrate bottom-up into the feature branch. +Reviews and operator tests still apply on intermediate bases even without CI. Sync `main` +weekly and before the final PR by merge, not a post-review rebase or force-push. Regenerate +localization and the lockfile rather than hand-merging them. + +### PR split + +| PR | Content | Base while predecessor is open | +| --- | -------------------------------------------------------------------------------- | ------------------------------------------ | +| 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch | +| 1 | WI-1: Entra silent renewal | PR 0 head | +| 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | PR 1 head | +| 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | PR 2 head | +| 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | PR 3 head | +| 5 | WI-6: surface binding and the disconnected state (host and webviews) | PR 4 head | +| 6 | WI-7 + WI-8: teardown, Disconnect, Remove, Update Credentials, dashboard polling | PR 5 head | +| 7 | WI-9 + WI-10: telemetry signals and dashboards, documentation | PR 6 head | +| F | `feature/connection-lifecycle` → `main` | `main` (all sub-PRs merged, OT-1–7 passed) | + +- WI-4 consumes the verified account, provider and tenant contract from WI-1. Do not reconstruct + the identity from a later cache read. +- **WI-2 scheduling (operator approved 2026-11-20):** Deliver the Shell and Playground token relays + together, after WI-4's verified identity and connection fingerprint and WI-7's disconnect latch + are available. Keep the planned **Sign in again** action. PR 1 is WI-1 only; it does not change + worker relay behavior. +- **PR 5 is the largest.** If it becomes too large to review well, split it into host (5a) and + webviews (5b). Stack 5b on 5a, and PR 6 on 5b, following rule 1. +- **#990 alternative:** #990 is its own issue in the 1.2.0 milestone. It can merge to `main` instead, + which keeps the busiest lockfile changes off the feature branch; it would still ship in the same + release. The default is the feature branch, so that the discovery fix and the WI-3 diagnostics + mapping are reviewed together. + +### Verification per PR + +Case 1 for work in progress, full Case 2 and a committed AI pre-review for handoff +([contributor workflow](../../../../../CONTRIBUTING.md)). The final PR also required packaged +operator tests, telemetry and documentation review, and about one week of post-merge observation. + +--- + +## WI-1: Entra ID, renew silently on every OIDC callback (decision 0001) + +**Problem:** the callback returns the token captured at connect time +([MicrosoftEntraIDAuthHandler.ts:155-162](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)). + +- The first connect stays as it is: interactive when the user asked for it (`createIfNone`), and it + records the account that signed in (`onTokenAcquired` already exposes `account`). +- **Each callback** calls `getSessionFromVSCode([scope], tenantId, { silent: true, account })`, with + the account pinned. + - Return `expiresInSeconds` from the JWT `exp` claim. Reuse the decoding in + [playgroundWorker.ts:215-230](../../../../../src/documentdb/playground/playgroundWorker.ts) and + [tokenExpiry.ts](../../../../../src/documentdb/auth/tokenExpiry.ts). + - Keep the destination policy checks that wrap the call + ([oidcClientOptions.ts:151](../../../../../src/documentdb/auth/oidcClientOptions.ts)). +- If there is no session, or a different account comes back, throw a **typed sign-in-required + error**. Never prompt from the callback. It must work with the existing `AuthInputUnavailableError` + and with the Entra failure registry. Per the comment at + [MicrosoftEntraIDAuthHandler.ts:117](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts), + a silent miss is not a token failure. +- Route the typed error through `ErrorExplanationService` + ([errorExplanationService.ts](../../../../../src/services/errorExplanationService.ts); see the + error-translation skill) so every surface gets the same message: "Your Microsoft sign-in for + '{cluster}' expired. Sign in again to continue." +- **Unit tests:** + - A second callback consults the provider again and uses its result; identical token bytes are + valid while the token is still good. + - A silent miss gives the typed error, and `getSession` is never called with `createIfNone`. + - A different account is reported as such. + - The destination policy is still enforced. + +**Driver verification gate:** in a local probe at `e22a39b8d`, driver 7.2.0 tried its cached token +on a new connection even with `expiresInSeconds: 0`. Code 18 on that token triggered the callback; +a transport failure did not. Returning the JWT lifetime alone does not meet #1102. Demonstrate +that a known-expired token is not offered on a new socket, including speculative authentication. +After a callback threw, the same driver workflow reused the rejection; a fresh workflow succeeded. +Test that explicit recovery replaces the failed workflow rather than retrying it indefinitely. + +> **Changed 2026-11-19 (decision [0010](../decisions.md)):** the "known-expired token is not offered" +> requirement is dropped. The extension relies on the server rejecting an expired token, after which the +> driver calls the callback and renews silently. No proactive rotation, no local expiry checks. The +> operator test OP-1 in [01-dev-plan.md](./01-dev-plan.md) checks what the server actually returns. + +## WI-2: Shell and Playground token relays use the same policy + +**Problem:** both relays call `createIfNone: true` inside the worker's token request +([ShellSessionManager.ts:450](../../../../../src/documentdb/shell/ShellSessionManager.ts), +[PlaygroundEvaluator.ts:467](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)). + +- Extend the [D12 snapshot](../../sovereign-clouds/decisions.md): it pins the audience today, **not** + the VS Code account. Capture the verified account ID, provider/cloud and tenant on initial + acquisition. Fail closed if the provider changes or the returned account does not match. +- A miss puts the shell or playground into a "sign in again" state: a printed line and an action. It + never opens a modal during a background refresh. +- Fold in the #1059 note: `PlaygroundEvaluator.buildInitMessage` + ([PlaygroundEvaluator.ts:288](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)) reads + `CredentialCache` on every run. +- **Unit tests:** the current worker IPC drops a sign-in-required error's type. Verify that a + bounded reason reaches the host action during both init and a warm evaluation. A healthy warm + worker must not need a new cache read; build its init message only when spawning it. + +## WI-3: Azure discovery, azureauth v6 (#990, decision 0005) + +Execute #990 as written. The issue already lists the breaking APIs, call sites, dedupe rule, l10n +bundle, filter and cache behavior, and how to verify. Additions from this investigation: + +- **Version alignment:** + - azureutils 4.2.0 expects azureauth `^6.0.0-alpha.6`; the challenge contract is the cause of the + `endsWith` crash. + - Pick versions so the bundle contains a **single** azureauth copy (see #990 "Dedupe"). + - Decide together whether to move azext-utils and azureutils to v5, as vscode-cosmosdb did + (azureauth 5.1.1 + azureutils 5 + utils 5; their host owns refresh). #626 is now stale; utils is + already 4.1.0. +- **Discovery tree items keep `AzureSubscription` objects:** + - Confirm that v6 `credential.getToken` and `authentication.getSession` acquire a token on every + call, so a subscription that was stored hours ago still works. + - Discovery item pointers: [DocumentDBResourceItem.ts](../../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts), + [MongoRUResourceItem.ts](../../../../../src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts), + and the VM items. + - ARM client creation: [azureClients.ts](../../../../../src/utils/azureClients.ts). +- **Diagnostics:** classify ARM sign-in failures as `signInRequired`, not `other`: + - `NotSignedInError`; + - a failed challenge; + - an `interaction_required` or AADSTS sign-in error. + + The place is `classifyResolutionFailure` + ([resolveTarget.ts:52-82](../../../../../src/connectionDiagnostics/checks/resolveTarget.ts)). Keep it + bounded: an error name and status only in the report, never messages (decision R2 in connectivity-troubleshooter). + A local probe of `6.0.0-alpha.8` through `createSubscriptionContext` confirmed that a held + subscription looks up a session again. On a silent miss the actual exception had `name: "Error"` + and no HTTP status; the current test manufactures `name: "NotSignedInError"`. Use the package's + `isNotSignedInError` guard and test the real exception. A challenge can request interactive + step-up; do not infer that ARM discovery shares the database callback's no-prompt behavior. + +- **Unit test:** a stored subscription whose first token "expires" still lists clusters (mock the + session sequence). +- **Fallback:** if #990 is not merged by the time WI-6 is ready, raise it with the operator before + changing course. Decision 0005 rejected a local shim. + +## WI-4: Client identity, generation and two cache bugs (decision 0002) + +In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): + +- **Identity and generation:** every client records, when it is created: + - an identity fingerprint: [getConnectionAuthIdentity](../../../../../src/documentdb/auth/connectionAuthIdentity.ts) + plus the signed-in Entra account id from WI-1; + - a per-cluster **generation**; + - its creation time. + + The fingerprint is derived from **what was used to connect**, not from the current `CredentialCache`. + The helper alone returned `native:sam` for two hosts and two auth databases. Bind the logical + deployment plus the effective principal (including auth source). Using a stable Kubernetes + provider target instead of the forwarded local port is deferred to #1105 (decision 0009). + Test managed identity using the actual runtime credential + shape, a password-only change, and the same username on a different deployment or auth source. + +- **Fix:** cancelling a _cached_ reuse must not close the shared client. + - Pointer: the `getClient` abort handler at + [ClustersClient.ts:586-592](../../../../../src/documentdb/ClustersClient.ts). + - This is a likely trigger for "Client must be connected before running operations" + (research §3). +- **Fix:** never hand out a client whose topology was closed. + - Today `getClient` calls `connect()` on a closed client, which reconnects with the old options. + - Replace it with a new generation that uses the current credentials, keeping the same fingerprint + rule. +- **Telemetry base:** one helper adds `authMethod`, `connectionAgeMs` and `clientGeneration` to any + failure that happens after the connection was established. The surfaces in WI-5 and WI-6 call it. + Follow the telemetry-instrumentation skill; property names must not contain "error" (masking). +- **Concurrent startup and teardown:** two deferred cold gets produced two clients, and a pending + connect repopulated the cache after deletion completed. Share one startup per cluster; invalidate + the generation before teardown awaits and check it before publishing or returning a client. + Test a late startup after Disconnect, an old Retry after replacement, and cancelling one of two waiters. +- **Optional test hook, development only:** a command that makes the Entra callback return an + invalid token N times and drops pooled connections. It lets WI-5 and WI-6 be checked in minutes + instead of 90. + - Declare it in `LAZY_COMMANDS` ([checks.cjs](../../../../../build/verification/activation/checks.cjs)), + as required for commands that are not registered in production. + - Use a dashed context key if it needs one. + +## WI-5: Classify failures and recover (main thread and tree) + +- **One classifier** for failures on an established client. Inputs: the driver error (code 18, code + 391, `MongoNotConnectedError` / closed topology, network codes and timeouts) and the WI-1 typed + error. Outputs: + - `signInRequired` (Entra): offer **Sign in again**. + - `credentialsRejected` (Native code 18 after a reconnect): offer **Update credentials**, and + **no automatic retry loop**. + - `credentialsRejected` (final Entra code 18): evict the client. With a verified Entra identity, + keep its in-memory connection settings and offer explicit **Sign in again** (decision 0014). + - `clientClosed`: create a new generation with the same identity. + - `transient` (network or timeout): no eviction, because the driver recovers. Offer Retry. + + Reuse `ErrorExplanationService` for wording. + +- **Sign in again** action: + - It calls `getSession(..., { createIfNone: true, account })` for the pinned account and tenant. + - Same account: evict and create a new generation. Surfaces continue (WI-6). + - Different account: treat it as an identity change (decision 0003). + - **One** prompt per user click. Dismissing it is respected: no reprompt until the user acts again. + - `createIfNone` can return an existing session. Test a still-present but rejected token as well + as a missing session; prove that the explicit action obtains usable credentials in both cases. +- **The tree's Retry must actually reconnect.** + - [retryAuthentication.ts](../../../../../src/commands/retryAuthentication/retryAuthentication.ts) + and the cached-client path in + [ClusterItemBase.ts:358-447](../../../../../src/tree/documentdb/ClusterItemBase.ts) should evict + the client when the last failure was `signInRequired`, `credentialsRejected` or `clientClosed`. + - Keep the cached credentials (#1059 open question 1: dropping the client is not the same as + forgetting the credentials). Exception: for a rejected RU Discovery key, explicit recovery must + reread the primary key from ARM once, not reuse the cached key or open a password wizard. + Test an old/new key pair and distinguish an ARM sign-in failure from database rejection. + - Add **Sign in again** to `createErrorRecoveryChildren` + ([ClusterItemBase.ts:304-326](../../../../../src/tree/documentdb/ClusterItemBase.ts)), following the + "actions only" order in the tree-cluster-architecture skill: repairs first, Retry last. +- **`vscode.authentication.onDidChangeSessions`:** when the bound Entra account disappears, mark its + clients `signInRequired`. Never sign the user out, and never remove sessions (#1059 "must NOT be + touched"). The event identifies the provider, not the removed account. Silently recheck affected + bindings and ignore results from stale generations; another account's change must not disconnect this one. + - **Changed 2026-11-19 (decision [0012](../decisions.md)):** dropped. The next operation's silent lookup + finds a signed-out account and fails with `signInRequired`, with no listener. +- **Unit tests:** + - classifier table tests; + - Retry after `clientClosed` produces a new generation; + - Sign in again with the same account versus a different account; + - no reprompt after a dismissal. + +## WI-6: Bind surfaces to `{ clusterId, fingerprint, generation }` and add a disconnected state (decisions 0002, 0003) + +The largest item. Host side first, then each view. + +- **Host:** + - `ClusterSession` stops holding a `ClustersClient` + ([ClusterSession.ts:65-78, 688-725](../../../../../src/documentdb/ClusterSession.ts)). It records + the binding and resolves the client for each operation. + - Per-operation `getClient` callers that skip any check must check the fingerprint too: + - Document View ([documentsViewRouter.ts:54,91](../../../../../src/webviews/documentdb/documentView/documentsViewRouter.ts)); + - the index router; + - the Query Insights routers; + - [QueryInsightsAIService.ts](../../../../../src/services/ai/QueryInsightsAIService.ts); + - the Cluster Dashboard router. + + The full call-site list is in research §3; rerun + `grep -rn "ClustersClient.getClient(\|\.getClient()" src`. + + - Outcomes: + - same fingerprint and generation: proceed; + - same fingerprint, new generation: re-run the applied query from page 1 with a notice that + results are no longer current. Pages use separate offset queries, not a cursor held between + pages. Discard old-generation responses on both host and UI; preserve unapplied editor text; + - **Changed 2026-11-19 (decision 0010):** transparent: proceed on the current client, with no + re-run and no notice. Any "out of date" indication is + [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106). + - different fingerprint, or no client: **disconnected**, with a reason. + - **The extension never resubmits a write with an unknown outcome.** Report the outcome as + unknown, not as a definite failure. The driver can retry the same logical write or handle 391 + internally; test one application submission when the server accepts a write but its reply is lost. + +- **Webviews:** + - 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 + (dirty editor) and the Cluster Dashboard. + - Accessibility: announce the state change (accessibility skill; live region). +- **Transfer scope:** copy and export may keep their current client or stream. Do not redesign + transfers to rebind per batch or resume after Disconnect. Protect active tasks from an explicit + disconnect using the existing resource-conflict check in WI-7. An unexpected connection loss + is not permission to restart a transfer under another identity. +- **Tests:** + - router tests for the three binding outcomes; + - 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; + - scenarios run through the L2-dev runner (`/scenarios/`, see the copilot instructions). + +## WI-7: Teardown service, Disconnect, Remove and Update Credentials (#1059, #566, decisions 0003, 0004) + +- **One teardown**, keyed by stable `clusterId`, with provider-specific equality. Azure case aliases + must match, but folding Kubernetes context IDs such as `Prod` and `prod` would target different + resources together. Remove = teardown + delete + clear schema; Disconnect = teardown only. + - **Changed 2026-11-19:** provider-specific equality and all Kubernetes tunnel work moved to + [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105), after 1.2.0 (decision + [0009](../decisions.md)). The teardown keeps each store's current `clusterId` matching. + - After the task-conflict preflight below, tear down the client, shells, playground, webviews, in-flight token + requests (sovereign-clouds finding E4), `CredentialCache`, the Entra failure registry, and the + `SchemaStore` decision. + - Its "must NOT be touched" rules apply: VS Code auth sessions, the managed identity cache, the + ARM cache. +- **Disconnect command** on connected clusters in the Connections, Azure Resources and Discovery + views. + - **Check for active tasks first.** Reuse + [`checkCanProceedAndInformUser({ clusterId }, …)`](../../../../../src/services/taskService/resourceUsageHelper.ts) + as [Remove Connection](../../../../../src/commands/removeConnection/removeConnection.ts) already + does. If a copy or export uses this cluster, name the conflicting task and leave **both the task + and connection running**. The user can retry Disconnect after the task finishes or they stop it. + Do not offer force-disconnect or automatically cancel the task. Verify that export registers its + source and copy registers both endpoints; fill registration gaps rather than changing transfer logic. + - Use dashed context keys (manifest rule in the copilot instructions). + - When surfaces are open, ask the user: **Close all** or **Keep open (disabled)** (decision 0004; + default and remembering per Q2). + - Document View is a plain webview panel: `dispose()` has no dirty-editor veto. For Close all, + confirm unsaved edits **before** disposing any panel or changing the connection. Cancelling leaves + every panel, draft and connection intact, including when Remove initiated teardown. +- **Update Credentials** + ([updateCredentials.ts:142-185](../../../../../src/commands/updateCredentials/updateCredentials.ts)) + and Update Connection String compare the old and new fingerprints: + - **same:** the client is replaced and tabs continue; + - **different:** before saving, run the same task and dirty-panel checks as Disconnect. If approved, + tear down with reason "credentials changed", offering the same Close/Keep choice. + - Only replace the client after the credential save succeeds; test that a failed save leaves the + old binding usable and a concurrent connect cannot publish the previous credentials after replacement. + + Today's D12 modal for open shells offers Disconnect as a button (#1059). + +- **Telemetry:** one event with the activation source and teardown counts. No identifiers (#1059). +- **Tests:** + - teardown per surface; + - ~~Azure case aliases vs distinct Kubernetes context IDs;~~ moved to #1105 (decision 0009); + - Disconnect blocked for copy source, copy destination and export source; an unrelated cluster + is not blocked. After the task finishes or is stopped, retrying Disconnect succeeds; + - a late token response after Disconnect is ignored; + - reconnecting uses the current credentials and cloud settings; + - Remove reuses the same teardown. + +## WI-8: Cluster Dashboard health polling + +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 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 overlay, and that reconnect starts only one poll loop. + +## WI-9: Measure token renewal and recovery after release + +The [existing correlation IDs](../../../telemetry-correlation-ids.md) identify a client or worker +startup and optionally link it to cluster metadata. They do **not** tell us when a token changed, +how long it was valid, or whether the database worked afterward. Reuse `startupCorrelationId` +for drill-down and `connectionCorrelationId` where already available; the headline metrics below +must be queryable without a join or a new persistent identifier. + +- **When did a refresh happen?** Emit `connection.tokenRenewal` once per completed post-startup + Entra database token lookup (host, shell or playground), not per query or dashboard tick. + Use the event timestamp, `surface`, and one bounded `renewalOutcome`: `changed`, `unchanged`, + `noSession`, `identityMismatch`, `failed`, or `unknown` when there is no prior observation. + Compare only within the same binding. Exclude initial acquisition; count a valid unchanged + token as successful reuse, **not** a refresh. `changed` means the extension received a + different token, not that it observed an MSAL network request. Count successes as well as misses. +- **What was the lifetime?** On that same event record numeric measurements, not timestamps: + `connectionAgeMs` (age of this client/worker at lookup), `previousTokenObservedAgeSeconds` + (time since the previous token was first seen, not reset by unchanged lookups), + `tokenLifetimeSeconds` (returned token's `exp - iat`) and `tokenRemainingSeconds` (`exp - now` + at lookup). Omit unavailable or invalid measurements; never substitute a worker fallback TTL + or zero for unknown. Do not retain tokens just for telemetry or send token values, hashes, raw + claims, account/tenant IDs, cluster IDs, fingerprints or hostnames. +- **Did the connection actually recover?** Emit `connection.recovered` once on the first successful + database operation after a pending recovery, with trigger (`silentRenewal`, `reconnect` or + `signInAgain`) and `connectionAgeMs`. A callback returning a token is not that success. Keep + WI-4's classified post-connect failures and WI-7's Disconnect event. Report ARM challenges + separately from database renewal and verify the final ARM request, not just token acquisition. + - **Changed 2026-11-19 (decision [0012](../decisions.md)):** no `connection.recovered` event and no + changed-token or remaining-validity measures. `connection.tokenRenewal` keeps its outcome and the token + lifetime; recovery shows as successful operations on a replaced client (`clientGeneration` above 1) + and fewer late failures. +- **Release dashboard and acceptance:** check in runnable queries that show daily renewal outcomes + and changed-token rate (`changed / all completed lookups`), plus p50/p90 token lifetime, + remaining validity and connection age at refresh, split by version and surface. Show sample + counts and missing timing data alongside percentiles. Trend confirmed recoveries by trigger and + late auth/socket/closed-client failures against the pre-release baseline using the same exposure + denominator. No lookups or no subsequent operation is **no evidence**, not success. + Before rollout, use a fake clock and token sequence (unchanged → changed → silent miss) to + verify counts and units; include an opaque token and a database rejection after lookup. Verify + the dashboard can read the classified fields from pre-release ingestion before judging outcomes. + +## WI-10: Documentation + +- User manual: + - Disconnect; + - "Sign in again"; + - what a disconnected tab means and how to resume; + - the Update Credentials note about open sessions. +- Release notes (writing-release-notes skill). +- Skills: + - tree-cluster-architecture: the connection lifecycle rule ("resolve the client per operation; + never hold a `ClustersClient`"); + - error-translation: the new categories. +- This feature's README, plus `docs/ai-and-plans/README.md`. + +--- + +## Operator acceptance tests (run on the installed VSIX at the end) + +These are the minimal checks that confirm the goal. The operator should finish them **without +restarting VS Code** and **without losing any typed text or unsaved edits**. + +**Setup:** + +- one Azure DocumentDB cluster with Entra ID enabled, and a native user on it; +- one RU account reached through Azure Discovery (account key); +- VS Code signed in to the Microsoft account that has access. + +**Test matrix:** RU with Entra ID for the database is **not supported** by the extension (key-based +only), so it is not tested. + +**Long wait:** "Wait ≥ 2 h" means leaving the window idle, for example over lunch or overnight. The +optional WI-4 test hook may shorten this during development. The release check uses a real wait at +least once. + +| # | Scenario | Steps | Pass when | +| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | +| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | +| OT-3 | **Changed connection details** | (a) With a Native tab open, save a different user through Update Credentials. (b) Repeat with a password-only change for the same user. (c) Entra: in OT-2, sign in again with a different account. OP-5 checks the pushed lock on saved edits (decision 0018). | (a) and (b): no tab-choice prompt; the old view immediately offers **Close view** only, with contents still copyable. (c): the old tab cannot run under the new account. Open a new view from the tree. | +| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | +| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | +| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | +| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**. Use **Reconnect** in the tree, then **Retry** in the tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason and content kept. After same-identity reconnect, the auto-opened Dashboard resumes and other views offer **Retry**. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". Remove disconnects and deletes the saved connection. | + +**After release** (telemetry, operator with Kusto access): run the WI-9 queries on the pre-release +cohort. + +**Evidence required for the matrix:** exercise both idle and dropped data-plane connections for +each supported backend/auth pair. For OT-1 record a new handshake or callback after the wait +(never log tokens): a successful read on an existing socket does not prove renewal. For OT-2 +distinguish local sign-out from remote revocation; their timing is not established. For OT-5 +force a new handshake after rotation. For OT-7 also try Disconnect during a tracked copy/export: +verify it is blocked before the Close/Keep prompt and the task continues. + +For WI-9, `challengeSuccess=true` means a challenge token was obtained, not that ARM accepted the +retried request. Check the final operation too. Record the cohort query, time window and exposure +denominator; a cohort with no challenges is inconclusive, and timing alone does not establish cause. + +--- + +## Open questions (to settle before or during WI-5 and WI-7) + +- **Q1:** For a user-initiated action, should the interactive sign-in open **immediately**, or only + through the **Sign in again** button? The proposal is the button everywhere (decision 0001). A + first connect from the tree stays interactive, as it is today. +- ~~**Q2:** The default for the Disconnect choice, and whether to remember it. The proposal is Keep + open (disabled), remembered in `globalState`.~~ **Resolved 2026-11-19:** a VS Code modal with nothing + remembered, plus a setting for the default (decision [0007](../decisions.md)). +- ~~**Q3:** Should Disconnect drop the `CredentialCache` entry (#1059 proposes yes), so a password + typed only for a discovery connection must be entered again?~~ **Resolved 2026-11-19:** no. Disconnect + keeps the cached credentials and the verified identity; only Remove drops them (decision + [0011](../decisions.md)). The WI-7 teardown bullet above still lists `CredentialCache`; read it as + "Remove only". +- **Q4:** Ask the Azure DocumentDB service team whether the server closes connections when the + token expires, and whether it ever sends code 391 `ReauthenticationRequired` (research §1). +- ~~**Q5:** Release slicing. Should WI-1 and WI-2 ship early as a patch (backport skill)? They are + small, isolated and fix the largest group (≥60 machines in 28 days).~~ **Resolved 2026-11-19:** + no. Everything ships at once from the feature branch (decision [0006](../decisions.md)). diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md new file mode 100644 index 000000000..c504800b2 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -0,0 +1,88 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +created: 2026-11-20 +--- + +# PR 1 pre-review: Entra silent renewal + +Reviewed `2666f2ac7..f731f482f` (WI-1 only). GPT-6.2-Sol performed the initial review; +Claude Opus 5.5 validated the findings and performed an independent sweep. The PR was not yet +published, so there were no GitHub review comments to incorporate. + +## F1. Regenerate localization before review + +**Confirmed; blocks full CI.** The five new strings in +[entraCallbackErrors.ts](../../../../../src/documentdb/auth/entraErrors/entraCallbackErrors.ts) +and [EntraSignInRequiredErrorExplainer.ts](../../../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts) +are not in the checked-in bundle. Generate the bundle as already scheduled for Case 2, then run +`npm run l10n:check`. No wording change is needed. + +**Resolved:** `a52f06320` regenerates the bundle with exactly five new keys. `npm run l10n:check` +passed. + +## F2. Typed Entra explanations do not yet reach webviews + +**Confirmed; deferred to WI-5/WI-6.** The existing webview explanation request passes only +an error message. The new explainer needs the typed error or its cause chain. The current +Collection View path can show a generic heading; the detail depends on what survives transport. + +**Advisor recommendation:** Track this in WI-5/WI-6, whose classifier and structured unavailable +response are designed to handle it. PR 1 does not ship separately. The alternative is to add an +allowlisted error name to the current webview request, but that still does not convey driver +server-selection causes and would add call-site changes that WI-6 replaces. Do not match raw +message text or wrap errors solely to transport explanations. + +**Author decision (2026-11-20):** Defer F2 to WI-5/WI-6. PR 1 will not add a temporary webview +transport for typed sign-in errors. + +## Independent sweep + +- **Recovery depends on WI-5.** The driver retains a rejected callback. PR 1 diagnoses the silent + miss but cannot recover that client by signing in again; WI-5 must replace it. +- **Provider-change wording:** `providerChanged` uses the planned expired-sign-in wording. + Changing it would be a separate user-visible decision. +- **Callback failure detail:** The new wrapper uses a bounded message and preserves the original + cause. Do not expose raw cause text as part of this PR. +- **Provider seam:** The installed dependency has a public getter, but the repository's token + resource module does not export a shared getter. WI-1 uses the public getter directly; WI-3 + should check both consumers during the dependency upgrade. + +OP-1b passed with a real cluster: the database list loaded after idle and no sign-in prompt +appeared. That test did not cover webview failure presentation or replacement after a silent miss. + +## Review handoff (2026-11-20) + +Case 2 ran on `6e108f0a3` with the generated localization and formatting applied. Localization, +formatting, localization check, build, test type-check, full Vitest (9,651 passed, one skipped), +and VSIX packaging passed. Lint initially rejected an inline import type in the Entra handler +test. `a0c1d1312` replaced it with a type-only import; full lint, the affected suite (47 passed), +and its formatting check then passed. No runtime code changed in that follow-up. + +## Copilot review follow-up (2026-11-20) + +- **R3, done in `cae1db890`:** Startup telemetry recognizes the three typed Entra callback + failures as `entraToken`, including wrapped and server-selection errors. The callback does not + write startup telemetry. The advisor (`claude-opus-5.5`, 80% confidence) recommended classifying + the error at the existing startup boundary; the leader applied that recommendation directly. + Build and 79 focused tests passed, including three new cases. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641033663). +- **R1, done in `98be5f18e`:** The operator approved pinning the effective cloud and authority. + The handler checks that snapshot before acquisition, after acquisition, and around silent + lookups. The snapshot also covers the wait for token-resource resolution. The advisor + (`claude-opus-5.5`, 85% confidence) approved the revised guard. Build and 137 focused tests passed. + [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641386918). +- **R2, done in `7ed07bd1f`:** The operator kept decision 0001: every callback does a silent + lookup. Diagnostics now reports the callback acquisition that supplies the token to the driver, + or reports an acquisition failure instead of keeping the earlier token facts. Late callbacks + cannot change a finished report. `claude-opus-5.5` approved the implementation at 85% confidence. + Build and 213 focused tests passed for the review fixes. +- **R4, done in `897329a8f`:** The operator approved the actionable account-mismatch heading. It + tells users to sign in with the account originally used for the connection. The error detail + is unchanged. Localization was regenerated and 16 focused tests passed. + [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641336633). +- **R5, deferred to WI-5:** The advisor (`claude-opus-5.5`, 85% confidence) verified from the pinned + driver's source that plain callback errors are not stored in per-server descriptions. They reach + the caller directly, where the existing cause traversal can explain them. WI-5 carries forward + the driver check and the shared explanation path if needed; PR1 does not add a second traversal. + The operator confirmed this deferral. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-final-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-final-review.md new file mode 100644 index 000000000..56d9cbaa9 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-final-review.md @@ -0,0 +1,654 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1136] +--- + +# Final review: Connection lifecycle (combined PR) + +This is the November review, not the current release status. The [feature README](../README.md) +and [scope review](./04-pr1136-scope-and-test-review.md) cover subsequent changes. + +[PR #1136](https://github.com/microsoft/vscode-documentdb/pull/1136) · `feature/connection-lifecycle` → `main` · +reviewed head `559c2f827` (draft) + +This is a whole-feature review of the combined branch (PR0–PR7, about +9.7k/−2.8k production +lines excluding tests and docs). Each stage already had its own pre-review, so this pass does +not repeat them. It looks at four things: + +- whether the feature meets its goal; +- whether failures are both recorded and explained to the user; +- edge cases that threaten the goal; +- over-engineering. + +Claude Opus 5.5 led the review. Four read-only explorer passes covered commands and tasks, +webviews, Shell and Playground workers, and Azure discovery. A separate rubber-duck pass +challenged the draft findings and severities. Its changes are listed at the end. No code was +changed. + +**The goal (operator):** a connection should not just time out or expire while someone is +actually using it. + +**The error-handling rule (operator):** a failure may happen, but we must know it happened +(telemetry, or `meterSilentCatch` for swallowed errors), and the user must see at least some +helpful report. + +## Verdict + +**The goal is met for the main path, with one gap that should be fixed before merge.** + +What works: + +- The root cause from #1102 is fixed. The extension-host OIDC callback no longer returns the + token captured at connect. It now looks up the pinned account silently on every call + ([MicrosoftEntraIDAuthHandler.ts](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts), + about lines 200–260). OP-1b verified renewal after idle without a prompt. +- Shell and Playground workers get the same behavior through the host relay. +- The main surfaces report failures, so a broken client is replaced on the next deliberate + action. These surfaces are tree expansion, Collection View, Document View, Dashboard, Index + view, Query Insights and import. + +What is missing: + +- A single failed token callback permanently breaks that `MongoClient` (driver behavior). + Nothing retires the client centrally, so about 13 command paths that call `getClient` + directly keep failing until a different surface happens to report the failure (F1). +- The first **write** after token expiry has not been verified (F2). OP-6 has to cover it. + +Nothing here argues against the architecture. Most findings are small, local fixes. + +## Summary + +| # | Severity | Finding | Fix size | Decision | +| --- | -------- | ------------------------------------------------------------------------------------------------- | ---------------------- | ------------------------- | +| F1 | High | A failed token callback leaves a dead client cached for direct `getClient` paths | ~10 lines + test | Accepted | +| F2 | Medium | First write after token expiry is unverified (`retrywrites=false`) | Gate (OP-6) | Accepted (OP-6 scenarios) | +| F3 | Medium | Webview operations blocked by the connection are recorded as RPC **success** with no reason | ~5 lines | Accepted (amends 0020) | +| F4 | Medium | A hung token lookup costs 60 s per operation, is classified `other`, and leaves no renewal record | Small | Accepted | +| F5 | Medium | Partial Azure subscription listing is reported only in the output channel | Small | Accepted | +| F6 | Low | Swallowed failures that hide real problems are not metered | Small, mechanical | Accepted | +| F7 | Low | Explain-then-display chains have no fallback if the explain RPC fails | 1 line × 4 | Accepted | +| F8 | Low | Collection View shows a generic error modal for a client marked for replacement | Small | Accepted | +| F9 | Low | Ships the prerelease `@microsoft/vscode-azext-azureauth` `6.1.0-alpha.2` | Track (accepted, 0008) | Accepted (no code change) | +| O1 | Medium | Over-engineering: lifecycle plumbing copied into three React views | Medium | Accepted | +| O2 | Low | Over-engineering: `retryAuthentication` decides policy by looking at view IDs in `contextValue` | Small | Accepted | +| O3 | Low | Over-engineering: `ClustersClient` keeps growing as the home for all lifecycle state | None in this PR | Accepted (no change) | + +There are no Critical findings. + +## Operator decisions (2026-11-26) + +The operator accepted every finding and proposal in this review as a set: F1–F9 and O1–O3. +Acceptance covers the recommended outcomes and constraints, including the validation-only, +tracking and no-change dispositions below; it does not mean implementation or verification is +complete. The lead and advisor prepare the work-item plan and model assignments, and resolve +implementation details within that accepted scope. + +All code and documentation changes land in **one dedicated PR against +`feature/connection-lifecycle`**. The operator's branch-protection correction supersedes the +earlier instruction to commit this review to the feature branch: carry the review and plan on +the new PR branch instead. This review is its first commit. Do not commit or push directly to +the feature branch. Avoiding over-engineering remains a constraint for every item. + +## Follow-up work plan + +The numbered findings below are the work ledger: F1/F4 shared the client and auth tests; +F3 and the Azure partial-listing fix could land independently. O1's recovery hook preceded +F7's error fallback. F9 and O3 required no code. For the original WI-01–WI-12 assignment and +acceptance matrix see the [review at the pinned revision](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-final-review.md#follow-up-work-plan). + +OP-6, CP-5 ingestion and workbench results are recorded separately from the implementation +items. A Save wording follow-up is conditional on an observed OP-6 failure, not a queued +implementation item. The known out-of-scope cases are the additional explain-then-display +chains, a new timeout mechanism, write replay or probes, and automatic retry policy changes. + +> **WI-11 done (2026-11-26), commit `b10fa6e84`, leader (docs only, no coding worker):** +> Recorded the operator's F3 amendment to 0020 without expanding it, documented the new +> fields, and updated the CP-5 gate and Azure Discovery documentation. Leader review (99%): +> the docs describe the committed telemetry semantics and do not claim successful ingestion. +> No automated tests added; CP-5 remains pending. + +--- + +## F1. A failed token callback leaves a dead client cached (High) + +**Why it matters for the goal.** This is the scenario the feature exists for: a long session, +a laptop waking up, a VPN switch. One silent renewal fails briefly because the network is not +up yet. That should cost one operation, not leave the connection stuck. + +**Evidence** + +- In mongodb 7.2.0, `CallbackWorkflow.withLock` runs `await lock` **before** it reassigns + `lock`. After one rejected `OIDC_CALLBACK`, every later callback on that `MongoClient` + rethrows the same rejection + (`node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js:108-124`). Recovery + needs a new `MongoClient`. +- A cached `ClustersClient` is retired in only two ways: + - `ClustersClient.reportFailure` + ([ClustersClient.ts:1163](../../../../../src/documentdb/ClustersClient.ts)) sets `_replacement`; + - the `topologyClosed` event sets `_closed` (`canReuse()`, line 1143). + + A poisoned callback does neither, because the topology stays open. + +- The OIDC wrapper in `connect()` + ([ClustersClient.ts:765-778](../../../../../src/documentdb/ClustersClient.ts)) only records + token expiry. It does not mark the client when the callback throws. It is also installed + only for Microsoft Entra ID. Managed identity uses the same driver workflow + ([ManagedIdentityAuthHandler.ts:104](../../../../../src/documentdb/auth/ManagedIdentityAuthHandler.ts)), + so it is exposed in the same way. +- `reportFailure` is called from `runWithClient`, `boundViewOperations`, `ClusterItemBase`, + `DatabaseItem`, `IndexesItem` and `importDocuments`. These callers get a client directly + and never report: + - `deleteDatabase.ts:78`, `deleteCollection.ts:72`; + - `dropIndex.ts:46`, `hideIndex.ts:51`, `unhideIndex.ts:46`; + - `pasteCollection/ExecuteStep.ts:70`, `pasteCollection.ts:106`; + - `queryGenerationCommands.ts:187`, `scanCollectionSchema.ts:37`; + - `CopyPasteCollectionTask.ts:120,169`, `DocumentDbDocumentReader.ts:62,92`; + - `CollectionItem.ts:135`, `openClusterDashboard.ts:119`, `getIndexConfirmationStats`. + +**Effect.** After one transient renewal failure: + +- Delete, drop/hide/unhide index, paste, copy-and-paste, AI query generation and schema scan + fail with driver or token text. +- **Running the same command again fails again.** It only recovers when something that + reports happens to run, such as a tree Refresh or a Collection View query. +- The main surfaces heal on the next action, which keeps this at High rather than Critical. +- This is still better than `main`, which never retires a client, but it is the gap most + directly against the goal. + +**Recommendation** + +- In `connect()`, wrap `OIDC_CALLBACK` for **every OIDC auth method** (Entra and managed + identity). +- On a throw, set `this._replacement ??= 'replaceOnNextForeground'`, but only once + `this._binding` exists. The binding is assigned only after the client is established, so + startup failures stay with `establishClient`. +- **Do not** call the full `reportFailure` from inside the callback. The rubber-duck pass + showed why: an identity-mismatch eviction there would remove the client before the + operation reports. The operation's own `reportFailure` would then return `undefined`, so + `runWithClient` would lose the typed `unavailable` result and `ClusterItemBase` (about + line 449) would skip its recovery message. +- Setting only the lowest replacement state keeps the client cached. A later report can still + upgrade it to `replaceOnRecovery`, or to evict plus latch. +- Add one test: reject one callback, call through a direct `getClient` path, and confirm the + next foreground call gets a new generation. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- Wrap `OIDC_CALLBACK` in `connect()` for Microsoft Entra ID and managed identity. +- On a throw, set only `replaceOnNextForeground`, and only once the client is bound. +- Never call `reportFailure` from inside the callback. +- Add one regression test through a direct `getClient` path. + +> **Done (2026-11-26), commit `6eb089ac4`, `gpt-6.1-sol`:** Both OIDC modes +> mark a bound client for replacement if the callback rejects, without evicting it or +> changing the thrown error. The accepted operator decision governs the scope; advised +> (`claude-opus-5.5`, 85%) that startup, replacement precedence and recovery remain +> intact. Added two parameterized direct `getClient` cases. Renewal assertions for +> startup suppression, result/outcome and lifetime fields, cached identity, abort, +> stale epoch, retired and closed clients remain; the rejecting lookup now runs last +> on a fresh generation. Expiry and explicit recovery tests retain their original +> assertions. Focused Case 1 run: 127 tests passed across WI-01 and WI-03. + +## F2. The first write after token expiry is unverified (Medium, gate) + +**Evidence** + +- OP-1a ([01-dev-plan.md](./01-dev-plan.md), about line 625): after two hours idle, the + server **closed** fresh sockets that tried to authenticate with the expired token. It did + not return code 18. +- OP-1b passed because `listDatabases` is a read, and the driver retried it on a second + socket. +- Azure connection strings commonly set `retrywrites=false`, and decision 0009 defers pool + and network hardening to #1105. +- The likely result: when the first operation after expiry is a **write** (Document View + Save, insert, delete, index create), it fails once with `MongoNetworkError`. The user + then retries and succeeds. That is a visible "the connection expired while I was using + it" moment. + +**Recommendation.** Do not replay writes automatically. Make the uncertainty explicit in +OP-6: + +1. After at least 2 h idle, make a **write the first operation**: a Document View Save on a + connection whose string has `retrywrites=false`, with no read beforehand. +2. Keep using the connection across a token expiry, for example a query every few minutes for + 90 minutes. +3. Test sleep and wake across an expiry, and Shell and Playground after expiry. + +If step 1 fails, fix the user-facing message first. It should tell the user to try again +and must not claim the write was not applied (F-22). A cheap read before a foreground write, +once the recorded token expiry has passed, is an option to weigh. Leave the broader pool +tuning to #1105. + +**Operator decision (2026-11-26):** Accepted. + +- In this PR, add the three F2 scenarios to OP-6 in [01-dev-plan.md](./01-dev-plan.md): the + OP-6 row at about line 93 and its PR F step 3. +- No automatic write replay. +- No pre-write read probe in this PR. It would need its own decision next to decision 0010. +- The message change is conditional: implement it only if OP-6 step 1 fails. Do not implement + it speculatively. + +> **WI-10 documentation done (2026-11-26), commit `10badbc0d`:** Added all three +> scenarios to the OP-6 row and PR F step 3. Operator decision: validation only (explicit +> acceptance); leader confirmed the plan includes the no-read/no-replay constraints. +> No automated tests added. **OP-6 pending:** run on the packaged VSIX and record actual +> outcomes. Do not change the Save message unless the first-write scenario fails. + +## F3. Blocked webview operations look like successes in telemetry (Medium) + +**Evidence** + +- The tRPC telemetry middleware + ([trpc.ts:147-173](../../../../../src/webviews/_integration/trpc.ts)) sets outcome + properties only for abort, cancellation and thrown errors. +- A procedure that returns `{ unavailable: { reason } }` is recorded as SDK `succeeded` with + no reason. The PR7 telemetry doc and decision 0020 acknowledge this. Renewal telemetry + (`connection.tokenRenewal`) captures some of the root causes. +- Even so, we cannot count how many **user operations** were blocked, or on which surface, + which is exactly what CP-5 and later regressions will need. + +**Recommendation** + +- In the middleware, when the result has `unavailable.reason`, set a bounded property, for + example `unavailableReason`. +- Do not put "error" or "exception" in the property name. The azext whole-error masking + redacts any property named that way. +- Add the property to [telemetry.md](../telemetry.md). + +This does not need the deferred cross-release comparison. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- This amends decision 0020 ("Do not add an instrumentation path … in this release") and the + PR7 review F1 author decision ("do not add a telemetry field"), for this one bounded property + only. +- The cross-release comparison stays deferred. +- Record the amendment as a factual note under decision 0020 in + [decisions.md](../decisions.md), citing this decision. + +> **Done (2026-11-26), commit `42dfc2332`, `mai-code-2`:** The RPC adapter records +> only the validated reason from an unavailable response; it leaves the SDK outcome +> and existing cancellation/error handling alone. Operator decision: bounded +> amendment to 0020; leader review (99%) reused the existing response guard rather +> than duplicating the allowlist. Added three regressions: valid reason, ordinary +> success, and unknown reason. Focused Case 1 run: 127 tests passed across WI-01 and +> WI-03. CP-5 ingestion has not been run; WI-11 records the decision and query. + +## F4. A hung token lookup costs 60 s per operation and is classified `other` (Medium) + +**Evidence** + +- The driver races the callback against a 60 s timeout and throws `MongoOIDCError` + (`node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js:67-75`). + The real callback, and with it the driver's lock, stays pending. +- `classifyConnectionFailure` has no case for `MongoOIDCError`, so it returns `OTHER` with + `keep` ([connectionFailures.ts](../../../../../src/documentdb/connectionFailures.ts), about + line 123). The client is never retired. +- As a result, every new socket on that client waits up to 60 s and then fails with + "OIDC callback timed out after 60000ms." +- In workers, an aborted callback suppresses its `connection.tokenRenewal` event + ([WorkerTokenRelay.ts:101-104, 248-250](../../../../../src/documentdb/auth/WorkerTokenRelay.ts)), + so a hung VS Code auth provider leaves no renewal record. + +The trigger is rare: VS Code's silent `getSession` has to hang. When it does happen, though, +the connection looks broken for the rest of the session. + +**Recommendation** + +- Classify the callback timeout as `transient` with `replaceOnNextForeground`. +- Emit a bounded `timedOut` renewal outcome instead of suppressing it. +- Do not add a parallel timeout mechanism. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- Reclassify only the driver's callback timeout. Every other `MongoOIDCError` keeps its current + classification. +- Add `timedOut` to the documented renewal outcomes in [telemetry.md](../telemetry.md). +- Add no timeout of our own. + +> **Done (2026-11-26), commit `b324be7b4`, `gpt-6.1-sol`:** The exact driver's +> callback timeout requests replacement on the next foreground action. Other OIDC +> errors keep their existing classification. The existing Entra observation scopes +> now record `timedOut`: at abort in the host and at settlement after driver abort in a +> worker. Operator decision: no additional timer; advised (`claude-opus-5.5`, 85%) +> that abort, stale epoch and cancellation guards are preserved. Added nine focused +> cases and the `timedOut` expectation to the existing Shell/Playground test; retained +> all prior assertions. Six focused suites passed (319 tests, including WI-04). +> A hung real provider was not exercised; a never-settling worker lookup cannot emit +> the renewal row. + +## F5. Partial Azure listings are reported only in the output channel (Medium) + +**Evidence** + +- `errorForAccount` and `errorForTenant` write only `ext.outputChannel.warn` + ([AzureSubscriptionProviderWithFilters.ts:107-113](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts)). +- `getUnfilteredAzureTenants(...).catch(() => undefined)` in + [SelectSubscriptionStep.ts:58](../../../../../src/plugins/api-shared/azure/wizard/SelectSubscriptionStep.ts) + and in the three discovery root items swallows the failure completely. +- The user sees fewer subscriptions or tenants than expected, with no hint, and we have no + count of how often it happens. + +**Recommendation** + +- Add bounded counters, `skippedAccounts` and `skippedTenants`, to the listing event. +- Show one non-modal hint per listing, for example in the tree item description or a single + warning with "Show output". No dialog per tenant. +- Meter the tenant-lookup catches. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- **Hint:** one helpful non-modal report per partial listing, with no per-tenant dialogs. + The lead and advisor select the simplest suitable presentation from the recommended + alternatives; the operator has not selected a specific UI option or warning text. +- **Telemetry:** record bounded skipped-account and skipped-tenant counters using the existing + telemetry mechanism. +- **Catches:** add `meterSilentCatch` to the tenant-lookup catches in `SelectSubscriptionStep.ts` + and in the three discovery root items. +- Specify the presentation and any user-facing text in the work item. + +> **Done (2026-11-26), commit `d676501c6`, `mai-code-2`:** Return the available +> subscriptions and show one warning with **Show Output** alongside numeric, identifier-free +> counters; meter the four tenant-lookup catches. Operator decision: one non-modal hint. +> Advised (`claude-opus-5.5`, 88% design, 90% review): scope counters to each SDK listing; +> callers coalesced by the SDK share one event and hint. Added an overlapping-listings case and +> extended the existing partial-listing test without removing assertions. Corrected two test +> types after the first build; the Case 1 build and 188 focused tests passed on retry. +> Workbench check with a failing Azure tenant remains pending. + +## F6. Swallowed failures that hide real problems are not metered (Low) + +The PR adds about 75 `catch` blocks in production code and 4 `meterSilentCatch` calls. Most +uncovered catches are legitimate: close-on-cleanup, abort, or rethrow after recording. Leave +those alone. The ones below either hide a meaningful failure or misreport it. Each should get +`meterSilentCatch('')`, with no UI: + +| Location | What is lost | +| --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [CollectionItem.ts:140](../../../../../src/tree/documentdb/CollectionItem.ts) | The count becomes `null`. It can be the first sign of a poisoned client (F1), and nothing records it | +| [IndexesItem.ts:134](../../../../../src/tree/documentdb/IndexesItem.ts) | A search-index lookup failure is shown as "not supported". An auth failure looks like a feature gap | +| [getIndexConfirmationStats.ts:32,43](../../../../../src/commands/index.shared/getIndexConfirmationStats.ts) | Size and usage stats silently disappear from the confirmation | +| [ClustersClient.ts:924,1192](../../../../../src/documentdb/ClustersClient.ts) | Failure to close an evicted or superseded client is logged at debug level only | +| [MicrosoftEntraIDAuthHandler.ts:259,299,322](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts) | Failures in the observer and in telemetry eligibility. Correct to swallow, but invisible | +| `SelectSubscriptionStep.ts:58` and the three discovery root items | Tenant lookup failure (see F5) | + +These are fine as they are: + +- the driver close-cleanup catches at `ClustersClient.ts:1111,1119,1135`; +- the relay serialization catch at `WorkerTokenRelay.ts:299` (promise-chain hygiene; the + current request still propagates its error); +- the Shell and Playground catches at `ShellSessionManager.ts:289,366` and + `WorkerSessionManager.ts:764`, which record and rethrow; +- `DisconnectedOverlay.tsx:65`, where the user sees a message and the RPC failure is already + recorded by the middleware. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- Add `meterSilentCatch` at the locations in the first table. Add no UI. +- Leave the "fine as they are" catches unchanged. + +> **Done (2026-11-26), commits `5cfb3de05` (`gpt-6-luna`) and `d676501c6` +> (`mai-code-2`, Azure overlap):** Added stable silent-catch counters without changing +> UI or control flow. Operator decision: meter only the listed swallowed failures; +> advised (`claude-opus-5.5`) that the Entra telemetry eligibility and observer catches +> are the intended sites, rather than the nearby rethrows. Leader spot-check (99%) found +> only the approved calls and imports. No new tests for the mechanical meters; 188 focused +> tests passed across WI-04/WI-05 and the related client/auth suites. + +## F7. Explain-then-display chains have no fallback (Low) + +**Evidence.** Retry and Save failures call +`trpcClient.common.explainOperationFailure.query(...)` inside an async `.catch` and then +display the result. If the explain query itself rejects, the inner `await` throws. The +notification is skipped, and the rejection goes unhandled. The affected places: + +- [documentView.tsx:397-410](../../../../../src/webviews/documentdb/documentView/documentView.tsx) + (**Save**) and line 458 (Retry); +- [CollectionView.tsx:859](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx); +- [ClusterDashboard.tsx:753](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx). + +`ErrorExplanationService.explain` catches provider errors internally, so only a transport +failure triggers this. That is why it is Low. + +**Recommendation.** Add `.catch(() => null)` to the explain query so the fallback text +("Error saving the document", "Unable to recover the connection") always shows. With O1 this +becomes a single fix. + +**Operator decision (2026-11-26):** Accepted as recommended. + +- If O1 lands first, fix the Retry chains once, in the shared hook. +- Fix the Document View **Save** chain separately; it is not part of the Retry flow. + +> **Done (2026-11-26), commit `47e1a93c1`, `gpt-6-luna`:** Retry and Save use +> their existing fallback wording and original operation error if explanation fails. +> Operator decision: restrict the fix to these chains. Leader review (98%): report +> the explanation failure through the existing webview event pipe without error +> text or identifiers and without waiting for delivery before showing feedback. +> Added one focused regression for each path; both passed. No change to Save +> wording or write behavior. + +## F8. Collection View shows a generic error modal for a client marked for replacement (Low) + +**Evidence** + +- `runWithClient` turns only `signInRequired`, `credentialsRejected`, `credentialsMissing` + and `identityChanged` into `unavailable` + ([runWithClient.ts:22-32](../../../../../src/documentdb/runWithClient.ts)). +- `transient` and `clientClosed` are rethrown, so the query shows "Error while running the + query" with driver text. The host has already marked the client for replacement, and the + next query works. +- `boundViewOperations.ts:93-104` maps `clientClosed` to `unavailable` for the Dashboard and + Document View, so the views behave differently. + +The user does see a report, so this is acceptable. Optional: for `clientClosed`, say "The +connection was reopened. Run the query again." Do not add an overlay for transient errors. + +**Operator decision (2026-11-26):** Accepted. + +- Collection View query errors only: show text, no overlay, and no change to `runWithClient` + semantics for other callers. +- Implementation note: the host attempts replacement on the next run, not before it, so + "reopened" would be inaccurate. Use truthful retry guidance rather than claiming recovery + already succeeded; the lead and advisor specify the wording during planning. + +> **Done (2026-11-26), commit `5f8b5280c`, `mai-code-2`:** Only a Collection +> View query that actually ran and left its current same-epoch client marked for +> replacement adds “Run the query again to retry the connection.” The original message +> and cause remain available, the overlay is unchanged, and no query is replayed. +> Operator decision: truthful query-only guidance; advised (`claude-opus-5.5`, +> 85% design, 88% review) to exclude startup, stale and latched failures and preserve +> the original cause classification. Added two cases covering a marked client and a +> startup failure. All 109 focused tests passed; workbench verification is pending. + +## F9. Prerelease `azureauth` dependency (Low, accepted) + +`@microsoft/vscode-azext-azureauth` `6.1.0-alpha.2` +([package.json:171](../../../../../package.json)) was accepted in decision 0008 because Azure +Resources ships the same version. The pin is not a defect in itself. Track the GA release, and +re-run the ARM renewal check when upgrading. + +**Operator decision (2026-11-26):** Accepted. No code change in this PR. + +> **WI-12 disposition recorded (2026-11-26):** Operator decision: retain the +> prerelease pin (explicit acceptance, decision 0008). Track GA here; rerun the ARM +> renewal check on upgrade. No code, tests, or new GitHub issue. + +--- + +## Over-engineering + +The design mostly honors decision 0012: + +- no manager or state machine; +- plain maps keyed by `clusterId`; +- one stateless operation wrapper (`runWithClient`). + +Generation, epoch and fingerprint fencing is **justified** complexity. It is what makes +Disconnect, Update credentials and Sign in again safe against late results, and it is +unit-tested. `connectionFailures.ts` (164 lines) is proportionate. + +### O1. Lifecycle plumbing copied into three React views (Medium) + +- `ClusterDashboard.tsx` (+686), `CollectionView.tsx` (+609) and `documentView.tsx` (+289) + each contain roughly 100–160 lines of the same pattern: + - `unavailable` state plus a mirroring ref; + - an operation-revision guard; + - a Retry handler (recover, update unavailable, clear on success, explain, display); + - overlay wiring. +- There is no shared hook. F7 shows the cost: one defect, written three times. + +**Suggestion (follow-up):** a small `useBoundViewRecovery()` hook that owns the +unavailable/revision/Retry flow. Make it a hook, not a manager. + +**Operator decision (2026-11-26):** Accepted, in this PR. + +- One small hook used by the three views. Keep behavior the same. +- Keep the hook local to the lifecycle webviews (decision 0016). Make no change to the webview + framework. + +> **Done (2026-11-26), commit `42d23a082`, `gpt-6.1-sol`:** The views share +> recovery state and the Retry/Close flow. Dashboard keeps its reconnect listener +> and reset policy; Collection keeps its extra revision advance; per-view busy +> state, dismissal and dirty-document protection remain local. Operator decision: +> share plumbing only. Advised (`claude-opus-5.5`, 90%) that guards, announcements +> and listener identities are preserved. Added 13 hook cases; 18 focused tests +> passed. Actual workbench behavior is pending verification. + +### O2. `retryAuthentication` decides policy by looking at view IDs (Low) + +- The `credentialsRejected` branch + ([retryAuthentication.ts:76-104](../../../../../src/commands/retryAuthentication/retryAuthentication.ts)) + works out the view from `contextValue` with regexes and tree-ID prefixes. +- It then combines quick-start, native-discovery and `readReplacementKey` rules to decide + whether Retry may clear the latch. Some branches return without telling the user anything. +- It is correct today but hard to reason about. + +**Suggestion (follow-up):** give the node a typed capability, for example +`canRetryRejectedCredentials()`, so the command stops encoding presentation details. + +**Operator decision (2026-11-26):** Accepted, in this PR. + +- Keep behavior the same: the same nodes may clear the latch. +- Add no new messages, and do not change the existing silent returns. + +> **Done (2026-11-26), commit `95def372a`, `mai-code-2`:** The node exposes typed +> retry eligibility using its model view and `clusterId`; the command keeps its +> distinct key-read and refresh behavior. Operator decision: preserve recovery +> eligibility and silent returns; advised at planning (`claude-opus-5.5`), with +> leader parity review (98%). Added four characterization cases: native Azure +> Resources, implicit native Discovery, missing Discovery credentials, and +> unsupported Azure Workspace. All 60 focused cases passed before and after the +> refactor. An isolated mock reset fixed a leaked fixture value without changing +> assertions. Live tree recovery remains unverified. + +### O3. `ClustersClient` is the home for all lifecycle state (Low) + +`ClustersClient.ts` grew by 727/−120 lines to 2,084 lines. It now has 5 static maps and 24 +public statics. It mixes the driver wrapper, the client cache, lifecycle policy, the identity +pin and startup telemetry. Each piece is reasonable, and no abstraction layer was added. +Leave it for this PR. Later, consider moving the static lifecycle registry (epochs, latches, +generations, pending startups) into its own module, so the class is easier to read. + +**Operator decision (2026-11-26):** Accepted as written. No change in this PR. The extraction +stays a possible later follow-up and is not scheduled. + +> **WI-12 disposition recorded (2026-11-26):** Operator decision: no extraction in +> this PR (explicit acceptance). No code or tests. + +### Considered and not raised + +- **`WorkerTokenRelay` (302 lines)** runs logic parallel to the host callback: identity pin, + destination check, JWT times, renewal telemetry. The worker's IPC, epoch fencing and + worker-facing errors justify a separate orchestrator. Share pure checks where that is easy; + do not merge the two lifecycles. +- **Three near-identical Azure discovery root items** (+24–26 lines each): the duplication was + already there. Leave it. +- **`TreeElementWithExplicitReload.ts`** (17 lines, one user): trivial. + +## Edge cases deliberately not raised + +- **Native `credentialsRejected` recovery.** Update credentials clears the latch, even when the + password is unchanged (`saveConnectionEdit.ts`). Retry handles discovery, quick-start and + key-reading nodes. The silent return on Retry for a native Connections View node is not + reachable from the tree, which offers Update credentials instead. +- **Latch leaks on update or removal.** Both `saveConnectionEdit` and the removal teardown + restore or clear the latch in `finally`. No path leaves a connection locked without a + message. +- **Mixed-server topology classification and teardown races.** These were covered in the + stage reviews. +- **Transfers across a network drop.** The streaming writer's `RetryOrchestrator` already + retries network errors. The remaining risk is F1, a poisoned client, not the network. + +## Done well + +- Silent renewal on every callback invocation for the pinned account, with no prompts and + typed errors (`EntraSignInRequiredError`, `EntraIdentityMismatchError`, + `TokenCallbackError`). +- Single-flight startup, generation and epoch guards, and background callers that never + start a client. +- The tree shows failures as a modal plus recovery actions only, never error rows. +- Bound views keep drafts and data while the connection is unavailable, and recover in place. +- Shell and Playground discard a worker after a callback failure and respawn it on the next + command without the user doing anything. They show "Sign in again" only when a sign-in is + actually needed. +- Disconnect, Update credentials and Remove run through one teardown path with task-conflict + checks, and folder deletion uses it too. +- The ARM credential renews on every `getToken` (azureauth v6). +- Teardown telemetry handles cancellation correctly, despite the azext wrapper swallowing + `UserCancelledError` (`connectionTeardown.ts:263-304`). + +## Recommended gates before ready-for-review + +1. Fix F1 (central retirement for Entra and managed identity, plus a test through a direct + `getClient` path) and F4 (timeout classification). +2. Add `unavailableReason` (F3) and document it in [telemetry.md](../telemetry.md). +3. OP-6 on the packaged VSIX, with the F2 scenarios: first operation a write after at least + 2 h idle; continuous use across an expiry; sleep and wake; Shell and Playground after + expiry. +4. CP-5 ingestion check, including the new property. +5. Case 2 checks and the remaining CONTRIBUTING §6.1 standard-context verification. + +**Draft verification (Case 1, 2026-11-26):** `npm run build` passed for the final +production changes. The final focused Vitest run passed 430 tests in 15 files; +no `TDD:` contract failed. The initial Azure build errors were test typing and +were fixed before push. The final first run had one non-`TDD:` fixture-isolation +failure; both the focused retry suites and the full focused batch passed after +resetting the fixture between cases. Case 2 was not run. Generate localization +for the new Azure warning and Collection View retry guidance in Case 2. + +F1–F8, O1 and O2 land in the dedicated PR described under +[Operator decisions](#operator-decisions-2026-11-26). F9 and O3 need no code change. + +### Pending operator checks in the workbench + +- **Bound views:** Open Collection View, a modified Document View, and Dashboard. Disconnect the + cluster, choose **Keep open**, dismiss the overlay with **X**, and try an operation. The + existing contents remain copyable and the overlay returns without submitting the operation. + Reconnect in the tree and use **Retry** in retained views; check the recovery announcement, + Dashboard's automatic Retry when reopened for the same identity, and the dirty Document View's + confirmation on **Close view**. +- **Collection query:** With a client that must be replaced, run a query and check the error + detail says to retry without asserting that reconnection succeeded. Run the query again and + check the result. Do not count the guidance itself as a recovery. +- **Azure Discovery:** With an account or tenant that cannot be listed, expand or refresh the + provider. Check that available subscriptions remain visible, one warning appears for the + partial listing, and **Show Output** opens the sanitized diagnostic. +- **Tree recovery:** With rejected credentials, check **Retry** for Quick Start and native + Discovery, and **Update credentials** on the saved connection. For a key-reading Azure + node, check that Retry obtains one fresh key and does not start another read automatically. + +## Rubber-duck adjustments + +The rubber-duck pass made these changes to the draft: + +- **F1** went from Medium-High to **High**, and its scope grew to include managed identity. +- **F1's fix** was narrowed: mark `replaceOnNextForeground` only, never call `reportFailure` + from inside the callback. +- **F4** was added as a separate finding (the driver timeout path on host clients). +- **F9**, the alpha dependency, went from High to **Low**: it was explicitly accepted, and + OP-6 and CP-5 are the real release risks. +- A native Retry finding was dropped because the path cannot be reached from the tree. +- **F7** stayed at **Low**, even though the rubber-duck rated it Medium, because the explain + service already catches provider errors. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md new file mode 100644 index 000000000..5fc8cda8d --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md @@ -0,0 +1,1122 @@ +--- +feature: connection-lifecycle +kind: ux-review +status: historical +prs: [1136] +created: 2026-11-27 +--- + +# Connection lifecycle — UX Review Pack + +> **Historical review, 2026-11-27.** The F-items distinguish what the operator saw from +> what the source suggested. “Open” and quoted UI text refer to this pass, not today's +> extension. The [next iteration](./02-ux-implementation-plan.md) records what was +> authorized, implemented, deferred and tested. + +- **Feature area:** connection-tree recovery; Disconnect / Reconnect; saved credential + and destination edits; Collection, Document and Dashboard views; Interactive Shell; + Query Playground; Azure Discovery account / tenant flows. +- **PR / branch:** [#1136](https://github.com/microsoft/vscode-documentdb/pull/1136) · + `feature/connection-lifecycle` · draft. +- **Code snapshot:** [`402b8e052`](https://github.com/microsoft/vscode-documentdb/commit/402b8e05251a5e2e688ac5d4a8eba8e8ce520139). + This iteration is evidence about that revision, not a promise of current behavior. +- **Related design docs:** [feature overview](../README.md), + [accepted decisions](../decisions.md), [implementation plan](./01-implementation-plan.md). +- **User-facing reference:** [connection and recovery manual](../../../../user-manual/connecting-to-databases.md). +- **Scope:** interaction, feedback, recoverability, retained work, identity continuity, + and cancellation. Internals appear only to explain visible behavior. Infrastructure + resilience beyond this PR, proactive account sign-out and stale-result indicators + remain follow-ups #1105, #1119 and #1106, respectively. +- **Review date:** 2026-11-27. + +For sample messages and review questions, see [Appendix C](#appendix-c--message-walkthrough-what-the-user-sees-and-when). +The [unabridged review pack](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md) +preserves the full diagrams, message templates and source citations. Relative source +links name the files; their line numbers refer to `402b8e052`. For current intent, use the overview and manual: +explicit Disconnect now leaves retained views read-only even after Reconnect. + +## How this review was run + +The assistant traced the manifest, commands, tree, views, workers and Azure flows to seed +F1–F6. The operator then drove the extension and dictated observations, checked here +against source; transcripts omit the test hostname. Only an explicit operator decision +settled a recommendation. + +**Case 1 preparation:** `npm run build` passed and local references resolved. No runtime +tests ran for the docs change. Case 2 (including `prettier-fix`) was deferred on the draft; +this was neither an AI code review nor a packaged-VSIX or telemetry gate. + +## Legend + +### Priority + +| Priority | Meaning | +| -------- | -------------------------------------------------- | +| **P0** | Blocking — the user gets stuck | +| **P1** | Broken / misleading, or a consistency & safety gap | +| **P2** | Polish, expectation, or a smaller feature gap | +| **P3** | Nice-to-have / cosmetic / acknowledged | + +### Status + +| Status | Meaning | +| ------------------ | ------------------------------------------------------------------------ | +| 🟠 **Open** | Recorded + analyzed; carries a recommendation but stays a _suggestion_ | +| 🟡 **Open (soft)** | Open, but the recommendation depends on an investigation or is "as-is" | +| ✅ **Implemented** | A change was made on this branch and verified (Decision + commit link) | +| 🚫 **Closed** | Won't fix — with a mandatory one-line reason | +| 🔗 **Tracked** | Deferred to a repo issue (linked); dropped from the active priority list | + +> Anything unresolved carries forward to the next iteration. An item leaves the active +> list only as Implemented, Closed with a reason, or Tracked with an issue link. + +### Markers (inline) + +| Marker | Meaning | +| ----------------- | ------------------------------------------------------- | +| ⚠️ **Flag** | Confirmed gap or bug | +| 💡 **Suggestion** | A design/wording recommendation to react to | +| 🔍 **Answered** | A "how does this work?" question answered from the code | + +Recommendations without an explicit decision remained open. + +--- + +## User interaction map + +Use I1–I13 for tree entry, repair and teardown; I14–I19 for retained views and +transfer guards; I20–I25 for workers, Azure and diagnostics. The inventory identifies +where each action ended. + +### Interaction inventory + +The primary tree source is +[ClusterItemBase.ts](../../../../../src/tree/documentdb/ClusterItemBase.ts); +the command surface and gating are in [the manifest](../../../../../package.json#L1349) +and [command registration](../../../../../src/documentdb/ClustersExtension.ts#L1014). + +| # | User action / entry | Implementation reference | Terminal states / feedback | +| --- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| I1 | Expand cluster in Connections, Discovery or Azure Resources | [connect and expand](../../../../../src/tree/documentdb/ClusterItemBase.ts#L153) | Cancellable progress; databases; modal + repair rows; cancellation without an error dialog | +| I2 | Click Create Database / Create Collection in an empty tree | [cluster empty state](../../../../../src/tree/documentdb/ClusterItemBase.ts#L649), [database empty state](../../../../../src/tree/documentdb/DatabaseItem.ts#L97) | Creation wizard, result/refresh or command error; cancel leaves the empty state | +| I3 | Expand an existing database or Indexes node | [database](../../../../../src/tree/documentdb/DatabaseItem.ts#L72), [indexes](../../../../../src/tree/documentdb/IndexesItem.ts#L66) | Collections/indexes or provider error feedback; F3 | +| I4 | Refresh view/node or click Retry | [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L63) | Error cache reset and fresh expansion; some stale-state guards are silent, F5 | +| I5 | Click Retry for a rejected Azure RU key | [key replacement](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L92) | Explicit fresh ARM key read; reconnect on refresh; modal on key-read failure | +| I6 | Click Retry sign-in under failed Entra cluster | [sign-in](../../../../../src/commands/signInAgain/signInAgain.ts#L74) | Interactive authentication; tree refresh; translated failure modal; cancel/stale guard | +| I7 | Click Diagnose connection… or invoke Diagnose from the palette | [diagnose command](../../../../../src/commands/diagnoseConnection/diagnoseConnection.ts#L27) | Read-only diagnostics panel; palette first picks a stored cluster | +| I8 | Click Open shell in failure rows / cluster context menu | [shell command](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L45) | Terminal and connection banner, or missing-credentials notification with no terminal, F1 | +| I9 | Click Update connection string… / Update credentials… | [destination edit](../../../../../src/commands/updateConnectionString/updateConnectionString.ts#L77), [credential edit](../../../../../src/commands/updateCredentials/updateCredentials.ts#L147) | Wizard; save feedback; changed settings retire webviews; error-node credential wizard asks whether to reconnect | +| I10 | Respond to old-Shell-settings notice after an edit | [Shell choice at review](https://github.com/microsoft/vscode-documentdb/blob/402b8e05251a5e2e688ac5d4a8eba8e8ce520139/src/commands/saveConnectionEdit.ts#L136) | Modal; Disconnect stops workers; dismissal keeps running workers on previous settings | +| I11 | Right-click connected cluster → Disconnect | [Disconnect](../../../../../src/commands/disconnect/disconnect.ts#L18), [tab choice](../../../../../src/documentdb/connectionTeardown.ts#L55) | Hidden from palette; connected-only menu; task block, tab choice, dirty warning, or teardown | +| I12 | Click Reconnect under a disconnected cluster | [Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L32) | Unlatch and tree refresh; connection result follows expansion; stale guard is silent | +| I13 | Delete one/multiple saved connections or a folder | [connection removal](../../../../../src/commands/removeConnection/removeConnection.ts#L23), [folder removal](../../../../../src/commands/connections-view/deleteFolder/ExecuteStep.ts#L22) | Shared destructive confirmation + teardown; refresh; configured summary; failures surfaced | +| I14 | Collection View: run, page, refresh, manipulate documents | [Collection View](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx#L179) | Current results or typed unavailable dialog; stale replies ignored; failed operations not replayed | +| I15 | Collection View: Indexes and Query Insights actions | [Indexes tab](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx), [Query Insights tab](../../../../../src/webviews/documentdb/collectionView/queryInsightsTab/QueryInsightsTab.tsx) | Shared parent lifecycle blocking; results retained; repair through tree + Retry | +| I16 | Document View: edit, Save, Refresh | [Document View](../../../../../src/webviews/documentdb/documentView/documentView.tsx#L90) | Dirty draft tracked; server actions blocked when unavailable; close/discard confirmation | +| I17 | Dashboard: refresh, create/drop, open views, copy/export | [Dashboard](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx), [row commands](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L254) | Busy state and results; unavailable dialog; no pending delete replay; retained namespace reference can be copied | +| I18 | Unavailable webview: Retry / Close view / X | [overlay](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L37), [recovery hook](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L93) | Same-binding recovery without replay; typed reason remains in dialog; exception notification, F4; confirmed close; X permits copying | +| I19 | Import, export, copy/paste while attempting teardown/edit | [import lease](../../../../../src/commands/importDocuments/importDocuments.ts#L161), [export lease](../../../../../src/commands/exportDocuments/exportDocuments.ts#L57), [task guard](../../../../../src/services/taskService/resourceUsageHelper.ts#L19) | Registered task/lease blocks teardown in modal; running transfer is not interrupted | +| I20 | Retained Shell: run after disconnect/reconnect; Sign in again | [worker evaluation](../../../../../src/documentdb/shell/ShellSessionManager.ts#L340), [sign-in action](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L941) | Same-settings worker restart; bounded failure output; warning action; successful sign-in has a rerun cue; F2/F5 | +| I21 | Playground: Run All / Run Selected; unbound connect-on-run | [execution](../../../../../src/commands/playground/executePlaygroundCode.ts#L101) | Database picker if unbound; progress + result document; latch warning; cancellation without execution | +| I22 | Playground CodeLens/status connection choice; Sign in again | [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L35), [recovery](../../../../../src/commands/playground/executePlaygroundCode.ts#L367) | Confirm switching; picker cancellation preserves binding; sign-in stops evaluator without replay or completion cue, F6 | +| I23 | Azure provider Refresh/Retry; Manage Accounts; Adjust Filters | [provider root](../../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts#L38), [listing](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts#L96) | Fresh listing; partial warning + Show Output; empty-state modal and actionable Retry | +| I24 | New/edit Entra connection: tenant, manual ID, Retry, Manage Azure Accounts | [new tenant picker](../../../../../src/commands/newConnection/PromptTenantStep.ts#L32), [edit tenant picker](../../../../../src/commands/updateCredentials/PromptTenantStep.ts) | Tenant selection/manual validation; recoverable lookup state; initial 5 s timeout and explicit retry up to 30 s | +| I25 | Show Connection Stats / Show Worker Stats during review | [connection stats](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L32) | Output channel; client state/generation and token expiry; worker stats are a separate surface | + +### Failure and feedback surface matrix + +The same failure could look different depending on who initiated the action: + +- **Tree:** first connect and cached acquisition/listing failures showed a translated + modal with separate detail and action-only children. Explained database/index failures + used a notification (F3). Tree sign-in and Azure key-read failures had dedicated modals. +- **Retained view:** a typed reason stayed over the content. An unexpected Retry error + went to a host notification (F4); a failed close confirmation stayed in the dialog. +- **Worker:** bounded terminal/result text, with a sign-in warning only when safe. Distinguish + F1's terminal startup failure from no terminal after cache eviction, and F5's explicit + stale click from intentionally silent cancellation, background counts and obsolete replies. +- **Persistence:** saving credentials did not guarantee usability (C7). Partial removal used + the summary setting; all-failed removal notified regardless. Check that a storage failure + restores the Reconnect state (C10). A task-blocking modal did not stop the task. +- **Discovery:** partial listings warned and offered Show Output; empty listings offered + account/filter repair. Tenant lookup failures kept Retry, manual ID and account management (C11). + +--- + +## The story in one paragraph + +The operator could reuse the same Shell and Playground after tree Reconnect, despite +instructions to start over. In contrast, Open shell on an invalid saved password +retried that password. The review separated misleading guidance from safety guards +that should stay: never replay an operation or silently switch identity. + +--- + +## Priority index + +| # | Priority | Item | Status | +| --- | -------- | --------------------------------------------------------------------------------- | -------------- | +| F1 | **P1** | Offer unauthenticated Shell from failure rows; choose a clear label | 🟠 Open | +| F2 | **P1** | Worker recovery wording requests unnecessary new Shell / connection pick | 🟠 Open | +| F3 | **P1** | Use modal failure feedback for tree-originated actions | 🟠 Open | +| F7 | **P1** | Disconnect missing after credential repair; version uncertain | 🟡 Open (soft) | +| F4 | **P2** | Retry exceptions appear outside the retained-view dialog | 🟠 Open | +| F5 | **P2** | State-drift guards silently terminate explicit recovery clicks | 🟠 Open | +| F8 | **P2** | Shell Disconnected output looks like text entered at the prompt | 🟠 Open | +| F9 | **P2** | Shorten Keep open (disabled) to Keep open | 🟠 Open | +| F10 | **P2** | Explain that decoded-password confirmation saves the correctly formatted password | 🟠 Open | +| F11 | **P2** | X label should describe access, not only copying | 🟠 Open | +| F12 | **P2** | Unify connection/worker debug-stat format for human readability | 🟠 Open | +| F6 | **P2** | Playground sign-in succeeds without a completion or rerun cue | 🚫 Closed | + +## P0 — Blocking (the user gets stuck) + +No P0 seeded. Promote an item only after confirming that no usable recovery path exists. + +## P1 — Broken / misleading, or consistency & safety + +### F1. Error-recovery Shell should not retry the failing authentication ⚠️ + +**Priority:** P1 · **Status:** 🟠 Open + +**Observation (operator, 2026-11-27):** a No Authentication connection opened the Shell +and showed a prompt. An invalid key/password opened a Shell that attempted the saved +authentication and failed. Relevant output, with the host omitted: + +```text +Connected to: {test host} +Authentication: No Authentication | Database: test +Type "help" for available commands. +test> +``` + +```text +Failed to connect: Invalid key +Run a command to try connecting again, or close this terminal. +test> +``` + +> **TN leans towards always offering Shell without authentication from error rows.** +> The label should make that difference explicit; “Open shell (w/o auth)” was offered +> as a possible name, not a final wording decision. + +**Finding:** + +- ⚠️ [Every cluster failure offers Open shell](../../../../../src/tree/documentdb/ClusterItemBase.ts#L431). + The [current command uses ordinary Shell startup](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L60); + [the worker builds Native authentication from cached credentials](../../../../../src/documentdb/shell/ShellSessionManager.ts#L435), + rather than selecting an unauthenticated diagnostic session for failure rows. + This supports the reported NoAuth-versus-invalid-key behavior. +- [Failed startup evicts non-recoverable credentials](../../../../../src/tree/documentdb/ClusterItemBase.ts#L324); + [the stored connection calls that cleanup](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L386) + before returning its recovery children. The user can therefore receive “Not signed in” + instead of the promised diagnostic terminal. This original pre-assessment branch + remains conditional; it does **not** mean every invalid-key click fails to open. + The operator's tested branch opened and then failed authentication instead. +- 🔍 This conflicts with the stated intent that experts can open a Shell on every failure + in the [tree architecture guidance](../../../../../.github/skills/tree-cluster-architecture/SKILL.md#failure-presentation-actions-only). + It is a command precondition gap, not evidence that Shell automatically repairs authentication. + +💡 **Suggestion:** For error-row entry only, open a separately unauthenticated Shell +without changing saved credentials or the existing connection identity. Do not silently +fall back to saved credentials after a server rejects anonymous operations. A Shell +opening without authentication is not a promise that database commands are authorized. +Normal context-menu Open Shell should keep its existing authenticated behavior. + +| Name option | Pros | Cons | +| ------------------------------------- | ------------------------------------------------------ | ----------------------------------------------- | +| **Open shell without authentication** | Recommended; explicit, plain language, no abbreviation | Longer tree row | +| Open unauthenticated shell | Accurate and shorter | More technical vocabulary | +| Open shell (no authentication) | Consistent with the No Authentication method label | Parenthetical is less readable in a narrow tree | +| Open shell (w/o auth) | Short | Two abbreviations; least clear for non-experts | + +**Decision state:** operator's preferred recovery direction recorded; final label and +implementation are still open. No anonymous-startup behavior has been added. + +### F2. Retained-worker guidance overstates when reopening or re-picking is required ⚠️ + +**Priority:** P1 · **Status:** 🟠 Open + +**Observation (operator, 2026-11-27):** the disconnected Shell requested a tree reconnect +and a new Shell, but after reconnecting the **same terminal** ran the query successfully. +The disconnected Playground warned: + +> This connection is unavailable. Reconnect from the tree, then re-pick it here. + +After tree Reconnect, running the retained Playground recovered without a connection +pick. The operator found “re-pick it here” difficult to interpret. The other two +observations reported with F2 are tracked separately as [F7](#f7-disconnect-menu-missing-after-credential-repair) +and [F8](#f8-disconnected-is-written-beside-the-active-shell-prompt). + +**Finding:** + +- ⚠️ [Shell user-disconnected output](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L895) + says to reconnect and open a new shell. [Playground's generic unavailable guidance](../../../../../src/commands/playground/executePlaygroundCode.ts#L356) + says to reconnect and re-pick. +- 🔍 Same-settings reuse is supported: teardown stops workers but preserves the + [terminal](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L273); + the [next Shell evaluation restarts its worker](../../../../../src/documentdb/shell/ShellSessionManager.ts#L340). + [Playground checks the original fingerprint when spawning](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L276) + and can use the retained binding. +- The [manual at the reviewed revision described reuse without a new terminal or pick](https://github.com/microsoft/vscode-documentdb/blob/402b8e05251a5e2e688ac5d4a8eba8e8ce520139/docs/user-manual/connecting-to-databases.md#disconnect-and-reconnect). + Source behavior supports that intent; the error wording is the mismatch. Identity or + destination changes still require the stricter guidance. + +> **Decision (Iteration 1):** for an unchanged disconnected connection, direct the person +> to reconnect from the tree and run the command/script again, not open a new Shell or +> re-pick the Playground. **Reason:** the operator verified in-place recovery; “re-pick +> it here” is not easy to follow. + +💡 **Proposed copy:** Shell: +**“Disconnected. Reconnect from the tree, then run your command again.”** +Playground: +**“This connection is disconnected. Reconnect from the tree, then run the script again.”** +These are proposed exact strings for the approved direction, not current source copy. +Preserve separate guidance when the connection was removed or its host/identity changed; +do not promise recovery or preservation of worker-local variables in those cases. + +### F3. Sibling tree expansion failures use modal versus notification feedback ⚠️ + +**Priority:** P1 · **Status:** 🟠 Open + +**Observation / direction (operator, 2026-11-27):** +“yes, modal all the way please, that's our ux guideline.” +The later clarification is: **“I meant modals for tree actions.”** +This is a policy decision; the operator did not supply a new reproduction transcript +for each descendant failure. + +**Finding:** + +- ⚠️ [Cluster expansion renders a modal](../../../../../src/tree/documentdb/ClusterItemBase.ts#L527) + with translated heading and separate detail. +- [Database](../../../../../src/tree/documentdb/DatabaseItem.ts#L81) and + [index](../../../../../src/tree/documentdb/IndexesItem.ts#L121) failures propagate to + [the shared provider catch](../../../../../src/tree/BaseExtendedTreeDataProvider.ts#L606), + which renders an explanation and cause in a non-modal notification. +- The [error-translation guidance](../../../../../.github/skills/error-translation/SKILL.md#adding-a-call-site) + shows modal-plus-detail tree presentation. The shared catch is an inherited boundary, + not a newly introduced renderer; code wins for current behavior, while the discrepancy + should be resolved explicitly rather than silently treating the guidance as implemented. + +> **Decision (Iteration 1):** failures of tree-originated actions, including expansion +> and tree commands, use modal feedback. **Reason:** this is the operator's stated UX +> guideline. Keep tree children as recovery actions, not error paragraphs. + +This does **not** make every worker or webview failure a host modal. It supersedes the +earlier suggestion here to leave tree database-command notification policy separate. +Use a translated heading and separate error detail consistently; avoid two modals for +one action. [O1](#o1-tree-modal-policy-and-in-view-feedback-are-separate-f3f4) +records the same scoped decision. + +### F7. Disconnect menu missing after credential repair + +**Priority:** P1 · **Status:** 🟡 Open (soft) + +**Observation (operator, 2026-11-27):** failed connect → Update Credentials → allow +reconnect with fresh credentials → the cluster context menu did not offer Disconnect. +The operator explicitly questioned whether an older version was being tested. +After restart and a fresh healthy connection, Disconnect was available. + +**Finding:** + +- 🔍 [The manifest gates Disconnect](../../../../../package.json#L1355) on a cluster + tree item with the `connected` context tag and no multi-selection. +- [The tag is emitted when a cached client exists and no latch applies](../../../../../src/tree/documentdb/ClusterItemBase.ts#L689); + [the stored cluster uses that helper](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L484). +- [Credential repair resets error state when reconnect was chosen, then refreshes](../../../../../src/commands/updateCredentials/updateCredentials.ts#L183). + These are the current-code eligibility checks, **not a confirmed root cause**. + +💡 **Suggestion:** reproduce that exact sequence in the current build before changing +the menu. Capture client existence/latch and the refreshed tree context tag. Do not +claim the old-version possibility has been ruled out or mark the feature fixed by restart. + +## P2 — Polish, expectation, or feature gap + +### F4. Retry exceptions leave the dialog intact but report elsewhere ⚠️ + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation:** Not yet observed live. Retry an unavailable view while the server remains +unreachable; compare a typed unavailable result and an unclassified thrown error. + +**Finding:** + +- 🔍 [Typed recovery failure updates the reason dialog](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L112). +- ⚠️ [An unclassified exception instead sends a non-modal host error](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L125) + while retaining the previous dialog. This creates two different feedback locations for + the same Retry interaction; whether the notification is missed requires runtime observation. +- [Close confirmation failure already stays in-context as an alert](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L67). + +💡 **Suggestion:** Walk this in all three retained views before deciding whether Retry +failure should update the dialog or remain a notification. Preserve the translated reason +and the ability to copy/close; never replay the failed operation. + +**Operator request (Iteration 1):** provide options with pros/cons. Recommendation: +keep Retry failure **inside the existing in-view dialog**, without stacking a host modal. +[O2](#o2-where-should-a-failed-in-view-retry-be-explained-f4) gives the alternatives. +This remains a suggestion; F3's tree-modal decision does not decide F4 automatically. + +### F5. Stale recovery actions can be safely rejected without explaining why ⚠️ + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation:** Not yet observed live. Leave a recovery row or Sign in again notification +available, change the connection's state elsewhere, then invoke the old action. + +**Finding:** + +- ⚠️ [Reconnect ignores an invalid target/state](../../../../../src/commands/disconnect/disconnect.ts#L32); + [Retry ignores incompatible latches](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L85); + [tree sign-in does the same](../../../../../src/commands/signInAgain/signInAgain.ts#L88). +- [Shell](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L949) and + [Playground](../../../../../src/commands/playground/executePlaygroundCode.ts#L389) + discard a stale sign-in notification choice when its epoch/owner no longer matches. +- 🔍 These guards correctly prevent recovery of the wrong connection. The code-level gap + is acknowledgement, not the safety check. Whether a stale affordance remains visible + long enough to confuse a person is still unverified. + +💡 **Suggestion:** Distinguish user cancellation and obsolete background work, which +should stay quiet, from an explicit click on a still-visible stale action. Consider a +refresh or brief bounded next-step notice only for the latter. + +**Operator request (Iteration 1):** provide options with pros/cons. Recommendation: +re-check and refresh on explicit stale clicks; show an actionable **modal for a failed +tree-originated action**, but keep cancellation/background disposal quiet and do not +report an already-completed action as an error. See +[O3](#o3-how-should-an-explicit-stale-action-end-f5). Decision remains open. + +### F6. Playground sign-in has no equivalent of Shell's “run again” completion cue ⚠️ + +**Priority:** P2 · **Status:** 🚫 Closed + +**Observation / comment (operator, 2026-11-27):** F6 is acceptable. The operator also did +not notice Shell's “Sign-in restored” line during testing, possibly because a `find()` +produced enough output to consume the visible scrollback. That explanation is a +possibility, not a verified cause. + +**Finding:** + +- [Playground writes the failed result before offering recovery](../../../../../src/commands/playground/executePlaygroundCode.ts#L276). +- ⚠️ [Successful sign-in only stops the evaluator](../../../../../src/commands/playground/executePlaygroundCode.ts#L397); + this path does not replace the failed result or announce that the next run is available. +- [Shell explicitly prints “Sign-in restored. Run your command again.”](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L972). + The authentication provider may show its own UI, but the Playground recovery handler + supplies no equivalent completion/rerun cue. + +> **Decision (Iteration 1):** leave the Playground completion behavior as-is. +> **Reason:** the operator accepts the lack of a dedicated completion/rerun cue. + +**Closed reason:** accepted as-is; no implementation change and no commit claimed. +Shell's line is emitted only after the explicit Shell Sign in again route succeeds +([source](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L962)); ordinary +tree Reconnect/worker restart is not evidence that the line must have appeared. +See [Q1](#q1-can-the-shell-scrollback-buffer-be-configured) for the buffer question. + +### F8. Disconnected is written beside the active Shell prompt + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation (operator, 2026-11-27):** + +```text +a11y-db> +a11y-db> Disconnected +a11y-db> +``` + +The system word looks like something the person entered at the prompt, rather than a +separate connection-state message. + +**Finding:** [disconnect writes Disconnected without first moving off the current line](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L274); +[writeLine appends only a trailing CRLF](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1120), +and [showPrompt leaves the cursor after the prompt](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1081). +This directly supports the reported rendering. + +> **Decision (Iteration 1):** render Disconnected on a separate system-output line +> before a fresh prompt. **Reason:** it must not look like user-entered input. + +💡 **Suggestion:** verify idle, partially typed and evaluating states when implementing; +preserve input intentionally rather than blindly adding a newline in every output path. + +### F9. Shorten the retained-tab choice + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** the host-modal option “Keep open (disabled)” (C0/C5) is too complex; +the operator knows the state is disabled but finds the label unclear. + +**Finding:** [the teardown modal currently uses Keep open (disabled)](../../../../../src/documentdb/connectionTeardown.ts#L78). +The choice controls retained webviews; it does not close the Shell terminal or Playground +file. The later overlay can explain unavailable database operations. + +> **Decision (Iteration 1):** change the visible choice to **“Keep open”**, dropping +> “(disabled)”. **Reason:** the suffix is unclear and unnecessarily complex. + +Retain disabled-operation behavior; this is a label change, not permission to execute. + +### F10. Explain what the decoded-password save will store + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** after decoding succeeds, enhance +“Connected to "Orders" using the decoded password. Would you like to update your saved credentials?” +so it states that the saved credentials will receive the correctly formatted password. + +**Finding:** [the current successful-retry prompt](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L350) +offers “Update saved password” and saves the decoded password only on that explicit action. +It does not reveal the password in the prompt. + +**Requested change (Iteration 1):** explicitly describe saving the correctly formatted +password into the connection's saved credentials. The operator specified the information +to add; no separate rationale or final exact sentence was supplied. + +💡 **Proposed copy:** +**“Connected to "Orders" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?”** +Keep the existing “Update saved password” action and do not include the secret value. + +### F11. X should describe access to retained contents + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** C6's X accessible name should describe accessing contents, +not only copying them. + +**Finding:** [the overlay's current accessible name](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L105) +is “Dismiss dialog to copy view contents”; dismissal exposes the retained content while +database-operation guards remain in place. + +> **Decision (Iteration 1):** use **“Dismiss dialog to access view contents”**. +> **Reason:** dismissing enables access/inspection, not just the narrower act of copying. + +No change to recovery or close semantics is implied. + +### F12. Make connection and worker debugging output use one readable format + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** Show Connection Stats and Show Worker Stats use different +formats. The operator requests unification and authorizes selecting the better format, +emphasizing that humans also read this debugging output. + +**Finding:** [connection stats compress multiple fields onto one Client line](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L40); +[worker stats use ruled headings and one field per line](../../../../../src/commands/showWorkerStats/showWorkerStats.ts#L18). +These commands report different things: host cached clients versus worker/session state. + +> **Decision (Iteration 1):** unify presentation for human-readable debugging. +> **Reason:** the operator explicitly prioritizes readability for human investigation. + +**Selected format recommendation:** use the worker-style **multiline labeled record** +structure for both commands, with consistent indentation, headings and units; omit +decorative ruler lines. Do not flatten it into the host command's dense key/value line. +Preserve the separate facts and field availability. A cached client is not proof of a +live socket, and worker count is not necessarily connection count. +See [O4](#o4-shared-debug-stat-format-f12) for a concrete shape and trade-offs. + +## P3 — Nice-to-have / cosmetic / acknowledged + +### Q1. Can the Shell scrollback buffer be configured? + +🔍 **Answered** + +**Observation:** the operator printed 50 documents and could not scroll back through +all output. Document count is not the same as terminal line count: multiline/wrapped +documents can consume many more lines. + +**Answer:** yes. The DocumentDB Shell uses a VS Code terminal; the live scrollback is +controlled by **`terminal.integrated.scrollback`**, whose documented default is **1000 +lines**. For example, in **user** settings: + +```json +{ + "terminal.integrated.scrollback": 10000 +} +``` + +This is a suggestion, not a setting changed by this review. Increase it before reproducing +the long-output case; output already discarded from scrollback is not recovered. +`terminal.integrated.persistentSessionScrollback` is a separate restored-session setting, +not the primary live-buffer control. The Shell's `clear` handling explicitly clears +scrollback, so increasing the limit does not preserve output across that action. + +Sources: [VS Code terminal buffer documentation](https://code.visualstudio.com/docs/terminal/basics#_navigating-the-buffer), +[persistent sessions](https://code.visualstudio.com/docs/terminal/advanced#_persistent-sessions), +[Shell clear](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1002). +No new extension-specific scrollback setting is proposed. + +## Implemented + +No fixes implemented in this UX review. Existing feature behavior is described above, +not relabeled as a fix from this pass. + +--- + +## Iteration log + +### Preparation — before Iteration 1 + +F1–F6 began as source-derived questions, not six live reproductions. + +### Iteration 1 — operator feedback recorded, implementation pending + +The [priority index](#priority-index) records the disposition at the end of the pass; +the F-items give the evidence and reasons where supplied. F1, F4 and F5 still needed design choices, +F7 needed a build-specific reproduction, and F6 was accepted as-is. Q1 was answered; +the Dashboard diagnostics request went to #1141. No product changes were requested +for execution in this pass. + +--- + +## Open ideas — options, pros & cons + +### O1. Tree modal policy and in-view feedback are separate (F3/F4) + +Accepted design already places typed unavailable webview reasons in a modal and keeps +worker failures in bounded output/notifications. The open question is the _sibling +failure branches_, not whether every error in the extension should block the user. + +| Option | Pros | Cons | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| **A. Keep current feedback boundaries** | Minimal change; preserves established command notifications | Sibling tree expansions and Retry outcomes remain asymmetric; guidance needs to describe this honestly | +| **B. Align tree-expansion errors; keep Retry failures inside their existing dialog** | One feedback location per journey; clearer relation between cause and recovery | Changes a shared tree boundary and needs explicit scope, accessibility and regression checks | +| **C. Make every lifecycle failure a host modal** | Prominent feedback everywhere | Can stack host/webview modals; disrupts workers and conflicts with deliberate surface-specific design | + +> **Decision (Iteration 1):** B's tree-alignment direction is accepted, with the +> operator's clarification **“I meant modals for tree actions.”** +> **Reason:** modal feedback for tree-originated failures is the UX guideline (F3). + +Tree-originated expansion and command failures should therefore be aligned to modal +feedback. This is not option C: do not impose host modals on all worker/webview errors. +The original B bundled tree alignment with in-dialog Retry feedback; F4 remains open +because the operator separately requests its pros/cons. O2 records that recommendation +without treating the tree decision as approval of a particular in-dialog implementation. + +### O2. Where should a failed in-view Retry be explained? (F4) + +| Option | Pros | Cons | +| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **A. Keep the current host notification** | Minimal implementation; existing error renderer and translated cause | May be missed while an old reason dialog remains; two feedback locations | +| **B. Show the Retry failure inside the existing unavailable dialog** | Recommended; keeps cause and actions together; no second modal; can announce the error once | Needs a clear distinction between the persistent unavailable reason and the failed attempt; detailed causes should not overwhelm the short explanation | +| **C. Open an additional host modal** | Prominent, hard to miss | Stacks host and webview modals; extra dismissal; does not follow from the tree-only modal policy | + +💡 **Suggested:** B. Keep the existing reason and add a concise failure explanation, +for example **“Could not reconnect. Check the network or server, then try Retry again.”** +only when that cause is supported; otherwise use a bounded **“Unable to recover the connection.”** +Keep translated technical detail available without replacing the user's next step with +a raw stack. Retry/Close/X become usable again after failure; no operation replay. +Use an alert/live announcement so a keyboard/screen-reader user notices the failed attempt. +Exact wording and detail disclosure remain proposals, not approved behavior. + +**Decision state:** awaiting the operator's choice. Modal **inside** the webview is +already the current unavailable presentation; the recommendation is to keep subsequent +failure feedback there, not open a new host modal. + +### O3. How should an explicit stale action end? (F5) + +| Option | Pros | Cons | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| **A. Preserve every silent early return** | Least intrusive; no accidental startup or identity changes | Person can click an apparent action and see nothing happen | +| **B. Show a modal for every stale event** | Uniformly visible | Noisy for background replies, cancellation and already-completed actions; can show obsolete errors | +| **C. Classify the outcome of an explicit click, refresh, then explain only a failed user action** | Recommended; keeps safety guards; consistent with tree-modal guideline; silence remains appropriate for non-actions | Requires precise classification of missing/changed/already-completed state and foreground ownership | + +💡 **Suggested:** C, with these separate endings: + +- **Explicit tree click, removed/changed target:** refresh relevant tree state, then a + bounded modal with a next step; proposed examples: + **“This connection was removed. Choose another connection.”** or + **“This connection changed. Refresh the tree and try again.”** + Use the actual reason, not an inferred generic network failure. +- **Already healthy/completed:** refresh/reveal the current state; do not call a successful + or no-longer-needed recovery an error. Any completion acknowledgement is optional. +- **Worker Sign in again notification became stale:** explain only if the terminal/file + still exists and that person actually chose the action; use that worker's existing + bounded surface, not the tree's host-modal rule by accident. +- **User cancelled, view disposed, obsolete background reply:** remain silent. + +Do not auto-connect another identity or restart a disposed worker to make a stale click +look successful. **Decision state:** awaiting operator choice. + +### O4. Shared debug-stat format (F12) + +| Format | Pros | Cons | +| ---------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| **Multiline labeled blocks** | Recommended; scan and compare fields; explicit units; works in Output without column alignment | More vertical space | +| Dense key/value lines | Compact; easy to grep a whole record | Existing host format is harder for humans to scan | +| Aligned tables | Compact comparison for a small set of common columns | Long IDs wrap; host/worker fields differ; missing cells can look like real zero values | + +**Recommended shape**, illustrative rather than current output: + +```text +[Connection Stats] + Entries: 1 + Connection 1: + Source: Extension host + Client state: cached + Generation: 4 + Age (ms): 32000 + Auth method: NativeAuth + Startup ID: {startup ID} + +[Worker Stats] + Shell sessions: 1 + Shell 1: + Terminal: {terminal title} + Worker state: ready + Initialized: true + Evaluating: false + Database: test + Auth method: NativeAuth +``` + +Use the same record/field conventions for Playground workers, include the existing +counts, held/pending states, Entra expiry, session IDs and init-duration facts where +available, and choose one explicit missing-value representation. Preserve truthful +labels: client state `cached` is not equivalent to a successful ping; a pending startup +is not a live client. Keep existing redaction boundaries and do not add credential values. +This is the selected recommendation under the operator's request to choose a readable +format; no debug command has yet been changed. + +### O5. Dashboard link to Connection Diagnostics + +**Status:** 🔗 Tracked in [#1141](https://github.com/microsoft/vscode-documentdb/issues/1141). + +The operator requested future work to make Connection Diagnostics reachable from the +Dashboard for its own connection. It is distinct from View Raw Diagnostics, which +exports different information. The issue asks for discoverable navigation and reuse +of the existing diagnostics flow, without silently selecting another connection. +It is not an active implementation item in #1136. + +--- + +## Appendix A — current flow (reference) + +### Retained-view state and action availability + +At the reviewed revision, the [reason map](../../../../../src/webviews/_integration/describeUnavailableConnection.ts#L11) +offered Retry for sign-in required, credential rejection/missing/updating, user Disconnect +and unreachable. Changed identity/settings and removal were close-only. Dismissing the +dialog cleared only render state, not the +[blocking ref](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L67). +[Host recovery](../../../../../src/webviews/documentdb/boundViewOperations.ts#L19) +resolved the original binding without rerunning the interrupted operation. + +**Intentional asymmetries to confirm, not automatically flag:** + +- Saved edits retired webviews even for password-only changes; workers had different + restart rules (decision 0018). +- Reconnect can auto-retry an existing same-identity Dashboard when auto-open brings it + forward; other retained views still require Retry. See + [Dashboard reveal](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L410). +- Tab choice covers registered webviews, not closing Shell terminals or Playground files. + Their database workers stop; scrollback/text remains. +- Tree explicit sign-in and worker sign-in differ in permitted account-change handling. + [Workers require the exact original identity](../../../../../src/commands/signInAgain/signInAgain.ts#L51); + old views must not silently inherit another account. +- Silence for token renewal, user cancellation, background counts and stale replies is + deliberate. Do not “fix” it by prompting from a callback. + +## Appendix B — hands-on run order and setup + +Use a dedicated development window and scratch database/connections owned by the +operator. Do not change shared accounts, cloud settings, services or real datasets just +to trigger a failure. This preparation did not launch servers or manipulate live data. + +Have a Native-auth or credential-free local test connection and an Azure DocumentDB +Entra test connection available. Open Collection View, a dirty Document View, Dashboard, +Shell and a Playground against the same scratch connection. Keep token-expiry/account +checks separate from network failure checks; use the stats commands for observation, +not as proof that renewal worked. + +| Phase | Exercise | Confirm before moving on | +| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1. First-run and entry parity | Expand; directly open Dashboard/Shell before expanding; empty DB/collection; cancel auth; fail initial auth; click each recovery row | Entries are actionable; no passive error rows; correct repair order; F1 and F3 | +| 2. Normal and silent recovery | Read/query in tree, views, Shell and Playground after idle/token expiry; observe Dashboard/background work | No surprise sign-in; same identity; actual operations still succeed; no interrupted write replay | +| 3. Explicit authentication repair | Tree Retry sign-in; worker Sign in again; cancel; wrong identity; Azure key Retry; stale notification | Failure explanation and next step; F5/F6; identity remains pinned where required | +| 4. Disconnect and retained work | `ask`, `closeAll`, `keepOpenDisabled`; dirty discard/cancel; X-copy and repeated blocked actions; reconnect and Retry | Modal choices match settings; no data loss on cancel; F2/F4; workers restart only on a new run; Dashboard exception is legible | +| 5. Saved edits | Cancel, unchanged save, password-only change, destination/account change; Shell keep/disconnect choice | Old webviews never resume after a changed save; unchanged save does not permanently lock them; copied drafts preserved; workers obey the documented distinction | +| 6. Transfers and destructive actions | Start scratch import/export/copy; attempt disconnect/remove/folder delete; later remove with retained views; cancel pending Dashboard delete across disconnect | Conflicting transfer continues; shared confirmation respected; no old delete replay; removal is distinct from Disconnect | +| 7. Discovery and accessibility | No accounts; filters hide results; partial listing; tenant lookup retry/manual ID; keyboard-only modal use in light/dark/high contrast | Account/filter exits work; Show Output is reachable; modal title/detail announced; focus and X-copy route usable | + +During Phase 4, also check whether long Retry waits have a perceivable busy signal: +[the overlay disables actions while recovering](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L115), +but its labels do not change to a progress message. Record actual wait durations before +assigning a progress defect. Escape dismissal is currently ignored by +[the controlled dialog handler](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L82); +confirm the keyboard journey rather than assuming the X requires a mouse. + +Optional fixture-only previews already exist in +[browser scenarios](../../../../../build/verification/browser/scenarios.ts#L2435): +Document View `disconnected-dirty` / `stale-save-after-reconnect`, Dashboard `disconnected`, and +Collection View `disconnected-signInRequired` / `stale-page-after-disconnect`. They help +inspect retained-content presentation but do not verify real sign-in, tree menus, workers +or packaged extension behavior. Follow the +[L2-dev runner recipe](../../../../../build/verification/README.md#l2-dev-source-scenarios); +do not treat fixture success as the hands-on review. + +## Appendix C — message walkthrough: what the user sees, and when + +This was a **source-based script**, not a list of tests that passed. `Orders`, +`inventory` and `reviews` instantiate templates; `{error}`, `{host}`, account labels, +provider UI and timings vary. F-items above hold the actual observations and decisions. +For the full wording and renderer inventory from this review, see the [original message walkthrough](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md#appendix-c--message-walkthrough-what-the-user-sees-and-when). + +### C0. Know which surface you are reviewing + +A host modal interrupted the window; a notification did not. Tree error children were +**actions**, not paragraphs repeating the modal. An overlay blocked one mounted webview; +a MessageBar stayed inline. Pickers and progress belonged to the action in flight. +Shell scrollback, Playground results and Output could outlast a notification. Badges, +CodeLens and tooltips conveyed state; accessible names and live announcements were not +toasts. Silent renewal, cancellation and obsolete replies could have no message at all. + +### C1. “I expand Orders and connect for the first time” + +Expand a fast, a slow and an empty scratch connection. Only the slow path might show +cancellable `Connecting to "Orders"…` (about 2 s); cancellation had no error dialog. +Success meant databases or “Create Database…” (within an empty database, “Create +Collection…”), not a toast. The optional Dashboard badge reflected periodic pings, +not the last command. Loading, reuse and failure details went to Output. + +**Check:** did completion and automatic Dashboard opening make sense? After cancel, +could the person explain any remaining rows? See I1–I3. + +### C2. “The server rejects my connection; now what do I read?” + +Fail a scratch connection with an incorrect password. The first fallback modal said +**Failed to connect to "Orders"**, then “Revisit connection details and try again.” and +`Error: {driver message}`. Cached failures put the raw error in detail without that +preface; enumeration had its own “Failed to load databases” heading. A provider could +replace the heading (e.g. start a stopped DocumentDB Local instance versus recreate a +missing container); this was advice, not automatic repair. + +**After dismissing the modal, review the action rows.** Examples: + +| Failed state | Example children, in order | Important absence | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| Stored Native credentials rejected | “Update connection string…”, “Update credentials…”, “Diagnose connection…”, “Open shell” | No ordinary Retry while the stored-credential rejection latch requires editing | +| Recoverable verified Entra sign-in failure on a stored connection | Provider repair rows when applicable, then “Retry sign-in”, “Diagnose connection…”, “Open shell” | No ordinary Retry beside Retry sign-in | +| Ordinary retryable failure | Provider repair rows when applicable, then “Diagnose connection…”, “Open shell”, “Retry” | No passive row containing the full driver error | +| Explicit user Disconnect | “Reconnect” | Not the failed-authentication repair block | + +The detail distinguished sign-in required, verified Entra rejection (Retry sign-in), +Azure replacement key (Retry reads from Azure), stored credentials (Update credentials) +and reloadable credentials (Retry). F1 records what happened with invalid credentials +versus the source-only “Not signed in” branch after cache eviction. + +**Encoded password:** “Try with decoded password” retried only by consent; success +then offered a _separate_ “Update saved password” action. F10 quotes the old and +proposed save prompts. After dismissing the modal, could the person choose the right +row unaided? Compare a database/Indexes failure's `{explanation} ({cause})` notification (F3). + +### C3. “My Microsoft sign-in expires while I am working” + +Successful silent renewal continued the operation. Only interactive recovery produced +the extension messages below; VS Code's provider owned browser/consent wording. + +| Where the failure is encountered | Exact extension wording | Where / next action | +| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Tree, typed expired sign-in explanation | “Your Microsoft sign-in for this connection expired. Sign in again to continue.” | Explanation heading in failure modal; tree offers “Retry sign-in” when the verified identity can recover | +| Tree, unexpected identity returned | “A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.” | Explanation heading in failure modal | +| Existing webview | “Sign-in required” / “Sign in from the connection tree, then click Retry.” | In-view dialog, not a Sign in again button; repair is in the tree | +| Shell, explicit worker recovery available | “Microsoft sign-in expired for this shell. Sign in again to continue.” | Terminal error **and** warning notification with “Sign in again” | +| Playground, explicit worker recovery available | “Microsoft sign-in expired for this playground. Sign in again to continue.” | Failed result document **and** warning notification with “Sign in again” | + +Sources: [typed Entra explanation](../../../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts#L24), +[Shell auth feedback](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L907), +[Playground auth feedback](../../../../../src/commands/playground/executePlaygroundCode.ts#L313), +[provider invocation](../../../../../src/documentdb/auth/entraSession.ts#L30). + +On success the tree refreshed without a toast; tabs still checked bindings. For Shell's +explicit rerun cue versus Playground's unchanged failed result, see F6. Cancellation +never replayed the operation; an old warning choice could end silently (F5). Failed +interactive sign-in used the tree's “Could not sign in again.” modal (or translated +heading), or a worker warning to open a new Shell / re-pick the Playground connection. + +**Other worker-authentication branches:** + +| Reason | Shell terminal message | Playground result message | +| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| Expired, no safe in-place sign-in action | “Microsoft sign-in expired for this shell. Open a new shell from the tree.” | “Microsoft sign-in expired for this playground. Re-pick its connection from the tree.” | +| Different account | “This shell is bound to a different Microsoft account. Open a new shell from the tree.” | “This playground is bound to a different Microsoft account. Re-pick its connection from the tree.” | +| Destination not trusted | “This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.” | “This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.” | +| Token refresh failed for another reason | “The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.” | “The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.” | + +Two **tree sign-in modal exceptions** are worth a separate read: + +- **“The connection was closed while you were signing in.”** when a sign-in attempt + finishes against a superseded connection. +- Heading **“The Azure cloud or sign-in provider changed.”**, detail: + **“Restore "microsoft-sovereign-cloud.environment" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.”** + +Source: [sign-in race and provider checks](../../../../../src/commands/signInAgain/signInAgain.ts#L114). + +For an untrusted destination the host modal explained that Microsoft Entra ID was +limited to Azure DocumentDB or trusted servers. It included `Server: {host}` (plus a +count for multiple hosts) and offered “Learn More”. Link failure warned “We couldn't +open this link.” + +**Review checkpoint:** can the person tell whether to use the tree, the warning's +Sign in again button, or the tab's Retry? Does each successful route visibly end? +Do not deliberately change shared accounts or cloud configuration for this test. + +### C4. “The server or network stops answering” + +Compare the same scratch-server failure across surfaces. The tree used C2's modal. +Only a _mapped_ unavailable view showed “Connection lost” / “Check the network or +server, then click Retry.” Ordinary operations kept their own errors. Ordinary Shell +startup wrote the error, possible infrastructure explanation and retry-or-close cue +(F1); a notification also explained the failure. Playground retained an error result +plus the explanation or `Query playground execution failed: {error}`. A missing +Kubernetes tunnel suggested collapsing and expanding to re-establish the port-forward, +not general network recovery. Typed worker failures followed C3/C8 instead. + +**The Dashboard has additional, non-overlay ways to say something is wrong:** + +| When | Message / affordance | Where it remains | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | +| Periodic health samples fail | Badge becomes “Disconnected” after two consecutive failed samples; one failed sample does not immediately switch it to Disconnected | Header; screen-reader announcement “Lost connection to the cluster.” | +| Initial cluster-information read fails ordinarily | “Failed to read cluster information: {error}” with “Retry” | Persistent inline MessageBar | +| Storage read fails but previous database rows exist | “Failed to read storage statistics: {error}” with “Retry” | Persistent inline MessageBar above retained inventory | +| Manual storage refresh throws | “Failed to read storage statistics.” plus the cause | Non-modal host error; also an accessible failure announcement | +| Another Dashboard action throws | For example “Failed to open the interactive shell.”, “Failed to copy the connection string.” or “Failed to export diagnostics.”, plus cause | Non-modal host error | + +Sources: [health polling](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L348), +[threshold](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L62), +[inline errors](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L879), +[manual refresh](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L248). +The shared [notification renderer](../../../../../src/webviews/_integration/appRouter.ts#L248) +appends a non-empty cause in parentheses; for example, an illustrative raw cause gives +`Failed to read storage statistics. (ECONNREFUSED)`. The cause is not always that short. + +**Review checkpoint:** compare the modal, toast, persistent banner, badge and retained +result. Which is still visible after attention moves elsewhere? Can “Disconnected” +from failed pings be distinguished from an explicit user Disconnect? + +### C5. “I choose Disconnect, but I need to keep my work” + +With Collection, dirty Document, Dashboard, Shell and Playground open, disconnect the +cluster. Record which steps appeared, in order: + +1. An active transfer blocked teardown before any tab question (C10). +2. With registered views and `openTabsOnDisconnect=ask`, “Disconnect?” offered “Close all” + or “Keep open (disabled)” (old wording; F9). Dismissal cancelled. `closeAll`, + `keepOpenDisabled`, or no registered views skipped the question, even with workers. +3. Closing a dirty Document still required “Discard unsaved document changes?” → + “Discard changes”, regardless of the default. Cancellation left teardown uncommitted. +4. Keeping views showed C6's dialog; Reconnect appeared in the tree. Workers stopped; + the terminal printed “Disconnected” and the Playground file stayed open. No success toast. +5. At this revision, tree Reconnect restarted acquisition, not the interrupted query/write. + Other retained views needed Retry; [revealing an auto-opened same-identity Dashboard](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L410) + could retry that Dashboard. + +**Review checkpoint:** does “open tabs” sound like it includes the Shell terminal or +Playground file, even though neither closes? Is the two-modal Close all → Discard +sequence understandable? Capture what the person thinks Reconnect will resume. + +### C6. “There is a dialog over my old results or unsaved document” + +These mapped reasons applied inside Collection, Document and Dashboard views, not to +every low-level error. “Close view” alone meant the binding could not recover. + +| Trigger / reason | Title | Detail | Footer buttons | +| ------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------- | +| Sign-in must be repaired | “Sign-in required” | “Sign in from the connection tree, then click Retry.” | Retry; Close view | +| Database rejected credentials | “Authentication failed” | “Repair the connection in the tree, then click Retry.” | Retry; Close view | +| Credentials are unavailable | “Disconnected” | “Connect from the connection tree, then click Retry.” | Retry; Close view | +| Person explicitly disconnected | “Disconnected” | “Reconnect from the connection tree, then click Retry.” | Retry; Close view | +| Connection edit is in progress | “Connection update in progress” | “Wait for the update to finish, then click Retry.” | Retry; Close view | +| Saved settings changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | +| Bound identity changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | +| Saved connection was removed | “Connection removed” | “This connection is no longer in the tree. Close this view.” | Close view | +| Bound connection is unreachable | “Connection lost” | “Check the network or server, then click Retry.” | Retry; Close view | + +Source: [all mapped titles/details](../../../../../src/webviews/_integration/describeUnavailableConnection.ts#L11). + +The three actions had different consequences: + +- **X** exposed retained contents without reconnecting. Another server action brought + the reason back. F11 records the old accessible name and its approved replacement. +- **Retry** left controls disabled but focusable while pending, with no changed label or + spinner. Success announced “Reconnected” without replay. Typed failure updated the + reason; unexpected exceptions left it in place and notified the host (F4). +- **Close view** [asked “Close this view?”](../../../../../src/webviews/_integration/appRouter.ts#L266) even when clean, suggesting dismissal instead + if the person needed to copy. Dirty views warned both inline and in the confirmation: + “Closing this view discards unsaved changes.” A failed confirmation request showed + “Unable to confirm closing the view. Try again.” inside the overlay. + +**Review checkpoint:** can the person copy without accidentally closing or reconnecting? +Can they hear the title/detail, reach X by keyboard, and distinguish “Retry the binding” +from “rerun the query”? Try Escape: the controlled overlay only accepts the explicit +trigger-click dismissal, not every close request. + +### C7. “I save changed credentials or a new connection string” + +Try cancel, unchanged values, password-only change and changed destination/identity +with dirty views and a Shell open. After “Select an authentication method”, error-node +credential repair asked whether to reconnect now or save without reconnecting (F7). +`showOperationSummaries` controlled the successful credential/string update message, +not all warnings. Cancel/unchanged settings did not permanently retire views; compare +“Connection update in progress” with “Connection changed” after an actual save. + +Even a password-only change retired old views without a tab-choice question. A separate +Shell modal said “Open shells are still using the previous connection settings.” +Disconnect stopped the workers and printed the status; dismissal kept the old settings. + +**Failure and special-case copy to read on this journey:** + +| Condition | Exact message | Surface | +| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| Cannot read original saved connection | “The connection could not be read from storage.” | Error notification | +| Credential save fails | “Failed to save credentials.” | Error notification; technical detail goes to Output | +| Connection-string save fails | “Failed to update the connection.” | Error notification; technical detail goes to Output | +| Cannot verify what persisted | “Could not verify the saved connection settings.” | Output warning only | +| Persisted settings differ but save is incomplete/unverified | “The connection update may be incomplete. Check the saved settings before reconnecting.” | Warning notification; old views may still be disabled for safety | +| New destination no longer supports the selected Entra method | “Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.” | Information notification instead of the ordinary string-update summary | +| Concurrent edit/removal already owns the connection | “A connection is already being updated or removed. Try again when it finishes.” | Thrown error, reported by caller/command handling | + +**Review checkpoint:** can “updated successfully” be mistaken for “old tabs are usable”? +Does the later Shell modal explain why Shell and webviews differ? Save success, reconnect +success and permission/identity continuity are three separate facts. + +### C8. “I keep my Shell open and try the next command” + +A new Shell showed “Connecting and authenticating...”, then host, authentication method, +optional identity, database and help cue (F1). Labels distinguished SCRAM, Entra Account, +Entra Managed Identity and No Authentication. A worker restart could show “Reconnecting...”. + +| State when the command is attempted | Shell terminal wording | +| ----------------------------------- | --------------------------------------------------------------------------------- | +| Explicitly disconnected | “Disconnected. Reconnect from the tree, then open a new shell.” | +| Different identity/settings binding | “This shell is bound to the previous connection. Open a new shell from the tree.” | +| Other typed unavailable state | “This connection is unavailable. Reconnect from the tree, then open a new shell.” | + +Source: [lifecycle worker failure](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L889). +These are output lines, not full-view overlays or necessarily host toasts. C3 lists +the separate authentication variants. + +After reconnecting with unchanged settings, try the **same** terminal: a new worker can +start without opening a new Shell. The more restrictive wording above is F2, not the +intended rule. Scrollback and the selected database remain; worker-local variables and +cursors are not preserved. An unexpected worker exit can instead print +**“Shell session ended unexpectedly.”** + +**Review checkpoint:** does the person trust the text or discover the less restrictive +working path? Are initial-connect error, explicit Disconnect, renewal failure and +worker restart distinguishable in scrollback? + +### C9. “I run the Playground before and after a connection problem” + +1. Unbound: “Connect” or Run All started the database picker; cancel ran nothing. + Bound: `Orders / inventory` named the binding, not a live health probe. Clicking it + offered “Connect to a different database…”; cancelling the picker preserved the binding. +2. Run: cancellable “Query Playground” progress went through “Initializing…”, + “Authenticating…”, “Running query…”. CodeLens switched to “Running…”; a second run + on the same cluster said to wait for the busy worker. +3. Failure **during** execution produced a read-only “Error executing query” result with + the binding, timestamp, query preview, duration and bounded reason. Expired sign-in + could also offer a “Sign in again” warning (C3). A changed binding directed the person + to re-pick; F2 quotes the confusing same-connection warning. +4. Failure **before** execution due to a latch only warned; the previous result could + still be on screen. Sign-in did not replace it or rerun code (F6). + +Sources: [phase text](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L265), +[result formatting](../../../../../src/documentdb/playground/resultFormatter.ts#L87). + +**Review checkpoint:** read the connection CodeLens, old result and current warning +together. Do they tell a consistent story about binding versus live connectivity? +Can a person tell whether the latest click executed any code? + +### C10. “I disconnect or remove while work is running, then remove for real” + +Try Disconnect, update and remove during a scratch transfer. The host modal named the +blocked operation (“Cannot disconnect this connection”, for example), listed task names +and types against the **cluster ID**, and asked the person to stop them. It did not +stop the tasks. After the transfer finishes: + +1. Delete one or several connections: “Are you sure?” named the target/count and warned + “This cannot be undone.” Default word input required `delete` (validation repeated + the instruction). Challenge mode offered three numbers; button mode offered Yes. +2. The separate “Remove the connection?” tab choice and dirty-discard confirmation + followed as applicable (C5). Retained views became “Connection removed”, without Retry. +3. Success and partial-success counts respected `showOperationSummaries`; partial failure + also logged each failed connection and cause. All-failed notified regardless of that + setting and directed the person to Output. + +**Folder variant:** the confirmation message can be +`Delete folder "reviews"?`, then `This will also delete 2 connections.`, then +**“This cannot be undone.”** It uses the same confirmation styles and descendant +teardown/tab choice. On success the summary is +**“The selected folder has been removed.”** +Sources: [folder confirmation](../../../../../src/commands/connections-view/deleteFolder/ConfirmDeleteStep.ts#L18), +[folder summary at review](https://github.com/microsoft/vscode-documentdb/blob/402b8e05251a5e2e688ac5d4a8eba8e8ce520139/src/commands/connections-view/deleteFolder/deleteFolder.ts#L60). + +**Review checkpoint:** count the prompts a person actually encounters. Is each asking a +different understandable question? Are partial failures visible with summaries disabled? +Do not interpret “delete connection” as deleting the database service itself. + +### C11. “Azure Discovery is empty or only some subscriptions appear” + +Compare an empty listing, partial results and failed tenant lookup without changing shared accounts: + +- **Empty listing:** “No Azure Subscriptions Found” explained sign-in and possibly hidden + results. Manage Accounts / Adjust Filters offered exits; dismissal left Retry. The + filter wizard omitted its own filter action and paragraph to avoid a loop. +- **Partial listing:** successful subscriptions stayed visible. One warning per listing + offered Show Output; sanitized detail distinguished a skipped account's tenants from + a skipped tenant's subscriptions, naming neither. +- **Manage Accounts:** the loading picker offered sign-in or Exit when empty; otherwise + tenant/signed-in counts and a different-account option. Tenant rows distinguished + “Signed in” from “Select to sign in”; an empty list offered Back or Exit. Explicit + tenant sign-in could notify “Successfully signed in to {tenantName}”. +- **New/edit Entra tenant pickers:** both kept manual GUID entry and account management; + the new flow said “Manage Azure Accounts…” and edit said “Sign in to other Azure + accounts to access more tenants”. Retry distinguished timeout (5 s, then 30 s on + explicit retry), load failure with Output detail, and no tenants returned. Manual + input rejected empty or non-GUID text; hyphenated and compact GUIDs were valid. + +**Azure RU key recovery** was separate from database sign-in: the [replacement-key read](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L107) +could show “Azure sign-in needed” / “Sign in to Azure and try Retry again.” or +“Could not read the database key from Azure.” / “Check access to the Azure resource and try again.” + +**Review checkpoint:** can the person tell missing resources from hidden filters, +failed discovery and expired database authentication? Does Show Output provide enough +detail to act without disclosing account identities in the warning itself? + +### C12. “I choose Diagnose, copy a report, or rely on assistive feedback” + +- **Diagnose:** Connection Diagnostics showed checking, cancelled or incomplete status, + Cancel/Re-run and, on completion, Show report / Share report. Opening an already-open + completed panel offered Re-run or dismissal inline, not an error modal. +- **Share:** the panel said to review the report and whether placeholders would hide + identifiers. With identifiers included, a host warning named host names, addresses + and username; cancel and select Hide identifiers, or explicitly Copy report / Save + report. Copy failure was inline; “Report copied” was a live announcement. + +Successful retained-view Retry announced **“Reconnected”**. Dashboard transitions announce +**“Connected to the cluster.”** / **“Lost connection to the cluster.”**; manual storage +refresh can announce **“Refreshing storage statistics…”**, then, for example, +**“Storage statistics refreshed. 2 databases.”** These are live-region messages, +not guaranteed visible banners. Check them with a real screen reader; source ARIA or +a browser accessibility tree does not establish what is actually spoken. +Sources: [recovery announcement](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L122), +[Dashboard announcements](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L210). + +**Output/debug-only examples:** Show Connection Stats opens Output and begins +`[Connection Stats] Extension-host cache entries: {count}`. It also explains +**“Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.”** +Generation, held state and token-expiry diagnostics are evidence for the operator; +they are not normal end-user lifecycle notifications +([stats command](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L32)). + +### C13. Capture the story, not just isolated strings + +For each scenario, dictate a short sequence using this review card: + +| Question | What to record | +| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| What did I click / what changed externally? | Entry point, connection type, open views/workers, relevant setting | +| What appeared first, second, and after dismissal? | Exact title/detail/action labels; notification vs modal vs inline vs Output | +| Did two surfaces disagree? | For example, a bound Playground CodeLens, a failed old result and a current sign-in warning | +| Could I explain the next action without opening docs? | Which button/row I expected to use, and what it actually did | +| How did I know it finished? | View enabled, result changed, live announcement, tree refreshed, or no visible completion | +| What was preserved or lost? | Draft, result, query text, scrollback, worker variables; whether anything unexpectedly replayed | +| Is this observed or only inferred? | Runtime evidence versus a source-only branch; link an existing F-item where applicable | diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md new file mode 100644 index 000000000..55395be11 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -0,0 +1,99 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +created: 2026-11-20 +--- + +# PR2 pre-review: Azure Discovery and azureauth v6 + +Reviewed [PR #1111](https://github.com/microsoft/vscode-documentdb/pull/1111), comparing +`8e5eda461` with `d6c4efc55`. GPT-6.2-Sol performed the initial review; Claude Opus 5.5 validated +the findings. The operator approved native SDK challenge handling and partial subscription +results with sanitized warnings. Neither decision is reopened here. + +| Finding | Validation | Technical recommendation | +| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| Refresh can leave a root on Retry. | Existing behavior (95% confidence). An explicit Retry clears the failed child cache; Refresh did not clear it before the upgrade either. | Do not change the tree recovery contract in WI-3. | +| Another caller can consume the one-shot freshness request. | Confirmed, non-blocking (80%). The fresh listing refills the cache before filtering; an overlapping tree listing can still return old results. | Observe explicit Refresh in OP-2. Keep the existing design unless the race reproduces. | +| SDK event suppression can hide a newly signed-in account. | WI-3 regression (90%). The SDK can suppress its cache invalidation event. A subsequent listing can miss an account that VS Code now knows about. | Read the local VS Code account inventory on each listing, while keeping tenant and subscription caches. Retain the cloud-change listener. | +| An account error can stop the filter wizard before it shows partial results. | Existing behavior (85%). The previous tenant enumeration also stopped on errors other than missing sign-in. | Keep the existing wizard contract; record any live failure in OP-2. | + +## Verification before the cache follow-up + +Build, lint, test type-check, localization and formatting passed after test-only lint repairs. +The first full run timed out in an unchanged Fluent UI test; a focused rerun and the subsequent +full run passed (9,682 tests passed, one skipped). The VSIX built, passed inspection, and the +inspection rejected all 24 negative controls. Local L3 activation could not start because this +Linux host lacks Electron's GUI libraries. OP-2 and the final CP-W3 verdict are still pending. + +## Cache follow-up + +`423c2e1b7` refreshes the local Azure account inventory even when the SDK suppresses session +events. Tenant and subscription caches remain intact. Added two focused regressions and retained +cloud-invalidation and listener-disposal coverage. The three affected suites (55 tests), root +type-check, and targeted formatting check passed. + +**Author sign-off (2026-11-20):** The operator accepted the recorded dispositions: keep the +account-inventory fix, leave the existing Refresh/Retry and filter-wizard behavior unchanged, +and keep the one-shot freshness design unless the overlap race reproduces. + +## OP-2 and CP-W3 + +The operator accepted OP-2 after testing the installed VSIX. Activation, Discovery, filters, +Refresh/Retry, same-account sign-out/sign-in, Azure New Connection discovery, and the Azure +Resources RU and vCore/DocumentDB nodes worked. Different-account switching, MFA, sovereign +cloud, Update Credentials and workspace-provider checks were not confirmed. The operator +accepted the untested deep-link URLs; partial failures were not reproducible live. + +CP-W3 retains L2 (Claude Opus 5.5, 85% confidence). L1 uses the same azureauth and Azure +Resources API versions, so stepping down does not reduce the remaining risk. + +## Final review handoff (2026-11-20) + +Case 2 verification at `4858e97d0` passed formatting, localization check, build, test +type-check, full Vitest (9,684 passed, one skipped), and VSIX packaging. Lint initially +reported unresolved types in the fresh worktree; it passed when rerun after the workspace +build generated the package declarations. No source changes were needed. Automated VSIX +activation remains unavailable on this host; the operator accepted the manual OP-2 result +and its coverage gaps above. + +## Copilot review follow-up + +The operator approved all four follow-ups: + +- [R1](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940342), `8de2a67da`: + Azure policy and app-registration failures no longer get misclassified as sign-in problems. + Typed additional-verification codes still report `signInRequired`. +- [R2](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940422), `df66e0172`: + A deep-link cache miss triggers a fresh listing before the extension offers tenant sign-in. + A successful tenant sign-in still triggers a fresh listing. Native SDK challenges are unchanged. +- [R3](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940489), `9805b7e25`: + A regression test uses the same stored subscription for two ARM operations across expiry. + Each operation creates its own management client, as production does. With the real SDK + pipeline and fake transport, the second request uses the fresh token without prompting or + relisting. Reusing one long-lived management client can send the previous token for an + additional request; changing that credential adapter is outside this follow-up. +- [R4](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940542), `490cf4376`: + Manage Azure Accounts fetches fresh tenants when loading its inventory. Routine Discovery + listing and wizard back-navigation keep their existing caching. + +Claude Opus 5.5 advised the dispositions (90%, 85%, 80%, and 85% confidence, respectively). +The build and all 109 focused tests passed. The earlier full Case 2 run predates these changes. + +## Azure ESM bundle verification + +The operator approved removing the obsolete CommonJS alias and replacing its historical +expected-failure test. In `f2b4641e6`, the production host probe verifies that the Azure ARM +subscription and tenant exports are callable and that the bundle uses ESM modules. The probe, +both BSON controls, all 267 verification tests, and inspection of the rebuilt VSIX passed. + +Two builds of the new revision had identical VSIX entry contents. Compared with the build +before alias removal, the host chunks kept the same module membership, but some chunk bytes +and names changed. The earlier live OP-2 result therefore does not verify this package. +**OP-2 repeat accepted (2026-11-23):** On the PR2 CI-built VSIX, the operator confirmed +that the Discovery roots loaded, filters and Refresh/Retry worked, signing out and back +in worked, and New Connection and the Azure Resources nodes worked. Update Credentials, +deep links, and partial-result handling were not tested. No separate account-switch, +sovereign-cloud, or MFA result was reported. The operator accepted these coverage gaps +and cleared the gate. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md new file mode 100644 index 000000000..1792eab9e --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md @@ -0,0 +1,44 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +created: 2026-11-23 +--- + +# PR3 pre-review: client identity and lifecycle + +Reviewed [PR #1113](https://github.com/microsoft/vscode-documentdb/pull/1113) at `657c9b2cf`, +against `96085c1dd`. GPT-6.2-Sol performed the initial review and Claude Opus 5.5 validated +the findings. The operator approved the dispositions on 2026-11-23. + +| Finding | Approved disposition | +| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Canceling the decoded-password retry could invalidate a startup shared by another caller. | Fix in PR3 (90% advisor confidence). Treat the canceled wait like the first attempt: record cancellation without showing another failure modal or evicting the shared client or credentials. | +| The passive index-count badge could start or replace a client. | Fix in PR3 (95%). Apply the existing background restriction to the count, not to explicit Indexes expansion. | +| A changed Kubernetes forwarded port could cause an identity mismatch if the old closed binding is still cached. | Defer stable tunnel fingerprints to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) (85% confidence in the finding). Keep the identity check in place, per [decision 0009](../decisions.md#0009-kubernetes-tunnel-recovery-cluster-id-case-handling-and-wider-network-resilience-testing-move-to-1105). | + +## Implementation and verification + +- `e751df24b` (`gpt-6.2-sol`) preserves the shared startup and credentials when the + decoded-password wait is canceled. Its regression checks cancellation reporting, the existing + pre-retry eviction, and the absence of failure UI or cleanup after the canceled wait. +- `db01f24a5` (`gpt-6.2-sol`) marks only the passive index count as background. Tests pin + the background flag and preserve the foreground expansion call. +- The operator approved keeping the fingerprint check unchanged and deferring stable tunnel + fingerprints. The feature decisions and both plans record this limitation. + +Case 1: the build and 95 focused tests passed with both fixes. + +## Case 2 handoff + +After merging the verified PR2 head in `3119db4ed`, localization generation and validation, +formatting, lint, build, strict workspace test type-check, and VSIX packaging passed. The +first full test run found six failures in the connection-string edit suite: its mock still +targeted `getClient` after the tree moved to `connectInteractive`. `be211c14c` updates the +fixture without changing its assertions or production code. The repaired suite passed all +seven tests and targeted lint; the full rerun passed **429 files, 9,735 tests, one skipped**. +`57cd2db14` records the generated localization and formatting used in verification. + +PR3 remains stacked on PR2 (#1111). Repeat OP-2 was accepted on the PR2 CI-built VSIX +with the gaps recorded in the [PR2 review](./01-pr2-azureauth-review.md). That was not a +live test of PR3; the next planned operator test is OP-3 after WI-5. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md new file mode 100644 index 000000000..d10a368fe --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -0,0 +1,82 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +created: 2026-11-23 +--- + +# PR4 pre-review: connection failure recovery + +[PR #1117](https://github.com/microsoft/vscode-documentdb/pull/1117), reviewed locally at +`69112da71` against PR3's `a301f6561`. GPT-6.2-Sol performed the initial review; Claude +Opus 5.5 validated the findings and performed an independent sweep. No published GitHub +reviews were present. The review findings below reflect the reviewed revision; the +operator's dispositions and verification are recorded separately. + +| ID | Severity | Validation | Finding and recommended disposition | +| --- | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| F1 | Medium | Partial, 75% | A rejected replacement outside the tree can try the same Entra settings again; the tree already covers its own path. Reproduce first, then latch only a current, verified Entra replacement with a terminal rejection. Leave first-startup and Native/RU behavior alone. [Startup](../../../../../src/documentdb/ClustersClient.ts#L1010) | +| F2 | Medium | Valid, 85%; predates PR4 | An explicit tenant edit can leave the old tenant pin after a sign-in failure. Keep the existing WI-7 requirement to replace or clear the pin on a saved tenant change; do not pull the broader credential-update transaction into PR4. [Update credentials](../../../../../src/commands/updateCredentials/updateCredentials.ts#L171) | +| F3 | Medium | Valid, 80% | An old Retry row can close a healthy replacement already published before the click. Fence the destructive step to the failed client; refresh without closing a newer client. [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L155) | +| F4 | Medium | Plausible race, 65% | A late successful database listing could render old rows after another account becomes current. Reproduce first. Discard a result when the identity differs or a latch is set, using the existing stale-result path; a same-identity replacement alone should not discard it. [Expansion](../../../../../src/tree/documentdb/ClusterItemBase.ts#L559) | +| F5 | Medium | Valid, 85% | For a latched stored Native connection, Retry does nothing; Update credentials is the repair. Hide only a Retry row with no action, while retaining Diagnose and Open shell and preserving error detection. Keep working RU and Native Discovery Retry paths. [Recovery rows](../../../../../src/tree/documentdb/ClusterItemBase.ts#L360) | +| N1 | Medium | Valid, 90%; WI-6 integration | The operation wrapper lacks auth context for startup rejection. Cover it when WI-6 first wires the wrapper to routers; the host must return the typed unavailable reason instead of a generic error. [Operation wrapper](../../../../../src/documentdb/runWithClient.ts#L48) | +| N2 | Medium | Potential regression, 70% | The new recovery fence applies to ordinary edits, and a return after storage has saved can leave storage and cached settings out of sync. Reproduce first; keep any PR4 repair scoped to the new regression. Leave the broader save, latch, and teardown transaction in WI-7. [Credentials save](../../../../../src/commands/updateCredentials/ExecuteStep.ts#L110) and [connection string save](../../../../../src/commands/updateConnectionString/ExecuteStep.ts#L95). | +| N3 | Medium | Valid, 90% | A real database named `sign-in-again` can match the recovery row's ID. Require the reserved error context as well as the ID, and test that the real database remains visible as healthy. [Error detection](../../../../../src/tree/documentdb/ClusterItemBase.ts#L610) | + +## Author decisions + +The operator approved scoped PR4 fixes for F1, F3–F5 and N2–N3, with reproduction +before changing F1, F4 or N2. They asked to avoid nonessential edge cases and keep the +implementation simple. F2 stays in WI-7; N1 stays in WI-6. + +The focused regressions reproduced F1, F3, F4, F5 and N3. All 132 tests in the three +affected suites passed after `87ab0ed1f` (F1, F3) and `1500634d1` (F4, F5, N3). +The stale-tree guard checks identity, not generation, so a same-identity replacement does +not by itself discard a result. + +N2 was reproduced in both edit commands: a connection-string edit was skipped, and a +credential write succeeded without updating the runtime cache. `64d6f3ffd` limits the +wizard epoch check to recovery edits and records a completed storage save accurately. +An obsolete recovery still cannot evict newer state or clear its latch. All 62 focused +tests passed across six suites. Reconciling an already in-flight recovery save that lands +after teardown stays in WI-7, with F2. + +## Copilot review follow-up + +Claude Opus 5.5 validated the nine inline findings against `ca841a7c8`. The confirmed medium +findings are addressed in dedicated commits. The operator approved reporting child expansion +failures in this PR without adding child recovery actions or replaying the request. + +| Finding | Disposition | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [R1](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677891992) | `27345af20` explains how to restore the pinned Azure cloud or provider before retrying sign-in. | +| [R2](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892084) | Preserve the approved F1 scope: no new Native/RU or first-startup latch policy. | +| [R3](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892154) | Keep retrying the silent lookup on a later foreground request so signing back in through VS Code Accounts can restore the session. Track in [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119#issuecomment-7127895057). | +| [R4](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892272) | `f3407187a` preserves localized Managed Identity guidance in the typed callback error without copying unrecognized SDK text into the message. | +| [R5](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892358), [R7](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892494) | Defer the two low-severity telemetry gaps to [#1123](https://github.com/microsoft/vscode-documentdb/issues/1123). | +| [R6](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892428) | `195243c52` lets Quick Start Retry clear only its current rejection and reload its service-owned credentials. | +| [R8](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892557) | `228be9f90` explains the rejection and points to the appropriate existing tree action. | +| [R9](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892633) | `b1b446e6d` reports foreground database and index listing failures against the binding that ran them and rethrows the original error. Optional navigation to the owning cluster is tracked in [#1124](https://github.com/microsoft/vscode-documentdb/issues/1124). | + +## Handoff verification + +OP-3 passed on the older CI VSIX. The current review proposals do not change the tested +sign-out, dismissal, or explicit sign-in sequence. The local `1.1.1-alpha.1` VSIX packaged +successfully; its shared Shell/Playground worker booted in plain Node and acknowledged +shutdown. On 2026-11-24, the operator confirmed that both Shell and Playground work +on the requested CI-built `1.1.1-alpha.1` VSIX. The live smoke gate is cleared. + +Final local Case 2 passed: localization generation and check, formatting, lint, build, +strict workspace test type-check, the full runtime suite (**432 files; 9,796 passed, one +skipped**), and VSIX packaging. The initial label test was corrected to assert the +label on the existing plain-object tree fixture. The review-fix run also caught an +enum-to-string lint error and a storage fixture type mismatch; both were fixed +without changing recovery behavior or weakening any assertions. Full CI also passed +on code head `d422d065b`. The operator confirmation is a documentation-only follow-up; +it does not change the tested build or require repeating OP-3. + +After the Copilot fixes, local Case 2 passed again: localization generation and check, +formatting, lint, build, strict workspace test type-check, the full runtime suite +(432 files; 9,805 tests passed, one skipped), and VSIX packaging. The earlier OP-3 and +worker smoke results stand; no repeat live test was required for these fixes. 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..0401d3f03 --- /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: historical +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/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md new file mode 100644 index 000000000..7741d5aaf --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -0,0 +1,147 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1133] +--- + +# PR6a pre-review: Shell and Playground token relays + +[PR #1133](https://github.com/microsoft/vscode-documentdb/pull/1133) · WI-2 · reviewed head `8c2ca3fdc` + +Claude Opus 5.5 performed the first pass. OpenAI GPT-5.6-Luna validated both findings and +independently found two more. There were no GitHub Copilot review threads on the draft at this +head. Findings are based on code inspection; the initial Case 1 build and 310 focused tests +passed, but those tests did not exercise the failing cases below. + +## F1. Successful Sign in again does not restart the worker (high) + +[`signInAgain`](../../../../../src/commands/signInAgain/signInAgain.ts#L172) replaces the host +client and advances its epoch. Both [Shell](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L950) +and [Playground](../../../../../src/commands/playground/executePlaygroundCode.ts#L401) reject this +successful result because it does not match the epoch captured before sign-in. The worker then +remains blocked and offers the same action again. + +**Recommendation:** Before opening sign-in, confirm the notification still belongs to the +same shell revision or document binding. After sign-in, check that the exact epoch returned +by that sign-in is still current and that the same surface owns the action. Do not accept +arbitrary newer epochs or remove the fence. Test a successful epoch change and a superseding +invalidation without replaying the old operation. + +**Author decision:** Approved as recommended. Use the confirmed post-sign-in epoch without +loosening the ownership checks or replaying the operation. + +**Fixed:** [`8faa1ba8f`](https://github.com/microsoft/vscode-documentdb/commit/8faa1ba8f). +Shell and Playground use the confirmed epoch and reject stale or superseded recovery +actions. The two surface suites passed 99 tests, including no replay. + +## F2. Re-picking a Playground connection leaves Run blocked (medium) + +The [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L120) updates +the document binding, but the [evaluator](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L194) +keeps the previous worker's authentication failure for the whole cluster. The next Run can +reject before it checks the new binding. + +**Recommendation:** Let an explicit re-pick advance past that failed worker on the next +deliberate Run, after the existing identity and execution checks. Do not stop an evaluator +from the picker: another document may be using it. Separate failure tracking for every +document would be more complex without removing the need to replace the failed worker. +Test successful re-pick and Run, preservation of the old binding's identity, and a second +document's in-flight run. + +**Author decision:** Approved as recommended. Apply the explicit re-pick on the next Run +without interrupting another document. + +**Fixed:** [`f5b79a3e9`](https://github.com/microsoft/vscode-documentdb/commit/f5b79a3e9). +The re-pick is scoped to that document and used on its next Run. The picker never stops +an active worker, and other documents cannot inherit the new binding. The two focused +Playground suites passed 51 tests. + +## F3. A no-op saved edit can discard healthy Shell state (medium) + +The [Shell manager](../../../../../src/documentdb/shell/ShellSessionManager.ts#L227) kills a +healthy worker when the host epoch changes. [Saving unchanged settings](../../../../../src/commands/saveConnectionEdit.ts#L54) +can advance the host epoch even though the Shell remains connected and the identity has not +changed. The next command then loses the Shell's variables and cursors. + +**Recommendation:** Keep the healthy Shell worker across a host-only epoch change. Keep the +epoch fence for startup and token replies, and keep the latch and fingerprint checks before +respawn. Do not add a separate epoch counter. Test that a no-op edit does not respawn the +healthy worker, while explicit Disconnect still stops it. + +**Author decision:** Approved as recommended. Preserve healthy Shell state on an unchanged save. + +**Fixed:** [`72fb52da6`](https://github.com/microsoft/vscode-documentdb/commit/72fb52da6). +A host-only invalidation no longer restarts a healthy Shell. The startup, latch and +explicit Disconnect checks remain in effect. + +## F4. A stale token request can hang a worker that is still attached (medium) + +The [host relay](../../../../../src/documentdb/auth/WorkerTokenRelay.ts#L71) drops the token reply +when the host epoch changes, even if the worker is still attached. The worker is awaiting +that reply and a warm evaluation has no IPC timeout. The existing late-reply test only +covers a worker that has been terminated. + +**Recommendation:** Keep ignoring detached workers. Settle an obsolete request on a worker +that is still attached with a bounded lifecycle cancellation. Do not send the stale token, +update diagnostics, or replay the evaluation. Adding a timeout alone would leave the +request running until the timeout and would not express why it was interrupted. Test +invalidation with an attached worker and no stale token or diagnostics. + +**Author decision:** Approved as recommended. Cancel the obsolete request without returning a +stale token or recording a stale failure. + +**Fixed:** [`25e686f93`](https://github.com/microsoft/vscode-documentdb/commit/25e686f93). +The supervisor cancels an obsolete operation and discards its attached worker. Detached +replies remain ignored. The combined F3 and F4 focused suites passed 114 tests. + +## Scope clarification + +[Decision 0018](../decisions.md#0018-saved-connection-edits-permanently-lock-existing-views) +retires registered webviews after a saved settings change. It does not make Shell terminals +or Playground documents Close-only. WI-2 and +[D12](../../sovereign-clouds/decisions.md#d12-open-sessions-keep-what-they-started-with) +allow a needed same-identity respawn after a password-only edit, but do not require a healthy +Shell worker to restart. + +## Verification after the fixes + +Case 1 passed on `f5b79a3e9`: `npm run build` and 534 focused tests across 18 suites. +The packaged live checks remain at OP-6. + +## Copilot review follow-up + +The advisor confirmed that a worker-only account pin cannot complete host recovery. +[`27410085f`](https://github.com/microsoft/vscode-documentdb/commit/27410085f) requires a +matching host-verified pin before offering **Sign in again**. Otherwise, the existing +surface guidance points to the tree; no worker-learned identity is promoted to a host pin. + +- A Playground document retains the account learned before a later startup failure + ([`a5ce99b97`](https://github.com/microsoft/vscode-documentdb/commit/a5ce99b97)). +- Late binding capture follows the same Playground connection through Save As but not + through an explicit re-pick ([`1e9fc1446`](https://github.com/microsoft/vscode-documentdb/commit/1e9fc1446)). +- Warm Playground runs retain the worker's destination metadata without reading cached + credentials ([`56b5143c8`](https://github.com/microsoft/vscode-documentdb/commit/56b5143c8)). +- The notification action records its own Playground sign-in outcome rather than writing + to the completed Run event ([`50cb05dc3`](https://github.com/microsoft/vscode-documentdb/commit/50cb05dc3)). +- A worker keeps its token audience and sign-in environment together and refuses cloud + or authority changes ([`f9dbc4ee0`](https://github.com/microsoft/vscode-documentdb/commit/f9dbc4ee0)). + The environment check also runs when a current token lookup rejects + ([`a42fa23f8`](https://github.com/microsoft/vscode-documentdb/commit/a42fa23f8)). + +The [configuration-guidance finding](https://github.com/microsoft/vscode-documentdb/pull/1133#discussion_r4704910161) +is not being changed in this PR. Some cloud or managed identity configuration errors +still receive the generic worker retry guidance. Keeping the bounded worker failure +contract avoids expanding error transport or adding a second guidance path just for these +failures. The tree connection and **Diagnose Connection** remain available for configuration +troubleshooting. + +The operator approved the sovereign-auth integration expectations after the full test run: +a warm Entra worker keeps the original token audience but refuses renewal if the configured +provider, cloud or authority changes. A different destination requires a new Shell or an +explicit Playground re-pick. Same-identity respawn and managed identity's existing audience +snapshot are unchanged. + +**Case 2 handoff:** Localization, formatting, lint, build, strict workspace test +type-checking, 9,959 tests across 444 suites (one skipped), and VSIX packaging passed. +The VSIX was built for verification, not published as a new operator candidate. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md new file mode 100644 index 000000000..adc75d53f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md @@ -0,0 +1,98 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1135] +--- + +# PR7 pre-review: Connection recovery telemetry and docs + +[PR #1135](https://github.com/microsoft/vscode-documentdb/pull/1135) · WI-9 and WI-10 · reviewed head `668ead86a` + +Claude Opus 5.5 performed the first pass. OpenAI GPT-6.2-Sol independently validated the +findings and added two. That run used long context; the standard-context verification +required by CONTRIBUTING §6.1 remains open. There were no Copilot threads when checked. +Neither reviewer found a runtime issue in the bounded renewal emitter. Neither ran the +queries against live data. + +## F1. The baseline can show a false drop in classified failures (high for WI-9) + +The original before/after query used error fields that the new tree `connect` path masks but +the baseline did not. The +same failure can move to the unclassified bucket without any change in its frequency. +Tree expansion can also return recovery actions as a normal result. + +**Recommendation:** Compare only stable RPC procedures and versions that share the same +`causeType` scheme, with the same exposure rules for both cohorts. Keep unclassified +counts visible and label tree data as descriptive, not comparable. If no comparable +cohort has enough exposure, report insufficient evidence. Do not change runtime +telemetry or relax redaction. + +**Author decision:** Approved as recommended. Limit the rate comparison to stable RPC +scopes; do not add a telemetry field or change redaction. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +limits the classified comparison to two database RPCs and uses `causeType` alone. Tree +events stay descriptive, and unclassified failures remain visible. + +**Superseded by Copilot follow-up:** The RPCs can also return typed unavailability normally, +which is reported as SDK success. The operator [deferred the comparison](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures) +and retained descriptive telemetry for 1.2.0. + +## F2. Disconnect does not wait behind an active task (medium) + +The [release notes](../../../../release-notes/1.2.md) say Disconnect waits, and the +[manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +does not explicitly tell the user to retry. The command refuses teardown and leaves +both the task and the connection running. + +**Recommendation:** State in both pages that the user must try Disconnect again after +the task finishes or is stopped. No command change. + +**Author decision:** Approved as recommended. Clarify that the user must retry Disconnect. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains in both pages that the task and connection keep running and the user must retry. + +## F3. Recovery rows can inflate replacement success counts (medium) + +The [replacement query](../telemetry.md) excludes cached failures, but a first failed +tree expansion can return recovery rows while its event still reports success. It can +already carry the replacement generation at that point. + +**Recommendation:** Exclude both first-time and cached recovery rows. Count confirmed +recovery only for operations whose success indicates that database work succeeded. + +**Author decision:** Approved as recommended. Do not count first-time or cached recovery +rows as successful replacement operations. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +counts only successful cluster expansions on a replacement generation, excluding both +first-time and cached recovery rows. + +## F4. A retained Dashboard can still require Retry (medium) + +The [manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +and [release notes](../../../../release-notes/1.2.md) imply that only other views need +Retry. The Dashboard retries automatically only if reconnect opens the already +bound panel. Auto-open can be disabled. + +**Recommendation:** Describe the conditional automatic retry and tell users to select +**Retry** if the Dashboard stays disabled. No behavior change. + +**Author decision:** Approved as recommended. Clarify when a retained Dashboard still +needs Retry. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains that the existing Dashboard retries automatically only when Reconnect opens it. +If it stays disabled, select **Retry**. + +## Remaining handoff requirements + +A second validation attempt could not verify its context tier or vendor and did not +review the changes. PR7 remains in draft until standard-context validation is confirmed. +Live query and ingestion verification remains pending for CP-5. + +Local Case 2 passed: formatting, localization check, lint, build, strict workspace +test type-checking, 9,963 tests across 444 suites (one skipped), and VSIX packaging. +No localization strings changed in PR7. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md new file mode 100644 index 000000000..46163bb6d --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md @@ -0,0 +1,348 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1136] +created: 2026-11-29 +verified: 2026-11-29 +code: + - src/commands/runBoundNamespaceCommand.ts + - src/commands/playground/newPlayground.ts + - src/commands/llmEnhancedCommands/queryGenerationCommands.ts + - src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts + - src/services/copilotService.ts + - src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx + - src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts +--- + +# PR #1136: Copilot review evaluation + +## Scope and verdict + +Evaluated [Copilot's review](https://github.com/microsoft/vscode-documentdb/pull/1136#pullrequestreview-6102540168) +against PR head `1e362403bc13fb0c5451cb84b57a458b8fe6c999`. All five Copilot inline threads were +open and not outdated when retrieved on 2026-11-29. Source links below are pinned to that head. +Recommendations are proposals, not operator decisions. + +Severity is assessed independently of Copilot: **High** is a plausible cross-identity disclosure; +**Medium** is a concrete write or wrong-target risk with a constrained trigger; **Low** affects +recovery guidance or telemetry. No actual disclosure or database write was observed. + +| Item | Finding | Verdict | Severity | Proposed direction | +| --------------------------------------------------------------------------------- | ----------------------------------------------- | --------- | -------- | -------------------------------------------------------- | +| [C01](#c01-create-commands-can-start-after-a-credential-update-latch) | Create after credential-update latch | Confirmed | Medium | Fence the bound command immediately before its operation | +| [C02](#c02-query-generation-can-sample-and-send-the-replacement-identitys-schema) | Replacement schema sent to Copilot | Confirmed | High | Bind and cancel the host generation path | +| [C03](#c03-playground-handoffs-can-adopt-a-replacement-identity) | Playground adopts a replacement identity | Confirmed | Medium | Carry and validate the originating binding and pin | +| [C04](#c04-provider-changes-are-explained-as-expired-sign-in) | Provider change reported as expiry | Confirmed | Low | Use reason-aware, truthful recovery guidance | +| [C05](#c05-stage-3-unavailability-is-recorded-as-cancellation) | Stage 3 unavailability recorded as cancellation | Confirmed | Low | Set the bounded outcome before the terminal yield | + +The active [feature intent](../README.md#intent) says open surfaces must not move to a different +identity and saved edits lock old views. C02 and C03 expose gaps between that intent and the code. +The proposals preserve the intent; if a weaker behavior is deliberately chosen instead, the +feature documentation should be corrected to describe it. + +## Operator decisions (2026-12-02) + +- **C01-C03:** implemented on `feature/connection-lifecycle` by the H pass of the + [complexity-reduction analysis](./03-complexity-reduction-analysis.md) (WI-H1 to WI-H3) before + any thread was answered. Each item below records the commit; no separate decision was needed. +- **C04:** operator selected **option 1**. No additional rationale was supplied. +- **C05:** operator selected **option 1**. No additional rationale was supplied. +- **Threads:** reply in each Copilot thread with the outcome and commit, then resolve it. + +## C01. Create commands can start after a credential-update latch + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4731072530). + +> Create Database and Create Collection pass no confirmation epoch, so a credential-update latch set +> after client resolution can still allow their write to start here. Capture the command epoch and +> check it and the current latch immediately before invoking `operation`, even without a delete +> confirmation. Add a regression that latches the connection between resolution and the callback and +> verifies that no write runs. + +**Evidence.** [The bound-command guard](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/runBoundNamespaceCommand.ts#L22) +does nothing when `confirmationEpoch` is absent, as it is for +[Create Database](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/createDatabase/ExecuteStep.ts#L35) +and [Create Collection](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/createCollection/ExecuteStep.ts#L26). +After awaiting resolution, [runWithClient](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/runWithClient.ts#L43) +invokes the callback without another latch check. A saved edit +[sets the latch before writing settings](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/saveConnectionEdit.ts#L58). +The create methods then call the driver without their own latch check. + +In a controlled microtask probe using the actual cached-client resolution and command wrappers, +the final resolution check completed, the update latch was set, and the create callback still ran. +The same schedule with a confirmation epoch stopped it. The client and write were mocked: a real +driver write could succeed or fail, and no database was modified. + +**Options.** + +1. **Recommended:** capture an operation epoch and check the current latch and epoch in the bound + helper immediately before calling the operation. Keep the existing, separate delete-confirmation + epoch semantics. **Pros:** closes the demonstrated boundary for both creates and shared bound + reads; keeps stale delete confirmations cancelled. **Cons:** a concurrent lifecycle change can + cancel an operation that the user must retry. +2. Check only whether the latch is currently set. **Pros:** smaller change. **Cons:** misses a + latch that was set and cleared while client resolution was pending. +3. Add a universal fence to `runWithClient`. **Pros:** one shared enforcement point. **Cons:** affects + unrelated consumers and their existing lifecycle semantics; broader than this finding. + +**Why option 1:** it fences the last synchronous point before the driver call without changing +unbound tree commands or claiming to cancel writes already in flight. + +**Acceptance:** both bound create commands must perform no write when a latch is set after +resolution; a latch cleared before the callback must also invalidate that attempt. Normal creates +and stale delete-confirmation behavior must remain intact, with appropriate unavailable or +cancellation feedback. + +**Done (2026-11-30), commit [`95cd11d0`](https://github.com/microsoft/vscode-documentdb/commit/95cd11d0ad6249f16b8ea284a9236ca7379761ec) +(WI-H1):** the shared binding check now runs after client resolution, at the last synchronous +point before the operation callback, so Create Database and Create Collection are fenced without a +confirmation epoch. Nine regressions in `runBoundNamespaceCommand.test.ts` cover stale creates, +temporary holds, permanent retirement, same-account replacement and stale delete confirmation. + +## C02. Query generation can sample and send the replacement identity's schema + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4731072559). + +> If a saved connection is edited and reconnected during Copilot availability lookup, this old +> view's request can sample the replacement identity and send its schema to Copilot; discarding the +> reply does not stop that access. Pass the originating session binding and cancellation through the +> host generation path, and validate them before sampling or sending the prompt. Preserve +> sampling-error causes and handle typed unavailable responses so authentication failures also +> reach the recovery dialog. + +**Evidence.** [QueryEditor](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L478) +aborts only locally and discards a late response. Its +[host procedure](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/collectionViewRouter.ts#L497) +passes a cluster ID, not the originating session binding. After awaiting availability, +[generation looks up the current client, samples documents and sends the inferred schema](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/llmEnhancedCommands/queryGenerationCommands.ts#L176). +Its sampling catch creates a new error without `cause`, and the procedure does not return the +typed unavailable response consumed by the recovery dialog. The +[Copilot service](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/services/copilotService.ts#L203) +also awaits model selection after the generator calls it, so a check only at that call boundary +does not cover a later lifecycle change before the actual model request. + +A synthetic probe paused the availability lookup, replaced identity A with B, and observed B's +schema in the messages passed to a fake Copilot service, with no abort signal. A second probe +confirmed that a sampling failure lost its cause. A model-selection probe showed that a pre-call +check can miss invalidation before `sendRequest` when the abort signal has not arrived. The schema +inference sends field names, types and structure, not the sampled field values; nevertheless, it can +disclose B's schema and database/collection names to Copilot from a view belonging to A. No real +model or database was used. + +**Options.** + +1. **Recommended:** resolve the originating `ClusterSession` in the host, carry its binding and + operation epoch through sampling, propagate the webview abort signal to the host and Copilot, + and recheck availability after awaited work and immediately before sampling and the actual + model request, including after model selection. A host-side lifecycle fence or abort must cover + that interval; a delayed webview abort alone is insufficient. Preserve error causes, map + classified connection failures to the existing typed unavailable response, and let the webview + show that response. **Pros:** protects the identity boundary and restores actionable recovery. + **Cons:** touches the host procedure, generator and webview; cancellation cannot retract a + request already sent. +2. Abort locally or only discard the reply. **Pros:** simple and prevents stale UI updates. + **Cons:** does not stop the host from sampling or sending the replacement schema. +3. Temporarily disable AI generation in retained views. **Pros:** fail-closed mitigation. + **Cons:** removes useful functionality rather than repairing the binding. + +**Why option 1:** the guard must be on the side that reads and sends data; a UI-only guard is too +late. Use the existing host-only session and cancellation mechanisms rather than transmitting a +fingerprint or credentials to the webview. + +**Acceptance:** pause availability, sampling and model selection independently, then edit/reconnect +or abort; no replacement client is sampled and no model request starts after invalidation. A +sampling authentication failure retains its cause, reaches the unavailable dialog, and +cancellation remains cancellation. Cancellation of a request already started is best effort. + +**Done (2026-11-30), commit [`54e89081`](https://github.com/microsoft/vscode-documentdb/commit/54e890813f08e7cf015116a430bc5da18e60ae4a) +(WI-H2):** query generation now carries the originating `ConnectionBinding` and the request's +`AbortSignal` from the Query Editor. Every schema sample is fenced against the captured origin, and +cancellation reaches the existing post-model-selection send fence. Sampling errors keep their +cause, and typed unavailable responses cross the telemetry wrapper and reach the Query Editor's +unavailable dialog. Twenty-four new effect cases include same-account replacement, stale +sampling, zero sends after selection and ignored-abort replies. + +## C03. Playground handoffs can adopt a replacement identity + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4731072567). + +> This captures the current host identity only after document-opening awaits, so an edit and +> reconnect during the hand-off can silently bind the new Playground to a replacement connection. +> A retained Shell's Playground link also carries no originating fingerprint and can bind to the +> edited identity. Pass the originating fingerprint and Entra pin through both hand-offs and +> preserve or reject that binding rather than recapturing the current host identity. + +**Evidence.** [New Playground](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/playground/newPlayground.ts#L142) +awaits document creation and display before +[capturing the current host binding](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/playground/PlaygroundService.ts#L169). +The [Collection View handoff](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/collectionViewRouter.ts#L637) +checks its session before calling the command but does not pass its binding. The +[index drawer](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.ts#L335) +does the same. A [Shell link](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/shell/ShellTerminalLinkProvider.ts#L310) +carries the cluster and namespace, not the Shell's fingerprint or pin, and remains available in +terminal scrollback. + +In a synthetic probe, an A-origin handoff paused during document creation, the host changed to B, +and the real Playground binding service captured B's fingerprint and Entra identity. A retained, +uninitialized Shell link also invoked the command without either identity field. Opening the +Playground does not execute its contents automatically; the risk is a later user-run operation, +including an index-creation command prepared by the index drawer, targeting B. + +**Options.** + +1. **Recommended:** carry the originating host-only binding and Entra pin from Collection View, + the index drawer and Shell; revalidate after document-opening awaits, and preserve the original + binding or leave the document unbound with actionable feedback. Also capture the intended + binding before awaits on the tree entry path when one exists. **Pros:** avoids silent rebinding + while retaining navigation and user content. **Cons:** needs a safe policy for a Shell or tree + selection that has no verified origin binding. +2. Pass only fingerprint and pin. **Pros:** smaller and prevents switching to a different + fingerprint. **Cons:** a password-only saved edit can keep the same fingerprint; saved-view + retirement is [generation-based](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/connectionBindingRetirement.ts#L8), + so fingerprint equality alone cannot establish that the originating view is still valid. +3. Disable these handoffs. **Pros:** simple fail-closed behavior. **Cons:** loses normal + cross-feature navigation. + +**Why option 1:** it preserves the source's identity and the saved-edit retirement rule, not just +the current account name. Keep the pin and fingerprint in the extension host, and distinguish a +retired saved edit from an ordinary same-identity client replacement. An anonymous diagnostic +Shell must not silently acquire saved authentication through this handoff. + +**Acceptance:** cover Collection View, index drawer, tree and retained Shell handoffs; edit and +reconnect during document opening; test both different identities and password-only edits with an +unchanged fingerprint. Missing origin identity must not silently adopt a later identity, while +ordinary same-identity recovery and explicit re-pick remain usable. + +**Done (2026-11-30), commit [`c640d447`](https://github.com/microsoft/vscode-documentdb/commit/c640d447d15ddb68dec82f62517880cb3bd5c51e) +(WI-H3):** every Playground hand-off now passes a required `PlaygroundHandoffOrigin`: the +originating binding and Entra pin; a retained Shell's fingerprint, pin and disconnect revision; or +the saved tree epoch. After the document opens, that origin is validated rather than recapturing +the current host identity. A stale origin leaves the Playground unbound and asks the user to +re-pick its connection. Tests cover Collection View, the index drawer, the tree and retained +Shell links. + +## C04. Provider changes are explained as expired sign-in + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4731072583). + +> `EntraSignInRequiredError` also represents a changed Azure cloud or sign-in provider, so this +> message can incorrectly claim expiry and recommend sign-in that cannot succeed with the pinned +> provider. Inspect the error's `reason`, including through causes, and direct `providerChanged` +> users to restore the original settings; use neutral wording for a missing session. Update the +> message expectations and localization too. + +**Evidence.** The +[auth handler](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts#L39) +uses `providerChanged` for cloud, authority or provider changes and `noSession` for a missing +session. The [explainer](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts#L24) +ignores the reason and always says the sign-in expired. Its +[existing test](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts#L15) +explicitly expects that wording for a wrapped `providerChanged` error; a synthetic probe produced +the same result. [Retry sign-in](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/commands/signInAgain/signInAgain.ts#L246) +already has a specific restore-settings message for a directly recognized provider change. + +**Scope caveat:** the [worker protocol](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/playground/workerTypes.ts#L67) +collapses sign-in causes into `signInRequired`, and the relay +[reconstructs it as `noSession`](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/documentdb/auth/WorkerTokenRelay.ts#L40). +Shell and Playground also have their own expiry wording. A change to the explainer alone cannot +identify provider changes on those paths. + +**Options.** + +1. **Recommended:** explain a known `providerChanged` reason with restore-original-settings + guidance; use neutral wording for `noSession` or missing/reconstructed reasons, retaining + cycle-safe cause and per-server traversal. Make the worker-facing generic sign-in wording + neutral as well. **Pros:** removes the false expiry claim without changing the worker protocol; + reuses the established tree recovery guidance. **Cons:** a worker error whose reason was lost + cannot give provider-specific advice. +2. Also preserve a bounded provider-change subreason across the worker relay and its recovery + surfaces. **Pros:** specific guidance is possible in Shell and Playground too. **Cons:** a wider + host/worker protocol and test change; the existing broad sign-in recovery behavior must remain + compatible. +3. Use one neutral message everywhere. **Pros:** smallest truthful change. **Cons:** omits the + actionable restore-settings instruction even when the real reason is known. + +**Why option 1:** it fixes the reviewed host explanation and avoids making a false claim on the +lossy worker paths; option 2 is warranted only if precise worker-specific guidance is required. + +**Acceptance:** test both reasons through direct, nested and driver per-server errors, plus a +name-only reconstructed error and cyclic causes. Update affected message expectations and +localization; preserve the pinned account and do not infer expiry from a missing session. + +**Done (2026-12-02), commit [`f8a6ece4`](https://github.com/microsoft/vscode-documentdb/commit/f8a6ece47ef8eb7622ffd68e386077776432b904):** +the explainer now reads the error's `reason` while walking causes and driver per-server errors. +`providerChanged` gets restore-original-settings guidance for +`microsoft-sovereign-cloud.environment`. `noSession`, or a reconstructed error without a reason, +gets neutral wording: "Microsoft sign-in is required for this connection. Sign in again to +continue." The Shell and Playground messages for the collapsed worker `signInRequired` reason no +longer claim expiry. The worker protocol is unchanged, as option 1 specifies. New explainer cases +cover a nested provider change, a missing session, a name-only reconstructed error and a provider +change inside the driver's per-server errors. Localization was regenerated. Focused run: 206 tests +in three files passed; `npm run build` passed. + +## C05. Stage 3 unavailability is recorded as cancellation + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1136#discussion_r4731072594). + +> When Stage 3 ends with `ConnectionUnavailableError` without an abort, this return leaves the +> completion outcome at `cancel`, incorrectly reporting `aborted='true'` and losing the failure +> reason. Set the error outcome and bounded `unavailableReason` before yielding, since the +> subscriber may immediately unsubscribe. Preserve the cancellation outcome if the request was +> already aborted. + +**Evidence.** The [stream generator](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts#L151) +defaults `outcome` to `cancel`; its +[unavailable catch](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts#L598) +yields and returns without changing it or recording the reason. The completion event therefore +sets `aborted='true'`. The [subscriber](https://github.com/microsoft/vscode-documentdb/blob/1e362403bc13fb0c5451cb84b57a458b8fe6c999/src/webviews/documentdb/collectionView/queryInsightsTab/QueryInsightsTab.tsx#L616) +shows the unavailable state, whose effect can unsubscribe. + +A controlled generator probe injected `credentialsChanged` without an abort, consumed the +unavailable event and immediately closed the iterator. It observed `outcome=cancel`, +`aborted=true` and no `unavailableReason`. This is a telemetry error, not evidence of a failed +recovery dialog. + +**Related edge found during verification:** the generator also sets `success` only _after_ +yielding `complete`. Immediate iterator closure after that event likewise recorded cancellation +in the probe. This is the same terminal-yield ordering problem, not another Copilot thread. + +**Options.** + +1. **Recommended:** if not already aborted, set `outcome=error` and the bounded unavailable + reason before yielding `unavailable`; retain `cancel` for an already-aborted request. Set + `success` before yielding `complete`, after the existing abort check. **Pros:** correct even + when the consumer immediately stops; preserves the UI event and cancellation semantics. + **Cons:** changes the dedicated completion event's classifications. +2. Record the outcome after the yield. **Pros:** minimal apparent change. **Cons:** iterator + closure can skip the assignment, so the defect remains. +3. Keep all early exits as cancellations. **Pros:** no telemetry changes. **Cons:** failures and + completed streams are counted as user aborts. + +**Why option 1:** terminal outcomes must be determined before control is returned to the +subscriber. Record only the existing bounded reason, not error text or connection identifiers. + +**Acceptance:** immediate unsubscribe after an unavailable event records `error`, `aborted=false` +and the reason; an already-aborted request stays `cancel`; immediate unsubscribe after a complete +event records `success`. Check the dedicated completion event separately from the outer RPC event. + +**Done (2026-12-02), commit [`bd7cbee1`](https://github.com/microsoft/vscode-documentdb/commit/bd7cbee1651fc5466e4362e562214f72c8434c86):** +when Stage 3 ends with `ConnectionUnavailableError` and the request was not already aborted, it +now sets `outcome=error` and the bounded `unavailableReason` before yielding the `unavailable` +event. `outcome=success` is set before `complete` is yielded, which also fixes the related edge +found during verification. A request that was already aborted stays `cancel`. A new +`queryInsightsEventsRouter.test.ts` stops the subscription immediately after each terminal event +and checks the dedicated completion event. Without the fix, the unavailable case and the complete +case fail. `npm run build` passed. + +## Verification and limits + +- Read all five threads and traced their production call paths at the stated head. Controlled + probes transpiled the current TypeScript with mocked clients, VS Code APIs and model responses; + they exercised the interleavings described above without network or database access. +- Five existing focused Vitest files passed: **84 tests**. The existing same-fingerprint + retirement test passed separately (**1 passed, 97 skipped**). These passing tests do not cover + the demonstrated gaps. +- No live VS Code, database or Copilot end-to-end reproduction was performed; timing and + external effects in a real installation remain to be verified. +- No implementation, GitHub reply, thread resolution, commit or push was made. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md new file mode 100644 index 000000000..366eac936 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md @@ -0,0 +1,283 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1146] +created: 2026-11-27 +verified: 2026-11-27 +--- + +# PR #1146: Copilot comment validation + +## Scope and review policy + +On 2026-11-27, the lead validated [Copilot's 12 comments](https://github.com/microsoft/vscode-documentdb/pull/1146#pullrequestreview-6090776593) +on [PR #1146](https://github.com/microsoft/vscode-documentdb/pull/1146) at `dec9ac64cbdb18f295fb0f05a7ebe12955703c47` +against `feature/connection-lifecycle`. All threads were current and unresolved. The PR had become +non-draft independently of this review. This ledger records the decisions and checks at the time, +not the current behavior or release status. The [unabridged ledger at `01590e0`](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md) +has the complete options, commands and host usage tables. + +The operator prioritized ordinary workflows without machinery for implausible races, but not at +the cost of data loss, wrong-target execution or automatic replay. All 12 findings were confirmed; +the severity pairs below are **Copilot → assessment**, not a vote on whether to fix. No database +loss was observed. + +## Operator-selected disposition + +The operator selected the recommendation for every item except C10: **"c10, ignore/wont fix."** +Nine fixes were accepted; C05, C10 and C12 were no-code decisions. The technical reasons below +are the review's unless attributed to the operator; no additional operator rationale was supplied. + +### Lead run intake (2026-11-27, 17:17 UTC) + +The operator withdrew **"we skip work items 1 and 2 for now."** as a different-project instruction: +**"here we don't skip 1 and 2"**, then **"we work on all decided/accepted work items."** The initial +endpoint was a committed plan, separate local fixes and Case 1 checks, with replies **"always in +the thread, no one multi-comment."** Push, Case 2, PR-state changes and thread resolution were not +part of that authorization; the later pre-push snapshot records the expanded endpoint. + +### Advisor implementation mapping + +The operator confirmed `claude-opus-5.5` for advice, `gpt-6.1-sol` for C01/C02/C06/C09, +`mai-code-2` for C03/C04/C07/C08/C11 and `mai-code-2-flash` for checks. Actual assignments +matched, without substitutions. C01 preceded C03; the PTY work ran sequentially, with one coder +for C08 then C07 (separate commits), and C07's restore primitive available for C09. + +## C01. Diagnostic worker startup rejects authentication holds + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515405) · High → High. +The [Shell filter](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/ShellSessionManager.ts#L462) +allowed three authentication holds, but the [worker startup assertion](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/playground/WorkerSessionManager.ts#L351) +rejected all three before spawn. Shell tests mocked that boundary; a real Shell-to-worker probe +showed recovery failed safely even for `credentialsRejected`. + +**Selected and implemented:** pass an explicit, host-only diagnostic capability through startup +and share the narrow three-hold predicate. Inferring permission from `NoAuth` would exempt saved +anonymous sessions too. Ordinary Shell/Playground, other holds, abort and epoch checks stayed +strict; no credentials, relay, wire flag or hold clearing. [Fix `476e65176`](https://github.com/microsoft/vscode-documentdb/commit/476e6517689381399f1809dd676782c4e3def625) +added 21 cases; 224 tests passed across four files. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722230665). + +## C02. VM diagnostic Shell can use the wrong port + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515477) · High → Medium. +[Discovery](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/plugins/service-azure-vm/discovery-tree/AzureSubscriptionItem.ts#L105) +seeded port 27017; the [credentials path](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts#L123) +used the user's port without updating the model. The inherited reader could thus target another +server after a custom-port failure. A visible banner was not a guard; no destructive command was observed. + +**Selected and implemented:** remember the credential-free endpoint actually attempted on that VM +node. The reader reflects later attempts, survives credential-cache eviction and fails closed on +unknown/recreated nodes. No diagnostic port prompt, credential fetch, ARM lookup or default fallback. +The lead rejected a silent sanitizer catch even after initial advisor approval. The accepted +revision used outer failure handling; its new test required a cleared endpoint, no client startup +and bounded feedback. [Fix `e3bd77b21`](https://github.com/microsoft/vscode-documentdb/commit/e3bd77b21759f7ca65e8fd9e5c770718e0f9a9d1): +eight cases added, 69 tests passed across three files. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722266137). + +## C03. Stale diagnostic Shell click has generic feedback + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515571) · Medium → Low. +The [command](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/openInteractiveShell/openInteractiveShell.ts#L105) +blocked startup but gave a generic modal. The stale-node claim was qualified: removal/update +could already refresh the provider. **Selected and implemented:** refresh supported views and use +removed/changed wording only when the current typed latch proves the cause. Epoch mismatch alone +is not proof of an edit. Unknown causes and unsupported views kept generic feedback; cancellation +stayed quiet and the original error survived. [Fix `c952e9624`](https://github.com/microsoft/vscode-documentdb/commit/c952e9624c8394205056b297751df4300ffb7a6e): +five cases added, 34 passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722266186). + +## C04. Old Playground sign-in can warn a new connection + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515627) · Medium → Low. +After a document switched from A to B and A was removed, [both stale-feedback branches](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/playground/executePlaygroundCode.ts#L414) +could warn about A against B (before the click or during sign-in). **Selected and implemented:** +check the document's current connection in both branches, not full evaluator ownership: +removal can dispose the evaluator while feedback for the same connection is still legitimate. +No evaluator reset or replay. [Fix `1fdcfd43d`](https://github.com/microsoft/vscode-documentdb/commit/1fdcfd43d8c1421fd3749846c7555e151877b37d): +four race cases added, 38 passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722213773). + +## C05. Completed edit can silently supersede tree sign-in + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515692) · Medium → Low. +A [completed save](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/saveConnectionEdit.ts#L120) +can clear the latch. [Sign-in](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/signInAgain/signInAgain.ts#L146) +still rejected the old credentials/epoch. The probe modeled completion (no real write): tree +refresh, no modal, no client startup. **Selected: won't fix / defer.** Keep quiet supersession +and refresh. Epoch or object inequality cannot distinguish an edit from Retry, reconnect or a +concurrent sign-in; richer attribution would need history or sensitive settings comparisons for +a missing explanation. No guard was relaxed. [No-code reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321228). + +## C06. Genuine sign-in dismissal can show a stale modal + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515749) · Medium → Low. +The [catch order](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/signInAgain/signInAgain.ts#L211) +showed a stale modal when acquisition returned `User did not consent to login.` after removal. +Internal stale acquisition also used cancellation, so reversing the checks would suppress real +stale-action feedback. **Selected and implemented:** identify genuine dismissal at the acquisition +boundary and keep it quiet. Accepted-but-superseded sign-in still explains; worker-origin recovery, +error identity and provider/identity/epoch fences were preserved. [Fix `2688f86ca`](https://github.com/microsoft/vscode-documentdb/commit/2688f86cac9f813df05b63218b50ca2e9d6574bf): +13 cases added, 41 passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722213722). + +## C07. Disconnect restores text but not the cursor + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515827) · Medium → Low. +After [Disconnect](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L282), +inserting `X` at the former position 2 submitted `abcdefX`, not `abXcdef`. The cursor move was +visible; nothing ran automatically. **Selected and implemented:** capture idle single-line text +and its logical cursor together; `restoreLine` uses the wrap-aware renderer, not synthetic arrows. +Share it with C09; do not restore incomplete multiline or queued executing input, reconnect or replay. +[Fix `ce2cf8d8b`](https://github.com/microsoft/vscode-documentdb/commit/ce2cf8d8b11a64260fffafa307e1c897bc46462c): +five cases added, 228 passed. The wrapped Home output changed intentionally; the End assertion did not. +[Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722303779). + +## C08. Anonymous startup failure also notifies the host + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515913) · Medium → Low. +The [startup catch](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L673) +produced both terminal output and a host notification. The advisor considered retaining normal +background visibility a reasonable won't-fix. The lead disagreed: the [feature intent](../README.md#intent) +and [error-translation guidance](../../../../../.github/skills/error-translation/SKILL.md) placed later +diagnostic failures in the terminal. **Selected and implemented:** guard only the anonymous host +notification; keep terminal feedback, safe logging, retry prompt and normal Shell notifications. +[Fix `bd70e3298`](https://github.com/microsoft/vscode-documentdb/commit/bd70e3298ee841fa50ff0bf10981b950dcfec995): +assertions added to two existing tests, 134 passed. Advisor-approved design; lead reviewed the +one-line guard. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722276450). + +## C09. Late Shell sign-in output corrupts the visible prompt + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515975) · Medium → Medium. +[Delayed success/failure](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L1007) +wrote over a live prompt without redrawing input; [writeLine](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L1200) +did not own input state. The advisor rated this upper-Low because the logical buffer survived. +The lead retained Medium: the next submitted command need not match what the user sees. + +**Selected and implemented:** separate asynchronous output from idle input, then restore text +and cursor using C07. The advisor's `showPrompt()`-then-restore proposal would reset multiline +state. Instead, move to End using the old render origin and reset only the physical origin with +`setPromptWidth` at the new prompt. During evaluation or disabled input, queue feedback until a +safe prompt; discard it on Disconnect/close. No history reset or automatic evaluation. +[Fix `b32d0a0dc`](https://github.com/microsoft/vscode-documentdb/commit/b32d0a0dc0e71840d93b55a81c6813520329ecf6): +21 cases added, 249 passed. Six exact-output assertions added the intended redraw without losing +message/no-replay checks. **Accepted residual:** after dismissal of a paste-choice dialog that +doesn't emit a prompt, queued feedback waits for the next prompt. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722358367). + +## C10. Anonymous command result is discarded on host-client churn + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516027) · Medium → Medium for outcome messaging; Low for the rare overlap. +[Anonymous evaluation](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/ShellSessionManager.ts#L399) +discarded a reply after an epoch change, even [host-client deletion](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/ClustersClient.ts#L1252) +at the same endpoint. A command may already have completed; rejecting its reply is not rollback. +Endpoint equality cannot exclude an intervening Disconnect/update. + +**Operator override: "c10, ignore/wont fix."** The review recommended retaining the epoch/latch +fences but changing **evaluation-only** feedback to “This command may have completed, but its result +is no longer current. Check the database before running it again.” The operator did **not** select +that warning or any guard/classification change, and supplied no further rationale. No replay or +second epoch mechanism. [No-code reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321276). + +## C11. Index failures can show two tree modals + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516084) · Medium → Medium. +[Hide](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/index.hideIndex/hideIndex.ts#L74), +drop and unhide presented an error and rethrew; their [tree wrapper](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/ClustersExtension.ts#L1087) +presented it again. The advisor identified the counterexample: [bound-command errors](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/rethrowBoundCommandUnavailable.ts#L9) +can set `suppressDisplay` without presenting anything. **Selected and implemented:** mark the +particular invocation and error only when the callback presents it. No generic suppression or +extra explanation notification. Early validation, primitives and different cleanup errors remain +visible; original identity, telemetry and webview behavior survive. [Fix `61f09ffcd`](https://github.com/microsoft/vscode-documentdb/commit/61f09ffcd6eef8b0e4e035145ab9e8c943df8cf1): +12 cases added, 26 passed including callback/wrapper integration. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722240271). + +## C12. Host-side stale Retry cancellation becomes an alert + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516133) · Medium → Low. +The [host guard](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/documentdb/boundViewOperations.ts#L55) +could cancel a stale Retry without a new unavailable event. The [hook](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/documentdb/useBoundViewRecovery.ts#L150) +then showed a generic failure; the [transport](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/_integration/trpc.ts#L149) +had no reliable client-side cancellation discriminator. This was a hook probe, not end-to-end RPC. +**Selected: won't fix / defer.** Keep bounded “Try Retry again” feedback and Retry itself. The view +stays blocked and contents survive; nothing replays. A typed result across three routers was not +selected; string matching or suppressing all internal errors could hide real failures. +[No-code reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321308). + +## Verification and outcome + +**Validation, before fixes:** explicit REST and GraphQL reads agreed on head and threads; the +active-PR tool had returned an unrelated cached PR. There was no additional substantive human +feedback. Source tracing covered all 12 items; the advisor's counterexample/provider sweep was +narrow, not a feature-wide audit. Nine files passed 428 tests (eight temporary probes); a second +run of three overlapping files passed 72 (four more probes). These were **12 distinct probes, not +500 distinct tests**. They asserted observed behavior, including defects, and were removed. No +`TDD:` contract failed. No production edit, commit, push or reply occurred in validation. + +## Lead outcome (2026-11-27, 17:53 UTC snapshot) + +### Unverified live checks first + +- **C02:** real Azure VM, failed custom-port attempt, diagnostic Shell banner/target, then a + refreshed/recreated node with no known endpoint. Expected: unavailable, never fallback to 27017. +- **C07/C09:** installed terminal, idle/mid-line/wrapped Disconnect; delayed success and failure + with partial, multiline and evaluating input. Compare visible text to the next read-only submission. +- No live account dialog, real server mutation, screen-reader or full transport cancellation test. + Mocked VM attempts and PTY output do not establish these results. + +### Endpoint and completed work + +The nine fixes were separate **local** commits when the individual replies were posted; the remote +head was still `dec9ac64c`. All 12 threads received individual replies, none were resolved, and +there was no omnibus comment or PR-state change. The lead recorded two planning and ten logic +consultations across nine advisor contexts. All final logic revisions were accepted (C08 used a +lead mechanical review); C02 required rework. No unresolved technical question was parked. + +### Final verification + +**Case 1:** `npm run build`, then 13 targeted Vitest files with `--maxWorkers=2`: **652 passed, +0 skipped, 0 failed** (17.58s). This superseded the build-pending notes in the replies. No `TDD:` +failure or dependency/localization change. The tracked tree was clean; the two pre-existing +untracked connection directories were untouched. This was not a full +[CONTRIBUTING §6](../../../../../CONTRIBUTING.md#6-ai-assisted-review-workflow) review or a live check. + +### Usage snapshot + +17:17:00.522Z–17:53 UTC, lead run only: **917.2 AIU** (249.0 leader, 668.2 subagents). Advisor: +522.2 (56.9%), including 334.5 for the planning context with the late C09 follow-up. The audit +suggested smaller planning packets and a fresh context for late questions, not a model downgrade. +[Per-model requests, times and tokens](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md#usage-snapshot) +exclude later persistence and the final response. AIU are not dollars; request spans overlap. + +## Case 2 pre-push verification (2026-11-27, 18:24 UTC snapshot) + +The operator expanded the endpoint: **"run case 2 checks, address issues, then push."** This +snapshot is **after local verification, before the authorized push**; it does not attest delivery or CI. + +### All eight commands passed + +`npm run l10n` left the bundle unchanged; `npm run prettier-fix` formatted nine tracked files +([`e33bb7bb1`](https://github.com/microsoft/vscode-documentdb/commit/e33bb7bb11f0fba90c59afcd7c29b9610ff993f3)). +`npm run l10n:check`, `npm run build`, `npm run typecheck:tests` and `npm run package` passed +(VSIX `vscode-documentdb-1.1.1-alpha.4.vsix`, 9,268,165 bytes). Full `npx vitest run`: **10,294 +passed, 1 skipped, 451 files** (118.89s), before the test-only corrections below. Afterwards +`npm run lint` passed in full and the two affected suites passed 26/26, not 26 additional unique +tests. No production change after build, strict test type-check and package; no `TDD:` failure, +dependency change, larger heap or worktree-ignore workaround. + +### C11 fixture correction + +[`2589ec75d`](https://github.com/microsoft/vscode-documentdb/commit/2589ec75d3a4a4b2169598858487bd045d813e5d) +replaced a primitive throw with a typed `mockRejectedValue(error)` and called a typed throwing +cleanup function in `finally`. An intermediate `Promise.reject(error)` had also failed lint. +No rule was disabled; rejection identity, modal counts, explanation telemetry, cleanup precedence +and exact replacement-error assertions remained intact. + +### Publishing and remaining checks + +The authorized destination was `dev/tnaum/connection-lifecycle-ux` → `feature/connection-lifecycle` +in #1146, milestone 1.2.0. Thread updates were to cite published commits, not resolve threads. +Case 2 did not complete the VM/terminal checks above or certify all §6 initial-review, validation +and sweep stages. + +### Case 2 follow-up usage + +17:59:57.853Z–18:24 UTC, separate from the lead run: **364.7 AIU** (336.1 leader, 28.6 subagents). +Leading accounted for 92.2%; a smaller verification context was suggested. The +[follow-up audit](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md#case-2-follow-up-usage) +excludes publication, later persistence and final response; rounded rows and overlapping +cache/reasoning fields are not additive. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md new file mode 100644 index 000000000..42e72fc6f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md @@ -0,0 +1,440 @@ +--- +feature: connection-lifecycle +kind: plan +status: historical +created: 2026-11-27 +code: + - src/tree/documentdb/ClusterItemBase.ts + - src/tree/documentdb/DatabaseItem.ts + - src/tree/documentdb/IndexesItem.ts + - src/tree/BaseExtendedTreeDataProvider.ts + - src/commands/openInteractiveShell/openInteractiveShell.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/shell/DocumentDBShellPty.ts + - src/commands/playground/executePlaygroundCode.ts + - src/webviews/documentdb/useBoundViewRecovery.ts + - src/webviews/components/DisconnectedOverlay.tsx + - src/documentdb/connectionTeardown.ts + - src/tree/connections-view/DocumentDBClusterItem.ts + - src/commands/showConnectionStats/showConnectionStats.ts + - src/commands/showWorkerStats/showWorkerStats.ts +--- + +# Iteration 2: implement the connection-lifecycle UX review findings + +> **Historical plan and execution record, 2026-11-27.** The [UX review](./01-pr1136-ux-review.md) +> holds the observations and alternatives. Below, each work item separates the original +> request from its disposition. The [unabridged plan and checkpoints](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md) +> preserve the sequence between the initial local-only authorization and the later Case 2 run. + +This is not a current specification. See the [feature overview](../README.md) and +[decisions](../decisions.md), especially 0031–0036: the later design no longer lets +an explicitly disconnected retained tab resume database operations. + +## Goal and scope + +The plan covered F1–F5 and F7–F12. Recovery must preserve the bound identity, never +replay an operation, keep tree recovery rows actionable and report failures on the +initiating surface. F6 was accepted as-is; Q1 needed no extension change; the +Dashboard diagnostics link went to #1141. Network resilience, account sign-out, +telemetry redesign and unrelated error copy were out of scope. + +## Authority and decision gates + +**At intake:** F2/F3 and F8–F12 had approved directions, not necessarily final copy. +F1's Shell behavior/label, F4's Retry feedback and F5's stale-click policy still +needed operator decisions; F7 needed live evidence. The plan required rechecking the +source, tests and localization, using existing surfaces, and recording significant +choices with the operator's rationale, not promoting suggestions to decisions. + +### Execution authorization (2026-11-27) + +The operator invoked `/lead` and approved the choices below for **local work and +commits**. No push, external edit or Case 2 handoff was initially requested. + +- Advisor: `claude-opus-5.5`. +- WI-1 expansion, WI-2, WI-3 and WI-5: `mai-code-2`, substituted for the advisor's + `gpt-6.1-terra` recommendations at the operator's request. +- WI-4: `gpt-6-luna`, the advisor's mechanical-copy recommendation. +- WI-1 stale recovery and WI-6: `gpt-6.1-sol`, retained for lifecycle/authentication logic. +- Tests, builds and other tool-running agents: `mai-code-2-flash`. +- F1: replace the error-row action with **Open shell without authentication**, using the + bounded authentication/endpoint policy in [decision 0022](../decisions.md#0022-offer-a-separately-unauthenticated-shell-from-failure-rows-only). +- F4: option B, with the bounded copy and in-view announcement in + [decision 0023](../decisions.md#0023-keep-retained-view-retry-failure-feedback-inside-the-unavailable-dialog). +- F5: option C, with the explicit-click and quiet-background policy in + [decision 0024](../decisions.md#0024-classify-explicit-stale-recovery-clicks-and-explain-only-failed-actions). +- F3: explicit tree-origin commands are included; webview-origin feedback is unchanged + ([decision 0025](../decisions.md#0025-tree-origin-failures-use-modals-webview-origin-command-feedback-stays-unchanged)). +- WI-2: the operator requested proposed copy for other unavailable reasons before editing; + the subsequent reason-specific Shell/Playground proposals were approved. Changed + identity/settings and sign-in messages remain unchanged. Single-line partial Shell input + is preserved; partial multi-line and queued evaluation input are cleared, as approved. +- WI-4: F10 changes explanatory copy only; the opt-in credential-save branch is unchanged. + The final approved wording retains the cluster and successful decoded-password context: + **Connected to "{cluster}" using the decoded password. Would you like to update your + saved credentials with the correctly formatted password?** +- F3 expansion: the operator selected extension-owned TreeViews only. Azure Resources + remains unchanged, with enhancement [#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) + created at their request. Foreground-origin/event-order verification is still required + before implementing owned-view expansion. +- F7: current source inspection has not established a defect. A live reproduction is + still pending; no speculative menu change is authorized. + +## Workstream order and dependencies + +WI-0 checked the baseline. Its F5, F4 and F1 decisions gated WI-1's stale actions, +WI-3 and WI-6 respectively; WI-2, WI-4 and WI-5 needed no such choice. Only a +reproduced F7 would open WI-7. Work could be grouped by surface as long as each +behavior and its tests remained independently reviewable. + +## WI-0: Revalidate findings and settle decision gates + +**Plan:** compare source/tests to the review; present the [O2 Retry alternatives](./01-pr1136-ux-review.md#o2-where-should-a-failed-in-view-retry-be-explained-f4) +and [O3 stale-click alternatives](./01-pr1136-ux-review.md#o3-how-should-an-explicit-stale-action-end-f5). +Settle the failure-row Shell label without changing normal startup. Record each choice or blocker and +collect the F7 build, client, latch and refreshed context tag. + +**Result:** the advisor checked `dd11ca7d3`; the operator settled F1/F4/F5 above. The +connected tag required a cached client without a hold; credential-save completion +released the update hold. That did not reproduce or disprove F7. The operator chose +live testing, not a speculative fix; WI-0 remained incomplete on that point. + +## WI-1: Align tree-action failures and stale explicit recovery (F3, F5) + +**Plan:** one modal per failed tree action, including database/index expansion, with a +translated heading and separate detail; children remain actions. Test the provider and +commands for duplicate feedback. For F5, test refresh on an explicit stale click, an +accurate explanation only on actual failure, and quiet cancellation/disposal/obsolete +background replies. Never bypass identity, epoch or latch guards to complete a click. + +> **Deferred, escalated (2026-11-27), WI-1a/F3 descendant expansion:** the advisor +> (`claude-opus-5.5`, 40% confidence in origin attribution) found no documented ordering +> between `onDidExpandElement` and the first failing `getChildren`. Options were modals +> for all owned-view failures including background refresh, a workbench event-order probe +> without an API guarantee, or deferral. The operator explicitly chose to ship +> tree-command alignment and defer descendant expansion to +> [#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) until foreground +> attribution is supported. No expansion code was changed. The issue records Azure +> scenarios, benefits, background-noise risks and host-coordination trade-offs. + +**WI-1b — explicit tree commands (`57f96b23b`).** Cluster-associated commands got the +single modal. Changing Diagnostics in place resolved the wrapper choice without changing +registrations, public arguments or webview/no-cluster feedback. Review checked callers, +cancellation, original error identity and feedback ownership (advisor 90%; worker's azext +runtime check 99%). Fourteen tests added; Batch 1 build passed, 67 tests in seven files. +Case 2 had not run. + +WI-1c split F5 by the surface that owned the action: + +**WI-1c-tree — stale clicks (`c77ba2115`).** Under option C, supported actions +refreshed first; only a proven removal/change gave a modal. Disconnect during sign-in +retained the closed-connection explanation. Worker sign-in entry, identity checks, +key/latch mutations and unsupported Azure Workspace guards stayed intact. No helper +export/expansion. Epoch-only tests expected silence but still checked no auth started. +44 cases added across three command files; 73 passed (advisor 85%, worker 97%). + +**WI-1c-worker — stale sign-in (`0a01a24e4`).** Only a click from a still-open +terminal/file with a typed removed/changed latch got worker-specific guidance. +Cancellation, closed work, reported revisions, epoch-only and no-latch states stayed +quiet; no reset, stop, restart or rebind. A helper-name error was corrected before edits +to reuse `handleWorkerFailure` and `getPlaygroundRecovery`. Ownership assertions stayed; +the telemetry mock suppressed only the fire-and-forget sign-in action. 38 cases added; +163 passed (advisor 85%). + +## WI-2: Correct worker recovery guidance and Shell status output (F2, F8) + +**Plan:** localize the rerun guidance and align the manual; do not promise worker-local +variables survive restart. Test same versus changed/removed bindings, and separate +system output from idle, partial and evaluating input. Check manual links/content where +available. WI-2a took the unit-testable wording first; WI-2b ran last because terminal +timing needed a live check. No concurrent Shell edits or added workstream. + +**WI-2a (`a2eba522a`):** unchanged settings prompted a tree reconnect and new run in +the existing terminal/file, not a new Shell or pick. Stricter reasons stayed distinct. +The leader checked selector/direct-latch reuse (99%); tests kept no-start/no-replay +assertions and used `vi.waitFor`, not a fixed sleep. 18 new cases in two files; 118 passed. + +**WI-2b (`9d434732d`):** “Disconnected” got its own line. The approved policy restored +single-line input and cleared partial multiline and queued evaluation input. Wrapped +input moved the caret to the end first so no old tail appeared beside the status. +Five cases added; 134 Shell tests and the post-fix build passed (advisor 88%). +Real terminal behavior remained a workbench gate. + +## WI-3: Keep failed retained-view Retry feedback in context (F4) + +**Plan:** if the operator chose O2/B, distinguish the unavailable reason from the +latest attempt. Test typed and thrown failures, restored controls (Retry/Close/X), +announcement, copy access and no replay in the shared hook/overlay and all three views. +No stacked host modal, speculative network diagnosis or raw stack. + +**Correction:** the first implementation passed 19 tests and type-checking but could +hide a _new_ removal/settings/identity reason (advisor 80%). The operator qualified +the choice (**2.A**): show the true current reason, but do not take away a previously +offered Retry. They chose **1A**, the current unavailable episode: dismissal/reopening +does not end it; successful recovery does. A later Close-only episode does not inherit +Retry. Neither identity nor hold checks change. + +**Result (`6d2e10715`):** each failure announced a separate bounded alert in the dialog. +Retained Retry dispatched `retry`, never `close` or the interrupted operation. Eight +cases added across two files; 23 passed (advisor 88%). An interim type-check met +unfinished WI-6 edits; WI-6 later passed the root check. + +**Fixture repair (`039c1cbd8`):** six Document View routes failed because the fixture +did not acknowledge the void `reportDirty` mutation. Returning transport-compatible +`null` fixed the fixture, not the application (`mai-code-2`; leader review 99%). +The rerun exercised the mutation with no remaining page, CSP, RPC or assertion failures. +See [Verification](#verification) for the routes/themes; source scenarios did not verify +the live extension host or screen reader. + +## WI-4: Clarify teardown and retained-content wording (F9–F11) + +**Plan:** localize and test three wording changes, not new behavior. “Keep open” drops +the confusing disabled suffix, not the operation block or its help. The F10 prompt +above explains what the opt-in action saves without showing the password. “Dismiss +dialog to access view contents” names inspection as well as copying, not reconnection. + +**Result (`5d00558cb`):** the operator corrected the leader's generic F10 wording +before commit to retain the cluster and successful decoded-password context. Teardown +settings, save branch and guards stayed unchanged (leader review 99%). One new workflow +test proved dismissal did not save; 26 tests passed in three files, including after +the correction. Batch 1 passed; live presentation was still unverified. + +## WI-5: Unify human-readable debug-stat formatting (F12) + +**Plan:** use labeled multiline records, consistent headings/indentation, explicit units, +one missing-value convention and no rulers. Test readable output and redaction, not +incidental whitespace. A cached client is not a ping; pending startup is not a live +connection. Keep host and worker counts, held states, Entra expiry, session IDs, +initialization durations and existing username facts only where available. + +**Result (`e4a6ad337`):** both commands used **(not available)** for missing fields; +review confirmed the values and redaction boundaries stayed intact (leader 99%). +A typed evaluator with a mocked worker replaced an `as never` fixture. Five new tests; +nine passed across both files, also included in Batch 1. + +## WI-6: Offer an unauthenticated Shell from connection failure rows (F1) + +**Plan:** distinguish the error-row entry from ordinary authenticated context-menu +startup without reordering recovery rows. Test both paths: no credential read, +mutation or fallback on the anonymous path; if a database command is rejected, +report that failure. Opening a Shell does not authorize an operation. + +> **Gate resolved (2026-11-27):** the worker stopped before edits because URI parser errors +> can contain credentials. Advisor `claude-opus-5.5` approved a constructor-only bounded +> replacement at 90%, and removing every mixed-case credential-key spelling at 95%. +> The operator selected **1.A**: **Invalid connection string.**, with the unsafe parser +> error/cause discarded entirely. WI-6 implementation resumed with the previously approved +> zero-cache, endpoint, trust and lifecycle constraints. + +> **Completion scope approved (2026-11-27):** the operator questioned blanket removal of +> working suggestions, then agreed to an internal `includeClusterMetadata` flag that preserves +> local completion/ghost behavior but excludes authenticated shared metadata from the new +> anonymous diagnostic path. The completion provider and its existing tests are directly +> dependent owned files. Normal Shell behavior is unchanged; no fake IDs, new setting or +> blanket completion disablement was authorized. + +> **Done (2026-11-27), commit `aea08108a`:** the failure-row Shell is a separate NoAuth entry +> with a sanitized, re-read endpoint and epoch/latch guards. It does not read `CredentialCache`, +> alter saved credentials/clients, use shared authenticated metadata, pin an authenticated +> identity, create a token relay, fall back to saved authentication or replay operations. +> Local completion/history/bracket behavior and normal Shell startup are preserved. Constructor +> parser errors become the approved bounded message without an unsafe cause. Pre-terminal +> failures use one modal; later driver failures stay in the terminal. +> Decisions: operator, explicit F1 authentication/endpoint/parser/metadata boundaries; advised +> (`claude-opus-5.5`), 88% full-path approval and 90% approval of the final pre-terminal hunk. +> Actual/recommended model: `gpt-6.1-sol`. Seventy-two cases were added across the existing/new +> test files; the initial eight-suite run passed 392 tests without TDD failures, the final +> command suite passed 29 and the strengthened Shell suite passed 111. Root type-check passed; +> build/localization followed in the final batch. No public command contract or manifest entry was added. + +## WI-7: Investigate F7 only if WI-0 reproduces it + +**Conditional plan:** fix only a demonstrated refresh/context-tag defect. Regression +test the exact repaired-and-connected transition and that Disconnect stays hidden for +disconnected/error items, no client or an active latch. A negative live run needed a +record of the build and state checks before closing F7 without code. + +> **Deferred, escalated (2026-11-27), operator decision:** leave F7 pending live testing +> with no speculative implementation. On the current build, try failed saved-password +> connection → Update Credentials → **Yes, reconnect now** → databases appear → +> right-click the refreshed cluster. Capture whether **Disconnect** is present, the cached +> client/held state from **Show Connection Stats**, and whether collapse/expand or Refresh +> changes the menu. Record the actual build/commit and state; do not label a source-only +> check **not reproducible**. + +## Cross-workstream verification + +The plan called for a Case 1 build (`npm run build`) and focused tests +(`npx vitest run `) for each implemented workstream, plus webview +scenarios where behavior changed. Check action-only rows, identity safety and +`vscode.l10n.t()` usage; regenerate localization for changed strings and edit the manual +only for changed guidance. Record deviations and negative evidence, not just passes. +Case 2 was a separate handoff gate. Results for both endpoints follow. + +## Progress + +| WI | Status | Outcome / decision / verification | +| ---- | ----------------------------------------------------------- | ----------------------------------------------------------------- | +| WI-0 | Gates approved; F7 live evidence pending | Current-code baseline checked; no live reproduction claim | +| WI-1 | Implemented and locally verified; expansion deferred | `57f96b23b`, `c77ba2115`, `0a01a24e4`; F3 expansion follows #1143 | +| WI-2 | Implemented and locally verified; terminal check pending | `a2eba522a`, `9d434732d`; final Shell suite 134 passed | +| WI-3 | Implemented and locally verified | `6d2e10715`, fixture `039c1cbd8`; 24 source routes passed | +| WI-4 | Implemented and locally verified; live presentation pending | `5d00558cb`; generated localization current | +| WI-5 | Implemented and locally verified | `e4a6ad337`; Batch 1 build/tests passed | +| WI-6 | Implemented and locally verified | `aea08108a`; full-path approval 88%, final hunk 90% | +| WI-7 | Deferred pending operator reproduction | No speculative code change; exact live sequence recorded | + +## Outcome + +**Initial endpoint: local work, committed and Case 1 verified.** No push or review handoff was requested. +The only external edit was the operator-requested enhancement issue +[#1143](https://github.com/microsoft/vscode-documentdb/issues/1143). No CI run for a pushed head +is claimed. Case 2 (including `prettier-fix`, lint, strict package-test type-check, full runtime +suite and packaging) had not run at this point; see the [subsequent authorization and results](#case-2-follow-up-2026-11-27). + +### Unverified workbench checks + +1. **Shell output:** disconnect while idle, with partial single-line input, with a long wrapped + input whose caret was moved Home, in multiline mode and while evaluating. Verify a separate + system status line, preserved visible single-line input, cleared multiline/queued input and + no stale output or replay. Try this before pushing. +2. **F7:** run the recorded failed-password → Update Credentials → reconnect → refreshed + Disconnect-menu sequence on the current build. Capture client/held state; do not infer a + regression from source or label it not reproducible without the live run. +3. **Presentation/accessibility:** inspect the Keep open/decoded-password/X copy in the workbench + and verify a real screen reader notices each failed Retry. Source browser and ARIA tests are + not a screen-reader or installed-extension check. + +### Verification + +- `npm run l10n`: passed; generated bundle committed separately as `6959c70f5`. +- `npm run build`: passed in the final batch and again after the last wrapped-cursor fix. +- Focused runtime batch: **18 files, 583 tests passed** (11.33 s). +- After the last added regression: the unchanged earlier files retain that result; the final + Shell suite was rerun separately and **134 tests passed** (11.36 s). No combined 584-test + invocation is claimed. +- Browser manifest/route tests: **47 passed** with the browser-specific Vitest config. +- Real source browser helpers: **24 unique routes ready** across all three themes: + Collection View 9, Document View 9, Dashboard 6. A missing void-mutation fixture caused six + initial Document View failures and was repaired in `039c1cbd8`; the rerun passed. +- No TDD contract failures. One interim root type-check saw concurrent unfinished NoAuth edits; + the later root type-check and final builds passed. +- All owned browser/watch helpers were stopped. No dependency installation was required. +- Unrelated untracked `.copilot-connection-relays/` and `.copilot-connection-telemetry/` were + left untouched. + +### Decisions, review and model plan + +Thirty substantive advisory packets ran across six `claude-opus-5.5` agents. The exact +code revisions received logic reviews under the approved model mapping. Decisions +0022–0025 record the operator's choices; WI-1, WI-3, WI-4 and WI-6 record where a +proposed implementation was rejected or corrected and why. + +### Usage: cumulative run + +Start **2026-11-27 11:06:38 UTC**, snapshot **14:23 UTC**: approximately 196 minutes wall-clock. +Model-request spans below sum to 162m20s; overlapping model/tool/check spans are not additive. +Build and localization durations were not separately reported. The final response and subsequent +progress-record writes are excluded from this snapshot. AIU are not dollars. + +| Model | Role | Requests | Summed model time | AIU | Share | +| ---------------- | ------- | -------: | ----------------: | -----: | ----: | +| claude-opus-5.5 | advisor | 146 | 21m16s | 1277.8 | 47.6% | +| gpt-6-luna | coding | 13 | 1m13s | 2.0 | 0.1% | +| gpt-6.1-sol | leader | 135 | 95m58s | 1019.3 | 37.9% | +| gpt-6.1-sol | coding | 123 | 23m46s | 321.0 | 11.9% | +| mai-code-2 | coding | 89 | 16m13s | 64.5 | 2.4% | +| mai-code-2-flash | checks | 41 | 3m54s | 1.7 | 0.1% | + +| Role | Requests | Summed model time | AIU | Share | +| ------- | -------: | ----------------: | -----: | ----: | +| leader | 135 | 95m58s | 1019.3 | 37.9% | +| coding | 225 | 41m12s | 387.5 | 14.4% | +| advisor | 146 | 21m16s | 1277.8 | 47.6% | +| checks | 41 | 3m54s | 1.7 | 0.1% | + +**Totals:** leader 1019.3 AIU; subagents 1667.0 AIU; run 2686.3 AIU. + +| Model / role | Input | Output | Cache read | Cache write | Reasoning | +| ------------------------- | ---------: | ------: | ---------: | ----------: | --------: | +| claude-opus-5.5 / advisor | 11,507,254 | 125,393 | 9,846,990 | 1,659,908 | 66,048 | +| gpt-6-luna / coding | 723,017 | 9,623 | 653,250 | 69,728 | 6,183 | +| gpt-6.1-sol / leader | 30,887,461 | 244,993 | 30,106,530 | 780,526 | 174,956 | +| gpt-6.1-sol / coding | 10,009,918 | 77,779 | 9,413,490 | 596,059 | 27,223 | +| mai-code-2 / coding | 5,329,087 | 47,245 | 4,499,968 | 0 | 20,975 | +| mai-code-2-flash / checks | 923,922 | 9,468 | 708,096 | 0 | 4,554 | + +Cache/reasoning fields may overlap input/output; do not sum them into a purported token total. + +### Usage: resumed work + +Separate window **12:37:15–14:24 UTC**, approximately 107 minutes wall-clock, following the +operator-reported authentication restoration. The original blocked edit succeeded on retry; +no alternative access route was used while it was denied. This window is a subset of the +cumulative run, not an additional charge to add to it. + +| Model | Role | Requests | Summed model time | AIU | Share | +| ---------------- | ------- | -------: | ----------------: | ----: | ----: | +| claude-opus-5.5 | advisor | 47 | 6m25s | 503.8 | 30.8% | +| gpt-6.1-sol | leader | 72 | 72m44s | 849.7 | 52.0% | +| gpt-6.1-sol | coding | 89 | 18m37s | 250.9 | 15.4% | +| mai-code-2 | coding | 45 | 6m34s | 28.6 | 1.7% | +| mai-code-2-flash | checks | 36 | 3m36s | 1.4 | 0.1% | + +| Role | Requests | Summed model time | AIU | Share | +| ------- | -------: | ----------------: | ----: | ----: | +| leader | 72 | 72m44s | 849.7 | 52.0% | +| coding | 134 | 25m11s | 279.5 | 17.1% | +| advisor | 47 | 6m25s | 503.8 | 30.8% | +| checks | 36 | 3m36s | 1.4 | 0.1% | + +**Resumed totals:** leader 849.7 AIU; subagents 784.7 AIU; run 1634.4 AIU. + +| Model / role | Input | Output | Cache read | Cache write | Reasoning | +| ------------------------- | ---------: | ------: | ---------: | ----------: | --------: | +| claude-opus-5.5 / advisor | 3,209,592 | 37,413 | 2,449,519 | 759,947 | 19,439 | +| gpt-6.1-sol / leader | 23,416,229 | 178,087 | 22,779,798 | 636,215 | 147,875 | +| gpt-6.1-sol / coding | 7,974,254 | 62,647 | 7,521,903 | 452,084 | 21,678 | +| mai-code-2 / coding | 2,962,098 | 17,172 | 2,607,104 | 0 | 7,978 | +| mai-code-2-flash / checks | 836,803 | 9,122 | 674,304 | 0 | 4,476 | + +**Optimization:** advising was the largest cumulative category (47.6%); leading was the largest +resumed category (52.0%). Repeated contract clarification, broad initial reading and long leader +turns were substantial overhead compared with coding/checks. For a future run, consolidate UX and +ownership gates into one compact packet, correct exact interfaces before dispatch, and keep leader +handoffs short. Preserve the approved model plan; these unlike tasks do not establish a model-quality +ranking. + +## Case 2 follow-up (2026-11-27) + +The operator requested committing the work, running the full Case 2 list, addressing failures, +then pushing once. A dedicated draft head, `dev/tnaum/connection-lifecycle-ux`, targets +`feature/connection-lifecycle`; the milestone is 1.2.0. The earlier local-only outcome above is +the record of the preceding endpoint, not the current publishing authorization. + +| Command | Result | +| ------------------------- | ----------------------------------------------------- | +| `npm run l10n` | Passed | +| `npm run prettier-fix` | Passed; 18 formatted files committed as `6a8ad8756` | +| `npm run l10n:check` | Passed | +| `npm run lint` | Passed with the default heap after the fixes below | +| `npm run build` | Passed; rerun after the scoped lint fixes | +| `npm run typecheck:tests` | Passed (exact strict package-test script) | +| `npx vitest run` | 449 files passed; 10,205 tests passed, 1 skipped | +| `npm run package` | Passed; rerun after fixes, producing the current VSIX | + +The first lint run exhausted the default Node heap. The operator identified the main-branch +worktree exclusion fix, which was ported from `f38e0282f` as `9553a3810`, without merging unrelated +main changes. Its regression test passed, and lint no longer required an increased heap. +The now-completing lint run exposed 20 diagnostics in seven changed files; `mai-code-2` corrected +only type-visible comparisons, mock/error typing, synchronous awaits and log inspection. +All existing assertions, unknown-error coverage, error identity, view identifiers and redaction +coverage were retained. Those fixes are committed as `feb640c3f`; targeted lint and 63 focused +tests passed. Final default-heap lint, build and packaging passed after targeted formatting. +The added worktree regression passed; its three ported files passed the formatting check. + +Readiness remains separate from publishing: there is no committed Section 6 AI pre-review file +for this UX round. The dedicated PR stays draft. The live workbench/F7/screen-reader checks and +the explicit #1143 deferral remain as recorded above; no human-review readiness is claimed. +No unrelated untracked `.copilot-connection-*` directories were changed. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md new file mode 100644 index 000000000..ba379364f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -0,0 +1,1384 @@ +--- +feature: connection-lifecycle +kind: analysis +status: historical +prs: [1136] +created: 2026-11-29 +verified: 2026-11-30 +code: + - src/commands/saveConnectionEdit.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/connectionTeardown.ts + - src/documentdb/connectionBindingRetirement.ts + - src/documentdb/connectionFingerprint.ts + - src/documentdb/connectionSurfaces.ts + - src/documentdb/ConnectionUnavailableError.ts + - src/commands/runBoundNamespaceCommand.ts + - src/commands/signInAgain/signInAgain.ts + - src/webviews/documentdb/boundViewOperations.ts + - src/webviews/documentdb/useBoundViewRecovery.ts + - src/webviews/components/DisconnectedOverlay.tsx +--- + +# PR #1136: can the connection lifecycle be much simpler? + +## Verdict + +**Recover the connection, not a retired tab.** A socket closing does not mean the user chose +Disconnect. The “80%” is a product priority, not a measured usage share. Build and verify the +common path first. [Decisions 0031–0032](../decisions.md) define the following minimum for #1136; +[section 6](#6-packages-regenerated-2026-11-30) compares the packages as proposed on November 30. +The [implementation handoff](#implementation-handoff) records what landed; the [feature README](../README.md) +gives current status. The scenarios below describe the decision at the time, not later UI wording. + +| What the user does or sees | What must happen | +| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Work continues across Entra token expiry or the machine wakes after sleep | Renew silently or recover the connection for the same account. Keep the tab, query and draft. If an operation failed, report it; don't silently replay it. | +| Silent renewal needs help | Offer **Sign in again** in the tree for the pinned account. Once repaired, the user can run the next operation **in the same tab**. No separate Retry to unlock it. | +| Explicit **Disconnect** or **Remove** | Honor Close/Keep/Cancel and protect unsaved edits. A **kept** tab is permanently read-only, even after reconnecting to the same account. New work belongs in a fresh tab. | +| Look at a kept tab | Show a notice such as **“This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.”** **X** dismisses the notice for copying; **Close view** closes the tab. Neither enables database access. | +| Change credentials or the connection string | Offer **Disconnect and update**. Edit only once the old session has ended. This is a new session, not same-account repair. | +| Use Shell or Playground | Renew and recover for the pinned account without a background prompt. Keep scrollback or file text on Disconnect, stop the worker, and never replay a command or silently bind old work to another identity. | + +**Scope cutoff.** The things missing from that user-facing list are safeguards, not new flows: +keep unsaved text, block teardown during an active transfer, and prevent old work from acting on +a new connection. No multi-identity reconnect, tab revival, cross-window synchronization or new +recovery setting. The separate Azure Discovery token fix, existing diagnostic Shell option and +telemetry are already on the branch; none requires more features for this minimum to be met. + +The deeper read corrects four claims in the first version: + +1. **A closed or disabled panel can still have host work in flight.** A picker, schema lookup or + model-selection await can outlive it. A2/B2 simplify identity policy, but do not make + [C01-C03](./02-pr1136-copilot-review.md) disappear without replacement cancellation guards. +2. **B2 needs host enforcement, not just a React boolean.** It is still substantially simpler + than recoverable retained tabs. Closing all tabs is not required to get that saving. +3. **Same-identity client replacement is part of today's token recovery**, not a speculative + edge case. The small internal generation counter is not the main maintenance cost. +4. **The earlier 70% and 2,000-3,000-line savings are not verified deletion budgets.** Keyword + counts measure footprint, not removable code; some guards and tests must survive. + +The useful new precondition is: **before changing connection settings, end the old connection's +ability to start work, including its retained surfaces and pending handoffs**. This is narrower +than continuous fingerprint comparison, but needs enforcement at asynchronous side-effect +boundaries. No software or GitHub discussions are changed by this document. + +## 1. How the complexity grew + +[Decision 0012](../decisions.md) approved a minimal design on 2026-11-19: no state machine, one +epoch, no prompts in `getClient`, one-step teardown, "I don't want too many managers, controllers, +and reconcile tools." The same day, 0013 added back latch-before-save, epoch checks on replies, +bindings through handoffs and the `runWithClient` wrapper. Each addition answered a real omission +found in review. The pattern since then is that every review of an invariant finds another place +where it is not enforced. + +| Date | Decision | What it added | +| ---------- | --------- | ---------------------------------------------------------------------------------------- | +| 2026-11-19 | 0003 | The invariant: an open surface never moves to a different identity | +| 2026-11-19 | 0004/0007 | Disconnect asks Close all / Keep open; a setting stores the default | +| 2026-11-19 | 0012 | **Minimal design approved** | +| 2026-11-19 | 0013 | Latch before save, epoch on replies, bindings through handoffs, `runWithClient` | +| 2026-11-23 | 0014/0015 | Keep settings after rejection; reuse the latch to block startup | +| 2026-11-24 | 0016/0017 | Full-view overlay; Retry and Close view only | +| 2026-11-24 | 0018 | Saved edits lock views permanently (a simplification that still needs a retirement map) | +| 2026-11-24 | 0019 | Dashboard delete confirmation does not survive Disconnect | +| 2026-11-26 | 0021 | HMAC-keyed fingerprint, plus a CodeQL exception | +| 2026-11-27 | 0022–0025 | Anonymous Shell entry, in-dialog retry feedback, stale-click classification, tree modals | + +The cost shows up as review findings, not only as lines: + +- **PR 5 review** ([bound surfaces](./01-pr5-bound-surfaces-review.md)): all six validated findings + (F1–F4, N1, N2) are about operations that continue, or are interrupted, across a binding change. +- **Iteration 2 review** ([02-pr1146](./02-pr1146-copilot-review.md)): by title, five of twelve + findings are "stale action after a lifecycle change" (C03, C04, C05, C06, C12). +- **This PR's Copilot review**: C01, C02 and C03 are call sites that forgot the fence. + +The checks are costly to propagate consistently. They also expose real asynchronous hazards: +removing the checks does not remove those hazards. The simplification should reduce the number of +policies and representations while keeping a small shared cancellation contract. + +## 2. Measured footprint + +Merge base `60e17e46` with `origin/main`, head `1e362403`. + +| Measure | Value | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | +| Files changed | 281 | +| Production code (src + packages) | +10,008 / −2,807 | +| Tests | +13,417 / −427 | +| Docs | +8,517 | +| `ClustersClient.ts` | 1,477 → 2,096 lines | +| Added production lines that use the binding vocabulary (`binding`, `fingerprint`, `epoch`, `latch`, `assertCurrent`, `unavailable`, `retire`, the nine reason names) | **1,428 of 9,587 (15%)**; 645 of 3,325 (19%) in `src/webviews` | + +The keyword share measures the spread of the vocabulary, **not a lower bound on deletable code**. +Neighbouring lines also participate, but many matching guards remain useful after simplification. + +Concept spread in production code (grep hits / files): + +| Concept | Hits / files | +| ------------------------------------------------------- | ------------ | +| epoch, `assertCurrent`, `beginOperation` | 344 / 51 | +| `ConnectionUnavailableError` | 118 / 33 | +| `entraIdentity`, `lastVerifiedIdentity` | 112 / 24 | +| `ConnectionBinding`, `getBinding`, `resolveBoundClient` | 80 / 24 | +| latch (`latch`, `getLatchReason`, `unlatch`) | 77 / 21 | +| `fingerprint` | 64 / 10 | +| `describeUnavailable`, `ConnectionUnavailableReason` | 58 / 18 | + +Latches are set only by the rejection paths (`credentialsRejected`), teardown (`userDisconnected`, +`connectionRemoved`, and `credentialsChanged` as a teardown reason) and the edit path +(`credentialsUpdating`, plus restoring `previous`). `identityChanged` is never latched: it comes from +binding mismatches and failure classification, and appears in about 20 production sites. +These other reasons are not merely presentation: typed failures stop operations and the classifier +can evict or hold a client. Reducing UI reasons does not justify deleting authentication policy. + +## 3. Scenario map + +"Wanted" means it belongs to the original ask (renewal, reconnect) or is a safety need. + +| # | Scenario | Wanted? | Cost today | Proposal | +| --- | ----------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------- | +| S1 | Token expires, silent renewal | Original | Core callback; small | **Keep** | +| S2 | Sleep or network drop, reconnect | Original | Closed-client replacement; moderate | **Keep** | +| S3 | Silent renewal impossible, sign-in needed | Original | Tree action plus overlay, Retry, binding re-check | **Keep tree sign-in; D2 removes the recovery dialog** | +| S4 | Server rejects credentials | Safety | Latch prevents retry storms and lockout | **Keep** (one latch reason) | +| S5 | Disconnect | Added | Close/Keep modal, setting, retained disabled views, Reconnect, Retry | **Keep the choice; B2 retained views never revive** | +| S6 | Remove connection or folder | Added | Batch latching, epoch and latch recovery, retained views | **Limit: same teardown as Disconnect** | +| S7 | Update credentials or connection string while connected | Added | `saveConnectionEdit`, retirement map, pin diffing, shell modal | **Limit: disconnect first** | +| S8 | Update credentials while not connected | Main | Was a few lines on `main` | **Keep editing; serialize save against reconnect** | +| S9 | Sign in again as a different account | Added | Account-label heuristic, `identityChanged` for open views | **Limit: pinned account only** | +| S10 | Retained disabled view: Keep open, Retry, Reconnect resumes | Added | Binding, generation, overlay, hook, revision guards in three views | **Keep copyable contents; drop revival** | +| S11 | Handoffs from a bound view (create, delete, import, export, indexes, playground, Copilot) | Added | `runBoundNamespaceCommand`, `boundViewOperations`, binding carry-through | **Simpler host lifetime/cancellation; not unguarded clusterId** | +| S12 | Dashboard delete confirmation across Disconnect (0019) | Added | Epoch snapshot per pending delete | **Keep cancellation; share the lifetime guard** | +| S13 | Shell and Playground after a lifecycle change | Partly | Per-worker pins, anonymous Shell entry (0022) | **Keep pins; worker simplification needs an explicit rebind policy** | +| S14 | Worker token renewal (`WorkerTokenRelay`) | Original | 307 lines | **Keep** | +| S15 | Running transfer blocks teardown | Safety | Task guard | **Keep** | +| S16 | Another window edits the same connection | None | No cross-window watcher; equality guards can reject observed changes | **Do not confuse no watcher with no protection** | + +### S1. Token expires (same before and after) + +```mermaid +flowchart LR + A["User connected, working"] --> B["Token expires"] + B --> C["Driver calls the OIDC callback"] + C --> D{"VS Code refreshes the session silently?"} + D -- yes --> E(["Operation continues, user sees nothing"]) + D -- no --> F["Typed sign-in-required error"] + F --> G["Tree: Sign in again"] + G --> H(["Same account signs in, next operation works"]) +``` + +### S2. Sleep or network drop (same before and after, except the last node) + +```mermaid +flowchart LR + A["Machine sleeps or network drops"] --> B["Next operation"] + B --> C{"Connection usable?"} + C -- "driver reconnects" --> D(["Callback renews token, operation succeeds"]) + C -- "client was closed" --> E["Closed client replaced on next use"] + E --> D + C -- "network still down" --> F(["Ordinary error: connection lost, try again"]) +``` + +Today's behavior varies by path: Collection View already adds "Run the query again" to some +closed-client failures; the bound namespace helper converts transient failures to `unreachable`, +which can produce an overlay. D2 removes that recovery-dialog distinction, not driver recovery. +An operation that already failed is not automatically replayed, especially a write. + +### S3. Sign-in needed while a view is open + +Today: + +```mermaid +flowchart TD + A["Operation fails: sign-in required"] --> B["Whole view blocked by overlay, blocking ref set"] + B --> C["User signs in from the tree"] + C --> D["User clicks Retry in the overlay"] + D --> E{"Binding, retirement, latch, epoch checks"} + E -- ok --> F(["Announces Reconnected; the failed operation is not replayed"]) + E -- failed --> B +``` + +Proposed B2: + +```mermaid +flowchart TD + A["Operation fails: sign-in required"] --> B["Ordinary error with 'Sign in again from the tree'"] + B --> C["User signs in from the tree"] + C --> D(["User runs the operation again; it works"]) +``` + +### S5. Disconnect + +Today: + +```mermaid +flowchart TD + D["Disconnect"] --> T{"Transfer running?"} + T -- yes --> B(["Blocked, modal lists tasks"]) + T -- no --> Q{"Views open? Modal or setting: Close all, Keep open, Cancel"} + Q -- Cancel --> X(["No change"]) + Q -- "Close all" --> DIRTY{"Dirty Document View, discard?"} + DIRTY -- no --> X + DIRTY -- yes --> C + Q -- "Keep open" --> C["Commit: latch, epoch, disable views, stop workers, close client"] + C --> R["Reconnect row"] + R --> N["Reconnect: unlatch, new client"] + N --> V["Each kept view: Retry with binding check; Dashboard may auto-retry"] +``` + +Proposed: + +```mermaid +flowchart TD + D["Disconnect"] --> T{"Transfer running?"} + T -- yes --> B(["Blocked, modal lists tasks"]) + T -- no --> Q{"Close tabs, keep read-only, or cancel?"} + Q -- cancel --> X(["No change"]) + Q -- close --> DIRTY{"Unsaved edits: discard confirmed?"} + DIRTY -- no --> X + DIRTY -- yes --> C["End host lifetimes; close selected views"] + Q -- keep --> K["End host lifetimes; keep contents permanently read-only"] + C --> R["Stop workers and close client; tree offers Reconnect"] + K --> R + R --> N(["Reconnect; open fresh views; old snapshots stay read-only"]) +``` + +The existing setting can supply the tab choice; its default is the asking path. This does not +authorize a new remembered-choice mechanism. If "still ask" means ignoring an explicitly configured +Close/Keep setting, that would be a separate change. None is proposed here. + +### S7. Update credentials or connection string while connected + +Today (credential prompts precede the save latch): + +```mermaid +flowchart TD + U["Update credentials / connection string"] --> WIZ["Prompt for new settings"] + WIZ --> M["confirmTeardown before save"] + M --> L["Latch credentialsUpdating"] + L --> W["Execute save: secrets, then metadata (not atomic)"] + W --> R{"Re-read storage: changed?"} + R -- no --> UL["Restore or clear the latch, case by case"] + R -- yes --> RT["Retire views by generation, disable surfaces, stop playground, delete client and credentials"] + RT --> P{"Auth method or tenant changed?"} + P -- yes --> PC["Clear or discard the Entra pin"] + P -- no --> UL + PC --> UL + UL --> SH["Shell modal: disconnect workers?"] + SH --> E(["Old views permanently dead; reopen from the tree"]) +``` + +Approved A2 (reuses Disconnect, including its tab choice and task/dirty checks): + +```mermaid +flowchart TD + U["Update credentials / connection string"] --> K{"Connection open?"} + K -- no --> W + K -- yes --> Q{"Offer Disconnect and update"} + Q -- Cancel --> X(["No change"]) + Q -- Confirm --> D{"Disconnect completed?"} + D -- "cancelled, blocked, failed" --> X + D -- yes --> W["Edit while reconnect is excluded; save"] + W --> C["Clear stale cached credentials and pin before any later connect"] + C --> R(["Reconnect row; the new connection starts clean"]) +``` + +A1 was accepted on 2026-11-29 and replaced by A2 on 2026-11-30. A2 need not be one dialog total: +the tab choice and dirty-document confirmation still apply. Cancelling the edit after a completed +Disconnect leaves the connection disconnected; do not add automatic rollback/reconnect. + +This removes the need to preserve a live identity during an edit. It does **not** remove the need +to serialize saving against reconnect or to report a partially failed storage write (section 5A). + +### S6. Remove connection or folder + +Today: confirmation, then a batch latch of every descendant, the Close/Keep choice, a conflict +re-check, a commit, and recovery of epochs and latches if the removal is refused midway. + +Proposed: + +```mermaid +flowchart TD + A["Delete connection or folder"] --> B["Confirm destructive action"] + B --> C{"Any transfer running on a descendant?"} + C -- yes --> D(["Blocked, modal lists tasks"]) + C -- no --> E["For each connected descendant: same teardown as Disconnect"] + E --> F(["Delete from storage, drop credentials and pin, refresh tree"]) +``` + +Keep the existing commit-time task recheck and batch invalidation. The preflight alone is not a +replacement for them; partial storage removal and cancellation still need a truthful outcome. + +### S9. Sign in again as a different account + +Today the tree command lets the user choose another account when VS Code reports a different +account label, which changes the identity under open views and is why `identityChanged` exists. + +Proposed: + +```mermaid +flowchart TD + A["Tree: Sign in again"] --> B["Sign in; session must be the pinned account"] + B --> C{"Same account?"} + C -- yes --> D(["Connection restored"]) + C -- no --> E(["Refused: use Update credentials to switch accounts"]) +``` + +This removes account switching from Sign in again and permits deleting its label heuristic +(about 15 lines). It does not eliminate identity mismatch errors from authentication: the provider +can still return an unexpected account or change environment. Worker identity pinning stays. + +### S11. Handoffs from a view + +```mermaid +flowchart LR + V["View action"] --> H["Capture host lifetime and cancellation"] + H --> W["Await picker, client, or model selection"] + W --> G{"Origin still active at side-effect boundary?"} + G -- yes --> O(["Perform operation once"]) + G -- no --> X(["Cancel; do not adopt a replacement connection"]) +``` + +Today's coverage is incomplete, as C01-C03 show. Ending a panel does not unwind already-running +JavaScript. Preserve cancellation before database writes, sampling, model sends and binding a +new Playground. The original document incorrectly treated the wizard-spanning-reconnect risk as +accepted; the operator has not approved dropping these guards. + +## 4. Measured components, not a deletion budget + +Line counts rechecked at `1e362403` on 2026-11-30 (including comments and blank lines): + +| Component | Lines | Revised disposition | +| --------------------------------------------------------- | ------: | --------------------------------------------------------------------------------------------------------- | +| `connectionSurfaces` | 39 | Keep registration; B2 needs host lifetime invalidation as well as notification | +| `connectionTeardown` | 337 | Keep Close/Keep, dirty checks, task guard and removal cleanup; shrink edit-specific policy | +| `saveConnectionEdit` | 152 | Replace live-edit reconciliation with disconnected editing; save exclusion and failure reporting remain | +| `useBoundViewRecovery` | 192 | D2 replaces its recovery workflow; retain simpler frozen-state and stale-reply checks | +| `DisconnectedOverlay` + stylesheet | 145 + 3 | B2 keeps or simplifies the copy/Close presentation; not wholly removable | +| `describeUnavailableConnection` + `connectionUnavailable` | 83 + 83 | Narrow/rework under D2; actionable error translation and frozen notification remain | +| `boundViewOperations` | 127 | Recovery part shrinks; side-effect and late-reply guards survive in a smaller form | +| `runBoundNamespaceCommand` | 49 | May consolidate, but do not remove cancellation before create/delete | +| Fingerprint + retirement modules | 39 + 17 | Retirement can be replaced by permanent surface lifetime; fingerprint removal needs C's coverage gate | +| `useBoundViewRecovery.test.tsx` | 436 | Some episode/Retry tests disappear; frozen state, cancellation and dirty-close contracts still need tests | + +The four recovery/presentation TypeScript files total **503 lines**; including the stylesheet, +**506**. They are a concrete simplification target, not 506 deletable lines. The old "about 1,095 +measured removals" combined measurements with assumed replacement sizes and was mislabeled. + +## 5. Proposals + +The 2026-11-30 follow-up distinguishes product choices from correctness mechanisms. References +below point to code read at `1e362403`; proposed APIs and states are not implemented. + +### A. Identity changes only while disconnected (S7, S9) + +**Approved: A2.** Offer **Disconnect and update** instead of sending the user to find Disconnect. +Perform the ordinary Disconnect flow, then edit only after it completes. Keep the tab choice and +task/dirty guards. A2 is orchestration around one teardown, not a second teardown implementation. + +**What becomes simpler:** no live client has to coexist with partially changed credentials; no +password-versus-tenant diff is needed to decide whether an old tab can survive the save. After a +write attempt, stale authentication state must not be reused. Cancel before writing leaves stored +credentials unchanged; cancel after Disconnect does not silently reconnect. + +**What the earlier estimate missed:** + +- `exists(clusterId)` is not "there is nothing left to disconnect." Authentication rejection can + evict the host client while panels or workers remain. There can also be pending startup. + [Disconnect](../../../../../src/commands/disconnect/disconnect.ts) currently returns early when + there is no client or a latch, and `commitTeardown` can return `superseded`. A2 must cover these + cases and distinguish completion from cancellation; blindly calling the command is insufficient. +- During a wizard, another command can reconnect. The minimum is a **safe save**, not a lock + for the time the user spends typing: revalidate after the prompts and refuse a stale save if + the session or settings changed. Once a save starts, exclude conflicting local saves and + reconnect until the storage writes finish. Prefer the existing latch/epoch; do not queue + reconnects, resume stale wizards, or try to roll back Disconnect. +- [saveConnectionEdit](../../../../../src/commands/saveConnectionEdit.ts) handles non-atomic + secrets/metadata writes. Ending the old lifetime removes the need to reconcile _live views_ on + partial failure, not the obligation to report an incomplete save and clear stale cached auth. + +**Trade-off:** A1 is marginally smaller, but A2 removes a navigation dead end without adding +live credential migration. This is a good UX/maintenance trade. The accepted account restriction +remains: Sign in again is for the pinned account; switching accounts uses this edit flow. + +### B. Keep tabs without keeping their connection alive + +**Chosen: B2 (decision 0031, reaffirming 0027).** Preserve the user's Close/Keep choice, but make Keep mean +**keep the contents read-only, not keep a connection that can be resumed**. + +| Choice | User experience | Maintenance cost | +| ----------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| B1: close | Copy first; all result tabs disappear at Disconnect | Smallest UI, but still needs cancellation of host work | +| B2: keep a frozen view | Copy loaded results, queries or unsaved text; reconnect opens new live views | One-way host lifetime + presentation; no recovery negotiation | +| Current recoverable retention | Reconnect/sign in, then Retry may revive the tab | Identity comparison, retirement exceptions, recovery RPC and UI episodes | + +The useful boundary is **one-way versus reversible**, not open versus closed. B2 has only +`active -> frozen -> closed`; no `frozen -> active` transition. An ordinary temporary network +failure does **not** freeze the tab permanently; that is D's separate choice. + +#### Actual work B2 requires + +1. **Retain what is already loaded.** No new persistence, serialization, or duplicate snapshot + model. A kept tab consumes memory until closed; it does not promise restoration after VS Code + restarts. Copying existing text is supported, not fetching the next page or server-side export. +2. **Make the host state terminal before closing the client.** Collection and Document controllers + currently implement `disable` by posting a message: + [collection controller](../../../../../src/webviews/documentdb/collectionView/collectionViewController.ts), + [document controller](../../../../../src/webviews/documentdb/documentView/documentsViewController.ts). + Their host routers rely on bindings/latches, not a permanent disabled flag. Once those guards + shrink, a delayed message or direct RPC must still be unable to start database work. +3. **Use a shared host lifetime reference, not a copied boolean in an RPC context.** + [attachTrpc](../../../../../packages/vscode-ext-webview/src/host/attachTrpc.ts) shallow-clones + the context per request (lines 351 and 235). A shared state object, closure or cancellation + signal stays observable across awaits; a primitive copied at dispatch does not. + Gate database/handoff routes and native context-menu commands, while keeping local Copy and + Close available. Do not duplicate credential fingerprints in React. +4. **Cancel pending work, not only future clicks.** Close aborts the transport; Keep does not. + A B2 host lifetime must invalidate active requests too. Both B1 and B2 still need cooperative + checks at external side-effect boundaries: JavaScript promises do not stop just because the + transport discards their replies. +5. **Keep the dismissible notice.** Show why the tab is permanently read-only. Its **X** must + expose the existing query, results and draft for local selection/copy without closing the tab + or re-enabling operations. **Close view** is separate and retains the dirty-document warning. + The notice needs no Retry, recovery RPC or success transition. +6. **Fix Dashboard reuse for old and new panels.** + [openClusterDashboardWebview](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts) + currently reveals any matching panel, and may auto-retry it. A frozen panel must not block + opening a fresh live Dashboard. Its native menu context currently identifies only + cluster/database, not the originating panel + ([contract](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardContextMenu.ts)). + A command from an old snapshot must not look up the new live panel and run there. Use an + originating panel/session handle for host validation, or remove operational menus from frozen + snapshots with equivalent host rejection. Merely replacing the `openPanels` entry is unsafe. + +**Cost assessment:** more than "one React boolean", but bounded. Registration, dirty tracking, +the Close/Keep prompt, loaded content and much of the presentation already exist. The incremental +cost over B1 is frozen-state enforcement, copy/Close presentation and panel routing; host +cancellation is needed under **both** choices. The 337-line teardown is not B2's incremental +cost: much of it is removal, telemetry, task exclusion and cleanup. + +**Why choose B2:** it retains a concrete benefit without promising revival. The earlier 70% +estimate had no defensible denominator; withdraw it. Evaluate this choice by the small number of +states and required boundary tests, not a speculative deletion percentage. + +#### Workers are not ordinary retained webviews + +- [Shell disconnect](../../../../../src/documentdb/shell/DocumentDBShellPty.ts) (line 289) kills + the worker but leaves the prompt enabled. `ShellSessionManager` retains a fingerprint and Entra + pin when restarting. Scrollback also contains active Playground links. B2 for webviews does not + automatically authorize removing those worker checks. +- [PlaygroundService](../../../../../src/documentdb/playground/PlaygroundService.ts) retains a + document connection separately from its evaluator. Stopping the evaluator does not make the + file unbound. `PlaygroundEvaluator` checks both worker replacement and document identity. +- **Recommended scope:** keep worker authentication/pins in this package. A later simplification + can make old Shells copy-only and require an explicit Playground connection re-pick after + Disconnect, but that is another user-visible restriction, not a free consequence of B2. + +### C. What a generation protects, and whether one ID is enough + +**Short answer:** yes, a client-generated ID supplied by the caller is a generation/token. +Its name is not important. **When it changes and who must retain it are important.** + +There are three different questions in the current code: + +| Question | Current mechanism | Necessary after A2/B2? | +| --------------------------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| Did this error come from the client still in the cache? | Physical client `generation` in `reportFailure` | Yes; generation or object identity is sufficient | +| Did Disconnect/recovery supersede an unfinished startup or operation? | `_epochs`, latches and cancellation | Yes; a generation assigned only after successful startup cannot cover this | +| May an old surface use a different physical client? | Fingerprint equality plus retirement-generation cutoff | Simpler with immutable live settings and one-way frozen surfaces; still needs host lifetime enforcement | + +#### Same identity, failed client: this is existing recovery, not future speculation + +Most ordinary network drops can be handled by the driver's own pool; they do not require a new +`MongoClient`. But an explicitly closed topology or a failed OIDC callback can require replacement. +In the installed driver, `CallbackWorkflow.withLock` awaits the prior lock **before** assigning the +promise that could recover it. Once the callback rejects, later calls hit that rejected lock. +The same account signing in successfully does not repair that old workflow object. + +This is reflected in +[failure classification](../../../../../src/documentdb/connectionFailures.ts) (closed-client, +callback-failed and sign-in-required policies) and +[replacement tests](../../../../../src/documentdb/ClustersClient.test.ts) (lines 832-863). +It belongs to the original request to recover without restarting VS Code. No production frequency +was measured here, so this is a verified mechanism, not a claim that it happens often. + +Example: + +```text +Query A uses client 7 + -> callback fails + -> explicit recovery / next foreground operation publishes client 8, same account + -> Query A reports a late error from client 7 + -> ignore that error for cache mutation; do not evict healthy client 8 +``` + +The generation check is enough for this question. A reference comparison with the actual failed +client is equivalent within one host. Keep the existing generation if changing it saves little: +it already supports connection diagnostics and `clientGeneration` telemetry +([ClustersClient](../../../../../src/documentdb/ClustersClient.ts), lines 90-110, 1174-1209, 2095). +It need not be exposed to React or copied into every command's inputs. + +#### Why the existing generation is not a lifetime ID for the tab + +Every successful physical-client publication increments it (line 1137). In contrast, +`resolveBoundClient` deliberately permits a newer generation with the same fingerprint +(lines 889-908). Thus `oldTab.generation === currentClient.generation` would change behavior: +**a same-account repair would invalidate the tab**. + +You can choose that restriction, but it makes token recovery less transparent. Updating every +tab's generation after a successful repair recreates the rebinding coordination we want to remove. +Checking only the current latch also fails: Disconnect and Reconnect may both finish while a +request is awaiting a picker, so the latch is clear by the time it resumes. + +#### Your ID idea: viable if it represents a logical connection lifetime + +```text +Connection lifetime L1 + -> driver 7 replaced by driver 8 for the same account: still L1 + -> explicit Disconnect: L1 ends permanently + -> reconnect (even same account): L2 + -> old caller supplies L1: reject; new caller supplies L2: allow +``` + +Capture the token in a **host** session/controller once and let a shared operation boundary ask +`ClustersClient` to validate it. It can be an opaque object/cancellation signal in this host; a +monotonic ID is useful when crossing a process boundary. It is not a credential and need not be +persisted. A request must not recapture the current token after an await, because that silently +adopts L2. + +This removes identity inference from most surface code, but not all propagation: commands that +outlive their source still need the source lifetime/signal, and non-database side effects such as +`sendRequest` need a check at their actual boundary. A guard only inside `getClient` is too early. +The existing `_epoch` cannot simply become this permanent lifetime token: it also advances on +unlatch, sign-in recovery and client deletion (lines 342-359, 920-937, 1197, 1257). + +**Chosen: C-balanced (decision 0031):** + +- Keep the small physical-client generation **inside client acquisition/failure accounting**. + Swapping it for object identity is optional cleanup, not the architectural prize. +- Keep startup epoch/cancellation. For B2, use a one-way host surface lifetime and carry that + through pending handoffs. Reuse the current wrappers and transport signals; do not introduce a + general lease manager, state machine, or public caller-ID framework. +- A centrally issued logical lifetime ID is a reasonable alternative if it genuinely replaces + scattered surface guards. Do not add it alongside every old mechanism and call that simpler. +- Retire fingerprint/retirement plumbing only after all settings mutations and worker/surface + entry paths either preserve the live lifetime's authentication or end it. Keep exact Entra + account/tenant/provider checks at authentication. A lifetime ID cannot detect an identity + change that bypassed its issuer. + +#### Potential future uses + +A logical lifetime is useful for more asynchronous commands, cursors and background work that +must stop at Disconnect. The existing internal generation remains useful for stale failures and +diagnostics. Neither requires storing credential-derived equality data on every view. + +A fingerprint can be useful if a future requirement allows tabs to follow changed settings, +revalidates independently started workers, or coordinates changes observed from another source. +Those are precisely the policies to decide explicitly, not speculative reasons to preserve all +current plumbing. A host-keyed HMAC is not itself a cross-window coordination protocol. + +**Bottom line:** keep a small generation; reduce how far lifecycle policy leaks. "Cluster ID +only, no cancellation" and "one generation does every job" are both misleading simplifications. + +### D. Separate permanent disconnection from a failed operation + +D originally bundled two different UI responsibilities: + +1. **B2's permanent state:** this tab can never run again. Its contents and a read-only explanation + must remain, with a Close action. +2. **Recoverable failure:** this connection can work again after the network returns or the same + account signs in. Today the UI can put the whole tab behind a recovery dialog. + +Removing responsibility 2 does **not** require removing responsibility 1. + +#### What happens today + +[useBoundViewRecovery](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts) has: + +- rendered dialog state plus a separate blocking ref that survives dismissal; +- a revision/disposed guard, recovering flag, latest recovery failure and announcement; +- an episode-level `retryOffered` flag: once visible, Retry stays even if the reason changes; +- a recovery RPC and different reset/advance options for the three views. + +[recoverBoundView](../../../../../src/webviews/documentdb/boundViewOperations.ts) checks the +binding, retirement and latch and obtains a client. **It does not rerun the failed query/save.** +Success says "Reconnected"; the user then performs the operation again. The +[overlay](../../../../../src/webviews/components/DisconnectedOverlay.tsx) adds Close confirmation, +dismissal, inert content and retry-failure feedback. + +Ordinary errors already coexist with this mechanism. For example, +[ClusterSession](../../../../../src/documentdb/ClusterSession.ts) (lines 351-374) can say to run +the query again, and Dashboard has inline failure reporting and background failure counts. D +does not mean replacing every current error with a new notification system. + +#### Choices + +| Choice | Behavior | Pros | Cons | +| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| D1: keep recoverable overlay | Failure blocks the tab; tree repair, then Retry to unlock | Most explicit global connection status; closest to current UX | Keeps recovery RPC, episode rules and duplicate host/UI recovery state | +| **D2: frozen notice + ordinary recoverable errors** | Only explicit Disconnect/Remove freezes; otherwise report failure and let the next explicit operation use the repaired client | Removes a recovery step and most episode machinery; preserves B2 | A user can repeat an operation while still offline and receive another error | +| D3: permanently freeze on every connection failure | Error means reopen a fresh view | One-way state everywhere | Punishes transient failures and same-account sign-in; undermines the original goal | + +**Chosen: D2 (decision 0031).** Concrete flows: + +```text +Query -> silent token refresh succeeds -> query succeeds; no new UI + +Query -> sign-in required -> actionable operation error + -> Sign in again in tree, same account -> Run query again + +Query -> network still down -> operation error, keep query/results + -> network restored -> Run query again + +Save -> uncertain connection failure -> explain failure; keep edited text + -> user checks/retries deliberately; never automatically replay the write + +Credentials rejected -> repair requires editing settings -> Disconnect and update + -> old kept tab stays read-only; run in a NEW tab + +Disconnect -> Keep open -> read-only notice -> X -> select/copy loaded text + -> Reconnect -> open a NEW tab; old tab never offers Retry +``` + +Retain translated, actionable errors and authentication holds. Removing `describeUnavailableConnection` +as a recovery-dialog mapper is not permission to display raw driver exceptions or erase error +causes. In particular, no automatic prompts from token callbacks and no repeated attempts after +credential rejection. + +**Background work needs its own restraint:** frozen tabs stop polling. A live Dashboard can keep +its existing failure counts/inline status for transient reads, but background requests must not +start a replacement client, prompt for auth, or raise repeated dialogs. Preserve +`background: true` acquisition policy and quiet failure handling; if a timer still checks a held +connection, it must not repeatedly hit the database. Removing the overlay alone does not prove +these properties. + +**What D2 can remove:** the retry/unlock mutation and success response, Retry-episode bookkeeping, +recovery-failed-versus-original-reason state, and auto-retry-after-reconnect. Frozen notification, +Close/dirty handling, ordinary errors, cancellation and latest-result guards remain. In particular, +Document View's editor revision prevents overwriting a user's edits with a late read; it is not +disposable "recovery complexity". + +This changes 0016/0017/0023 for recoverable webview failures. It does not automatically supersede +0024's tree/worker stale-click behavior or 0025's origin-specific feedback. D2 is selected by 0031; +its implementation remains pending. + +### E. Simplify handoff guards; do not delete their contract (S11, S12) + +Fold repeated identity comparisons into C's host lifetime boundary. Keep source cancellation +through create/delete confirmations, query generation and Playground opening. In C02, stopping a +late UI update cannot stop the host from sending a prompt; in C03, closing the originating view +cannot undo a later capture of the replacement identity. + +**Recommendation:** consolidate existing helpers where their contracts align. Do not promise to +delete both helpers in section 4 or cancel only at RPC entry. Keep decision 0019's no-stale-delete +behavior, implemented through the common lifetime rather than a separate Dashboard policy where +possible. C01-C03 require boundary fixes or an explicit product limitation; they are not resolved +by a documentation decision. + +### F. Keep the core + +Silent Entra renewal pinned to account and tenant (0001, 0010), failure classification and +closed-client replacement (`reportFailure`, `connectionFailures`), single-flight startup, +`WorkerTokenRelay`, tree **Sign in again** and Retry, the credential-rejection latch, the transfer +guard on Disconnect, and the azureauth upgrade (0005). These carry the feature the operator asked for. + +No map-count target or unrelated anonymous-Shell redesign is part of this simplification. + +## 6. Packages (regenerated 2026-11-30) + +**Chosen package: P (decision 0031).** A2, B2, C-balanced and D2 are selected, with guarded +handoffs. All packages retain F: renewal, pinned sign-in, +same-account client replacement, startup single-flight, rejection holds, worker token relay and +the transfer guard. + +| Package | Contents | What becomes simpler | What remains / trade-off | +| ---------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| **P: practical simplification (chosen)** | A2 + B2 + C-balanced + D2 + guarded handoffs | No live credential migration, no revival of retained tabs, no separate recoverable-view Retry workflow; consolidate host guards | Keep copyable snapshots, internal client generation, startup epochs, cancellation and worker pins | +| U: preserve recovery UI | A2 + B2 + C-balanced + D1 | Removes live edits and post-Disconnect revival only | Lower UX change, but retains most recovery hook/mapper/episode machinery; smaller architectural saving | +| X: close-only | A2 + B1 + C-balanced + D2 | P plus no frozen-tab UI or old/new Dashboard snapshot coexistence | Smallest surface policy, but loses the user benefit explicitly valued here; host guards are still needed | + +**Why P:** it limits the hard-to-maintain promise (resume a retained view), rather than the useful +one (read/copy its contents). It also removes a redundant recovery step: repairing the connection +in the tree and then unlocking the view through Retry. It does not spend engineering effort +removing a cheap, useful generation counter. + +#### How much simplification is actually supported by the evidence? + +- **High confidence, structural:** one-way frozen lifetime replaces recovery after explicit + Disconnect; one shared disconnected-edit flow replaces live-edit reconciliation; D2 removes + the separate recoverable-view episode/unlock workflow. +- **Measured work area:** 506 lines of recovery presentation/protocol, 152 of live-edit handling, + and the 17-line retirement module: **675 current lines to rework**, plus integrations in the + three views/controllers. Some of those 675 lines must remain or be replaced. This is **not** + 675 net deletions, nor an exhaustive total. +- **Conditional:** broad fingerprint and bound-command deletion needs the lifecycle coverage gate + in C, especially Shell/Playground and alternative settings sources. Do not count it in P's + guaranteed saving. Worker pins stay in the bounded package. +- **Tests:** shrink tests for removed retry episodes and live-edit permutations, but preserve + stale-request, save-failure, dirty-content, worker renewal and same-identity replacement tests. + The 436-line hook suite measures current test footprint, not deletable test lines. + +Withdraw the original R/M estimates (2,000-3,000 production lines and "70%") as decision criteria. +A defensible net deletion count requires an implementation diff; this analysis verifies the +mechanisms and boundaries, not that hypothetical diff. + +#### Implementation handoff + +The November 30 plan started from `3d66aa937`, with a passing build and 271 focused tests. +Renewal and worker tests could proceed independently; edits, views and asynchronous handoffs +depended on ending the old host session **before** cleanup could wait. Each entry below gives +the outcome, not a new task. The [original handoff at the reviewed revision](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md#implementation-handoff) +retains the per-slice commands, receipts and intermediate failures. + +- **R — pinned recovery (`b58b74501`).** Tree sign-in accepts only the original account ID. A late + failure from the old physical client cannot evict its replacement. +- **W — worker isolation (`4c5ff5fa2`).** The test waits until evaluation actually reaches the old + worker before Disconnect. Stopping earlier had tested startup cancellation, not in-flight work. + The new worker gets neither the stale token reply nor an automatic replay. +- **F — retained views (`b7fd8bff5`, `7417e01ea`).** Teardown retires the logical lifetime + synchronously and detaches kept views from the active registry. A later Close all cannot close + the old snapshot. Dashboard menu commands resolve their originating panel, not the newest one. + At this iteration failed Remove corrected the last retirement reason without reviving the tab; + [decision 0036](../decisions.md#0036-simplify-obsolete-actions-and-ended-bindings-without-cutting-useful-features) + later kept the disconnected state on the surviving connection but dropped per-tab reason history. +- **E — disconnected edits (`1d971f4c1`).** Both editors use ordinary Disconnect. Check eligibility + again before saving; the wizard can outlive a reconnect. A partial storage failure remains visible. + The later [#1149 review](./03-pr1149-copilot-review.md) records the concurrent-edit edge the + operator accepted rather than adding teardown-completion tracking. +- **H — delayed work ([review findings C01–C03](./02-pr1136-copilot-review.md)).** Check after + resolving the client and before issuing the write (`95cd11d0a`); carry cancellation through schema + sampling and model selection to the send boundary (`54e890813`); preserve the originating binding + when opening a Playground asynchronously (`c640d447d`). On rejection keep the text, not the binding. +- **U — recoverable vs. terminal (`674ab9c41`, `6bcf634e7`).** Removed the Retry/unlock action + and its RPC protocol. A live tab reports a failed operation without replaying it. On a retained + tab X only dismisses the notice; host checks still prevent database access. +- **P — integration and delivery.** `1a1c6ceff` aligned the manual, draft notes and feature intent. + [#1149](https://github.com/microsoft/vscode-documentdb/pull/1149) records candidate-specific + Case 2 and VSIX receipts. The [initial full CI run](https://github.com/microsoft/vscode-documentdb/actions/runs/46452303937) + applies only to `c4cc00e56`. Its first local Case 2 attempt had lint failures and one suite that + could not load an incomplete azext mock; the passing test count was not a full-suite pass. + +**Limits of the rendered attempt:** 27 routes were attempted across three themes on `c4cc00e56`. +Only the three default Document View layouts passed. Collection readiness, Monaco editing and +Dashboard readiness/held replies prevented the lifecycle assertions from completing. This was +neither proof of a product defect nor a pass for copy, no-save, or same-tab recovery. Local packaged +activation was blocked by a missing `libatk` dependency; use a receipt for the exact candidate. + +#### Manual-test follow-up (2026-11-30, 20:25 UTC) + +The operator added three requests after the original seven checkpoints: + +- **Edit prompt (`e1757115d`):** explain why updating credentials or the connection string + requires Disconnect; leave the existing heading, button and cancellation behavior alone. +- **Close view (`dcbf37fd8`):** close clean Dashboard, Collection and Document views directly. + Only dirty Document views need confirmation; cancelling must preserve the draft. +- **Playground status (`39be627c4`):** CodeLens, status bar and the information action must show + Disconnect immediately, without a failed Run first. Update the display when the latch changes; + do not start a worker, change the selection, or execute the script. + +The combined build and 587 focused tests passed. Post-push Case 2 exposed a test fixture +missing the latch-change subscription, then a getter-spy type error. The operator approved +a **mock-only** repair, keeping every `TDD:` assertion; [#1149](https://github.com/microsoft/vscode-documentdb/pull/1149) +holds the final receipt. **Manual retest outstanding:** try both edit prompts, close a clean view, +cancel closing a dirty one, and watch Playground's status across Disconnect/Reconnect without Run. +These checks do not replace the candidate-specific A–H runbook below. + +#### Evidence the agent collects directly + +- **Host/race evidence:** run the affected suites with `npx vitest run `. Use deferred + promises at real production boundaries, fake timers only for timers, and spies at the _effect_ + (driver write, prompt, worker reply, model send). Don't infer “nothing happened” from an empty + screen or a cancelled return value. Never try to undo an operation already sent. +- **Rendered UI evidence:** adapt the checked-in [`disconnected-dirty`, `stale-save-after-reconnect` + and Dashboard `disconnected` scenarios](../../../../../build/verification/browser/scenarios.ts); + some fixtures currently expect Retry. Test both X/copy on a frozen tab and same-tab recovery + on a still-live one. Run `npm run watch:views` on port 18080 and drive the affected routes with + the [L2-dev Playwright runner](../../../../../build/verification/README.md#l2-dev-source-scenarios). + Retain the route, readiness, assertions, errors and relevant RPC call counts; stop the server + afterwards. The manifest test below validates fixtures, **not** rendered behavior. Browser RPCs + are fixtures: pair U with F's real host code tests rather than claiming end-to-end coverage. + + ```sh + npx vitest run --config build/verification/browser/vitest.config.ts build/verification/browser/scenarios.test.ts + ``` + +- **Packaged/live evidence ([OP-6 and CP-5](./01-dev-plan.md#pr-f-featureconnection-lifecycle--main)):** + use an authorized test cluster, disposable data and an isolated VS Code profile. Use an existing + matching VSIX for baselining when available; identify the final artifact by SHA/version and hash. + At handoff run the Case 2 list; use the [packaged checks](../../../../../build/verification/README.md) + or matching CI results for VSIX contents and activation. Activation alone does not test renewal. + Drive the actual workbench when available, including both worker paths and a blocked transfer. + For OP-6 record separately: continuous queries for ~90 min across expiry without a prompt; + a dirty document idle ≥2 h with `retrywrites=false` and **Save as the first DB operation**, no + warm-up read; genuine sleep/wake across expiry; Shell and Playground use after expiry. Use + separate sessions for continuous traffic and first-write idle; pause incidental Dashboard + traffic on the idle target. Capture elapsed time, sanitized callback evidence, prompt count, + operation count and observed outcome per surface. Follow the existing telemetry gate for + ingestion; local emission is not proof of ingestion. + + ##### Manual OP-6 / CP-5 execution runbook — NOT RUN for the candidate + + **Gate status and scope:** every group below is **NOT RUN** until a tester returns the evidence + requested in that group for the candidate identified in A. Pending manual evidence blocks + readiness only; it does not block publication of the authorized draft PR or the Case 2 checks. + Never copy a pass from another revision, package, profile, machine or account. Fake clocks, + mocked tokens, socket interruption or screenshots of a completed UI do not satisfy an expiry + gate; VM/simulated suspend does not satisfy the physical sleep/wake gate; local telemetry + emission does not satisfy ingestion. + + **Common safety boundary:** use only an authorized, disposable, non-production Entra-backed + DocumentDB test database and collection. The authorized administrator supplies two harmless + test documents and the normal test connection; do not request or record passwords, tokens, + access-token contents, tenant secrets or a complete connection string. Keep screenshots, + notes and logs free of account details, host names, resource IDs and database contents beyond + synthetic manual-test markers. Use the test ID instead of a person's name or email address. + Stop on a wrong target before saving, creating or deleting anything. + + Run A–H in the order below, but use a fresh session for each runtime group as stated. A is + common candidate preflight, B is continuous use, C is an independent first-write-after-idle + run, D is an independent physical sleep/wake run, E is an independent forced-repair run, F is + an independent teardown matrix, G is independent worker/workbench verification and H is + receipt/ingestion verification. A candidate may have mixed results; each group has its own + `pass`, `fail` or `blocked` result. + + ###### A. Isolated candidate and safe baseline (NOT RUN) + + **Prerequisites** + - The leader has supplied, for the candidate only: the candidate ID, exact commit SHA, VSIX + file name/version and expected SHA-256. Blank fields remain blocked; do not invent them. + - The operator is authorized to use a disposable Entra test database and collection containing + two synthetic documents. The account used to establish the connection is recorded under a + neutral alias such as `account-A`; use the same underlying account throughout A–G. + - A separate VS Code user-data directory or isolated VS Code Profile is available. It must not + inherit credentials, extensions, settings or synced state from the tester's normal profile. + + **Ordered steps** + 1. Assign `A---01` as the run's test ID. Record UTC start time, OS and + OS build, VS Code version, hardware class, and authentication path (`interactive Entra`, + `silent cached Entra`, or another candidate-supported path). Record `Entra account alias A` + only; do not record the sign-in address. + 2. Calculate the VSIX SHA-256 with the operator's local hashing tool. Record the result, VSIX + file name/version, candidate ID and commit SHA. Mismatch against the supplied tuple means + `fail`; a missing expected value means `blocked`. + 3. Install that VSIX into the isolated profile and enable only the extensions needed for the + test. Reload once and record the installed extension version. Do not continue if it differs + from the candidate tuple. + 4. Establish the named, disposable connection with the approved account. In the collection, + verify that the two expected synthetic documents are present, then record their count + without copying document IDs or real field values. + 5. Open a Collection View. Enter the synthetic filter for the two documents and select + **Find Query**. Open a Cluster Dashboard. Open one document, make a synthetic local-only + marker change and keep it dirty; capture the text without saving. Open an Interactive + Shell and run one read-only command, for example + `db..findOne({ manualRun: "" })`. Open a Query Playground, use the + same read-only shape in one block and select **Run** or press `Ctrl+Enter`. + 6. Before saving anything, confirm that the Collection query, Dashboard, dirty Document draft, + Shell result and Playground result retain the expected state. Record one prompt counter + (zero is expected) and one database-operation counter for the baseline. Count only explicit + user operations plus any clearly attributable database callback observed in sanitized logs; + do not count UI redraws or keystrokes as database operations. + + **Pass / fail / uncertain** + - **Pass:** one matching candidate is installed in an isolated profile; all five surfaces are + usable; the draft is still dirty and unchanged; the baseline has no background sign-in prompt; + records contain no secret or personal data. + - **Fail:** candidate mismatch, wrong target, unexpected prompt, lost dirty text, an operation + unexpectedly writes, or a surface cannot use the same account alias and target. + - **Uncertain:** any result depends on a blank profile check, unidentified server, missing + operation counter or sensitive value removal. Mark `blocked` and preserve only the safe + observation; do not turn uncertainty into `pass`. + + **Evidence and independence:** return the candidate tuple; sanitized environment/profile record; + baseline prompt and operation counts; and one observation line per surface. Baseline A is not + evidence for B–E elapsed or environmental prerequisites. + + ###### B. Continuous real-token-expiry use for about 90 minutes (NOT RUN) + + **Prerequisites** + - Use a fresh isolated run after A. The authorized tenant/test administrator confirms that the + normal issued Entra token has a real expiry inside the roughly 90-minute window and supplies + a safe way to record the expiry and renewal callback timestamps. The confirmation must not + contain the token or reveal its claims. If expiry cannot be demonstrated, the result is + `blocked: real expiry timestamp unavailable`. + - Prepare one read-only Collection query, a dirty Document draft, one Interactive Shell and one + Playground block as in A. Keep all four open. This is active use, not the idle-first-write + session in C. + + **Ordered steps** + 1. At `T0`, record UTC time, expected real-token expiry time, account alias, extension candidate + and the marker count. Establish the periodic query cadence: at `T0` and every 10 minutes + thereafter, select **Find Query** for the same filter or **Refresh** to rerun the last query. + Do not use an invented command palette action, script or other client. + 2. After each query, record the time, success/failure, result count, interactive prompt count and + explicit database-operation count. Keep the dirty Document draft open and do not save it; + record that its text remains unchanged. + 3. Continue this cadence through the observed real expiry and for at least one full post-expiry + interval. Capture only a sanitized callback outcome and timestamp proving that expiry/renewal + handling was crossed; never capture the callback payload or token. + 4. After confirmed expiry, issue a separate explicit read-only Interactive Shell command and + select **Run** once for the prepared Playground block. Record each command's visible result, + timestamp and prompt count. Do not type **Run All** or use more than the single prepared block. + 5. End only after at least about 90 real minutes have elapsed and after all Collection, + Shell and Playground post-expiry operations have completed. Record UTC end time and exact + elapsed duration; then compare the collection count/markers with the initial server-side + baseline. + + **Pass / fail / uncertain** + - **Pass:** elapsed time is about 90 minutes, real expiry is evidenced, post-expiry Collection, + Shell and Playground reads succeed, prompt count is zero, operation count equals the explicit + query/command attempts (no duplicate replay), server-side markers/counts did not change, and + the original query and dirty draft remain available. + - **Fail:** any interactive background prompt, wrong-account use, automatic command replay, + unexplained database write, lost query/draft, post-expiry operation failure, or duplicate + operation submission. + - **Uncertain:** no timestamped expiry proof, incomplete operation accounting or missing + server-side final count. Record `blocked`/`uncertain`, not a silent-renewal pass. + + **Evidence and independence:** return the cadence log, start/end/expiry times, sanitized callback + summary, per-surface prompt/operation counts and before/after marker counts. B must not be + reused as C: B intentionally creates database traffic and is not an idle-first-write test. + + ###### C. Independent idle first-write for at least two hours (NOT RUN) + + **Prerequisites** + - Start a new, non-sleeping session after A. The named disposable connection must be configured + with `retryWrites=false`. To configure the existing connection without exposing its value: + first end any live session through **Update Connection String…** → **Disconnect and update**, + edit the connection-string input locally, add `retryWrites=false` to the URI option portion + (after `?` when it has no options, or after `&` when it already has options), then save through + the existing flow. Do not paste, print, quote, screenshot or copy the full string into the + evidence. Reconnect and sanitize any log that contains it. If the operator cannot prove this + named connection uses `retryWrites=false`, the group is `blocked`. + - Close the Dashboard. Close Shell and Playground surfaces. Stop copy/export/import tasks and + all other database clients. Do not leave another VS Code window, polling tab or tree refresh + targeting the same collection. + - Create a unique, local-only marker in an existing test document and leave the Document View + dirty. The marker identifies this run and changes exactly one harmless field. + + **Ordered steps** + 1. Record `idle-start` immediately after the last connection operation. From this point, do not + expand/collapse the tree, open another surface, refresh, query, connect, diagnose or perform + a server-side check. Keep the machine awake; do not suspend it. + 2. Leave the one dirty Document View untouched for at least 7,200 real seconds. Record + `idle-end` and exact elapsed time. Keep the marker text visible; a screenshot is not required + and must exclude connection/account details. + 3. Select **Save** once. This Save must be the first database operation after the idle start; + there is no warm-up read, Find Query, tree expansion or Shell command. Start capturing the + sanitized host/driver observation before clicking, and stop when Save reaches a definite + acknowledged or failed result. Count matching submissions sent to the driver/server. + 4. Do not click Save again if the result is delayed, canceled or uncertain. Do not rely on a UI + spinner disappearing as an acknowledgement. Preserve the dirty draft text on an uncertain + result and record the visible outcome; never accept or initiate automatic replay. + 5. Only after the submission capture is complete, perform a separate explicit server-side check + through the authorized test method. Verify one target document has the exact marker and that + no second document or duplicate field update appeared. Record the check's time, marker + equality and resulting count. + + **Pass / fail / uncertain** + - **Pass:** real idle time is at least two hours; the first post-idle database operation is one + Save; exactly one driver/server submit is observed; the post-capture server result matches the + unique marker once; there was no automatic replay or warm-up; and the draft remained available + and its text was not replaced throughout any acknowledgement uncertainty. After a definite + acknowledgement the editor may show its normal saved state, but the exact draft text remains + captured until the post-ack server check; an uncertain result retains the dirty editor draft + and is not a zero-write pass. + - **Fail:** any pre-Save operation, more than one submit, duplicate write, wrong target, lost + draft, unexplained prompt, automatic retry, or a different server result. + - **Uncertain:** missing before-Save request capture, unavailable server-side result, inability + to distinguish acknowledgement from timeout, or inability to prove `retryWrites=false`. + Do not claim zero writes; retain the draft and report the exact unknown. + + **Evidence and independence:** return start/end/elapsed, configuration proof without the + connection string, the marker identifier, first-operation observation, submit count, final + dirty/saved state and post-capture server result. C must be separate from B and D. + + ###### D. Dedicated physical sleep/wake across real expiry (NOT RUN) + + **Prerequisites** + - Use a dedicated physical machine assigned to this test. A shared host, remote/shared VM, + container, VM save state, fake clock or simulated sleep is not an allowed substitute. Record + the machine assignment and confirm it has no unrelated users or workloads. + - A is complete on the machine and the approved test path can provide a real token expiry + timestamp without exposing a token. Prepare Collection, dirty Document, Shell and Playground + surfaces while still connected. + + **Ordered steps** + 1. Record `suspend-start` UTC, token expiry UTC, system uptime/power state and account alias. + Put the physical machine into its actual suspend/sleep mode. Do not perform network or + database traffic after that point. + 2. Leave it suspended until after the real token expiry. Record the physical `resume` UTC, power + event and elapsed suspended time. Do not inspect the token. + 3. Do not refresh the tree or open a new client. Explicitly, in this order, record the first + post-resume action and outcome on each existing surface: + 1. Collection View: select **Find Query** for the same read-only query. + 2. Document View: select **Save** once for its one unique dirty marker. + 3. Interactive Shell: press Enter for one prepared read-only command. + 4. Query Playground: select **Run** once for the one prepared read-only block. + 4. After each action, record prompts, operation count and visible result. A failed action must + remain failed unless the tester explicitly reruns it once for the tested account; no worker, + view or timer may replay it. + 5. Verify the Document draft/text state and perform the server marker/count check only after all + four submissions have been captured. Record account alias again to prove it was unchanged. + + **Pass / fail / uncertain** + - **Pass:** actual physical suspend/resume is evidenced, the resume follows real token expiry, + each first explicit action either succeeds silently or gives the documented explicit-repair + path, prompt count is zero for the silent path, no action is replayed, the Document text is + preserved, no duplicate write occurs and the account alias is unchanged. + - **Fail:** a shared/virtual/fake sleep substitute; unexplained interactive sign-in during + otherwise-silent renewal; lost text/query; automatic command replay; duplicate write; or + post-resume action binding to another account. + - **Uncertain:** missing physical power/resume evidence or proof that expiry occurred while + suspended. Record `blocked`; a resume before expiry is not the sleep gate. + + **Evidence and independence:** return machine description, suspend/expiry/resume timestamps, + elapsed duration, first-action log per surface, prompt/replay counts, account alias check and + final server result. D is one physical run separate from B and C. + + If manual sign-in is actually required on any D step, record `manual sign-in required` with the + timestamp and affected surface; do not label D a silent-recovery pass even if the operation + succeeds after signing in. Continue only as directed for E's explicit-repair gate. + + ###### E. Approved real renewal failure and same-tab sign-in repair (NOT RUN) + + **Prerequisites** + - An authorized tenant administrator has intentionally established a real test condition in + which silent renewal cannot complete and interactive sign-in is required. Obtain the + administrator's safe confirmation and test window, not instructions to revoke an arbitrary + account or token. If that condition is unavailable or not authorized, the result is + `blocked: real Sign-in condition unavailable`; do not fabricate it with mocks, a deleted + profile, a network break or token revocation instructions. + - Start with one live Collection View under account alias A and a prepared read-only query. + A Shell/Playground may be opened separately for their own explicit-repair observations. + + **Ordered steps** + 1. At the approved condition, run the read-only Collection query once. Capture its failure and + the Document/Collection state. Confirm no failed write or query result is replayed. + 2. In the tree, select **Retry sign-in**. First have the operator choose a different, authorized + test account alias B. Expected result: the repair is rejected; alias A remains pinned; + the view stays on the same tab and no database write occurs. + 3. Select **Retry sign-in** again and choose alias A, the account that established the + connection. Capture only the outcome, not the account address. Keep the same tab open; do + not use a separate unlock or reopen flow. + 4. Return to the same Collection tab and rerun the failed query exactly once through **Find + Query**. Repeat the same one-explicit-rerun rule for a Shell **Sign in again** and a + Playground **Sign in again** in their separate surfaces; never let a held command or code + block replay by itself. + 5. Verify server counts and markers did not change. Record prompt count and the number of + explicit repair/rerun operations. Close the approved condition only through the tenant + administrator's normal cleanup process. + + **Pass / fail / uncertain** + - **Pass:** the real Sign-in condition is observed; alias B is rejected without changing the + pin; alias A repairs the same tab; the tester explicitly reruns once; failed operations are + not replayed; no duplicate/automatic write occurs; and Shell/Playground retain their local text. + - **Fail:** alias B repairs or rebinds the old tab, a failed write/command automatically runs, + the same tab is permanently disabled despite an unchanged-account repair, or a connection + operation changes server data. + - **Uncertain:** setup is synthetic, callback/failure reason is unavailable, the same account + cannot be demonstrated under the alias record, or outcome cannot be separated from a manual + reopen. Mark `blocked` or `fail` according to the missing evidence; never infer repair. + + **Evidence and independence:** return the approved condition window/confirmation reference, + account-alias rejection and acceptance results, same-tab rerun counts, per-surface prompt counts + and unchanged marker/count check. E is separate from the silent paths in B and D. + + ###### F. Explicit end, edit, retained-view and fresh-view matrix (NOT RUN) + + **Prerequisites** + - The target is a disposable named connection. Prepare unique markers for: one dirty document, + one harmless document to create, one harmless document to delete, and one small copy/export or + import task. Keep all within the authorized collection and record baseline counts. + - Open Collection View, Document View and Cluster Dashboard. Set + `documentDB.connections.openTabsOnDisconnect` to `ask` for the choice matrix so the dialog + labels from the user manual are visible. + - Use distinct runs for **Disconnect**, **Remove**, and **Disconnect and update** so deletion + of the saved connection and edits do not contaminate later observations. + + **Ordered steps** + 1. For **Disconnect**, exercise: + 1. **Cancel** by closing the **Disconnect?** modal: connection and all views remain live, + and no database write or removal occurs. + 2. **Close all** with a dirty Document: at the unsaved confirmation choose the refusal/cancel + path, proving teardown does not continue. Repeat, choose **Discard changes**, and prove + the old views close only after teardown. + 3. **Keep open** with a fresh dirty local marker: old Collection/Document/Dashboard contents + remain copyable snapshots; dismiss the notice with **X**, copy loaded text and continue + with the negative/positive test below. + 2. Repeat the three choice paths for **Remove** in a disposable saved-connection run. A refused + dirty close or Cancel must leave the saved connection and cached account path intact; Close + all or Keep open removes only after ordinary teardown succeeds. + 3. Repeat the choice/cancel paths for **Disconnect and update**: + Cancel, a dirty-close refusal or teardown failure writes no connection-string/credential + change. A successful teardown alone opens the edit wizard. Cancel that wizard after teardown + and verify the connection remains disconnected and no partial setting was saved. + 4. Hold a small, safe copy/export/import long enough to invoke Disconnect. The extension must + report the active-transfer conflict and leave both task and live connection running. + Never kill the extension/host to create a race. After the task ends normally, perform a + new explicit Disconnect to complete the test. + 5. For a retained old session, complete this precise negative/positive sequence: + 1. Choose **Keep open**, reconnect the named connection and open fresh Collection, + Document and Dashboard views. Record the server baseline and the unique markers. + 2. In the old snapshot after X, attempt the enabled old Document **Save**, Collection create, + Collection delete and the Dashboard's existing native safe delete action. Use only + visible product controls. If a control is unavailable/disabled, record that the manual + run did not reach the host boundary; do not use DevTools, crafted requests or a claimed + manual RPC pass. + 3. Check actual database state: the old marker must not be saved, old create marker must + not appear, delete target must still exist, and Dashboard target/count must be unchanged. + A disabled appearance by itself is not evidence of zero database writes. + 4. In the newly opened fresh views, perform equivalent disposable Save/create/delete actions + with fresh unique markers and verify positive server-side changes. This positive control + proves the server and test permissions can observe writes. + 6. Start another old-session/fresh-session sequence, retain the old snapshot, then Disconnect + the replacement connection and choose **Close all**. The replacement session's views close; + the older retained snapshot and its dirty/copyable contents must remain open and read-only. + + **Pass / fail / uncertain** + - **Pass:** every selected choice follows the user-manual labels; Cancel/dirty refusal makes no + change; active transfer blocks teardown safely; edits start only after successful teardown; + kept tabs cannot change the database after replacement; fresh views prove positive writes; + old snapshots survive the second Close all; and no old view adopts the new settings. + - **Fail:** any zero-write claim lacks a server check; an old action changes data or binds to + the replacement client; a fresh action cannot make its positive control; Cancel/refusal + partially edits/removes; or the second Close all closes an older snapshot. + - **Uncertain:** manual controls cannot exercise an old host boundary. Record the UI limitation + and pair it with the deterministic host-race evidence; manual workbench evidence alone must + not be described as old-RPC coverage. + + **Evidence and independence:** return one matrix row per entry action/choice, transfer outcome, + the four-step old/fresh server checks, prompt/operation counts, and a second-Disconnect tab + inventory. Each entry action is a new connection/session; do not combine F with B/C/D timing. + + ###### G. Shell, Playground and retained-link workbench (NOT RUN) + + **Prerequisites** + - Start a fresh, independent real-expiry session after A; do not reuse B or D's operation counts + as G evidence. Keep terminal scrollback and the Playground file text. The deterministic host + race gate (holding a token reply or evaluation across Disconnect and releasing it after + reconnect) belongs to automated tests; the manual operator must not kill, pause or inject it + and must not rerun that suite. + + **Ordered steps** + 1. After real expiry, run one visible, read-only Shell command and one Playground **Run** in a + normal, non-held flow. Record result, prompt count, explicit operation count and retained + terminal/file text. Do not claim coverage from the command merely appearing in the editor. + 2. Explicitly Disconnect the connection. The Shell worker and Playground worker must stop; the + terminal scrollback and file text remain. Record that the interrupted command/evaluation is + not replayed after Disconnect or a later Reconnect. + 3. From a retained Shell result produced **before** the explicit end, click its Shell result/link + while the same-account recoverable connection is still live: it may recover/use that same + pinned account. After explicit end and reconnect, repeat with a retained old link: it opens + an unbound Shell, does not silently adopt the replacement worker, and requests an explicit + selection when a database operation is attempted. + 4. Use a retained Playground file after explicit end. Choosing a database/connection again must + be explicit; an allowed repick may open a fresh worker, but no old evaluation automatically + runs and no new account is adopted. + + **Pass / fail / uncertain** + - **Pass:** both normal post-expiry paths work once; text survives teardown; no command/evaluation + replays; pre-end same-account recovery remains usable; post-end links/files remain unbound + until explicit repick. + - **Fail:** a worker rebinds silently, a stopped command/evaluation replays, text disappears, a + post-end link uses the new connection without a user choice, or a different account is used. + - **Uncertain:** a held token/evaluation race was attempted manually or no worker identity/state + can be observed. Report automated host-race coverage separately and do not call the manual + run a race pass. + + **Evidence and independence:** return per-surface explicit operation/replay counts, preserved + text observations, pre-end versus post-end link behavior and repick choice. G is a workbench + complement to, not a replacement for, the automated worker-race tests. + + ###### H. Packaged candidate receipt and telemetry ingestion (NOT RUN) + + **Prerequisites** + - The leader supplies a candidate-matched package/activation receipt tying the candidate ID, + commit, VSIX version and SHA-256 to packaged contents and successful activation. A generic + fast-CI receipt or baseline VSIX is insufficient. The operator does not rerun automated checks + already performed by the implementation/handoff process. + - An authorized workspace viewer can query the extension's Application Insights workspace for + the exact UTC windows from A–G. If workspace/ingestion access is absent, record + `blocked: telemetry workspace access unavailable`. + + **Ordered steps** + 1. Verify and transcribe the supplied receipt fields into the H result; do not rebuild, + repackage or claim a successful Case 2 from local activation. A missing or mismatched receipt + is `blocked` until the leader supplies the matching one. + 2. Ask the authorized viewer for aggregate counts only, using the candidate version (including + prerelease suffix), each test's start/end UTC window and the existing queries in + [`telemetry.md`](../telemetry.md). Request `connection.tokenRenewal` by surface/outcome, + operations by family/result/failure class, and the other candidate-relevant lifecycle event + classes represented in that document. Do not request user IDs, event rows, raw properties, + host names, tenant/account IDs, tokens or connection values. + 3. Return one count table per run window showing event class, surface, outcome/result and count, + plus explicit `0`, `missing` or `not queryable` where applicable. Compare B–G observed + operations with the ingested aggregates. Local log emission alone is not ingestion proof. + 4. Reconcile any expected event count mismatch with the receipt/candidate version/time window. + If the candidate, window or identity of the event class cannot be established, mark the + telemetry gate `uncertain`/`blocked` rather than passing on a nonzero total. + + **Pass / fail / uncertain** + - **Pass:** the packaged receipt matches the candidate tuple and aggregate ingestion covers the + relevant test windows/classes for the matching extension version. + - **Fail:** package/hash/commit/version mismatch, activation receipt failure or an ingested + count/class proving a prohibited failure path that the manual report did not explain. + - **Uncertain:** no authorized ingestion query, wrong/missing candidate version/window, local + emission only, or counts that cannot be tied safely to this test. + + **Evidence and independence:** return the matched receipt reference, candidate tuple, UTC query + windows and aggregate-only class counts. H is not a substitute for B–G observations. + + ###### Copyable manual result template + + Return one block per group/run; never combine unrelated runs to hide a failure or missing + prerequisite. + + ```text + Candidate ID: + Commit SHA: + VSIX version/file: + SHA-256: + Group (A-H): + Test ID / independent run ID: + Start UTC: + End UTC: + Elapsed: + Environment (OS/build, VS Code, profile, physical/shared): + Auth path / account alias: + Token expiry, suspend/resume or idle timestamps (if applicable): + Preconditions completed (including target and retryWrites=false where applicable): + Ordered observations (timestamp | surface | explicit action | outcome | prompt count): + Operation counts (expected / submitted / replayed / writes / duplicates): + Database marker/count check and when it was performed: + Draft/query/terminal/file retention: + Sanitized evidence references (no tokens, secrets, personal IDs or connection strings): + Result: PASS | FAIL | BLOCKED | UNCERTAIN + Failure/uncertainty and exact remaining prerequisite: + ``` + +- **Operator exception, not the default:** the agent sets up, drives and records everything its + authorized environment permits. Request only the missing input/action (e.g. MFA, a disposable + live target, genuine suspend/resume on a dedicated machine, or access to ingested telemetry). + Never suspend a shared host, use personal/production data, or request tokens, passwords or + connection strings. Give the candidate ID, exact remaining steps, expected result and safe + evidence needed. A mocked token, fake clock, browser screenshot or socket interruption does + **not** pass a real Entra expiry or physical sleep gate. Leave it explicitly blocked rather + than waiving it or making the operator repeat local tests. + +**Completion:** hand back the per-row evidence, outstanding live/CI gates and a clear verdict: +implemented, verified at each named layer, or still blocked. Do not declare release readiness +while a required gate is failing, unrun or tied to a superseded candidate. + +## 7. What is not reduced + +- **Reliability work in `ClustersClient`:** the F1 fix (a failed callback must not leave a dead + client cached) and F2 (the unverified first write after expiry) are not about identity. +- **Shell and Playground token renewal:** `WorkerTokenRelay` still pins the account so a worker + never refreshes as a different VS Code account. +- **Telemetry:** most events survive. The reason-based ones need a pass in `telemetry.md`. + +## 8. Trade-offs and risks, not blanket operator acceptance + +The previous version labeled risks "accepted" without a corresponding decision. That was too +strong. A2 approval and B2 acceptance do not authorize stale writes or unintended data disclosure. + +- **Accepted direction:** A2 adds a Disconnect flow before editing. Under B2, old tabs remain + useful for copying but never resume. Reopening views costs user effort, and old snapshots retain + memory until closed. +- **Chosen D2:** recoverable failures use ordinary actionable errors; repeating an operation + before repair may produce another error. Preserve background restraint. +- **Not accepted:** an old wizard, AI request or Playground handoff silently adopting a replacement + connection. Server authorization is not enough: an authorized operation on the wrong target, + or sending the wrong schema to a model, can still be harmful. +- **Not accepted:** interpreting absence of a cross-window watcher as absence of all protection. + Current equality checks may still reject an observed mismatch. +- **Not included:** making old Shell prompts freely adopt new settings, deleting worker Entra + pins, dropping removal/task rechecks, or suppressing partial-save errors. + +## 9. Decisions this would change + +| Decision | Revised effect | +| --------- | ------------------------------------------------------------------------------------------------------------------------------ | +| 0002 | C-balanced keeps internal generation; surface lifetime representation may change | +| 0003 | Keep no implicit identity switch; enforce through edit preconditions **and** lifetime cancellation | +| 0004/0007 | Keep Close/Keep and the existing setting under B2 | +| 0011 | Keep credentials/pin on Disconnect; avoid stale cached auth after an edit write | +| 0012/0013 | Simplify representations, but retain startup, save exclusion and handoff guards | +| 0016/0017 | B2 ends revival after explicit Disconnect; D2 removes recoverable-view Retry as well | +| 0018 | Live-edit policy superseded by disconnected editing; its risks still require coverage | +| 0019 | Keep no stale Dashboard delete; consolidate its guard if equivalent | +| 0021 | Remains relevant until fingerprint callers are actually removed | +| 0022 | Worker/anonymous Shell policy unchanged in this package | +| 0023 | D2 removes recoverable-view Retry episodes; B2 is Close-only after explicit Disconnect | +| 0024/0025 | Retain tree/worker stale-click and origin-specific feedback contracts | +| 0026 | A1 selection modified by 0030; pinned-account requirement retained | +| 0027 | B2 reaffirmed by 0031 | +| 0028 | Broad deletion rejected by 0031; section 5C's C-balanced replacement chosen | +| 0029 | Before 1.2.0, inside #1136, unchanged | +| 0030 | A2 approved on 2026-11-30 | +| 0031/0032 | Package P chosen; same-account repair keeps tabs live, explicit session end freezes kept tabs, and X only dismisses the notice | + +Decisions are immutable: record each reversal as a new entry plus a status change in the index. + +Documents that would need implementation-aligned updates if adopted: the feature README, +`telemetry.md`, the user manual's Disconnect/Reconnect section and the unpublished 1.2 release +notes. Keep `documentDB.connections.openTabsOnDisconnect`; change its text only if the semantics +require clarification. Update `.github/codeql-exceptions.md` only if the corresponding fingerprint +code actually disappears. Existing code, manual and release drafts still describe the older runtime; +this task updates analysis and approved intent, not shipped behavior. + +## 10. Open questions and verification limits + +Package P, pinned-only Sign in again and pre-1.2.0 timing are approved. Implementation is pending. + +Limits of this analysis: + +- No application code was changed or run for this follow-up. Measurements refer to head + `1e362403`; the original diff comparison used base `60e17e46`. +- The deeper read covered client acquisition/replacement/failure accounting, teardown, live edit, + all three webview controllers, representative router/React operations, RPC cancellation and + context cloning, Dashboard native routing, and Shell/Playground restart/binding paths. +- It is not an exhaustive audit of every worker, router or credential-cache mutation. This is why + package P does not claim a repository-wide fingerprint deletion or a verified net line saving. +- The installed driver's lock and relevant tests were read; the application tests were not rerun. + The original eleven Mermaid diagrams were parser-checked on 2026-11-29; diagrams revised in this + follow-up have not been rerun through that parser. +- On `main` an edit deleted the client, replaced the cached credentials, stopped the Playground + worker and showed an informational modal for open shells. Views obtained the client by + `clusterId` per operation (confirmed in `documentsViewRouter.ts`; the Collection View router + follows the same documented pattern but I did not re-check every call). + +## 11. Operator responses + +### 2026-11-29 (historical selection) + +The operator answered the questions of section 10 and asked to record the direction. Recorded in +[decisions.md](../decisions.md) as 0026 to 0029. + +| Question | Answer | Differs from the recommendation? | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------- | +| 1. A1 or A2 | **A1**: refuse and tell the user to Disconnect first (0026) | Yes (recommended A2) | +| 2. B1 or B2 | **B2**, "but still ask the user": the Close or Keep open modal stays; kept views are permanently disabled (0027) | Yes (recommended B1) | +| 3. Overlay (D) | Not answered. The in-view Retry overlay (0016, 0017, 0023, 0024) stays in force until decided | Open | +| 4. Sign in again, pinned only | **Yes** (0026) | No | +| 5. Before or after 1.2.0 | **Before 1.2.0, inside #1136** (0029) | No | + +The original package shorthand was "M with A1". It is historical; section 6 above is the revised +recommendation, and the earlier broad deletion estimate is withdrawn. + +### 2026-11-30 + +- **A2 approved instead of A1:** the user receives an option to disconnect and the extension + performs it. Recorded as decision 0030, modifying 0026 without rewriting its historical entry. +- **B:** the operator values keeping tabs and asked for a closer cost assessment of B2. Section + 5B now recommends B2 and identifies host enforcement, Dashboard reuse and worker boundaries. +- **C:** the operator asked whether a generation or caller-supplied client ID is sufficient. + Section 5C separates physical client identity, startup cancellation and logical lifetime. +- **D:** the operator requested explanation, not approval. Section 5D separates frozen tabs from + recoverable errors and recommends D2. +- **Subsequent choices:** 0031 accepted package P. In 0032 the operator confirmed same-account + recovery keeps the existing tab live, including tree sign-in. Only an explicit session end + freezes a kept tab; X exposes its contents for copying without reviving it. Section 6 puts + packaged verification of token renewal, recovery and workers first. Implementation is pending. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md new file mode 100644 index 000000000..448091ca9 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md @@ -0,0 +1,333 @@ +--- +feature: connection-lifecycle +kind: review +status: historical +prs: [1149, 1154] +created: 2026-12-01 +verified: 2026-12-01 +code: + - src/documentdb/connectionTeardown.ts + - src/commands/saveConnectionEdit.ts + - src/commands/playground/newPlayground.ts + - src/documentdb/shell/DocumentDBShellPty.ts + - src/commands/openCollectionView/openCollectionView.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/commands/llmEnhancedCommands/queryGenerationCommands.ts + - src/documentdb/playground/PlaygroundService.ts + - src/documentdb/connectionFailures.ts + - src/webviews/_integration/connectionUnavailable.ts + - src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx + - src/webviews/documentdb/useBoundViewRecovery.ts + - src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts + - src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx + - src/webviews/documentdb/documentView/documentView.tsx +--- + +# PR #1149: Copilot review evaluation + +## Approved dispositions and implementation ledger + +On 2026-12-01 the operator approved nine fixes and three no-code dispositions for +[draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Decision 0033](../decisions.md#0033-approve-the-pr1149-review-dispositions-with-explicit-complexity-tradeoffs) +accepted the recommendations **except C01, C06, C08 and C10**. Each finding below pairs the +evidence at the reviewed head with the choice actually made, the pushed commit and the reply. +The [unabridged ledger at `01590e0`](https://github.com/microsoft/vscode-documentdb/blob/01590e0617e3dcf70cb237acab3fd880ca908162/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md) +preserves the original alternatives, acceptance criteria, run instructions and per-item checks. +Neither the rejected proposals nor this historical ledger are a current product specification. + +## Scope and verdict + +Two reads confirmed [Copilot's review](https://github.com/microsoft/vscode-documentdb/pull/1149#pullrequestreview-6128681886) +of draft #1149 at `f8da433c084d298bdecfe09a8003408dd7dcd708`: local HEAD matched and all 12 +threads were current and unresolved. Following the [previous evaluation](./02-pr1136-copilot-review.md), +the lead assessed 11 confirmed findings and one optional refactor. Ratings below are **Copilot → +assessment**: four High, seven Medium and one Low became one High, six Medium, four Low and one +optional. Only C04 demonstrated a live surface bound to a different identity. + +[Decisions 0030–0032](../decisions.md#0030-offer-disconnect-and-update-performing-the-ordinary-disconnect-flow-before-editing) +were the baseline. Decision 0033 qualified teardown success for a concurrent edit (C01) and +copy-only retention for local Collection query text (C08); it did not approve a general lease +framework or relax database-operation guards. + +## C01. Editing can start before teardown finishes or after it fails + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752057973) · High → Medium. +[Teardown](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L173) +sets the latch and [deletes the cached client](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClustersClient.ts#L1274) +before close settles. A **second** edit passed [preflight](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L66) +and the [save guard](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/saveConnectionEdit.ts#L34) +against mocked storage while close was pending; another check still passed after rejection. +The [ordering test](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.test.ts#L619) +covered the initiating command, which still waits for its own teardown. No database write was shown. + +**Option 3, no fix:** keep the latch/idle check. The operator's reason: “this is an edge case, and +option 1 adds a lot of complexity.” The review recommended tracking actual teardown completion +through success **and** failure; tracking only pending close would miss the latter. Neither was +implemented or tested as a fix. [Decision checkpoint `1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae) +· [reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757117308). + +## C02. Idle edits do not retire pending Playground origins + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058063) · High → Medium. +The probe paused a [tree handoff](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L41), +evicted the last client on credential rejection, then used the [idle preflight](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L73) +and [save helper](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/saveConnectionEdit.ts#L34). +A password-only edit preserved the [fingerprint](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionFingerprint.ts#L18); +the [resumed handoff](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L169) +bound the document but did not run it. + +**Option 1:** retire the prior lifetime at the common edit boundary, after acquiring the update +latch and before storage changes, even when idle. No registry of pending handoffs or C01 +completion tracking. Earlier Disconnect keeps its reason; eviction alone does not retire. +[Fix `d0132088`](https://github.com/microsoft/vscode-documentdb/commit/d0132088cbcf21ee56333c9668197c8d1409a076): +two new cases pin retirement order without weakening Disconnect-before-prompt; 105 tests passed. +[Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757355849). + +## C03. Closing a Shell does not invalidate its captured handoff origin + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058111) · High → Medium. +After [PTY close](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/shell/DocumentDBShellPty.ts#L253) +unregistered the Shell, a probe could still obtain a [new origin and a current captured callback](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/shell/DocumentDBShellPty.ts#L329). +Later teardown could not reach that Shell. The [consumer](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L182) +still checked fingerprint; this was stale authority within a matching identity, not arbitrary substitution. + +**Option 1:** check closure at origin creation **and** in the captured callback, rather than +treating close as Disconnect. An interrupted handoff can keep its text without binding; normal +Disconnect/authentication behavior is unchanged. [Fix `2e01db69`](https://github.com/microsoft/vscode-documentdb/commit/2e01db6951268337eb3804424bf82b36f2d9f320): +one regression exercised both lookups and the callback; 208 tests passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757418958). + +## C04. Dashboard navigation can create a session for a replacement identity + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058182) · High → High. +Both [row actions](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L281) +and the [toolbar](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts#L505) +checked but did not pass the source binding to the [opener](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/openCollectionView/openCollectionView.ts#L40). +The probe held [client acquisition](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClustersClient.ts#L1000) +across teardown/reconnect: [session creation](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClusterSession.ts#L804) +opened a live view for a **different fingerprint** although the Dashboard was retired. Startup and +panel were mocked; no database read was needed to show the wrong binding. + +**Option 1:** carry the originating binding through bound-client resolution and check it immediately +before panel publication for Open Collection, Manage Indexes and toolbar navigation. Checking +after the opener returns is too late. Reject retirement/change/cancellation and close the unpublished +session; allow physical-client replacement within the same live identity. Ordinary tree/deep-link +opens remain separate. [Fix `5e39ca70`](https://github.com/microsoft/vscode-documentdb/commit/5e39ca709a59728ef89395bef9575ac9cfbc7f2b): +15 cases added, 319 tests passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757276509). + +## C05. Query generation cannot be the first operation to recover an evicted client + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058252) · Medium → Medium. +[Generate Query](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/llmEnhancedCommands/queryGenerationCommands.ts#L179) +called the [full guard](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/boundViewOperations.ts#L13) +too early. With an unretired binding and empty cache, the probe counted **zero** resolution +attempts; the [existing replacement test](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts#L120) +started with a cached replacement. + +**Option 1:** check cancellation first, resolve the bound client, then validate lifetime/identity +before sampling or sending. Do not weaken the shared guard or require a separate tree action. +An unavailable-Copilot notice can precede a stale-binding error; neither path sends a request. +[Fix `94d6287e`](https://github.com/microsoft/vscode-documentdb/commit/94d6287e93d193e40e8fae2419eb7baf26e4e8e0): +four regressions added, 18 tests passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757492585). + +## C06. Removed Playground connections are presented as connected + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058319) · Medium → Low. +The [predicate](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundService.ts#L320) +missed `connectionRemoved`; a probe saw a connected [status bar](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundService.ts#L423). +[CodeLens](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundCodeLensProvider.ts#L84) +and the [information action](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/connectDatabase.ts#L35) +used the same distinction. Misleading presentation did not authorize execution. + +**Option 2 direction, not recommended option 1:** the operator preferred clearing the selected +binding and reusing **Connect** because it was simpler than retaining the target and adding shared +reason-aware wording. Successful connection/folder removal clears matching selections and remembered +bindings **after** storage deletion, preserving file text. Ordinary Disconnect and cancelled or +failed removal keep the selection. [Fix `eb57981f`](https://github.com/microsoft/vscode-documentdb/commit/eb57981f01ea3d06d9dfc559cf298ecfaad68844): +two regressions plus negative assertions, 126 tests passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757815667). + +## C07. A rejected Entra account is mistaken for a permanently ended binding + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058391) · Medium → Medium. +The [token callback](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts#L244) +correctly rejected a different account. The [classifier](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionFailures.ts#L98) +mapped the mismatch to `identityChanged`; [runWithClient](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/runWithClient.ts#L19) +carried that [terminal reason](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/_integration/connectionUnavailable.ts#L20) +to the hook. Even a same-fingerprint replacement could not unblock the synthetic client's view. + +**Option 1:** classify the rejected account as `signInRequired`, keeping the original pin and +explicit same-account replacement path. Actual incompatible bindings remain terminal; the wrong +account is never used and no operation replays. No new protocol reason or blanket recovery for +`identityChanged`. [Fix `82723db3`](https://github.com/microsoft/vscode-documentdb/commit/82723db379c3bc89c5d499083b3623d57757593d): +mocked host recovery and updated classifier/telemetry expectations, 253 tests passed; not live Entra. +[Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757586804). + +## C08. Retained Collection queries remain editable after notice dismissal + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058453) · Medium → Low. +After dismissing the [Collection View notice](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/CollectionView.tsx#L818), +[Monaco](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L274), +[Clear Query](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L688) +and [Skip/Limit](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L817) +could change retained local values. Source trace only; no database submission or rendered Monaco test. + +**Won't fix:** the operator considered the overlay sufficient notice that the connection was +disabled; choosing to edit local query text after dismissal was the user's responsibility. +The proposed read-only/mutation gates were **not** required. The overlay, database/lifetime +guards and Document View's read-only/dirty protection were unchanged. No code or new tests. +[Decision checkpoint `1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae) +· [reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757120247). + +## C09. A recoverable failure can leave an independent Dashboard read loading forever + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058526) · Medium → Medium. +A recoverable [storage failure](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L218) +advanced the [view revision](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L75). +The [collections hook](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts#L81) +dropped its reply but did not settle the request. The React probe found [loading](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts#L131) +true with no interruption or submission block; [Refresh](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L831) +stayed disabled. + +**Option 1:** settle only the invalidated current read as interrupted; retain existing rows and +enable manual Refresh. Do not settle a newer key, redesign view-wide invalidation or retry in +the background. Review caught a same-key return-navigation defect; the first run also exposed +an unstable mock. [Fix `0b81b831`](https://github.com/microsoft/vscode-documentdb/commit/0b81b83199ef0f7f47ae49cdf3ebf9241b65960a): +five cases added, 14 tests passed. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757735541). +[Integration correction `269d371f`](https://github.com/microsoft/vscode-documentdb/commit/269d371f7bda21aa828ecd5bf3cee9938c02619b) +used stable ref objects in the test for React Compiler lint; no runtime or assertion change. + +## C10. Index build polling can repeat recoverable-error notifications + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058577) · Medium → Low. +The [poll](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx#L451) +re-armed while a row was building. Typed [index refresh failures](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx#L289) +always reached the [recoverable notification path](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L73). +Three hook callbacks gave three notifications. Source tracing established one per failed cycle +(five-second delay **plus request time**), not a rendered timer measurement. + +**Option 2, not recommended option 1:** stop polling on the first recoverable failure rather +than extending callbacks to distinguish foreground/background errors. Repair, sign-in or switching +tabs must not restart that table. Only a **successful explicit Refresh** may resume polling if a +row is still building. Failed Refresh leaves it paused; terminal teardown still blocks submission. +Review found the pause initially lost on remount. [Fix `700c6d1f`](https://github.com/microsoft/vscode-documentdb/commit/700c6d1f91960a4a4f17f3e19ad7d5c287192256): +five fake-timer regressions passed, including remount. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757984995). + +## C11. Recovery notifications display an internal reason and omit the title + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058652) · Medium → Low. +The [hook](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L87) +sent `failure.detail` and `failure.reason`; the [host](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/_integration/appRouter.ts#L249) +appended the raw category (e.g. `signInRequired`) in parentheses, omitting the localized title. +The prior exact-payload test asserted that behavior; the token was an enum, not a credential. + +**Option 1:** send the localized title as `message` and detail as `cause` through the existing +non-modal contract. No shared formatter or localization-source change; terminal/close behavior +stayed intact. [Fix `dc4a95b7`](https://github.com/microsoft/vscode-documentdb/commit/dc4a95b7d2b0c07521354dde51d6572a9f14bb61): +all five recoverable reasons covered, 35 focused and 47 static scenario tests passed. Neither a +rendered journey nor a workbench toast was tested. [Reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4758052211). + +## C12. Persistent retained state would clarify rendering, but no rendering defect was demonstrated + +[Discussion](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058722) · Low (optional) → optional. +[Document View](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/documentView/documentView.tsx#L448) +read a ref during render. The [terminal transition](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L75) +also set notice state; dismissal changed state again without clearing the ref. A React probe +observed editable → disabled/read-only → still disabled/read-only. It did not render production Monaco. + +**Option 1, no standalone refactor:** keep terminal/dismissal coverage and the implicit render +dependency. Separate persistent render state plus synchronous guard ref (option 2) might clarify +the code, but no failing behavior warranted the extra synchronization. No code or new tests. +[Decision checkpoint `1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae) +· [reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757120153). + +## Approved execution handoff + +### Branch and pull request + +The operator chose a **separate draft**, `dev/tnaum/connection-lifecycle-pr1149-review-fixes` → +`feature/connection-lifecycle`, starting at the reviewed #1149 head. Because #1149 was unmerged, +that base included the simplification in #1154. No merge, retarget or push onto either original +branch was authorized. + +### Authority and model routing + +`claude-opus-5.5` owned technical judgment and acceptance within scope; the lead reused it rather +than repeating reviews. New failures went back to the advisor; only the operator could change an +approved behavior. `gpt-6.1-sol` handled C04's cross-module publication race; `mai-code-2` handled +the other eight fixes (Terra-class and simpler Sol work); `mai-code-2-flash` ran commands and checks. + +### Items, commits and replies + +The decision checkpoint was pushed after a passing build. Each accepted fix had its own commit, +regression coverage, advisor acceptance, push and original-thread reply explaining the choice +with its commit URL. The three no-code replies cited the decision checkpoint instead. The Flash +runner counted one reply from this round in each of the 12 original threads; a reply is not a resolution. + +### Verification and final iteration + +Case 1 was `npm run build` plus focused Vitest for each fix (results above). Formatting, +localization checks, full tests and packaging were reserved for the integrated candidate. Its +build also counted for final Case 1. The separate advisor sweep, final checks and remaining live +gates follow; a passing package was not authorization to mark the PR ready. + +## Advisor-led integrated AI pre-review for draft #1154 + +`claude-opus-5.5` independently swept `f8da433c084d298bdecfe09a8003408dd7dcd708..e8479641793bbcc0c5d4910c75c0d335e17c86f0` +for runtime interactions. It checked retirement after bound startup and before publication, +Shell/Playground origins, query generation, Entra recovery, concurrent Dashboard reads and +per-view polling/notification state. Same-account sign-in neither re-armed polling nor replayed +work. **No Critical, High or Medium; one valid Low (N01)**, high confidence from source. The +advisor did not rerun checks or reopen C01/C08/C12. + +### N01. Creating an index while polling is paused + +A typed unavailable result, even on initial load, can pause polling in +[IndexesTab](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx); +[CollectionView](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx) retains +the pause. Create may succeed after repair while its row stays **Creating**. **Operator decision +(2026-12-01), option 1:** keep manual Refresh and document the workaround. Select **Refresh** for +current status; a successful refresh may resume polling if a build is active. The operator did +**not** select automatic resume after successful Create (the advisor's recommendation) or a localized +pause hint. [Decision 0034](../decisions.md#0034-keep-manual-refresh-as-the-only-way-to-resume-paused-index-polling-after-create) +made no runtime change or exception to C10. + +## Final integration evidence + +- **Formatting/localization:** `npm run prettier-fix` ran in a detached worktree; round-only + formatting landed in [`754098c83`](https://github.com/microsoft/vscode-documentdb/commit/754098c83ffdb0f6e2b33f10df5a4adb1554e1f4). + Targeted Prettier passed after the later edits. `npm run l10n:check` passed (3,732 keys); + unchanged source strings did not require generation. +- **Static/build:** initial lint failed on the Dashboard test harness (C09); full `npm run lint` + and `npm run typecheck:tests` passed on the corrected candidate. Focused ESLint: zero errors, + 20 existing warnings. `npm run build` passed; later test and documentation edits did not change + production build, package or localization inputs. +- **Runtime:** integrated focused run **939 passed / 26 suites**; after correction, **18 passed / + two affected suites**. Static browser scenarios: 47 passed, not rendered journeys. Full + `npx vitest run` on the corrected candidate: **10,541 passed, 1 skipped / 461 files**. +- **Package:** `npm run package` produced `vscode-documentdb-1.1.1-alpha.4.vsix` (9,270,193 bytes). + It was not installed or exercised in the workbench. + +## Approval-update outcome + +The earlier approval-only step verified branch/stash recovery against the saved blob, preserved +the staged README link and retained stash `ce93e767475777c94dd20c5d49c44cd9413a32c0` as backup. +The unrelated untracked relay/telemetry directories were excluded. That step prepared the branch; +it did not implement, publish, reply or resolve. Those implementation and reply results above +belong to the subsequent draft #1154 run. + +## Verification and limits + +**Initial #1149 triage, before fixes:** 382 existing tests passed in 12 files, zero failures. +Offline probes composed the real lifecycle helpers/hooks with synthetic storage, client/driver, +VS Code, panel and RPC boundaries. C01–C07 and C09 were corroborated at those boundaries; C10/C11 +combined hook behavior with polling/host source tracing. C08 was source-only; C12 did not reproduce +a missed render. Passing tests did not disprove the gaps. No actual disclosure or database write, +production/test contract change, build, Case 2, GitHub reply or PR-state change in triage. + +**Still manual/live at handoff:** Dashboard navigation and interruption timing; Shell closure during +a pending handoff; Playground removal and file preservation; Generate Query with a genuinely evicted +client and live Copilot; wrong-account Entra rejection and explicit original-account repair; index +poll pause/Refresh and Create while paused; localized notification in the workbench; production +Monaco, real authentication, token expiry and sleep/wake. Mocked, static and packaged checks did +not close those gates. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md new file mode 100644 index 000000000..2cedd567e --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md @@ -0,0 +1,167 @@ +--- +feature: connection-lifecycle +kind: analysis +status: historical +prs: [1136] +created: 2026-12-02 +--- + +# PR #1136: what to cut from connection recovery + +**After operator review: simplify what happens to obsolete work; keep the useful features.** Accepted: one explanation for a stale user action (#2), one terminal “session ended” outcome for an old binding (#3), and trimming duplicate tests. Keep Azure Discovery/ARM **in this PR**, Close/Keep/Cancel for webviews, and Show Connection Stats for debugging. Do not cut ordinary Shell or Playground recovery. [Decision 0036](../decisions.md#0036-simplify-obsolete-actions-and-ended-bindings-without-cutting-useful-features) records the disposition. The changes landed in #1169; see the [post-merge assessment](#post-merge-assessment). + +**One open question: the isolated Shell.** The operator sees value in launching it from Connection Diagnostics, but considers it substantial work for an edge case. Extraction and placement are under evaluation, **not approved for removal or implementation**. Keep the current action and its isolation tests pending that decision. [Options and recommendation below](#isolated-shell-extract-the-feature-or-move-the-button). + +This is a review of [#1136](https://github.com/microsoft/vscode-documentdb/pull/1136), `feature/connection-lifecycle` at `7a1a7f5d2`, against its `main` merge base `c6b06e8ca`. [#1149](https://github.com/microsoft/vscode-documentdb/pull/1149) is already in that head. “80%” is a design criterion, not a measured usage share. + +## What users need, and what depends on what + +```mermaid +flowchart TD + A[Use an open tab, Shell or Playground] --> B{Can the same account continue?} + B -->|Yes| C[Silent token lookup or healthy replacement client] + C --> D([Next operation works; existing work stays]) + B -->|No| E([Actionable error; failed command is not replayed]) + E --> F[Explicit same-account repair; user runs the operation again] + E --> G[Failed tree row: Diagnose connection] + E --> H[Failed tree row today: separate anonymous Shell] + I[Disconnect, Remove or disconnect to edit] --> J{Active transfer or user cancels?} + J -->|Yes| K([Stop; do not tear down or edit]) + J -->|No| L[End old lifetime; stop workers and fence pending host work] + L --> M([Close views or retain copyable disabled views; dirty close requires consent]) + L --> N([Reconnect opens a new session; old work cannot target it]) +``` + +| Cluster | Dependency and user promise | Disposition | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Database Entra renewal | The [OIDC callback](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts#L233) asks VS Code silently for the pinned account on each driver lookup; it doesn't keep handing out the original token. The [driver contract](../../../../../src/documentdb/auth/driverOidcContract.test.ts#L63) shows the same driver workflow can repeat a rejected callback without invoking it again. | **Keep.** Fixing only the callback leaves users stuck after one failed refresh. No background sign-in prompt or extension-level replay of a failed write. | +| Client replacement and explicit tree repair | [Failure classification](../../../../../src/documentdb/connectionFailures.ts#L45) distinguishes a transient network failure, a closed/poisoned client, and rejected credentials. [Failure reporting](../../../../../src/documentdb/ClustersClient.ts#L1196) checks which physical client actually failed. A [bound operation](../../../../../src/documentdb/runWithClient.ts#L34) can use its replacement without moving to a different identity. | **Keep.** Not every network error calls for a new client. Do not silently redial rejected credentials. A late error on yesterday's client must not evict today's. | +| Disconnect, Remove and credential edits | One [teardown](../../../../../src/documentdb/connectionTeardown.ts#L111) coordinates tasks, views and workers. A connected edit first disconnects; a [save](../../../../../src/commands/saveConnectionEdit.ts#L53) excludes new startup and checks what persisted. [Secret and metadata writes](../../../../../src/services/storageService.ts#L356) are not atomic. | **Keep the boundary, not every branch.** Cancelling a dirty close must leave the edit unstarted. A partial save/delete must report failure and leave the surviving connection recoverable. A toast alone cannot establish either fact. | +| Collection, Document and Dashboard views | Collection has query/results state, Document has editor text, Dashboard can launch commands on a namespace. A [Dashboard → Collection handoff](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L298) and a [session check after an await](../../../../../src/documentdb/ClusterSession.ts#L82) protect work already running in the host, not just buttons in the panel. | **Keep live views through ordinary failure.** Preserve drafts/results and let the user retry the operation. Don't rebuild panels on every dropped socket. Explicit Disconnect/Remove is different; see the close-only alternative below. | +| Playground and ordinary integrated Shell | Both use the [host token relay](../../../../../src/documentdb/auth/WorkerTokenRelay.ts#L53) and worker protocol, not the extension host's database client. [Playground](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L333) must not rerun a script after startup/repair; [Shell](../../../../../src/documentdb/shell/ShellSessionManager.ts#L223) has persistent session state. | **Keep both.** Removing renewal from one brings back the original defect on that surface without removing the relay for the other. On explicit Disconnect stop the worker; keep file text or scrollback, not a live session. | +| Azure Discovery / ARM | A separate token consumer: a subscription kept across expiry, the Azure SDK challenge path, listing/cache behavior and the host bundle. [The ARM regression](../../../../../src/utils/azureClients.test.ts#L66) uses one stored subscription for two operations; no Collection tab or worker is needed. | **Keep as-is in #1136.** The operator considers this a good solution already in place. Keep the SDK/lockfile, adapter/provider callers, ARM regression and [bundle verification](./01-pr2-azureauth-review.md#azure-esm-bundle-verification) together; no split. | + +### Expensive-looking features that are already gone + +There is **no** Retry-to-unlock step for a recoverable webview error; a retained view does **not** revive, even after reconnecting to the same account. Updating connection settings does **not** migrate live tabs to a new identity. A failed operation is not an invitation to replay it. These were consequential simplifications in [decisions 0031–0032](../decisions.md#0031-choose-package-p-a2-b2-c-balanced-d2-and-guarded-handoffs); don't count them again as future savings. A physical client replaced after expiry and a logical session ended by the user are still two different events. A single “connected” boolean cannot represent both safely. + +## Disposition of the five proposals + +1. **Open: evaluate extracting the isolated diagnostic Shell as future work.** On `main` the failed row offered ordinary **Open shell**. This branch [replaces that action](../../../../../src/tree/documentdb/ClusterItemBase.ts#L419) with an isolated mode. Neither moving it nor removing it has been approved. [Decision 0022](../decisions.md#0022-offer-a-separately-unauthenticated-shell-from-failure-rows-only) still applies. +2. **Collapse stale-action feedback; preserve actionable failures.** [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L90) repeats the refresh/removed-or-changed modal decision at entry, after a failed key read, after a successful key read, and after closing a client. [Disconnect/Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L41) and [sign-in](../../../../../src/commands/signInAgain/signInAgain.ts#L88) have variants. For an explicit action that can no longer run, refresh the supported tree and say once: **“This connection is no longer available for that action. Refresh the tree and try again.”** Genuine user cancellation and obsolete background work stay quiet. Genuine provider changes, missing credentials and a rejected sign-in still get their specific repair instructions. **Tradeoff:** less precise copy on a race, fewer branches and test matrices; no change to whether stale work can run. This narrows [decision 0024](../decisions.md#0024-classify-explicit-stale-recovery-clicks-and-explain-only-failed-actions). +3. **Accepted: use a generic reason for an old binding.** The [retirement registry](../../../../../src/documentdb/connectionBindingRetirement.ts#L10) appends a generation/reason range and searches that history after later sessions start. A failed storage removal can [correct the last range and re-notify retained panels](../../../../../src/documentdb/connectionTeardown.ts#L318). A retained panel can instead say **“Session ended. Copy what you need and open a new tab.”** A monotonic cutoff plus the existing abort signal is a candidate implementation, not a requirement. Keep the _current_ connection's accurate latch, failed-removal ownership checks and the disconnected recovery path. Audit consumers before changing the typed reason; don't replace this small registry with another lifetime framework. +4. **Rejected: forcing webviews closed is too aggressive.** Keep the [open-tabs setting and choice](../../../../../src/documentdb/connectionTeardown.ts#L126), copyable retained contents and dirty-document consent. Closing everything would sacrifice results/drafts without eliminating guards for pending host work. +5. **Rejected: deferring Show Connection Stats.** Keep the [command](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L28) and [host snapshot](../../../../../src/documentdb/ClustersClient.ts#L427). The operator uses it for debugging; deleting a small, isolated formatter is a poor trade for losing visibility into expiry, pending startup and held connections. + +### Isolated Shell: extract the feature or move the button? + +| Option | What the user gains or loses | What it actually saves | +| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Keep the existing tree entry; add nothing now | Direct access after a failed connection. No new UI to learn or maintain. | No reduction, but also no extraction or retesting cost. Lowest-risk default while demand is unknown. | +| Extract the **whole mode** to future work | For now the failed row offers Diagnose and repair, not an anonymous terminal. Ordinary Shell, normal NoAuth connections and Playground still work. | The only option that removes the anonymous worker/startup/isolation policy from this release. Move its specific tests with it; dropping only the tree row or hiding it behind a flag is not extraction. | +| Later, **panel only** | Users try the built-in checks first and explicitly launch a separate terminal if those checks cannot answer their question. One extra click from the failed row. | Better placement, **not** a cheaper Shell. One panel-to-host launch path replaces one tree entry; endpoint isolation and worker checks remain. | +| Later, **panel and tree** | Expert users retain the shortcut, and panel users can discover the tool. | No runtime simplification. Even with one shared launcher, there are two entry points to explain and test. | + +**Recommendation:** don't add a panel action in #1136. The [diagnostics panel already tests DNS, TCP, TLS and the unauthenticated server greeting](../../../../user-manual/diagnose-connection.md#what-the-checks-do). Revisit panel-only placement when support can name a task those checks cannot answer and an anonymous terminal can. Keep both entries only if the shortcut itself proves useful. If the goal is to take this edge case out of the release, extract only if its branches and tests can be removed cleanly without destabilizing the shared worker; otherwise keep the working tree entry rather than pay for a rewrite to make the diff smaller. + +**One design constraint if revisited:** launch a _separate terminal_ on an explicit click, never as a diagnostic step or embedded command runner. A [panel can be retargeted](../../../../../src/webviews/documentdb/connectionDiagnostics/connectionDiagnosticsController.ts#L29) while an old run keeps [its original subject](../../../../../src/webviews/documentdb/connectionDiagnostics/diagnosticsPanelSession.ts#L84). A report is not launch authority: the host must resolve the intended current target, reject a removed/changed/disconnected one and use the [isolated launch checks](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L106). Read-only diagnosis remains available from retained Dashboards under [0035](../decisions.md#0035-keep-dashboard-connection-diagnostics-available-in-disconnected-views); that exception must not authorize a Shell. Reuse the launcher, never saved credentials, authenticated completions or Playground state. + +## Test pruning: cut by contract, not by file size + +### Can consolidate now, without a product change + +| Group | Proposed reduction | What must still fail if the code regresses | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Update Credentials](../../../../../src/commands/updateCredentials/updateCredentials.test.ts#L518) and [Update Connection String](../../../../../src/commands/updateConnectionString/updateConnectionString.test.ts#L386) | Both run the **same five teardown outcomes and five initial states**: 20 expanded cases, 170 added lines in those four blocks. Exercise each matrix once at the shared boundary; keep one blocked/cancelled wiring test and the distinct successful persistence path for each command. | Neither wizard opens after a refused/failed disconnect. Keep secret-first partial-save coverage, the rejected-destination case, and the separate [work appears _during_ a wizard](../../../../../src/commands/saveConnectionEdit.test.ts#L489) check: that is not the initial-state matrix. | +| [Superseded sign-in dismissal](../../../../../src/commands/signInAgain/signInAgain.test.ts#L249) | Three stale reasons × two provider dismissal forms × tree/worker = **12 cases** for the same “no startup, no error UI” outcome. Cover both dismissal forms and both caller types across a small selection, not their product. Keep the distinct non-cancellation failure. | A real provider error is still surfaced; a dismissal never connects. A different account, tenant/provider drift and late publication after Disconnect are **not** dismissal variants. | +| [Collection controller](../../../../../src/webviews/documentdb/collectionView/collectionViewController.test.ts#L113) and [Document controller](../../../../../src/webviews/documentdb/documentView/documentsViewController.test.ts#L92) | Share the mock/setup for register → disable → dispose and avoid asserting the same notification plumbing in full everywhere. Keep a representative wiring check per view. This saves fixture maintenance, not a whole suite. | Document preserves its dirty draft; Collection removes the old session; Dashboard reuse can't route an old action to a new panel. Router authorization, controller disposal and rendered copy/dismiss behavior are different boundaries. | + +### Delete or rewrite **only with the corresponding feature cut** + +| Diagnostic Shell test group | Expanded cases | PR-added lines inside group | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------: | --------------------------: | +| [Command: unauthenticated failure-row entry](../../../../../src/commands/openInteractiveShell/openInteractiveShell.test.ts#L182) | 24 | 262 | +| [PTY: unauthenticated isolation](../../../../../src/documentdb/shell/DocumentDBShellPty.test.ts#L288) | 8 | 149 | +| [Shell session manager: unauthenticated sessions](../../../../../src/documentdb/shell/ShellSessionManager.test.ts#L172) | 27 | 236 | +| [Shared worker manager: diagnostic Shell startup](../../../../../src/documentdb/playground/WorkerSessionManager.test.ts#L759) | 21 | 164 | +| [Standalone endpoint sanitization suite](../../../../../src/documentdb/shell/unauthenticatedEndpoint.test.ts) | 6 | 65 | +| **Named scope, not projected net deletion** | **86** | **876** | + +These are actual Vitest cases, counting parameterized rows, not 86 hand-written tests. **None are approved deletions just because the entry point is under discussion.** If the whole mode is extracted, move its specific coverage with it. Retain one regression that the ordinary worker flow cannot bypass a hold, plus the shared destination, credential-isolation and no-replay contracts wherever still applicable. Do **not** delete the four mixed-purpose test files or their existing Shell/Playground behavior contracts. + +- **If stale feedback is unified:** remove the removed/changed/disconnected **wording** cross-product from [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.test.ts#L445) and [sign-in](../../../../../src/commands/signInAgain/signInAgain.test.ts#L312). Keep tests at the actual race boundaries: a key read completes after removal, the startup returns after Disconnect, or a stale error arrives after a replacement. They must prove no publication or side effect, not merely assert a modal. +- **When historical reasons go:** replace the first-reason-per-range and reason-rewriting cases in [binding retirement](../../../../../src/documentdb/connectionBindingRetirement.test.ts#L48) with old/new cutoff, abort-once and no-revival cases. Keep [late client resolution](../../../../../src/documentdb/connectionBindingRetirement.test.ts#L123), [failed Remove](../../../../../src/documentdb/connectionTeardown.test.ts#L141), retained-view copy/dismiss and dirty cancel. +- **Keep with their features:** the [Show Connection Stats tests](../../../../../src/commands/showConnectionStats/showConnectionStats.test.ts), especially non-disclosure, and the real ARM SDK/transport regression. + +**Do not prune these to hit a size target:** a second token lookup returns a fresh token with no prompt; a poisoned client is replaced and a late failure cannot evict its replacement; a failed write/script is not replayed; a worker cannot switch identity or destination; a pending destructive command cannot cross Disconnect; a dirty discard can be cancelled; a failed storage write does not masquerade as success. Prefer one test at the boundary that can actually break. A mocked router cannot verify the driver callback contract, and a disabled button cannot verify that a pending host write was stopped. + +## Size, evidence and decision order + +`git diff --numstat c6b06e8ca...7a1a7f5d2` gives **307 files, +42,097 / −4,019** before this report. Categories below are disjoint; this is diff size, not executable complexity. + +| Changed files | Files | Added | Removed | +| ---------------------------------------------------------- | ----: | -----: | ------: | +| `*.test.*` anywhere | 95 | 18,433 | 570 | +| `docs/` | 30 | 12,179 | 8 | +| Other `src/` and `packages/` files | 158 | 10,429 | 3,014 | +| Other `build/` files (includes browser fixtures/scenarios) | 12 | 633 | 102 | +| Everything else | 12 | 423 | 325 | + +**73% of additions are named tests or docs.** The 16 historical iteration files alone add **10,421 lines**. For a smaller _review_, route those files to a documentation pass while keeping decisions and the user manual discoverable. Don't confuse moving history or splitting ARM into an earlier PR with deleting runtime complexity. Likewise, 876 test lines are a measured footprint, not 876 guaranteed net deletions after replacement tests. + +**Stopping point:** start with the duplicate edit and dismissal tests and #2's repeated stale-click feedback. Tackle #3 separately, alongside tests showing that old work still cannot write and a failed Remove still leaves the surviving connection recoverable. Stop after those accepted simplifications; don't wait on the Shell placement decision. In particular, keep in-place Shell/Playground sign-in: removing its UI would make people reopen or reconnect their working surface but would not remove the shared token relay. Beyond this point a live expiry, idle-wake and dirty-disconnect check buys more confidence than deleting another useful feature. + +**Verification (Case 1, not a release handoff):** `npm run build` passed. Two local focused Vitest runs at the stated head passed: **107/107** driver-contract, edit-command and sign-in cases; **375/375** across the five Shell/worker-related files above (**482 cases total**, including the 86, not in addition to them). Group line counts intersect the named test blocks with added diff lines. No full-suite, packaged-workbench, live Entra or live database run was performed for this report; no frequency estimates or release-readiness claim follow from these tests. + +## Implementation ledger + +### WI-1. Consolidate duplicate tests + +**Done (2026-12-02), commit `c5ac0403d`:** moved the edit refusals and initial-state coverage to `ensureDisconnectedForEdit`; kept one blocked-path wiring check and each command's distinct save path. The superseded sign-in cases now cover both dismissal forms and both caller types in two rows, with a separate genuine provider error test. Retained the partial-save, rejected destination, and mid-wizard guards. No runtime changes. + +- Decisions: scope accepted by the operator in 0036. Advised (`claude-opus-5.5`): use the existing teardown boundary (90%); do not share controller mocks, which would add setup rather than remove it. Recommended and actual coding model: `gpt-6.1-terra` for the bounded test-only change. +- Verification: 143/143 tests passed across the two edit commands, teardown, save and sign-in (166 before consolidation). Five teardown-outcome rows added at the shared boundary; the existing survivor and safe-idle rows exercise the same entry point. `npx tsc --noEmit -p .` and `git diff --check` passed. + +### WI-2. Unify feedback for stale explicit recovery actions + +**Done (2026-12-02), commit `0159d11dc`:** Retry, Reconnect, Disconnect and tree sign-in share one translated modal for obsolete actions. Kept each caller's existing refresh eligibility, refresh-before-feedback order, cancellation and worker/background silence, and specific guidance for real failures. No credential, startup or command fence moved. + +- Decisions: scope and wording accepted by the operator in 0036 and proposal 2. Advised (`claude-opus-5.5`): preserve each caller's view predicate, and centralize the text and eligibility without moving refresh. Advisor approved guard and ordering equivalence (85%). Kept one scenario for each distinct race instead of testing every wording permutation. Recommended and actual coding model: `gpt-6.1-sol` for cross-command lifecycle logic. +- Verification: 76/76 tests passed across Retry, Disconnect/Reconnect and sign-in after the review trims. Coverage includes an obsolete key read (success or failure), client close, deferred sign-in and startup, genuine errors, and unsupported or cancelled work. `npx tsc --noEmit -p .` (before the test-only trims) and `git diff --check` passed. + +### WI-3. Use one terminal outcome for retired bindings + +The operator approved a bundled `sessionEnded` reason, including the bounded `unavailableReason` telemetry value, with title **Session ended** and detail **Copy what you need and open a new tab.** Current-connection reasons and guidance remain unchanged. + +**Done (2026-12-02), commit `c99753dd8`:** replaced historical reason ranges with one generation cutoff and the existing lifetime abort signal. A failed storage removal can restore its own current disconnected latch, without rewriting history or notifying retained tabs a second time. Old tabs cannot run database work even after the same account reconnects. + +- Decisions: terminal copy and bounded telemetry value approved by the operator. Advised (`claude-opus-5.5`): cutoff equivalent to the ranges (95% in planning; 90% confidence in the reviewed implementation). Kept abort ordering and the epoch, latch and latest-retirement ownership checks. Recommended and actual coding model: `gpt-6.1-sol` for lifetime and cross-module behavior. Expanded test ownership only for the two edit-command interface pins; their exact call counts, ordering and cluster IDs are unchanged. +- Verification: targeted coverage distinguishes same-account physical replacement from explicit retirement and reconnect, fences a pending write and a late reply, and verifies that a failed Remove can recover the surviving connection without reviving old work. The generic reason is terminal in the webview and bounded in telemetry. Retained tabs can still be dismissed for copying or closed with dirty-draft protection. The worker's final focused run passed 435 tests, 80 browser scenario-definition tests and `npx tsc --noEmit -p .`. + +### Combined verification and delivery + +The operator chose local-only Case 1 delivery on a branch based on `feature/connection-lifecycle`. `npm run build` passed (~46s); the combined root Vitest run passed **518 tests in 28 files** (~11s), including all changed tests, the connection-surface suite and the OIDC driver contract. The dedicated browser scenario-definition run passed **80 tests** (~3s). No push, draft PR, CI, or Case 2; refresh the generated localization bundle with `npm run l10n` before the Case 2 localization check. + +**Not run in a live workbench:** same-account expiry or idle recovery in an open tab; **Keep open** with a dirty edit, notice dismissal/copy, then reconnect and open a fresh tab; stale tree actions during a real sign-in or Azure retry. Browser scenario-definition tests do not run those interactions. No decision or work on isolated Shell placement or extraction. + +### Case 2 follow-up (2026-12-02) + +The operator subsequently authorized publishing [draft #1169](https://github.com/microsoft/vscode-documentdb/pull/1169) against `feature/connection-lifecycle` before running Case 2. All eight checks passed: `npm run l10n`, `npm run prettier-fix`, `npm run l10n:check`, `npm run lint`, `npm run build`, `npm run typecheck:tests`, `npx vitest run` (**11,011 passed, 1 skipped; 473 files**) and `npm run package` (8.65 MB VSIX). Commit `868cfe934` regenerates the localization bundle, applies formatting and replaces two lint-rejected mock type annotations with Vitest's typed mock syntax. Repository-wide lint passed on retry; no production behavior changed. + +At the time of this verification the PR was in draft. Local checks do not replace the live workbench checks above. + +### Post-merge assessment + +[#1169](https://github.com/microsoft/vscode-documentdb/pull/1169) merged into #1136 as `01590e061`. Compared with its parent `7a1a7f5d2`, all three approved work items landed. **The code now does less; the overall PR did not get smaller.** `git diff --numstat` between those commits gives: + +| Category | Added | Removed | Net | +| ---------------------------- | ------: | ------: | -------: | +| Runtime (`src/`, non-test) | 75 | 142 | −67 | +| Named tests (`*.test.*`) | 692 | 685 | +7 | +| Documentation | 184 | 4 | +180 | +| Browser scenarios and locale | 7 | 8 | −1 | +| **Total (43 files)** | **958** | **839** | **+119** | + +- **Test trimming was real but local.** WI-1 alone removed 114 net test lines; its five focused suites went from 166 to 143 cases, including 12 superseded-dismissal combinations reduced to two. WI-2 and WI-3 added 90 and 38 net test lines respectively; final formatting/lint fixes removed seven. The tests now distinguish a stale key read, a late sign-in, a pending write and failed removal rather than crossing every reason with every caller. Some modal and “no side effect” assertions still repeat in the [sign-in suite](../../../../../src/commands/signInAgain/signInAgain.test.ts#L285). That's a small test-only opportunity, not an unimplemented feature. +- **The main benefit is structural.** The four named tree actions use [one feedback policy](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L71); deliberate quiet refreshes remain quiet. [Retirement](../../../../../src/documentdb/connectionBindingRetirement.ts#L16) stores one cutoff per cluster instead of a growing history of reasons. [Failed Remove](../../../../../src/documentdb/connectionTeardown.ts#L322) still verifies ownership before restoring the current disconnected state without rewriting history or notifying stale panels twice. Keeping Azure Discovery, Show Connection Stats, retained views, ordinary workers and the isolated Shell was intentional. The 876 diagnostic-Shell test lines were never an approved saving. +- **What is still missing is runtime evidence, not another abstraction.** On the merged head the build and 307 focused cases in 10 suites passed independently, as did 80 browser scenario-definition tests. The latter do not drive a browser. The prior Case 2 results are recorded above, not rerun here. Before release, exercise same-account expiry/idle wake in a real tab, dirty **Keep open → dismiss/copy → reconnect** with the old tab still unable to save, and a tree Retry/sign-in superseded in flight. No blocking implementation omission was found in the accepted scope. Stop cutting unless one of those checks exposes a problem. diff --git a/docs/ai-and-plans/features/connection-lifecycle/research-findings.md b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md new file mode 100644 index 000000000..e2e01f3b0 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md @@ -0,0 +1,271 @@ +--- +feature: connection-lifecycle +kind: research +status: active +created: 2026-11-19 +verified: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/utils/azureClients.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Why connections stop working in long-running sessions (#1102) + +> Evidence gathered on 2026-11-18/19 for [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102). +> Code was read at `main` @ `1180ceb2f`: mongodb driver 7.2.0, `@microsoft/vscode-azext-azureauth` +> 4.1.1, `@microsoft/vscode-azext-azureutils` 4.2.0, `@microsoft/vscode-azext-utils` 4.1.0. +> Telemetry comes from `ddtelvscode/VSCodeExt.RawEventsVSCodeExt`, last 28 full days. "Machines" +> means distinct `VSCodeMachineId`. Line numbers are at that commit and will drift; function names +> are the stable pointer. + +## Summary + +There are three separate defects. Two are about tokens that expire. The third is about a stale +client. Together they explain "everything is disconnected, and only restarting VS Code helps". + +| # | Defect | Who | Telemetry (28 days) | Confidence | +| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | +| 1 | The **Entra ID database token is captured once** and the OIDC callback returns it forever | Interactive Entra ID (Azure DocumentDB) | ≥60 of 153 long-running Entra machines. No failures between 30 and 60 min; the first failures appear at 60–75 min | Verified (code + telemetry) | +| 2 | The **ARM token is frozen inside the `AzureSubscription`** that discovery tree items hold, and the ARM 401 challenge handler crashes with `e.endsWith is not a function` | Azure Discovery (vCore + RU) | 27 of 350 discovery machines. **Every** ARM challenge in 28 days failed. Median onset is about 13 h | Verified (code + telemetry) | +| 3 | **No recovery path.** The cached `ClustersClient` is never evicted, Retry reuses it, and Collection View tabs hold the old instance | All auth methods | Amplifies #1. 16 machines saw "Client must be connected before running operations" in the Collection View | Code verified; the trigger for #3b is a hypothesis | + +Native (username and password) authentication is **not** affected by expiry. The driver signs every +new socket in again with SCRAM. Native failures are mostly timeouts, and a few code 18 errors that do +not depend on how long the connection has been open. + +## 1. Entra ID (interactive) database connections + +### Mechanism + +- `MicrosoftEntraIDAuthHandler.configureAuth` acquires one VS Code session (`getSessionFromVSCode`, + [MicrosoftEntraIDAuthHandler.ts:93-107](../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)). + It then builds the OIDC callback as a closure over that session + ([MicrosoftEntraIDAuthHandler.ts:155-162](../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)): + `Promise.resolve({ accessToken: session.accessToken, expiresInSeconds: 0 })`. +- The wrapper in [oidcClientOptions.ts:151](../../../../src/documentdb/auth/oidcClientOptions.ts) + (`buildOidcClientConfiguration`) checks the destination policy around the callback. It does not + change the token. +- The driver can recover on its own. In `node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js:22-51`, + when the cached token gets code 18, the driver drops it and **calls the callback again**. Our + callback returns the same expired token, so the code 18 error reaches the user. +- The driver gives `OIDC_CALLBACK` a hard **60 s timeout** (`AUTOMATED_TIMEOUT_MS`, + `automated_callback_workflow.js:67-74`). The callback runs under a lock + (`callback_workflow.js`, `withLock`). +- The `MongoClient` lives in the static `ClustersClient._clients` map until it is explicitly deleted + ([ClustersClient.ts:196](../../../../src/documentdb/ClustersClient.ts)). Every new pool connection + signs in through that callback. New pool connections appear after idle sockets close, or after the + server drops sockets when the token expires. +- These paths are already correct, because they acquire a token for each callback: + - managed identity ([ManagedIdentityAuthHandler.ts:103-148](../../../../src/documentdb/auth/ManagedIdentityAuthHandler.ts)); + - the shell and playground workers, whose `tokenRequest` IPC is answered on the main thread + ([playgroundWorker.ts:189-230](../../../../src/documentdb/playground/playgroundWorker.ts) decodes + the JWT `exp` claim; [ShellSessionManager.ts:450](../../../../src/documentdb/shell/ShellSessionManager.ts); + [PlaygroundEvaluator.ts:467](../../../../src/documentdb/playground/PlaygroundEvaluator.ts)). + However, both of these use **`createIfNone: true` inside the callback**, so a token refresh in + the background can open a sign-in prompt. +- VS Code's Microsoft auth provider (MSAL) refreshes access tokens silently from its refresh token. + `getSession(..., { silent: true })` inside the callback returns a valid token without a prompt in + the normal case. + +### Telemetry + +Failures were attributed to auth methods through successful `connect.startup` events in the same +`VSCodeSessionId`, using single-auth sessions only. "Late" means at least 60 min after the last +successful startup in that session. + +| Auth | Signature | Surface | Machines late | Machines early | +| -------- | ------------------------------ | ------------------------ | ----------------- | -------------- | +| Entra ID | code 18 `AuthenticationFailed` | tree | **60** (430 rows) | 15 | +| Entra ID | `connection N to … closed` | tree | **41** | 13 | +| Entra ID | `connection N to … closed` | Collection/Document View | **40** | 5 | +| Native | code 18 | tree | 14 | 11 | +| Native | timeout | tree / webview | 26 / 18 | 9 / 7 | + +Denominators, from sessions with a successful connect: + +| Auth | Machines | Machines active ≥60 min after connect | +| -------- | -------- | ------------------------------------- | +| Native | 921 | 674 | +| Entra ID | 187 | 153 | +| No Auth | 107 | 48 | + +Age of the **first** failure in sessions that used only Entra ID: + +| Age | Sessions with code 18 | Sessions with socket closed | +| ---------- | --------------------- | --------------------------- | +| <30 min | 4 | 0 | +| 30–60 min | **0** | **0** | +| 60–75 min | 8 | 12 | +| 75–90 min | 11 | 16 | +| 90–120 min | 27 | 25 | +| 2–4 h | 28 | 36 | +| 4–8 h | 17 | 17 | +| ≥8 h | 49 | 55 | + +Failures start at 60–90 min, which matches the lifetime of an Entra access token. The socket-closed +errors start at the same time. **Hypothesis, not confirmed with the service team:** the server closes +connections when the token expires, and the following reconnects then fail with code 18. + +## 2. Azure Discovery (ARM) credentials + +### Mechanism + +1. In azureauth 4.1.1, `VSCodeAzureSubscriptionProvider.getSubscriptionsForTenant` + (`out/src/VSCodeAzureSubscriptionProvider.js:319-331, 364-391`) creates every subscription with + `authentication.getSession = () => session` and a credential that returns the token captured at + listing time. +2. Discovery tree items keep that subscription (`readonly subscription` in + [DocumentDBResourceItem.ts:45](../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts), + and the same in the RU and VM items). +3. ARM clients are built through `createSubscriptionContext` ([azureClients.ts](../../../../src/utils/azureClients.ts) → + azext-utils `credentialUtils.js:33-44`). The credential wraps `subscription.authentication.getSession`, + which is the frozen session. +4. After the token expires, ARM answers 401 with a challenge. The azureutils 4.2.0 `BearerChallengePolicy` + (`createAzureClient.js:76-98`) calls `createCredentialsForScopes(challengeRequest)`, which leads to + `getSessionWithScopes(requestObject)`. azureauth 4.1.1 expects a list of scope strings and calls + `scope.endsWith(...)`, which throws **`TypeError: e.endsWith is not a function`**. azureutils + 4.2.0 is built against azureauth `^6.0.0-alpha.6`. +5. Diagnostics turns this into `target.sourceInaccessible` with reason `other`, which shows as + "Azure details unavailable". The TypeError has no HTTP status and no sign-in error name + ([resolveTarget.ts:52-82](../../../../src/connectionDiagnostics/checks/resolveTarget.ts), + [readCredentialsForDiagnostics.ts](../../../../src/tree/documentdb/readCredentialsForDiagnostics.ts)). +6. Refresh or Retry on a cluster node reuses the subscription stored on the item. Only listing the + subscriptions again creates a new session. + +azureauth 5.1.1, the latest stable version, still captures the token. **v6 (alpha) fixes this:** +`AzureSubscriptionProviderBase.getToken` calls `getSessionFromVSCode(..., { silent: true })` on every +call. Upgrading is tracked in [#990](https://github.com/microsoft/vscode-documentdb/issues/990). + +### Telemetry + +- `challenge=true` occurs only together with `challengeSuccess=false` and + `challengeError="e.endsWith is not a function"`. **There is no successful challenge** in the 28 days. + Affected events include `azure-discovery.getchildren` (12 machines), `connect` from vCore discovery + (8), `getcredentials` from RU discovery (8), and `azure-mongo-ru-discovery.getchildren` (3). +- 27 of the 350 machines that used Azure discovery were affected (about 8%). Onset was a median of + about 13 h after the session's first discovery event; the 25th percentile is 96 min. + +## 3. No recovery path, and stale references + +- `ClustersClient.getClient` returns the cached instance and calls `mongoClient.connect()` + ([ClustersClient.ts:571-619](../../../../src/documentdb/ClustersClient.ts)). That call does nothing + on a live topology. On a closed topology it reconnects with the same options, so with the same + stale callback. +- No error path evicts a client on code 18, code 391 or a network failure. `deleteClient` is called + only by Update Credentials ([updateCredentials.ts:142](../../../../src/commands/updateCredentials/updateCredentials.ts)), + Update Connection String, Remove Connection and Local Quick Start cleanup. +- The tree's **Retry** ([retryAuthentication.ts](../../../../src/commands/retryAuthentication/retryAuthentication.ts)) + only resets the node's error state and refreshes it. `getChildren` then reuses the cached client + and fails again ([ClusterItemBase.ts:358-447](../../../../src/tree/documentdb/ClusterItemBase.ts)). +- Different surfaces get their client differently: + - **`ClusterSession` holds a direct client reference.** Collection View queries and the AI + services use it ([ClusterSession.ts:65-78, 688-725](../../../../src/documentdb/ClusterSession.ts); + `initNewSession` is called from [openCollectionView.ts:67](../../../../src/commands/openCollectionView/openCollectionView.ts)). + - **These resolve the client per operation**, with no identity check: + - Document View ([documentsViewRouter.ts:54,91](../../../../src/webviews/documentdb/documentView/documentsViewRouter.ts)); + - the index and Query Insights routers; + - the Cluster Dashboard. + + After an identity change, these would quietly use the new identity. + +- The Cluster Dashboard `measureRtt` polls the cached client + ([clusterDashboardRouter.ts:221-225](../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts)). + Polling backoff is tracked in [#1091](https://github.com/microsoft/vscode-documentdb/issues/1091). +- **Possible triggers for "Client must be connected before running operations"** (16 machines): + - `updateCredentials` calls `deleteClient` while Collection View tabs still hold the closed client. + - The `getClient` abort handler closes the **shared** cached client when someone cancels a cached + reuse ([ClustersClient.ts:586-592](../../../../src/documentdb/ClustersClient.ts)). +- There is no Disconnect command. It is proposed in [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059), + and its overlap with Remove Connection is [#566](https://github.com/microsoft/vscode-documentdb/issues/566). +- Under sovereign-clouds decision D12 ([decisions.md](../sovereign-clouds/decisions.md)), open + shells snapshot their identity and token audience, and Update Credentials does not touch them. That + snapshot is a precedent for the identity binding proposed here. + +## 4. Native auth, RU and others + +- **Native (SCRAM):** idle socket closes recover on their own. Late failures are timeouts, which + points to sleep, VPN or idle firewalls. The code 18 errors appear about as often early as late, + so they point to changed credentials rather than expiry. +- **RU:** the extension authenticates with account keys only. These are fetched from ARM through + `listConnectionStrings` ([ruClusterHelpers.ts](../../../../src/plugins/service-azure-mongo-ru/utils/ruClusterHelpers.ts)). + Signing in to Azure matters only for discovery, which is defect #2. A regenerated key causes + code 18 until the client is recreated, which is defect #3. +- **Managed identity:** already correct. + +## 5. How telemetry reports this today + +- `connect.startup` masks its whole error, which is by design. Failure events after the connection + has been established carry neither `authMethod` nor connection age. Attributing them needs a join + on `connectionCorrelationId` (1.1.0+) or on `VSCodeSessionId`. +- `connectionCorrelationId` is present on only about 2% of the tree failures with code 18 in the + window. +- Webview RPC failures keep the real message only in `errorcause`. +- Some code 18 messages are replaced by the secret scanner. +- Diagnostics reports the ARM challenge crash as `other` instead of `signInRequired`. +- No event records "a client that had worked failed" or "recovered". + +## 6. How vscode-cosmosdb handles this (origin/main `3b19fd92`, 2026-11-19) + +- **Data-plane Entra tokens are never captured.** `aadCredentials.getToken` calls `getSessionFromVSCode` + on every request and returns `expiresOnTimestamp: 0` (`src/cosmosdb/getCosmosClient.ts:98-124`). + This is the pattern this plan adopts. +- **Prompting:** as a last resort, they call `createIfNone: true` from inside the token callback + (`getCosmosClient.ts:151-190`). That causes the open P1 microsoft/vscode-cosmosdb#3110: the sign-in + prompt keeps coming back after the session expires, even after the user dismisses it. Users ask for + a disconnected or read-only mode. **Avoid this.** +- **Subscriptions** come from the Azure Resources host extension, which owns token refresh. Their azext + major versions match (azureauth 5.1.1, azureutils 5, utils 5). +- **No client cache:** a new `CosmosClient` is created for each operation, and tabs hold a connection + descriptor. Cosmos traffic is stateless HTTP, so this works for them. It is **not** suitable for us; + see decision [0002](./decisions.md). +- **Query Editor connection state:** a `connectionVersion` counter. A connection change disposes its + sessions, and stale results are rejected with "These query results are no longer current. Run the + query again before using them." (`panels/trpc/queryEditorConnectionState.ts`). +- **Gaps they share with us:** + - Remove does not close or notify open tabs. + - There is no `onDidChangeSessions` listener. + - There is no identity binding: `getSession` is called without `account`, so a tab can quietly use + a different account. + - The shell receives a captured token. + +## 7. Cost of creating a client (why the cache stays) + +Successful `connect.startup` durations over the last 14 days. The value is `Measures.duration`, +read as seconds: + +| Auth | Startups | p50 | p90 | +| -------- | -------- | ------- | ------ | +| Native | 2,102 | ~1.1 s | ~4.3 s | +| Entra ID | 912 | ~2.0 s | ~9.0 s | +| No Auth | 188 | ~0.07 s | ~1.8 s | + +A `MongoClient` also owns server sessions and monitoring, and the shell and playground hold cursors. +Collection View pagination does **not** hold a cursor: each page is a separate offset (`skip`) query, as +`ClusterSession.runFindQueryWithCache` shows (corrected 2026-11-19; an earlier version of this document +said it used `getMore`). A per-operation client would still cost seconds per action. + +## Appendix: queries + +The queries were run in the local telemetry dashboards devbox worktree, using the +`vscode-documentdb-telemetry-dashboards` skill. They are summarized here so they can be rerun. + +- **Failure signatures:** failed events whose `errormessage` or `errorcause` matches + `Authentication failed` or `error == "18"`, `connection … closed`, `ECONNRESET`, + `Client must be connected`, or `timed out`, grouped by event. +- **Attribution by session:** + - Failures joined to successful `connect.startup` (`startupoutcome == "succeeded"`) on + `VSCodeSessionId`, with `StartTs <= FailTs`. + - Only sessions where every startup used the same `authmethod`. + - Late means `FailTs - max(StartTs) >= 60 min`. +- **Histogram of the first failure:** sessions that used only Entra ID, from + `min(FailTs) - min(StartTs)`. +- **ARM challenge:** `Properties.challenge == "true"` or a non-empty `challengeerror`. Reach is + measured against machines with any Azure discovery event (`discoveryproviderid` starting with + `azure-`). diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md new file mode 100644 index 000000000..3bee34fd0 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -0,0 +1,245 @@ +--- +feature: connection-lifecycle +kind: notes +status: active +created: 2026-11-25 +--- + +# Connection lifecycle telemetry + +**Pending ingestion verification.** Run these queries in the extension's Application Insights Logs workspace. +Paste the common setup before any one query body. Set the actual extension version (including +the prerelease suffix for CP-5) and UTC window to inspect. + +```kusto +let StartAt = startofday(ago(7d)); +let EndAt = StartAt + 7d; +let ReleaseVersion = "1.2.0"; +let Events = + customEvents + | where timestamp >= StartAt and timestamp < EndAt + | extend version = coalesce(tostring(customDimensions["common.extversion"]), + tostring(customDimensions.extensionVersion), tostring(column_ifexists("application_Version", "")), "(missing)") + | where version == ReleaseVersion + | extend eventScope = tolower(extract(@"([^/]+)$", 1, name)), + sdkResult = tolower(tostring(customDimensions.result)); +let Operations = + Events + | extend parentContext = tostring(customDimensions.parentNodeContext) + | extend family = case( + eventScope == "connect", "connect", + eventScope startswith "documentdb.rpc.", "rpc", + (eventScope == "getchildren" or eventScope endswith ".getchildren") + and isnotempty(parentContext) and parentContext !~ "root", "getchildren", + "") + | where isnotempty(family) + | extend connectionResult = tolower(tostring(customDimensions.connectionResult)) + | extend operationResult = case( + sdkResult == "canceled" or connectionResult in ("canceled", "cancelled"), "canceled", + sdkResult == "failed" or connectionResult == "failed", "failed", + sdkResult == "succeeded" or connectionResult == "success", "succeeded", + "(missing)") + | extend ageMs = todouble(customMeasurements.connectionAgeMs), + generation = tolong(customMeasurements.clientGeneration), + failureKind = tostring(customDimensions.connectionFailureKind), + failureType = tostring(customDimensions.causeType), + recoveryRows = tostring(customDimensions.usedCachedErrorNode) =~ "true" + or tostring(customDimensions.cachedErrorNode) =~ "true" + | extend signature = case( + operationResult != "failed", "", + family != "rpc", "notClassified", + failureType in~ ("18", "391", "AuthenticationFailed", "Unauthorized", + "EntraSignInRequiredError", "EntraIdentityMismatchError"), "auth", + failureType in~ ("MongoNotConnectedError", "MongoTopologyClosedError"), "closedClient", + failureType in~ ("MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE"), "socket", + "otherOrUnclassified"); +``` + +## Daily database token lookups and lifetime + +`connection.tokenRenewal` counts post-startup Entra database token lookup outcomes. For `extension`, +`returned` means the token passed the host callback's checks. For `shell` and `playground`, it means +the host checked and sent a token response; the worker can still reject or discard it before its +callback completes. On any surface, `returned` does **not** mean the token changed, MSAL made a +network request, or the database accepted the token. Lifetime is the +JWT's positive `exp − iat` in seconds, not its remaining validity. An opaque or invalid lifetime is +missing, not zero. Compare returned rows with and without a lifetime; failures don't have one. +The bounded outcomes are `returned`, `noSession`, `providerChanged`, `identityMismatch`, `failed` and +`timedOut`. The extension host reports `timedOut` when the driver aborts a pending, still +eligible lookup. The Shell and Playground relay gives the timeout precedence over the late +lookup outcome if it settles after the driver stopped waiting; a worker lookup that never +settles does not produce a renewal row. +Before the provider-change split, `noSession` also included changes to the sign-in environment. + +```kusto +Events +| where eventScope == "connection.tokenrenewal" +| extend surface = coalesce(tostring(customDimensions.surface), "(missing)"), + outcome = coalesce(tostring(customDimensions.renewalOutcome), "(missing)"), + lifetime = todouble(customMeasurements.tokenLifetimeSeconds) +| extend lifetime = iff(lifetime > 0, lifetime, real(null)) +| summarize lookups = count(), + lifetimeSamples = countif(isnotnull(lifetime)), + missingLifetime = countif(isnull(lifetime)), + percentiles(lifetime, 50, 90) + by version, day = bin(timestamp, 1d), surface, outcome +| order by day asc, surface asc, outcome asc +``` + +This is background activity: exclude `connection.tokenrenewal` from active-use event scopes. +Expect roughly one lookup per active Entra client-hour, not one per operation. Use daily counts by +surface to check the observed volume against the telemetry budget. No lookups means no evidence. + +## Explicit Reconnect requests and startup outcomes + +Count `connect.startup` with `startupTrigger=explicitReconnect`: one event per first physical +extension-client startup after an accepted tree **Reconnect** in the same connection lifetime, +including when several callers wait on it. Use `startupOutcome`, not the command's SDK result. + +```kusto +Events +| where eventScope == "connect.startup" and tostring(customDimensions.startupTrigger) == "explicitReconnect" +| summarize attempts = count(), succeeded = countif(customDimensions.startupOutcome == "succeeded"), + failed = countif(customDimensions.startupOutcome == "failed"), + canceled = countif(customDimensions.startupOutcome == "canceled") +``` + +An accepted command carries `requestedStartupCorrelationId`, equal to the `startupCorrelationId` +of that startup if one runs. A click that only clears the disconnected state has no startup +outcome; a missing match is **not observed**, not a failed connection. Stale clicks do not +reserve an ID. A new disconnect, credential edit or invalidation discards the reservation. +Later retries, worker startups and driver-internal socket reconnects are not explicit Reconnect +starts. A successful startup is also distinct from the user completing their next database read. + +## Observed outcomes by client age and entry generation + +`successfulExpansionsEnteringGen2Plus` counts successful cluster expansions that reported +generation 2 or later **at entry** and did not return first-time or cached recovery rows. It +does not count an expansion that enters on generation 1 and replaces it during the operation. +Discovery expansions do not report a generation here. The count is neither unique recoveries nor +proof that renewal triggered them. Other operations are shown for context only: an RPC can return a +typed unavailable result without reporting an SDK failure. Missing ages and generations are shown +explicitly. + +```kusto +Operations +| extend ageBand = case( + isnull(ageMs) or ageMs < 0, "(missing)", + ageMs < 3600000, "<1h", ageMs < 7200000, "1–2h", ageMs < 14400000, "2–4h", "4h+"), + generationBand = case(isnull(generation) or generation < 1, "(missing)", generation == 1, "1", "2+"), + lifecycleKind = coalesce(failureKind, "(missing)") +| summarize operations = count(), + successfulExpansionsEnteringGen2Plus = countif( + family == "getchildren" and tolower(parentContext) matches regex @"\btreeitem_documentdbcluster\b" + and operationResult == "succeeded" and generation >= 2 and not(recoveryRows)) + by version, family, ageBand, generationBand, operationResult, lifecycleKind, signature +| order by family asc, ageBand asc, generationBand asc +``` + +## Webview operations blocked by the connection + +On `documentDB.rpc.*`, `unavailableReason` is set only for a valid connection-unavailable +response. Its bounded values are `signInRequired`, `credentialsRejected`, `credentialsMissing`, +`credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, +`connectionRemoved`, `unreachable` and `sessionEnded`. `sessionEnded` identifies a permanently +retired binding, regardless of how its session ended. It does not replace the current connection's +failure reason. The property carries no error text or connection identifiers. +Check that CP-5 can see the property after exercising a typed unavailable response, and that +an ordinary successful response does not get it. + +```kusto +Events +| where eventScope startswith "documentdb.rpc." +| extend reason = tostring(customDimensions.unavailableReason) +| where isnotempty(reason) +| summarize blockedOperations = count() by version, eventScope, reason, sdkResult +``` + +## Did an affected Collection View tab complete another database read? + +Use the common setup above with a **verified candidate version** and a completed UTC window. +The unit is one affected tab, not a person, a click or a physical client. Only first-page Find +and Refresh RPCs carry the existing host-generated `collectionSessionId`. It survives a same-tab +client replacement; a fresh tab gets a different ID. No new event, identifier, query text or +database name is needed. A successful empty first page is a real database read. Pagination, +cached rendering, retained-tab notices and background work are not evidence of recovery. + +```kusto +let Reads = materialize(Events + | where eventScope == "documentdb.rpc.query.mongoclusters.collectionview.runfindquery" + | extend tab = tostring(customDimensions.collectionSessionId), + reason = tostring(customDimensions.unavailableReason), cause = tostring(customDimensions.causeType), + seconds = todouble(customMeasurements.duration) + | where isnotempty(tab) + | project tab, finished = timestamp, started = timestamp - seconds * 1s, sdkResult, reason, cause); +let Affected = Reads + | where sdkResult != "canceled" and (reason in ("signInRequired", "credentialsRejected", "credentialsMissing", "unreachable") + or (sdkResult == "failed" and cause in~ ("18", "AuthenticationFailed", "MongoNotConnectedError", + "MongoTopologyClosedError", "MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE"))) + | summarize failure = min(finished) by tab + | where failure < EndAt - 1h; +Affected +| join kind=leftouter Reads on tab +| extend later = started > failure and finished <= failure + 1h +| summarize observed = countif(later), completed = countif(later and sdkResult == "succeeded" and isempty(reason)) by tab +| summarize affectedTabs = count(), readSucceeded = countif(completed > 0), + followedUpWithoutSuccess = countif(observed > 0 and completed == 0), noObservedFollowUp = countif(observed == 0) +``` + +`duration` here is the azext RPC measurement in **seconds**; subtract it from the event's client +timestamp, not server ingestion time, to exclude overlapping calls. Missing durations cannot +establish ordering. Count once per tab, even after repeated failures or successes. The three +outcomes partition the affected tabs. No follow-up is **unknown**, not failure: the user may +have stopped, closed the tab or had telemetry omitted. The query need not be identical and +the data cannot establish which repair caused the success. This does not measure Shell, +Playground, writes or a cross-release improvement. + +For ingestion acceptance, exercise a failed Find and a successful Refresh in the same live tab; +check that they count as **one** affected tab with a successful read. Repeat with the success +in a fresh tab only: the original must remain without an observed follow-up. Check the version +and window against the package receipt. Zero affected tabs is not a 0% recovery rate. + +## Cross-release comparison deferred + +In 1.2.0, a database RPC can return auth or closed-client unavailability as a normal +response, recorded as `Succeeded` without `causeType`. Older versions could report the same +outcome as an RPC failure. Matching procedures and signatures therefore does not make the +counts comparable. Use the queries here to describe a single release and verify ingestion, +not to claim that late failures fell; see +[decision 0020](./decisions.md#0020-defer-the-cross-release-comparison-of-late-failures). + +## Partial Azure subscription listings + +`azureSubscriptions.partialListing` records `skippedAccounts` and `skippedTenants` as numeric +measurements when the SDK skips an account or tenant but returns a listing. Signed-out omissions +are not counted. Callers coalesced onto one SDK listing share a single event. The event does not +contain account, tenant or subscription identifiers. It does not mean that the whole listing failed. + +## Webview explanation fallback + +`documentDB.webview.event..explainOperationFailureFailed` records a rejected explanation +request in the shared recovery flow or on Document View Save. The event adds no error text or +connection identifiers. The fallback notification keeps the original operation failure as its +detail. If the reporting request also fails, the webview logs a fixed diagnostic without the +original error. + +## ARM challenge versus final operation result + +Use the existing Azure SDK challenge dimensions and the final framework `result` on the **same** +event. A token was acquired when `challengeSuccess=true`; count `true` with `succeeded` separately +from `true` with `failed`, `canceled`, or a missing result. For a scope that wraps multiple requests +or both ARM and database work, this is the enclosing operation's result, not a per-request ARM +status. Use an ARM-only single-request scope when verifying that ARM accepted the retried request. +Zero observed challenges is inconclusive. + +```kusto +Events +| where tostring(customDimensions.challenge) =~ "true" +| extend challengeOutcome = tolower(tostring(customDimensions.challengeSuccess)) +| extend challengeOutcome = case(challengeOutcome == "true", "tokenAcquired", + challengeOutcome == "false", "noToken", "(missing)"), + finalResult = coalesce(sdkResult, "(missing)") +| summarize challengedOperations = count() + by version, day = bin(timestamp, 1d), eventScope, challengeOutcome, finalResult +| order by day asc, eventScope asc +``` diff --git a/docs/ai-and-plans/features/survey/design.md b/docs/ai-and-plans/features/survey/design.md index 858484976..777ce9613 100644 --- a/docs/ai-and-plans/features/survey/design.md +++ b/docs/ai-and-plans/features/survey/design.md @@ -180,8 +180,8 @@ precondition and eligibility gate for presentation and invitation actions. That override is ignored outside Development. Telemetry independently requires `isFeedbackPermitted()` even during previews; the survey URL remains unchanged. -Development activation registers `_DocumentDB: Survey: Simulate Milestone` and -`_DocumentDB: Survey: Reset State`, with no category and palette visibility gated by +Development activation registers `_DocumentDB: Developer: Survey: Simulate Milestone` and +`_DocumentDB: Developer: Survey: Reset State`, with no category and palette visibility gated by `documentdb-development-mode`. Simulation calls the real inviting entry point with `connection`. Reset closes the invitation, invalidates pending work, waits for queued writes, deletes `SURVEY_STATE_KEY`, and clears local reservation and session suppression. It can diff --git a/docs/index.md b/docs/index.md index 6fae58758..74e98b62d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -89,6 +89,7 @@ The User Manual provides guidance on using the extension. It contains detailed d Explore the history of updates and improvements to the extension. Each release brings new features, enhancements, and fixes to improve your experience. +- [1.2 (unpublished draft)](./release-notes/1.2) - [1.1](./release-notes/1.1) - [1.0](./release-notes/1.0), [1.0.1](./release-notes/1.0#patch-release-v101), [1.0.2](./release-notes/1.0#patch-release-v102) - [0.11](./release-notes/0.11), [0.11.1](./release-notes/0.11#patch-release-v0111), [0.11.2](./release-notes/0.11#patch-release-v0112) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index 32e303e22..8417eca3a 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -9,10 +9,65 @@ published: false # DocumentDB extension for Visual Studio Code v1.2 -Version 1.2 of the **DocumentDB extension for Visual Studio Code** makes collection results +> **Unpublished draft:** this page describes planned 1.2.0 behavior for review. It is not a +> statement that version 1.2 has shipped, and the text may change before release. + +Version 1.2 is planned to make database connections survive routine token renewal and idle drops, +while keeping open views safe when credentials, identities, or connection settings change. It also +adds an explicit Disconnect workflow with clear choices for open tabs, and makes collection results easier to explore, with clearer nested-data navigation and more useful keyboard interactions. -## What's New in v1.2 +## What's New in v1.2 (draft) + +### ⭐ Connections That Stay Usable + +Microsoft Entra ID token renewal is planned to remain silent during normal use. The extension keeps +the connection pinned to the account and tenant that established it, including in the Interactive +Shell and Query Playground. Closed clients and recoverable transient failures can be replaced on a +later foreground operation without restarting VS Code. + +When silent sign-in is no longer possible, the extension asks for an explicit action at the surface +where work is happening. The tree offers **Retry sign-in**, while the shell and playground can offer +**Sign in again**. The operation never moves an existing session to a different Microsoft account. + +Azure discovery also renews its Azure Resource Manager credentials rather than retaining a frozen +token from an earlier provider tree. This work addresses +[#990](https://github.com/microsoft/vscode-documentdb/issues/990) and +[#1102](https://github.com/microsoft/vscode-documentdb/issues/1102). + +See [Keep connections usable](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#keep-connections-usable). + +### ⭐ Disconnect, Reconnect, and Keep Your Place + +Connected clusters gain a **Disconnect** action. Before ending live work, the extension asks what to +do with open view tabs: **Close all** or **Keep open**. A setting can choose either +behavior in advance, while closing the dialog cancels and unsaved document changes still require +explicit confirmation. + +Retained Collection View, Document View, and Cluster Dashboard contents stay available for +inspection or copying under a read-only notice. Dismissing the notice does not restore +database access, and **Reconnect** never revives the old tab. Use **Close view** to close it and +open a fresh view from the tree for new work. Ordinary token, sign-in or network recovery is +different: it keeps an unchanged connection's existing view usable, and the user explicitly runs +an operation again after repair. + +If a tracked copy, export, or import is using the cluster, the task and connection keep running. +Select **Disconnect** again after the task finishes or you stop it. The same teardown rules apply +when a saved connection is deleted, with the additional step of removing its saved +connection and cached credentials. See +[#566](https://github.com/microsoft/vscode-documentdb/issues/566) and +[#1059](https://github.com/microsoft/vscode-documentdb/issues/1059). + +Learn how retained views, shells, and playgrounds behave in the +[connection lifecycle guide](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#disconnect-and-reconnect). + +### ⭐ Open Work Stays Bound to Its Original Connection + +Saving changes with **Update Credentials…** or **Update Connection String…** requires the old +connection to end first. For a connected item, **Disconnect and update** runs the normal +Disconnect checks and tab choice before the editor opens. Kept tabs remain permanently read-only; +open a fresh view from the tree to use the saved settings. Cancelling or a blocked/failed +Disconnect does not start the edit. ### ⭐ Explore nested collection results @@ -30,4 +85,20 @@ row if desired. See [Querying in Collection View](https://microsoft.github.io/vscode-documentdb/user-manual/collection-view-querying) for details. This work was tracked in [#1101](https://github.com/microsoft/vscode-documentdb/issues/1101). +## Key Limits and Improvements + +- **No replay of uncertain writes.** Recovery and reconnect never resubmit a failed operation. + Check the server before repeating a write that did not report an outcome. +- **Keep useful text, not the old worker.** Disconnect stops Shell and Playground workers while + retaining terminal scrollback and file text. An explicitly ended session is not replayed or + silently rebound to a later connection. +- **Follow-up network work is outside this release.** Kubernetes tunnel recreation and broader + network resilience remain tracked in + [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105). + **Minimum VS Code version:** 1.123.0. + +## Changelog + +See the unpublished draft entry for this release: +[CHANGELOG.md#120](https://github.com/microsoft/vscode-documentdb/blob/main/CHANGELOG.md#120-unreleased) diff --git a/docs/user-manual/collection-view-index-management-troubleshooting.md b/docs/user-manual/collection-view-index-management-troubleshooting.md index d61419b4f..08786d328 100644 --- a/docs/user-manual/collection-view-index-management-troubleshooting.md +++ b/docs/user-manual/collection-view-index-management-troubleshooting.md @@ -18,7 +18,13 @@ If the list loads but Size or Usage is unavailable, the server may not provide t The tab shows **Creating** after the extension sends a create request. It shows **Building** while the server reports an active index build. -The tab refreshes while an active build is present. Wait for the status to become **Ready**, or use **Refresh** to request the current server state. +The tab refreshes while an active build is present. Wait for **Ready**, or select **Refresh** to +request the current server state. If automatic refresh paused because of a connection error, select +**Refresh** after restoring the connection; it does not resume automatically. + +If you create an index while automatic refresh is paused, the row can still show **Creating** +after the request succeeds. Select **Refresh** to see its current status and resume automatic +refresh if the index is still building. ## Creating an index fails diff --git a/docs/user-manual/collection-view-index-management.md b/docs/user-manual/collection-view-index-management.md index 4a964a0ea..3e2a655c6 100644 --- a/docs/user-manual/collection-view-index-management.md +++ b/docs/user-manual/collection-view-index-management.md @@ -39,7 +39,8 @@ An index can have one of these states: | Creating | The create request has been sent and the extension is waiting for the server result. | | Building | The server reports that the index build is still in progress. | -The tab refreshes while an index is creating or building. You can also select **Refresh** at any time. +The tab refreshes while an index is creating or building. If a recoverable connection error pauses +automatic refresh, restore the connection and select **Refresh** to resume it. ## Create an index diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 64811b8cf..31555e1e4 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -21,8 +21,85 @@ The actions available depend on the connection and the failure: 1. **Update connection string…**, when offered, corrects the saved destination before you change credentials. 2. **Update credentials…**, when offered, lets you review the saved authentication. 3. **Diagnose connection…** opens [step-by-step connection diagnostics](./diagnose-connection). -4. **Open shell** opens the Interactive Shell for further investigation. +4. **Open shell without authentication** opens a diagnostic Interactive Shell without using the + failed saved login. The server can still reject database commands that require authentication. 5. **Retry** tries the connection again after you have corrected or investigated the problem. Retry is always last. These shorter labels apply to the recovery rows under a failed cluster; context-menu and Command Palette titles can differ. + +If a recovery action can no longer act on the original connection, refresh the tree and choose +the action available for the current connection. Actual sign-in and credential failures still +show their specific repair instructions. + +The normal context-menu Shell still uses the connection's saved authentication. The diagnostic +Shell keeps local commands, methods, operators and history suggestions, but does not borrow +database, collection or field suggestions from an authenticated shared client. If the endpoint is +not available, the action explains that instead of retrying the saved authentication. + +## Keep connections usable + +The extension normally recovers from an expired Microsoft Entra ID token or an idle connection +without restarting VS Code. Silent recovery uses the account and tenant that established the +connection. It does not open a sign-in prompt from a background refresh. + +If Microsoft sign-in can no longer be renewed, the tree offers **Retry sign-in**. The Interactive +Shell and Query Playground can instead offer **Sign in again**. Sign in with the identity originally +used for that connection. The old view is not moved to a different account. After the repair, +run the operation again in the same view when recovery was for the unchanged connection; failed +commands are not replayed automatically. + +## Disconnect and reconnect + +Right-click a connected cluster and select **Disconnect** to end its live connections. If a copy, +export, or import is using the cluster, both the task and connection keep running. Select +**Disconnect** again after the task finishes or you stop it. + +When open connection views exist and the setting `documentDB.connections.openTabsOnDisconnect` is +`ask`, the **Disconnect?** modal offers: + +- **Close all**, which closes open connection views. Closing any editable Document View first + asks whether to **Discard changes**, even if no edits have been reported. Read-only Document + Views do not need this confirmation. +- **Keep open**, which retains a copyable snapshot but permanently prevents database operations in + those views. +- **Cancel**, by closing the modal, which leaves the connection running. + +This choice applies to Collection View, Document View, and Cluster Dashboard tabs. It does not close +the Interactive Shell terminal or the Query Playground file; Disconnect stops their database +workers. + +The setting can use `closeAll` or `keepOpenDisabled` as a default instead of showing the choice each +time. It never bypasses the editable-document confirmation. **Delete Connection…** uses the same +choice and confirmation, but also removes the saved connection and its cached credentials. + +A retained Collection View, Document View, or Cluster Dashboard shows **Session ended**. Copy what +you need and open a new tab to resume database work: + +- Use the **X** to dismiss the notice and inspect or copy the loaded contents. Database operations + remain disabled. +- Select **Close view** to close the tab. A dirty Document View warns before closing. + +Use the cluster's **Reconnect** action in the tree to start a new session, then open a fresh view. +Neither Reconnect nor same-account sign-in revives a retained view after an explicit Disconnect or +removal. This is different from an ordinary token, authentication or network recovery: those do not +turn a live view into a read-only snapshot. + +Disconnect stops the connection's Shell and Playground workers, but their terminal scrollback or +file text remains. If you delete a saved connection, affected Playground files keep their text but +lose the selection. Use **Connect** in the Playground to select another database. Interrupted +commands and evaluations are not replayed. + +## After changing connection details + +**Update Credentials…** and **Update Connection String…** cannot edit a live connection. When it +is connected, choose **Disconnect and update**. The extension performs the ordinary Disconnect +flow first, including its task checks, tab choice and editable-document confirmation. When you select +**Disconnect and update**, that command waits for its Disconnect to finish before opening the +wizard. Cancelling the flow, a task conflict or a Disconnect failure in that command prevents the edit. + +If you keep tabs during that Disconnect, database operations remain disabled in those tabs, even +after a later reconnect with the same account. Loaded contents remain available for copying, and you +can still edit local query text in Collection View after dismissing the notice. Open fresh views +from the tree to use the updated settings. A cancelled edit leaves the connection disconnected +but does not partially save settings. diff --git a/docs/user-manual/diagnose-connection.md b/docs/user-manual/diagnose-connection.md index af3ff0f2d..23c23bec7 100644 --- a/docs/user-manual/diagnose-connection.md +++ b/docs/user-manual/diagnose-connection.md @@ -38,7 +38,7 @@ There are three ways to open it: - **From a failed connection.** When a cluster fails to connect, the tree shows recovery items under it. Select **Diagnose connection…**. Configuration repairs appear before diagnosis and - **Open shell**, with **Retry** last; see [connection recovery](./connecting-to-databases#recover-from-a-failed-connection). + **Open shell without authentication**, with **Retry** last; see [connection recovery](./connecting-to-databases#recover-from-a-failed-connection). - **From any cluster.** Right-click a cluster in the Connections, Discovery or Azure view and select **Diagnose Connection…**. This works whether or not the cluster is connected. It is not offered on the Local Quick Start instance node. diff --git a/docs/user-manual/interactive-shell.md b/docs/user-manual/interactive-shell.md index cbfe35af9..9ef6e889e 100644 --- a/docs/user-manual/interactive-shell.md +++ b/docs/user-manual/interactive-shell.md @@ -57,6 +57,9 @@ Type "help" for available commands. myDatabase> ``` +For token renewal, Microsoft sign-in recovery, Disconnect, and the limits of reusing an existing +shell after a connection change, see [Keep connections usable](./connecting-to-databases#keep-connections-usable). + ## Shell Commands The following built-in commands are available at the prompt: @@ -258,4 +261,4 @@ The help output also prints the full Settings search query for manual access. --- -> **Related**: [Query Playground](./query-playground) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Query Playground](./query-playground) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) diff --git a/docs/user-manual/managing-azure-discovery.md b/docs/user-manual/managing-azure-discovery.md index d5c574d46..3909028ad 100644 --- a/docs/user-manual/managing-azure-discovery.md +++ b/docs/user-manual/managing-azure-discovery.md @@ -20,6 +20,9 @@ For a general overview of service discovery, see the [Service Discovery](./servi The **Manage Credentials** feature allows you to view your Azure accounts, sign in to specific tenants, and add new accounts for service discovery. +If Azure cannot list some accounts or tenants, Discovery still shows the subscriptions it +could list. Select **Show Output** in the warning to see which listing step was skipped. + ### How to Access You can access the credential management feature in two ways: @@ -178,3 +181,4 @@ When adding a new connection via the **"Add New Connection"** wizard: - [Azure Cosmos DB for MongoDB (RU) Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-ru) - [Azure DocumentDB Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-vcore) - [Azure VMs (DocumentDB) Service Discovery](./service-discovery-azure-vms) +- [Connection lifecycle, sign-in renewal, and teardown](./connecting-to-databases#keep-connections-usable) diff --git a/docs/user-manual/query-playground.md b/docs/user-manual/query-playground.md index b3498eafb..e440d291e 100644 --- a/docs/user-manual/query-playground.md +++ b/docs/user-manual/query-playground.md @@ -38,6 +38,8 @@ There are several ways to open a new Query Playground: The three inline icons next to each collection node are (from left to right): Open Collection View, **New Query Playground**, and Open Interactive Shell. When a playground opens, a CodeLens header at the top displays the connection status, showing which cluster and database the file is connected to. +If the connection expires or is disconnected, see [Keep connections usable](./connecting-to-databases#keep-connections-usable) +for the exact sign-in and reconnect behavior. ## Writing Queries @@ -219,4 +221,4 @@ or use `.maxTimeMS()` on a supported query to set a server-side limit. --- -> **Related**: [Interactive Shell](./interactive-shell) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Interactive Shell](./interactive-shell) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 896451723..ade5ee7fb 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -301,9 +301,7 @@ "$(add) Create...": "$(add) Create...", "$(arrow-left) Back": "$(arrow-left) Back", "$(arrow-left) Go Back": "$(arrow-left) Go Back", - "$(check) Success": "$(check) Success", "$(close) Cancel": "$(close) Cancel", - "$(error) Failure": "$(error) Failure", "$(info) Empty": "$(info) Empty", "$(info) No connections found": "$(info) No connections found", "$(info) Some storage accounts were filtered because of their sku. Learn more...": "$(info) Some storage accounts were filtered because of their sku. Learn more...", @@ -335,6 +333,7 @@ "A client ID uses only 0-9, a-f, and dashes, like {0}.": "A client ID uses only 0-9, a-f, and dashes, like {0}.", "A collection with the name \"{0}\" already exists": "A collection with the name \"{0}\" already exists", "A configured TLS exception allowed the connection despite a certificate verification problem.": "A configured TLS exception allowed the connection despite a certificate verification problem.", + "A connection is already being updated or removed. Try again when it finishes.": "A connection is already being updated or removed. Try again when it finishes.", "A connection name is required.": "A connection name is required.", "A connection to the same host with the same authentication settings already exists.": "A connection to the same host with the same authentication settings already exists.", "A connection with the same username and host already exists.": "A connection with the same username and host already exists.", @@ -343,6 +342,7 @@ "A credential contains a reserved character that is not percent-encoded.": "A credential contains a reserved character that is not percent-encoded.", "a custom cloud": "a custom cloud", "A default kubeconfig source already exists.": "A default kubeconfig source already exists.", + "A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.": "A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.", "A direct connection is requested with more than one seed host.": "A direct connection is requested with more than one seed host.", "A firewall or IP allowlist may be blocking this connection. Check access from the computer or remote host where these checks ran, including VPN and network rules.": "A firewall or IP allowlist may be blocking this connection. Check access from the computer or remote host where these checks ran, including VPN and network rules.", "A folder with this name already exists at this level": "A folder with this name already exists at this level", @@ -499,6 +499,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}", @@ -587,6 +588,7 @@ "Cannot copy TTL or unique indexes with documents": "Cannot copy TTL or unique indexes with documents", "Cannot delete folder \"{0}\". The following {1} task(s) are using connections within this folder:": "Cannot delete folder \"{0}\". The following {1} task(s) are using connections within this folder:", "Cannot move {0} {1}. The following {2} task(s) are using connections being moved:": "Cannot move {0} {1}. The following {2} task(s) are using connections being moved:", + "Cannot open a shell without authentication for \"{0}\": its endpoint is not available.": "Cannot open a shell without authentication for \"{0}\": its endpoint is not available.", "Cannot start task in state: {0}": "Cannot start task in state: {0}", "Capabilities": "Capabilities", "Certificate": "Certificate", @@ -609,6 +611,7 @@ "Changelog": "Changelog", "Check": "Check", "Check a connection step by step and review the results.": "Check a connection step by step and review the results.", + "Check access to the Azure resource and try again.": "Check access to the Azure resource and try again.", "Check Docker again": "Check Docker again", "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.": "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.", "Check how database traffic should reach this cluster from the host running these checks.": "Check how database traffic should reach this cluster from the host running these checks.", @@ -654,6 +657,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.": "Check the network or server.", "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.", @@ -704,7 +708,6 @@ "Choose the migration action…": "Choose the migration action…", "Choose what to copy…": "Choose what to copy…", "Choose whether the listed fields are the only fields indexed or the fields omitted from the index.": "Choose whether the listed fields are the only fields indexed or the fields omitted from the index.", - "Choose whether the task should succeed or fail": "Choose whether the task should succeed or fail", "Choose which fields the wildcard index covers.": "Choose which fields the wildcard index covers.", "Choose your provider…": "Choose your provider…", "Choose your Service Provider": "Choose your Service Provider", @@ -726,7 +729,12 @@ "Clock difference detected": "Clock difference detected", "Clock offset": "Clock offset", "Close": "Close", + "Close all": "Close all", "Close this view and add the credential again.": "Close this view and add the credential again.", + "Close this view?": "Close this view?", + "Close view": "Close view", + "Closing these tabs will discard their unsaved changes.": "Closing these tabs will discard their unsaved changes.", + "Closing this view discards unsaved changes.": "Closing this view discards unsaved changes.", "Closing…": "Closing…", "Cluster": "Cluster", "Cluster actions": "Cluster actions", @@ -803,6 +811,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.": "Connect from the connection tree.", "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…", @@ -815,7 +824,7 @@ "Connect without a username or password": "Connect without a username or password", "Connected": "Connected", "Connected to": "Connected to", - "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials?": "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials?", + "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?": "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?", "Connected to {0}": "Connected to {0}", "Connected to the cluster \"{cluster}\" using decoded password.": "Connected to the cluster \"{cluster}\" using decoded password.", "Connected to the cluster \"{cluster}\".": "Connected to the cluster \"{cluster}\".", @@ -828,6 +837,7 @@ "Connecting to the cluster using a managed identity…": "Connecting to the cluster using a managed identity…", "Connecting to the cluster using a Microsoft Entra account…": "Connecting to the cluster using a Microsoft Entra account…", "Connecting…": "Connecting…", + "connection": "connection", "Connection": "Connection", "connection \"{0}\"": "connection \"{0}\"", "Connection attempt failed": "Connection attempt failed", @@ -842,6 +852,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", @@ -864,7 +875,7 @@ "Connection successful, but 1 check failed": "Connection successful, but 1 check failed", "Connection successful, but 1 check needs attention": "Connection successful, but 1 check needs attention", "Connection timed out": "Connection timed out", - "Connection to \"{cluster}\" was cancelled.": "Connection to \"{cluster}\" was cancelled.", + "Connection update in progress": "Connection update in progress", "Connection updated successfully.": "Connection updated successfully.", "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.": "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.", "Connection works, but sign-in is required": "Connection works, but sign-in is required", @@ -918,6 +929,7 @@ "Copy the Public Key and Private Key from an API Key in MongoDB Atlas. We use them to sign in and show the clusters you can access.": "Copy the Public Key and Private Key from an API Key in MongoDB Atlas. We use them to sign in and show the clusters you can access.", "Copy the source collection's secondary index definitions. TTL and unique indexes must be pasted separately.": "Copy the source collection's secondary index definitions. TTL and unique indexes must be pasted separately.", "Copy this cluster’s connection string to the clipboard": "Copy this cluster’s connection string to the clipboard", + "Copy what you need and open a new tab.": "Copy what you need and open a new tab.", "Copy with password": "Copy with password", "Copy without password": "Copy without password", "Copy-and-Merge": "Copy-and-Merge", @@ -947,6 +959,7 @@ "Could not find parent folder.": "Could not find parent folder.", "Could not find the Azure Resource Groups extension": "Could not find the Azure Resource Groups extension", "Could not find unique name for new file.": "Could not find unique name for new file.", + "Could not finish closing the connection.": "Could not finish closing the connection.", "Could not follow the DocumentDB Local container logs: {0}": "Could not follow the DocumentDB Local container logs: {0}", "Could not list the collections of \"{database}\": {reason}": "Could not list the collections of \"{database}\": {reason}", "Could not load indexes.": "Could not load indexes.", @@ -955,8 +968,13 @@ "Could not reach a server": "Could not reach a server", "Could not read collections": "Could not read collections", "Could not read databases": "Could not read databases", + "Could not read the database key from Azure.": "Could not read the database key from Azure.", "Could not save the report: {0}": "Could not save the report: {0}", "Could not show the report: {0}": "Could not show the report: {0}", + "Could not sign in again.": "Could not sign in again.", + "Could not sign in again. Open a new shell from the tree.": "Could not sign in again. Open a new shell from the tree.", + "Could not sign in again. Re-pick the playground connection from the tree.": "Could not sign in again. Re-pick the playground connection from the tree.", + "Could not verify the saved connection settings.": "Could not verify the saved connection settings.", "Counting documents in the source collection...": "Counting documents in the source collection...", "Counting source indexes…": "Counting source indexes…", "Coverage and limits": "Coverage and limits", @@ -1008,7 +1026,6 @@ "Credentials missing": "Credentials missing", "Credentials rejected by the cluster": "Credentials rejected by the cluster", "Credentials updated successfully.": "Credentials updated successfully.", - "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.": "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.", "Cursor ({0} documents)": "Cursor ({0} documents)", "Custom cloud": "Custom cloud", "Custom tag": "Custom tag", @@ -1065,8 +1082,6 @@ "Deleting this index is permanent and cannot be undone.": "Deleting this index is permanent and cannot be undone.", "Deleting...": "Deleting...", "Deleting…": "Deleting…", - "Demo Task {0}": "Demo Task {0}", - "Demo Task Configuration": "Demo Task Configuration", "Denied for a reason the check could not narrow down": "Denied for a reason the check could not narrow down", "Dependency failed": "Dependency failed", "Dependency skipped": "Dependency skipped", @@ -1104,14 +1119,21 @@ "Disable TLS/SSL (Not recommended)": "Disable TLS/SSL (Not recommended)", "Disable TLS/SSL checks when connecting.": "Disable TLS/SSL checks when connecting.", "Disabled": "Disabled", + "Discard changes": "Discard changes", "Discard the pasted input.": "Discard the pasted input.", + "Discard unsaved document changes?": "Discard unsaved document changes?", "Disconnect and connect this playground to a different database?": "Disconnect and connect this playground to a different database?", + "Disconnect and update": "Disconnect and update", + "disconnect this connection": "disconnect this connection", + "Disconnect?": "Disconnect?", "Disconnected": "Disconnected", + "Disconnected. Reconnect from the tree, then run your command again.": "Disconnected. Reconnect from the tree, then run your command again.", "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.": "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.", "Discovery Plugins: {0}": "Discovery Plugins: {0}", "Discovery view": "Discovery view", "DiskANN": "DiskANN", "Dismiss": "Dismiss", + "Dismiss notice": "Dismiss notice", "Dissatisfied": "Dissatisfied", "DNS connection options invalid": "DNS connection options invalid", "DNS lookup temporarily failed": "DNS lookup temporarily failed", @@ -1417,7 +1439,6 @@ "Failed to initialize task": "Failed to initialize task", "Failed to initialize the DocumentDB survey: {0}": "Failed to initialize the DocumentDB survey: {0}", "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.": "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.", - "Failed to list databases for \"{cluster}\": {error}": "Failed to list databases for \"{cluster}\": {error}", "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.": "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.", "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.": "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.", "Failed to list services": "Failed to list services", @@ -1437,6 +1458,7 @@ "Failed to load the Kubernetes client library: {0}. Try reloading the window; if the problem persists, reinstall the extension.": "Failed to load the Kubernetes client library: {0}. Try reloading the window; if the problem persists, reinstall the extension.", "Failed to load this kubeconfig source: {0}": "Failed to load this kubeconfig source: {0}", "Failed to modify index: {error}": "Failed to modify index: {error}", + "Failed to obtain a Microsoft Entra ID token.": "Failed to obtain a Microsoft Entra ID token.", "Failed to obtain Entra ID token.": "Failed to obtain Entra ID token.", "Failed to open Collection View: {0}": "Failed to open Collection View: {0}", "Failed to open Connection Diagnostics.": "Failed to open Connection Diagnostics.", @@ -1465,7 +1487,6 @@ "Failed to rename connection: connection not found in storage.": "Failed to rename connection: connection not found in storage.", "Failed to rename the connection.": "Failed to rename the connection.", "Failed to retrieve Azure accounts: {0}": "Failed to retrieve Azure accounts: {0}", - "Failed to reuse the active connection for \"{cluster}\": {error}": "Failed to reuse the active connection for \"{cluster}\": {error}", "Failed to save credentials for \"{cluster}\".": "Failed to save credentials for \"{cluster}\".", "Failed to save credentials: {0}": "Failed to save credentials: {0}", "Failed to save credentials: connection not found in storage.": "Failed to save credentials: connection not found in storage.", @@ -1725,6 +1746,7 @@ "Invalid conflict resolution strategy selected.": "Invalid conflict resolution strategy selected.", "Invalid connection string format. It should start with \"mongodb://\" or \"mongodb+srv://\".": "Invalid connection string format. It should start with \"mongodb://\" or \"mongodb+srv://\".", "Invalid Connection String: {error}": "Invalid Connection String: {error}", + "Invalid connection string.": "Invalid connection string.", "Invalid connection type selected.": "Invalid connection type selected.", "Invalid filter syntax: {0}. Please use valid JSON or a DocumentDB API expression, for example: { name: \"value\" }": "Invalid filter syntax: {0}. Please use valid JSON or a DocumentDB API expression, for example: { name: \"value\" }", "Invalid folder type.": "Invalid folder type.", @@ -1760,6 +1782,7 @@ "JSON results view: Read-only display of query results in JSON format": "JSON results view: Read-only display of query results in JSON format", "JSON View": "JSON View", "Keep one tls option with the value required by your cluster.": "Keep one tls option with the value required by your cluster.", + "Keep open": "Keep open", "Keep the existing data": "Keep the existing data", "Keep validation on": "Keep validation on", "Keep-alive timeout exceeded": "Keep-alive timeout exceeded", @@ -1926,6 +1949,11 @@ "Microsoft Entra ID sign-in appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this.": "Microsoft Entra ID sign-in appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this.", "Microsoft Entra ID sign-in failed": "Microsoft Entra ID sign-in failed", "Microsoft Entra ID sign-in for Azure DocumentDB appears to require Microsoft to preauthorize VS Code. 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}": "Microsoft Entra ID sign-in for Azure DocumentDB appears to require Microsoft to preauthorize VS Code. 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}", + "Microsoft sign-in is required for this connection. Sign in again to continue.": "Microsoft sign-in is required for this connection. Sign in again to continue.", + "Microsoft sign-in is required for this playground. Re-pick its connection from the tree.": "Microsoft sign-in is required for this playground. Re-pick its connection from the tree.", + "Microsoft sign-in is required for this playground. Sign in again to continue.": "Microsoft sign-in is required for this playground. Sign in again to continue.", + "Microsoft sign-in is required for this shell. Open a new shell from the tree.": "Microsoft sign-in is required for this shell. Open a new shell from the tree.", + "Microsoft sign-in is required for this shell. Sign in again to continue.": "Microsoft sign-in is required for this shell. Sign in again to continue.", "Migration Providers: {0}": "Migration Providers: {0}", "Mode: {0}": "Mode: {0}", "Moderate efficiency ratio": "Moderate efficiency ratio", @@ -2030,9 +2058,8 @@ "No copyable indexes are selected.": "No copyable indexes are selected.", "No credentials found for cluster \"{0}\"": "No credentials found for cluster \"{0}\"", "No credentials found for cluster {0}": "No credentials found for cluster {0}", - "No credentials found for id {clusterId}": "No credentials found for id {clusterId}", - "No credentials found for the query playground connection.": "No credentials found for the query playground connection.", "No credentials found for the selected cluster.": "No credentials found for the selected cluster.", + "No credentials found.": "No credentials found.", "No databases in this cluster": "No databases in this cluster", "No databases visible": "No databases visible", "No diagnostic timeouts": "No diagnostic timeouts", @@ -2103,6 +2130,7 @@ "No tenants selected. Tenant filtering disabled (all tenants will be shown).": "No tenants selected. Tenant filtering disabled (all tenants will be shown).", "No tenants were returned for the available Azure accounts.": "No tenants were returned for the available Azure accounts.", "no token was returned": "no token was returned", + "No verified Microsoft Entra ID connection is available to sign in again.": "No verified Microsoft Entra ID connection is available to sign in again.", "No, only copy documents": "No, only copy documents", "node-routed": "node-routed", "Node.js: {0}": "Node.js: {0}", @@ -2199,8 +2227,8 @@ "Open setting: {0}": "Open setting: {0}", "Open settings to change the default behavior.": "Open settings to change the default behavior.", "Open setup": "Open setup", - "Open shell": "Open shell", "Open Shell": "Open Shell", + "Open shell without authentication": "Open shell without authentication", "Open the VS Code Marketplace to learn more about \"{0}\"": "Open the VS Code Marketplace to learn more about \"{0}\"", "Open this query in Collection View": "Open this query in Collection View", "Open this query in Interactive Shell": "Open this query in Interactive Shell", @@ -2354,7 +2382,6 @@ "Private Key": "Private Key", "Probe": "Probe", "Process exited: \"{command}\"": "Process exited: \"{command}\"", - "Processing step {0} of {1}": "Processing step {0} of {1}", "Product quantization": "Product quantization", "Product quantization compresses vectors to support higher dimensions on DiskANN indexes.": "Product quantization compresses vectors to support higher dimensions on DiskANN indexes.", "Product quantization is only available for DiskANN indexes.": "Product quantization is only available for DiskANN indexes.", @@ -2441,6 +2468,7 @@ "Recommendation: Modify Index": "Recommendation: Modify Index", "Recommended": "Recommended", "Recommended Index": "Recommended Index", + "Reconnect": "Reconnect", "Reconnect now with the updated credentials": "Reconnect now with the updated credentials", "Reconnecting...": "Reconnecting...", "Recovery command copied.": "Recovery command copied.", @@ -2479,6 +2507,7 @@ "Remove $** from the parent path. It is added automatically.": "Remove $** from the parent path. It is added automatically.", "Remove field": "Remove field", "Remove kubeconfig source \"{0}\"?": "Remove kubeconfig source \"{0}\"?", + "Remove the connection?": "Remove the connection?", "Remove the DOCUMENTDB_DISABLE_SRV_FALLBACK environment variable, restart VS Code, then run the diagnosis again.": "Remove the DOCUMENTDB_DISABLE_SRV_FALLBACK environment variable, restart VS Code, then run the diagnosis again.", "Remove the port. SRV records supply the server ports.": "Remove the port. SRV records supply the server ports.", "Remove the unavailable compressor from the compressors option, or put zlib first.": "Remove the unavailable compressor from the compressors option, or put zlib first.", @@ -2492,6 +2521,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.": "Repair the connection in the tree.", "Repairing…": "Repairing…", "Replaced, Start fresh": "Replaced, Start fresh", "Replica set": "Replica set", @@ -2517,6 +2547,7 @@ "Resource not found.": "Resource not found.", "Resource: {0} ({1})": "Resource: {0} ({1})", "Restarting…": "Restarting…", + "Restore \"microsoft-sovereign-cloud.environment\" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.": "Restore \"microsoft-sovereign-cloud.environment\" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.", "Restore certificate verification and configure a trusted CA and matching server host name.": "Restore certificate verification and configure a trusted CA and matching server host name.", "Result": "Result", "Result: {0}": "Result: {0}", @@ -2530,6 +2561,7 @@ "Retry loading tenants": "Retry loading tenants", "Retry setup": "Retry setup", "Retry setup…": "Retry setup…", + "Retry sign-in": "Retry sign-in", "Retry TS Plugin Setup": "Retry TS Plugin Setup", "Retry with longer timeouts": "Retry with longer timeouts", "Retry without diagnostic timeouts": "Retry without diagnostic timeouts", @@ -2572,6 +2604,7 @@ "Run the diagnosis again and enter the port the server listens on.": "Run the diagnosis again and enter the port the server listens on.", "Run the diagnosis to the end, then choose Show report for the technical details.": "Run the diagnosis to the end, then choose Show report for the technical details.", "Run the entire file ({0}+Shift+Enter)": "Run the entire file ({0}+Shift+Enter)", + "Run the query again to retry the connection.": "Run the query again to retry the connection.", "Run this block ({0}+Enter)": "Run this block ({0}+Enter)", "Running": "Running", "Running in a dev container, not on this computer": "Running in a dev container, not on this computer", @@ -2687,6 +2720,7 @@ "Service Discovery for MongoDB Atlas": "Service Discovery for MongoDB Atlas", "Service record (SRV)": "Service record (SRV)", "Service-based fallback target": "Service-based fallback target", + "Session ended": "Session ended", "Session ID is required": "Session ID is required", "sessionId is required for query optimization": "sessionId is required for query optimization", "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.": "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.", @@ -2742,10 +2776,15 @@ "Showing the first {shown} collections; {omitted} more are not listed.": "Showing the first {shown} collections; {omitted} more are not listed.", "Showing the first {shown} databases; {omitted} more are not listed.": "Showing the first {shown} databases; {omitted} more are not listed.", "Sign in": "Sign in", + "Sign in again": "Sign in again", + "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.": "Sign in from the connection tree.", "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.", "Sign in to Azure": "Sign in to Azure", + "Sign in to Azure and try Retry again.": "Sign in to Azure and try Retry again.", "Sign in to Azure in VS Code, then run the diagnosis again.": "Sign in to Azure in VS Code, then run the diagnosis again.", "Sign in to Azure to continue…": "Sign in to Azure to continue…", "Sign in to Azure to open {0}.": "Sign in to Azure to open {0}.", @@ -2767,8 +2806,10 @@ "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 restored. Run your command again.": "Sign-in restored. Run your command again.", "Sign-in set to {0}": "Sign-in set to {0}", "Sign-in succeeded, but the cluster did not accept this identity.": "Sign-in succeeded, but the cluster did not accept this identity.", "Sign-in to tenant was cancelled or failed: {0}": "Sign-in to tenant was cancelled or failed: {0}", @@ -2782,7 +2823,6 @@ "Signing out programmatically is not supported. You must sign out by selecting the account in the Accounts menu and choosing Sign Out.": "Signing out programmatically is not supported. You must sign out by selecting the account in the Accounts menu and choosing Sign Out.", "Similarity": "Similarity", "Similarity metric": "Similarity metric", - "Simulated failure at step {0} for testing purposes": "Simulated failure at step {0} for testing purposes", "Size": "Size", "Size on disk": "Size on disk", "Size: {0}": "Size: {0}", @@ -2792,8 +2832,11 @@ "Skip problematic documents and continue; issues are recorded. Good for scenarios where partial success is acceptable.": "Skip problematic documents and continue; issues are recorded. Good for scenarios where partial success is acceptable.", "skipped": "skipped", "Skipped": "Skipped", + "Skipped an Azure account because its tenants could not be listed.": "Skipped an Azure account because its tenants could not be listed.", + "Skipped an Azure tenant because its subscriptions could not be listed.": "Skipped an Azure tenant because its subscriptions could not be listed.", "Slow execution": "Slow execution", "Socket access": "Socket access", + "Some Azure accounts or tenants could not be listed, so some subscriptions may be missing.": "Some Azure accounts or tenants could not be listed, so some subscriptions may be missing.", "Some collection statistics could not be read: {reason}": "Some collection statistics could not be read: {reason}", "Some credentials need attention, so parts of your fleet may be missing from this list.": "Some credentials need attention, so parts of your fleet may be missing from this list.", "Some database statistics could not be read: {reason}": "Some database statistics could not be read: {reason}", @@ -2917,8 +2960,6 @@ "Task stopped": "Task stopped", "Task stopped during initialization": "Task stopped during initialization", "Task stopped. {0}": "Task stopped. {0}", - "Task will complete successfully": "Task will complete successfully", - "Task will fail at a random step for testing": "Task will fail at a random step for testing", "Task with ID {0} already exists": "Task with ID {0} already exists", "Task with ID {0} not found": "Task with ID {0} not found", "TCP address": "TCP address", @@ -2946,6 +2987,8 @@ "The active Docker context is unavailable. Select or repair a valid context, then check again.": "The active Docker context is unavailable. Select or repair a valid context, then check again.", "The authentication database is {0}, rather than admin or $external. This may be intentional.": "The authentication database is {0}, rather than admin or $external. This may be intentional.", "The authentication database is neither admin nor $external. This may be intentional.": "The authentication database is neither admin nor $external. This may be intentional.", + "The Azure cloud or sign-in provider changed after this connection was established. Restore \"microsoft-sovereign-cloud.environment\" to the setting used then, and try again. If it used the Azure public cloud, reset the setting.": "The Azure cloud or sign-in provider changed after this connection was established. Restore \"microsoft-sovereign-cloud.environment\" to the setting used then, and try again. If it used the Azure public cloud, reset the setting.", + "The Azure cloud or sign-in provider changed.": "The Azure cloud or sign-in provider changed.", "The Azure cloud selected for sign-in does not match the cluster cloud.": "The Azure cloud selected for sign-in does not match the cluster cloud.", "The Azure resource {0} was not found in subscription {1}. Check the link, and whether the resource still exists.": "The Azure resource {0} was not found in subscription {1}. Check the link, and whether the resource still exists.", "The Azure resource reports that in-region high availability is disabled.": "The Azure resource reports that in-region high availability is disabled.", @@ -2971,14 +3014,19 @@ "The connection already exists in the Connections view. Opening it selects and expands it there.": "The connection already exists in the Connections view. Opening it selects and expands it there.", "The connection appears in the Connections view, ready to open.": "The connection appears in the Connections view, ready to open.", "The connection attempt failed, and the diagnosis could not identify a more specific cause.": "The connection attempt failed, and the diagnosis could not identify a more specific cause.", + "The connection changed while it was opening. Try again.": "The connection changed while it was opening. Try again.", "The connection closed during the secure handshake, before a certificate arrived.": "The connection closed during the secure handshake, before a certificate arrived.", "The connection could not be prepared for diagnosis.": "The connection could not be prepared for diagnosis.", + "The connection could not be read from storage.": "The connection could not be read from storage.", "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.": "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.", "The connection details could not be read from Azure because the Azure sign-in is missing or expired. Connection diagnosis does not open sign-in.": "The connection details could not be read from Azure because the Azure sign-in is missing or expired. Connection diagnosis does not open sign-in.", "The connection details could not be read from Azure.": "The connection details could not be read from Azure.", "The connection details could not be read from MongoDB Atlas.": "The connection details could not be read from MongoDB Atlas.", "The connection details could not be read.": "The connection details could not be read.", "The connection did not finish in time. You can increase the timeout in Settings:": "The connection did not finish in time. You can increase the timeout in Settings:", + "The connection is unavailable.": "The connection is unavailable.", + "The connection is unavailable. Check the server or network, then run the script again.": "The connection is unavailable. Check the server or network, then run the script again.", + "The connection is unavailable. Check the server or network, then run your command again.": "The connection is unavailable. Check the server or network, then run your command again.", "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.": "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.", "The connection option {0} is deprecated. This does not establish that the driver ignores it.": "The connection option {0} is deprecated. This does not establish that the driver ignores it.", "The connection requests {0}, but the extension cannot use it.": "The connection requests {0}, but the extension cannot use it.", @@ -2991,7 +3039,9 @@ "The connection string will not include the password": "The connection string will not include the password", "The connection succeeded, but the database-list request returned no databases visible to this user.": "The connection succeeded, but the database-list request returned no databases visible to this user.", "The connection succeeded, but the server denied the database-list request used by the extension.": "The connection succeeded, but the server denied the database-list request used by the extension.", + "The connection update may be incomplete. Check the saved settings before reconnecting.": "The connection update may be incomplete. Check the saved settings before reconnecting.", "The connection works, but these checks need attention:": "The connection works, but these checks need attention:", + "The connections to remove changed. Refresh the tree and try again.": "The connections to remove changed. Refresh the tree and try again.", "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".": "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".", "The container engine": "The container engine", "The container engine became unavailable during setup: {0}": "The container engine became unavailable during setup: {0}", @@ -3015,6 +3065,10 @@ "The custom cloud choice is not configured. Please configure the setting `{0}.{1}`.": "The custom cloud choice is not configured. Please configure the setting `{0}.{1}`.", "The database \"{0}\" already exists in the DocumentDB cluster \"{1}\".": "The database \"{0}\" already exists in the DocumentDB cluster \"{1}\".", "The database did not sort data in memory.\n\nResults came back in the right order naturally, either from the index or because no sort was requested.": "The database did not sort data in memory.\n\nResults came back in the right order naturally, either from the index or because no sort was requested.", + "The database rejected the credentials. Choose Retry sign-in to continue.": "The database rejected the credentials. Choose Retry sign-in to continue.", + "The database rejected the credentials. Choose Retry to reload them.": "The database rejected the credentials. Choose Retry to reload them.", + "The database rejected the credentials. Choose Update credentials to continue.": "The database rejected the credentials. Choose Update credentials to continue.", + "The database rejected the key. Choose Retry to read the key from Azure again.": "The database rejected the key. Choose Retry to read the key from Azure again.", "The database retrieved your documents through a multikey index.\n\nAn index on an array field was used. Each array element creates a separate index entry, so the database examined more index keys than documents. This is expected for array indexes but adds overhead.": "The database retrieved your documents through a multikey index.\n\nAn index on an array field was used. Each array element creates a separate index entry, so the database examined more index keys than documents. This is expected for array indexes but adds overhead.", "The database retrieved your documents using a collection scan.\n\nEvery document was read sequentially because no supporting index was available. This is the slowest retrieval method for filtered queries.": "The database retrieved your documents using a collection scan.\n\nEvery document was read sequentially because no supporting index was available. This is the slowest retrieval method for filtered queries.", "The database retrieved your documents using a covered query.\n\nAll the data your query needs was already stored in the index. The database did not need to load the actual documents, making this the most efficient retrieval method.": "The database retrieved your documents using a covered query.\n\nAll the data your query needs was already stored in the index. The database did not need to load the actual documents, making this the most efficient retrieval method.", @@ -3133,6 +3187,8 @@ "The requested managed identity is not assigned to this machine.": "The requested managed identity is not assigned to this machine.", "The requested Microsoft Entra sign-in resource does not appear to be valid for this cloud. If \"documentDB.customEnvironment.ossrdbmsEndpoint\" is set, check its value with your cloud administrator. Otherwise, report this on GitHub so the extension maintainers can investigate. See {link}": "The requested Microsoft Entra sign-in resource does not appear to be valid for this cloud. If \"documentDB.customEnvironment.ossrdbmsEndpoint\" is set, check its value with your cloud administrator. Otherwise, report this on GitHub so the extension maintainers can investigate. See {link}", "The requested sign-in resource does not appear to be valid for this cloud.": "The requested sign-in resource does not appear to be valid for this cloud.", + "The saved credentials were rejected. Update them from the tree, then run the script again.": "The saved credentials were rejected. Update them from the tree, then run the script again.", + "The saved credentials were rejected. Update them from the tree, then run your command again.": "The saved credentials were rejected. Update them from the tree, then run your command again.", "The selected {0} index is not supported by Copy/Paste Indexes.": "The selected {0} index is not supported by Copy/Paste Indexes.", "The selected authentication mechanism does not match what the server offers.": "The selected authentication mechanism does not match what the server offers.", "The selected authentication method is not supported.": "The selected authentication method is not supported.", @@ -3157,6 +3213,8 @@ "The sign-in application could not be found in the selected directory.": "The sign-in application could not be found in the selected directory.", "The sign-in resource could not be determined from the cloud configuration.": "The sign-in resource could not be determined from the cloud configuration.", "The sign-in service reported an error without further details.": "The sign-in service reported an error without further details.", + "The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.": "The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.", + "The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.": "The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.", "The sign-in window reported an error without details. Check the error code shown in that window, or open Developer: Show Logs... > {authenticationLog} in VS Code. Your IT help desk can help interpret the code; if the problem persists, report it on GitHub. See {link}": "The sign-in window reported an error without details. Check the error code shown in that window, or open Developer: Show Logs... > {authenticationLog} in VS Code. Your IT help desk can help interpret the code; if the problem persists, report it on GitHub. See {link}", "The silent sign-in lookup cannot distinguish not being signed in from a consent or preauthorization failure. Open Developer: Show Logs… → {0} to check the sign-in error.": "The silent sign-in lookup cannot distinguish not being signed in from a consent or preauthorization failure. Open Developer: Show Logs… → {0} to check the sign-in error.", "The SORT stage exceeded the {0}MB memory limit.\n\n**Solutions:**\n1. Add .allowDiskUse(true) to allow disk-based sorting for large result sets\n2. Create an index matching the sort pattern: {1}\n3. Add filters to reduce the number of documents being sorted\n4. Increase server memory limit (requires server configuration)": "The SORT stage exceeded the {0}MB memory limit.\n\n**Solutions:**\n1. Add .allowDiskUse(true) to allow disk-based sorting for large result sets\n2. Create an index matching the sort pattern: {1}\n3. Add filters to reduce the number of documents being sorted\n4. Increase server memory limit (requires server configuration)", @@ -3230,10 +3288,22 @@ "This cluster is paused. Resume it in MongoDB Atlas before connecting.": "This cluster is paused. Resume it in MongoDB Atlas before connecting.", "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 changed. Refresh the tree and try again.": "This connection changed. Refresh the tree and try again.", "This connection has no connection string.": "This connection has no connection string.", + "This connection is being updated. Run the script again when the update finishes.": "This connection is being updated. Run the script again when the update finishes.", + "This connection is being updated. Run your command again when the update finishes.": "This connection is being updated. Run your command again when the update finishes.", + "This connection is disconnected. Reconnect from the tree, then run the script again.": "This connection is disconnected. Reconnect from the tree, then run the script again.", + "This connection is no longer available for that action. Refresh the tree and try again.": "This connection is no longer available for that action. Refresh the tree and try again.", + "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.": "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.", + "This connection is unavailable.": "This connection is unavailable.", + "This connection is unavailable. Reconnect from the tree, then run the script again.": "This connection is unavailable. Reconnect from the tree, then run the script again.", + "This connection is unavailable. Reconnect from the tree, then run your command again.": "This connection is unavailable. Reconnect from the tree, then run your command again.", "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:", + "This connection was removed. Choose another connection for this playground.": "This connection was removed. Choose another connection for this playground.", + "This connection was removed. Choose another connection.": "This connection was removed. Choose another connection.", + "This connection was removed. Open a shell from another connection.": "This connection was removed. Open a shell from another connection.", "This credential no longer exists": "This credential no longer exists", "This deletes the container named {0} and its data volume, then creates a new one. Everything stored in DocumentDB Local is erased.": "This deletes the container named {0} and its data volume, then creates a new one. Everything stored in DocumentDB Local is erased.", "This deletes the DocumentDB Local container and its data volume in {0}, then creates a new instance. All data in the existing instance is permanently erased.": "This deletes the DocumentDB Local container and its data volume in {0}, then creates a new instance. All data in the existing instance is permanently erased.", @@ -3274,6 +3344,8 @@ "This operation will copy all documents from the source to the target collection.": "This operation will copy all documents from the source to the target collection.", "This playground has no connection.": "This playground has no connection.", "This playground has no connection. Click to connect it to a database.": "This playground has no connection. Click to connect it to a database.", + "This playground is bound to a different Microsoft account. Re-pick its connection from the tree.": "This playground is bound to a different Microsoft account. Re-pick its connection from the tree.", + "This playground is bound to the previous connection. Re-pick its connection from the tree.": "This playground is bound to the previous connection. Re-pick its connection from the tree.", "This playground is connected to {0} / {1}.": "This playground is connected to {0} / {1}.", "This project does not contain any clusters yet.": "This project does not contain any clusters yet.", "This project does not currently contain any MongoDB Atlas clusters.": "This project does not currently contain any MongoDB Atlas clusters.", @@ -3286,8 +3358,12 @@ "This report was generated using the DocumentDB extension for Visual Studio Code.": "This report was generated using the DocumentDB extension for Visual Studio Code.", "this resource": "this resource", "This service type has no address that can be reached from the host running these checks.": "This service type has no address that can be reached from the host running these checks.", + "This shell is bound to a different Microsoft account. Open a new shell from the tree.": "This shell is bound to a different Microsoft account. Open a new shell from the tree.", + "This shell is bound to the previous connection. Open a new shell from the tree.": "This shell is bound to the previous connection. Open a new shell from the tree.", + "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.": "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.", "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 tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.": "This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.", "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.", @@ -3347,6 +3423,9 @@ "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 close the view. Try again.": "Unable to close the view. Try again.", + "Unable to complete this tree action.": "Unable to complete this tree action.", + "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.", @@ -3407,6 +3486,7 @@ "Update MongoDB Atlas connection": "Update MongoDB Atlas connection", "Update MongoDB Atlas Credentials": "Update MongoDB Atlas Credentials", "Update saved password": "Update saved password", + "update this connection": "update this connection", "Updated": "Updated", "Updated {0} minutes ago": "Updated {0} minutes ago", "Updated 1 minute ago": "Updated 1 minute ago", @@ -3509,10 +3589,12 @@ "Viewing Azure account information for: {0}": "Viewing Azure account information for: {0}", "Visible in the tree, but not connectable until the cluster returns to IDLE.": "Visible in the tree, but not connectable until the cluster returns to IDLE.", "Visit the [documentation]({0}) for more information about TLS/SSL certificates.": "Visit the [documentation]({0}) for more information about TLS/SSL certificates.", + "Visual Studio Code returned a different Microsoft account for this connection.": "Visual Studio Code returned a different Microsoft account for this connection.", "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.": "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.", "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.": "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.", "VS Code version: {0}": "VS Code version: {0}", "VS Code: v{0}": "VS Code: v{0}", + "Wait for the update to finish.": "Wait for the update to finish.", "Wait longer": "Wait longer", "Wait until the service has an external address, then run the diagnosis again.": "Wait until the service has an external address, then run the diagnosis again.", "Waiting {0}": "Waiting {0}", @@ -3565,6 +3647,7 @@ "We found a container using the DocumentDB Local name, but it very likely was not created by this extension, so we cannot open it.": "We found a container using the DocumentDB Local name, but it very likely was not created by this extension, so we cannot open it.", "We found an existing data volume after the image downloaded. Setup stopped to protect its data. Go back to Configure and try again.": "We found an existing data volume after the image downloaded. Setup stopped to protect its data. Go back to Configure and try again.", "We found an existing DocumentDB Local instance, but its saved credentials are unavailable. Without them, we cannot reopen or reuse the existing data, so you need to start fresh. Nothing has been changed yet. Starting fresh erases the existing instance and its data, then creates a new one.": "We found an existing DocumentDB Local instance, but its saved credentials are unavailable. Without them, we cannot reopen or reuse the existing data, so you need to start fresh. Nothing has been changed yet. Starting fresh erases the existing instance and its data, then creates a new one.", + "What should happen to the open tabs for this connection?": "What should happen to the open tabs for this connection?", "What should setup do with the existing data?": "What should setup do with the existing data?", "What will happen in the Set up step": "What will happen in the Set up step", "What's New": "What's New", @@ -3617,6 +3700,7 @@ "You asked us to remind you later, so here we are.": "You asked us to remind you later, so here we are.", "You can disable this confirmation by setting \"{0}\" to false.": "You can disable this confirmation by setting \"{0}\" to false.", "You can now close this tab and explore your MongoDB Atlas clusters in the Service Discovery area.": "You can now close this tab and explore your MongoDB Atlas clusters in the Service Discovery area.", + "You can only update credentials or the connection string while disconnected.": "You can only update credentials or the connection string while disconnected.", "You cancelled the diagnosis. The results so far are kept.": "You cancelled the diagnosis. The results so far are kept.", "You closed this invitation a while ago, so we are asking once more.": "You closed this invitation a while ago, so we are asking once more.", "You do not have permission to create a resource group in subscription \"{0}\".": "You do not have permission to create a resource group in subscription \"{0}\".", diff --git a/package-lock.json b/package-lock.json index 36dafe777..897404c3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.4", "license": "SEE LICENSE IN LICENSE.md", "workspaces": [ "packages/*" @@ -26,10 +26,10 @@ "@fluentui/react-components": "~9.75.1", "@fluentui/react-icons": "~2.0.345", "@kubernetes/client-node": "1.4.0", - "@microsoft/vscode-azext-azureauth": "~4.1.1", - "@microsoft/vscode-azext-azureutils": "~4.2.0", - "@microsoft/vscode-azext-utils": "~4.1.0", - "@microsoft/vscode-azureresources-api": "~2.5.0", + "@microsoft/vscode-azext-azureauth": "6.1.0-alpha.2", + "@microsoft/vscode-azext-azureutils": "~5.1.0", + "@microsoft/vscode-azext-utils": "~5.1.0", + "@microsoft/vscode-azureresources-api": "~3.1.1", "@microsoft/vscode-container-client": "^0.5.4", "@microsoft/vscode-ext-webview": "*", "@microsoft/vscode-ext-webview-fluentui": "*", @@ -1089,19 +1089,20 @@ } }, "node_modules/@azure/arm-resources-subscriptions": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@azure/arm-resources-subscriptions/-/arm-resources-subscriptions-2.1.0.tgz", - "integrity": "sha512-vKiu/3Yh84IV3IuJJ+0Fgs/ZQpvuGzoZ3dAoBksIV++Uu/Qz9RcQVz7pj+APWYIuODuR9I0eGKswZvzynzekug==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@azure/arm-resources-subscriptions/-/arm-resources-subscriptions-3.0.0.tgz", + "integrity": "sha512-Uu3i3HZ3nv69tVeNaXTr7KZ2qtcrJQiLvhREnZ0p5xNrV8Pmtrnx1o8A+z2T+OVQZlnySU5nPT4O4gJIJbfA5A==", "license": "MIT", "dependencies": { - "@azure/core-auth": "^1.3.0", - "@azure/core-client": "^1.7.0", - "@azure/core-paging": "^1.2.0", - "@azure/core-rest-pipeline": "^1.8.0", - "tslib": "^2.2.0" + "@azure-rest/core-client": "^2.3.1", + "@azure/core-auth": "^1.9.0", + "@azure/core-rest-pipeline": "^1.20.0", + "@azure/core-util": "^1.12.0", + "@azure/logger": "^1.2.0", + "tslib": "^2.8.1" }, "engines": { - "node": ">=14.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/arm-storage": { @@ -4850,53 +4851,38 @@ "license": "MIT" }, "node_modules/@microsoft/1ds-core-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/1ds-core-js/-/1ds-core-js-4.4.1.tgz", - "integrity": "sha512-utqwacfUkiGJROn4WC7aNdRBsRxwhNWXuqaJM2B0N0WHmv1+IhSuI7RQ3FHwxRP1dxZi/xn9aELMZ7HMStsW1w==", + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/1ds-core-js/-/1ds-core-js-4.4.6.tgz", + "integrity": "sha512-u19bMRL3XvxMYL8PcJZz/ADOSDBSBYrzrtZoEvIxKaA9+nxSygu7suos/RIPdmNTBkqLJmANHzITZFX/2P9bkA==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" } }, "node_modules/@microsoft/1ds-post-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/1ds-post-js/-/1ds-post-js-4.4.1.tgz", - "integrity": "sha512-CkFEhDY7X8E2JLr6HsEvRiC0DaLOCsA7vlbq/9DJP65gAumgw2NnFNIAOg6Je5Geq1LDu76/nb2hP34p8eGggw==", + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/1ds-post-js/-/1ds-post-js-4.4.6.tgz", + "integrity": "sha512-B8XMrquo1l1JQBSd7ft4r1dKPfOj4I0JoU2kMqlKtZJh/y4TYcR4CuNDZ1jnyx2q8rLj4ikivBTxgAUuQd/UJw==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", - "@microsoft/applicationinsights-shims": "3.0.1", - "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" - } - }, - "node_modules/@microsoft/applicationinsights-channel-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-3.4.2.tgz", - "integrity": "sha512-Q7Q9gV45WSgSmOP2abu0y9tdbFh8sPELMgKUCDy62FsNd3xmE8X3zLtkzc7mcXPlpTeoDXwMCYjCRIAYd6d2lQ==", - "license": "MIT", - "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.2", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", "@nevware21/ts-utils": ">= 0.14.0 < 2.x" - }, - "peerDependencies": { - "tslib": ">= 1.0.0" } }, - "node_modules/@microsoft/applicationinsights-channel-js/node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.2.tgz", - "integrity": "sha512-Iw3gq1JREKLbXiVpr3F0+Ezuzphe+o25n9me9H5Kkjmck6tIkuGQea01SNfeemE4wf2mop2QQSvTcKxT8tNN1g==", + "node_modules/@microsoft/applicationinsights-channel-js": { + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-3.4.6.tgz", + "integrity": "sha512-cDCDsQqvd6/4bp5X4f/IRDmiBRaHEcLxFefVkqb9nUPslXeA62NXloGBXK4CtRfN43ULg3R7NM/atY4TkzC3iw==", "license": "MIT", "dependencies": { + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", @@ -4907,30 +4893,30 @@ } }, "node_modules/@microsoft/applicationinsights-common": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.1.tgz", - "integrity": "sha512-CTbD0g/68tiv2yCItsodDQBYxyHdfQkG7VhvVU8OHenukpl/7W4wEuxZuOntqhv5m9Nx/DFncbz+T83nvYTG3g==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.6.tgz", + "integrity": "sha512-X/5fPRv3FevJZXqRDr9hERM3BhplbnAqyGKv2R2xHO/EJy5V/5R/2r2anItTXaOnWIGHv5Bj2cSsjnvOdWrJsw==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" } }, "node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.1.tgz", - "integrity": "sha512-eXIHZ1+nvBiJgVpufBiTP801Vtr5FEwjWZioUsb44NC/z/UcsZh2MDJ1mBpjaDO73LVYUw/ZZmDCCo6Pg/61kA==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.6.tgz", + "integrity": "sha512-YPvGUCgcpQa0MkUnJAcWi/SPDBabAohXSoa85c/GDkFiXWPsjihN8RcVj43r5I6nY4Y3+gHRvGVT6hBPTumKJg==", "license": "MIT", "dependencies": { "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" @@ -4946,28 +4932,13 @@ } }, "node_modules/@microsoft/applicationinsights-web-basic": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-3.4.2.tgz", - "integrity": "sha512-ONJbCSdJ/KMOVT7b8oVVPa2Etp99SHhehprpQn51QrHTiJtTehBLOmovBBIKQZuwWm0ZLKOaoUBWHCkRXUqNAw==", - "license": "MIT", - "dependencies": { - "@microsoft/applicationinsights-channel-js": "3.4.2", - "@microsoft/applicationinsights-core-js": "3.4.2", - "@microsoft/applicationinsights-shims": "3.0.1", - "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", - "@nevware21/ts-utils": ">= 0.14.0 < 2.x" - }, - "peerDependencies": { - "tslib": ">= 1.0.0" - } - }, - "node_modules/@microsoft/applicationinsights-web-basic/node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.2.tgz", - "integrity": "sha512-Iw3gq1JREKLbXiVpr3F0+Ezuzphe+o25n9me9H5Kkjmck6tIkuGQea01SNfeemE4wf2mop2QQSvTcKxT8tNN1g==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-3.4.6.tgz", + "integrity": "sha512-T3CX9EwHPbI95I5CQ1aVRRRRynxtKVejW4if5EvGB6QaShcOOK56xnJ7Yn9Bb39YHkYqstQ7tMfxDDuO782XXg==", "license": "MIT", "dependencies": { + "@microsoft/applicationinsights-channel-js": "3.4.6", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", @@ -4987,21 +4958,25 @@ } }, "node_modules/@microsoft/vscode-azext-azureauth": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-4.1.1.tgz", - "integrity": "sha512-ZHRoNBBwZBg8sqZ7/C+VMQOp7zusJxIpXzLlRpWGjrDI8PSFQk2bZloVdW877YeSLMe2464mjTlWMhEEa07Kaw==", + "version": "6.1.0-alpha.2", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-6.1.0-alpha.2.tgz", + "integrity": "sha512-hiEpLpNe/TiV1Cvx5gcgTxybfI1sYIRjKJ361bZyDOz3CchLjbupKiEi1jqyonMq5MvWftVlENBnvk3vq8AT0w==", "license": "MIT", "dependencies": { - "@azure/arm-resources-subscriptions": "^2.1.0", - "@azure/core-client": "^1.9.2", - "@azure/core-rest-pipeline": "^1.16.0", + "@azure/arm-resources-subscriptions": "^3.0.0-beta.1", + "@azure/core-auth": "^1.10.1", + "@azure/core-rest-pipeline": "^1.23.0", + "@azure/identity": "^4.13.1", "@azure/ms-rest-azure-env": "^2.0.0" + }, + "engines": { + "vscode": "^1.106.0" } }, "node_modules/@microsoft/vscode-azext-azureutils": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureutils/-/vscode-azext-azureutils-4.2.0.tgz", - "integrity": "sha512-j/YzGI0uRzQjCM+jr9YyLxnJRHl2H9WQCw9Dlw7DhztV4ED3NCoIuG6k6jjKmSS3c5cTF/lqmPaVZ4SxZUssvA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureutils/-/vscode-azext-azureutils-5.1.0.tgz", + "integrity": "sha512-Jm2hEEMBcTocq8AZ4sVO7vqNI3Sg0Wu4lvsTR4Oqp972d126ufcIZ7FVzU726BwkM2/BiA2NdUwJQhfNY61lGg==", "license": "MIT", "dependencies": { "@azure/arm-authorization": "^9.0.0", @@ -5009,14 +4984,14 @@ "@azure/arm-msi": "^2.2.0", "@azure/arm-resources": "^5.0.0", "@azure/arm-resources-profile-2020-09-01-hybrid": "^2.1.0", - "@azure/arm-resources-subscriptions": "^2.1.0", + "@azure/arm-resources-subscriptions": "^3.0.0-beta.1", "@azure/arm-storage": "^18.6.0", "@azure/arm-storage-profile-2020-09-01-hybrid": "^2.1.0", "@azure/core-client": "^1.10.1", "@azure/core-rest-pipeline": "^1.23.0", "@azure/logger": "^1.3.0", - "@microsoft/vscode-azext-azureauth": "^6.0.0-alpha.6", - "@microsoft/vscode-azext-utils": "^4.0.4", + "@microsoft/vscode-azext-azureauth": "^6.1.0-alpha.2", + "@microsoft/vscode-azext-utils": "^5.0.0", "@microsoft/vscode-azureresources-api": "^3.1.0", "semver": "^7.7.4" }, @@ -5057,53 +5032,24 @@ "node": ">=14.0.0" } }, - "node_modules/@microsoft/vscode-azext-azureutils/node_modules/@microsoft/vscode-azext-azureauth": { - "version": "6.0.0-alpha.8", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-6.0.0-alpha.8.tgz", - "integrity": "sha512-oOZpeTe4tOupKzQpeKxyHOSG10Bxsyp8YhCeyadQMsz1wICR/JZEdSMKPR0GnXpXYlYSsEDFbSzJWqZUZ/3+Yw==", - "license": "MIT", - "dependencies": { - "@azure/arm-resources-subscriptions": "^2.1.0", - "@azure/core-rest-pipeline": "^1.22.2", - "@azure/identity": "^4.13.0", - "@azure/ms-rest-azure-env": "^2.0.0" - }, - "engines": { - "vscode": "^1.106.0" - } - }, - "node_modules/@microsoft/vscode-azext-azureutils/node_modules/@microsoft/vscode-azureresources-api": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.0.tgz", - "integrity": "sha512-jcx5VdDiOftjkjQ+ZXuGQ7xpy7WSKnB7oRLdmGuW3ykaB/PrBSHwStkItSg8l8ycJ0t1kaPOz3eDJP0Ol309jg==", - "license": "MIT", - "engines": { - "vscode": "^1.105.0" - }, - "peerDependencies": { - "@azure/ms-rest-azure-env": "^2.0.0" - } - }, "node_modules/@microsoft/vscode-azext-utils": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-utils/-/vscode-azext-utils-4.1.0.tgz", - "integrity": "sha512-00/wz3n2W6xNFZK4ur2lGjTqX8RhSrbAIoNwhMreOKk2n6gOpY389XO20oHu77uBxjgoqMTAL5R+SWcMeqD0Gg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-utils/-/vscode-azext-utils-5.1.0.tgz", + "integrity": "sha512-Bmzz2p6vw0kk7lUJhY0wXb8iFc9jXe/etiV9h0vbI+2crMbMg0Vo7TvZTXTNbX2bqOtEvh2Cv4UhMUkuxn9NSg==", "license": "MIT", "dependencies": { - "@microsoft/vscode-azureresources-api": "^3.1.0", - "@microsoft/vscode-processutils": "^0.2.1", + "@microsoft/vscode-azureresources-api": "^3.1.1", + "@microsoft/vscode-processutils": "^1.0.0", "@vscode/extension-telemetry": "^1.5.2", "dayjs": "^1.11.19", - "html-to-text": "^9.0.5", - "semver": "^7.7.4", - "vscode-tas-client": "^0.1.84" + "semver": "^7.7.4" }, "engines": { "vscode": "^1.105.0" }, "peerDependencies": { "@azure/ms-rest-azure-env": "^2.0.0", - "@github/copilot-sdk": "0.1.32" + "@github/copilot-sdk": "^1.0.14" }, "peerDependenciesMeta": { "@github/copilot-sdk": { @@ -5111,23 +5057,42 @@ } } }, - "node_modules/@microsoft/vscode-azext-utils/node_modules/@microsoft/vscode-azureresources-api": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.0.tgz", - "integrity": "sha512-jcx5VdDiOftjkjQ+ZXuGQ7xpy7WSKnB7oRLdmGuW3ykaB/PrBSHwStkItSg8l8ycJ0t1kaPOz3eDJP0Ol309jg==", + "node_modules/@microsoft/vscode-azext-utils/node_modules/@microsoft/vscode-processutils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-processutils/-/vscode-processutils-1.0.0.tgz", + "integrity": "sha512-vAX1YRqQFb7PJgljQORY8gYJTDymVxh2hXnQaJYoVIb8uostOlin5Dpa9n9ZUkQbSw/K9FlxVR5GQtT3Uedzew==", "license": "MIT", + "dependencies": { + "tree-kill": "^1.2.2", + "which": "^5.0.0" + }, "engines": { - "vscode": "^1.105.0" + "node": ">=22" + } + }, + "node_modules/@microsoft/vscode-azext-utils/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" }, - "peerDependencies": { - "@azure/ms-rest-azure-env": "^2.0.0" + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/@microsoft/vscode-azureresources-api": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-2.5.1.tgz", - "integrity": "sha512-CUlDVsau6RJA8F1IENnfA3N0XqyGQz/VJgh9QLnWjRkiBjW8/VSUpxNab6qflnN9SS38EHGv81v/92kEkoOQKQ==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.1.tgz", + "integrity": "sha512-koV1+XvWSzA+pOc1g17Kbw9Gm26SIvg+j5puT5vB/T9vNiE2oeAlxlAatfZOT3tRHN1qGqPLl90HHs5mQAPkew==", "license": "MIT", + "engines": { + "vscode": "^1.105.0" + }, "peerDependencies": { "@azure/ms-rest-azure-env": "^2.0.0" } @@ -5161,15 +5126,6 @@ "which": "^5.0.0" } }, - "node_modules/@microsoft/vscode-processutils/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/@microsoft/vscode-processutils/node_modules/which": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", @@ -5597,9 +5553,9 @@ } }, "node_modules/@nevware21/ts-utils": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.14.0.tgz", - "integrity": "sha512-WoeqTIXQ8WPhl+lD2NbMHoAQ4sJl0n7EoRoDmVJui//Usg512enl9q1fdbVobuZt3omnxnmVsDrNIvPBvFgddQ==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.16.0.tgz", + "integrity": "sha512-DDln15VUBSw5JjJlNno1UCSzgAGzHHklm7u695jXDCzwSn7W2F7B2VYHwLLcT1cOWQQBQAJK6e2/Y8oTG+W0Ig==", "funding": [ { "type": "github", @@ -6437,19 +6393,6 @@ "node": ">=20.0.0" } }, - "node_modules/@selderee/plugin-htmlparser2": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz", - "integrity": "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==", - "license": "MIT", - "dependencies": { - "domhandler": "^5.0.3", - "selderee": "^0.11.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/@smithy/config-resolver": { "version": "4.4.17", "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.4.17.tgz", @@ -9590,15 +9533,6 @@ "dev": true, "license": "MIT" }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/deepmerge-json": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/deepmerge-json/-/deepmerge-json-1.5.0.tgz", @@ -9785,6 +9719,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, "license": "MIT", "dependencies": { "domelementtype": "^2.3.0", @@ -9799,6 +9734,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, "funding": [ { "type": "github", @@ -9811,6 +9747,7 @@ "version": "5.0.3", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, "license": "BSD-2-Clause", "dependencies": { "domelementtype": "^2.3.0" @@ -9826,6 +9763,7 @@ "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, "license": "BSD-2-Clause", "dependencies": { "dom-serializer": "^2.0.0", @@ -9955,6 +9893,7 @@ "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=0.12" @@ -11832,41 +11771,6 @@ "node": ">=18" } }, - "node_modules/html-to-text": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz", - "integrity": "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==", - "license": "MIT", - "dependencies": { - "@selderee/plugin-htmlparser2": "^0.11.0", - "deepmerge": "^4.3.1", - "dom-serializer": "^2.0.0", - "htmlparser2": "^8.0.2", - "selderee": "^0.11.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/html-to-text/node_modules/htmlparser2": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", - "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "node_modules/html-url-attributes": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", @@ -12655,6 +12559,15 @@ "dev": true, "license": "MIT" }, + "node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/isnumber": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isnumber/-/isnumber-1.0.0.tgz", @@ -13060,15 +12973,6 @@ "node": ">=0.10" } }, - "node_modules/leac": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/leac/-/leac-0.6.0.tgz", - "integrity": "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==", - "license": "MIT", - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/leven": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", @@ -15321,19 +15225,6 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, - "node_modules/parseley": { - "version": "0.12.1", - "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz", - "integrity": "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==", - "license": "MIT", - "dependencies": { - "leac": "^0.6.0", - "peberminta": "^0.9.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -15417,15 +15308,6 @@ "dev": true, "license": "MIT" }, - "node_modules/peberminta": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz", - "integrity": "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==", - "license": "MIT", - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -16525,18 +16407,6 @@ "node": ">=20.0.0" } }, - "node_modules/selderee": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz", - "integrity": "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==", - "license": "MIT", - "dependencies": { - "parseley": "^0.12.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/semaphore": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/semaphore/-/semaphore-1.1.0.tgz", @@ -17486,15 +17356,6 @@ "streamx": "^2.15.0" } }, - "node_modules/tas-client": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/tas-client/-/tas-client-0.3.2.tgz", - "integrity": "sha512-Hr0k7swJSyI7fsgqWf28GoME3lDXysTV1pJW/OBCrokhkqd3dTL+79SLKRGaYNHNaHii5N7VLRlZZc/up6xdAA==", - "license": "MIT", - "engines": { - "node": ">=22" - } - }, "node_modules/teex": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", @@ -18698,18 +18559,6 @@ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", "license": "MIT" }, - "node_modules/vscode-tas-client": { - "version": "0.1.86", - "resolved": "https://registry.npmjs.org/vscode-tas-client/-/vscode-tas-client-0.1.86.tgz", - "integrity": "sha512-4P3zjGXTKXknbWOd6EDnD3lWZuc/aFrW8Ixzk0B8gQDBq2BXuKg0NwsZiFeAzBohAxCcsRA4gQipH57Bxf6XXg==", - "license": "MIT", - "dependencies": { - "tas-client": "^0.3.2" - }, - "engines": { - "vscode": "^1.85.0" - } - }, "node_modules/vscode-uri": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", diff --git a/package.json b/package.json index e030e927d..fdca8c040 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.4", "releaseNotesUrl": "https://github.com/microsoft/vscode-documentdb/discussions/1089", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "publisher": "ms-azuretools", @@ -168,10 +168,10 @@ "@fluentui/react-components": "~9.75.1", "@fluentui/react-icons": "~2.0.345", "@kubernetes/client-node": "1.4.0", - "@microsoft/vscode-azext-azureauth": "~4.1.1", - "@microsoft/vscode-azext-azureutils": "~4.2.0", - "@microsoft/vscode-azext-utils": "~4.1.0", - "@microsoft/vscode-azureresources-api": "~2.5.0", + "@microsoft/vscode-azext-azureauth": "6.1.0-alpha.2", + "@microsoft/vscode-azext-azureutils": "~5.1.0", + "@microsoft/vscode-azext-utils": "~5.1.0", + "@microsoft/vscode-azureresources-api": "~3.1.1", "@microsoft/vscode-container-client": "^0.5.4", "@microsoft/vscode-ext-webview": "*", "@microsoft/vscode-ext-webview-fluentui": "*", @@ -354,15 +354,23 @@ "commands": [ { "command": "vscode-documentdb.debug.survey.showInvitation", - "title": "_DocumentDB: Survey: Show Invitation" + "title": "_DocumentDB: Developer: Survey: Show Invitation" }, { "command": "vscode-documentdb.debug.survey.simulateMilestone", - "title": "_DocumentDB: Survey: Simulate Milestone" + "title": "_DocumentDB: Developer: Survey: Simulate Milestone" }, { "command": "vscode-documentdb.debug.survey.resetState", - "title": "_DocumentDB: Survey: Reset State" + "title": "_DocumentDB: Developer: Survey: Reset State" + }, + { + "command": "vscode-documentdb.command.clearSchemaCache", + "title": "_DocumentDB: Developer: Clear Schema Cache" + }, + { + "command": "vscode-documentdb.command.showSchemaStoreStats", + "title": "_DocumentDB: Developer: Show Schema Store Stats" }, { "category": "DocumentDB", @@ -524,12 +532,6 @@ "title": "Refresh", "icon": "$(refresh)" }, - { - "//": "[Testing] Start Demo Task", - "category": "DocumentDB", - "command": "vscode-documentdb.command.testing.startDemoTask", - "title": "Start Demo Task" - }, { "//": "[DiscoveryView] Show Hidden Provider", "category": "DocumentDB", @@ -603,6 +605,11 @@ "command": "vscode-documentdb.command.diagnoseConnection", "title": "Diagnose Connection…" }, + { + "category": "DocumentDB", + "command": "vscode-documentdb.command.disconnect", + "title": "%connections.disconnect%" + }, { "//": "[DiscoveryView] Rename Kubernetes kubeconfig source", "category": "DocumentDB", @@ -798,10 +805,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" @@ -959,22 +962,16 @@ "title": "Copy Reference…" }, { - "//": "[Diagnostics] Clear Schema Cache", - "category": "DocumentDB", - "command": "vscode-documentdb.command.clearSchemaCache", - "title": "Clear Schema Cache" - }, - { - "//": "[Diagnostics] Show Schema Store Stats", - "category": "DocumentDB", - "command": "vscode-documentdb.command.showSchemaStoreStats", - "title": "Show Schema Store Stats" + "//": "[Diagnostics] Show Connection Client Sessions", + "category": "DocumentDB Developer", + "command": "vscode-documentdb.command.showConnectionStats", + "title": "%diagnostics.showConnectionStats%" }, { - "//": "[Diagnostics] Show Worker Stats", - "category": "DocumentDB", + "//": "[Diagnostics] Show Shell and Playground Sessions", + "category": "DocumentDB Developer", "command": "vscode-documentdb.command.showWorkerStats", - "title": "Show Worker Stats" + "title": "Show Shell and Playground Sessions" } ], "menus": { @@ -1080,11 +1077,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", @@ -1120,11 +1112,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", @@ -1441,6 +1428,11 @@ "when": "view =~ /connectionsView|discoveryView|azure(ResourceGroups|FocusView)/ && viewItem =~ /\\btreeitem_documentdbcluster\\b/i && !listMultiSelection", "group": "2@2" }, + { + "command": "vscode-documentdb.command.disconnect", + "when": "view =~ /connectionsView|discoveryView|azure(ResourceGroups|FocusView)/ && viewItem =~ /\\btreeitem_documentdbcluster\\b/i && viewItem =~ /\\bconnected\\b/ && !listMultiSelection", + "group": "2@3" + }, { "//": "[Account] Open Interactive Shell", "command": "vscode-documentdb.command.shell.open", @@ -1666,6 +1658,10 @@ ], "explorer/context": [], "commandPalette": [ + { + "command": "vscode-documentdb.command.disconnect", + "when": "false" + }, { "command": "vscode-documentdb.debug.survey.showInvitation", "when": "documentdb-development-mode" @@ -1678,6 +1674,14 @@ "command": "vscode-documentdb.debug.survey.resetState", "when": "documentdb-development-mode" }, + { + "command": "vscode-documentdb.command.clearSchemaCache", + "when": "documentdb-development-mode" + }, + { + "command": "vscode-documentdb.command.showSchemaStoreStats", + "when": "documentdb-development-mode" + }, { "command": "vscode-documentdb.command.giveFeedback", "when": "config.telemetry.feedback.enabled" @@ -1714,10 +1718,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" @@ -2160,6 +2160,22 @@ } }, "additionalProperties": false + }, + "documentDB.connections.openTabsOnDisconnect": { + "order": 6, + "type": "string", + "default": "ask", + "description": "Choose what happens to open tabs when you disconnect or remove a connection. Closing tabs with unsaved document changes always requires confirmation.", + "enum": [ + "ask", + "closeAll", + "keepOpenDisabled" + ], + "enumDescriptions": [ + "Ask whether to close or keep open tabs.", + "Close all tabs for the connection.", + "Keep tabs open but disable database operations." + ] } } }, diff --git a/package.nls.json b/package.nls.json index 000ac6cf7..0ec099292 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +1,6 @@ { + "connections.disconnect": "Disconnect", + "diagnostics.showConnectionStats": "Show Connection Client Sessions", "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", "survey.giveFeedbackTitle": "Give Feedback", diff --git a/src/commands/connections-view/deleteFolder/ExecuteStep.ts b/src/commands/connections-view/deleteFolder/ExecuteStep.ts index 3e40393a8..81dd41589 100644 --- a/src/commands/connections-view/deleteFolder/ExecuteStep.ts +++ b/src/commands/connections-view/deleteFolder/ExecuteStep.ts @@ -4,12 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import { AzureWizardExecuteStep } from '@microsoft/vscode-azext-utils'; +import { withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ext } from '../../../extensionVariables'; import { ConnectionStorageService, ItemType } from '../../../services/connectionStorageService'; import { refreshParentInConnectionsView, withConnectionsViewProgress, } from '../../../tree/connections-view/connectionsViewHelpers'; +import { enumerateConnectionsInFolder } from '../verificationUtils'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; /** @@ -28,18 +30,20 @@ export class ExecuteStep extends AzureWizardExecuteStep { - await ext.state.showDeleting(context.folderItem.id, async () => { - // Recursively delete all descendants - await this.deleteRecursive(context, context.folderItem.storageId); - - // Delete the folder itself (count as 1 more folder) - await ConnectionStorageService.delete(context.connectionType, context.folderItem.storageId); - context.deletedFolders++; + const ids = await enumerateConnectionsInFolder(context.folderItem.storageId, context.connectionType); + try { + await withConnectionRemoval(ids, async (removeConnection) => { + await withConnectionsViewProgress(async () => { + await ext.state.showDeleting(context.folderItem.id, async () => { + await this.deleteRecursive(context, context.folderItem.storageId, removeConnection); + await ConnectionStorageService.delete(context.connectionType, context.folderItem.storageId); + context.deletedFolders++; + }); + }); }); - + } finally { refreshParentInConnectionsView(context.folderItem.id); - }); + } // Record telemetry measurements context.telemetry.measurements.deletedFolders = context.deletedFolders; @@ -52,19 +56,25 @@ export class ExecuteStep extends AzureWizardExecuteStep { + private async deleteRecursive( + context: DeleteFolderWizardContext, + parentId: string, + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ): Promise { const children = await ConnectionStorageService.getChildren(parentId, context.connectionType); for (const child of children) { // Recursively delete child folders first if (child.properties.type === ItemType.Folder) { - await this.deleteRecursive(context, child.id); + await this.deleteRecursive(context, child.id, removeConnection); + await ConnectionStorageService.delete(context.connectionType, child.id); context.deletedFolders++; } else { + await removeConnection(child.id, () => + ConnectionStorageService.delete(context.connectionType, child.id), + ); context.deletedConnections++; } - // Delete the child item - await ConnectionStorageService.delete(context.connectionType, child.id); } } diff --git a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts index c0db46f67..b4d95aa38 100644 --- a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts +++ b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts @@ -59,11 +59,18 @@ vi.mock('../verificationUtils', async () => ({ })); import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { type withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ConnectionType, ItemType, type ConnectionItem } from '../../../services/connectionStorageService'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; import { ExecuteStep } from './ExecuteStep'; import { VerifyNoConflictsStep } from './VerifyNoConflictsStep'; +vi.mock('../../../documentdb/connectionTeardown', () => ({ + withConnectionRemoval: vi.fn(async (_ids: string[], remove: Parameters[1]) => { + await remove(async (_id, deleteStored) => deleteStored()); + }), +})); + // Mock vscode-azext-utils vi.mock('@microsoft/vscode-azext-utils', () => ({ AzureWizardPromptStep: class { diff --git a/src/commands/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..72ab417b2 --- /dev/null +++ b/src/commands/dashboardBoundCommands.test.ts @@ -0,0 +1,253 @@ +/*--------------------------------------------------------------------------------------------- + * 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), + getLatchReason: vi.fn(), + resolveBoundClient: vi.fn(), + assertBindingActive: 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/diagnoseConnection/diagnoseConnection.test.ts b/src/commands/diagnoseConnection/diagnoseConnection.test.ts index c428ccfa6..85d61240a 100644 --- a/src/commands/diagnoseConnection/diagnoseConnection.test.ts +++ b/src/commands/diagnoseConnection/diagnoseConnection.test.ts @@ -49,7 +49,10 @@ vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn(), setCredentials: vi.fn(), setAuthCredentials: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), getClient: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), diff --git a/src/commands/disconnect/disconnect.test.ts b/src/commands/disconnect/disconnect.test.ts new file mode 100644 index 000000000..8ebd4e7df --- /dev/null +++ b/src/commands/disconnect/disconnect.test.ts @@ -0,0 +1,242 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { type PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { Views } from '../../documentdb/Views'; +import { ext } from '../../extensionVariables'; +import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { connectDisconnected, disconnect } from './disconnect'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { exists: vi.fn(), hasPendingStartup: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, +})); +vi.mock('../../documentdb/connectionSurfaces', () => ({ getConnectionSurfaces: vi.fn() })); +vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: vi.fn() })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators: vi.fn() })); +vi.mock('../../extensionVariables', () => ({ ext: { state: { notifyChildrenChanged: vi.fn() } } })); +vi.mock('../../tree/documentdb/ClusterItemBase', () => ({ ClusterItemBase: class {} })); +vi.mock(import('../retryAuthentication/retryAuthentication'), async (importOriginal) => ({ + ...(await importOriginal()), + refreshAuthenticationNode: vi.fn(), +})); + +function actionContext(): IActionContext { + return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; +} + +function clusterNode(viewId: Views = Views.ConnectionsView): ClusterItemBase { + return Object.assign(Object.create(ClusterItemBase.prototype) as ClusterItemBase, { + id: `${viewId}/folder/cluster`, + contextValue: `${viewId};treeItem_documentdbcluster`, + cluster: { clusterId: 'stable-cluster', treeId: `${viewId}/folder/cluster`, viewId }, + }); +} + +describe('tree disconnect recovery', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(ClustersClient.exists).mockReturnValue(true); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getConnectionSurfaces).mockReturnValue([]); + vi.mocked(getPlaygroundEvaluators).mockReturnValue(new Map()); + vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); + }); + + it.each([ + [disconnect, 'connectionRemoved'], + [connectDisconnected, 'identityChanged'], + ] as const)( + '%s rejects removed or changed stale actions after refreshing once', + async (command, reason): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (command === disconnect) { + vi.mocked(ClustersClient.exists).mockReturnValue(false); + } + const context = actionContext(); + const node = clusterNode(); + + await command(context, node); + + expect(ClustersClient.getLatchReason).toHaveBeenCalledWith('stable-cluster'); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.state.notifyChildrenChanged).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, 'credentialsRejected', 'userDisconnected'] as const)( + 'refreshes an obsolete Disconnect quietly for %s', + async (reason): Promise => { + const node = clusterNode(); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await disconnect(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, 'credentialsRejected'] as const)( + 'refreshes an already completed or superseded Reconnect quietly for %s', + (reason): void => { + const node = clusterNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + connectDisconnected(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.state.notifyChildrenChanged).not.toHaveBeenCalled(); + }, + ); + + it('disconnects the stable identity and delegates its single refresh to teardown', async (): Promise => { + const node = clusterNode(); + vi.mocked(teardownConnection).mockImplementationOnce(async (_clusterId, _reason, refresh): Promise => { + refresh?.(); + }); + + await disconnect(actionContext(), node); + + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + 'stable-cluster', + 'userDisconnected', + expect.any(Function), + ); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('only clears the current user-disconnected latch when reconnecting', (): void => { + const node = clusterNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + + const context = actionContext(); + connectDisconnected(context, node); + + const requestedId = context.telemetry.properties.requestedStartupCorrelationId; + expect(requestedId).toEqual(expect.any(String)); + expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith('stable-cluster', requestedId); + expect(ext.state.notifyChildrenChanged).toHaveBeenCalledExactlyOnceWith(node.id); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it.each([disconnect, connectDisconnected])( + '%s leaves unsupported stale Workspace nodes untouched', + async (command): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + if (command === disconnect) { + await expect(command(actionContext(), clusterNode(Views.AzureWorkspaceView))).rejects.toBeInstanceOf( + UserCancelledError, + ); + } else { + command(actionContext(), clusterNode(Views.AzureWorkspaceView)); + } + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }, + ); + + it('keeps an absent Disconnect selection cancelled without UI', async (): Promise => { + await expect(disconnect(actionContext())).rejects.toBeInstanceOf(UserCancelledError); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'does not bypass ordinary Disconnect for a surviving %s on a rejected or absent client', + async (survivor): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(survivor === 'heldClient'); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(survivor === 'startup'); + if (survivor === 'surface') { + vi.mocked(getConnectionSurfaces).mockReturnValue([ + { clusterId: 'stable-cluster', kind: 'documentView', disable: vi.fn(), dispose: vi.fn() }, + ]); + } + if (survivor === 'evaluator') { + vi.mocked(getPlaygroundEvaluators).mockReturnValue( + new Map([['stable-cluster', {} as PlaygroundEvaluator]]), + ); + } + if (survivor === 'shell') { + const terminal: vscode.Terminal = { + name: 'Test shell', + processId: Promise.resolve(undefined), + creationOptions: {}, + exitStatus: undefined, + state: { isInteractedWith: false, shell: undefined }, + shellIntegration: undefined, + sendText: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + }; + const shell: ReturnType[number] = { + terminal, + info: { + clusterId: 'stable-cluster', + clusterDisplayName: 'Cluster', + activeDatabase: 'database', + isInitialized: true, + isEvaluating: false, + workerState: 'ready', + authMethod: 'NoAuth', + username: undefined, + }, + disconnect: vi.fn(), + }; + vi.mocked(getRegisteredShellTerminals).mockReturnValue([shell]); + } + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + 'stable-cluster', + 'userDisconnected', + expect.any(Function), + ); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('leaves credentialsUpdating safely terminal even with surviving surfaces', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsUpdating'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts new file mode 100644 index 000000000..8c452463e --- /dev/null +++ b/src/commands/disconnect/disconnect.ts @@ -0,0 +1,88 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { randomUUID } from 'node:crypto'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { Views } from '../../documentdb/Views'; +import { ext } from '../../extensionVariables'; +import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { type TreeElement } from '../../tree/TreeElement'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; +import { refreshAuthenticationNode, showObsoleteTreeAction } from '../retryAuthentication/retryAuthentication'; + +function isClusterNode(node: TreeElement | undefined): node is ClusterItemBase { + return node instanceof ClusterItemBase; +} + +export async function disconnect(context: IActionContext, node?: TreeElement): Promise { + context.telemetry.suppressAll = true; // connection.disconnect owns this operation's telemetry. + if (!isClusterNode(node)) { + throw new UserCancelledError(); + } + + const { clusterId } = node.cluster; + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'userDisconnected' || + reason === 'connectionRemoved' || + reason === 'credentialsUpdating' || + (!ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId)) + ) { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + throw new UserCancelledError(); + } + refreshAuthenticationNode(node); + showObsoleteTreeAction(context, reason); + return; + } + + await teardownConnection(clusterId, 'userDisconnected', () => refreshAuthenticationNode(node)); +} + +export function connectDisconnected(context: IActionContext, node?: TreeElement): void { + if (!isClusterNode(node)) { + return; + } + const reason = ClustersClient.getLatchReason(node.cluster.clusterId); + if (reason !== 'userDisconnected') { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + return; + } + refreshAuthenticationNode(node); + showObsoleteTreeAction(context, reason); + return; + } + + if (context.telemetry?.properties) { + const requestedStartupId = randomUUID(); + context.telemetry.properties.requestedStartupCorrelationId = requestedStartupId; + ClustersClient.unlatch(node.cluster.clusterId, requestedStartupId); + } else { + ClustersClient.unlatch(node.cluster.clusterId); + } + ext.state.notifyChildrenChanged(node.id); +} diff --git a/src/commands/exportDocuments/exportDocuments.ts b/src/commands/exportDocuments/exportDocuments.ts index 0f2fd7bb2..8adc17ed7 100644 --- a/src/commands/exportDocuments/exportDocuments.ts +++ b/src/commands/exportDocuments/exportDocuments.ts @@ -7,22 +7,37 @@ 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 { TaskService } from '../../services/taskService/taskService'; 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,46 +54,59 @@ export async function exportQueryResults( return; } - const client = await ClustersClient.getClient(node.cluster.clusterId); + const lease = TaskService.acquireResourceLease( + { + clusterId: node.cluster.clusterId, + databaseName: node.databaseInfo.name, + collectionName: node.collectionInfo.name, + }, + l10n.t('Export documents'), + ); - const docStreamAbortController = new AbortController(); + try { + const client = await resolveTransferClient(node.cluster.clusterId, props?.binding); - // Convert legacy queryText to queryParams if needed - const queryParams: FindQueryParams = props?.queryParams ?? { - filter: props?.queryText ?? '{}', - }; + const docStreamAbortController = new AbortController(); - const docStream = client.streamDocumentsWithQuery( - node.databaseInfo.name, - node.collectionInfo.name, - docStreamAbortController.signal, - queryParams, - ); - - const filePath = targetUri.fsPath; // Convert `vscode.Uri` to a regular file path - ext.outputChannel.info(l10n.t('Starting export to: {filePath}', { filePath })); + // Convert legacy queryText to queryParams if needed + const queryParams: FindQueryParams = props?.queryParams ?? { + filter: props?.queryText ?? '{}', + }; - let documentCount = 0; + const docStream = client.streamDocumentsWithQuery( + node.databaseInfo.name, + node.collectionInfo.name, + docStreamAbortController.signal, + queryParams, + ); - // Wrap the export process inside a progress reporting function - await callWithTelemetryAndErrorHandling('exportDocuments', async (actionContext) => { - await runExportWithProgressAndDescription(node.id, async (progress, cancellationToken) => { - documentCount = await exportDocumentsToFile( - docStream, - filePath, - progress, - cancellationToken, - docStreamAbortController, - ); + const filePath = targetUri.fsPath; // Convert `vscode.Uri` to a regular file path + ext.outputChannel.info(l10n.t('Starting export to: {filePath}', { filePath })); + + let documentCount = 0; + + // Wrap the export process inside a progress reporting function + await callWithTelemetryAndErrorHandling('exportDocuments', async (actionContext) => { + await runExportWithProgressAndDescription(node.id, async (progress, cancellationToken) => { + documentCount = await exportDocumentsToFile( + docStream, + filePath, + progress, + cancellationToken, + docStreamAbortController, + ); + }); + + actionContext.telemetry.properties.source = props?.source; + actionContext.telemetry.measurements.queryLength = + props?.queryParams?.filter?.length ?? props?.queryText?.length; + actionContext.telemetry.measurements.documentCount = documentCount; }); - actionContext.telemetry.properties.source = props?.source; - actionContext.telemetry.measurements.queryLength = - props?.queryParams?.filter?.length ?? props?.queryText?.length; - actionContext.telemetry.measurements.documentCount = documentCount; - }); - - ext.outputChannel.info(l10n.t('Export complete. Exported document count: {documentCount}', { documentCount })); + ext.outputChannel.info(l10n.t('Export complete. Exported document count: {documentCount}', { documentCount })); + } finally { + lease.dispose(); + } } async function runExportWithProgressAndDescription( diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts new file mode 100644 index 000000000..e992196ac --- /dev/null +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { beforeEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { confirmTeardown } from '../../documentdb/connectionTeardown'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { DocumentDBExperience } from '../../DocumentDBExperiences'; +import { ext } from '../../extensionVariables'; +import { TaskService } from '../../services/taskService/taskService'; +import { CollectionItem } from '../../tree/documentdb/CollectionItem'; +import { exportQueryResults } from '../exportDocuments/exportDocuments'; +import { importDocuments } from './importDocuments'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { + getClient: vi.fn(), + getLatchReason: vi.fn(), + resolveBoundClient: vi.fn(), + assertBindingActive: 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() })); +vi.mock('../../utils/fs/appendToFile', () => ({ appendToFile: 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 createContext(showOpenDialog: () => Promise = async () => []): IActionContext { + return { + ui: { showOpenDialog }, + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + valuesToMask: [], + } as unknown as IActionContext; +} +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(ClustersClient.getClient).mockReset(); + vi.mocked(ClustersClient.resolveBoundClient).mockReset(); + vi.mocked(ClustersClient.getLatchReason).mockReset().mockReturnValue(undefined); + vi.mocked(vscode.window.withProgress).mockImplementation((_options, task) => + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ); + vi.mocked(vscode.window.showSaveDialog).mockReset(); +}); + +it('does not import using a different identity selected while the file picker was open', async (): Promise => { + const insertDocuments = vi.fn(); + 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(createContext(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('holds an import lease through client resolution and the final flush', async (): Promise => { + let resolveClient!: (client: ClustersClient) => void; + const clientResolution = new Promise((resolve) => { + resolveClient = resolve; + }); + let resolveInsert!: (result: { insertedCount: number }) => void; + const insertDocuments = vi.fn( + () => + new Promise<{ insertedCount: number }>((resolve) => { + resolveInsert = resolve; + }), + ); + vi.mocked(ClustersClient.getClient).mockReturnValue(clientResolution); + + const importOperation = importDocuments(createContext(), createSource(), [ + vscode.Uri.file('/fixture/documents.json'), + ]); + + await vi.waitFor(() => { + expect(ClustersClient.getClient).toHaveBeenCalledWith('cluster'); + }); + + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([ + expect.objectContaining({ taskName: 'Import documents' }), + ]); + expect( + TaskService.getConflictingTasks({ + clusterId: 'cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toHaveLength(1); + expect(TaskService.getConflictingTasks({ clusterId: 'unrelated' })).toEqual([]); + await expect(confirmTeardown('cluster', 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + resolveClient({ + getConnectionString: () => 'mongodb://example.test', + insertDocuments, + } as unknown as ClustersClient); + await vi.waitFor(() => { + expect(insertDocuments).toHaveBeenCalledOnce(); + }); + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toHaveLength(1); + + resolveInsert({ insertedCount: 1 }); + await importOperation; + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([]); +}); + +it('holds an export lease before client resolution and releases it on failure', async (): Promise => { + let rejectClient!: (error: Error) => void; + const clientResolution = new Promise((_resolve, reject) => { + rejectClient = reject; + }); + vi.mocked(vscode.window.showSaveDialog).mockResolvedValue(vscode.Uri.file('/fixture/export.json')); + vi.mocked(ClustersClient.getClient).mockReturnValue(clientResolution); + + const exportOperation = exportQueryResults(createContext(), createSource()); + + await vi.waitFor(() => { + expect(ClustersClient.getClient).toHaveBeenCalledWith('cluster'); + }); + + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([ + expect.objectContaining({ taskName: 'Export documents' }), + ]); + expect( + TaskService.getConflictingTasks({ + clusterId: 'cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toHaveLength(1); + expect(TaskService.getConflictingTasks({ clusterId: 'unrelated' })).toEqual([]); + await expect(confirmTeardown('cluster', 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + rejectClient(new Error('client resolution failed')); + await expect(exportOperation).rejects.toThrow('client resolution failed'); + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([]); +}); + +it('stops a bound import after rejection and reports only confirmed inserts', async (): Promise => { + const failure = new Error('Rejected fixture credentials'); + const insertDocuments = vi.fn().mockResolvedValueOnce({ insertedCount: 1 }).mockRejectedValueOnce(failure); + 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 = createContext(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).'); + expect(TaskService.getConflictingTasks({ clusterId: binding.clusterId })).toEqual([]); +}); diff --git a/src/commands/importDocuments/importDocuments.ts b/src/commands/importDocuments/importDocuments.ts index 82b323216..5ccdce0f2 100644 --- a/src/commands/importDocuments/importDocuments.ts +++ b/src/commands/importDocuments/importDocuments.ts @@ -8,21 +8,26 @@ 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, hasDomainSuffix, } from '../../documentdb/utils/connectionStringHelpers'; import { ext } from '../../extensionVariables'; +import { TaskService } from '../../services/taskService/taskService'; import { CollectionItem } from '../../tree/documentdb/CollectionItem'; import { BufferErrorCode, createMongoDbBuffer, type DocumentBuffer } from '../../utils/documentBuffer'; import { getRootPath } from '../../utils/workspacUtils'; +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 +80,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 +95,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, @@ -144,69 +158,97 @@ export async function importDocumentsWithProgress(selectedItem: CollectionItem, const countDocuments = documents.length; const incrementDocuments = 75 / (countDocuments || 1); let count = 0; - let buffer: DocumentBuffer | 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 connectionString = client.getConnectionString(); - - // Determine if this is an Azure MongoDB RU resource - // Fall back to non-RU buffer if connection string is unavailable - let isRuResource = false; - if (connectionString) { - const hosts = getHostsFromConnectionString(connectionString); - isRuResource = hasDomainSuffix(AzureDomains.RU, ...hosts); - } + const lease = TaskService.acquireResourceLease( + { + clusterId: selectedItem.cluster.clusterId, + databaseName: selectedItem.databaseInfo.name, + collectionName: selectedItem.collectionInfo.name, + }, + l10n.t('Import documents'), + ); - if (isRuResource) { - // For Azure MongoDB RU, we use a buffer with maxDocumentCount = 1 - buffer = createMongoDbBuffer({ - maxDocumentCount: 1, - }); - } else { - buffer = createMongoDbBuffer(); + try { + let buffer: DocumentBuffer | undefined; + let boundClient: ClustersClient | undefined; + if (selectedItem instanceof CollectionItem) { + // Get the connection string from the ClustersClient, not from the cluster model. + // For Discovery View items, the cluster model may not have connectionString populated, + // but the ClustersClient will have it after authentication. + const client = await resolveTransferClient(selectedItem.cluster.clusterId, binding); + if (binding) { + // A bound import must not switch clients between batches. + boundClient = client; + } + const connectionString = client.getConnectionString(); + + // Determine if this is an Azure MongoDB RU resource + // Fall back to non-RU buffer if connection string is unavailable + let isRuResource = false; + if (connectionString) { + const hosts = getHostsFromConnectionString(connectionString); + isRuResource = hasDomainSuffix(AzureDomains.RU, ...hosts); + } + + if (isRuResource) { + // For Azure MongoDB RU, we use a buffer with maxDocumentCount = 1 + buffer = createMongoDbBuffer({ + maxDocumentCount: 1, + }); + } else { + buffer = createMongoDbBuffer(); + } } - } - let wasCancelled = false; + let wasCancelled = false; + 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) { - wasCancelled = true; - ext.outputChannel.warn(l10n.t('Import operation was canceled after {0} document(s).', count)); - break; - } + for (let i = 0; i < countDocuments; i++) { + if (cancellationToken.isCancellationRequested) { + wasCancelled = true; + ext.outputChannel.warn(l10n.t('Import operation was canceled after {0} document(s).', count)); + break; + } - progress.report({ - increment: incrementDocuments, - message: l10n.t('Importing document {num} of {countDocuments}', { - num: i + 1, - countDocuments, - }), - }); + progress.report({ + increment: incrementDocuments, + message: l10n.t('Importing document {num} of {countDocuments}', { + num: i + 1, + countDocuments, + }), + }); - const result = await insertDocument(selectedItem, documents[i], buffer); + const result = await insertBatch(documents[i]); - // 'count' in result means that the result is from the buffer - count += result.count; - // check if error occurred as partial failure would happen in bulk insertion - hasErrors = hasErrors || result.errorOccurred; - } + // 'count' in result means that the result is from the buffer + count += result.count; + // check if error occurred as partial failure would happen in bulk insertion + hasErrors = hasErrors || result.errorOccurred; + } - // Do insertion for the last batch for bulk insertion - if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { - const lastBatchFlushResult = await insertDocument(selectedItem, undefined, buffer); + // Do insertion for the last batch for bulk insertion + if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { + const lastBatchFlushResult = await insertBatch(undefined); - count += lastBatchFlushResult.count; - hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; - } + count += lastBatchFlushResult.count; + hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; + } - // let's make sure we reach 100% progress, useful in case of errors etc. - progress.report({ increment: 100, message: l10n.t('Finished importing') }); + // let's make sure we reach 100% progress, useful in case of errors etc. + progress.report({ increment: 100, message: l10n.t('Finished importing') }); - return { hasErrors, count, wasCancelled }; + return { hasErrors, count, wasCancelled }; + } finally { + lease.dispose(); + } }, ); @@ -313,6 +355,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 +366,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 +385,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 +411,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 +424,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/index.dropIndex/dropIndex.ts b/src/commands/index.dropIndex/dropIndex.ts index 62eb3dc05..c11a7a085 100644 --- a/src/commands/index.dropIndex/dropIndex.ts +++ b/src/commands/index.dropIndex/dropIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -72,6 +73,7 @@ export async function dropIndex(context: IActionContext, node: IndexItem): Promi // error, then rethrow so telemetry still records the failure. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to delete index "{indexName}".', { indexName }), { modal: true, detail, diff --git a/src/commands/index.hideIndex/hideIndex.ts b/src/commands/index.hideIndex/hideIndex.ts index a50ad35f9..d5b6f7ad7 100644 --- a/src/commands/index.hideIndex/hideIndex.ts +++ b/src/commands/index.hideIndex/hideIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -76,6 +77,7 @@ export async function hideIndex(context: IActionContext, node: IndexItem): Promi // azext's default non-modal error and rethrow for telemetry. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to hide index "{indexName}".', { indexName }), { modal: true, detail, diff --git a/src/commands/index.shared/getIndexConfirmationStats.ts b/src/commands/index.shared/getIndexConfirmationStats.ts index f0fc9b155..aa111f21b 100644 --- a/src/commands/index.shared/getIndexConfirmationStats.ts +++ b/src/commands/index.shared/getIndexConfirmationStats.ts @@ -5,6 +5,7 @@ import { ClustersClient } from '../../documentdb/ClustersClient'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { meterSilentCatch } from '../../utils/accumulatingTelemetry'; /** * Fetch the size + usage of a single index for a confirmation dialog, so the @@ -30,6 +31,7 @@ export async function getIndexConfirmationStats(node: IndexItem): Promise<{ size sizeBytes = bytes; } } catch { + meterSilentCatch('getIndexConfirmationStats_size'); // Ignore — size stays unknown. } @@ -41,6 +43,7 @@ export async function getIndexConfirmationStats(node: IndexItem): Promise<{ size usageOps = stat.accesses.ops; } } catch { + meterSilentCatch('getIndexConfirmationStats_usage'); // Ignore — usage stays unknown. } diff --git a/src/commands/index.shared/indexCommandFeedback.test.ts b/src/commands/index.shared/indexCommandFeedback.test.ts new file mode 100644 index 000000000..3dc0f7650 --- /dev/null +++ b/src/commands/index.shared/indexCommandFeedback.test.ts @@ -0,0 +1,229 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + createTestActionContext, + registerCommand, + type IActionContext, + type TreeNodeCommandCallback, +} from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; +import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { registerCommandWithTreeNodeUnwrappingAndDiagnostics } from '../../utils/commandErrorHandling'; +import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; +import { dropIndex } from '../index.dropIndex/dropIndex'; +import { hideIndex } from '../index.hideIndex/hideIndex'; +import { unhideIndex } from '../index.unhideIndex/unhideIndex'; +import { getIndexConfirmationStats } from './getIndexConfirmationStats'; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, registerCommand: vi.fn() }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal & { default: Record }>(); + class CancellationError extends Error {} + actual.default.CancellationError = CancellationError; + return { ...actual, CancellationError }; +}); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getClient: vi.fn() }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { + state: { + runWithTemporaryDescription: vi.fn( + async (_id: string, _description: string, callback: () => Promise) => callback(), + ), + showDeleting: vi.fn(async (_id: string, callback: () => Promise) => callback()), + notifyChildrenChanged: vi.fn(), + }, + }, +})); + +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +vi.mock('../../utils/dialogs/confirmIndexAction', () => ({ + confirmIndexAction: vi.fn(), +})); + +vi.mock('../../utils/dialogs/showConfirmation', () => ({ + showConfirmationAsInSettings: vi.fn(), +})); + +vi.mock('./getIndexConfirmationStats', () => ({ + getIndexConfirmationStats: vi.fn(), +})); + +const explanation = { providerId: 'test-provider', message: 'Check the connection infrastructure.' }; + +function createIndexNode(overrides: Partial = {}): IndexItem { + return { + id: 'folder/cluster/database/collection/indexes/example_1', + cluster: { clusterId: 'stable-cluster' }, + databaseInfo: { name: 'database' }, + collectionInfo: { name: 'collection' }, + indexInfo: { name: 'example_1', type: 'traditional', key: { example: 1 }, ...overrides }, + experience: { api: 'documentdb' }, + } as unknown as IndexItem; +} + +function registerHandler( + handler: TreeNodeCommandCallback, +): (context: IActionContext, ...args: unknown[]) => unknown { + registerCommandWithTreeNodeUnwrappingAndDiagnostics('test.indexAction', handler); + const callback = vi.mocked(registerCommand).mock.calls.at(-1)?.[1]; + if (!callback) { + throw new Error('Command was not registered.'); + } + return callback; +} + +interface ActionCase { + readonly name: string; + readonly callback: TreeNodeCommandCallback; + readonly method: 'dropIndex' | 'hideIndex' | 'unhideIndex'; + readonly telemetryAction: 'drop' | 'hide' | 'unhide'; + readonly heading: string; + readonly error: unknown; + readonly node?: IndexItem; +} + +const actionCases: ActionCase[] = [ + { + name: 'hide', + callback: hideIndex, + method: 'hideIndex', + telemetryAction: 'hide', + heading: 'Failed to hide index "example_1".', + error: new Error('Hide failure'), + }, + { + name: 'unhide', + callback: unhideIndex, + method: 'unhideIndex', + telemetryAction: 'unhide', + heading: 'Failed to unhide index "example_1".', + error: 'Unhide primitive failure', + node: createIndexNode({ hidden: true }), + }, + { + name: 'delete', + callback: dropIndex, + method: 'dropIndex', + telemetryAction: 'drop', + heading: 'Failed to delete index "example_1".', + error: Object.freeze(new Error('Delete failure')), + }, +]; + +describe('tree index command feedback', () => { + let context: IActionContext; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.mocked(confirmIndexAction).mockResolvedValue(true); + vi.mocked(getIndexConfirmationStats).mockResolvedValue({}); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined); + context = await createTestActionContext(); + context.errorHandling.rethrow = true; + context.errorHandling.suppressDisplay = false; + }); + + it.each(actionCases)('shows exactly one callback modal for a failed $name action', async (action) => { + const operation = vi.fn().mockRejectedValue(action.error); + vi.mocked(ClustersClient.getClient).mockResolvedValue({ + [action.method]: operation, + } as unknown as ClustersClient); + const command = registerHandler(action.callback); + const node = action.node ?? createIndexNode(); + + await expect(command(context, node, [node])).rejects.toBe(action.error); + + expect(operation).toHaveBeenCalledExactlyOnceWith('database', 'collection', 'example_1'); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(action.heading, { + modal: true, + detail: String(action.error instanceof Error ? action.error.message : action.error), + }); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: 'stable-cluster', + error: action.error, + }); + expect(context.telemetry.properties).toMatchObject({ + experience: 'documentdb', + actionType: action.telemetryAction, + userCancelled: 'false', + explanationProviderId: explanation.providerId, + }); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + }); + + it.each([ + { + name: 'hide', + callback: hideIndex, + node: createIndexNode({ name: '_id_', key: { _id: 1 } }), + message: 'The "_id_" index cannot be hidden.', + }, + { + name: 'unhide', + callback: unhideIndex, + node: createIndexNode({ hidden: false }), + message: 'Index "example_1" is not hidden.', + }, + { + name: 'delete', + callback: dropIndex, + node: createIndexNode({ name: '_id_', key: { _id: 1 } }), + message: 'The "_id_" index cannot be deleted.', + }, + ] as const)('keeps $name validation failures on the wrapper display path', async ({ callback, node, message }) => { + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + const command = registerHandler(callback); + + const result = command(context, node, [node]); + + await expect(result).rejects.toThrow(message); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail: message, + }); + expect(confirmIndexAction).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(true); + }); + + it('shows a different refresh error after the operation modal was presented', async () => { + const operationError = new Error('Hide failure'); + const refreshError = new Error('Refresh failure'); + vi.mocked(ClustersClient.getClient).mockResolvedValue({ + hideIndex: vi.fn().mockRejectedValue(operationError), + } as unknown as ClustersClient); + vi.mocked(ext.state.notifyChildrenChanged).mockImplementationOnce(() => { + throw refreshError; + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + const command = registerHandler(hideIndex); + const node = createIndexNode(); + + await expect(command(context, node, [node])).rejects.toBe(refreshError); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(2); + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(2, 'Unable to complete this tree action.', { + modal: true, + detail: refreshError.message, + }); + }); +}); diff --git a/src/commands/index.unhideIndex/unhideIndex.ts b/src/commands/index.unhideIndex/unhideIndex.ts index 093491d71..6dc7bcd4c 100644 --- a/src/commands/index.unhideIndex/unhideIndex.ts +++ b/src/commands/index.unhideIndex/unhideIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -71,6 +72,7 @@ export async function unhideIndex(context: IActionContext, node: IndexItem): Pro // azext's default non-modal error and rethrow for telemetry. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to unhide index "{indexName}".', { indexName }), { modal: true, detail, 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/llmEnhancedCommands/queryGenerationCommands.test.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts new file mode 100644 index 000000000..afa37a256 --- /dev/null +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts @@ -0,0 +1,319 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createTestActionContext, UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type Document } from 'mongodb'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import type * as vscodeModule from 'vscode'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { getBindingLifetimeSignal, retireConnectionBindings } from '../../documentdb/connectionBindingRetirement'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CopilotService } from '../../services/copilotService'; +import { PromptTemplateService } from '../../services/promptTemplateService'; +import { generateQuery, QueryGenerationType, type QueryGenerationContext } from './queryGenerationCommands'; + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { trace: vi.fn() } }, +})); +vi.mock('../../services/copilotService', () => ({ + CopilotService: { isAvailable: vi.fn(), sendMessage: vi.fn() }, +})); +vi.mock('../../services/promptTemplateService', () => ({ + PromptTemplateService: { getQueryGenerationPromptTemplate: vi.fn() }, +})); +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + LanguageModelChatMessage: { User: vi.fn((content: string) => ({ role: 1, content })) }, +})); + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((complete): void => { + resolve = complete; + }); + return { promise, resolve }; +} + +let sequence = 0; +let context: IActionContext; +let binding: ConnectionBinding; +let queryContext: QueryGenerationContext; +let sampleDocuments: ReturnType>; +let listCollections: ReturnType>; +let client: ClustersClient; + +beforeEach(async (): Promise => { + vi.resetAllMocks(); + context = await createTestActionContext(); + binding = { clusterId: `query-generation-${++sequence}`, fingerprint: 'original', generation: 1 }; + queryContext = { + binding, + signal: getBindingLifetimeSignal(binding), + databaseName: 'database', + collectionName: 'collection', + naturalLanguageQuery: 'Find active records', + generationType: QueryGenerationType.SingleCollection, + }; + sampleDocuments = vi.fn().mockResolvedValue([{ active: true }]); + listCollections = vi + .fn() + .mockResolvedValue([{ name: 'first' }, { name: 'second' }]); + client = { binding, getSampleDocuments: sampleDocuments, listCollections } as unknown as ClustersClient; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(binding); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockResolvedValue(client); + vi.spyOn(ClustersClient, 'reportFailure').mockReturnValue(undefined); + vi.mocked(CopilotService.isAvailable).mockResolvedValue(true); + vi.mocked(CopilotService.sendMessage).mockResolvedValue({ + text: JSON.stringify({ explanation: 'Generated', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockResolvedValue('Fake prompt'); +}); + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it('does not sample a replacement after retirement during availability', async (): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + expect(CopilotService.isAvailable).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, binding.generation); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, fingerprint: 'replacement', generation: 2 }); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('preserves request cancellation during availability without sampling', async (): Promise => { + const availability = deferred(); + const controller = new AbortController(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, { ...queryContext, signal: controller.signal }); + controller.abort(); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('recovers an unretired same-identity binding with no cached client', async (): Promise => { + const recoveredBinding = { ...binding, generation: 2 }; + const recoveredSamples = vi.fn().mockResolvedValue([{ active: true }]); + let currentBinding: ConnectionBinding | undefined; + vi.mocked(ClustersClient.getBinding).mockImplementation(() => currentBinding); + vi.mocked(ClustersClient.resolveBoundClient).mockImplementationOnce(async () => { + currentBinding = recoveredBinding; + return { + binding: recoveredBinding, + getSampleDocuments: recoveredSamples, + } as unknown as ClustersClient; + }); + + await expect(generateQuery(context, queryContext)).resolves.toMatchObject({ explanation: 'Generated' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { + trigger: 'collectionView', + }); + expect(recoveredSamples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('does not resolve or sample for a pre-aborted request with no cached client', async (): Promise => { + const controller = new AbortController(); + controller.abort(); + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + + await expect(generateQuery(context, { ...queryContext, signal: controller.signal })).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample or send for a retired binding with no cached client', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + retireConnectionBindings(binding.clusterId, binding.generation); + + await expect(generateQuery(context, queryContext)).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample or send when recovery resolves to a different identity', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( + new ConnectionUnavailableError('identityChanged'), + ); + + await expect(generateQuery(context, queryContext)).rejects.toMatchObject({ reason: 'identityChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { + trigger: 'collectionView', + }); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('samples and sends once after same-account physical replacement during availability', async (): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + const replacementBinding = { ...binding, generation: 2 }; + const replacementSamples = vi.fn().mockResolvedValue([{ active: true }]); + vi.mocked(ClustersClient.getBinding).mockReturnValue(replacementBinding); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValue({ + binding: replacementBinding, + getSampleDocuments: replacementSamples, + } as unknown as ClustersClient); + availability.resolve(true); + + await expect(pending).resolves.toMatchObject({ explanation: 'Generated' }); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(replacementSamples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledWith(binding, { trigger: 'collectionView' }); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledWith(expect.any(Array), { + featureSource: 'queryGeneration', + signal: queryContext.signal, + }); +}); + +it('does not start the second collection sample after invalidation during the first', async (): Promise => { + const firstSample = deferred(); + sampleDocuments.mockReturnValueOnce(firstSample.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(sampleDocuments).toHaveBeenCalledExactlyOnceWith('database', 'first', 3)); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + firstSample.resolve([{ active: true }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample after retirement during collection listing', async (): Promise => { + const listing = deferred>>(); + listCollections.mockReturnValueOnce(listing.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(listCollections).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation); + listing.resolve([{ name: 'first' }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not send after retirement during prompt preparation', async (): Promise => { + const template = deferred(); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockReturnValueOnce(template.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(PromptTemplateService.getQueryGenerationPromptTemplate).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation); + template.resolve('Fake prompt'); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('returns a successful model response after same-account repair advances the epoch', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Generated after repair', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).resolves.toMatchObject({ + generatedQuery: JSON.stringify({ filter: '{"active":true}' }, null, 2), + explanation: 'Generated after repair', + }); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('cancels a model response after retirement even when the fake model ignores abort', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + expect(vi.mocked(CopilotService.sendMessage).mock.calls[0][1]?.signal?.aborted).toBe(true); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Late response', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + await expect(pending).rejects.toHaveProperty('stepName', 'staleBoundViewOperation'); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('preserves a schema sampling failure as the cause', async (): Promise => { + const cause = new Error('Synthetic sampling failure'); + sampleDocuments.mockRejectedValueOnce(cause); + + await expect(generateQuery(context, queryContext)).rejects.toMatchObject({ + message: expect.stringContaining('Failed to gather schema information'), + cause, + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledWith(binding, expect.objectContaining({ cause })); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it.each([new UserCancelledError('Synthetic cancellation'), new ConnectionUnavailableError('credentialsUpdating')])( + 'rethrows terminal sampling errors unchanged: $name', + async (error): Promise => { + sampleDocuments.mockRejectedValueOnce(error); + + await expect(generateQuery(context, queryContext)).rejects.toBe(error); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); + }, +); + +it('samples both collections and sends one request in normal cross-collection generation', async (): Promise => { + await expect( + generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }), + ).resolves.toMatchObject({ explanation: 'Generated' }); + + expect(listCollections).toHaveBeenCalledExactlyOnceWith('database'); + expect(sampleDocuments.mock.calls).toEqual([ + ['database', 'first', 3], + ['database', 'second', 3], + ]); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts index bce7621c0..acd52aafd 100644 --- a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts @@ -3,15 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { type Document } from 'mongodb'; import * as vscode from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; import { CopilotService } from '../../services/copilotService'; import { PromptTemplateService } from '../../services/promptTemplateService'; import { generateSchemaDefinition, type SchemaDefinition } from '../../utils/schemaInference'; +import { guardBoundViewOperation, runBoundViewOperation } from '../../webviews/documentdb/boundViewOperations'; import { getQueryTypeConfig, type FilledPromptResult } from './promptTemplates'; /** @@ -26,8 +28,8 @@ export enum QueryGenerationType { * Context information needed for query generation */ export interface QueryGenerationContext { - // The cluster/connection ID - clusterId: string; + readonly binding: ConnectionBinding; + readonly signal: AbortSignal; // Database name databaseName: string; // Collection name (only for single-collection queries) @@ -174,6 +176,10 @@ export async function generateQuery( // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); + const assertCurrent = guardBoundViewOperation(queryContext.binding, queryContext.signal); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } if (!copilotAvailable) { throw new Error( l10n.t( @@ -182,79 +188,96 @@ export async function generateQuery( ); } - // Get the MongoDB client const getClientStart = Date.now(); - const client = await ClustersClient.getClient(queryContext.clusterId); - context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas = await runBoundViewOperation( + queryContext.binding, + assertCurrent, + async (client) => { + context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas: Array = []; + const schemaGatheringStart = Date.now(); + try { + if (queryContext.generationType === QueryGenerationType.CrossCollection) { + // Get all collections in the database + const listCollectionsStart = Date.now(); + assertCurrent(); + const collections = await client.listCollections(queryContext.databaseName); + assertCurrent(); + context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { + ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), + count: collections.length.toString(), + }), + ); - // Gather schema information - const schemas: Array = []; - const schemaGatheringStart = Date.now(); + let collectionIndex = 0; + for (const collection of collections) { + collectionIndex++; + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + collection.name, + 3, + ); + assertCurrent(); + const sampleDocsDuration = Date.now() - sampleDocsStart; + context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { + collection: collection.name, + ms: sampleDocsDuration.toString(), + }), + ); - try { - if (queryContext.generationType === QueryGenerationType.CrossCollection) { - // Get all collections in the database - const listCollectionsStart = Date.now(); - const collections = await client.listCollections(queryContext.databaseName); - context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { - ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), - count: collections.length.toString(), - }), - ); + if (sampleDocs.length > 0) { + const schema = generateSchemaDefinition(sampleDocs, collection.name); + schemas.push(schema); + } else { + schemas.push({ collectionName: collection.name, fields: {} }); + } + } + } else { + if (!queryContext.collectionName) { + throw new Error(l10n.t('Collection name is required for single-collection query generation')); + } - let collectionIndex = 0; - for (const collection of collections) { - collectionIndex++; - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments(queryContext.databaseName, collection.name, 3); - const sampleDocsDuration = Date.now() - sampleDocsStart; - context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { - collection: collection.name, - ms: sampleDocsDuration.toString(), - }), - ); + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + queryContext.collectionName, + 10, + ); + assertCurrent(); + context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { + ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), + }), + ); - if (sampleDocs.length > 0) { - const schema = generateSchemaDefinition(sampleDocs, collection.name); + const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); schemas.push(schema); - } else { - schemas.push({ collectionName: collection.name, fields: {} }); } + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + return schemas; + } catch (error) { + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + if (error instanceof ConnectionUnavailableError || error instanceof UserCancelledError) { + throw error; + } + throw new Error( + l10n.t('Failed to gather schema information: {message}', { + message: error instanceof Error ? error.message : String(error), + }), + { cause: error }, + ); } - } else { - if (!queryContext.collectionName) { - throw new Error(l10n.t('Collection name is required for single-collection query generation')); - } - - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments( - queryContext.databaseName, - queryContext.collectionName, - 10, - ); - context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { - ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), - }), - ); - - const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); - schemas.push(schema); - } - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - } catch (error) { - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - throw new Error( - l10n.t('Failed to gather schema information: {message}', { - message: error instanceof Error ? error.message : String(error), - }), - ); - } + }, + { trigger: 'collectionView' }, + ); // Fill the prompt template const { craftedPrompt, userQuery, contextData } = await fillPromptTemplate( @@ -263,6 +286,9 @@ export async function generateQuery( schemas, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } ext.outputChannel.trace(l10n.t('[Query Generation] Calling Copilot...')); const response = await CopilotService.sendMessage( [ @@ -272,8 +298,12 @@ export async function generateQuery( ], { featureSource: 'queryGeneration', + signal: queryContext.signal, }, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } context.telemetry.measurements.llmCallDurationMs = response.durationMs; ext.outputChannel.trace( l10n.t('[Query Generation] Copilot response received in {ms}ms (model: {model})', { diff --git a/src/commands/newConnection/PromptTenantStep.test.ts b/src/commands/newConnection/PromptTenantStep.test.ts index e1ae7c902..2971c61ae 100644 --- a/src/commands/newConnection/PromptTenantStep.test.ts +++ b/src/commands/newConnection/PromptTenantStep.test.ts @@ -3,10 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; -const mockGetTenants = vi.fn(); -const mockIsSignedIn = vi.fn(); +const mockGetAccounts = vi.fn(); +const mockGetTenantsForAccount = vi.fn(); +const mockSignIn = vi.fn(); // Read eagerly by the credentialsManagement factory below, which `vi.mock` hoists above this line. const { mockConfigureAzureCredentials } = vi.hoisted(() => ({ mockConfigureAzureCredentials: vi.fn() })); const mockOutputChannel = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; @@ -19,12 +21,14 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth', () => ({ +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), // A `function`, not an arrow: Vitest 4 calls the implementation with `new`. VSCodeAzureSubscriptionProvider: vi.fn().mockImplementation(function () { return { - getTenants: mockGetTenants, - isSignedIn: mockIsSignedIn, + getAccounts: mockGetAccounts, + getTenantsForAccount: mockGetTenantsForAccount, + signIn: mockSignIn, }; }), })); @@ -51,6 +55,8 @@ vi.mock('../../plugins/api-shared/azure/credentialsManagement', () => ({ configureAzureCredentials: mockConfigureAzureCredentials, })); +import { Environment } from '@azure/ms-rest-azure-env'; +import { ExtendedEnvironment } from '@microsoft/vscode-azext-azureauth'; import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { traceTenantLookup } from '../../plugins/api-shared/azure/traceTenantLookup'; @@ -62,7 +68,11 @@ const tenant = { tenantId: TENANT_ID, displayName: 'Example Organization', defaultDomain: 'example.test', - account: { id: 'account', label: 'alex@example.test' }, + account: { + id: 'account', + label: 'alex@example.test', + environment: new ExtendedEnvironment(Environment.AzureCloud, false), + }, }; type PromptTenantStep = NewConnectionPromptTenantStep | UpdateCredentialsPromptTenantStep; @@ -107,8 +117,9 @@ describe.each([ ])('PromptTenantStep for %s', (_name, makeStep: () => PromptTenantStep) => { beforeEach(() => { vi.clearAllMocks(); - mockIsSignedIn.mockReset().mockResolvedValue(true); - mockGetTenants.mockReset().mockResolvedValue([tenant]); + mockSignIn.mockReset().mockResolvedValue(true); + mockGetAccounts.mockReset().mockResolvedValue([tenant.account]); + mockGetTenantsForAccount.mockReset().mockResolvedValue([tenant]); mockConfigureAzureCredentials.mockResolvedValue(undefined); }); @@ -137,12 +148,13 @@ describe.each([ expect(mockOutputChannel.info).toHaveBeenCalledTimes(2); expect(mockOutputChannel.info.mock.calls[1][0]).toContain('"skipped":true'); expect(mockOutputChannel.info.mock.calls[1][0]).toContain('notInteractiveEntra'); - expect(mockIsSignedIn).not.toHaveBeenCalled(); - expect(mockGetTenants).not.toHaveBeenCalled(); + expect(mockSignIn).not.toHaveBeenCalled(); + expect(mockGetAccounts).not.toHaveBeenCalled(); + expect(mockGetTenantsForAccount).not.toHaveBeenCalled(); }); it('runs account management before listing tenants when signed out', async () => { - mockIsSignedIn.mockResolvedValue(false); + mockSignIn.mockResolvedValue(false); const showQuickPick = vi.fn().mockImplementation(async (itemsPromise: Promise) => { const items = await itemsPromise; return items.find((item) => (item as { tenant?: unknown }).tenant); @@ -152,7 +164,12 @@ describe.each([ await makeStep().prompt(context as never); expect(mockConfigureAzureCredentials).toHaveBeenCalledTimes(1); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockSignIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false, noCache: true }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { + filter: false, + noCache: true, + }); expect((context as IActionContext & { entraIdAuthConfig?: { tenantId?: string } }).entraIdAuthConfig).toEqual({ tenantId: TENANT_ID, }); @@ -162,7 +179,7 @@ describe.each([ }); it('re-enumerates tenants after account management without exiting the wizard', async () => { - mockIsSignedIn.mockResolvedValue(true); + mockSignIn.mockResolvedValue(true); const showQuickPick = vi .fn() .mockImplementationOnce(async (items: Promise) => { @@ -178,7 +195,11 @@ describe.each([ await makeStep().prompt(context as never); expect(showQuickPick).toHaveBeenCalledTimes(2); - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts.mock.calls).toEqual([[{ filter: false }], [{ filter: false, noCache: true }]]); + expect(mockGetTenantsForAccount.mock.calls).toEqual([ + [tenant.account, { filter: false }], + [tenant.account, { filter: false, noCache: true }], + ]); expect(mockConfigureAzureCredentials).toHaveBeenCalledTimes(1); expect((context as IActionContext & { entraIdAuthConfig?: { tenantId?: string } }).entraIdAuthConfig).toEqual({ tenantId: TENANT_ID, @@ -186,7 +207,7 @@ describe.each([ }); it('distinguishes a successful empty result from failure and timeout', async () => { - mockGetTenants.mockResolvedValue([]); + mockGetTenantsForAccount.mockResolvedValue([]); const context = makeFallbackContext(); await makeStep().prompt(context as never); @@ -204,7 +225,7 @@ describe.each([ code: 'AuthorizationFailed', statusCode: 403, }); - mockGetTenants.mockRejectedValue(error); + mockGetTenantsForAccount.mockRejectedValue(error); await makeStep().prompt(makeFallbackContext() as never); @@ -215,7 +236,7 @@ describe.each([ }); it('does not print unrecognized error metadata', async () => { - mockGetTenants.mockRejectedValue( + mockGetTenantsForAccount.mockRejectedValue( Object.assign(new Error('secret-token'), { name: tenant.account.label, code: 'secret-token', @@ -230,7 +251,7 @@ describe.each([ }); it('does not print arbitrary thrown values', async () => { - mockGetTenants.mockRejectedValue(`secret-token ${tenant.account.label}`); + mockGetTenantsForAccount.mockRejectedValue(`secret-token ${tenant.account.label}`); await makeStep().prompt(makeFallbackContext() as never); @@ -239,19 +260,20 @@ describe.each([ }); it('logs sign-in failure while preserving the existing true fallback', async () => { - mockIsSignedIn.mockRejectedValue(new Error('secret-token')); + mockSignIn.mockRejectedValue(new Error('secret-token')); await makeStep().prompt(makeFallbackContext() as never); expect(outputText()).toMatch(/isSignedIn: failed in/); expect(mockConfigureAzureCredentials).not.toHaveBeenCalled(); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false }); expect(outputText()).not.toContain('secret-token'); }); it('logs sign-in timeout while preserving the existing true fallback', async () => { vi.useFakeTimers(); - mockIsSignedIn.mockReturnValue(new Promise(() => {})); + mockSignIn.mockReturnValue(new Promise(() => {})); const prompt = makeStep().prompt(makeFallbackContext() as never); await vi.advanceTimersByTimeAsync(5000); @@ -259,13 +281,14 @@ describe.each([ expect(outputText()).toContain('isSignedIn: timed out after 5000 ms; using fallback (signedIn=true)'); expect(mockConfigureAzureCredentials).not.toHaveBeenCalled(); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false }); }); it('logs late tenant completion without replacing the timeout fallback', async () => { vi.useFakeTimers(); let completeLookup!: (tenants: (typeof tenant)[]) => void; - mockGetTenants.mockReturnValue( + mockGetTenantsForAccount.mockReturnValue( new Promise<(typeof tenant)[]>((resolve) => { completeLookup = resolve; }), @@ -290,7 +313,7 @@ describe.each([ it('logs late provider rejection after a timeout', async () => { vi.useFakeTimers(); let failLookup!: (reason: Error) => void; - mockGetTenants.mockReturnValue( + mockGetTenantsForAccount.mockReturnValue( new Promise<(typeof tenant)[]>((_resolve, reject) => { failLookup = reject; }), @@ -308,7 +331,7 @@ describe.each([ it('offers an explicit retry after timeout and allows 30 seconds for it', async () => { vi.useFakeTimers(); - mockGetTenants + mockGetTenantsForAccount .mockReturnValueOnce(new Promise<(typeof tenant)[]>(() => {})) .mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve([tenant]), 29_000))); const showQuickPick = vi @@ -328,7 +351,11 @@ describe.each([ const prompt = makeStep().prompt(context as never); await vi.advanceTimersByTimeAsync(5000); - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts.mock.calls).toEqual([[{ filter: false }], [{ filter: false, noCache: true }]]); + expect(mockGetTenantsForAccount.mock.calls).toEqual([ + [tenant.account, { filter: false }], + [tenant.account, { filter: false, noCache: true }], + ]); await vi.advanceTimersByTimeAsync(29_000); await prompt; @@ -339,7 +366,7 @@ describe.each([ it('keeps manual entry, account management, and retry available after a retry timeout', async () => { vi.useFakeTimers(); - mockGetTenants.mockReturnValue(new Promise<(typeof tenant)[]>(() => {})); + mockGetTenantsForAccount.mockReturnValue(new Promise<(typeof tenant)[]>(() => {})); const showQuickPick = vi .fn() .mockImplementationOnce(async (itemsPromise: Promise<{ isRetryOption?: boolean }[]>) => @@ -367,7 +394,8 @@ describe.each([ await vi.advanceTimersByTimeAsync(35_000); await prompt; - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts).toHaveBeenCalledTimes(2); + expect(mockGetTenantsForAccount).toHaveBeenCalledTimes(2); }); it.each([ @@ -375,9 +403,9 @@ describe.each([ ['failure', new Error('synthetic failure'), 'Unable to load tenants'], ])('offers retry for a %s result without misreporting a timeout', async (_name, error, detail) => { if (error) { - mockGetTenants.mockRejectedValueOnce(error); + mockGetTenantsForAccount.mockRejectedValueOnce(error); } else { - mockGetTenants.mockResolvedValueOnce([]); + mockGetTenantsForAccount.mockResolvedValueOnce([]); } const showQuickPick = vi.fn().mockImplementation( async ( @@ -396,7 +424,8 @@ describe.each([ ); await makeStep().prompt(makeContext(showQuickPick) as never); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledTimes(1); + expect(mockGetTenantsForAccount).toHaveBeenCalledTimes(1); }); }); diff --git a/src/commands/newConnection/PromptTenantStep.ts b/src/commands/newConnection/PromptTenantStep.ts index 7595c0fe1..246cbe379 100644 --- a/src/commands/newConnection/PromptTenantStep.ts +++ b/src/commands/newConnection/PromptTenantStep.ts @@ -8,7 +8,10 @@ import { AzureWizardPromptStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; -import { type AzureSubscriptionProviderWithFilters } from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; import { traceTenantLookup, type TenantLookupResult } from '../../plugins/api-shared/azure/traceTenantLookup'; import { traceAuthFlow } from '../../utils/authTrace'; import { nonNullValue } from '../../utils/nonNull'; @@ -29,16 +32,22 @@ export class PromptTenantStep extends AzureWizardPromptStep => { // Load available tenants from Azure subscription provider - const { tenants, status } = await this.getAvailableTenants(subscriptionProvider, lookupTimeoutMs); + const { tenants, status } = await this.getAvailableTenants( + subscriptionProvider, + lookupTimeoutMs, + reloadTenants, + ); context.telemetry.measurements.availableTenantsCount = tenants.length; // Create quick pick items @@ -122,9 +131,11 @@ export class PromptTenantStep extends AzureWizardPromptStep { try { - return await traceTenantLookup('newConnection.isSignedIn', () => subscriptionProvider.isSignedIn(), { - timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, - fallbackValue: true, - }); + return await traceTenantLookup( + 'newConnection.isSignedIn', + () => subscriptionProvider.signIn(undefined, { promptIfNeeded: false }), + { timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, fallbackValue: true }, + ); } catch { return true; } @@ -191,12 +203,13 @@ export class PromptTenantStep extends AzureWizardPromptStep { let timedOut = false; try { const tenants = await traceTenantLookup( 'newConnection.getTenants', - () => subscriptionProvider.getTenants(), + () => getUnfilteredAzureTenants(subscriptionProvider, noCache), { timeoutMs, fallbackValue: [], diff --git a/src/commands/openClusterDashboard/openClusterDashboard.ts b/src/commands/openClusterDashboard/openClusterDashboard.ts index 65422b076..5ccd38002 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,7 +155,9 @@ export async function openClusterDashboard( ? context.telemetry.properties.journeyCorrelationId : undefined, }, + client.binding, options?.deepLink, + options?.activationSource === 'autoOpenOnConnect', ); context.telemetry.properties.viewId = viewId; diff --git a/src/commands/openCollectionView/openCollectionView.test.ts b/src/commands/openCollectionView/openCollectionView.test.ts index ff9d6ff11..6b19028ef 100644 --- a/src/commands/openCollectionView/openCollectionView.test.ts +++ b/src/commands/openCollectionView/openCollectionView.test.ts @@ -4,12 +4,24 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ClusterSession } from '../../documentdb/ClusterSession'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { openCollectionWebview } from '../../webviews/documentdb/collectionView/collectionViewController'; import { openCollectionViewInternal } from './openCollectionView'; +const { assertAvailable } = vi.hoisted(() => ({ assertAvailable: vi.fn() })); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { assertBindingActive: vi.fn() }, +})); vi.mock('../../documentdb/ClusterSession', () => ({ - ClusterSession: { initNewSession: vi.fn().mockResolvedValue('collection-session'), closeSession: vi.fn() }, + ClusterSession: { + initNewSession: vi.fn().mockResolvedValue('collection-session'), + getSession: vi.fn(() => ({ assertAvailable })), + closeSession: vi.fn(), + }, })); vi.mock('../../utils/feedbackPermission', () => ({ isFeedbackPermitted: () => true })); vi.mock('../../webviews/documentdb/collectionView/collectionViewController', () => ({ @@ -40,3 +52,73 @@ describe('URL-driven collection opening', () => { ); }); }); + +describe('bound collection opening', () => { + const origin = { clusterId: 'stable-id', fingerprint: 'dashboard-fingerprint', generation: 1 }; + const props = { + clusterId: origin.clusterId, + clusterDisplayName: 'Cluster', + viewId: 'connectionsView', + databaseName: 'db', + collectionName: 'collection', + }; + let context: IActionContext; + + beforeEach((): void => { + vi.clearAllMocks(); + context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + valuesToMask: [], + ui: {} as IActionContext['ui'], + }; + }); + + it('forwards the origin and cancellation to session creation without serializing them', async (): Promise => { + const signal = new AbortController().signal; + const options = { origin, signal }; + + await openCollectionViewInternal(context, props, options); + + expect(ClusterSession.initNewSession).toHaveBeenCalledExactlyOnceWith(origin.clusterId, options); + expect(ClustersClient.assertBindingActive).toHaveBeenCalledExactlyOnceWith(origin); + expect(ClusterSession.getSession).toHaveBeenCalledExactlyOnceWith('collection-session'); + expect(assertAvailable).toHaveBeenCalledExactlyOnceWith(signal); + expect(openCollectionWebview).toHaveBeenCalledExactlyOnceWith( + { + ...props, + sessionId: 'collection-session', + feedbackPermitted: true, + initialQuery: undefined, + initialTab: undefined, + }, + undefined, + undefined, + ); + }); + + it.each(['origin', 'session'] as const)( + 'closes the new session when the %s guard rejects immediately before publication', + async (guard): Promise => { + const error = new ConnectionUnavailableError('userDisconnected'); + const check = guard === 'origin' ? vi.mocked(ClustersClient.assertBindingActive) : assertAvailable; + check.mockImplementationOnce((): never => { + throw error; + }); + + await expect(openCollectionViewInternal(context, props, { origin })).rejects.toBe(error); + + expect(ClusterSession.closeSession).toHaveBeenCalledExactlyOnceWith('collection-session'); + expect(openCollectionWebview).not.toHaveBeenCalled(); + }, + ); + + it('preserves the unbound one-argument session call without bound guards', async (): Promise => { + await openCollectionViewInternal(context, props); + + expect(ClusterSession.initNewSession).toHaveBeenCalledExactlyOnceWith(props.clusterId); + expect(ClustersClient.assertBindingActive).not.toHaveBeenCalled(); + expect(ClusterSession.getSession).not.toHaveBeenCalled(); + expect(openCollectionWebview).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/commands/openCollectionView/openCollectionView.ts b/src/commands/openCollectionView/openCollectionView.ts index a73700cdc..0b399d7e2 100644 --- a/src/commands/openCollectionView/openCollectionView.ts +++ b/src/commands/openCollectionView/openCollectionView.ts @@ -7,6 +7,7 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { readDeepLinkTelemetry } from '../../deepLinks/deepLinkTelemetry'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { ClusterSession } from '../../documentdb/ClusterSession'; import { inferViewIdFromTreeId } from '../../documentdb/Views'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; @@ -59,14 +60,27 @@ export async function openCollectionViewInternal( */ initialTab?: 'tab_result' | 'tab_indexes' | 'tab_queryInsights'; }, + options?: { readonly origin?: ConnectionBinding; readonly signal?: AbortSignal }, ): Promise { /** * We're starting a new "session" using the existing connection. * A session can cache data, handle paging, and convert data. */ - const sessionId = await ClusterSession.initNewSession(props.clusterId); + const sessionId = options + ? await ClusterSession.initNewSession(props.clusterId, options) + : await ClusterSession.initNewSession(props.clusterId); context.telemetry.properties.collectionSessionId = sessionId; + if (options?.origin) { + try { + ClustersClient.assertBindingActive(options.origin); + ClusterSession.getSession(sessionId).assertAvailable(options.signal); + } catch (error) { + ClusterSession.closeSession(sessionId); + throw error; + } + } + const view = openCollectionWebview( { sessionId: sessionId, 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/openInteractiveShell/openInteractiveShell.test.ts b/src/commands/openInteractiveShell/openInteractiveShell.test.ts index 457a82fe6..caf8f3ca6 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.test.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.test.ts @@ -5,9 +5,43 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { openInteractiveShell } from './openInteractiveShell'; +import { Views } from '../../documentdb/Views'; +import { DocumentDBShellPty, type DocumentDBShellPtyOptions } from '../../documentdb/shell/DocumentDBShellPty'; +import { registerShellTerminal } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import * as unauthenticatedEndpoint from '../../documentdb/shell/unauthenticatedEndpoint'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { openInteractiveShell, openUnauthenticatedShell } from './openInteractiveShell'; + +vi.mock('../../documentdb/ClustersClient', () => { + const latches = new Map(); + return { + ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn((clusterId: string) => latches.get(clusterId)), + latch: vi.fn((clusterId: string, reason: string): void => { + latches.set(clusterId, reason); + }), + unlatch: vi.fn((clusterId: string): void => { + latches.delete(clusterId); + }), + }, + }; +}); + +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +vi.mock('../retryAuthentication/retryAuthentication', () => ({ + refreshAuthenticationNode: vi.fn(), +})); // Mock DocumentDBShellPty vi.mock('../../documentdb/shell/DocumentDBShellPty', () => ({ @@ -22,6 +56,7 @@ vi.mock('../../documentdb/shell/DocumentDBShellPty', () => ({ handleInput: vi.fn(), setTerminal: vi.fn(), getTerminalInfo: vi.fn().mockReturnValue({ clusterId: 'test-cluster-id' }), + disconnect: vi.fn(), }; }), })); @@ -36,6 +71,7 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn().mockReturnValue(true), + getCredentials: vi.fn(), }, })); @@ -50,7 +86,7 @@ describe('openInteractiveShell', () => { properties: {} as Record, measurements: {}, }, - errorHandling: {}, + errorHandling: {} as { suppressDisplay?: boolean }, ui: {}, valuesToMask: [], }; @@ -64,6 +100,7 @@ describe('openInteractiveShell', () => { mockShowInformationMessage = vi.spyOn(vscode.window, 'showInformationMessage').mockResolvedValue(undefined); mockShowErrorMessage = vi.spyOn(vscode.window, 'showErrorMessage').mockResolvedValue(undefined); mockContext.telemetry.properties = {}; + mockContext.errorHandling = {}; (CredentialCache.hasCredentials as Mock).mockReturnValue(true); }); @@ -97,14 +134,17 @@ describe('openInteractiveShell', () => { overrides?: Partial<{ clusterId: string; clusterName: string; + viewId: string; + contextValue: string; }>, ): unknown { return { + contextValue: overrides?.contextValue ?? 'connectionsView;treeItem_documentdbcluster', cluster: { clusterId: overrides?.clusterId ?? 'test-cluster-id', name: overrides?.clusterName ?? 'TestCluster', treeId: 'treeId-test', - viewId: 'connectionsView', + viewId: overrides?.viewId ?? 'connectionsView', dbExperience: { api: 'documentDB' }, }, experience: { api: 'documentDB' }, @@ -139,6 +179,269 @@ describe('openInteractiveShell', () => { }); }); + describe('unauthenticated failure-row entry', () => { + function expectPreTerminalModal(detail: string): void { + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail, + }); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBe(true); + } + + function makeAnonymousNode( + overrides?: Partial<{ + viewId: string; + contextValue: string; + }>, + ): ClusterItemBase { + return { + ...(makeClusterNode(overrides) as object), + getUnauthenticatedEndpoint: vi.fn().mockResolvedValue('mongodb://user:secret@host/?authSource=admin'), + getCredentials: vi.fn(), + getCredentialsForDiagnostics: vi.fn(), + } as unknown as ClusterItemBase; + } + + it('opens with an evicted cache and rereads sanitized endpoints without fetching credentials', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); + await openUnauthenticatedShell(mockContext as never, node); + const options = vi.mocked(DocumentDBShellPty).mock.calls[0][0]; + expect(options.unauthenticated?.connectionString).toBe('mongodb://host/'); + expect(await options.unauthenticated?.reread()).toBe('mongodb://host/'); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(node.getCredentials).not.toHaveBeenCalled(); + expect(node.getCredentialsForDiagnostics).not.toHaveBeenCalled(); + expect(registerShellTerminal).toHaveBeenCalledWith( + expect.anything(), + expect.any(Function), + expect.any(Function), + ); + expect(mockShowTerminal).toHaveBeenCalledOnce(); + }); + + it('keeps the normal command on its authenticated startup options', async (): Promise => { + await openInteractiveShell(mockContext as never, makeClusterNode() as never); + expect(CredentialCache.hasCredentials).toHaveBeenCalledWith('test-cluster-id'); + const options: DocumentDBShellPtyOptions = vi.mocked(DocumentDBShellPty).mock.calls[0][0]; + expect(options.unauthenticated).toBeUndefined(); + }); + + it('reports an unavailable endpoint without opening a terminal', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockResolvedValue(undefined); + await openUnauthenticatedShell(mockContext as never, node); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Cannot open a shell without authentication for "TestCluster": its endpoint is not available.', + { modal: true }, + ); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + }); + + it('propagates only bounded parser errors without creating a terminal', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockResolvedValue('mongodb://user:private@'); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + message: 'Invalid connection string.', + }); + expectPreTerminalModal('Invalid connection string.'); + }); + + it.each(['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const)( + 'allows the %s hold without clearing it', + async (reason): Promise => { + const node = makeAnonymousNode(); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await openUnauthenticatedShell(mockContext as never, node); + expect(mockShowTerminal).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(node.cluster.clusterId)).toBe(reason); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each([ + [Views.ConnectionsView, 'connectionsView;treeItem_documentdbcluster', 'connectionRemoved'], + [Views.DiscoveryView, 'discoveryView;treeItem_documentdbcluster', 'credentialsChanged'], + [Views.AzureResourcesView, 'azureResourcesView;ruBranch;treeItem_documentdbcluster', 'identityChanged'], + [ + Views.AzureResourcesView, + 'azureResourcesView;documentDbBranch;treeItem_documentdbcluster', + 'connectionRemoved', + ], + ] as const)( + 'refreshes and explains %s stale nodes with routing tag %s for %s', + async (viewId, contextValue, reason): Promise => { + const node = makeAnonymousNode({ viewId, contextValue }); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason, + }); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + reason === 'connectionRemoved' + ? 'This connection was removed. Choose another connection.' + : 'This connection changed. Refresh the tree and try again.', + { modal: true }, + ); + expect(node.getUnauthenticatedEndpoint).not.toHaveBeenCalled(); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBe(true); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each(['userDisconnected', 'credentialsUpdating', 'unreachable'] as const)( + 'uses the generic modal for the %s hold before reading an endpoint', + async (reason): Promise => { + const node = makeAnonymousNode(); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason, + }); + expect(node.getUnauthenticatedEndpoint).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each([ + [Views.AzureWorkspaceView, 'azureWorkspaceView;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;otherBranch;treeItem_documentdbcluster'], + ] as const)( + 'keeps typed stale feedback generic for unsupported %s node', + async (viewId, contextValue): Promise => { + const node = makeAnonymousNode({ viewId, contextValue }); + ClustersClient.latch(node.cluster.clusterId, 'connectionRemoved'); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'connectionRemoved', + }); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it('rethrows the same unavailability error with generic feedback when no current latch exists', async (): Promise => { + const node = makeAnonymousNode(); + const error = new ConnectionUnavailableError('credentialsChanged'); + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(error); + + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expectPreTerminalModal(error.message); + }); + + it('uses the current latch rather than the unavailable error reason', async (): Promise => { + const node = makeAnonymousNode(); + const error = new ConnectionUnavailableError('credentialsChanged'); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementationOnce(async (): Promise => { + ClustersClient.latch(node.cluster.clusterId, 'connectionRemoved'); + throw error; + }); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection was removed. Choose another connection.', + { modal: true }, + ); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }); + + it('honors Disconnect during the endpoint read', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementation(async (): Promise => { + ClustersClient.latch(node.cluster.clusterId, 'userDisconnected'); + return 'mongodb://host/'; + }); + + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }); + + it('honors an epoch change during the endpoint read before opening a terminal', async (): Promise => { + const node = makeAnonymousNode(); + let epoch = 0; + vi.mocked(ClustersClient.getEpoch).mockImplementation(() => epoch); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementation(async (): Promise => { + epoch++; + return 'mongodb://host/'; + }); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expectPreTerminalModal('The connection is unavailable.'); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); + }); + + it.each(['endpoint', 'sanitization', 'pty'] as const)( + 'shows one modal and rethrows the same safe %s failure', + async (phase): Promise => { + const node = makeAnonymousNode(); + const error = new Error('Safe startup failure'); + if (phase === 'endpoint') { + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(error); + } else if (phase === 'sanitization') { + vi.spyOn(unauthenticatedEndpoint, 'toUnauthenticatedConnectionString').mockImplementationOnce( + (): never => { + throw error; + }, + ); + } else { + vi.mocked(DocumentDBShellPty).mockImplementationOnce(function (): never { + throw error; + }); + } + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + expectPreTerminalModal(error.message); + }, + ); + + it('keeps endpoint-read cancellation quiet and rethrows the same cancellation', async (): Promise => { + const node = makeAnonymousNode(); + const cancellation = new UserCancelledError(); + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(cancellation); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(cancellation); + expect(mockShowErrorMessage).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBeUndefined(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + }); + }); + describe('when invoked from a database node', () => { it('should create terminal with correct name', async () => { await openInteractiveShell(mockContext as never, makeDatabaseNode() as never); diff --git a/src/commands/openInteractiveShell/openInteractiveShell.ts b/src/commands/openInteractiveShell/openInteractiveShell.ts index 39dd4fcda..48ccb16bc 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { @@ -11,13 +11,22 @@ import { type DeepLinkOpenOptions, type DeepLinkOpenResult, } from '../../deepLinks/deepLinkTelemetry'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { + ConnectionUnavailableError, + isDiagnosticAuthenticationHold, +} from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { DocumentDBShellPty } from '../../documentdb/shell/DocumentDBShellPty'; import { type ShellConnectionInfo } from '../../documentdb/shell/ShellSessionManager'; import { registerShellTerminal } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { toUnauthenticatedConnectionString } from '../../documentdb/shell/unauthenticatedEndpoint'; +import { type ConnectionClusterModel } from '../../tree/connections-view/models/ConnectionClusterModel'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; /** * Parameters for opening an interactive shell with pre-formatted content. @@ -84,12 +93,108 @@ export async function openInteractiveShell( }); pty.setTerminal(terminal); - registerShellTerminal(terminal, () => pty.getTerminalInfo()); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); terminal.show(); return { opened: true, shellSessionId: pty.shellSessionId }; } +export async function openUnauthenticatedShell(context: IActionContext, node?: ClusterItemBase): Promise { + if (!node) { + return; + } + const connectionInfo = extractConnectionInfo(node); + let pty: DocumentDBShellPty; + try { + const { clusterId } = node.cluster; + const assertAvailable = (): void => { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason && !isDiagnosticAuthenticationHold(reason)) { + throw new ConnectionUnavailableError(reason); + } + }; + assertAvailable(); + const epoch = ClustersClient.getEpoch(clusterId); + const endpoint = await node.getUnauthenticatedEndpoint(); + assertAvailable(); + if (epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (!endpoint) { + await vscode.window.showErrorMessage( + vscode.l10n.t( + 'Cannot open a shell without authentication for "{0}": its endpoint is not available.', + node.cluster.name, + ), + { modal: true }, + ); + return; + } + const connectionString = toUnauthenticatedConnectionString(endpoint); + pty = new DocumentDBShellPty({ + connectionInfo, + unauthenticated: { + connectionString, + emulatorConfiguration: (node.cluster as Partial).emulatorConfiguration, + reread: async (): Promise => { + const current = await node.getUnauthenticatedEndpoint(); + return current ? toUnauthenticatedConnectionString(current) : undefined; + }, + }, + }); + } catch (error) { + if (error instanceof UserCancelledError) { + throw error; + } + context.errorHandling.suppressDisplay = true; + if ( + error instanceof ConnectionUnavailableError && + (node.cluster.viewId === String(Views.ConnectionsView) || + node.cluster.viewId === String(Views.DiscoveryView) || + (node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue))) + ) { + const currentReason = ClustersClient.getLatchReason(node.cluster.clusterId); + refreshAuthenticationNode(node); + if ( + currentReason === 'connectionRemoved' || + currentReason === 'credentialsChanged' || + currentReason === 'identityChanged' + ) { + await vscode.window.showErrorMessage( + currentReason === 'connectionRemoved' + ? l10n.t('This connection was removed. Choose another connection.') + : l10n.t('This connection changed. Refresh the tree and try again.'), + { modal: true }, + ); + throw error; + } + } + await vscode.window.showErrorMessage(l10n.t('Unable to complete this tree action.'), { + modal: true, + detail: error instanceof Error ? error.message : String(error), + }); + throw error; + } + context.telemetry.properties.shellSessionId = pty.shellSessionId; + const terminal = vscode.window.createTerminal({ + name: l10n.t('DocumentDB: {0}/{1}', connectionInfo.clusterDisplayName, connectionInfo.databaseName), + pty, + iconPath: new vscode.ThemeIcon('terminal'), + }); + pty.setTerminal(terminal); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); + terminal.show(); +} + /** * Opens an interactive shell with explicit connection info and optional pre-filled input. * @@ -133,7 +238,11 @@ export async function openInteractiveShellWithInput( }); pty.setTerminal(terminal); - registerShellTerminal(terminal, () => pty.getTerminalInfo()); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); terminal.show(); } diff --git a/src/commands/playground/connectDatabase.test.ts b/src/commands/playground/connectDatabase.test.ts new file mode 100644 index 000000000..aa2873403 --- /dev/null +++ b/src/commands/playground/connectDatabase.test.ts @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { pickTreeNode } from '../../utils/pickItem/pickTreeNode'; +import { showConnectionInfo } from './connectDatabase'; + +vi.mock('../../utils/pickItem/pickTreeNode', () => ({ pickTreeNode: vi.fn() })); + +describe('playground connection information', () => { + let service: PlaygroundService; + let context: IActionContext; + let sequence = 0; + let uri: vscode.Uri; + let clusterId: string; + + beforeEach((): void => { + vi.clearAllMocks(); + clusterId = `playground-connection-info-${++sequence}`; + uri = vscode.Uri.parse(`untitled:connection-info-${sequence}.documentdb.js`); + Object.assign(vscode.window, { + activeTextEditor: { + document: { + uri, + languageId: PLAYGROUND_LANGUAGE_ID, + }, + } as vscode.TextEditor, + }); + context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + } as IActionContext; + service = PlaygroundService.getInstance(); + service.setConnection(uri, { + clusterId, + clusterDisplayName: 'Original Cluster', + databaseName: 'original', + }); + }); + + afterEach((): void => { + ClustersClient.unlatch(clusterId); + service.dispose(); + Object.assign(vscode.window, { activeTextEditor: undefined }); + vi.restoreAllMocks(); + }); + + it('explains an explicit disconnect without clearing the selected connection', async () => { + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + await showConnectionInfo(context); + + expect(vscode.window.showWarningMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + { modal: true }, + 'Connect to a different database…', + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(pickTreeNode).not.toHaveBeenCalled(); + expect(context.telemetry.properties.reconnectChoice).toBe('dismissed'); + expect(service.getConnection(uri)).toMatchObject({ + clusterId, + clusterDisplayName: 'Original Cluster', + databaseName: 'original', + }); + }); + + it('keeps the switch action on the normal picker flow', async () => { + const replacement = Object.assign(Object.create(DatabaseItem.prototype) as DatabaseItem, { + cluster: { + clusterId: `replacement-${sequence}`, + name: 'Replacement Cluster', + viewId: 'connectionsView', + }, + databaseInfo: { name: 'replacement' }, + experience: { api: 'DocumentDB' }, + }); + vi.mocked(vscode.window.showWarningMessage).mockResolvedValue('Connect to a different database…' as never); + vi.mocked(pickTreeNode).mockResolvedValue(replacement); + ClustersClient.latch(clusterId, 'userDisconnected'); + + await showConnectionInfo(context); + + expect(pickTreeNode).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + leafContextValue: 'treeItem_database', + telemetrySource: 'playground.connect', + placeHolder: 'Select a database to connect this playground to', + }), + ); + expect(context.telemetry.properties).toMatchObject({ + reconnectChoice: 'switch', + outcome: 'connected', + experience: 'DocumentDB', + }); + expect(service.getConnection(uri)).toMatchObject({ + clusterId: `replacement-${sequence}`, + clusterDisplayName: 'Replacement Cluster', + databaseName: 'replacement', + }); + }); +}); diff --git a/src/commands/playground/connectDatabase.ts b/src/commands/playground/connectDatabase.ts index 9b23c0989..cba4296a3 100644 --- a/src/commands/playground/connectDatabase.ts +++ b/src/commands/playground/connectDatabase.ts @@ -52,6 +52,21 @@ export async function showConnectionInfo(context: IActionContext, ...args: unkno } const switchAction = l10n.t('Connect to a different database…'); + if (service.isUserDisconnected(editor.document.uri)) { + const choice = await vscode.window.showWarningMessage( + l10n.t('This connection is disconnected. Reconnect from the tree, then run the script again.'), + { modal: true }, + switchAction, + ); + + context.telemetry.properties.reconnectChoice = choice === switchAction ? 'switch' : 'dismissed'; + + if (choice === switchAction) { + await promptAndConnectPlayground(context, editor.document.uri, 'playground.connect'); + } + return; + } + const choice = await vscode.window.showInformationMessage( l10n.t('This playground is connected to {0} / {1}.', connection.clusterDisplayName, connection.databaseName), { @@ -126,8 +141,7 @@ export async function promptAndConnectPlayground( context.telemetry.properties.outcome = 'connected'; context.telemetry.properties.experience = node instanceof DatabaseItem ? node.experience?.api : undefined; - PlaygroundService.getInstance().setConnection(uri, connection); - return connection; + return PlaygroundService.getInstance().setConnectionFromHost(uri, connection); } /** diff --git a/src/commands/playground/executePlaygroundCode.afterRun.test.ts b/src/commands/playground/executePlaygroundCode.afterRun.test.ts new file mode 100644 index 000000000..90a5ad9d2 --- /dev/null +++ b/src/commands/playground/executePlaygroundCode.afterRun.test.ts @@ -0,0 +1,345 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { type ExecutionResult, type PlaygroundConnection } from '../../documentdb/playground/types'; +import { disposeEvaluators, executePlaygroundCode } from './executePlaygroundCode'; + +const mocks = vi.hoisted(() => ({ + evaluate: vi.fn<() => Promise>(), + killWorker: vi.fn(), + consoleOutputCount: 0, + provider: { showResult: vi.fn(), focusResult: vi.fn<() => Promise>() }, + service: { getConnection: vi.fn(), isExecuting: vi.fn(), setExecuting: vi.fn() }, + recordSurveyActivity: vi.fn(), + notificationChoice: vi.fn<() => Promise>(), + errors: [] as { event: string; error: unknown }[], + tasks: [] as Promise[], +})); + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal()), + callWithTelemetryAndErrorHandling: ( + event: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + const context = { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; + const task = (async (): Promise => { + try { + return await callback(context); + } catch (error) { + mocks.errors.push({ event, error }); + return undefined; + } + })(); + mocks.tasks.push(task); + return task; + }, +})); +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getExistingClient: vi.fn(), getLatchReason: vi.fn() }, +})); +vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { getCredentials: vi.fn() } })); +vi.mock('../../documentdb/feedResultToSchemaStore', () => ({ feedResultToSchemaStore: vi.fn() })); +vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ + PlaygroundEvaluator: class { + readonly evaluate = mocks.evaluate; + readonly killWorker = mocks.killWorker; + readonly sessionEvalCount = 1; + readonly lastInitDurationMs = 0; + get lastEvalConsoleOutputCount(): number { + return mocks.consoleOutputCount; + } + dispose(): void {} + }, +})); +vi.mock('../../documentdb/playground/PlaygroundService', () => ({ + PlaygroundService: { getInstance: (): typeof mocks.service => mocks.service }, +})); +vi.mock('../../documentdb/utils/getClusterMetadata', () => ({ addDomainInfoToProperties: vi.fn() })); +vi.mock('../../documentdb/utils/connectionStringHelpers', () => ({ getHostsFromConnectionString: vi.fn() })); +vi.mock('../../extensionVariables', () => ({ ext: { playgroundResultProvider: mocks.provider } })); +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn().mockResolvedValue(undefined) }, +})); +vi.mock('../../services/survey/SurveyService', () => ({ recordSurveyActivity: mocks.recordSurveyActivity })); +vi.mock('./connectDatabase', () => ({ promptAndConnectPlayground: vi.fn() })); + +describe('executePlaygroundCode after-run behavior', () => { + const sourceUri = vscode.Uri.file('/query.documentdb.js'); + const connection: PlaygroundConnection = { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'db', + }; + const result: ExecutionResult = { type: 'Cursor', printable: [{ _id: 1 }, { _id: 2 }], durationMs: 5 }; + let cancellation: vscode.EventEmitter; + let progressFinished: boolean; + let token: vscode.CancellationToken; + + beforeEach(() => { + mocks.errors.length = 0; + mocks.tasks.length = 0; + mocks.consoleOutputCount = 0; + mocks.evaluate.mockResolvedValue(result); + mocks.provider.showResult.mockResolvedValue(undefined); + mocks.provider.focusResult.mockResolvedValue(true); + mocks.service.getConnection.mockReturnValue(connection); + mocks.service.isExecuting.mockReturnValue(false); + mocks.notificationChoice.mockResolvedValue(undefined); + cancellation = new vscode.EventEmitter(); + token = { isCancellationRequested: false, onCancellationRequested: cancellation.event }; + progressFinished = false; + vi.spyOn(vscode.window, 'showInformationMessage').mockImplementation( + async ( + _message: string, + ...items: (T | vscode.MessageOptions)[] + ): Promise => { + const choice = await mocks.notificationChoice(); + return items.find((item): item is T => { + if (typeof item === 'string') { + return item === choice; + } + return typeof item === 'object' && 'title' in item && item.title === choice; + }); + }, + ); + vi.spyOn(vscode.window, 'showErrorMessage').mockResolvedValue(undefined); + vi.spyOn(vscode.window, 'withProgress').mockImplementation( + async ( + _options: vscode.ProgressOptions, + task: ( + progress: vscode.Progress<{ message?: string; increment?: number }>, + token: vscode.CancellationToken, + ) => Thenable, + ): Promise => { + try { + return await task({ report: vi.fn() }, token); + } finally { + progressFinished = true; + } + }, + ); + }); + + afterEach(() => { + cancellation.dispose(); + disposeEvaluators(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it.each([undefined, 'stay', 'focusResult', 'notify'] as const)( + 'performs only the %s success outcome', + async (afterRun) => { + await executePlaygroundCode( + 'db.test.find()', + 'runSelected', + sourceUri, + afterRun ? { afterRun } : undefined, + ); + + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( + sourceUri, + expect.stringContaining('// Result: Cursor (2 documents)'), + { focus: afterRun === 'focusResult' }, + ); + if (afterRun === 'notify') { + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'Query completed: Cursor (2 documents)', + 'Focus Result', + ); + } else { + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + } + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).toHaveBeenCalledWith('queryPlayground'); + expect(mocks.service.setExecuting.mock.calls).toEqual([ + ['cluster', true], + ['cluster', false], + ]); + expect(progressFinished).toBe(true); + }, + ); + + it('uses the approved no-return message only when the worker proves the printable was undefined', async () => { + mocks.evaluate.mockResolvedValue({ + type: null, + printable: undefined, + printableIsUndefined: true, + durationMs: 5, + }); + + await executePlaygroundCode('const a = 1', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + 'Query completed without a return value.', + 'Focus Result', + ); + }); + + it.each([ + [null, 'null'], + [42, 'number'], + ] as const)( + 'truthfully announces an untyped printable %j instead of claiming no return value', + async (printable, description) => { + mocks.evaluate.mockResolvedValue({ type: null, printable, durationMs: 5 }); + + await executePlaygroundCode('db.test.findOne()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + `Query completed: ${description}`, + 'Focus Result', + ); + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { + focus: false, + }); + }, + ); + + it.each([undefined, 'Focus Result'])( + 'finishes progress and unlocks execution before the notification choice %s', + async (choice) => { + let choose: ((value: string | undefined) => void) | undefined; + const notification = new Promise((resolve) => { + choose = resolve; + }); + mocks.notificationChoice.mockReturnValueOnce(notification); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(progressFinished).toBe(true); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + choose?.(choice); + await Promise.all(mocks.tasks); + if (choice) { + expect(mocks.provider.focusResult).toHaveBeenCalledExactlyOnceWith(sourceUri); + } else { + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + } + expect(mocks.errors).toEqual([]); + }, + ); + + it('reports a result closed before the notification action is chosen', async () => { + mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); + mocks.provider.focusResult.mockResolvedValue(false); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + await Promise.all(mocks.tasks); + + expect(vscode.window.showInformationMessage).toHaveBeenLastCalledWith('No Query Playground result is open.'); + }); + + it.each(['notification', 'focus'])( + 'handles a failed fire-and-forget %s through the telemetry/error wrapper', + async (failure) => { + const error = new Error('Action failed'); + if (failure === 'notification') { + mocks.notificationChoice.mockRejectedValueOnce(error); + } else { + mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); + mocks.provider.focusResult.mockRejectedValue(error); + } + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + await Promise.all(mocks.tasks); + + expect(mocks.errors).toEqual([{ event: 'playground.afterRun.notify', error }]); + expect(progressFinished).toBe(true); + }, + ); + + it.each(['stay', 'focusResult', 'notify'] as const)( + 'preserves the existing error result and notification for %s', + async (afterRun) => { + const error = new Error('Query failed'); + mocks.evaluate.mockRejectedValue(error); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( + sourceUri, + expect.stringContaining('Query failed'), + ); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Query playground execution failed: Query failed', + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + expect(mocks.errors).toEqual([{ event: 'playground.execute', error }]); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + }, + ); + + it.each(['focusResult', 'notify'] as const)( + 'keeps focus and skips completion when a cancelled evaluation still succeeds (%s)', + async (afterRun) => { + mocks.evaluate.mockImplementation(async () => { + cancellation.fire(); + return result; + }); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + + expect(mocks.killWorker).toHaveBeenCalledOnce(); + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { + focus: false, + }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + }, + ); + + it('keeps focus and suppresses error/success UI when worker cancellation rejects', async () => { + mocks.evaluate.mockImplementation(async () => { + cancellation.fire(); + throw new Error('Worker killed'); + }); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(mocks.provider.showResult).not.toHaveBeenCalled(); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(mocks.errors).toEqual([ + { + event: 'playground.execute', + error: expect.objectContaining({ stepName: 'playground.execute', _isUserCancelledError: true }), + }, + ]); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + }); + + it('does not focus or notify when progress was cancelled before its callback', async () => { + token = { ...token, isCancellationRequested: true }; + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'focusResult' }); + + expect(mocks.provider.showResult).toHaveBeenCalledWith(sourceUri, expect.any(String), { focus: false }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + }); + + it('retains the existing console output hint in the result', async () => { + mocks.consoleOutputCount = 1; + + await executePlaygroundCode('print(1)', 'runAll', sourceUri); + + expect(mocks.provider.showResult).toHaveBeenCalledWith( + sourceUri, + expect.stringContaining( + '\n\n// Note: Output was printed to the "DocumentDB Query Playground Output" channel', + ), + { focus: false }, + ); + }); +}); diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index b1591d22d..aa50e79a4 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -3,341 +3,524 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'; import * as vscode from 'vscode'; -import { type ExecutionResult, type PlaygroundConnection } from '../../documentdb/playground/types'; -import { disposeEvaluators, executePlaygroundCode } from './executePlaygroundCode'; - -const mocks = vi.hoisted(() => ({ - evaluate: vi.fn<() => Promise>(), - killWorker: vi.fn(), - consoleOutputCount: 0, - provider: { showResult: vi.fn(), focusResult: vi.fn<() => Promise>() }, - service: { getConnection: vi.fn(), isExecuting: vi.fn(), setExecuting: vi.fn() }, - recordSurveyActivity: vi.fn(), - notificationChoice: vi.fn<() => Promise>(), - errors: [] as { event: string; error: unknown }[], - tasks: [] as Promise[], +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { type PlaygroundConnection } from '../../documentdb/playground/types'; +import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; + +const { + evaluate, + dispose, + setExecuting, + showResult, + getConnection, + getLatchReason, + getEpoch, + canRecover, + recover, + contexts, + createEvaluator, +} = vi.hoisted(() => ({ + evaluate: vi.fn(), + dispose: vi.fn(), + setExecuting: vi.fn(), + showResult: vi.fn(), + getConnection: vi.fn<() => PlaygroundConnection | undefined>(), + getLatchReason: vi.fn(), + getEpoch: vi.fn<() => number>(), + canRecover: vi.fn(), + recover: vi.fn(), + contexts: new Map(), + createEvaluator: vi.fn(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), callWithTelemetryAndErrorHandling: ( - event: string, - callback: (context: IActionContext) => Promise, - ): Promise => { - const context = { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; - const task = (async (): Promise => { - try { - return await callback(context); - } catch (error) { - mocks.errors.push({ event, error }); - return undefined; - } - })(); - mocks.tasks.push(task); - return task; + name: string, + run: (context: IActionContext) => Promise, + ): Promise => { + const context = { errorHandling: {}, telemetry: { measurements: {}, properties: {} } } as IActionContext; + contexts.set(name, context); + const result = run(context); + // Fire-and-forget recovery uses the real telemetry wrapper's default error suppression. + return name === 'playground.signInAgain' ? result.catch((): undefined => undefined) : result; + }, +})); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { + getLatchReason, + getExistingClient: vi.fn(), + getEpoch, + getLastVerifiedIdentity: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + getClient: vi.fn(), + startAfterSignIn: vi.fn(), + deleteClient: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + invalidate: vi.fn(), }, })); -vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getExistingClient: vi.fn() } })); -vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { getCredentials: vi.fn() } })); -vi.mock('../../documentdb/feedResultToSchemaStore', () => ({ feedResultToSchemaStore: vi.fn() })); + +vi.mock('../signInAgain/signInAgain', () => ({ + canSignInAgainForWorker: canRecover, + signInAgainForWorker: recover, +})); + vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ PlaygroundEvaluator: class { - readonly evaluate = mocks.evaluate; - readonly killWorker = mocks.killWorker; - readonly sessionEvalCount = 1; - readonly lastInitDurationMs = 0; - get lastEvalConsoleOutputCount(): number { - return mocks.consoleOutputCount; + constructor() { + createEvaluator(); } - dispose(): void {} + evaluate = evaluate; + dispose = dispose; + sessionDomainProperties = { domainInfo_isAzure: 'true' }; }, })); + vi.mock('../../documentdb/playground/PlaygroundService', () => ({ - PlaygroundService: { getInstance: (): typeof mocks.service => mocks.service }, -})); -vi.mock('../../documentdb/utils/getClusterMetadata', () => ({ addDomainInfoToProperties: vi.fn() })); -vi.mock('../../documentdb/utils/connectionStringHelpers', () => ({ getHostsFromConnectionString: vi.fn() })); -vi.mock('../../extensionVariables', () => ({ ext: { playgroundResultProvider: mocks.provider } })); -vi.mock('../../services/errorExplanationService', () => ({ - ErrorExplanationService: { explain: vi.fn().mockResolvedValue(undefined) }, + PlaygroundService: { + getInstance: () => ({ + getConnection, + isExecuting: () => false, + setExecuting, + }), + }, })); -vi.mock('../../services/survey/SurveyService', () => ({ recordSurveyActivity: mocks.recordSurveyActivity })); -vi.mock('./connectDatabase', () => ({ promptAndConnectPlayground: vi.fn() })); -describe('executePlaygroundCode after-run behavior', () => { - const sourceUri = vscode.Uri.file('/query.documentdb.js'); - const connection: PlaygroundConnection = { - clusterId: 'cluster', - clusterDisplayName: 'Cluster', - databaseName: 'db', - }; - const result: ExecutionResult = { type: 'Cursor', printable: [{ _id: 1 }, { _id: 2 }], durationMs: 5 }; - let cancellation: vscode.EventEmitter; - let progressFinished: boolean; - let token: vscode.CancellationToken; +vi.mock('../../extensionVariables', () => ({ + ext: { playgroundResultProvider: { showResult } }, +})); +describe('executePlaygroundCode', () => { beforeEach(() => { - mocks.errors.length = 0; - mocks.tasks.length = 0; - mocks.consoleOutputCount = 0; - mocks.evaluate.mockResolvedValue(result); - mocks.provider.showResult.mockResolvedValue(undefined); - mocks.provider.focusResult.mockResolvedValue(true); - mocks.service.getConnection.mockReturnValue(connection); - mocks.service.isExecuting.mockReturnValue(false); - mocks.notificationChoice.mockResolvedValue(undefined); - cancellation = new vscode.EventEmitter(); - token = { isCancellationRequested: false, onCancellationRequested: cancellation.event }; - progressFinished = false; - vi.spyOn(vscode.window, 'showInformationMessage').mockImplementation( - async ( - _message: string, - ...items: (T | vscode.MessageOptions)[] - ): Promise => { - const choice = await mocks.notificationChoice(); - return items.find((item): item is T => { - if (typeof item === 'string') { - return item === choice; - } - return typeof item === 'object' && 'title' in item && item.title === choice; - }); - }, - ); - vi.spyOn(vscode.window, 'showErrorMessage').mockResolvedValue(undefined); - vi.spyOn(vscode.window, 'withProgress').mockImplementation( - async ( - _options: vscode.ProgressOptions, - task: ( - progress: vscode.Progress<{ message?: string; increment?: number }>, - token: vscode.CancellationToken, - ) => Thenable, - ): Promise => { - try { - return await task({ report: vi.fn() }, token); - } finally { - progressFinished = true; - } - }, - ); - }); - - afterEach(() => { - cancellation.dispose(); - disposeEvaluators(); - vi.restoreAllMocks(); vi.clearAllMocks(); + contexts.clear(); + getConnection.mockReturnValue({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }); + getEpoch.mockReturnValue(0); + canRecover.mockReturnValue(false); }); - it.each([undefined, 'stay', 'focusResult', 'notify'] as const)( - 'performs only the %s success outcome', - async (afterRun) => { - await executePlaygroundCode( - 'db.test.find()', - 'runSelected', - sourceUri, - afterRun ? { afterRun } : undefined, + it.each([ + ['userDisconnected', 'This connection is disconnected. Reconnect from the tree, then run the script again.'], + ['unreachable', 'The connection is unavailable. Check the server or network, then run the script again.'], + [ + 'credentialsRejected', + 'The saved credentials were rejected. Update them from the tree, then run the script again.', + ], + ['credentialsUpdating', 'This connection is being updated. Run the script again when the update finishes.'], + ['connectionRemoved', 'This connection was removed. Choose another connection for this playground.'], + [ + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + ['credentialsMissing', 'This connection is unavailable. Reconnect from the tree, then run the script again.'], + ['signInRequired', 'This connection is unavailable. Reconnect from the tree, then run the script again.'], + ] as const)('uses %s guidance for latch and worker failures', async (reason, message) => { + getLatchReason.mockReturnValueOnce(reason); + const showWarning = vi.spyOn(vscode.window, 'showWarningMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), ); - expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( - sourceUri, - expect.stringContaining('// Result: Cursor (2 documents)'), - { focus: afterRun === 'focusResult' }, - ); - if (afterRun === 'notify') { - expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - 'Query completed: Cursor (2 documents)', - 'Focus Result', - ); - } else { - expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - } - expect(mocks.provider.focusResult).not.toHaveBeenCalled(); - expect(mocks.recordSurveyActivity).toHaveBeenCalledWith('queryPlayground'); - expect(mocks.service.setExecuting.mock.calls).toEqual([ - ['cluster', true], - ['cluster', false], - ]); - expect(progressFinished).toBe(true); - }, - ); + try { + const uri = vscode.Uri.file('test.documentdb.js'); + await executePlaygroundCode('db.stats()', 'runAll', uri); + expect(showWarning).toHaveBeenCalledExactlyOnceWith(message); + expect(evaluate).not.toHaveBeenCalled(); + expect(setExecuting).not.toHaveBeenCalled(); + + showWarning.mockClear(); + const failure = new ConnectionUnavailableError(reason); + evaluate.mockRejectedValueOnce(failure); + + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + expect(showResult).toHaveBeenCalledExactlyOnceWith(expect.anything(), expect.stringContaining(message)); + expect(evaluate).toHaveBeenCalledOnce(); + expect(showWarning).not.toHaveBeenCalled(); + } finally { + progress.mockRestore(); + showWarning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); - it('uses the approved no-return message only when the worker proves the printable was undefined', async () => { - mocks.evaluate.mockResolvedValue({ - type: null, - printable: undefined, - printableIsUndefined: true, - durationMs: 5, + it('cancels a stopped worker without replacing the retained result or showing an error', async () => { + let stopEvaluation: (error: Error) => void = () => {}; + evaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + stopEvaluation = reject; + }), + ); + dispose.mockImplementation(() => { + stopEvaluation(new Error('Worker terminated')); }); + const showError = vi.spyOn(vscode.window, 'showErrorMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); - await executePlaygroundCode('const a = 1', 'runAll', sourceUri, { afterRun: 'notify' }); - - expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( - 'Query completed without a return value.', - 'Focus Result', - ); + try { + const run = executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js'), { + afterRun: 'focusResult', + }); + expect(evaluate).toHaveBeenCalledOnce(); + stopPlaygroundEvaluator('cluster'); + await expect(run).rejects.toBeInstanceOf(UserCancelledError); + expect(showResult).not.toHaveBeenCalled(); + expect(showError).not.toHaveBeenCalled(); + expect(setExecuting).toHaveBeenLastCalledWith('cluster', false); + } finally { + progress.mockRestore(); + showError.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } }); - it.each([ - [null, 'null'], - [42, 'number'], - ] as const)( - 'truthfully announces an untyped printable %j instead of claiming no return value', - async (printable, description) => { - mocks.evaluate.mockResolvedValue({ type: null, printable, durationMs: 5 }); + it('writes one actionable result for a bounded worker failure without an unsolicited modal', async () => { + const failure = Object.assign(new Error('private callback details'), { + name: 'TokenCallbackError', + }); - await executePlaygroundCode('db.test.findOne()', 'runAll', sourceUri, { afterRun: 'notify' }); + evaluate.mockRejectedValueOnce(failure); + const showError = vi.spyOn(vscode.window, 'showErrorMessage'); + const showWarning = vi.spyOn(vscode.window, 'showWarningMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); - expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - `Query completed: ${description}`, - 'Focus Result', + try { + await expect( + executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')), + ).rejects.toBe(failure); + expect(showResult).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.stringContaining( + 'The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.', + ), ); - expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { - focus: false, - }); - }, - ); + expect(showResult.mock.calls[0][1]).not.toContain('private callback details'); + expect(showError).not.toHaveBeenCalled(); + expect(showWarning).not.toHaveBeenCalled(); + } finally { + progress.mockRestore(); + showError.mockRestore(); + showWarning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); - it.each([undefined, 'Focus Result'])( - 'finishes progress and unlocks execution before the notification choice %s', - async (choice) => { - let choose: ((value: string | undefined) => void) | undefined; - const notification = new Promise((resolve) => { - choose = resolve; + it('keeps the worker destination properties on a warm run', async () => { + const failure = Object.assign(new Error('token unavailable'), { name: 'TokenCallbackError' }); + evaluate.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + try { + const uri = vscode.Uri.file('test.documentdb.js'); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + expect(contexts.get('playground.execute')?.telemetry.properties).toMatchObject({ + isNewEvaluator: 'false', + domainInfo_isAzure: 'true', }); - mocks.notificationChoice.mockReturnValueOnce(notification); - - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); - - expect(progressFinished).toBe(true); - expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); - expect(mocks.provider.focusResult).not.toHaveBeenCalled(); - choose?.(choice); - await Promise.all(mocks.tasks); - if (choice) { - expect(mocks.provider.focusResult).toHaveBeenCalledExactlyOnceWith(sourceUri); - } else { - expect(mocks.provider.focusResult).not.toHaveBeenCalled(); - } - expect(mocks.errors).toEqual([]); - }, - ); - - it('reports a result closed before the notification action is chosen', async () => { - mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); - mocks.provider.focusResult.mockResolvedValue(false); - - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); - await Promise.all(mocks.tasks); - - expect(vscode.window.showInformationMessage).toHaveBeenLastCalledWith('No Query Playground result is open.'); + } finally { + progress.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } }); - it.each(['notification', 'focus'])( - 'handles a failed fire-and-forget %s through the telemetry/error wrapper', - async (failure) => { - const error = new Error('Action failed'); - if (failure === 'notification') { - mocks.notificationChoice.mockRejectedValueOnce(error); - } else { - mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); - mocks.provider.focusResult.mockRejectedValue(error); - } - - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); - await Promise.all(mocks.tasks); - - expect(mocks.errors).toEqual([{ event: 'playground.afterRun.notify', error }]); - expect(progressFinished).toBe(true); - }, - ); - - it.each(['stay', 'focusResult', 'notify'] as const)( - 'preserves the existing error result and notification for %s', - async (afterRun) => { - const error = new Error('Query failed'); - mocks.evaluate.mockRejectedValue(error); + it.each([false, true])('honors the sign-in epoch unless superseded (%s)', async (superseded) => { + const identity: NonNullable = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + getConnection.mockReturnValue({ + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'test', + entraIdentity: identity, + }); + canRecover.mockReturnValue(true); + recover.mockImplementationOnce(async () => { + getEpoch.mockReturnValue(superseded ? 2 : 1); + return { identity, epoch: 1 }; + }); + const failure = Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }); + evaluate.mockRejectedValueOnce(failure); + const warning = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + try { + await expect( + executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')), + ).rejects.toBe(failure); + const signInContext = contexts.get('playground.signInAgain'); + expect(signInContext).toBeDefined(); + expect(signInContext).not.toBe(contexts.get('playground.execute')); + expect(recover).toHaveBeenCalledExactlyOnceWith(signInContext, 'cluster', identity); + expect(evaluate).toHaveBeenCalledOnce(); + expect(dispose).toHaveBeenCalledTimes(superseded ? 0 : 1); + } finally { + progress.mockRestore(); + warning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); - expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( - sourceUri, - expect.stringContaining('Query failed'), + describe('stale sign-in notifications', () => { + const uri = vscode.Uri.file('test.documentdb.js'); + let connection: PlaygroundConnection; + let chooseAction: (choice: vscode.MessageItem | undefined) => void; + let warning: MockInstance; + let modal: MockInstance; + let openDocuments: vscode.TextDocument[]; + let connectionStateCalls: MockInstance[]; + + beforeEach(async (): Promise => { + connection = { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'test', + entraIdentity: { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }, + }; + getConnection.mockReturnValue(connection); + getLatchReason.mockReturnValue(undefined); + canRecover.mockReturnValue(true); + openDocuments = vscode.workspace.textDocuments as vscode.TextDocument[]; + openDocuments.push({ uri: vscode.Uri.parse(uri.toString()) } as vscode.TextDocument); + warning = vi.spyOn(vscode.window, 'showWarningMessage').mockImplementationOnce( + () => + new Promise((resolve) => { + chooseAction = resolve; + }), ); - expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - 'Query playground execution failed: Query failed', + modal = vi.spyOn(vscode.window, 'showErrorMessage'); + vi.spyOn(vscode.window, 'withProgress').mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), ); - expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(mocks.provider.focusResult).not.toHaveBeenCalled(); - expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); - expect(mocks.errors).toEqual([{ event: 'playground.execute', error }]); - expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); - }, - ); + const failure = Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }); + evaluate.mockRejectedValueOnce(failure); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + connectionStateCalls = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'setCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'clearLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'startAfterSignIn'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(ClustersClient, 'latch'), + vi.spyOn(ClustersClient, 'unlatch'), + vi.spyOn(ClustersClient, 'invalidate'), + ]; + }); - it.each(['focusResult', 'notify'] as const)( - 'keeps focus and skips completion when a cancelled evaluation still succeeds (%s)', - async (afterRun) => { - mocks.evaluate.mockImplementation(async () => { - cancellation.fire(); - return result; - }); + afterEach((): void => { + stopPlaygroundEvaluator('cluster'); + openDocuments.splice(0); + vi.restoreAllMocks(); + }); - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + it.each([ + [ + 'before click', + 'connectionRemoved', + 'This connection was removed. Choose another connection for this playground.', + ], + [ + 'before click', + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'before click', + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'during sign-in', + 'connectionRemoved', + 'This connection was removed. Choose another connection for this playground.', + ], + [ + 'during sign-in', + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'during sign-in', + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + ] as const)('explains %s %s for the existing document only', async (stage, reason, message): Promise => { + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue(reason); + } else { + recover.mockImplementationOnce(async (): Promise => { + getLatchReason.mockReturnValue(reason); + return undefined; + }); + } - expect(mocks.killWorker).toHaveBeenCalledOnce(); - expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { - focus: false, - }); - expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); - expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); - }, - ); + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(warning).toHaveBeenCalledTimes(2)); - it('keeps focus and suppresses error/success UI when worker cancellation rejects', async () => { - mocks.evaluate.mockImplementation(async () => { - cancellation.fire(); - throw new Error('Worker killed'); + expect(warning).toHaveBeenNthCalledWith( + 1, + 'Microsoft sign-in is required for this playground. Sign in again to continue.', + 'Sign in again', + ); + expect(warning).toHaveBeenNthCalledWith(2, message); + expect(modal).not.toHaveBeenCalled(); + expect(recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(evaluate).toHaveBeenCalledOnce(); + expect(createEvaluator).toHaveBeenCalledOnce(); + expect(dispose).not.toHaveBeenCalled(); + expect(showResult).toHaveBeenCalledOnce(); + expect(getConnection()).toBe(connection); + expect(canRecover).toHaveBeenCalledTimes(2); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } }); - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + it.each([ + ['before click', 'cancelled'], + ['before click', 'closed'], + ['before click', 'disposed'], + ['before click', 'epoch only'], + ['before click', 'unproven no latch'], + ['before click', 're-picked healthy'], + ['before click', 're-picked removed'], + ['before click', 're-picked changed'], + ['before click', 'already completed'], + ['during sign-in', 'cancelled'], + ['during sign-in', 'closed'], + ['during sign-in', 'disposed'], + ['during sign-in', 'epoch only'], + ['during sign-in', 'unproven no latch'], + ['during sign-in', 're-picked healthy'], + ['during sign-in', 're-picked removed'], + ['during sign-in', 're-picked changed'], + ['during sign-in', 'already completed'], + ] as const)( + 'keeps %s %s quiet without replacing the worker or result', + async (stage, outcome): Promise => { + const supersede = (): void => { + if (outcome === 'closed' || outcome === 'disposed') { + openDocuments.splice(0); + openDocuments.push({ uri: vscode.Uri.file('another.documentdb.js') } as vscode.TextDocument); + } + if (outcome === 'disposed') { + stopPlaygroundEvaluator('cluster'); + dispose.mockClear(); + } + if ( + outcome === 're-picked healthy' || + outcome === 're-picked removed' || + outcome === 're-picked changed' || + outcome === 'unproven no latch' + ) { + getConnection.mockReturnValue({ + ...connection, + clusterId: 'healthy-cluster', + entraIdentity: undefined, + }); + } + getEpoch.mockReturnValue(2); + getLatchReason.mockReturnValue( + outcome === 'closed' || + outcome === 'disposed' || + outcome === 'cancelled' || + outcome === 're-picked removed' + ? 'connectionRemoved' + : outcome === 're-picked changed' + ? 'credentialsChanged' + : undefined, + ); + }; + if (stage === 'before click') { + supersede(); + } else { + recover.mockImplementationOnce(async () => { + supersede(); + if (outcome === 'cancelled') { + throw new UserCancelledError('playground.signInAgain'); + } + return outcome === 'unproven no latch' + ? undefined + : { identity: connection.entraIdentity, epoch: 1 }; + }); + } - expect(mocks.provider.showResult).not.toHaveBeenCalled(); - expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); - expect(mocks.errors).toEqual([ - { - event: 'playground.execute', - error: expect.objectContaining({ stepName: 'playground.execute', _isUserCancelledError: true }), + chooseAction( + stage === 'before click' && outcome === 'cancelled' + ? undefined + : ('Sign in again' as unknown as vscode.MessageItem), + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(warning).toHaveBeenCalledOnce(); + expect(modal).not.toHaveBeenCalled(); + expect(recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(evaluate).toHaveBeenCalledOnce(); + expect(createEvaluator).toHaveBeenCalledOnce(); + expect(dispose).not.toHaveBeenCalled(); + expect(showResult).toHaveBeenCalledOnce(); + expect(canRecover).toHaveBeenCalledTimes(2); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } }, - ]); - expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); - }); - - it('does not focus or notify when progress was cancelled before its callback', async () => { - token = { ...token, isCancellationRequested: true }; - - await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'focusResult' }); - - expect(mocks.provider.showResult).toHaveBeenCalledWith(sourceUri, expect.any(String), { focus: false }); - expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); - }); - - it('retains the existing console output hint in the result', async () => { - mocks.consoleOutputCount = 1; - - await executePlaygroundCode('print(1)', 'runAll', sourceUri); - - expect(mocks.provider.showResult).toHaveBeenCalledWith( - sourceUri, - expect.stringContaining( - '\n\n// Note: Output was printed to the "DocumentDB Query Playground Output" channel', - ), - { focus: false }, ); }); }); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index d6e7ea71d..e0518b203 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -11,20 +11,20 @@ import { import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; -import { CredentialCache } from '../../documentdb/CredentialCache'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { feedResultToSchemaStore } from '../../documentdb/feedResultToSchemaStore'; import { type PlaygroundAfterRunOutcome } from '../../documentdb/playground/afterRun'; import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { describeCompletion, formatError, formatResult } from '../../documentdb/playground/resultFormatter'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; +import { getWorkerAuthReason, type WorkerAuthReason } from '../../documentdb/playground/workerTypes'; import { extractErrorCode } from '../../documentdb/shell/ShellOutputFormatter'; -import { getHostsFromConnectionString } from '../../documentdb/utils/connectionStringHelpers'; -import { addDomainInfoToProperties } from '../../documentdb/utils/getClusterMetadata'; import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; import { recordSurveyActivity } from '../../services/survey/SurveyService'; import { classifyCodeBlock } from '../../utils/classifyCommand'; +import { canSignInAgainForWorker, signInAgainForWorker } from '../signInAgain/signInAgain'; import { promptAndConnectPlayground } from './connectDatabase'; /** Per-cluster evaluator pool — one worker per cluster, lazily created. */ @@ -54,6 +54,17 @@ export function shutdownEvaluator(clusterId: string): void { } } +/** Stop an evaluator immediately without changing the open documents or their bindings. */ +export function stopPlaygroundEvaluator(clusterId: string): void { + const evaluator = evaluators.get(clusterId); + evaluators.delete(clusterId); + evaluator?.dispose(); +} + +export function clearRemovedPlaygroundConnections(clusterId: string): void { + PlaygroundService.getInstance().removeConnectionsForCluster(clusterId); +} + /** * Shut down all evaluators that have no remaining open playground documents. * Called when playground documents close or state changes. @@ -120,9 +131,18 @@ export async function executePlaygroundCode( return; // user cancelled the connection picker } } + let boundConnection: PlaygroundConnection = connection; + + const { clusterId } = boundConnection; + const latchReason = ClustersClient.getLatchReason(clusterId); + if (latchReason) { + const recovery = getPlaygroundRecovery(new ConnectionUnavailableError(latchReason), connection); + void vscode.window.showWarningMessage(recovery?.message ?? l10n.t('This connection is unavailable.')); + return; + } // Prevent concurrent runs on the same cluster — no queuing - if (service.isExecuting(connection.clusterId)) { + if (service.isExecuting(boundConnection.clusterId)) { void vscode.window.showInformationMessage( l10n.t('A playground is already running on this cluster. Wait for it to finish.'), ); @@ -130,14 +150,14 @@ export async function executePlaygroundCode( } // Get or create the evaluator for this cluster - let evaluator = evaluators.get(connection.clusterId); + let evaluator = evaluators.get(boundConnection.clusterId); const isNewEvaluator = !evaluator; if (!evaluator) { evaluator = new PlaygroundEvaluator(); - evaluators.set(connection.clusterId, evaluator); + evaluators.set(boundConnection.clusterId, evaluator); } - service.setExecuting(connection.clusterId, true); + service.setExecuting(boundConnection.clusterId, true); // callWithTelemetryAndErrorHandling automatically tracks: // - duration (measured from callback start to end) @@ -166,14 +186,9 @@ export async function executePlaygroundCode( context.telemetry.measurements[`cmd_${category}`] = count; } - // Domain info — privacy-safe hashed host data for platform analytics - const domainProps: Record = {}; - collectDomainTelemetry(connection, domainProps); - Object.assign(context.telemetry.properties, domainProps); - // Link to server metadata via connectionCorrelationId try { - const existingClient = ClustersClient.getExistingClient(connection.clusterId); + const existingClient = ClustersClient.getExistingClient(boundConnection.clusterId); if (existingClient?.connectionCorrelationId) { context.telemetry.properties.connectionCorrelationId = existingClient.connectionCorrelationId; } @@ -202,10 +217,24 @@ export async function executePlaygroundCode( const sourceUri = documentUri; try { - const result = await evaluator!.evaluate(connection, code, (message) => { - progress.report({ message }); - }); + if (evaluators.get(clusterId) !== evaluator) { + throw new UserCancelledError('playground.execute'); + } + const result = await evaluator!.evaluate( + boundConnection, + code, + (message) => { + progress.report({ message }); + }, + (binding) => { + boundConnection = + service.captureWorkerBinding(documentUri, boundConnection, binding) ?? boundConnection; + }, + ); + if (evaluators.get(clusterId) !== evaluator) { + return; + } // ── Post-execution telemetry (known after success) ──── context.telemetry.properties.resultType = result.type ?? 'null'; context.telemetry.measurements.initDurationMs = evaluator!.lastInitDurationMs; @@ -214,8 +243,8 @@ export async function executePlaygroundCode( context.telemetry.measurements.sessionEvalCount = evaluator!.sessionEvalCount; context.telemetry.properties.authMethod = evaluator!.sessionAuthMethod ?? 'unknown'; - let formattedOutput = formatResult(result, code, connection); - feedResultToSchemaStore(result, connection.clusterId); + let formattedOutput = formatResult(result, code, boundConnection); + feedResultToSchemaStore(result, boundConnection.clusterId); // If console output was produced, append a hint to check the output channel if (evaluator!.lastEvalConsoleOutputCount > 0) { @@ -252,13 +281,16 @@ export async function executePlaygroundCode( } // result: 'Succeeded' is set automatically by the framework } catch (error: unknown) { + if (error instanceof UserCancelledError) { + throw error; + } // Update session telemetry even on failure (worker may have spawned before failing) context.telemetry.properties.sessionId = evaluator!.sessionId ?? 'none'; context.telemetry.measurements.sessionEvalCount = evaluator!.sessionEvalCount; context.telemetry.properties.authMethod = evaluator!.sessionAuthMethod ?? 'unknown'; context.telemetry.measurements.initDurationMs = evaluator!.lastInitDurationMs; - if (cancelled) { + if (cancelled || evaluators.get(clusterId) !== evaluator) { // Throw UserCancelledError so framework marks result as 'Canceled' throw new UserCancelledError('playground.execute'); } @@ -269,14 +301,21 @@ export async function executePlaygroundCode( // the extracted code is preserved for future telemetry. const { message: errorMessage } = extractErrorCode(rawMessage); const durationMs = Date.now() - startTime; - const formattedOutput = formatError(error, code, durationMs, connection); + const recovery = getPlaygroundRecovery(error, boundConnection); + const displayError = recovery ? new Error(recovery.message) : error; + const formattedOutput = formatError(displayError, code, durationMs, boundConnection); if (sourceUri) { await ext.playgroundResultProvider.showResult(sourceUri, formattedOutput); } + if (recovery) { + offerPlaygroundRecovery(sourceUri, boundConnection, recovery); + throw error; + } + const explanation = await ErrorExplanationService.explain({ - clusterId: connection.clusterId, + clusterId: boundConnection.clusterId, error, }); @@ -288,31 +327,175 @@ export async function executePlaygroundCode( // error, and errorMessage in telemetry throw error; } finally { - service.setExecuting(connection.clusterId, false); + Object.assign(context.telemetry.properties, evaluator?.sessionDomainProperties); + service.setExecuting(boundConnection.clusterId, false); } }, ); }); } -// ─── Domain telemetry ──────────────────────────────────────────────────────── +interface PlaygroundRecovery { + readonly message: string; + readonly authReason?: WorkerAuthReason; +} -/** - * Collects domain info from the query playground connection's cached credentials. - * Reuses the same hashing logic as the connection metadata telemetry. - */ -function collectDomainTelemetry( +function getPlaygroundRecovery(error: unknown, connection: PlaygroundConnection): PlaygroundRecovery | undefined { + const authReason = getWorkerAuthReason(error); + if (authReason) { + switch (authReason) { + case 'signInRequired': + return { + authReason, + message: + connection.entraIdentity && + canSignInAgainForWorker(connection.clusterId, connection.entraIdentity) + ? l10n.t('Microsoft sign-in is required for this playground. Sign in again to continue.') + : l10n.t( + 'Microsoft sign-in is required for this playground. Re-pick its connection from the tree.', + ), + }; + case 'identityMismatch': + return { + authReason, + message: l10n.t( + 'This playground is bound to a different Microsoft account. Re-pick its connection from the tree.', + ), + }; + case 'destinationRejected': + return { + authReason, + message: l10n.t( + 'This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.', + ), + }; + case 'refreshFailed': + return { + authReason, + message: l10n.t( + 'The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.', + ), + }; + } + } + + if (!(error instanceof ConnectionUnavailableError)) { + return undefined; + } + if (error.reason === 'credentialsChanged' || error.reason === 'identityChanged') { + return { + message: l10n.t( + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ), + }; + } + if (error.reason === 'userDisconnected') { + return { + message: l10n.t('This connection is disconnected. Reconnect from the tree, then run the script again.'), + }; + } + if (error.reason === 'unreachable') { + return { + message: l10n.t('The connection is unavailable. Check the server or network, then run the script again.'), + }; + } + if (error.reason === 'credentialsRejected') { + return { + message: l10n.t( + 'The saved credentials were rejected. Update them from the tree, then run the script again.', + ), + }; + } + if (error.reason === 'credentialsUpdating') { + return { + message: l10n.t('This connection is being updated. Run the script again when the update finishes.'), + }; + } + if (error.reason === 'connectionRemoved') { + return { + message: l10n.t('This connection was removed. Choose another connection for this playground.'), + }; + } + return { + message: l10n.t('This connection is unavailable. Reconnect from the tree, then run the script again.'), + }; +} + +function offerPlaygroundRecovery( + documentUri: vscode.Uri, connection: PlaygroundConnection, - properties: Record, + recovery: PlaygroundRecovery, ): void { - try { - const credentials = CredentialCache.getCredentials(connection.clusterId); - if (!credentials?.connectionString) { + if ( + recovery.authReason !== 'signInRequired' || + !connection.entraIdentity || + !canSignInAgainForWorker(connection.clusterId, connection.entraIdentity) + ) { + return; + } + const identity = connection.entraIdentity; + const { clusterId } = connection; + const service = PlaygroundService.getInstance(); + const evaluator = evaluators.get(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const stillOwnsAction = (): boolean => + service.getConnection(documentUri) === connection && + evaluators.get(clusterId) === evaluator && + !service.isExecuting(clusterId); + const action = l10n.t('Sign in again'); + void vscode.window.showWarningMessage(recovery.message, action).then(async (choice) => { + if (choice !== action || ClustersClient.getEpoch(clusterId) !== epoch || !stillOwnsAction()) { + if ( + choice === action && + service.getConnection(documentUri) === connection && + vscode.workspace.textDocuments.some((d) => d.uri.toString() === documentUri.toString()) + ) { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { + const currentRecovery = getPlaygroundRecovery(new ConnectionUnavailableError(reason), connection); + if (currentRecovery) { + void vscode.window.showWarningMessage(currentRecovery.message); + } + } + } return; } - const hosts = getHostsFromConnectionString(credentials.connectionString); - addDomainInfoToProperties(hosts, properties); - } catch { - // Domain info is best-effort — don't fail telemetry if parsing fails - } + await callWithTelemetryAndErrorHandling('playground.signInAgain', async (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.properties.sessionId = evaluator?.sessionId ?? 'none'; + try { + const result = await signInAgainForWorker(context, clusterId, identity); + if (!result || ClustersClient.getEpoch(clusterId) !== result.epoch || !stillOwnsAction()) { + if ( + service.getConnection(documentUri) === connection && + vscode.workspace.textDocuments.some((d) => d.uri.toString() === documentUri.toString()) + ) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + const currentRecovery = getPlaygroundRecovery( + new ConnectionUnavailableError(reason), + connection, + ); + if (currentRecovery) { + void vscode.window.showWarningMessage(currentRecovery.message); + } + } + } + return; + } + stopPlaygroundEvaluator(clusterId); + } catch (error) { + if (!(error instanceof UserCancelledError) && stillOwnsAction()) { + void vscode.window.showWarningMessage( + l10n.t('Could not sign in again. Re-pick the playground connection from the tree.'), + ); + } + throw error; + } + }); + }); } diff --git a/src/commands/playground/newPlayground.test.ts b/src/commands/playground/newPlayground.test.ts index 32a6573a2..bad626229 100644 --- a/src/commands/playground/newPlayground.test.ts +++ b/src/commands/playground/newPlayground.test.ts @@ -3,12 +3,14 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { createTestActionContext, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { createTextDocument } from 'jest-mock-vscode'; import * as vscode from 'vscode'; import { modifierKey } from '../../constants'; -import { type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { ClustersClient, type ConnectionBinding, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../../documentdb/connectionBindingRetirement'; import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { DocumentDBExperience } from '../../DocumentDBExperiences'; @@ -19,8 +21,13 @@ import { createPlaygroundFileName, newPlayground, newPlaygroundWithContent, + type PlaygroundHandoffOrigin, } from './newPlayground'; +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { trace: vi.fn() } }, +})); + function playgroundDocument(fileName: string): vscode.TextDocument { return { fileName, @@ -43,13 +50,232 @@ function javascriptDocument(fileName: string): vscode.TextDocument { } as vscode.TextDocument; } +describe('Playground origin handoffs', () => { + let sequence = 0; + let context: IActionContext; + let binding: ConnectionBinding; + let service: PlaygroundService; + let doc: vscode.TextDocument; + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + } as const; + + beforeEach(async (): Promise => { + context = await createTestActionContext(); + binding = { clusterId: `playground-handoff-${++sequence}`, fingerprint: 'original', generation: 1 }; + const uri = vscode.Uri.parse(`untitled:handoff-${sequence}.documentdb.js`); + doc = createTextDocument(uri, "db.getCollection('records').find({})", PLAYGROUND_LANGUAGE_ID); + vi.spyOn(vscode.Uri, 'file').mockReturnValue(uri); + vi.spyOn(vscode.workspace, 'applyEdit').mockClear().mockResolvedValue(true); + vi.spyOn(vscode.workspace, 'openTextDocument').mockClear().mockResolvedValue(doc); + vi.spyOn(vscode.window, 'showTextDocument') + .mockClear() + .mockResolvedValue({ document: doc } as vscode.TextEditor); + vi.spyOn(vscode.window, 'showWarningMessage').mockClear().mockResolvedValue(undefined); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(binding); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(identity); + vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue(binding.fingerprint); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue(undefined); + service = PlaygroundService.getInstance(); + vi.spyOn(service, 'setConnectionFromHost'); + vi.spyOn(service, 'removeConnection'); + }); + + afterEach((): void => { + service.dispose(); + vi.restoreAllMocks(); + }); + + function open(origin: PlaygroundHandoffOrigin): Promise { + return newPlaygroundWithContent(context, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + content: "db.getCollection('records').find({})", + origin, + }); + } + + function treeNode(): DatabaseItem { + return { + cluster: { clusterId: binding.clusterId, name: 'Cluster', viewId: 'connectionsView' }, + databaseInfo: { name: 'database' }, + experience: { api: 'DocumentDB' }, + } as unknown as DatabaseItem; + } + + it.each([ + ['binding', 'open', 'different'], + ['binding', 'show', 'same'], + ['tree', 'open', 'same'], + ['tree', 'show', 'different'], + ['shell', 'open', 'different'], + ['shell', 'show', 'same'], + ['binding', 'show', 'disconnect'], + ['saved', 'open', 'same'], + ] as const)( + 'leaves the %s draft unbound when %s pauses across %s explicit session end', + async (source, boundary, replacement): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + if (boundary === 'open') { + vi.mocked(vscode.workspace.openTextDocument).mockImplementationOnce(async () => { + await pause; + return doc; + }); + } else { + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document: doc } as vscode.TextEditor; + }); + } + let shellCurrent = true; + let origin: PlaygroundHandoffOrigin = { kind: 'binding', binding, entraIdentity: identity }; + if (source === 'shell') { + origin = { + kind: 'shell', + fingerprint: binding.fingerprint, + entraIdentity: identity, + isCurrent: () => shellCurrent, + }; + } else if (source === 'saved') { + origin = { kind: 'saved', epoch: 1 }; + } + const pending = source === 'tree' ? newPlayground(context, treeNode()) : open(origin); + await vi.waitFor(() => + expect( + boundary === 'open' ? vscode.workspace.openTextDocument : vscode.window.showTextDocument, + ).toHaveBeenCalledOnce(), + ); + // Simulate the open-document listener restoring a remembered untitled binding. + service.setConnection(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + retireConnectionBindings(binding.clusterId, binding.generation); + shellCurrent = false; + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + if (replacement === 'disconnect') { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + } else { + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + ...binding, + fingerprint: replacement === 'different' ? 'replacement' : binding.fingerprint, + generation: 2, + }); + } + release(); + await pending; + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.removeConnection).toHaveBeenCalledExactlyOnceWith(doc.uri); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(vscode.workspace.applyEdit).toHaveBeenCalledOnce(); + expect(vscode.window.showTextDocument).toHaveBeenCalledWith(doc, { preview: true }); + expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + }, + ); + + it.each(['binding', 'shell'] as const)( + 'preserves the original %s pin across same-account repair during document display', + async (source): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document: doc } as vscode.TextEditor; + }); + const pending = open( + source === 'binding' + ? { kind: 'binding', binding, entraIdentity: identity } + : { + kind: 'shell', + fingerprint: binding.fingerprint, + entraIdentity: identity, + isCurrent: () => true, + }, + ); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('signInRequired'); + release(); + await pending; + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)).toMatchObject({ + fingerprint: binding.fingerprint, + entraIdentity: identity, + }); + expect(service.removeConnection).not.toHaveBeenCalled(); + }, + ); + + it('never binds an anonymous handoff or retains its restored authenticated binding', async (): Promise => { + service.setConnection(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + await open({ kind: 'none' }); + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(ClustersClient.getExpectedFingerprint).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + }); + + it('binds a normal saved tree selection once through the existing host capture API', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValueOnce(undefined); + await newPlayground(context, treeNode()); + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)?.fingerprint).toBe(binding.fingerprint); + }); + + it('still permits an explicit connection re-pick after rejecting an old handoff', async (): Promise => { + retireConnectionBindings(binding.clusterId, binding.generation); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + ...binding, + fingerprint: 'replacement', + generation: 2, + }); + await open({ kind: 'binding', binding, entraIdentity: identity }); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + + const replacementIdentity = { ...identity, accountId: 'replacement-account' }; + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(replacementIdentity); + service.setConnectionFromHost(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)).toMatchObject({ + fingerprint: 'replacement', + entraIdentity: replacementIdentity, + }); + }); +}); + describe('createPlaygroundFileName', () => { it('uses cluster and collection context when provided', () => { const fileName = createPlaygroundFileName([], { clusterDisplayName: 'my-cluster', databaseOrCollectionName: 'users', }); - expect(fileName).toBe('my-cluster_users.documentdb.js'); }); @@ -163,6 +389,7 @@ describe('buildPlaygroundHeader', () => { clusterDisplayName: 'content-cluster', databaseName: 'database', content: 'db.users.find({})', + origin: { kind: 'saved', epoch: ClustersClient.getEpoch('cluster-id') }, }); expect(insertedContent).toHaveLength(2); diff --git a/src/commands/playground/newPlayground.ts b/src/commands/playground/newPlayground.ts index 3a9e34d14..ae0809f90 100644 --- a/src/commands/playground/newPlayground.ts +++ b/src/commands/playground/newPlayground.ts @@ -9,8 +9,11 @@ import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { modifierKey } from '../../constants'; -import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { type VerifiedEntraIdentity } from '../../documentdb/auth/AuthHandler'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { isRetiredConnectionBinding } from '../../documentdb/connectionBindingRetirement'; import { PLAYGROUND_FILE_EXTENSION } from '../../documentdb/playground/constants'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; @@ -21,6 +24,12 @@ interface PlaygroundFileNameContext { readonly databaseOrCollectionName: string; } +export type PlaygroundHandoffOrigin = + | { kind: 'binding'; binding: ConnectionBinding; entraIdentity?: VerifiedEntraIdentity; signal?: AbortSignal } + | { kind: 'shell'; fingerprint: string; entraIdentity?: VerifiedEntraIdentity; isCurrent: () => boolean } + | { kind: 'saved'; epoch: number } + | { kind: 'none' }; + export function buildPlaygroundHeader(clusterName: string): string[] { return [ `// Query Playground: ${clusterName}`, @@ -47,6 +56,11 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem ); return; } + const binding = ClustersClient.getBinding(node.cluster.clusterId); + const identity = binding ? ClustersClient.getLastVerifiedIdentity(node.cluster.clusterId) : undefined; + const origin: PlaygroundHandoffOrigin = binding + ? { kind: 'binding', binding, entraIdentity: identity?.kind === 'entra' ? identity : undefined } + : { kind: 'saved', epoch: ClustersClient.getEpoch(node.cluster.clusterId) }; // ── Telemetry: activation source & context ─────────────────────── context.telemetry.properties.activationSource ??= 'treeNode'; @@ -71,6 +85,7 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem databaseName: node.databaseInfo.name, viewId: node.cluster.viewId, }, + origin, isCollectionItem(node) ? node.collectionInfo.name : undefined, ); } @@ -80,6 +95,7 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem * Used by cross-feature navigation links (Collection View → Playground, Shell → Playground). */ export interface NewPlaygroundWithContentParams { + readonly origin: PlaygroundHandoffOrigin; readonly clusterId: string; readonly clusterDisplayName: string; readonly databaseName: string; @@ -107,12 +123,16 @@ export async function newPlaygroundWithContent( const template = [...buildPlaygroundHeader(params.clusterDisplayName), params.content, ''].join('\n'); - await createPlaygroundWithContent(template, { - clusterId: params.clusterId, - clusterDisplayName: params.clusterDisplayName, - databaseName: params.databaseName, - viewId: params.viewId, - }); + await createPlaygroundWithContent( + template, + { + clusterId: params.clusterId, + clusterDisplayName: params.clusterDisplayName, + databaseName: params.databaseName, + viewId: params.viewId, + }, + params.origin, + ); } /** @@ -121,6 +141,7 @@ export async function newPlaygroundWithContent( async function createPlaygroundWithContent( content: string, connection: PlaygroundConnection, + origin: PlaygroundHandoffOrigin, collectionName?: string, ): Promise { const service = PlaygroundService.getInstance(); @@ -141,8 +162,46 @@ async function createPlaygroundWithContent( const doc = await vscode.workspace.openTextDocument(uri); await vscode.window.showTextDocument(doc, { preview: true }); - // Bind connection to this specific document - service.setConnection(doc.uri, connection); + let current = false; + switch (origin.kind) { + case 'binding': { + const hostBinding = ClustersClient.getBinding(connection.clusterId); + current = + !origin.signal?.aborted && + !isRetiredConnectionBinding(origin.binding) && + (!hostBinding || hostBinding.fingerprint === origin.binding.fingerprint); + connection = { + ...connection, + fingerprint: origin.binding.fingerprint, + entraIdentity: origin.entraIdentity, + }; + break; + } + case 'shell': + current = + origin.isCurrent() && + ClustersClient.getExpectedFingerprint(connection.clusterId, origin.entraIdentity) === + origin.fingerprint; + connection = { ...connection, fingerprint: origin.fingerprint, entraIdentity: origin.entraIdentity }; + break; + case 'saved': + current = + ClustersClient.getEpoch(connection.clusterId) === origin.epoch && + !ClustersClient.getLatchReason(connection.clusterId); + break; + case 'none': + break; + } + if (!current) { + service.removeConnection(doc.uri); + if (origin.kind !== 'none') { + void vscode.window.showWarningMessage( + l10n.t('This playground is bound to the previous connection. Re-pick its connection from the tree.'), + ); + } + return; + } + service.setConnectionFromHost(doc.uri, connection); } function isCollectionItem(node: DatabaseItem | CollectionItem | undefined): node is CollectionItem { diff --git a/src/commands/refreshTreeElement/refreshTreeElement.test.ts b/src/commands/refreshTreeElement/refreshTreeElement.test.ts new file mode 100644 index 000000000..e6cf6dd76 --- /dev/null +++ b/src/commands/refreshTreeElement/refreshTreeElement.test.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { expect, it, vi } from 'vitest'; +import { ext } from '../../extensionVariables'; +import { refreshTreeElement } from './refreshTreeElement'; + +vi.mock('../../extensionVariables', () => ({ + ext: { discoveryBranchDataProvider: { refresh: vi.fn() } }, +})); + +it('marks a node for an explicit reload before refreshing that node', async () => { + const node = { + id: 'discoveryView/azure', + contextValue: 'discoveryView', + getTreeItem: vi.fn(), + prepareExplicitReload: vi.fn(), + }; + + await refreshTreeElement({} as IActionContext, node); + + expect(node.prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(node.prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(ext.discoveryBranchDataProvider.refresh)); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); +}); diff --git a/src/commands/refreshTreeElement/refreshTreeElement.ts b/src/commands/refreshTreeElement/refreshTreeElement.ts index 5a7fcb077..aa92ad262 100644 --- a/src/commands/refreshTreeElement/refreshTreeElement.ts +++ b/src/commands/refreshTreeElement/refreshTreeElement.ts @@ -7,12 +7,17 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { l10n } from 'vscode'; import { ext } from '../../extensionVariables'; import { type TreeElement } from '../../tree/TreeElement'; +import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; export async function refreshTreeElement(context: IActionContext, node: TreeElement): Promise { if (!node) { throw new Error(l10n.t('No node selected.')); } + if (isTreeElementWithExplicitReload(node)) { + node.prepareExplicitReload(); + } + if (node && 'refresh' in node && typeof node.refresh === 'function') { await node.refresh.call(node, context); return; diff --git a/src/commands/refreshView/refreshView.test.ts b/src/commands/refreshView/refreshView.test.ts new file mode 100644 index 000000000..f33bf7c94 --- /dev/null +++ b/src/commands/refreshView/refreshView.test.ts @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { expect, it, vi } from 'vitest'; +import { Views } from '../../documentdb/Views'; +import { ext } from '../../extensionVariables'; +import { getVisibleDiscoveryProviders } from '../../services/discoveryProviderVisibility'; +import { DiscoveryService } from '../../services/discoveryServices'; +import { refreshView } from './refreshView'; + +vi.mock('../../extensionVariables', () => ({ + ext: { discoveryBranchDataProvider: { refresh: vi.fn() } }, +})); +vi.mock('../../services/discoveryProviderVisibility', () => ({ + getVisibleDiscoveryProviders: vi.fn(), +})); + +it('marks visible Discovery providers before refreshing the view', async () => { + const prepareExplicitReload = vi.fn(); + const azureProvider = { + id: 'azure', + label: 'Azure', + description: '', + iconPath: undefined, + getDiscoveryWizard: vi.fn(), + getDiscoveryTreeRootItem: vi.fn(), + prepareExplicitReload, + }; + const otherProvider = { ...azureProvider, id: 'other', prepareExplicitReload: undefined }; + const hiddenProvider = { ...azureProvider, id: 'hidden', prepareExplicitReload: vi.fn() }; + for (const provider of [azureProvider, otherProvider, hiddenProvider]) { + DiscoveryService.registerProvider(provider); + } + vi.mocked(getVisibleDiscoveryProviders).mockResolvedValue([azureProvider, otherProvider]); + + await refreshView({} as IActionContext, Views.DiscoveryView); + + expect(prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(ext.discoveryBranchDataProvider.refresh)); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(); + expect(hiddenProvider.prepareExplicitReload).not.toHaveBeenCalled(); +}); diff --git a/src/commands/refreshView/refreshView.ts b/src/commands/refreshView/refreshView.ts index 75fbab833..2967c4c50 100644 --- a/src/commands/refreshView/refreshView.ts +++ b/src/commands/refreshView/refreshView.ts @@ -6,6 +6,8 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { getVisibleDiscoveryProviders } from '../../services/discoveryProviderVisibility'; +import { DiscoveryService } from '../../services/discoveryServices'; export async function refreshView(_context: IActionContext, view: Views): Promise { switch (view) { @@ -13,6 +15,9 @@ export async function refreshView(_context: IActionContext, view: Views): Promis ext.connectionsBranchDataProvider.refresh(); break; case Views.DiscoveryView: + for (const { id } of await getVisibleDiscoveryProviders()) { + DiscoveryService.getProvider(id)?.prepareExplicitReload?.(); + } ext.discoveryBranchDataProvider.refresh(); break; default: diff --git a/src/commands/removeConnection/removeConnection.ts b/src/commands/removeConnection/removeConnection.ts index c889a2d78..49d211171 100644 --- a/src/commands/removeConnection/removeConnection.ts +++ b/src/commands/removeConnection/removeConnection.ts @@ -6,8 +6,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; -import { CredentialCache } from '../../documentdb/CredentialCache'; -import { SchemaStore } from '../../documentdb/SchemaStore'; +import { withConnectionRemoval } from '../../documentdb/connectionTeardown'; import { ext } from '../../extensionVariables'; import { ConnectionStorageService } from '../../services/connectionStorageService'; import { checkCanProceedAndInformUser } from '../../services/taskService/resourceUsageHelper'; @@ -75,33 +74,41 @@ export async function removeConnection( let successCount = 0; let failureCount = 0; - await withConnectionsViewProgress(async () => { - for (const connection of connectionsToDelete) { - try { - await ext.state.showDeleting(connection.id, async () => { - await ConnectionStorageService.delete(resolveStorageZone(connection.cluster), connection.storageId); + try { + await withConnectionRemoval( + connectionsToDelete.map((connection) => connection.cluster.clusterId), + async (remove) => { + await withConnectionsViewProgress(async () => { + for (const connection of connectionsToDelete) { + try { + await remove(connection.cluster.clusterId, async () => { + await ext.state.showDeleting(connection.id, async () => { + await ConnectionStorageService.delete( + resolveStorageZone(connection.cluster), + connection.storageId, + ); + }); + }); + successCount++; + } catch (error) { + failureCount++; + const errorMessage = error instanceof Error ? error.message : String(error); + ext.outputChannel.error( + l10n.t('Failed to remove connection "{connectionName}": {error}', { + connectionName: connection.cluster.name, + error: errorMessage, + }), + ); + } + } }); - - // delete cached credentials from memory using stable clusterId (not treeId) - CredentialCache.deleteCredentials(connection.cluster.clusterId); - - // clear cached schema data for this cluster - SchemaStore.getInstance().clearCluster(connection.cluster.clusterId); - - refreshParentInConnectionsView(connection.id); - successCount++; - } catch (error) { - failureCount++; - const errorMessage = error instanceof Error ? error.message : String(error); - ext.outputChannel.error( - l10n.t('Failed to remove connection "{connectionName}": {error}', { - connectionName: connection.cluster.name, - error: errorMessage, - }), - ); - } + }, + ); + } finally { + for (const connection of connectionsToDelete) { + refreshParentInConnectionsView(connection.id); } - }); + } context.telemetry.measurements.connectionsDeleted = successCount; context.telemetry.measurements.errorCount = failureCount; diff --git a/src/commands/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/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index e037391e8..32e580425 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -5,7 +5,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import type * as vscode from 'vscode'; +import { commands, window } from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { DEFAULT_ALIAS, clusterId as quickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; +import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; vi.mock('../../extensionVariables', () => ({ @@ -30,17 +39,29 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + hasReusableClient: vi.fn(), + clearCredentialRejection: vi.fn(), + deleteClient: vi.fn(), getLastFailedStartupCorrelationId: vi.fn((clusterId: string) => clusterId === 'failed-cluster' ? 'failed-attempt' : undefined, ), }, })); -vi.mock('vscode', () => ({ +vi.mock('../../documentdb/CredentialCache', () => ({ + CredentialCache: { getCredentials: vi.fn(), deleteCredentials: vi.fn(), setAuthCredentials: vi.fn() }, +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), l10n: { t: vi.fn((value: string) => value), }, + window: { showErrorMessage: vi.fn() }, })); describe('retryAuthentication', () => { @@ -51,8 +72,22 @@ describe('retryAuthentication', () => { }; const getTreeItem = vi.fn(); + function withRetryCapability( + node: T, + viewId: Views, + ): T & { cluster: { clusterId: string; viewId: Views }; canRetryRejectedCredentials(): boolean } { + return { + ...node, + cluster: { ...node.cluster, viewId }, + canRetryRejectedCredentials: ClusterItemBase.prototype.canRetryRejectedCredentials, + }; + } + beforeEach(() => { vi.clearAllMocks(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(CredentialCache.getCredentials).mockReset(); }); // The next connect.startup names the same attempt in previousFailedStartupCorrelationId. @@ -98,6 +133,23 @@ describe('retryAuthentication', () => { expect(ext.azureResourcesRUBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); }); + it('marks a Discovery node for an explicit reload before resetting or refreshing it', async () => { + const node = { + id: 'discoveryView/azure', + getTreeItem, + prepareExplicitReload: vi.fn(), + }; + + await retryAuthentication(actionContext as never, node); + + const { resetNodeErrorState, refresh } = ext.discoveryBranchDataProvider; + expect(node.prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(node.prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(resetNodeErrorState)); + expect(resetNodeErrorState).toHaveBeenCalledBefore(vi.mocked(refresh)); + expect(resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + expect(refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + it('throws for unsupported retry nodes', async () => { await expect( retryAuthentication(actionContext as never, { @@ -107,4 +159,462 @@ describe('retryAuthentication', () => { }), ).rejects.toThrow('Unsupported view for an authentication retry.'); }); + + function ruNode(): Parameters[1] & { + readReplacementKey: ReturnType>>; + } { + return { + id: 'discoveryView/azure/ru', + cluster: { clusterId: 'ru' }, + getTreeItem, + readReplacementKey: vi.fn>(), + }; + } + + it('discards the old RU key and installs the single replacement read', async (): Promise => { + const node = ruNode(); + const nativeAuthConfig = { connectionUser: 'test', connectionPassword: 'new-key' }; + node.readReplacementKey.mockResolvedValue({ + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore(node.readReplacementKey); + expect(node.readReplacementKey).toHaveBeenCalledBefore(vi.mocked(ClustersClient.clearCredentialRejection)); + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith('ru', 0); + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledBefore( + vi.mocked(CredentialCache.setAuthCredentials), + ); + expect(CredentialCache.setAuthCredentials).toHaveBeenCalledExactlyOnceWith( + 'ru', + AuthMethodId.NativeAuth, + 'mongodb://test', + nativeAuthConfig, + ); + expect(CredentialCache.setAuthCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + + it.each([ + [Views.DiscoveryView, AuthMethodId.NativeAuth, true], + [Views.DiscoveryView, AuthMethodId.MicrosoftEntraID, false], + [Views.ConnectionsView, AuthMethodId.NativeAuth, false], + ] as const)( + 'allows the existing discovery credential setup only for Native auth (%s, %s)', + async (view, authMechanism, shouldRefresh): Promise => { + const node = withRetryCapability({ id: `${view}/test`, cluster: { clusterId: 'test' }, getTreeItem }, view); + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce({ + clusterId: 'test', + connectionString: 'mongodb://test', + authMechanism, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + if (shouldRefresh) { + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + } + + await retryAuthentication(actionContext as never, node); + + if (shouldRefresh) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('test'); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }, + ); + + it.each([ + [ + 'native Azure Resources credentials', + { + id: '_subscriptions_test_resourceGroups_test_providers_Microsoft.DocumentDB_mongoClusters_native', + contextValue: 'treeItem_documentdbcluster;documentDbBranch;azureResourcesView', + cluster: { clusterId: 'native-resources' }, + getTreeItem, + }, + { + clusterId: 'native-resources', + connectionString: 'mongodb://native-resources', + authMechanism: AuthMethodId.NativeAuth, + }, + 'azureResources', + Views.AzureResourcesView, + ], + [ + 'implicit Native auth in Discovery', + { + id: 'discoveryView/azure/implicit-native', + contextValue: 'treeItem_documentdbcluster;discoveryView', + cluster: { clusterId: 'implicit-native' }, + getTreeItem, + }, + { + clusterId: 'implicit-native', + connectionString: 'mongodb://implicit-native', + }, + 'discovery', + Views.DiscoveryView, + ], + [ + 'missing credentials in Discovery', + { + id: 'discoveryView/azure/missing-credentials', + contextValue: 'treeItem_documentdbcluster;discoveryView', + cluster: { clusterId: 'missing-credentials' }, + getTreeItem, + }, + undefined, + undefined, + Views.DiscoveryView, + ], + [ + 'native credentials in Azure Workspace', + { + id: 'azureWorkspaceView/native-resource', + contextValue: 'treeItem_documentdbcluster;azureWorkspaceView', + cluster: { clusterId: 'workspace-native' }, + getTreeItem, + }, + { + clusterId: 'workspace-native', + connectionString: 'mongodb://workspace-native', + authMechanism: AuthMethodId.NativeAuth, + }, + undefined, + Views.AzureWorkspaceView, + ], + ] as const)( + 'characterizes rejected credential recovery for %s', + async (_description, nodeDefinition, credentials, refreshTarget, viewId): Promise => { + const node = withRetryCapability(nodeDefinition, viewId); + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce(credentials); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + if (refreshTarget) { + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + } + + await retryAuthentication(actionContext as never, node); + + if (!refreshTarget) { + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesVCoreBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.azureResourcesVCoreBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + return; + } + + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, 0); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledBefore( + vi.mocked(CredentialCache.deleteCredentials), + ); + + if (refreshTarget === 'discovery') { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.resetNodeErrorState), + ); + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.azureResourcesVCoreBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.azureResourcesVCoreBranchDataProvider.refresh).not.toHaveBeenCalled(); + } else { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.azureResourcesVCoreBranchDataProvider.resetNodeErrorState), + ); + expect(ext.azureResourcesVCoreBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith( + node.id, + ); + expect(ext.azureResourcesVCoreBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(ext.azureResourcesVCoreBranchDataProvider.refresh), + ); + expect(ext.azureResourcesVCoreBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it.each([true, false])( + 'reloads Quick Start with an empty cache only if the rejection can be cleared (%s)', + async (cleared): Promise => { + const clusterId = quickStartClusterId(DEFAULT_ALIAS); + const node = withRetryCapability( + { id: 'connectionsView/localQuickStart/instance', cluster: { clusterId }, getTreeItem }, + Views.ConnectionsView, + ); + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(7); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce(undefined); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(cleared); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith(clusterId, 7); + if (cleared) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }, + ); + + it('abandons a successful key read if the epoch changed', async (): Promise => { + const node = ruNode(); + node.readReplacementKey.mockResolvedValue({ connectionString: 'mongodb://test', availableAuthMethods: [] }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(1).mockReturnValueOnce(2); + await retryAuthentication(actionContext as never, node); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('refreshes without closing a healthy client that replaced the one that failed', async (): Promise => { + const node = { + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + + it('refreshes an old Retry quietly after the client was replaced while its close was pending', async (): Promise => { + const node = { + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(2); + vi.mocked(ClustersClient.deleteClient).mockResolvedValueOnce(undefined); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it.each([new UserCancelledError(), Object.assign(new Error('ARM rejected access'), { statusCode: 401 })])( + 'distinguishes ARM sign-in failure from dismissal and keeps the rejection latch', + async (error): Promise => { + const node = ruNode(); + node.readReplacementKey.mockRejectedValue(error); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + await expect(retryAuthentication(actionContext as never, node)).rejects.toBe(error); + if (error instanceof UserCancelledError) { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(window.showErrorMessage).toHaveBeenCalledWith('Azure sign-in needed', expect.anything()); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + }, + ); + + it.each(['connectionRemoved', 'userDisconnected'] as const)( + 'refreshes a stale Retry for %s without clearing another latch or doing auth work', + async (reason): Promise => { + const node = ruNode(); + const context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { suppressDisplay: false }, + }; + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await retryAuthentication(context as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (reason === 'userDisconnected') { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledBefore( + vi.mocked(window.showErrorMessage), + ); + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + } + expect(node.readReplacementKey).not.toHaveBeenCalled(); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }, + ); + + it.each(['credentialsChanged', undefined] as const)( + 'discards a replacement key when %s supersedes the read', + async (reason): Promise => { + const node = ruNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ext.discoveryBranchDataProvider.refresh).mockImplementationOnce(() => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + }); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + return { + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig: { connectionUser: 'test', connectionPassword: 'replacement' }, + }; + }); + + await retryAuthentication(actionContext as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (reason === 'credentialsChanged') { + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledBefore( + vi.mocked(window.showErrorMessage), + ); + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + } else { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); + expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }, + ); + + it.each([false, true])( + 'refreshes a superseded failed key read with cancellation kept quiet (%s)', + async (cancelled): Promise => { + const node = ruNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + throw cancelled ? new UserCancelledError() : new Error('obsolete ARM failure'); + }); + + await retryAuthentication(actionContext as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (cancelled) { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledBefore( + vi.mocked(window.showErrorMessage), + ); + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }, + ); + + it('refreshes and explains an obsolete client close without closing again', async (): Promise => { + const node = { + id: 'connectionsView/folder/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(false); + vi.mocked(ClustersClient.deleteClient).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('identityChanged'); + }); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledBefore(vi.mocked(window.showErrorMessage)); + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('discards a stale replacement key without feedback for an unsupported view', async (): Promise => { + const node = { ...ruNode(), id: 'azureWorkspaceView/ru' }; + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig: { connectionUser: 'test', connectionPassword: 'replacement' }, + }; + }); + + await retryAuthentication(actionContext as never, node); + + expect(node.readReplacementKey).toHaveBeenCalledOnce(); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesVCoreBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 67be85e13..b5d1b60c5 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -3,13 +3,20 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { l10n } from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { l10n, window } from 'vscode'; +import { classifyResolutionFailure } from '../../connectionDiagnostics/checks/resolveTarget'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; +import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -18,7 +25,13 @@ const containsDelimited = (fullContext: string | undefined, value: string): bool return new RegExp(`\\b${value}\\b`, 'i').test(fullContext); }; -type RetryableTreeNode = TreeElement & Partial; +type RetryableTreeNode = TreeElement & + Partial< + TreeElementWithContextValue & + Pick + > & { + readonly cluster?: { readonly clusterId: string }; + }; function getViewId(node: RetryableTreeNode): Views | undefined { if (containsDelimited(node.contextValue, Views.ConnectionsView)) { @@ -55,6 +68,25 @@ function failedStartupCorrelationIdOf(node: RetryableTreeNode): string | undefin return typeof clusterId === 'string' ? ClustersClient.getLastFailedStartupCorrelationId(clusterId) : undefined; } +export function showObsoleteTreeAction( + context: IActionContext, + reason: ConnectionUnavailableReason | undefined, + includeDisconnected = false, +): void { + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' || + (includeDisconnected && reason === 'userDisconnected') + ) { + context.errorHandling.suppressDisplay = true; + void window.showErrorMessage( + l10n.t('This connection is no longer available for that action. Refresh the tree and try again.'), + { modal: true }, + ); + } +} + export async function retryAuthentication(context: IActionContext, node: RetryableTreeNode): Promise { if (!node?.id) { throw new Error(l10n.t('No node selected.')); @@ -65,6 +97,116 @@ export async function retryAuthentication(context: IActionContext, node: Retryab context.telemetry.properties.failedStartupCorrelationId = failedStartupCorrelationId; } + const clusterId = node.cluster?.clusterId; + if (clusterId) { + const viewId = getViewId(node); + const supportsRefresh = + viewId === Views.ConnectionsView || + viewId === Views.DiscoveryView || + (viewId === Views.AzureResourcesView && + (containsDelimited(node.contextValue, 'ruBranch') || + containsDelimited(node.contextValue, 'documentDbBranch'))); + const reportObsolete = (reason?: ConnectionUnavailableReason, error?: unknown): void => { + if (!supportsRefresh) { + return; + } + refreshAuthenticationNode(node); + const currentReason = reason ?? ClustersClient.getLatchReason(clusterId); + if (!(error instanceof UserCancelledError)) { + showObsoleteTreeAction(context, currentReason); + } + }; + let epoch = ClustersClient.getEpoch(clusterId); + const latch = ClustersClient.getLatchReason(clusterId); + const kind = latch === 'credentialsRejected' ? latch : node.lastConnectionFailureKind; + if (latch && latch !== 'credentialsRejected') { + reportObsolete(latch); + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + if (kind) { + context.telemetry.properties.connectionFailureKind = kind; + } + if (latch === 'credentialsRejected') { + if (!node.readReplacementKey) { + if ( + !node.canRetryRejectedCredentials?.() || + !ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + return; + } + CredentialCache.deleteCredentials(clusterId); + refreshAuthenticationNode(node); + return; + } + context.telemetry.maskEntireErrorMessage = true; + CredentialCache.deleteCredentials(clusterId); + let credentials: Awaited>>; + try { + credentials = await node.readReplacementKey(context); + } catch (error) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { + reportObsolete(undefined, error); + return; + } + if (error instanceof UserCancelledError) { + throw error; + } + const finding = classifyResolutionFailure(new ConnectionSourceUnavailableError('azure', error)); + const signInNeeded = + finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; + context.telemetry.properties.azureKeyReadFailure = signInNeeded ? 'signInRequired' : 'other'; + context.errorHandling.suppressDisplay = true; + void window.showErrorMessage( + signInNeeded + ? l10n.t('Azure sign-in needed') + : l10n.t('Could not read the database key from Azure.'), + { + modal: true, + detail: signInNeeded + ? l10n.t('Sign in to Azure and try Retry again.') + : l10n.t('Check access to the Azure resource and try again.'), + }, + ); + throw error; + } + if (ClustersClient.getEpoch(clusterId) !== epoch) { + reportObsolete(); + return; + } + // One fresh ARM read per explicit click. A subsequent database rejection re-latches in + // the tree; it cannot start another ARM read. + if ( + credentials.nativeAuthConfig?.connectionPassword && + ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.NativeAuth, + credentials.connectionString, + credentials.nativeAuthConfig, + ); + } else { + return; + } + } else if ( + (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') && + !ClustersClient.hasReusableClient(clusterId) + ) { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (ClustersClient.getEpoch(clusterId) !== epoch) { + reportObsolete(); + return; + } + } + } + + refreshAuthenticationNode(node); +} + +export function refreshAuthenticationNode(node: RetryableTreeNode): void { const contextValue = node.contextValue; const viewId = getViewId(node); @@ -74,6 +216,9 @@ export async function retryAuthentication(context: IActionContext, node: Retryab return ext.connectionsBranchDataProvider.refresh(node); case Views.DiscoveryView: + if (isTreeElementWithExplicitReload(node)) { + node.prepareExplicitReload(); + } ext.discoveryBranchDataProvider.resetNodeErrorState(node.id); return ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/commands/runBoundNamespaceCommand.test.ts b/src/commands/runBoundNamespaceCommand.test.ts new file mode 100644 index 000000000..9de2ef6fd --- /dev/null +++ b/src/commands/runBoundNamespaceCommand.test.ts @@ -0,0 +1,181 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { afterEach, expect, it, vi } from 'vitest'; +import { ClustersClient, type ConnectionBinding } from '../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../documentdb/connectionBindingRetirement'; +import { runBoundNamespaceCommand } from './runBoundNamespaceCommand'; + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +interface CreateClientFixture { + readonly client: ClustersClient; + readonly createDatabase: ClustersClient['createDatabase']; + readonly createCollection: ClustersClient['createCollection']; + readonly dropDatabase: ClustersClient['dropDatabase']; +} + +interface CreateEffect { + readonly name: string; + readonly method: 'createDatabase' | 'createCollection'; + readonly run: (client: ClustersClient) => Promise; +} + +const createEffects: readonly CreateEffect[] = [ + { + name: 'database', + method: 'createDatabase', + run: async (client) => client.createDatabase('database'), + }, + { + name: 'collection', + method: 'createCollection', + run: async (client) => client.createCollection('database', 'collection'), + }, +]; + +let clusterSequence = 0; + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((resolvePromise): void => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function createBinding(): ConnectionBinding { + return { + clusterId: `run-bound-namespace-${++clusterSequence}`, + fingerprint: 'original', + generation: 0, + }; +} + +function createClient(binding: ConnectionBinding): CreateClientFixture { + const createDatabase = vi.fn().mockResolvedValue(undefined); + const createCollection = vi + .fn() + .mockResolvedValue({} as Awaited>); + const dropDatabase = vi.fn().mockResolvedValue(true); + return { + client: { + binding, + generation: binding.generation, + fingerprint: binding.fingerprint, + createDatabase, + createCollection, + dropDatabase, + } as unknown as ClustersClient, + createDatabase, + createCollection, + dropDatabase, + }; +} + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it.each(createEffects)('does not create a $name after its binding lifetime ends during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + + retireConnectionBindings(binding.clusterId, binding.generation); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'sessionEnded' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)('does not create a $name when a current latch starts during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsUpdating'); + resolution.resolve(replacement.client); + + try { + await expect(pending).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + } finally { + ClustersClient.unlatch(binding.clusterId); + } +}); + +it.each(createEffects)('does not revive a retired $name binding when its teardown latch clears', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation); + ClustersClient.unlatch(binding.clusterId); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'sessionEnded' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)( + 'creates a $name once when the resolved client is a live same-identity replacement', + async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + resolution.resolve(replacement.client); + await pending; + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).toHaveBeenCalledOnce(); + }, +); + +it('preserves stale delete-confirmation cancellation while resolution is pending', async (): Promise => { + const binding = createBinding(); + const client = createClient(binding); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + const confirmationEpoch = ClustersClient.getEpoch(binding.clusterId); + + const pending = runBoundNamespaceCommand( + binding.clusterId, + binding, + async (resolved) => resolved.dropDatabase('database'), + confirmationEpoch, + ); + ClustersClient.invalidate(binding.clusterId); + resolution.resolve(client.client); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(client.dropDatabase).not.toHaveBeenCalled(); +}); 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/commands/saveConnectionEdit.test.ts b/src/commands/saveConnectionEdit.test.ts new file mode 100644 index 000000000..cf923a404 --- /dev/null +++ b/src/commands/saveConnectionEdit.test.ts @@ -0,0 +1,584 @@ +/*--------------------------------------------------------------------------------------------- + * 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 AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import type * as mongoModule from 'mongodb'; +import { MongoClient, MongoServerError, type MongoClientOptions } from 'mongodb'; +import { EventEmitter } from 'node:events'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../documentdb/ClustersClient'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + isRetiredConnectionBinding, +} from '../documentdb/connectionBindingRetirement'; +import { registerConnectionSurface } from '../documentdb/connectionSurfaces'; +import { canSaveEdit, teardownConnection } from '../documentdb/connectionTeardown'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { API } from '../DocumentDBExperiences'; +import { ext } from '../extensionVariables'; +import type * as storageModule from '../services/connectionStorageService'; +import { + ConnectionStorageService, + ConnectionType, + ItemType, + type ConnectionItem, +} from '../services/connectionStorageService'; +import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../utils/dialogs/showConfirmation'; +import { refreshView } from './refreshView/refreshView'; +import { saveConnectionEdit } from './saveConnectionEdit'; +import { ExecuteStep as UpdateStringExecuteStep } from './updateConnectionString/ExecuteStep'; +import { updateConnectionString } from './updateConnectionString/updateConnectionString'; +import { type UpdateCSWizardContext } from './updateConnectionString/UpdateCSWizardContext'; +import { ExecuteStep as UpdateCredentialsExecuteStep } from './updateCredentials/ExecuteStep'; +import { updateCredentials } from './updateCredentials/updateCredentials'; +import { type UpdateCredentialsWizardContext } from './updateCredentials/UpdateCredentialsWizardContext'; + +type EditContext = UpdateCredentialsWizardContext | UpdateCSWizardContext; +const capturedContexts: EditContext[] = []; +const driverConnect = vi.fn(); +const driverClose = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const { wizardPrompt, getPlaygroundEvaluators, getRegisteredShellTerminals } = vi.hoisted(() => ({ + wizardPrompt: vi.fn<(context: EditContext) => Promise>(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), +})); +const registrations: vscode.Disposable[] = []; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal<{ AzureWizard: typeof AzureWizard; UserCancelledError: typeof UserCancelledError }>()), + // Match the client-suite fixture: the shared VS Code stub has no CancellationError. + parseError: (error: unknown): { message: string; errorType: string } => ({ + message: error instanceof Error ? error.message : String(error), + errorType: + typeof error === 'object' && + error !== null && + 'code' in error && + (typeof error.code === 'string' || typeof error.code === 'number') + ? String(error.code) + : error instanceof Error + ? error.constructor.name + : typeof error, + }), + AzureWizard: class { + constructor(private readonly context: EditContext) { + capturedContexts.push(context); + } + public async prompt(): Promise { + if ('originalConnectionString' in this.context) { + this.context.newConnectionString = 'mongodb://new.example.com/'; + } else { + this.context.selectedAuthenticationMethod = AuthMethodId.NativeAuth; + this.context.nativeAuthConfig = { connectionUser: 'new-user', connectionPassword: 'new-password' }; + } + await wizardPrompt(this.context); + } + public async execute(): Promise { + if ('originalConnectionString' in this.context) { + await new UpdateStringExecuteStep().execute(this.context); + } else { + await new UpdateCredentialsExecuteStep().execute(this.context); + } + } + }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + const context = makeContext(); + try { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } + return undefined; + } + }, +})); +vi.mock('mongodb', async (importOriginal) => ({ + ...(await importOriginal()), + MongoClient: vi.fn(), +})); +vi.mock('../documentdb/LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); +vi.mock('../documentdb/client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('../documentdb/utils/getClusterMetadata', () => ({ + getClusterMetadata: vi.fn().mockResolvedValue({}), + getDomainMetadata: vi.fn().mockReturnValue({}), +})); +vi.mock('../documentdb/srv/prepareDriverConnectionString', () => ({ + prepareDriverConnectionString: async (input: { + connectionString: string; + options: MongoClientOptions; + }): Promise<{ connectionString: string; options: MongoClientOptions }> => ({ + connectionString: input.connectionString, + options: input.options, + }), +})); +vi.mock('../services/connectionStorageService', async (importOriginal) => ({ + ...(await importOriginal()), + ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, +})); +vi.mock('../services/SettingsService', () => ({ + SettingsService: { getSetting: (): undefined => undefined }, +})); +vi.mock('../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (): readonly unknown[] => [] }, +})); +vi.mock('./playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators, + stopPlaygroundEvaluator: vi.fn(), +})); +vi.mock('../documentdb/shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals, +})); +vi.mock('./refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../extensionVariables', () => ({ + ext: { + connectionsBranchDataProvider: { + hasNodeErrorState: vi.fn(), + resetNodeErrorState: vi.fn(), + refresh: vi.fn(), + }, + outputChannel: { debug: vi.fn(), info: vi.fn(), trace: vi.fn(), warn: vi.fn(), error: vi.fn() }, + }, +})); + +function makeContext(): IActionContext { + return { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + } as unknown as IActionContext; +} + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((finish) => { + resolve = finish; + }); + return { promise, resolve }; +} + +describe('disconnected connection edits', () => { + let clusterId: string; + let number = 0; + let node: DocumentDBClusterItem; + let stored: ConnectionItem; + + function cacheStoredCredentials(): void { + const method = + stored.properties.selectedAuthMethod === AuthMethodId.NativeAuth + ? AuthMethodId.NativeAuth + : AuthMethodId.NoAuth; + CredentialCache.setAuthCredentials( + clusterId, + method, + stored.secrets.connectionString, + stored.secrets.nativeAuthConfig, + ); + } + + beforeEach((): void => { + vi.clearAllMocks(); + clusterId = `disconnected-edit-${number++}`; + node = { + id: `folder/${clusterId}`, + storageId: clusterId, + cluster: { clusterId, storageZone: ConnectionType.Clusters, treeId: `folder/${clusterId}` }, + } as unknown as DocumentDBClusterItem; + stored = { + id: clusterId, + name: 'Saved connection', + properties: { + type: ItemType.Connection, + api: API.DocumentDB, + selectedAuthMethod: AuthMethodId.NoAuth, + availableAuthMethods: [AuthMethodId.NativeAuth, AuthMethodId.NoAuth], + }, + secrets: { connectionString: 'mongodb://old.example.com/' }, + }; + capturedContexts.length = 0; + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); + vi.mocked(refreshView).mockReset().mockResolvedValue(undefined); + wizardPrompt.mockReset().mockResolvedValue(undefined); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + cacheStoredCredentials(); + vi.mocked(ConnectionStorageService.get).mockImplementation(async () => structuredClone(stored)); + vi.mocked(ConnectionStorageService.save) + .mockReset() + .mockImplementation(async (_zone, item): Promise => { + stored = structuredClone(item); + }); + driverConnect.mockReset().mockResolvedValue(undefined); + driverClose.mockResolvedValue(undefined); + vi.mocked(MongoClient).mockImplementation(function () { + return Object.assign(new EventEmitter(), { + connect: driverConnect, + close: driverClose, + }) as unknown as MongoClient; + }); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); + }); + + afterEach(async (): Promise => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + await ClustersClient.deleteClient(clusterId); + CredentialCache.deleteCredentials(clusterId); + ClustersClient.clearLastVerifiedIdentity(clusterId); + ClustersClient.unlatch(clusterId); + }); + + it('retires an evicted binding before a password-only edit reaches storage', async (): Promise => { + stored.properties.selectedAuthMethod = AuthMethodId.NativeAuth; + stored.secrets.nativeAuthConfig = { + connectionUser: 'old-user', + connectionPassword: 'old-password', + }; + cacheStoredCredentials(); + const original = await ClustersClient.getClient(clusterId); + + expect(ClustersClient.reportFailure(original.binding, new MongoServerError({ code: 18 }))).toBe( + 'credentialsRejected', + ); + expect(ClustersClient.exists(clusterId)).toBe(false); + expect(isRetiredConnectionBinding(original.binding)).toBe(false); + + const changed = await saveConnectionEdit(node, async (): Promise => { + expect(isRetiredConnectionBinding(original.binding)).toBe(true); + stored.secrets.nativeAuthConfig = { + connectionUser: 'old-user', + connectionPassword: 'new-password', + }; + await ConnectionStorageService.save(ConnectionType.Clusters, structuredClone(stored), true); + return true; + }); + + expect(changed).toBe(true); + expect(getRetiredBindingReason(original.binding)).toBe('sessionEnded'); + }); + + it('preserves an explicit Disconnect retirement when the edit boundary is reached', async (): Promise => { + const original = await ClustersClient.getClient(clusterId); + await teardownConnection(clusterId, 'userDisconnected', vi.fn()); + + await saveConnectionEdit(node, async (): Promise => false); + + expect(getRetiredBindingReason(original.binding)).toBe('sessionEnded'); + }); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'excludes real client startup between both %s writes, including a metadata failure', + async (_commandName, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + expect(original.binding.clusterId).toBe(clusterId); + expect(driverConnect).toHaveBeenCalledOnce(); + const secretWritten = deferred(); + const finishMetadata = deferred(); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored.secrets = structuredClone(item.secrets); + secretWritten.resolve(); + await finishMetadata.promise; + throw new Error('Metadata write failed'); + }); + + const updating = update(makeContext(), node); + await secretWritten.promise; + expect(driverClose).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsUpdating'); + expect(ClustersClient.exists(clusterId)).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toMatchObject({ + reason: 'credentialsUpdating', + }); + expect(driverConnect).toHaveBeenCalledOnce(); + finishMetadata.resolve(); + await updating; + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + const edited = capturedContexts[0]; + if ('originalConnectionString' in edited) { + expect(edited.connectionStringSaved).toBe(false); + } else { + expect(edited.credentialsSaved).not.toBe(true); + } + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(driverConnect).toHaveBeenCalledOnce(); + }, + ); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'allows a fresh client using the fully saved %s after explicit reconnect', + async (_name, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item); + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(driverConnect).toHaveBeenCalledOnce(); + cacheStoredCredentials(); + ClustersClient.unlatch(clusterId); + const current = await ClustersClient.getClient(clusterId); + expect(current).not.toBe(original); + expect(current.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(driverClose).toHaveBeenCalledOnce(); + }, + ); + + it('does not start saving after its wizard epoch was superseded', async (): Promise => { + const save = vi.fn<() => Promise>(); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.invalidate(clusterId); + + await expect( + saveConnectionEdit(node, save, { canStart: (): boolean => canSaveEdit(clusterId, epoch) }), + ).rejects.toBeInstanceOf(UserCancelledError); + + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + }); + + it('does not save or restore a hold superseded during the storage read', async (): Promise => { + const readStarted = deferred(); + const finishRead = deferred(); + ClustersClient.latch(clusterId, 'userDisconnected'); + vi.mocked(ConnectionStorageService.get).mockImplementationOnce(async () => { + readStarted.resolve(); + await finishRead.promise; + return structuredClone(stored); + }); + const save = vi.fn<() => Promise>(); + const saving = saveConnectionEdit(node, save); + await readStarted.promise; + ClustersClient.latch(clusterId, 'connectionRemoved'); + finishRead.resolve(); + + await expect(saving).rejects.toBeInstanceOf(UserCancelledError); + + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('connectionRemoved'); + }); + + it('reconnects after Yes with a fresh session while the kept old tab remains read-only', async (): Promise => { + const original = await ClustersClient.getClient(clusterId); + const lifetime = getBindingLifetimeSignal(original.binding); + const draft = { + clusterId, + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = true; + } + }); + let connected: ClustersClient | undefined; + vi.mocked(refreshView).mockImplementationOnce(async (): Promise => { + connected = await ClustersClient.getClient(clusterId); + }); + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(unlatch).toHaveBeenCalledBefore(vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState)); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(refreshView), + ); + expect(connected).toBeDefined(); + expect(connected).not.toBe(original); + expect(connected?.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.isDirty()).toBe(true); + expect(lifetime.aborted).toBe(true); + await expect(ClustersClient.resolveBoundClient(original.binding)).rejects.toMatchObject({ + reason: 'sessionEnded', + }); + if (!connected) { + throw new Error('Expected refresh to open a fresh connection.'); + } + await expect(ClustersClient.resolveBoundClient(connected.binding)).resolves.toBe(connected); + expect(driverConnect).toHaveBeenCalledTimes(2); + } finally { + unlatch.mockRestore(); + } + }); + + it.each(['No', 'failed save', 'connectionRemoved'] as const)( + 'does not unlatch or start another session after %s', + async (outcome): Promise => { + await ClustersClient.getClient(clusterId); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = outcome !== 'No'; + } + }); + if (outcome === 'failed save') { + vi.mocked(ConnectionStorageService.save).mockRejectedValueOnce(new Error('Save failed')); + } else if (outcome === 'connectionRemoved') { + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item); + ClustersClient.latch(clusterId, 'connectionRemoved'); + }); + } + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).not.toHaveBeenCalled(); + const reason = outcome === 'connectionRemoved' ? 'connectionRemoved' : 'userDisconnected'; + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason }); + expect(driverConnect).toHaveBeenCalledOnce(); + if (outcome !== 'connectionRemoved') { + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + } + } finally { + unlatch.mockRestore(); + } + }, + ); + + describe.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)('%s idle-wizard exclusion', (_name, update): void => { + it.each(['client', 'pending startup', 'surface', 'shell', 'evaluator'] as const)( + 'does not save when a %s appears during the wizard without changing the epoch', + async (work): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + const original = structuredClone(stored); + const started = deferred(); + const finishStartup = deferred(); + let startup: Promise | undefined; + const disconnect = vi.fn(); + const surface = { + clusterId, + kind: 'documentView' as const, + disable: vi.fn(), + dispose: vi.fn(), + }; + wizardPrompt.mockImplementationOnce(async (): Promise => { + if (work === 'client') { + await ClustersClient.getClient(clusterId); + } else if (work === 'pending startup') { + driverConnect.mockImplementationOnce(async (): Promise => { + started.resolve(); + await finishStartup.promise; + }); + startup = ClustersClient.getClient(clusterId); + await started.promise; + } else if (work === 'surface') { + registrations.push(registerConnectionSurface(surface)); + } else if (work === 'shell') { + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } else { + getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(stored).toEqual(original); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + expect(driverConnect).toHaveBeenCalledTimes(work === 'client' || work === 'pending startup' ? 1 : 0); + expect(driverClose).not.toHaveBeenCalled(); + expect(disconnect).not.toHaveBeenCalled(); + expect(surface.disable).not.toHaveBeenCalled(); + expect(surface.dispose).not.toHaveBeenCalled(); + finishStartup.resolve(); + if (startup) { + await startup; + expect(ClustersClient.exists(clusterId)).toBe(true); + } + }, + ); + + it('saves a user-disconnected connection with a still-registered old shell', async (): Promise => { + ClustersClient.latch(clusterId, 'userDisconnected'); + const disconnect = vi.fn(); + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(disconnect).not.toHaveBeenCalled(); + expect(driverConnect).not.toHaveBeenCalled(); + expect(driverClose).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('allows saving when a startup attempted during the wizard has failed and disappeared', async (): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + wizardPrompt.mockImplementationOnce(async (): Promise => { + driverConnect.mockRejectedValueOnce(new Error('Startup failed')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('Startup failed'); + expect(ClustersClient.hasPendingStartup(clusterId)).toBe(false); + expect(ClustersClient.exists(clusterId)).toBe(false); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts new file mode 100644 index 000000000..84d0dd6db --- /dev/null +++ b/src/commands/saveConnectionEdit.ts @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { isDeepStrictEqual } from 'node:util'; +import * as vscode from 'vscode'; +import { clearEntraTokenFailure } from '../documentdb/auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../documentdb/ClustersClient'; +import { latchForTeardown } from '../documentdb/connectionTeardown'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { ext } from '../extensionVariables'; +import { ConnectionStorageService, isConnection, type StoredItem } from '../services/connectionStorageService'; +import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; +import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; +import { resolveStorageZone } from '../tree/connections-view/models/ConnectionClusterModel'; + +function storedSettings(item: StoredItem | undefined): object | undefined { + if (!item || !isConnection(item)) { + return undefined; + } + return { + secrets: item.secrets, + authMethod: item.properties.selectedAuthMethod, + emulator: item.properties.emulatorConfiguration, + }; +} + +/** + * Exclude startup across both storage writes and verify what actually persisted. + * The old session has already ended; secret storage and metadata are not written atomically. + */ +export async function saveConnectionEdit( + node: DocumentDBClusterItem, + save: (isCurrent: () => boolean) => Promise, + options?: { + readonly canStart?: () => boolean; + readonly publishCredentials?: (connection: StoredItem | undefined) => void; + }, +): Promise { + const { clusterId } = node.cluster; + const zone = resolveStorageZone(node.cluster); + if (options?.canStart?.() === false) { + throw new UserCancelledError(); + } + const previous = ClustersClient.getLatchReason(clusterId); + if (previous === 'connectionRemoved' || previous === 'credentialsUpdating') { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (!latchForTeardown(clusterId, 'credentialsUpdating')) { + await checkCanProceedAndInformUser({ clusterId }, vscode.l10n.t('update this connection')); + throw new UserCancelledError(); + } + + ClustersClient.retireBoundViews(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + let changed = false; + let saved = false; + try { + const before = await ConnectionStorageService.get(node.storageId, zone); + const originalSettings = structuredClone(storedSettings(before)); + if (!originalSettings) { + void vscode.window.showErrorMessage(vscode.l10n.t('The connection could not be read from storage.')); + return false; + } + try { + if (!isCurrent()) { + throw new UserCancelledError(); + } + saved = await save(isCurrent); + } finally { + let after: StoredItem | undefined; + try { + after = await ConnectionStorageService.get(node.storageId, zone); + } catch { + ext.outputChannel.warn(vscode.l10n.t('Could not verify the saved connection settings.')); + } + if (isCurrent() && !isDeepStrictEqual(originalSettings, storedSettings(after))) { + changed = true; + CredentialCache.deleteCredentials(clusterId); + clearEntraTokenFailure(clusterId); + if ( + !after || + !isConnection(after) || + !before || + !isConnection(before) || + before.properties.selectedAuthMethod !== after.properties.selectedAuthMethod + ) { + ClustersClient.clearLastVerifiedIdentity(clusterId); + } else if (before.secrets.entraIdAuthConfig?.tenantId !== after.secrets.entraIdAuthConfig?.tenantId) { + ClustersClient.discardEntraPinForDifferentTenant( + clusterId, + after.secrets.entraIdAuthConfig?.tenantId, + ); + } + if (!saved || !after) { + void vscode.window.showWarningMessage( + vscode.l10n.t( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ), + ); + } + if (isCurrent()) { + options?.publishCredentials?.(after); + } + } + } + } finally { + if (isCurrent()) { + const recovered = previous === 'credentialsRejected' && saved; + if (previous && !recovered && (!changed || previous === 'userDisconnected')) { + ClustersClient.latch(clusterId, previous); + } else { + ClustersClient.unlatch(clusterId); + } + } + } + return changed; +} diff --git a/src/commands/showConnectionStats/showConnectionStats.test.ts b/src/commands/showConnectionStats/showConnectionStats.test.ts new file mode 100644 index 000000000..9586e6f3b --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.test.ts @@ -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. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; +import { showConnectionStats } from './showConnectionStats'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getDiagnosticsSnapshot: vi.fn() }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { appendLog: vi.fn(), show: vi.fn() } }, +})); + +afterEach(() => { + vi.useRealTimers(); +}); + +it.each([ + ['2026-11-24T19:02:03.000Z', '2026-11-24T19:02:03.000Z (in 25:02:03)'], + ['2026-11-23T18:00:00.001Z', '2026-11-23T18:00:00.001Z (in 00:00:01)'], + ['2026-11-23T18:00:00.000Z', '2026-11-23T18:00:00.000Z (expired)'], + [undefined, '(not available)'], +])('prints the UTC expiry with remaining time or status for %s', (expiry, expected): void => { + vi.useFakeTimers({ now: new Date('2026-11-23T18:00:00.000Z') }); + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ + { + client: { + generation: 1, + ageMs: 1000, + authMethod: AuthMethodId.MicrosoftEntraID, + state: 'cached', + socketTrace: true, + lastEntraTokenExpiresAt: expiry, + }, + }, + ]); + + showConnectionStats({} as IActionContext); + + expect(vi.mocked(ext.outputChannel.appendLog).mock.lastCall?.[0]).toContain( + `\n • Last Entra token expires at: ${expected}`, + ); +}); + +it('separates cached and pending client entries while retaining lifecycle details', (): void => { + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ + { + client: { + generation: 4, + ageMs: 32000, + authMethod: AuthMethodId.NativeAuth, + startupId: undefined, + state: 'cached', + socketTrace: false, + }, + pending: { startupId: 'pending-startup', superseded: true }, + held: 'credentialsUpdating', + lastFailedStartupId: 'failed-startup', + }, + { pending: { startupId: 'new-startup', superseded: false } }, + ]); + + showConnectionStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.lastCall?.[0]; + expect(output).toContain('CONNECTION CLIENT SESSIONS · 2 entries · Extension host'); + expect(output).toContain( + [ + '\n--- Connection 1 · cached ---', + ' • Client state: cached', + ' • Generation: 4', + ' • Age (ms): 32000', + ' • Auth method: NativeAuth', + ' • Startup ID: (not available)', + ' • Socket trace: false', + ' • Pending state: superseded', + ' • Pending startup ID: pending-startup', + ' • Held reason: credentialsUpdating', + ' • Last failed startup ID: failed-startup', + '', + '--- Connection 2 · startup pending ---', + ' • Client state: (not available)', + ' • Pending state: current', + ' • Pending startup ID: new-startup', + ].join('\n'), + ); +}); + +it('does not expose values outside the diagnostics fields', (): void => { + const snapshot = [ + { + client: { + generation: 1, + ageMs: 10, + authMethod: AuthMethodId.NativeAuth, + state: 'cached' as const, + socketTrace: true, + connectionString: 'mongodb://user:password@example.test/', + accessToken: 'secret-access-token', + }, + }, + ]; + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce(snapshot); + + showConnectionStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.lastCall?.[0]; + expect(output).not.toContain('password'); + expect(output).not.toContain('secret-access-token'); + expect(output).not.toContain('mongodb://'); +}); diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts new file mode 100644 index 000000000..bf92c66e8 --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -0,0 +1,72 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; + +function formatEntraExpiry(expiresAt: string | undefined, now: number): string { + if (expiresAt === undefined) { + return '(not available)'; + } + + const remainingMs = Date.parse(expiresAt) - now; + if (remainingMs <= 0) { + return `${expiresAt} (expired)`; + } + + const seconds = Math.ceil(remainingMs / 1000); + const remaining = [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60] + .map((part) => String(part).padStart(2, '0')) + .join(':'); + return `${expiresAt} (in ${remaining})`; +} + +export function showConnectionStats(_context: IActionContext): void { + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const now = Date.now(); + const entryLabel = snapshot.length === 1 ? 'entry' : 'entries'; + const lines = [ + `CONNECTION CLIENT SESSIONS · ${String(snapshot.length)} ${entryLabel} · Extension host`, + 'Socket counts: (not available); each cached client can own multiple sockets.', + 'For workers, use DocumentDB Developer: Show Shell and Playground Sessions.', + ]; + + for (const [index, { client, pending, held, lastFailedStartupId }] of snapshot.entries()) { + const clientState = client?.state ?? '(not available)'; + let status = clientState; + if (!client && pending) { + status = pending.superseded ? 'startup superseded' : 'startup pending'; + } + lines.push('', `--- Connection ${String(index + 1)} · ${status} ---`, ` • Client state: ${clientState}`); + if (client) { + lines.push( + ` • Generation: ${String(client.generation)}`, + ` • Age (ms): ${String(client.ageMs)}`, + ` • Auth method: ${client.authMethod ?? '(not available)'}`, + ` • Startup ID: ${client.startupId ?? '(not available)'}`, + ` • Socket trace: ${String(client.socketTrace)}`, + ); + } + if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { + lines.push(` • Last Entra token expires at: ${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`); + } + if (pending) { + lines.push( + ` • Pending state: ${pending.superseded ? 'superseded' : 'current'}`, + ` • Pending startup ID: ${pending.startupId}`, + ); + } + if (held) { + lines.push(` • Held reason: ${held}`); + } + if (lastFailedStartupId) { + lines.push(` • Last failed startup ID: ${lastFailedStartupId}`); + } + } + ext.outputChannel.appendLog(lines.join('\n')); + ext.outputChannel.show(); +} diff --git a/src/commands/showWorkerStats/showWorkerStats.test.ts b/src/commands/showWorkerStats/showWorkerStats.test.ts new file mode 100644 index 000000000..1bf00a3a9 --- /dev/null +++ b/src/commands/showWorkerStats/showWorkerStats.test.ts @@ -0,0 +1,127 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { beforeEach, expect, it, vi } from 'vitest'; +import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { ext } from '../../extensionVariables'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; +import { showWorkerStats } from './showWorkerStats'; + +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals: vi.fn(), +})); + +vi.mock('../playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators: vi.fn(), +})); + +vi.mock('../../documentdb/playground/WorkerSessionManager', () => ({ + WorkerSessionManager: vi.fn().mockImplementation(function () { + return { + get workerState(): string { + return 'idle'; + }, + get isAlive(): boolean { + return false; + }, + get workerClusterId(): string | undefined { + return undefined; + }, + }; + }), +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { appendLog: vi.fn(), show: vi.fn() } }, +})); + +beforeEach(() => { + vi.mocked(getRegisteredShellTerminals).mockReset(); + vi.mocked(getPlaygroundEvaluators).mockReset(); + vi.mocked(ext.outputChannel.appendLog).mockReset(); + vi.mocked(ext.outputChannel.show).mockReset(); + vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); + vi.mocked(getPlaygroundEvaluators).mockReturnValue(new Map()); +}); + +it('prints only the summary when no sessions exist', (): void => { + showWorkerStats({} as IActionContext); + + expect(vi.mocked(ext.outputChannel.appendLog).mock.lastCall?.[0]).toBe( + 'SHELL AND PLAYGROUND SESSIONS · 0 Shell · 0 Playground', + ); +}); + +it('separates Shell and Playground blocks and shows worker state even when session values are missing', (): void => { + vi.mocked(getRegisteredShellTerminals).mockReturnValueOnce([ + { + terminal: { name: 'DocumentDB Shell' } as ReturnType< + typeof getRegisteredShellTerminals + >[number]['terminal'], + info: { + clusterId: 'shell-cluster', + clusterDisplayName: 'Shell Cluster', + activeDatabase: 'test', + isInitialized: false, + isEvaluating: false, + workerState: 'spawning', + authMethod: undefined, + username: undefined, + }, + }, + ]); + const evaluator = new PlaygroundEvaluator(); + vi.spyOn(evaluator, 'workerState', 'get').mockReturnValue('idle'); + vi.spyOn(evaluator, 'isAlive', 'get').mockReturnValue(false); + vi.mocked(getPlaygroundEvaluators).mockReturnValueOnce(new Map([['playground-cluster', evaluator]])); + + showWorkerStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.lastCall?.[0]; + expect(output).toContain('SHELL AND PLAYGROUND SESSIONS · 1 Shell · 1 Playground\n\n--- Shell 1 · spawning ---'); + expect(output).toContain(' • Username: (not available)\n\n--- Playground 1 · idle ---'); + expect(output?.split('\n')).toEqual( + expect.arrayContaining([ + ' • Initialized: no', + ' • Evaluating: no', + ' • Worker state: spawning', + ' • Auth method: (not available)', + ' • Worker alive: no', + ' • Worker state: idle', + ' • Session ID: (not available)', + ' • Evaluations this session: 0', + ' • Last init duration (ms): 0', + ]), + ); +}); + +it('does not print identifying or credential values that are not worker fields', (): void => { + const shell = { + terminal: { name: 'Safe terminal' } as ReturnType[number]['terminal'], + info: { + clusterId: 'visible-cluster-id', + clusterDisplayName: 'Visible Cluster', + activeDatabase: 'test', + isInitialized: true, + isEvaluating: false, + workerState: 'ready' as const, + authMethod: 'NativeAuth' as const, + username: 'existing-username', + connectionString: 'mongodb://user:password@example.test/', + accessToken: 'secret-access-token', + }, + }; + vi.mocked(getRegisteredShellTerminals).mockReturnValueOnce([shell]); + + showWorkerStats({} as IActionContext); + + const output = JSON.stringify(vi.mocked(ext.outputChannel.appendLog).mock.calls); + expect(output).toContain('Username: existing-username'); + expect(output).not.toContain('password'); + expect(output).not.toContain('secret-access-token'); + expect(output).not.toContain('mongodb://'); +}); diff --git a/src/commands/showWorkerStats/showWorkerStats.ts b/src/commands/showWorkerStats/showWorkerStats.ts index e8954d123..3809d114e 100644 --- a/src/commands/showWorkerStats/showWorkerStats.ts +++ b/src/commands/showWorkerStats/showWorkerStats.ts @@ -13,54 +13,43 @@ import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; * Displays all playground workers (one per cluster) and all active interactive shell sessions. */ export function showWorkerStats(_context: IActionContext): void { - const log = (msg: string): void => ext.outputChannel.appendLog(msg); - - log('──────────────────────────────────────'); - log('[Worker Task Manager] Worker Stats'); - log('──────────────────────────────────────'); - - // ── Playground Workers ─────────────────────────────────────────────── - log(''); - log(' Playground Workers:'); - const evaluators = getPlaygroundEvaluators(); - if (evaluators.size === 0) { - log(' (no playground workers — no playground run yet)'); - } else { - log(` Active workers: ${String(evaluators.size)}`); - for (const [clusterId, evaluator] of evaluators) { - log(` ─ Cluster: ${clusterId}`); - log(` Status: ${evaluator.isAlive ? 'alive' : 'not running'}`); - log(` Worker state: ${evaluator.workerState}`); - log(` Session ID: ${evaluator.sessionId ?? '(none)'}`); - log(` Eval count (session): ${String(evaluator.sessionEvalCount)}`); - log(` Auth method: ${evaluator.sessionAuthMethod ?? '(none)'}`); - log(` Last init duration: ${String(evaluator.lastInitDurationMs)}ms`); - } - } - // ── Interactive Shell Workers ──────────────────────────────────────── - log(''); - log(' Interactive Shell Workers:'); - const shellTerminals = getRegisteredShellTerminals(); - if (shellTerminals.length === 0) { - log(' (no active shell sessions)'); - } else { - log(` Active sessions: ${String(shellTerminals.length)}`); - for (const { terminal, info } of shellTerminals) { - log(` ─ Terminal: "${terminal.name}"`); - log(` Cluster: ${info.clusterDisplayName} (${info.clusterId})`); - log(` Database: ${info.activeDatabase}`); - log(` Initialized: ${String(info.isInitialized)}`); - log(` Worker state: ${info.workerState}`); - log(` Evaluating: ${String(info.isEvaluating)}`); - log(` Auth method: ${info.authMethod ?? '(not yet initialized)'}`); - log(` Username: ${info.username ?? '(n/a)'}`); - } + const lines = [ + `SHELL AND PLAYGROUND SESSIONS · ${String(shellTerminals.length)} Shell · ${String(evaluators.size)} Playground`, + ]; + + for (const [index, { terminal, info }] of shellTerminals.entries()) { + lines.push( + '', + `--- Shell ${String(index + 1)} · ${info.workerState} ---`, + ` • Terminal: ${terminal.name}`, + ` • Cluster: ${info.clusterDisplayName}`, + ` • Cluster ID: ${info.clusterId}`, + ` • Database: ${info.activeDatabase || '(not available)'}`, + ` • Worker state: ${info.workerState}`, + ` • Initialized: ${info.isInitialized ? 'yes' : 'no'}`, + ` • Evaluating: ${info.isEvaluating ? 'yes' : 'no'}`, + ` • Auth method: ${info.authMethod ?? '(not available)'}`, + ` • Username: ${info.username ?? '(not available)'}`, + ); } - log(''); - log('──────────────────────────────────────'); + for (const [index, [clusterId, evaluator]] of Array.from(evaluators).entries()) { + const workerState = evaluator.workerState; + lines.push( + '', + `--- Playground ${String(index + 1)} · ${workerState} ---`, + ` • Cluster ID: ${clusterId}`, + ` • Worker alive: ${evaluator.isAlive ? 'yes' : 'no'}`, + ` • Worker state: ${workerState}`, + ` • Session ID: ${evaluator.sessionId ?? '(not available)'}`, + ` • Evaluations this session: ${String(evaluator.sessionEvalCount)}`, + ` • Auth method: ${evaluator.sessionAuthMethod ?? '(not available)'}`, + ` • Last init duration (ms): ${String(evaluator.lastInitDurationMs)}`, + ); + } + ext.outputChannel.appendLog(lines.join('\n')); ext.outputChannel.show(); } diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts new file mode 100644 index 000000000..1f391565b --- /dev/null +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -0,0 +1,509 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { type AuthCallerPolicy } from '../../documentdb/auth/authCallerPolicy'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { Views } from '../../documentdb/Views'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { signInAgain, signInAgainForWorker } from './signInAgain'; + +const pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'pinned', + accountLabel: 'Pinned', + tenantId: 'tenant', +} as const; +const clusterId = 'cluster'; +const mocks = vi.hoisted(() => ({ + configureAuth: vi.fn(), + capturePolicy: vi.fn<(policy: AuthCallerPolicy) => void>(), +})); + +vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 1), + getLatchReason: vi.fn(() => 'credentialsRejected'), + getLastVerifiedIdentity: vi.fn(() => pin), + startAfterSignIn: vi.fn(), + getExistingClient: vi.fn(), + }, +})); +vi.mock('../../documentdb/auth/entraSession', () => ({ getEntraSession: vi.fn() })); +vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ + MicrosoftEntraIDAuthHandler: class { + constructor(_credentials: unknown, policy: AuthCallerPolicy) { + mocks.capturePolicy(policy); + } + + public async configureAuth( + _timings: undefined, + _trace: undefined, + acquire: typeof getEntraSession, + ): Promise { + return await mocks.configureAuth(_timings, _trace, acquire); + } + }, +})); +vi.mock(import('../retryAuthentication/retryAuthentication'), async (importOriginal) => ({ + ...(await importOriginal()), + refreshAuthenticationNode: vi.fn(), +})); +vi.mock('../../documentdb/showClusterConnectFailure', () => ({ showClusterConnectFailure: vi.fn() })); + +function actionContext(): IActionContext { + return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; +} + +describe('signInAgain', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(pin); + mocks.configureAuth.mockImplementation( + async (_timings: undefined, _trace: undefined, acquire: typeof getEntraSession): Promise => { + const session = await acquire({ + mode: 'forceNew', + providerId: pin.providerId, + resource: 'scope', + tenantId: pin.tenantId, + account: { id: pin.accountId, label: pin.accountLabel }, + }); + return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; + }, + ); + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://test', + undefined, + undefined, + { tenantId: pin.tenantId }, + ); + }); + + it('requests one pinned forced session and forwards the repaired account', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); + + await signInAgain(actionContext(), { clusterId }); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); + expect(ClustersClient.startAfterSignIn).toHaveBeenCalledExactlyOnceWith( + clusterId, + 1, + CredentialCache.getCredentials(clusterId), + { verifiedIdentity: pin }, + ); + }); + + it.each([pin.accountLabel, 'Explicitly selected in VS Code'])( + 'rejects a different account with label %s without changing the repair pin or hold', + async (label): Promise => { + const credentials = CredentialCache.getCredentials(clusterId); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: 'different-account', label }, + } as vscode.AuthenticationSession); + + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf( + EntraIdentityMismatchError, + ); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(showClusterConnectFailure).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ error: expect.any(EntraIdentityMismatchError) }), + ); + }, + ); + + it('observes renewal only for the client established by this sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + const getTokenLookupEpoch = vi.fn<() => number | undefined>(() => 1); + vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); + return { getTokenLookupEpoch } as unknown as ClustersClient; + }); + + await signInAgain(actionContext(), { clusterId }); + + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.onTokenLookup).toBeTypeOf('function'); + expect(policy.getTokenLookupEpoch?.()).toBe(1); + getTokenLookupEpoch.mockReturnValue(2); + expect(policy.getTokenLookupEpoch?.()).toBe(2); + getTokenLookupEpoch.mockReturnValue(undefined); + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); + }); + + it.each([undefined, new Error('User did not consent to login.')])( + 'dismisses without reconnecting or retrying session acquisition', + async (error): Promise => { + if (error) { + vi.mocked(getEntraSession).mockRejectedValueOnce(error); + } else { + vi.mocked(getEntraSession).mockResolvedValueOnce(undefined); + } + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf(UserCancelledError); + expect(getEntraSession).toHaveBeenCalledTimes(1); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('does not reconnect when the epoch changes during sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + await signInAgain(actionContext(), { clusterId }); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + }); + + it('explains how to restore the pinned provider before opening an authorization prompt', async (): Promise => { + const error = new EntraSignInRequiredError('providerChanged'); + mocks.configureAuth.mockRejectedValueOnce(error); + + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBe(error); + + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'The Azure cloud or sign-in provider changed.', + { + modal: true, + detail: 'Restore "microsoft-sovereign-cloud.environment" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.', + }, + ); + }); + + it('never installs a different-label account during worker recovery', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: 'different-account', label: 'Different label' }, + } as vscode.AuthenticationSession); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).rejects.toBeInstanceOf( + EntraIdentityMismatchError, + ); + + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('does not prompt when only the worker retains the identity pin', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(undefined); + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + function treeNode(viewId: Views = Views.ConnectionsView): ClusterItemBase { + return { + id: `${viewId}/folder/cluster`, + contextValue: `${viewId};treeItem_documentdbcluster`, + cluster: { clusterId, treeId: `${viewId}/folder/cluster`, viewId, name: 'test' }, + } as ClusterItemBase; + } + + it.each([ + ['tree', undefined, 'connectionRemoved'], + ['worker', new Error('User did not consent to login.'), 'identityChanged'], + ] as const)('keeps a superseded %s dismissal quiet', async (caller, error, reason): Promise => { + if (caller === 'worker') { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + } + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (error) { + throw error; + } + return undefined; + }); + + const pending = + caller === 'tree' + ? signInAgain(actionContext(), treeNode()) + : signInAgainForWorker(actionContext(), clusterId, pin); + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + + expect(getEntraSession).toHaveBeenCalledTimes(1); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it('preserves a noncancellation session acquisition error', async (): Promise => { + const error = new Error('Session acquisition failed'); + vi.mocked(getEntraSession).mockRejectedValueOnce(error); + + await expect(signInAgain(actionContext(), treeNode())).rejects.toBe(error); + + expect(showClusterConnectFailure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ error })); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it('refreshes and explains an explicit stale tree sign-in without auth work', async (): Promise => { + const context = actionContext(); + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsChanged'); + + await signInAgain(context, node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(mocks.configureAuth).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('refreshes before feedback when Disconnect supersedes a pending tree sign-in', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('reports an obsolete provider failure instead of its superseded guidance', async (): Promise => { + const node = treeNode(); + mocks.configureAuth.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('identityChanged'); + throw new EntraSignInRequiredError('providerChanged'); + }); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('refreshes once when Disconnect supersedes sign-in startup', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + return undefined; + }); + + await signInAgain(actionContext(), node); + + expect(ClustersClient.startAfterSignIn).toHaveBeenCalledTimes(1); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('stays quiet when synchronous stale refresh clears the reason', async (): Promise => { + const context = actionContext(); + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + vi.mocked(refreshAuthenticationNode).mockImplementationOnce(() => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + }); + + await signInAgain(context, node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).not.toBe(true); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(mocks.configureAuth).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('refreshes an epoch-only stale tree sign-in quietly', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it('refreshes an already disconnected tree sign-in quietly', async (): Promise => { + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + }); + + it('does not refresh or show a stale modal for an unsupported Workspace node', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + await signInAgain(actionContext(), treeNode(Views.AzureWorkspaceView)); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + }); + + it.each([ + [Views.DiscoveryView, 'discoveryView;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;ruBranch;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;documentDbBranch;treeItem_documentdbcluster'], + ] as const)( + 'refreshes eligible stale nodes using their existing %s routing tags (%s)', + async (viewId, contextValue): Promise => { + const node = Object.assign(treeNode(viewId), { contextValue }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }, + ); + + it('propagates an unexpected stale refresh failure without a second refresh or modal', async (): Promise => { + const error = new Error('refresh failed'); + vi.mocked(refreshAuthenticationNode).mockImplementationOnce(() => { + throw error; + }); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await expect(signInAgain(actionContext(), treeNode())).rejects.toBe(error); + + expect(refreshAuthenticationNode).toHaveBeenCalledTimes(1); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', 'userDisconnected'] as const)( + 'keeps stale worker recovery quiet for %s', + async (reason): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }, + ); + + it('keeps an obsolete pending worker sign-in quiet without restarting', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); +}); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts new file mode 100644 index 000000000..a49af136f --- /dev/null +++ b/src/commands/signInAgain/signInAgain.ts @@ -0,0 +1,241 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { type VerifiedEntraIdentity } from '../../documentdb/auth/AuthHandler'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { emitTokenRenewal } from '../../documentdb/auth/tokenRenewalTelemetry'; +import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { Views } from '../../documentdb/Views'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode, showObsoleteTreeAction } from '../retryAuthentication/retryAuthentication'; + +interface WorkerSignInResult { + readonly identity: VerifiedEntraIdentity; + readonly epoch: number; +} + +export function canSignInAgainForWorker(clusterId: string, expectedIdentity: VerifiedEntraIdentity): boolean { + const credentials = CredentialCache.getCredentials(clusterId); + const hostIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + return ( + ClustersClient.getLatchReason(clusterId) === undefined && + credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && + credentials.entraIdConfig?.tenantId === expectedIdentity.tenantId && + hostIdentity?.kind === 'entra' && + sameEntraIdentity(hostIdentity, expectedIdentity) + ); +} + +function isSignInDismissal(error: unknown): boolean { + return ( + error instanceof UserCancelledError || + (error instanceof Error && + (error.name === 'Canceled' || + error.message === 'User did not consent to login.' || + ('errorCode' in error && error.errorCode === 'user_cancelled'))) + ); +} + +export async function signInAgain( + context: IActionContext, + target: ClusterItemBase | { readonly clusterId: string }, +): Promise { + await signInAgainInternal(context, target); +} + +/** + * Recover only the exact identity pinned by a shell or playground worker. + * + * Unlike the tree command, this path never accepts a different account selected + * by VS Code, even when its label differs. + */ +export async function signInAgainForWorker( + context: IActionContext, + clusterId: string, + expectedIdentity: VerifiedEntraIdentity, +): Promise { + if (!canSignInAgainForWorker(clusterId, expectedIdentity)) { + return undefined; + } + return signInAgainInternal(context, { clusterId }, expectedIdentity); +} + +async function signInAgainInternal( + context: IActionContext, + target: ClusterItemBase | { readonly clusterId: string }, + expectedIdentity?: VerifiedEntraIdentity, +): Promise { + const node = target && 'cluster' in target ? target : undefined; + const clusterId = target && ('cluster' in target ? target.cluster.clusterId : target.clusterId); + if (!clusterId) { + throw new Error(vscode.l10n.t('No node selected.')); + } + const epoch = ClustersClient.getEpoch(clusterId); + const reason = ClustersClient.getLatchReason(clusterId); + let closedReported = false; + const reportClosed = (): void => { + if (expectedIdentity || closedReported) { + return; + } + closedReported = true; + if (node) { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + return; + } + refreshAuthenticationNode(node); + } + const currentReason = ClustersClient.getLatchReason(clusterId); + showObsoleteTreeAction(context, currentReason, reason !== 'userDisconnected'); + }; + if (reason && reason !== 'credentialsRejected') { + reportClosed(); + return; + } + const storedIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + const identity = expectedIdentity ?? storedIdentity; + const credentials = CredentialCache.getCredentials(clusterId); + if ( + identity?.kind !== 'entra' || + credentials?.authMechanism !== AuthMethodId.MicrosoftEntraID || + identity.tenantId !== credentials.entraIdConfig?.tenantId + ) { + throw new Error(vscode.l10n.t('No verified Microsoft Entra ID connection is available to sign in again.')); + } + + context.telemetry.maskEntireErrorMessage = true; + context.errorHandling.suppressDisplay = true; + addEstablishedConnectionContext(context.telemetry, clusterId); + const isCurrent = (): boolean => { + if (ClustersClient.getEpoch(clusterId) !== epoch || CredentialCache.getCredentials(clusterId) !== credentials) { + return false; + } + if (!expectedIdentity) { + return true; + } + const currentIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + return currentIdentity?.kind === 'entra' && sameEntraIdentity(currentIdentity, expectedIdentity); + }; + let starting = false; + let establishedClient: ClustersClient | undefined; + let dismissal: unknown; + try { + const handler = new MicrosoftEntraIDAuthHandler(credentials, { + interactive: false, + pinnedEntraIdentity: identity, + getTokenLookupEpoch: () => establishedClient?.getTokenLookupEpoch(), + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), + }); + const auth = await handler.configureAuth(undefined, undefined, async (request) => { + if (!isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + let session: vscode.AuthenticationSession | undefined; + try { + session = await getEntraSession(request); + } catch (error) { + if (isSignInDismissal(error)) { + dismissal = error; + } + throw error; + } + if (!session) { + dismissal = new UserCancelledError('signInAgain'); + throw dismissal; + } + if (!isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + if (session.account.id !== identity.accountId) { + throw new EntraIdentityMismatchError(); + } + return session; + }); + if ( + expectedIdentity && + (auth.verifiedIdentity?.kind !== 'entra' || !sameEntraIdentity(auth.verifiedIdentity, expectedIdentity)) + ) { + throw new EntraIdentityMismatchError(); + } + if (!isCurrent()) { + reportClosed(); + return undefined; + } + starting = true; + const startup = ClustersClient.startAfterSignIn(clusterId, epoch, credentials, auth); + const startupEpoch = ClustersClient.getEpoch(clusterId); + const client = await startup; + if (!client || ClustersClient.getEpoch(clusterId) !== startupEpoch) { + reportClosed(); + return undefined; + } + establishedClient = client; + if ( + ClustersClient.getExistingClient(clusterId) === client && + !ClustersClient.getLatchReason(clusterId) && + node + ) { + refreshAuthenticationNode(node); + } + return auth.verifiedIdentity ? { identity: auth.verifiedIdentity, epoch: startupEpoch } : undefined; + } catch (error) { + if (dismissal !== undefined && error === dismissal) { + throw new UserCancelledError('signInAgain'); + } + if (closedReported) { + throw error; + } + if (!starting && !isCurrent()) { + reportClosed(); + return undefined; + } + if (isSignInDismissal(error)) { + throw new UserCancelledError('signInAgain'); + } + context.telemetry.properties.connectionFailureKind = classifyConnectionFailure( + error, + AuthMethodId.MicrosoftEntraID, + ).kind; + if (error instanceof EntraSignInRequiredError && error.reason === 'providerChanged') { + if (!expectedIdentity) { + await vscode.window.showErrorMessage(vscode.l10n.t('The Azure cloud or sign-in provider changed.'), { + modal: true, + detail: vscode.l10n.t( + 'Restore "microsoft-sovereign-cloud.environment" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.', + ), + }); + } + throw error; + } + if (!expectedIdentity) { + await showClusterConnectFailure({ + clusterId, + clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), + fallbackHeading: vscode.l10n.t('Could not sign in again.'), + error, + context, + }); + } + throw error; + } +} diff --git a/src/commands/updateConnectionString/ExecuteStep.ts b/src/commands/updateConnectionString/ExecuteStep.ts index 72f517229..e195ddb64 100644 --- a/src/commands/updateConnectionString/ExecuteStep.ts +++ b/src/commands/updateConnectionString/ExecuteStep.ts @@ -18,9 +18,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { public priority: number = 100; public async execute(context: UpdateCSWizardContext): Promise { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connection = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connection || !connection.secrets?.connectionString) { ext.outputChannel.error( @@ -87,6 +93,9 @@ export class ExecuteStep extends AzureWizardExecuteStep { await ConnectionStorageService.save(resourceType, connection, true); context.connectionStringSaved = true; + if (context.isRecoveryCurrent?.() === false) { + return; + } if (clearedEntraMethod) { void window.showInformationMessage( diff --git a/src/commands/updateConnectionString/UpdateCSWizardContext.ts b/src/commands/updateConnectionString/UpdateCSWizardContext.ts index 81fe2af6e..ba54a2dac 100644 --- a/src/commands/updateConnectionString/UpdateCSWizardContext.ts +++ b/src/commands/updateConnectionString/UpdateCSWizardContext.ts @@ -16,4 +16,5 @@ export interface UpdateCSWizardContext extends IActionContext { originalConnectionString: string; newConnectionString?: string; connectionStringSaved?: boolean; + isRecoveryCurrent?: () => boolean; } diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 5c09c56c8..4ca0b26e7 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -36,10 +36,22 @@ import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; import { updateConnectionString } from './updateConnectionString'; -const { capturedContexts, showInputBox, showQuickPick } = vi.hoisted(() => ({ +const { + capturedContexts, + showInputBox, + showQuickPick, + getConflictingTasks, + getPlaygroundEvaluators, + getRegisteredShellTerminals, + stopPlaygroundEvaluator, +} = vi.hoisted(() => ({ capturedContexts: [] as UpdateCSWizardContext[], showInputBox: vi.fn(), showQuickPick: vi.fn(), + getConflictingTasks: vi.fn(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), + stopPlaygroundEvaluator: vi.fn(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -73,9 +85,13 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ _name: string, callback: (context: IActionContext) => Promise, ): Promise => { + const context = makeContext(); try { - return await callback(makeContext()); - } catch { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } return undefined; } }, @@ -85,7 +101,21 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + getExistingClient: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + retireBoundViews: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + discardEntraPinForDifferentTenant: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, @@ -94,6 +124,9 @@ vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: vi.fn(() => false) }, })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks } })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators, stopPlaygroundEvaluator })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals })); vi.mock('../../extensionVariables', () => ({ ext: { outputChannel: { appendLine: vi.fn(), append: vi.fn(), debug: vi.fn(), info: vi.fn(), error: vi.fn() }, @@ -106,6 +139,12 @@ vi.mock('../../tree/connections-view/LocalQuickStart/LocalQuickStartItem', () => const originalUri = 'mongodb://old.example.com/'; const approvedUri = 'mongodb://new.mongocluster.cosmos.azure.com/'; const deleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); function makeContext(): IActionContext { return { @@ -145,10 +184,35 @@ describe('updateConnectionString rejected-destination recovery', () => { let provider: ConnectionsBranchDataProvider; let storedConnection: ConnectionItem; let item: DocumentDBClusterItem; + let epoch: number; + let latch: ReturnType; beforeEach((): void => { CredentialCache.deleteCredentials('stable-id'); vi.resetAllMocks(); + epoch = 0; + latch = undefined; + vi.mocked(ClustersClient.getEpoch).mockImplementation(() => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + getConflictingTasks.mockReturnValue([]); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; provider = new ConnectionsBranchDataProvider(); ext.connectionsBranchDataProvider = provider; @@ -166,7 +230,7 @@ describe('updateConnectionString rejected-destination recovery', () => { items.find((entry) => entry.authMethod === AuthMethodId.NoAuth), ); CredentialCache.setAuthCredentials('stable-id', AuthMethodId.ManagedIdentity, originalUri); - vi.mocked(ClustersClient.getClient).mockRejectedValue( + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'old.example.com', hostCount: 1 }), ); }); @@ -180,11 +244,12 @@ describe('updateConnectionString rejected-destination recovery', () => { const failedChildren = await provider.getChildren(item); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(item.lastConnectionFailureReason).toBe('entraDestinationRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); showInputBox.mockResolvedValue(newUri); vi.mocked(ClustersClient.deleteClient).mockImplementation(async (): Promise => { - expect(storedConnection.secrets.connectionString).toBe(newUri); + expect(storedConnection.secrets.connectionString).toBe(originalUri); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(CredentialCache.hasCredentials('stable-id')).toBe(true); }); @@ -192,28 +257,34 @@ describe('updateConnectionString rejected-destination recovery', () => { await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { + alreadyInvalidated: true, + }); expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).toHaveBeenCalledExactlyOnceWith(item.id); expect(provider.hasNodeErrorState(item.id)).toBe(false); expect(CredentialCache.hasCredentials('stable-id')).toBe(false); expect(item.lastConnectionFailureReason).toBeUndefined(); expect(item.lastConnectionOutcome).toBeUndefined(); - expect(vi.mocked(ConnectionStorageService.save).mock.invocationCallOrder[0]).toBeLessThan( - vi.mocked(ClustersClient.deleteClient).mock.invocationCallOrder[0], - ); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(showInputBox); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(vi.mocked(ConnectionStorageService.save)); expect(deleteCredentials.mock.invocationCallOrder[0]).toBeLessThan(resetError.mock.invocationCallOrder[0]); - expect(resetError.mock.invocationCallOrder[0]).toBeLessThan(refresh.mock.invocationCallOrder[0]); + expect(resetError.mock.invocationCallOrder[0]).toBeLessThan( + refresh.mock.invocationCallOrder[refresh.mock.invocationCallOrder.length - 1], + ); const client = { listDatabases: vi.fn().mockResolvedValue([]), connectionCorrelationId: 'retry' }; - vi.mocked(ClustersClient.getClient).mockImplementation(async (clusterId): Promise => { - expect(clusterId).toBe('stable-id'); - expect(CredentialCache.getCredentials(clusterId)).toMatchObject({ - connectionString: newUri, - authMechanism: expectedMethod, - }); - return client as unknown as ClustersClient; - }); + vi.mocked(ClustersClient.connectInteractive).mockImplementation( + async (clusterId): Promise => { + expect(clusterId).toBe('stable-id'); + expect(CredentialCache.getCredentials(clusterId)).toMatchObject({ + connectionString: newUri, + authMechanism: expectedMethod, + }); + return client as unknown as ClustersClient; + }, + ); + ClustersClient.unlatch('stable-id'); const retriedChildren = await provider.getChildren(item); expect(retriedChildren).not.toEqual(failedChildren); @@ -263,21 +334,68 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); - it('leaves the existing connected-edit lifecycle unchanged after a successful ordinary edit', async (): Promise => { + it('ends the old session before an ordinary saved edit', async (): Promise => { const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; - const cachedCredentials = CredentialCache.getCredentials('stable-id'); + vi.mocked(ClustersClient.exists).mockReturnValue(true); await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); - expect(deleteCredentials).not.toHaveBeenCalled(); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(1, 'stable-id'); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(2, 'stable-id'); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); + expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).not.toHaveBeenCalled(); - expect(CredentialCache.getCredentials('stable-id')).toBe(cachedCredentials); + expect(CredentialCache.getCredentials('stable-id')).toBeUndefined(); expect(item.lastConnectionOutcome).toBe('connected'); - expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).toHaveBeenCalledTimes(2); + expect(latch).toBe('userDisconnected'); + }); + + it('does not save an ordinary edit superseded while the input is open', async (): Promise => { + const refresh = vi.spyOn(provider, 'refresh'); + item.lastConnectionOutcome = 'connected'; + showInputBox.mockImplementationOnce(async (): Promise => { + epoch++; + return approvedUri; + }); + + await updateConnectionString(makeContext(), item); + + expect(storedConnection.secrets.connectionString).toBe(originalUri); + expect(capturedContexts[0].connectionStringSaved).toBe(false); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(deleteCredentials).not.toHaveBeenCalled(); + expect(refresh).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + }); + + it('does not begin the wizard or save when Disconnect is declined', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showWarning.mockResolvedValueOnce(undefined); + + await expect(updateConnectionString(makeContext(), item)).rejects.toBeInstanceOf(UserCancelledError); + + expect(capturedContexts).toHaveLength(0); + expect(showInputBox).not.toHaveBeenCalled(); + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + }); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showInputBox.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateConnectionString(makeContext(), item)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(ClustersClient.deleteClient).toHaveBeenCalledOnce(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); }); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index cfb7f9d25..2734435d8 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -5,8 +5,9 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; -import { CredentialCache } from '../../documentdb/CredentialCache'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { maskSensitiveValuesInTelemetry } from '../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -15,6 +16,7 @@ import { ConnectionStorageService } from '../../services/connectionStorageServic import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { ConnectionStringStep } from './ConnectionStringStep'; import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; @@ -23,20 +25,24 @@ import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; * Updates the connection string (hosts, ports, etc.) for a cluster connection. * * Architecture: - * 1. Loads the current connection string with credentials masked + * 1. Ends the old session, then loads the current connection string with credentials masked * 2. Runs wizard to collect new connection string: * - ConnectionStringStep: Enter new connection string * 3. ExecuteStep: Saves updated connection string to storage * 4. Post-wizard: Refreshes the view * - * Only a successful destination-rejection recovery edit clears cached connection and error state. - * Other edits retain the existing connection lifecycle. + * Tabs kept during Disconnect remain read-only, even if the edit is cancelled. */ export async function updateConnectionString(context: IActionContext, node: DocumentDBClusterItem): Promise { if (!node) { throw new Error(l10n.t('No node selected.')); } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; + const clusterId = node.cluster.clusterId; + const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); + const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; + const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // Extract the connection string but hide the username and password @@ -46,6 +52,9 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } const connectionString = connection?.secrets?.connectionString || ''; context.valuesToMask.push(connectionString); @@ -63,6 +72,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -72,11 +82,24 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); - await wizard.execute(); - - if (recoveringRejectedDestination && wizardContext.connectionStringSaved) { - await ClustersClient.deleteClient(node.cluster.clusterId); - CredentialCache.deleteCredentials(node.cluster.clusterId); + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); + return; + } + const changed = + wizardContext.newConnectionString && + wizardContext.newConnectionString !== wizardContext.originalConnectionString + ? await saveConnectionEdit( + node, + async (isCurrent) => { + wizardContext.isRecoveryCurrent = isCurrent; + await wizard.execute(); + return wizardContext.connectionStringSaved === true; + }, + { canStart: () => canSaveEdit(clusterId, epoch) }, + ) + : false; + if (recovering && changed && wizardContext.connectionStringSaved) { ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); node.lastConnectionFailureReason = undefined; node.lastConnectionOutcome = undefined; diff --git a/src/commands/updateCredentials/ExecuteStep.ts b/src/commands/updateCredentials/ExecuteStep.ts index 4e2d78552..d37c7ac03 100644 --- a/src/commands/updateCredentials/ExecuteStep.ts +++ b/src/commands/updateCredentials/ExecuteStep.ts @@ -27,9 +27,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connectionCredentials = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connectionCredentials) { ext.outputChannel.error(l10n.t('Failed to save credentials: connection not found in storage.')); @@ -101,6 +107,10 @@ export class ExecuteStep extends AzureWizardExecuteStep => { // Load available tenants from Azure subscription provider - const { tenants, status } = await this.getAvailableTenants(subscriptionProvider, lookupTimeoutMs); + const { tenants, status } = await this.getAvailableTenants( + subscriptionProvider, + lookupTimeoutMs, + reloadTenants, + ); context.telemetry.measurements.availableTenantsCount = tenants.length; // Create quick pick items @@ -119,9 +128,11 @@ export class PromptTenantStep extends AzureWizardPromptStep { try { - return await traceTenantLookup('updateCredentials.isSignedIn', () => subscriptionProvider.isSignedIn(), { - timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, - fallbackValue: true, - }); + return await traceTenantLookup( + 'updateCredentials.isSignedIn', + () => subscriptionProvider.signIn(undefined, { promptIfNeeded: false }), + { timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, fallbackValue: true }, + ); } catch { return true; } @@ -188,12 +200,13 @@ export class PromptTenantStep extends AzureWizardPromptStep { let timedOut = false; try { const tenants = await traceTenantLookup( 'updateCredentials.getTenants', - () => subscriptionProvider.getTenants(), + () => getUnfilteredAzureTenants(subscriptionProvider, noCache), { timeoutMs, fallbackValue: [], diff --git a/src/commands/updateCredentials/UpdateCredentialsWizardContext.ts b/src/commands/updateCredentials/UpdateCredentialsWizardContext.ts index f759040af..17bb6145a 100644 --- a/src/commands/updateCredentials/UpdateCredentialsWizardContext.ts +++ b/src/commands/updateCredentials/UpdateCredentialsWizardContext.ts @@ -36,4 +36,6 @@ export interface UpdateCredentialsWizardContext extends IActionContext { isErrorState: boolean; /** Set by the reconnect prompt; when true, error state is cleared to trigger a reconnect. */ reconnectAfterError: boolean; + isRecoveryCurrent?: () => boolean; + credentialsSaved?: boolean; } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 03545615a..d7aa58e42 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -3,66 +3,147 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; import { API } from '../../DocumentDBExperiences'; +import { ext } from '../../extensionVariables'; import type * as storageModule from '../../services/connectionStorageService'; import { ItemType } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; +import { ExecuteStep } from './ExecuteStep'; import { updateCredentials } from './updateCredentials'; import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardContext'; const capturedContexts: UpdateCredentialsWizardContext[] = []; +const mockExecute = vi.fn<(context: UpdateCredentialsWizardContext) => Promise>().mockResolvedValue(undefined); +const mockPrompt = vi.fn<() => Promise>(); const mockGet = vi.fn(); +const mockSave = vi.fn(); +const mockGetEpoch = vi.fn(() => 0); const mockDeleteClient = vi.fn(); +const mockRetireBoundViews = vi.hoisted(() => vi.fn()); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); const mockGetRegisteredShellTerminals = vi.fn(); +const mockGetPlaygroundEvaluators = vi.fn(); +const mockGetConflictingTasks = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +let epoch = 0; +let latch: ReturnType; vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ AzureWizard: typeof AzureWizard }>()), AzureWizard: class { - constructor(context: UpdateCredentialsWizardContext) { + constructor(private readonly context: UpdateCredentialsWizardContext) { capturedContexts.push(context); } public prompt(): Promise { - return Promise.resolve(); + return mockPrompt(); } public execute(): Promise { - return Promise.resolve(); + return mockExecute(this.context); + } + }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + try { + await callback({ + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + } as unknown as IActionContext); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + throw error; + } } }, })); vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ...(await importOriginal()), - ConnectionStorageService: { get: (...args: unknown[]): unknown => mockGet(...args) }, + ConnectionStorageService: { + get: (...args: unknown[]): unknown => mockGet(...args), + save: (...args: unknown[]): unknown => mockSave(...args), + }, })); vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, + getEpoch: (): number => mockGetEpoch(), + getLatchReason: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + retireBoundViews: mockRetireBoundViews, + clearLastVerifiedIdentity: vi.fn(), + discardEntraPinForDifferentTenant: vi.fn(), }, })); vi.mock('../playground/executePlaygroundCode', () => ({ - shutdownEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), + stopPlaygroundEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), + getPlaygroundEvaluators: (): unknown => mockGetPlaygroundEvaluators(), })); vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), })); vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: (): undefined => undefined } })); +vi.mock('../../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (...args: unknown[]): unknown => mockGetConflictingTasks(...args) }, +})); vi.mock('../../extensionVariables', () => ({ - ext: { connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(() => false) } }, + ext: { + connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + outputChannel: { error: vi.fn(), warn: vi.fn() }, + }, })); beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); + epoch = 0; + latch = undefined; + mockGetEpoch.mockImplementation((): number => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + mockDeleteClient.mockReset().mockResolvedValue(undefined); + mockPrompt.mockReset().mockResolvedValue(undefined); + mockExecute.mockReset().mockResolvedValue(undefined); + mockGetConflictingTasks.mockReturnValue([]); + mockGetPlaygroundEvaluators.mockReturnValue(new Map()); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); mockGetRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; }); @@ -96,7 +177,7 @@ async function inferMethods( cluster: { clusterId: 'stable-cluster-id', treeId: 'folder/current-tree-path' }, } as unknown as DocumentDBClusterItem; await updateCredentials(context, node); - expect(mockDeleteClient).toHaveBeenCalledWith('stable-cluster-id'); + expect(mockDeleteClient).not.toHaveBeenCalled(); expect(mockDeleteCredentials).not.toHaveBeenCalled(); const captured = capturedContexts[0]; if (!captured) { @@ -208,6 +289,91 @@ describe('updateCredentials post-wizard updates', () => { ); }); + it('disconnects before prompting and saving a password-only edit', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + let storedConnection: storageModule.ConnectionItem = originalConnection; + const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + mockGet.mockImplementation(async () => structuredClone(storedConnection)); + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = newCredentials; + await new ExecuteStep().execute(wizardContext); + }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem): Promise => { + storedConnection = structuredClone(item); + }, + ); + + await updateCredentials(context, node); + + expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); + expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); + expect(capturedContexts[0].credentialsSaved).toBe(true); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); + expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockSave); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); + }); + + it.each([true, false])( + 'only clears rejection and refreshes the recovery node when an unchanged edit saves (%s)', + async (saved) => { + latch = 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(true); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + mockExecute.mockImplementationOnce((wizardContext) => { + wizardContext.reconnectAfterError = true; + wizardContext.credentialsSaved = saved; + return Promise.resolve(); + }); + + await updateCredentials(context, node); + + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); + if (saved) { + expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(ClustersClient.unlatch).toHaveBeenCalledBefore( + vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState), + ); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + } else { + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + } + }, + ); + + it('keeps the ended session disconnected if a secret write persists but metadata fails', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + const stored = structuredClone(originalConnection); + mockGet.mockImplementation(async () => structuredClone(stored)); + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + await new ExecuteStep().execute(wizardContext); + }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem) => { + stored.secrets = structuredClone(item.secrets); + throw new Error('Metadata write failed'); + }, + ); + + await updateCredentials(context, node); + + expect(capturedContexts[0].credentialsSaved).not.toBe(true); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + }); + it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ { authMethod: AuthMethodId.NativeAuth, @@ -224,18 +390,24 @@ describe('updateCredentials post-wizard updates', () => { }, { authMethod: AuthMethodId.NoAuth, secrets: {} }, ])( - 'caches the saved $authMethod credentials and shuts down the old client and playground', + 'caches the saved $authMethod credentials without redundantly tearing down an idle connection', async ({ authMethod, secrets }) => { const savedConnection: storageModule.ConnectionItemInput = { ...originalConnection, properties: { ...originalConnection.properties, selectedAuthMethod: authMethod }, secrets: { connectionString: 'mongodb://new.example.com:27017/', ...secrets }, }; - mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(savedConnection); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue(savedConnection); + mockExecute.mockImplementationOnce(async (wizardContext) => { + wizardContext.credentialsSaved = true; + }); await updateCredentials(context, node); - expect(mockGet).toHaveBeenCalledTimes(2); + expect(mockGet).toHaveBeenCalledTimes(3); expect(mockGet.mock.calls[1]).toEqual(mockGet.mock.calls[0]); expect(CredentialCache.getCredentials(node.cluster.clusterId)).toEqual({ clusterId: node.cluster.clusterId, @@ -251,20 +423,23 @@ describe('updateCredentials post-wizard updates', () => { managedIdentityConfig: secrets.managedIdentityAuthConfig, }); expect(CredentialCache.hasCredentials(node.cluster.treeId)).toBe(false); - expect(mockDeleteCredentials).not.toHaveBeenCalled(); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); }, ); it('deletes cached credentials when stored native authentication has no password', async () => { - mockGet.mockResolvedValue({ - ...originalConnection, - secrets: { - ...originalConnection.secrets, - nativeAuthConfig: { connectionUser: 'new-user' }, - }, - }); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + secrets: { + ...originalConnection.secrets, + nativeAuthConfig: { connectionUser: 'new-user' }, + }, + }); await updateCredentials(context, node); @@ -273,10 +448,13 @@ describe('updateCredentials post-wizard updates', () => { }); it('deletes cached credentials when the stored authentication method is missing', async () => { - mockGet.mockResolvedValue({ - ...originalConnection, - properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, - }); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, + }); await updateCredentials(context, node); @@ -284,21 +462,34 @@ describe('updateCredentials post-wizard updates', () => { expect(CredentialCache.getCredentials(node.cluster.clusterId)).toBeUndefined(); }); - it('shows a modal without action items when a shell for the cluster is open', async () => { + it('stops only matching shells before editing without a post-save shell modal', async () => { + const disconnect = vi.fn(); + const disconnectOther = vi.fn(); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + secrets: { + ...originalConnection.secrets, + nativeAuthConfig: { connectionUser: 'old-user', connectionPassword: 'new-password' }, + }, + }); + mockExecute.mockImplementationOnce(async (wizardContext) => { + wizardContext.credentialsSaved = true; + }); mockGetRegisteredShellTerminals.mockReturnValue([ - { info: { clusterId: 'another-cluster-id' } }, - { info: { clusterId: node.cluster.clusterId } }, + { info: { clusterId: 'another-cluster-id' }, disconnect: disconnectOther }, + { info: { clusterId: node.cluster.clusterId }, disconnect }, ]); await updateCredentials(context, node); - expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - "Credentials updated. New connections will use them. Open shells for 'cluster' keep their current connection until you close them.", - { modal: true }, - ); - const modalCallOrder = vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0]; - expect(mockDeleteClient.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); - expect(mockShutdownEvaluator.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(disconnect).toHaveBeenCalledOnce(); + expect(disconnectOther).not.toHaveBeenCalled(); + expect(disconnect).toHaveBeenCalledBefore(mockPrompt); + expect(mockShutdownEvaluator).toHaveBeenCalledBefore(mockPrompt); }); it.each([ @@ -315,4 +506,43 @@ describe('updateCredentials post-wizard updates', () => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }); + + it('does not begin the wizard or save when Disconnect is declined', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showWarning.mockResolvedValueOnce(undefined); + + await expect(updateCredentials(context, node)).rejects.toBeInstanceOf(UserCancelledError); + + expect(capturedContexts).toHaveLength(0); + expect(mockPrompt).not.toHaveBeenCalled(); + expect(mockGet).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + }); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + mockPrompt.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateCredentials(context, node)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(mockDeleteClient).toHaveBeenCalledOnce(); + expect(mockSave).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }); + + it('does not save an ordinary edit superseded while the wizard is open', async (): Promise => { + mockPrompt.mockImplementationOnce(async (): Promise => { + epoch++; + }); + + await updateCredentials(context, node); + + expect(mockExecute).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + expect(mockDeleteCredentials).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + }); }); diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 301e09c7d..543ace0d9 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -5,7 +5,7 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import * as vscode from 'vscode'; +import { window } from 'vscode'; import { AuthMethodId, authMethodFromString, @@ -14,8 +14,8 @@ import { } from '../../documentdb/auth/AuthMethod'; import { evaluateEntraDestinationFromSettings } from '../../documentdb/auth/entraDestinationSettings'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; @@ -23,8 +23,8 @@ import { ext } from '../../extensionVariables'; import { ConnectionStorageService, isConnection } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; -import { shutdownEvaluator } from '../playground/executePlaygroundCode'; import { refreshView } from '../refreshView/refreshView'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { PromptAuthMethodStep } from '../updateCredentials/PromptAuthMethodStep'; import { ExecuteStep } from './ExecuteStep'; import { PromptPasswordStep } from './PromptPasswordStep'; @@ -37,7 +37,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * Updates the authentication credentials for a cluster connection. * * Architecture: - * 1. Loads stored credentials and determines available authentication methods + * 1. Ends the old session, then loads stored credentials and available authentication methods * 2. Runs wizard to collect new credentials from user: * - PromptAuthMethodStep: Select authentication method * - SelectEntraTokenSourceStep: Select account sign-in or a managed identity (if needed) @@ -46,8 +46,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * - PromptPasswordStep: Enter password (if needed) * - PromptReconnectStepForErrorNodes: Ask to reconnect (only for error nodes) * 3. ExecuteStep: Saves updated credentials to storage - * 4. Post-wizard: Refreshes cached credentials, drops the client and playground worker, - * warns about open shells, and optionally resets error state for reconnection + * 4. Post-wizard: Refreshes cached credentials and optionally resets error state for reconnection * * For error recovery nodes, prompts whether to reconnect immediately. If user chooses * not to reconnect, the error state is preserved and the node remains as an error node. @@ -57,6 +56,12 @@ export async function updateCredentials(context: IActionContext, node: DocumentD if (!node) { throw new Error(l10n.t('No node selected.')); } + const clusterId = node.cluster.clusterId; + const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); + const isRecoveryCurrent = recoveringRejection + ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch + : undefined; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); @@ -72,6 +77,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } // Type guard ensures we have connection properties (not a folder) const connectionCredentials = storedItem && isConnection(storedItem) ? storedItem : undefined; const connectionString = connectionCredentials?.secrets?.connectionString || ''; @@ -115,6 +123,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -137,48 +146,51 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); - await wizard.execute(); - - await ClustersClient.deleteClient(node.cluster.clusterId); - - const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); - const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; - const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); - const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; - const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; - if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { - const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); - - CredentialCache.setAuthCredentials( - node.cluster.clusterId, - authMethod, - connectionString.toString(), - username && password ? { connectionUser: username, connectionPassword: password } : undefined, - node.cluster.emulatorConfiguration, - updatedConnection.secrets.entraIdAuthConfig, - updatedConnection.secrets.managedIdentityAuthConfig, - ); - } else { - // Clear stale credentials so the tree can prompt from storage. - CredentialCache.deleteCredentials(node.cluster.clusterId); - } - - shutdownEvaluator(node.cluster.clusterId); - - if (getRegisteredShellTerminals().some(({ info }) => info.clusterId === node.cluster.clusterId)) { - void vscode.window.showInformationMessage( - l10n.t( - "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.", - { cluster: node.cluster.name }, - ), - { modal: true }, - ); + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); + return; } + await saveConnectionEdit( + node, + async (isCurrent) => { + wizardContext.isRecoveryCurrent = isCurrent; + await wizard.execute(); + return wizardContext.credentialsSaved === true; + }, + { + canStart: () => canSaveEdit(clusterId, epoch), + publishCredentials: (updated): void => { + if (!updated || !isConnection(updated)) { + return; + } + const authMethod = authMethodFromString(updated.properties.selectedAuthMethod); + const native = updated.secrets.nativeAuthConfig; + if ( + !authMethod || + (authMethod === AuthMethodId.NativeAuth && (!native?.connectionUser || !native.connectionPassword)) + ) { + return; + } + CredentialCache.setAuthCredentials( + clusterId, + authMethod, + new DocumentDBConnectionString(updated.secrets.connectionString).toString(), + native?.connectionUser && native.connectionPassword ? native : undefined, + node.cluster.emulatorConfiguration, + updated.secrets.entraIdAuthConfig, + updated.secrets.managedIdentityAuthConfig, + ); + }, + }, + ); // When the node is in an error state, only clear it if the user chose to reconnect. // Clearing the error state triggers a fresh connection attempt on refresh. - if (node.id && wizardContext.isErrorState) { + if (wizardContext.credentialsSaved && node.id && wizardContext.isErrorState) { if (wizardContext.reconnectAfterError) { + if (ClustersClient.getLatchReason(clusterId) === 'userDisconnected') { + ClustersClient.unlatch(clusterId); + } ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); context.telemetry.properties.reconnected = 'true'; } diff --git a/src/connectionDiagnostics/acceptance.test.ts b/src/connectionDiagnostics/acceptance.test.ts index 293896e5d..82b10be49 100644 --- a/src/connectionDiagnostics/acceptance.test.ts +++ b/src/connectionDiagnostics/acceptance.test.ts @@ -95,8 +95,9 @@ vi.mock('../extensionVariables', () => ({ outputChannel: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), trace: vi.fn(), debug: vi.fn() }, }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]): unknown => bridge.getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: bridge.getSessionFromVSCode }, })); vi.mock('../documentdb/auth/managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken: (...args: unknown[]): unknown => bridge.getManagedIdentityAccessToken(...args), diff --git a/src/connectionDiagnostics/checks/authenticate.test.ts b/src/connectionDiagnostics/checks/authenticate.test.ts index 2bf54d48e..e9b07d38a 100644 --- a/src/connectionDiagnostics/checks/authenticate.test.ts +++ b/src/connectionDiagnostics/checks/authenticate.test.ts @@ -24,6 +24,7 @@ import { MongoServerSelectionError, type MongoClientOptions, type OIDCCallbackParams, + type OIDCResponse, type TopologyDescription, } from 'mongodb'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -32,6 +33,7 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { AuthInputUnavailableError } from '../../documentdb/auth/createAuthHandler'; import type * as documentdbTokenResource from '../../documentdb/auth/documentdbTokenResource'; import { type TokenResourceResolverDeps } from '../../documentdb/auth/documentdbTokenResource'; +import { EntraIdentityMismatchError, TokenCallbackError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import type * as entraTokenFailures from '../../documentdb/auth/entraErrors/entraTokenFailures'; import { clearEntraTokenFailure, @@ -58,8 +60,9 @@ const mocks = vi.hoisted(() => ({ vi.mock('../../extensionVariables', () => ({ ext: { outputChannel: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), trace: vi.fn(), debug: vi.fn() } }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]): unknown => mocks.getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: mocks.getSessionFromVSCode }, })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal()), @@ -189,6 +192,14 @@ interface FakeClient { readonly close: ReturnType; } +function invokeOidcCallback(client: FakeClient): Promise { + const callback = client.options.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Missing OIDC callback'); + } + return callback({ version: 1, timeoutContext: new AbortController().signal }); +} + let connectBehavior: (client: FakeClient) => Promise; let clients: FakeClient[]; let tick: number; @@ -946,9 +957,11 @@ describe('createAuthenticateCheck', (): void => { hostCloud: 'AzureCloud', entraFailureKind: 'none', }); - expect(mocks.getSessionFromVSCode).toHaveBeenCalledWith([`${publicResource}/.default`], tenant, { - silent: true, - }); + expect(mocks.getSessionFromVSCode).toHaveBeenCalledWith( + 'microsoft', + [`${publicResource}/.default`, `VSCODE_TENANT:${tenant}`], + { silent: true }, + ); for (const call of mocks.getSessionFromVSCode.mock.calls) { expect(JSON.stringify(call[2])).not.toMatch(/createIfNone|forceNewSession/); } @@ -957,6 +970,7 @@ describe('createAuthenticateCheck', (): void => { it('keeps audience and tenant mismatches as warnings that never fail the check by themselves', async (): Promise => { mocks.getSessionFromVSCode.mockResolvedValue({ accessToken: entraToken({ aud: governmentResource, tid: '99999999-2222-3333-4444-555555555555' }), + account: { label: 'alice@contoso.example', id: 'account-id' }, }); const { result } = await runAuth( setupFor(AuthMethodId.MicrosoftEntraID, publicHost, { entraIdConfig: { tenantId: tenant } }), @@ -971,6 +985,151 @@ describe('createAuthenticateCheck', (): void => { expect(result.facts.authenticated).toBe(true); }); + it('replaces eager evidence with the latest callback claims without changing timing or accepting late events', async (): Promise => { + const account = { label: 'alice@contoso.example', id: 'account-id' }; + const mismatchedToken = entraToken({ aud: governmentResource, tid: 'different-tenant' }); + const callbackToken = entraToken({ ver: '1.0' }); + mocks.getSessionFromVSCode + .mockResolvedValue({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: callbackToken, account }); + connectBehavior = async (client): Promise => { + await expect(invokeOidcCallback(client)).resolves.toMatchObject({ accessToken: mismatchedToken }); + await expect(invokeOidcCallback(client)).resolves.toMatchObject({ accessToken: callbackToken }); + }; + const deps = fakeDeps(); + const now = vi.fn(deps.now); + const { result, events, telemetry } = await runAuth( + setupFor(AuthMethodId.MicrosoftEntraID, publicHost, { entraIdConfig: { tenantId: tenant } }), + { deps: { ...deps, now } }, + ); + expect(result.status).toBe('pass'); + const token = step(result, 'auth.token'); + expect(token).toMatchObject({ + status: 'pass', + durationMs: 10, + facts: { claims: { tokenVersion: '1.0', audience: 'match', tenantMatch: 'match' } }, + }); + expect(token.findings).toEqual([]); + const snapshots = JSON.stringify([result, events, telemetry]); + const clockCalls = now.mock.calls.length; + await expect(invokeOidcCallback(clients[0])).resolves.toMatchObject({ accessToken: mismatchedToken }); + expect(now).toHaveBeenCalledTimes(clockCalls); + expect(JSON.stringify([result, events, telemetry])).toBe(snapshots); + for (const secret of [callbackToken, callbackToken.split('.')[1], claimSentinel]) { + expect(snapshots + outputLines().join('\n')).not.toContain(secret); + } + }); + + it.each(['callback noSession', 'initial providerChanged'] as const)( + 'skips unavailable Entra input on %s without recording authError', + async (kind): Promise => { + if (kind === 'callback noSession') { + mocks.getSessionFromVSCode + .mockResolvedValueOnce({ + accessToken: entraToken({ aud: governmentResource }), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }) + .mockResolvedValueOnce(undefined); + connectBehavior = async (client): Promise => { + await invokeOidcCallback(client); + }; + } else { + mocks.getSessionFromVSCode.mockImplementationOnce(async () => { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn((name: string): string | undefined => + name === 'environment' ? 'USGovernment' : undefined, + ), + inspect: vi.fn().mockReturnValue(undefined), + } as unknown as vscode.WorkspaceConfiguration); + return { + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }; + }); + } + const { result, holder } = await runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost)); + expect(clients).toHaveLength(kind === 'callback noSession' ? 1 : 0); + expect(holder.authError).toBeUndefined(); + expect(holder.client).toBeUndefined(); + expect(result).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'inputUnavailable' }, + facts: { signInLimitation: 'silentLookupCannotDistinguishConsent', authenticated: false }, + }); + expect(result.facts.account).toBeUndefined(); + expect(codes(result)).toEqual(['auth.credentialsUnavailable']); + expect(step(result, 'auth.token')).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'inputUnavailable' }, + }); + expect(step(result, 'auth.token').facts).toEqual({}); + expect(step(result, 'auth.token').findings).toEqual([]); + expect(step(result, 'auth.serverAuthentication')).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'dependencySkipped', stepId: 'auth.token' }, + }); + expect(recordEntraTokenFailure).not.toHaveBeenCalled(); + }, + ); + + it.each([ + [TokenCallbackError, 'resourceNotInTenant', '500011'], + [EntraIdentityMismatchError, 'unclassified', undefined], + ] as const)( + 'replaces eager evidence for callback-only %s with bounded token failure evidence', + async (errorType, ruleId, aadstsCode): Promise => { + const accessToken = entraToken({ aud: governmentResource }); + mocks.getSessionFromVSCode.mockResolvedValueOnce({ + accessToken, + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); + if (errorType === TokenCallbackError) { + mocks.getSessionFromVSCode.mockRejectedValueOnce(new Error(`AADSTS500011: ${errorSentinel}`)); + } else { + mocks.getSessionFromVSCode.mockResolvedValueOnce({ + accessToken, + account: { label: errorSentinel, id: 'different-account' }, + }); + } + connectBehavior = async (client): Promise => { + await invokeOidcCallback(client); + }; + const { result, holder, events, telemetry } = await runAuth( + setupFor(AuthMethodId.MicrosoftEntraID, publicHost), + ); + expect(holder.authError).toBeInstanceOf(errorType); + expect(holder.client).toBeUndefined(); + expect(result).toMatchObject({ status: 'fail', facts: { authenticated: false } }); + expect(result.facts.account).toBeUndefined(); + const token = step(result, 'auth.token'); + expect(token).toMatchObject({ + status: 'fail', + facts: { errorName: errorType.name, ruleId }, + }); + expect(token.facts.claims).toBeUndefined(); + expect(token.facts.aadstsCode).toBe(aadstsCode); + expect(token.findings).toEqual([ + expect.objectContaining({ + code: 'auth.entraTokenFailed', + data: { + ruleId, + ...(aadstsCode === undefined ? {} : { aadstsCode }), + authMethod: AuthMethodId.MicrosoftEntraID, + }, + }), + ]); + const server = step(result, 'auth.serverAuthentication'); + expect(server.status).toBe('fail'); + expect(server.findings).toEqual([]); + expect(result.findings).toEqual([]); + expect(JSON.stringify([result, events, telemetry]) + outputLines().join('\n')).not.toContain( + errorSentinel, + ); + }, + ); + it('never claims acceptance when the token succeeds and the server rejects it', async (): Promise => { connectBehavior = (): Promise => Promise.reject( @@ -978,7 +1137,11 @@ describe('createAuthenticateCheck', (): void => { ); const { result, holder } = await runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost)); expect(result).toMatchObject({ status: 'fail', facts: { authenticated: false } }); - expect(step(result, 'auth.token').status).toBe('pass'); + expect(step(result, 'auth.token')).toMatchObject({ + status: 'pass', + facts: { claims: { available: true, audience: 'match', tokenVersion: '2.0' } }, + }); + expect(mocks.getSessionFromVSCode).toHaveBeenCalledOnce(); const server = step(result, 'auth.serverAuthentication'); expect(server).toMatchObject({ status: 'fail', @@ -1150,6 +1313,48 @@ describe('createAuthenticateCheck', (): void => { }); describe('owned client lifetime', (): void => { + it('does not summarize a callback lookup that completes after cancellation while connect is pending', async (): Promise => { + const controller = new AbortController(); + const lookup = pending(); + const startedLookup = pending(); + const finishedCallback = pending(); + const connection = pending(); + mocks.getSessionFromVSCode.mockImplementationOnce(async () => ({ + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + })); + mocks.getSessionFromVSCode.mockImplementationOnce(() => { + startedLookup.resolve(); + return lookup.promise; + }); + connectBehavior = async (client): Promise => { + try { + await invokeOidcCallback(client); + } finally { + finishedCallback.resolve(); + } + await connection.promise; + }; + const deps = fakeDeps(); + const now = vi.fn(deps.now); + const running = runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost), { + signal: controller.signal, + deps: { ...deps, now }, + }); + await startedLookup.promise; + controller.abort(); + await expect(running).rejects.toBeInstanceOf(DiagnosticsCancelledError); + const clockCalls = now.mock.calls.length; + lookup.resolve({ + accessToken: entraToken({ ver: '1.0' }), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); + await finishedCallback.promise; + expect(now).toHaveBeenCalledTimes(clockCalls); + connection.resolve(); + await flush(); + }); + it('closes a client that finishes connecting after the run timed out, and never publishes it', async (): Promise => { const connection = pending(); connectBehavior = (): Promise => connection.promise; @@ -1188,7 +1393,10 @@ describe('createAuthenticateCheck', (): void => { timeouts: { authenticationTimeoutMs: 30 }, }); expect(codes(result)).toEqual(['check.timeout']); - session.resolve({ accessToken: entraToken() }); + session.resolve({ + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); await flush(); expect(deps.createClient).not.toHaveBeenCalled(); }); diff --git a/src/connectionDiagnostics/checks/authenticate.ts b/src/connectionDiagnostics/checks/authenticate.ts index dba4f41cb..74e9d32b5 100644 --- a/src/connectionDiagnostics/checks/authenticate.ts +++ b/src/connectionDiagnostics/checks/authenticate.ts @@ -30,6 +30,7 @@ import { } from '../../documentdb/auth/createAuthHandler'; import { TokenResourceResolutionError } from '../../documentdb/auth/documentdbTokenResource'; import { classifyEntraError } from '../../documentdb/auth/entraErrors/classifyEntraError'; +import { EntraSignInRequiredError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getRecentEntraTokenFailure } from '../../documentdb/auth/entraErrors/entraTokenFailures'; import { getCloudForTokenResource } from '../../documentdb/auth/entraScopes'; import { @@ -130,6 +131,8 @@ const knownErrorNames: ReadonlySet = new Set([ 'UserCancelledError', 'TokenResourceResolutionError', 'AuthInputUnavailableError', + 'EntraIdentityMismatchError', + 'TokenCallbackError', 'CredentialUnavailableError', 'AuthenticationRequiredError', 'AggregateAuthenticationError', @@ -211,13 +214,21 @@ class AuthSteps { record.findings.push(...findings); } - /** Overrides an already recorded result, for a phase whose failure becomes known later. */ - public replace(id: AuthStepId, status: CheckStatus, findings: readonly Finding[]): void { + /** Replaces a phase's evidence without changing its original timing. */ + public replace( + id: AuthStepId, + status: CheckStatus, + facts: Facts, + findings: readonly Finding[], + skippedBecause?: StepRecord['skippedBecause'], + ): void { const record = this.get(id); record.startedAt ??= this.now(); record.finishedAt ??= this.now(); record.status = status; - record.findings.push(...findings); + record.skippedBecause = skippedBecause; + record.facts = facts; + record.findings = [...findings]; } public skip(id: AuthStepId, reason: SkipReason, stepId?: AuthStepId): void { @@ -320,6 +331,34 @@ export function createAuthenticateCheck( const timings = new ConnectionStartupTimings(); let requestedResource = ''; let tokenFailed = false; + let observingCallbackToken = false; + let callbackInputUnavailable = false; + + function summarizeAcquisition(info: { + readonly accessToken: string; + readonly tenantId?: string; + }): [status: 'pass' | 'warning', facts: Facts, findings: Finding[]] { + const claims = summarizeTokenClaims( + info.accessToken, + { requestedResource, configuredTenantId: info.tenantId }, + deps.now(), + ); + const findings = claimFindings(claims); + return [findings.length > 0 ? 'warning' : 'pass', { claims }, findings]; + } + + function summarizeTokenFailure( + error: unknown, + ): [status: 'fail', facts: Facts, findings: Finding[]] { + const classification = classifyEntraError(errorMessages(error)); + const ruleId = classification?.ruleId ?? 'unclassified'; + const aadstsCode = classification?.code; + return [ + 'fail', + { ...errorFacts(error), ruleId, ...(aadstsCode === undefined ? {} : { aadstsCode }) }, + [entraTokenFailedFinding(ruleId, aadstsCode, method)], + ]; + } const observer: AuthPhaseObserver = { onSignInConfigurationResolved(info): void { @@ -338,32 +377,33 @@ export function createAuthenticateCheck( }, onTokenAcquired(info): void { // The token is summarized here and never stored; only the allowlisted summary remains. - const claims = summarizeTokenClaims( - info.accessToken, - { requestedResource, configuredTenantId: info.tenantId }, - deps.now(), - ); if (info.account?.label) { facts.account = info.account.label; } - const findings = claimFindings(claims); - steps?.finish('auth.token', findings.length > 0 ? 'warning' : 'pass', { claims }, findings); + steps?.finish('auth.token', ...summarizeAcquisition(info)); }, onTokenFailed(error): void { - if (error instanceof AuthInputUnavailableError) { + if (error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError) { steps?.finish('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); return; } tokenFailed = true; - const classification = classifyEntraError(errorMessages(error)); - const ruleId = classification?.ruleId ?? 'unclassified'; - const aadstsCode = classification?.code; - steps?.finish( - 'auth.token', - 'fail', - { ...errorFacts(error), ruleId, ...(aadstsCode === undefined ? {} : { aadstsCode }) }, - [entraTokenFailedFinding(ruleId, aadstsCode, method)], - ); + steps?.finish('auth.token', ...summarizeTokenFailure(error)); + }, + onCallbackTokenObserved(observation): void { + if (!observingCallbackToken || signal.aborted) { + return; + } + callbackInputUnavailable = + observation.outcome === 'failed' && observation.error instanceof EntraSignInRequiredError; + tokenFailed = observation.outcome === 'failed' && !callbackInputUnavailable; + if (observation.outcome === 'acquired') { + steps?.replace('auth.token', ...summarizeAcquisition(observation)); + } else if (callbackInputUnavailable) { + steps?.replace('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); + } else { + steps?.replace('auth.token', ...summarizeTokenFailure(observation.error)); + } }, }; @@ -380,6 +420,9 @@ export function createAuthenticateCheck( status: CheckStatus; findings?: Finding[]; }): CheckOutcome => { + if (tokenFailed && method === AuthMethodId.MicrosoftEntraID) { + delete facts.account; + } const costs = timings.finish(); if (costs.tokenAcquireDurationMs !== undefined) { facts.tokenMs = Math.round(costs.tokenAcquireDurationMs); @@ -419,8 +462,9 @@ export function createAuthenticateCheck( const handler = createAuthHandler(method, credentials, { interactive: false, observer }); configured = await handler.configureAuth(timings, traceContext); } catch (error) { - if (error instanceof AuthInputUnavailableError) { - return finish(inputUnavailable(error.missing, method, steps, facts)); + if (error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError) { + const missing = error instanceof AuthInputUnavailableError ? error.missing : 'entraSession'; + return finish(inputUnavailable(missing, method, steps, facts)); } getRunOwnedClient().authError = error; if (isEntraDestinationRejectedError(error)) { @@ -491,12 +535,20 @@ export function createAuthenticateCheck( signal.addEventListener('abort', onAbort, { once: true }); const stopDatabaseConnect = timings.startDatabaseConnect(); try { + observingCallbackToken = true; await ownedClient.connect(); } finally { + observingCallbackToken = false; stopDatabaseConnect(); signal.removeEventListener('abort', onAbort); } } catch (error) { + if (method === AuthMethodId.MicrosoftEntraID && signal.aborted) { + return finish({ status: 'fail' }); + } + if (callbackInputUnavailable) { + return finish(inputUnavailable('entraSession', method, steps, facts)); + } if (!(error instanceof AuthInputUnavailableError)) getRunOwnedClient().authError = error; failure ??= { error, phase: 'connect' }; return finish(connectFailure(error, client, options, seedAddresses(context, driverConnectionString))); @@ -507,6 +559,9 @@ export function createAuthenticateCheck( await client.close().catch((): void => undefined); return finish({ status: 'fail' }); } + if (callbackInputUnavailable) { + return finish(inputUnavailable('entraSession', method, steps, facts)); + } getRunOwnedClient().client = client; steps?.finish('auth.serverAuthentication', 'pass'); facts.authenticated = method !== AuthMethodId.NoAuth; @@ -535,8 +590,11 @@ export function createAuthenticateCheck( "Microsoft Entra ID isn't allowed for this server.", ); if (steps) { - steps.replace('auth.signInConfiguration', 'fail', [finding]); - steps.get('auth.signInConfiguration').facts.allHostsAllowed = false; + const signIn = steps.get('auth.signInConfiguration'); + steps.replace('auth.signInConfiguration', 'fail', { ...signIn.facts, allHostsAllowed: false }, [ + ...signIn.findings, + finding, + ]); steps.skip('auth.serverAuthentication', 'dependencyFailed', 'auth.signInConfiguration'); return { status: 'fail' }; } @@ -636,6 +694,7 @@ export function createAuthenticateCheck( facts: Facts, ): { status: CheckStatus; findings: Finding[] } { if (missing === 'entraSession') { + delete facts.account; // The silent lookup cannot tell "not signed in" from a consent or preauthorization // failure; an earlier recorded failure is evidence only and never changes the outcome. facts.signInLimitation = 'silentLookupCannotDistinguishConsent'; @@ -647,7 +706,7 @@ export function createAuthenticateCheck( ...(earlier.ruleId === undefined ? {} : { ruleId: earlier.ruleId }), }; } - steps?.finish('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); + steps?.replace('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); steps?.skip('auth.serverAuthentication', 'dependencySkipped', 'auth.token'); } facts.authenticated = false; diff --git a/src/connectionDiagnostics/checks/resolveTarget.test.ts b/src/connectionDiagnostics/checks/resolveTarget.test.ts index f9a190440..264f393e2 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.test.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type CheckResult, type RunContext } from '@documentdb-js/connection-diagnostics'; +import { NotSignedInError } from '@microsoft/vscode-azext-azureauth'; import { describe, expect, it, vi } from 'vitest'; import { type AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { @@ -150,14 +151,54 @@ describe('resolveTarget check (review R2, option A)', (): void => { 'target.sourceInaccessible', { source: 'azure', reason: 'accessDenied', errorName: 'RestError', statusCode: 403 }, ], + [ + new ConnectionSourceUnavailableError('azure', new NotSignedInError()), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error' }, + ], + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret challenge'), { statusCode: 401 }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error', statusCode: 401 }, + ], + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret broker detail'), { code: 'interaction_required' }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error' }, + ], + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret authority detail'), { code: 'AADSTS50076', statusCode: 403 }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error', statusCode: 403 }, + ], [ new ConnectionSourceUnavailableError( 'azure', - withStatus(new Error('expired'), { name: 'NotSignedInError' }), + withStatus(new Error('secret contains AADSTS50076'), { statusCode: 403 }), ), 'target.sourceInaccessible', - { source: 'azure', reason: 'signInRequired', errorName: 'NotSignedInError' }, + { source: 'azure', reason: 'accessDenied', errorName: 'Error', statusCode: 403 }, ], + ...['AADSTS53003', 'AADSTS700016'].map( + (code) => + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret authority detail'), { code, statusCode: 403 }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'accessDenied', errorName: 'Error', statusCode: 403 }, + ] as const, + ), [ new ConnectionSourceUnavailableError( 'kubernetes', diff --git a/src/connectionDiagnostics/checks/resolveTarget.ts b/src/connectionDiagnostics/checks/resolveTarget.ts index ea01c7536..0a15f5a87 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type Check, type CheckOutcome, type Finding, type RunContext } from '@documentdb-js/connection-diagnostics'; +import { isNotSignedInError } from '@microsoft/vscode-azext-azureauth'; import { ConnectionEndpointUnavailableError, ConnectionInputCancelledError, @@ -25,6 +26,19 @@ const SIGN_IN_ERROR_NAMES: ReadonlySet = new Set([ 'NotSignedInError', ]); +function isAzureSignInSignal(error: unknown): boolean { + if (isNotSignedInError(error)) { + return true; + } + if (!(error instanceof Error)) { + return false; + } + const code = 'code' in error ? error.code : undefined; + return [error.name, code].some( + (value) => value === 'interaction_required' || value === 'AADSTS50076' || value === 'AADSTS50079', + ); +} + function finding(code: FindingCode, data: Readonly>, text: string): Finding { return { code, severity: 'error', data, detail: { language: 'en', text } }; } @@ -68,7 +82,11 @@ export function classifyResolutionFailure(error: unknown): Finding ); } let reason: SourceInaccessibleReason = 'other'; - if (status === 401 || (cause instanceof Error && SIGN_IN_ERROR_NAMES.has(cause.name))) { + if ( + status === 401 || + (cause instanceof Error && SIGN_IN_ERROR_NAMES.has(cause.name)) || + (source === 'azure' && isAzureSignInSignal(cause)) + ) { reason = 'signInRequired'; } else if (status === 403) { reason = 'accessDenied'; diff --git a/src/debug/debug.test.ts b/src/debug/debug.test.ts index b79335938..1583f23e3 100644 --- a/src/debug/debug.test.ts +++ b/src/debug/debug.test.ts @@ -5,8 +5,11 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { type IActionContext, registerCommand } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import * as packageJson from '../../package.json'; +import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; +import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; import { getSurveyService, recordSurveyActivityWithInvitation, @@ -14,9 +17,11 @@ import { } from '../services/survey/SurveyService'; import { DEBUG_SURVEY_ALWAYS_INVITE_ENV, readDebugOverrides } from './debugOverrides'; import { + CLEAR_SCHEMA_CACHE_COMMAND, DEVELOPMENT_MODE_CONTEXT, registerDebugCommands, RESET_SURVEY_STATE_COMMAND, + SHOW_SCHEMA_STORE_STATS_COMMAND, SHOW_SURVEY_INVITATION_COMMAND, SIMULATE_SURVEY_MILESTONE_COMMAND, } from './registerDebugCommands'; @@ -29,6 +34,9 @@ vi.mock('vscode', (): object => ({ }, window: { showInformationMessage: vi.fn(), showWarningMessage: vi.fn() }, })); +vi.mock('@microsoft/vscode-azext-utils', (): object => ({ registerCommand: vi.fn() })); +vi.mock('../commands/schemaStore/clearSchemaCache', (): object => ({ clearSchemaCache: vi.fn() })); +vi.mock('../commands/schemaStore/showSchemaStoreStats', (): object => ({ showSchemaStoreStats: vi.fn() })); vi.mock('../services/survey/SurveyService', (): object => ({ getSurveyService: vi.fn(), recordSurveyActivityWithInvitation: vi.fn(), @@ -52,6 +60,7 @@ it.each([vscode.ExtensionMode.Production, vscode.ExtensionMode.Test])( await registerDebugCommands(context); expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); expect(vscode.commands.registerCommand).not.toHaveBeenCalled(); + expect(registerCommand).not.toHaveBeenCalled(); expect(context.subscriptions).toHaveLength(0); }, ); @@ -113,14 +122,33 @@ it('registers development commands that use the real milestone entry point and s expect(resetState).toHaveBeenCalledTimes(1); }); -it('contributes uncategorized underscore titles and development-only palette entries', (): void => { +it('registers the schema commands with their existing handlers in development mode', async (): Promise => { + const context = { + extensionMode: vscode.ExtensionMode.Development, + subscriptions: [], + } as unknown as vscode.ExtensionContext; + await registerDebugCommands(context); + + const registrations = new Map( + vi.mocked(registerCommand).mock.calls.map(([command, handler]) => [command, handler]), + ); + const actionContext = {} as IActionContext; + await registrations.get(CLEAR_SCHEMA_CACHE_COMMAND)?.(actionContext); + await registrations.get(SHOW_SCHEMA_STORE_STATS_COMMAND)?.(actionContext); + expect(clearSchemaCache).toHaveBeenCalledWith(actionContext); + expect(showSchemaStoreStats).toHaveBeenCalledWith(actionContext); +}); + +it('labels development-only palette entries as Developer commands', (): void => { for (const command of [ SHOW_SURVEY_INVITATION_COMMAND, SIMULATE_SURVEY_MILESTONE_COMMAND, RESET_SURVEY_STATE_COMMAND, + CLEAR_SCHEMA_CACHE_COMMAND, + SHOW_SCHEMA_STORE_STATS_COMMAND, ]) { const contribution = packageJson.contributes.commands.find((entry): boolean => entry.command === command); - expect(contribution?.title).toMatch(/^_DocumentDB: Survey: /); + expect(contribution?.title).toMatch(/^_DocumentDB: Developer: /); expect(contribution).not.toHaveProperty('category'); expect(packageJson.contributes.menus.commandPalette).toContainEqual({ command, @@ -128,3 +156,14 @@ it('contributes uncategorized underscore titles and development-only palette ent }); } }); + +it.each(['showConnectionStats', 'showWorkerStats'])( + 'keeps %s discoverable as a Developer command outside development mode', + (commandName): void => { + const command = `vscode-documentdb.command.${commandName}`; + const contribution = packageJson.contributes.commands.find((entry): boolean => entry.command === command); + expect(contribution).toMatchObject({ category: 'DocumentDB Developer' }); + expect(contribution).not.toHaveProperty('enablement'); + expect(packageJson.contributes.menus.commandPalette).not.toContainEqual(expect.objectContaining({ command })); + }, +); diff --git a/src/debug/registerDebugCommands.ts b/src/debug/registerDebugCommands.ts index 4d73cd762..349269c55 100644 --- a/src/debug/registerDebugCommands.ts +++ b/src/debug/registerDebugCommands.ts @@ -3,19 +3,25 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { registerCommand } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; +import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; import { getSurveyService, recordSurveyActivityWithInvitation, type SurveyService, } from '../services/survey/SurveyService'; import { SURVEY_FEATURE_AREAS } from '../services/survey/surveyTypes'; +import { withCommandCorrelation } from '../utils/commandTelemetry'; // Hyphenated: the VSIX inspection reads bare `name.ext` manifest strings as file paths. export const DEVELOPMENT_MODE_CONTEXT = 'documentdb-development-mode'; export const SHOW_SURVEY_INVITATION_COMMAND = 'vscode-documentdb.debug.survey.showInvitation'; export const SIMULATE_SURVEY_MILESTONE_COMMAND = 'vscode-documentdb.debug.survey.simulateMilestone'; export const RESET_SURVEY_STATE_COMMAND = 'vscode-documentdb.debug.survey.resetState'; +export const CLEAR_SCHEMA_CACHE_COMMAND = 'vscode-documentdb.command.clearSchemaCache'; +export const SHOW_SCHEMA_STORE_STATS_COMMAND = 'vscode-documentdb.command.showSchemaStoreStats'; function reportSurveyDebugStatus(service: SurveyService): void { const s = service.getDebugStatus(); @@ -33,6 +39,8 @@ export async function registerDebugCommands(context: vscode.ExtensionContext): P return; } await vscode.commands.executeCommand('setContext', DEVELOPMENT_MODE_CONTEXT, true); + registerCommand(CLEAR_SCHEMA_CACHE_COMMAND, withCommandCorrelation(clearSchemaCache)); + registerCommand(SHOW_SCHEMA_STORE_STATS_COMMAND, withCommandCorrelation(showSchemaStoreStats)); context.subscriptions.push( vscode.commands.registerCommand(SHOW_SURVEY_INVITATION_COMMAND, async (): Promise => { const service = getSurveyService(); diff --git a/src/deepLinks/azureSubscription.test.ts b/src/deepLinks/azureSubscription.test.ts index 7cd8237f8..2a9efcef4 100644 --- a/src/deepLinks/azureSubscription.test.ts +++ b/src/deepLinks/azureSubscription.test.ts @@ -3,7 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; +import { getSessionFromVSCode, type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import * as vscode from 'vscode'; @@ -29,6 +30,10 @@ vi.mock('../extensionVariables', () => ({ vi.mock('@microsoft/vscode-azext-utils', () => ({ callWithTelemetryAndErrorHandling: vi.fn(), })); +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getSessionFromVSCode: vi.fn(), +})); vi.mock('../services/discoveryServices', () => ({ DiscoveryService: { getProvider: vi.fn() }, })); @@ -37,9 +42,17 @@ vi.mock('../plugins/api-shared/azure/subscriptionFiltering/subscriptionFiltering })); const azureSubscriptionProvider = { - isSignedIn: vi.fn(), signIn: vi.fn(), - getSubscriptions: vi.fn(), + getAvailableSubscriptions: vi.fn(), +}; +const listingOptions = { filter: false, maximumTenants: Number.POSITIVE_INFINITY }; +const freshListingOptions = { ...listingOptions, noCache: true }; + +const session: vscode.AuthenticationSession = { + id: 'session-id', + accessToken: 'token', + account: { id: 'account-id', label: 'account-id' }, + scopes: [], }; const provider = { @@ -76,9 +89,9 @@ beforeEach((): void => { }, ); provider.configureCredentials.mockResolvedValue(undefined); - azureSubscriptionProvider.isSignedIn.mockResolvedValue(true); azureSubscriptionProvider.signIn.mockResolvedValue(true); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([]); + vi.mocked(getSessionFromVSCode).mockResolvedValue(session); vi.mocked(isTenantFilteredOut).mockReturnValue(false); }); @@ -86,14 +99,16 @@ describe('resolveAzureSubscription', (): void => { it('reports sign-in and subscription lookup before running each step', async (): Promise => { const report = vi.fn<(message: string) => void>(); const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.isSignedIn.mockImplementation(async (): Promise => { + azureSubscriptionProvider.signIn.mockImplementation(async (): Promise => { expect(report).toHaveBeenLastCalledWith('Checking Azure sign-in…'); return true; }); - azureSubscriptionProvider.getSubscriptions.mockImplementation(async (): Promise => { - expect(report).toHaveBeenLastCalledWith('Looking for the subscription…'); - return [found]; - }); + azureSubscriptionProvider.getAvailableSubscriptions.mockImplementation( + async (): Promise => { + expect(report).toHaveBeenLastCalledWith('Looking for the subscription…'); + return [found]; + }, + ); await expect(resolveAzureSubscription(context, request, report)).resolves.toBe(found); @@ -102,21 +117,25 @@ describe('resolveAzureSubscription', (): void => { it('prompts a signed-out user, signs in, and resolves an unfiltered subscription', async (): Promise => { const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([found]); + azureSubscriptionProvider.signIn.mockResolvedValueOnce(false); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([found]); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in'); await expect(resolveAzureSubscription(context, request)).resolves.toBe(found); expect(DiscoveryService.getProvider).toHaveBeenCalledWith(request.providerId); - expect(azureSubscriptionProvider.isSignedIn).toHaveBeenCalledWith(); + expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(1, undefined, { promptIfNeeded: false }); expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( 'Sign in to Azure', { modal: true, detail: 'Sign in to Azure to open linked-resource.' }, 'Sign in', ); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledWith(); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(2, undefined, { + clearSessionPreference: true, + }); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledTimes(2); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(1); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in: sign-in required'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in confirmation: accepted'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] 1 matching subscription(s) found'); @@ -132,7 +151,7 @@ describe('resolveAzureSubscription', (): void => { }); it('returns undefined without listing subscriptions when the Azure sign-in prompt is dismissed', async (): Promise => { - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); + azureSubscriptionProvider.signIn.mockResolvedValueOnce(false); (vscode.window.showInformationMessage as Mock).mockResolvedValue(undefined); await expect(resolveAzureSubscription(context, request)).resolves.toBeUndefined(); @@ -145,12 +164,11 @@ describe('resolveAzureSubscription', (): void => { result: 'Canceled', }); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in confirmation: dismissed'); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); }); it('treats a false Azure sign-in result as cancellation', async (): Promise => { - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); azureSubscriptionProvider.signIn.mockResolvedValue(false); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in'); @@ -158,13 +176,24 @@ describe('resolveAzureSubscription', (): void => { expect(context.telemetry.properties.userCancelledAtStep).toBe('AzureSignIn'); expect(context.telemetry.properties.failureStage).toBe('azureSignIn'); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); + }); + + it('propagates unrelated silent sign-in failures without prompting or listing subscriptions', async () => { + const failure = new Error('Azure authentication provider failed'); + azureSubscriptionProvider.signIn.mockRejectedValueOnce(failure); + + await expect(resolveAzureSubscription(context, request)).rejects.toBe(failure); + + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); }); it('uses the case-insensitive tenant hint to select between accounts sharing a subscription ID', async (): Promise => { const otherTenant = subscription('other-tenant', 'account-one'); const hintedTenant = subscription('tenant-id', 'account-two'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([otherTenant, hintedTenant]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([otherTenant, hintedTenant]); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'TENANT-ID' })).resolves.toBe( hintedTenant, @@ -176,13 +205,13 @@ describe('resolveAzureSubscription', (): void => { tenantSignInRequired: 'false', }); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); }); it('prefers the first non-filtered account when there is no tenant hint', async (): Promise => { const filtered = subscription('tenant-one', 'account-one'); const visible = subscription('tenant-two', 'account-two'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([filtered, visible]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([filtered, visible]); vi.mocked(isTenantFilteredOut).mockImplementation( (tenantId, accountId): boolean => tenantId === filtered.tenantId && accountId === filtered.account.id, ); @@ -196,7 +225,7 @@ describe('resolveAzureSubscription', (): void => { it('falls back to the first candidate when all matching tenants are filtered out', async (): Promise => { const first = subscription('tenant-one', 'account-one'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ first, subscription('tenant-two', 'account-two'), ]); @@ -208,17 +237,41 @@ describe('resolveAzureSubscription', (): void => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }); - it('signs into the hinted tenant and retries unfiltered subscription resolution exactly once', async (): Promise => { + it.each([ + { hint: 'without a tenant hint', tenantId: undefined }, + { hint: 'with a tenant hint', tenantId: 'TENANT-ID' }, + ])('resolves a fresh hit without prompting $hint', async ({ tenantId }): Promise => { + const found = subscription('tenant-id', 'account-id'); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValueOnce([]).mockResolvedValueOnce([found]); + const lookupRequest = tenantId === undefined ? request : { ...request, tenantId }; + + await expect(resolveAzureSubscription(context, lookupRequest)).resolves.toBe(found); + + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(context.telemetry.properties.tenantSignInRequired).toBe('false'); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); + expect(context.telemetry.measurements.subscriptionAccountCount).toBe(1); + }); + + it('offers hinted tenant sign-in after a fresh miss and refreshes exactly once after sign-in', async (): Promise => { const report = vi.fn<(message: string) => void>(); const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValueOnce([]).mockResolvedValueOnce([found]); + azureSubscriptionProvider.getAvailableSubscriptions + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([found]); (vscode.window.showInformationMessage as Mock).mockImplementation(async (): Promise => { expect(report).not.toHaveBeenCalledWith('Signing in to tenant…'); return 'Sign in to tenant'; }); - azureSubscriptionProvider.signIn.mockImplementation(async (): Promise => { + vi.mocked(getSessionFromVSCode).mockImplementation(async (): Promise => { expect(report).toHaveBeenLastCalledWith('Signing in to tenant…'); - return true; + return session; }); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'TENANT-ID' }, report)).resolves.toBe( @@ -228,6 +281,7 @@ describe('resolveAzureSubscription', (): void => { expect(report.mock.calls).toEqual([ ['Checking Azure sign-in…'], ['Looking for the subscription…'], + ['Looking for the subscription…'], ['Signing in to tenant…'], ['Looking for the subscription…'], ]); @@ -240,10 +294,26 @@ describe('resolveAzureSubscription', (): void => { }, 'Sign in to tenant', ); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('TENANT-ID'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(2); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenNthCalledWith(1, false); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenNthCalledWith(2, false); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'TENANT-ID', { + createIfNone: true, + clearSessionPreference: true, + }); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + [freshListingOptions], + ]); + const [cachedList, freshList, tenantList] = + azureSubscriptionProvider.getAvailableSubscriptions.mock.invocationCallOrder; + const order = [ + cachedList, + freshList, + vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0], + vi.mocked(getSessionFromVSCode).mock.invocationCallOrder[0], + tenantList, + ]; + expect(order).toEqual([...order].sort((a, b): number => a - b)); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(3); expect(context.telemetry.properties).toEqual({ failureStage: 'resolveSubscription', azureSignInRequired: 'false', @@ -251,14 +321,21 @@ describe('resolveAzureSubscription', (): void => { }); }); - it('treats a false tenant sign-in result as cancellation without retrying subscription lookup', async (): Promise => { - azureSubscriptionProvider.signIn.mockResolvedValue(false); + it('treats a false tenant sign-in result as cancellation without listing again after sign-in', async (): Promise => { + vi.mocked(getSessionFromVSCode).mockResolvedValue(undefined); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in to tenant'); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'tenant-id' })).resolves.toBeUndefined(); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('tenant-id'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'tenant-id', { + createIfNone: true, + clearSessionPreference: true, + }); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); expect(context.telemetry.properties).toMatchObject({ tenantSignInRequired: 'true', deepLinkOutcome: 'canceled', @@ -271,7 +348,7 @@ describe('resolveAzureSubscription', (): void => { }); it('throws with a working Manage Azure accounts button when the tenant retry still cannot find the subscription', async (): Promise => { - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ subscription('other-tenant', 'account-id'), subscription('tenant-id', 'account-id', 'different-subscription'), ]); @@ -281,8 +358,12 @@ describe('resolveAzureSubscription', (): void => { 'We could not find subscription Subscription-ID among your signed-in Azure accounts. Check that you are signed in with the right account and to the right Azure cloud.', ); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(2); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('tenant-id'); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(3); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(3); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'tenant-id', { + createIfNone: true, + clearSessionPreference: true, + }); expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1); expect(context.telemetry.properties).toEqual({ failureStage: 'resolveSubscription', @@ -314,13 +395,18 @@ describe('resolveAzureSubscription', (): void => { expect(context.telemetry.properties.userCancelledAtStep).toBe('AzureTenantSignIn'); expect(context.telemetry.properties.tenantSignInRequired).toBe('true'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(1); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); expect(context.errorHandling.buttons).toBeUndefined(); }); it('throws without a tenant prompt when no subscription matches and there is no tenant hint', async (): Promise => { - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ subscription('tenant-id', 'account-id', 'different-subscription'), ]); @@ -329,9 +415,14 @@ describe('resolveAzureSubscription', (): void => { ); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); expect(context.telemetry.properties.tenantSignInRequired).toBe('false'); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); expect(context.telemetry.measurements.subscriptionAccountCount).toBe(0); expect(context.errorHandling.buttons?.[0].title).toBe('Manage Azure accounts'); }); @@ -346,8 +437,8 @@ describe('resolveAzureSubscription', (): void => { ); expect(context.telemetry.properties.failureStage).toBe('azureSignIn'); - expect(azureSubscriptionProvider.isSignedIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }, ); diff --git a/src/deepLinks/azureSubscription.ts b/src/deepLinks/azureSubscription.ts index da699af39..063617df9 100644 --- a/src/deepLinks/azureSubscription.ts +++ b/src/deepLinks/azureSubscription.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; +import { getSessionFromVSCode, type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../extensionVariables'; @@ -53,7 +53,7 @@ export async function resolveAzureSubscription( ext.outputChannel.trace('[DeepLink] Checking Azure sign-in'); report?.(vscode.l10n.t('Checking Azure sign-in…')); const isSignedIn = await measureDeepLinkPhase(context, 'azureSignInCheck', () => - azureSubscriptionProvider.isSignedIn(), + azureSubscriptionProvider.signIn(undefined, { promptIfNeeded: false }), ); ext.outputChannel.trace(`[DeepLink] Azure sign-in: ${isSignedIn ? 'signed in' : 'sign-in required'}`); context.telemetry.properties.azureSignInRequired = isSignedIn ? 'false' : 'true'; @@ -72,7 +72,9 @@ export async function resolveAzureSubscription( ); if ( choice !== signInButton || - !(await measureDeepLinkPhase(context, 'azureSignIn', () => azureSubscriptionProvider.signIn())) + !(await measureDeepLinkPhase(context, 'azureSignIn', () => + azureSubscriptionProvider.signIn(undefined, { clearSessionPreference: true }), + )) ) { ext.outputChannel.trace('[DeepLink] Azure sign-in stopped'); cancelDeepLink(context, 'AzureSignIn'); @@ -83,11 +85,17 @@ export async function resolveAzureSubscription( context.telemetry.properties.failureStage = 'resolveSubscription'; context.telemetry.properties.tenantSignInRequired = 'false'; - for (let attempt = 0; attempt < 2; attempt++) { + let lookupAttempts = 0; + async function lookupSubscription(noCache = false): Promise { ext.outputChannel.trace('[DeepLink] Listing subscriptions'); report?.(vscode.l10n.t('Looking for the subscription…')); + context.telemetry.measurements.subscriptionLookupAttempts = ++lookupAttempts; const subscriptions = await measureDeepLinkPhase(context, 'subscriptionLookup', () => - azureSubscriptionProvider.getSubscriptions(false), + azureSubscriptionProvider.getAvailableSubscriptions({ + filter: false, + maximumTenants: Number.POSITIVE_INFINITY, + ...(noCache ? { noCache: true } : {}), + }), ); const candidates = subscriptions.filter( (subscription) => @@ -97,18 +105,17 @@ export async function resolveAzureSubscription( ); ext.outputChannel.trace(`[DeepLink] ${candidates.length} matching subscription(s) found`); context.telemetry.measurements.subscriptionAccountCount = candidates.length; - context.telemetry.measurements.subscriptionLookupAttempts = attempt + 1; - const subscription = + return ( candidates.find((candidate) => !isTenantFilteredOut(candidate.tenantId, candidate.account.id)) ?? - candidates[0]; - if (subscription) { - return subscription; - } - - if (attempt > 0 || request.tenantId === undefined) { - break; - } + candidates[0] + ); + } + const subscription = (await lookupSubscription()) ?? (await lookupSubscription(true)); + if (subscription) { + return subscription; + } + if (request.tenantId !== undefined) { context.telemetry.properties.tenantSignInRequired = 'true'; const tenantId = request.tenantId; ext.outputChannel.trace('[DeepLink] Tenant sign-in offered'); @@ -134,13 +141,17 @@ export async function resolveAzureSubscription( } report?.(vscode.l10n.t('Signing in to tenant…')); const signedIn = await measureDeepLinkPhase(context, 'azureSignIn', () => - azureSubscriptionProvider.signIn(tenantId), + getSessionFromVSCode(undefined, tenantId, { createIfNone: true, clearSessionPreference: true }), ); if (!signedIn) { ext.outputChannel.trace('[DeepLink] Tenant sign-in stopped'); cancelDeepLink(context, 'AzureTenantSignIn'); return undefined; } + const tenantSubscription = await lookupSubscription(true); + if (tenantSubscription) { + return tenantSubscription; + } } ext.outputChannel.trace('[DeepLink] Subscription not found'); diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 3514dd414..4498cac68 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'; @@ -14,7 +15,11 @@ import { toTablePage } from '../utils/documentGrid/toTablePage'; import { toTreeNodes } from '../utils/documentGrid/toTreeNodes'; import { type TablePage, type TreeNode } from '../utils/documentGrid/types'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; -import { ClustersClient, type FindQueryParams } from './ClustersClient'; +import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; +import { getRetiredBindingReason, isRetiredConnectionBinding } from './connectionBindingRetirement'; +import { classifyConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -50,15 +55,67 @@ 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 getClient(): ClustersClient { - return this._client; + public getEpoch(): number { + return ClustersClient.getEpoch(this.binding.clusterId); + } + + private isCurrent(epoch: number): boolean { + const { clusterId, fingerprint } = this.binding; + return ( + epoch === ClustersClient.getEpoch(clusterId) && + !isRetiredConnectionBinding(this.binding) && + 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 = getRetiredBindingReason(this.binding) ?? 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; } /** @@ -95,7 +152,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) @@ -230,6 +286,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; @@ -243,10 +300,13 @@ 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 = []; - this._currentPageIdentityTrusted = false; - return 0; + return this.runWithClient((_client, epoch) => { + this.assertCurrent(epoch, signal); + // We're trying to page beyond the query's limit - return empty results + this._currentRawDocuments = []; + this._currentPageIdentityTrusted = false; + return Promise.resolve(0); + }); } // Calculate effective limit: @@ -258,18 +318,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, @@ -292,14 +340,45 @@ export class ClusterSession { } } - // 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(); + let ran: ConnectionBinding | undefined; + let ranAuthMethod: ClustersClient['authMethod'] | undefined; + let queryResult: { documents: WithId[]; executionTimeMs: number }; + try { + queryResult = await this.runWithClient(async (client) => { + this.assertCurrent(epoch, signal); + const startTime = performance.now(); + ran = client.binding; + ranAuthMethod = client.authMethod; + const documents = await client.runFindQuery(databaseName, collectionName, paginatedQueryParams); + return { documents, executionTimeMs: performance.now() - startTime }; + }, epoch); + } catch (error) { + if ( + error instanceof Error && + ran !== undefined && + classifyConnectionFailure(error, ranAuthMethod).generation === 'replaceOnNextForeground' && + !signal?.aborted && + ClustersClient.getEpoch(ran.clusterId) === epoch && + ClustersClient.getBinding(ran.clusterId) === ran && + !ClustersClient.hasReusableClient(ran.clusterId) && + ClustersClient.getLatchReason(ran.clusterId) === undefined + ) { + throw new Error(`${error.message} ${l10n.t('Run the query again to retry the connection.')}`, { + cause: error, + }); + } + throw error; + } + const { documents, executionTimeMs } = queryResult; + + 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; @@ -312,10 +391,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`, ); } @@ -330,10 +410,19 @@ export class ClusterSession { return toTreeNodes(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); @@ -353,7 +442,7 @@ export class ClusterSession { const store = SchemaStore.getInstance(); const headers = this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this._clusterId, this._databaseName, this._collectionName, path) + ? store.getPropertyNamesAtLevel(this.binding.clusterId, this._databaseName, this._collectionName, path) : []; return toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted); } @@ -366,7 +455,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, + ); } // ============================================================================ @@ -387,6 +480,8 @@ export class ClusterSession { * @returns Explain output from queryPlanner verbosity */ public async getQueryPlannerInfo( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -396,14 +491,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, @@ -412,10 +509,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(), @@ -441,6 +539,8 @@ export class ClusterSession { * @returns Explain output with executionStats */ public async getExecutionStats( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -450,7 +550,9 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._executionStatsCache) { return this._executionStatsCache.result; @@ -458,7 +560,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' @@ -466,7 +568,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, @@ -478,6 +581,7 @@ export class ClusterSession { const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._executionStatsCache = { result: explainResult, timestamp: Date.now(), @@ -600,7 +704,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 }; } @@ -629,7 +739,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, @@ -643,7 +753,7 @@ export class ClusterSession { } // TODO: Phase 3 implementation - // const recommendations = await this._client.queryInsightsAIService.generateRecommendations( + // const recommendations = await client.queryInsightsAIService.generateRecommendations( // databaseName, // collectionName, // filter, @@ -681,12 +791,21 @@ export class ClusterSession { * * @throws Will throw an error if the client cannot be obtained using the provided cluster ID. */ - public static async initNewSession(clusterId: string): Promise { - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'collectionView'); + public static async initNewSession( + clusterId: string, + options?: { readonly origin?: ConnectionBinding; readonly signal?: AbortSignal }, + ): Promise { + const client = options?.origin + ? await ClustersClient.resolveBoundClient(options.origin, { trigger: 'collectionView' }) + : await ClustersClient.getClient(clusterId, undefined, undefined, 'collectionView'); + + if (options?.signal?.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } 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 a0c9a8a7a..e621fc50b 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -7,18 +7,43 @@ import { EJSON, ObjectId } from 'bson'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import { UserCancelledError, type IActionContext, type ITelemetryContext } from '@microsoft/vscode-azext-utils'; +import { EventEmitter } from 'events'; import type * as Mongodb from 'mongodb'; -import { MongoClient, MongoServerError, type MongoClientOptions } from 'mongodb'; +import { + MongoClient, + MongoNetworkError, + MongoNotConnectedError, + MongoServerError, + type MongoClientOptions, +} from 'mongodb'; import { ext } from '../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; +import { type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import * as authHandlerFactory from './auth/createAuthHandler'; +import * as tokenResource from './auth/documentdbTokenResource'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; +import * as entraSession from './auth/entraSession'; import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; import { NoAuthHandler } from './auth/NoAuthHandler'; -import { ClustersClient, getIndexExclusionReason, type IndexItemModel } from './ClustersClient'; +import { + addEstablishedConnectionContext, + ClustersClient, + 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'; @@ -32,6 +57,16 @@ interface RecordedTelemetry { const mockTelemetryEvents: RecordedTelemetry[] = []; +function deferred(): { promise: Promise; resolve: () => void; reject: (error: Error) => void } { + let resolve!: () => void; + let reject!: (error: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + vi.mock('@microsoft/vscode-azext-utils', async () => { const actual = await vi.importActual<{ UserCancelledError: typeof UserCancelledError }>( '@microsoft/vscode-azext-utils', @@ -100,7 +135,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'); @@ -207,11 +246,36 @@ describe('ClustersClient upsertDocument', () => { }); describe('regular connection startup diagnostics', () => { - const clusterId = 'private-cluster'; + let clusterId: string; + let clusterNumber = 0; + const verifiedIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'private-test-account-id', + accountLabel: 'private-test-account-label', + tenantId: 'private-test-tenant', + }; 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; + const configureEntraAuth = MicrosoftEntraIDAuthHandler.prototype.configureAuth; + + function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { + const started = deferred(); + const finish = deferred(); + mockConnect.mockImplementationOnce(() => { + started.resolve(); + return finish.promise; + }); + return { started: started.promise, resolve: finish.resolve, reject: finish.reject }; + } beforeEach(() => { + clusterId = `private-cluster-${++clusterNumber}`; vi.clearAllMocks(); vi.useFakeTimers(); mockTelemetryEvents.length = 0; @@ -230,8 +294,20 @@ describe('regular connection startup diagnostics', () => { vi.advanceTimersByTime(30); }); mockClose.mockResolvedValue(undefined); + mockListDatabases.mockReset(); + mockFind.mockReset().mockReturnValue({ toArray: mockToArray }); + mockToArray.mockReset(); + mockDeleteMany.mockReset(); vi.mocked(MongoClient).mockImplementation(function () { - return { connect: mockConnect, close: mockClose } as unknown as MongoClient; + poolEvents = new EventEmitter(); + return Object.assign(poolEvents, { + connect: mockConnect, + close: mockClose, + db: () => ({ + admin: () => ({ listDatabases: mockListDatabases }), + collection: () => ({ find: mockFind, deleteMany: mockDeleteMany }), + }), + }) as unknown as MongoClient; }); for (const handler of [ MicrosoftEntraIDAuthHandler, @@ -241,12 +317,1312 @@ describe('regular connection startup diagnostics', () => { ]) { vi.spyOn(handler.prototype, 'configureAuth').mockImplementation(async () => { vi.advanceTimersByTime(20); - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { + connectionString: 'mongodb://private-host:27017', + options: {}, + ...(handler === MicrosoftEntraIDAuthHandler ? { verifiedIdentity } : {}), + }; + }); + } + }); + + it('publishes a new binding only on successful establishment and advances generations across deletion', async () => { + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + const first = await ClustersClient.connectInteractive(clusterId); + expect(first.binding).toEqual({ clusterId, fingerprint: first.fingerprint, generation: first.generation }); + expect(first.createdAt).toBe(Date.now()); + expect(await ClustersClient.getClient(clusterId)).toBe(first); + expect(ClustersClient.getBinding(clusterId)).toBe(first.binding); + + await ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + mockConnect.mockRejectedValueOnce(new Error('driver failure')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('driver failure'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + + const second = await ClustersClient.getClient(clusterId); + expect(ClustersClient.getBinding(clusterId)).toBe(second.binding); + expect(second.generation).toBe(first.generation + 1); + expect(second.fingerprint).toBe(first.fingerprint); + expect(second.createdAt).toBeGreaterThan(first.createdAt); + }); + + it('reports read-only client diagnostics without connection or identity details', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + vi.advanceTimersByTime(2_000); + + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const entry = snapshot.find(({ client: row }) => row?.startupId === client.connectionCorrelationId); + + expect(entry?.client).toEqual({ + generation: client.generation, + ageMs: 2_000, + authMethod: AuthMethodId.MicrosoftEntraID, + startupId: client.connectionCorrelationId, + state: 'cached', + socketTrace: true, + lastEntraTokenExpiresAt: undefined, + }); + const output = JSON.stringify(snapshot); + for (const value of [ + clusterId, + client.fingerprint, + verifiedIdentity.accountId, + verifiedIdentity.accountLabel, + verifiedIdentity.tenantId, + 'private-host', + ]) { + expect(output).not.toContain(value); + } + expect(await ClustersClient.getClient(clusterId)).toBe(client); + expect(mockConnect).toHaveBeenCalledOnce(); + 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('compares current credentials with the canonical password-free and auth-qualified fingerprint', (): void => { + const uri = 'mongodb://host.example.com:27017/'; + function setNative(user: string, password: string): void { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, uri, { + connectionUser: user, + connectionPassword: password, + }); + } + setNative('first', 'first-password'); + const first = ClustersClient.getExpectedFingerprint(clusterId); + expect(first).toBe( + computeConnectionFingerprint({ connectionString: uri, principal: { kind: 'native', username: 'first' } }), + ); + setNative('first', 'rotated-password'); + expect(ClustersClient.getExpectedFingerprint(clusterId)).toBe(first); + setNative('second', 'rotated-password'); + expect(ClustersClient.getExpectedFingerprint(clusterId)).not.toBe(first); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, uri); + expect(ClustersClient.getExpectedFingerprint(clusterId)).not.toBe(first); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, uri, undefined, undefined, { + tenantId: verifiedIdentity.tenantId, + }); + expect(ClustersClient.getExpectedFingerprint(clusterId)).toBeUndefined(); + expect(ClustersClient.getExpectedFingerprint(clusterId, verifiedIdentity)).toBe( + computeConnectionFingerprint({ connectionString: uri, principal: verifiedIdentity }), + ); + expect( + ClustersClient.getExpectedFingerprint(clusterId, { ...verifiedIdentity, tenantId: 'other' }), + ).toBeUndefined(); + }); + + 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 a disconnected view retired after same-account reconnect while fresh work runs once', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + ClustersClient.latch(clusterId, 'userDisconnected'); + ClustersClient.retireBoundViews(clusterId); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + ClustersClient.unlatch(clusterId); + + await expect(ClustersClient.resolveBoundClient(old.binding)).rejects.toMatchObject({ + reason: 'sessionEnded', + }); + expect(mockConnect).toHaveBeenCalledOnce(); + const current = await ClustersClient.getClient(clusterId); + expect(current.binding.fingerprint).toBe(old.binding.fingerprint); + expect(current.generation).toBeGreaterThan(old.generation); + expect(() => session.assertAvailable()).toThrow(expect.objectContaining({ reason: 'sessionEnded' })); + await expect(ClustersClient.resolveBoundClient(current.binding)).resolves.toBe(current); + const operation = vi.fn(async (client: ClustersClient): Promise => client); + await expect(runWithClient(old.binding, operation)).resolves.toEqual({ + unavailable: { reason: 'sessionEnded' }, + }); + expect(operation).not.toHaveBeenCalled(); + await expect(runWithClient(current.binding, operation)).resolves.toBe(current); + expect(operation).toHaveBeenCalledExactlyOnceWith(current); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it.each([false, true])( + 'does not create a bound session after Disconnect during startup (changed identity: %s)', + async (changedIdentity): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + const handshake = pauseNextConnect(); + const opening = ClusterSession.initNewSession(clusterId, { origin: original.binding }); + await handshake.started; + + ClustersClient.latch(clusterId, 'userDisconnected'); + ClustersClient.retireBoundViews(clusterId); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + if (changedIdentity) { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://different.test/', + ); + } + ClustersClient.unlatch(clusterId); + const replacement = await ClustersClient.getClient(clusterId); + expect(replacement.fingerprint === original.fingerprint).toBe(!changedIdentity); + + handshake.resolve(); + await expect(opening).rejects.toMatchObject({ + reason: changedIdentity ? 'identityChanged' : 'sessionEnded', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }, + ); + + it('does not create a bound session while the origin is latched', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + await expect(ClusterSession.initNewSession(clusterId, { origin: original.binding })).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + + it('does not create a bound session against a replacement identity', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + const replacement = await ClustersClient.getClient(clusterId); + + await expect(ClusterSession.initNewSession(clusterId, { origin: original.binding })).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }); + + it('creates a bound session after ordinary same-identity client replacement', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + + const sessionId = await ClusterSession.initNewSession(clusterId, { origin: original.binding }); + const session = ClusterSession.getSession(sessionId); + expect(session.getBinding()).toEqual({ ...original.binding, generation: original.generation + 1 }); + expect(() => session.assertAvailable()).not.toThrow(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('does not store a bound session when cancelled during client startup', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + const handshake = pauseNextConnect(); + const controller = new AbortController(); + const opening = ClusterSession.initNewSession(clusterId, { + origin: original.binding, + signal: controller.signal, + }); + await handshake.started; + controller.abort(); + handshake.resolve(); + + await expect(opening).rejects.toBeInstanceOf(UserCancelledError); + expect(ClusterSession._sessions.size).toBe(0); + }); + + 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('adds retry guidance when the query marks its current client for replacement', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const failure = new MongoNotConnectedError('private-query-connection-closed'); + mockToArray.mockImplementationOnce(async () => { + poolEvents.emit('topologyClosed'); + throw failure; + }); + + let caught: unknown; + try { + await session.runFindQueryWithCache('db', 'items', { filter: '{}' }, 1, 10); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + if (!(caught instanceof Error)) { + throw new Error('Expected the query to fail.'); + } + expect(caught).not.toBe(failure); + expect(caught.message).toBe('private-query-connection-closed Run the query again to retry the connection.'); + expect(caught.cause).toBe(failure); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.hasReusableClient(clusterId)).toBe(false); + + mockToArray.mockResolvedValueOnce([{ _id: 'retried' }]); + await expect(session.runFindQueryWithCache('db', 'items', { filter: '{}' }, 1, 10)).resolves.toBe(1); + expect(ClustersClient.getBinding(clusterId)).toMatchObject({ + generation: client.generation + 1, + }); + }); + + it('does not add retry guidance when classifier-equivalent replacement startup fails before the query', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('previous connection closed')); + const failure = new MongoNotConnectedError('private-replacement-connection-closed'); + mockConnect.mockRejectedValueOnce(failure); + + await expect(session.runFindQueryWithCache('db', 'items', { filter: '{}' }, 1, 10)).rejects.toBe(failure); + expect(failure.message).toBe('private-replacement-connection-closed'); + expect(mockToArray).not.toHaveBeenCalled(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + 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; + const tokenAt = (exp: number): string => + `test.${Buffer.from(JSON.stringify({ exp })).toString('base64url')}.signature`; + const first = { accessToken: tokenAt(firstExpiry) }; + const renewed = { accessToken: tokenAt(renewedExpiry) }; + const missingSession = new EntraSignInRequiredError('noSession'); + const callback = vi + .fn() + .mockResolvedValueOnce(first) + .mockResolvedValueOnce({ accessToken: 'opaque-test-token' }) + .mockResolvedValueOnce(renewed) + .mockRejectedValueOnce(missingSession); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const client = await ClustersClient.connectInteractive(clusterId); + const driverCallback = vi.mocked(MongoClient).mock.calls[0][1]?.authMechanismProperties?.OIDC_CALLBACK; + const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; + const expiry = (): string | undefined => + ClustersClient.getDiagnosticsSnapshot().find( + ({ client: row }) => row?.startupId === client.connectionCorrelationId, + )?.client?.lastEntraTokenExpiresAt; + + expect(expiry()).toBeUndefined(); + await expect(driverCallback!(params)).resolves.toBe(first); + expect(expiry()).toBe(new Date(firstExpiry * 1000).toISOString()); + expect(JSON.stringify(ClustersClient.getDiagnosticsSnapshot())).not.toContain(first.accessToken); + await driverCallback!(params); + expect(expiry()).toBeUndefined(); + await expect(driverCallback!(params)).resolves.toBe(renewed); + expect(expiry()).toBe(new Date(renewedExpiry * 1000).toISOString()); + await expect(driverCallback!(params)).rejects.toBe(missingSession); + expect(expiry()).toBe(new Date(renewedExpiry * 1000).toISOString()); + }); + + it('shows a superseded startup and a hold even without a cached client', async (): Promise => { + const handshake = pauseNextConnect(); + const onStartup = vi.fn<(id: string) => void>(); + const opening = ClustersClient.connectInteractive(clusterId, undefined, onStartup); + await handshake.started; + const startupId = onStartup.mock.calls[0][0]; + const findPending = () => + ClustersClient.getDiagnosticsSnapshot().find(({ pending }) => pending?.startupId === startupId); + expect(findPending()).toMatchObject({ client: undefined, pending: { superseded: false } }); + + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(findPending()).toMatchObject({ + client: undefined, + pending: { superseded: true }, + held: 'userDisconnected', + }); + + handshake.resolve(); + await expect(opening).rejects.toMatchObject({ reason: 'userDisconnected' }); + ClustersClient.unlatch(clusterId); + }); + + it('never hydrates unpinned Entra silently, even after a native connection', async () => { + const expectNoSession = async (): Promise => { + await expect( + ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect'), + ).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'noSession', }); + }; + await expectNoSession(); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + + const uri = 'mongodb://private-user@private-host:27017'; + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, uri); + vi.mocked(NativeAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: uri, + options: {}, + }); + await ClustersClient.getClient(clusterId); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual({ kind: 'native', username: 'private-user' }); + await ClustersClient.deleteClient(clusterId); + + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://private-host:27017'); + await expectNoSession(); + expect(MicrosoftEntraIDAuthHandler.prototype.configureAuth).not.toHaveBeenCalled(); + await ClustersClient.connectInteractive(clusterId); + expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( + AuthMethodId.MicrosoftEntraID, + expect.objectContaining({ clusterId }), + expect.objectContaining({ interactive: true }), + ); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + }); + + it('records only the current publication and retains its pin across eviction and reconnect', async () => { + const staleHandshake = pauseNextConnect(); + const staleWaiter = ClustersClient.connectInteractive(clusterId); + await staleHandshake.started; + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBeUndefined(); + await ClustersClient.deleteClient(clusterId); + const currentIdentity = { ...verifiedIdentity, accountId: 'private-current-account' }; + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: currentIdentity, + }); + const current = await ClustersClient.connectInteractive(clusterId); + const published = ClustersClient.getLastVerifiedIdentity(clusterId); + expect(published).toEqual(currentIdentity); + staleHandshake.resolve(); + await expect(staleWaiter).resolves.toBe(current); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); + + await ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); + const configureAuth = vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth); + for (const connect of [ClustersClient.getClient, ClustersClient.connectInteractive]) { + configureAuth.mockRejectedValueOnce(new Error('pinned startup failed')); + await expect(connect(clusterId)).rejects.toThrow('pinned startup failed'); + expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( + AuthMethodId.MicrosoftEntraID, + expect.objectContaining({ clusterId }), + expect.objectContaining({ interactive: false, pinnedEntraIdentity: currentIdentity }), + ); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); } }); + it('rechecks silent authorization using the credentials cloned during initialization', async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const waiter = ClustersClient.getClient(clusterId, undefined, () => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://private-host:27017', + ); + }); + await expect(waiter).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'noSession' }); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + expect(MongoClient).not.toHaveBeenCalled(); + }); + + it('background calls never start a client, but can reuse a cached one', async () => { + const onStartup = vi.fn(); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, onStartup, 'clusterDashboardPoll', { background: true }); + + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); + CredentialCache.deleteCredentials(clusterId); + await expect(background()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'credentialsMissing', + }); + ClustersClient.latch(clusterId, 'userDisconnected'); + await expect(background()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + }); + expect(onStartup).not.toHaveBeenCalled(); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + expect(MongoClient).not.toHaveBeenCalled(); + expect(mockTelemetryEvents).toHaveLength(0); + + ClustersClient.unlatch(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + await expect(background()).resolves.toBe(client); + expect(onStartup).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + + it('rechecks cancellation and the latch after a cached reuse callback', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const controller = new AbortController(); + const abort = vi.fn(() => controller.abort()); + await expect(ClustersClient.getClient(clusterId, controller.signal, abort)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(abort).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + + const latchedController = new AbortController(); + const latch = vi.fn(() => { + ClustersClient.latch(clusterId, 'userDisconnected'); + latchedController.abort(); + }); + await expect(ClustersClient.getClient(clusterId, latchedController.signal, latch)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + }); + expect(latch).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('retries instead of returning a cached client evicted by the startup callback', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const onStartup = vi.fn().mockImplementationOnce((): void => { + void ClustersClient.deleteClient(clusterId); + }); + const next = await ClustersClient.getClient(clusterId, undefined, onStartup); + expect(next.generation).toBe(client.generation + 1); + expect(onStartup.mock.calls).toEqual([[client.connectionCorrelationId], [next.connectionCorrelationId]]); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('shares one same-identity replacement after topology closure, including a background joiner', async () => { + const old = await ClustersClient.connectInteractive(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + poolEvents.emit('topologyClosed'); + const onBackground = vi.fn(); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, onBackground, 'clusterDashboardPoll', { background: true }); + + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); + expect(onBackground).not.toHaveBeenCalled(); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + + const handshake = pauseNextConnect(); + const onForeground = vi.fn(); + const first = ClustersClient.getClient(clusterId, undefined, onForeground); + await handshake.started; + const second = ClustersClient.getClient(clusterId); + const joined = background(); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + handshake.resolve(); + const [replacement, other, polled] = await Promise.all([first, second, joined]); + expect(other).toBe(replacement); + expect(polled).toBe(replacement); + expect(replacement.generation).toBe(old.generation + 1); + expect(replacement.fingerprint).toBe(old.fingerprint); + expect(replacement.connectionCorrelationId).not.toBe(old.connectionCorrelationId); + expect(onForeground).toHaveBeenCalledExactlyOnceWith(replacement.connectionCorrelationId); + expect(onBackground).toHaveBeenCalledExactlyOnceWith(replacement.connectionCorrelationId); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + + it('keeps the closed binding when repeated replacements would change identity', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + poolEvents.emit('topologyClosed'); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValue({ + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'private-different-account' }, + }); + + for (let attempt = 0; attempt < 2; attempt++) { + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'identityChanged', + }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + } + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( + 'replaces a bound %s client after a rejected callback on the next direct foreground acquisition', + async (authMethod): Promise => { + CredentialCache.setAuthCredentials(clusterId, authMethod, 'mongodb://private-host:27017'); + const handler = + authMethod === AuthMethodId.ManagedIdentity ? ManagedIdentityAuthHandler : MicrosoftEntraIDAuthHandler; + const error = new Error('private-token-lookup-failure'); + const callback = vi.fn().mockRejectedValueOnce(error); + vi.mocked(handler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + ...(authMethod === AuthMethodId.MicrosoftEntraID ? { verifiedIdentity } : {}), + }); + const client = await ClustersClient.connectInteractive(clusterId); + const driverCallback = vi.mocked(MongoClient).mock.lastCall?.[1]?.authMechanismProperties?.OIDC_CALLBACK; + const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; + + await expect(driverCallback!(params)).rejects.toBe(error); + expect(callback).toHaveBeenCalledExactlyOnceWith(params); + expect(ClustersClient.getExistingClient(clusterId)).toBe(client); + expect(ClustersClient.hasReusableClient(clusterId)).toBe(false); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockClose).not.toHaveBeenCalled(); + + const replacement = await ClustersClient.getClient(clusterId); + expect(replacement).not.toBe(client); + expect(replacement.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(MongoClient).toHaveBeenCalledTimes(2); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + }, + ); + + it.each([ + ['transient', new TokenCallbackError(new Error('IMDS unavailable'), AuthMethodId.ManagedIdentity)], + ['clientClosed', new MongoNotConnectedError('driver closed')], + ] as const)('reports %s and replaces once on foreground, fencing late failures and close', async (kind, error) => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.ManagedIdentity, 'mongodb://private-host:27017'); + const old = await ClustersClient.getClient(clusterId); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll', { background: true }); + + expect(ClustersClient.reportFailure(old.binding, error)).toBe(kind); + await expect(background()).rejects.toMatchObject({ reason: 'unreachable' }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + const foreground = ClustersClient.getClient(clusterId); + const [replacement, joined] = await Promise.all([foreground, background()]); + expect(joined).toBe(replacement); + expect(replacement.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(mockClose.mock.contexts[0]).toBe(old.getMongoClient()); + + expect(ClustersClient.reportFailure(old.binding, new EntraIdentityMismatchError())).toBeUndefined(); + expect( + ClustersClient.reportFailure({ ...replacement.binding, fingerprint: 'unmatched' }, error), + ).toBeUndefined(); + expect(ClustersClient.reportFailure(replacement.binding, new ConnectionUnavailableError('unreachable'))).toBe( + 'other', + ); + closing.reject(new Error('old close failed')); + await expect(background()).resolves.toBe(replacement); + }); + + it('holds a rejected Entra replacement without retrying its cached settings', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + poolEvents.emit('topologyClosed'); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + + it('holds a sign-in miss for explicit recovery and does not let a pending replacement bypass it', async () => { + const signInMiss = new EntraSignInRequiredError('noSession'); + const callback = vi.fn().mockRejectedValueOnce(signInMiss); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const client = await ClustersClient.connectInteractive(clusterId); + const driverCallback = vi.mocked(MongoClient).mock.lastCall?.[1]?.authMechanismProperties?.OIDC_CALLBACK; + const pin = ClustersClient.getLastVerifiedIdentity(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + await expect(driverCallback!({ version: 1, timeoutContext: new AbortController().signal })).rejects.toBe( + signInMiss, + ); + expect(ClustersClient.getExistingClient(clusterId)).toBe(client); + expect(mockClose).not.toHaveBeenCalled(); + const handshake = pauseNextConnect(); + const pending = ClustersClient.getClient(clusterId); + await handshake.started; + + expect(ClustersClient.reportFailure(client.binding, signInMiss)).toBe('signInRequired'); + handshake.resolve(); + await expect(pending).rejects.toMatchObject({ reason: 'signInRequired' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(mockConnect).toHaveBeenCalledTimes(2); + + await ClustersClient.deleteClient(clusterId); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + }); + + it('evicts rejected clients without silently retrying or losing the verified Entra settings', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const settings = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const error = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(client.binding, error)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(CredentialCache.getCredentials(clusterId)).toBe(settings); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect( + ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + }), + ).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(true); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(ClustersClient.reportFailure(client.binding, error)).toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBe(recovered.binding); + }); + + it('does not let recovery from a credential rejection clear a newer Disconnect', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + expect(ClustersClient.clearCredentialRejection(clusterId, epoch)).toBe(false); + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + }); + + it('does not publish an explicitly selected account when Disconnect wins the startup race', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const connection = pauseNextConnect(); + const startup = ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + CredentialCache.getCredentials(clusterId)!, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' }, + }, + ); + await connection.started; + ClustersClient.latch(clusterId, 'userDisconnected'); + connection.resolve(); + + await expect(startup).resolves.toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + }); + + it('recovers a rejected Entra account without retiring or replaying its binding', async (): Promise => { + const wrongAccountId = 'private-other-account-id'; + const callback = vi.fn(async (): Promise => { + if (wrongAccountId !== verifiedIdentity.accountId) { + throw new EntraIdentityMismatchError(); + } + throw new Error('The wrong account must not be used'); + }); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + const driverCallback = vi.mocked(MongoClient).mock.lastCall?.[1]?.authMechanismProperties?.OIDC_CALLBACK; + const pin = ClustersClient.getLastVerifiedIdentity(clusterId); + const rejectedOperation = vi.fn(async (): Promise => { + await driverCallback!({ version: 1, timeoutContext: new AbortController().signal }); + throw new Error('The wrong account operation must not continue'); + }); + + await expect(runWithClient(old.binding, rejectedOperation)).resolves.toEqual({ + unavailable: { reason: 'signInRequired' }, + }); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + expect(() => ClustersClient.assertBindingActive(old.binding)).not.toThrow(); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(rejectedOperation).toHaveBeenCalledExactlyOnceWith(old); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + await expect(runWithClient(old.binding, rejectedOperation)).resolves.toEqual({ + unavailable: { reason: 'signInRequired' }, + }); + expect(rejectedOperation).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); + + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const operation = vi.fn(async (client: ClustersClient) => client); + + await expect(runWithClient(old.binding, operation)).resolves.toBe(repaired); + + expect(repaired.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(operation).toHaveBeenCalledExactlyOnceWith(repaired); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('serves the next explicit operation once on a repaired same-account generation', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const operation = vi.fn(async (client: ClustersClient) => client); + + await expect(runWithClient(old.binding, operation)).resolves.toBe(repaired); + + expect(repaired.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(operation).toHaveBeenCalledExactlyOnceWith(repaired); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('ignores a late failure from the generation replaced by same-account repair', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const closes = mockClose.mock.calls.length; + const lateFailure = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(old.binding, lateFailure)).toBeUndefined(); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getBinding(clusterId)).toBe(repaired.binding); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(closes); + expect(await ClustersClient.getClient(clusterId)).toBe(repaired); + expect(mockConnect).toHaveBeenCalledTimes(2); + + expect(ClustersClient.reportFailure(repaired.binding, lateFailure)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(mockClose).toHaveBeenCalledTimes(closes + 1); + }); + + 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 network = Object.freeze(new MongoNetworkError('tunnel refused')); + const op = vi.fn<() => Promise>().mockRejectedValueOnce(network); + await expect(runWithClient(old.binding, op, { background: true })).resolves.toEqual({ + unavailable: { reason: 'unreachable' }, + }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(op).not.toHaveBeenCalled(); + + 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)).resolves.toEqual({ + unavailable: { reason: 'signInRequired' }, + }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + expect(op).toHaveBeenCalledTimes(2); + expect(mockConnect).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'; + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, originalUri); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce(async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://replacement.example.com'); + return { + connectionString: `${originalUri}&authMechanism=MONGODB-OIDC`, + options: {}, + verifiedIdentity, + }; + }); + vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ + connectionString: driverUri, + options: {}, + srvResolution: 'fallback', + }); + + const client = await ClustersClient.connectInteractive(clusterId); + expect(MongoClient).toHaveBeenCalledWith(driverUri, {}); + expect(client.fingerprint).toBe( + computeConnectionFingerprint({ connectionString: originalUri, principal: verifiedIdentity }), + ); + expect(CredentialCache.getCredentials(clusterId)?.authMechanism).toBe(AuthMethodId.NoAuth); + expect(client.authMethod).toBe(AuthMethodId.MicrosoftEntraID); + }); + + it('does not publish an Entra binding when auth does not return a verified identity', async () => { + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: {}, + }); + + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('verifiedIdentity'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(MongoClient).not.toHaveBeenCalled(); + }); + + it('aborts only one waiter while both are waiting for the same replacement', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + poolEvents.emit('topologyClosed'); + const handshake = pauseNextConnect(); + const controller = new AbortController(); + const cancelled = ClustersClient.getClient(clusterId, controller.signal); + const other = ClustersClient.getClient(clusterId, new AbortController().signal); + await handshake.started; + expect(mockConnect).toHaveBeenCalledTimes(2); + + controller.abort(); + await expect(cancelled).rejects.toBeInstanceOf(UserCancelledError); + expect(mockClose).not.toHaveBeenCalled(); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + + handshake.resolve(); + const replacement = await other; + expect(replacement.generation).toBe(client.generation + 1); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('shares one cold startup even with a caller re-entering from onStartup', async () => { + const onJoin = vi.fn(); + let joined!: Promise; + const onStart = vi.fn(() => { + joined = ClustersClient.getClient(clusterId, undefined, onJoin); + }); + const first = ClustersClient.connectInteractive(clusterId, undefined, onStart); + const [client, same] = await Promise.all([first, joined]); + expect(same).toBe(client); + expect(onStart).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(onJoin).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(getClusterMetadata).toHaveBeenCalledTimes(1); + expect(startupEvent().telemetry.properties.startupTrigger).toBe('treeConnect'); + }); + + it.each([0, 1])('canceling cold waiter %i leaves the other waiter connected', async (index) => { + const handshake = pauseNextConnect(); + const controllers = [new AbortController(), new AbortController()]; + const waits = [ + ClustersClient.connectInteractive(clusterId, controllers[0].signal), + ClustersClient.getClient(clusterId, controllers[1].signal, undefined, 'clusterDashboardPoll', { + background: true, + }), + ]; + await handshake.started; + controllers[index].abort(); + await expect(waits[index]).rejects.toBeInstanceOf(UserCancelledError); + expect(vi.mocked(prepareDriverConnectionString).mock.calls[0][0].abortSignal).toBeUndefined(); + expect(mockClose).not.toHaveBeenCalled(); + handshake.resolve(); + const client = await waits[1 - index]; + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('closes the superseded driver without publishing it or removing the newer pending startup', async () => { + const baseline = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + mockClose.mockClear(); + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + + const first = pauseNextConnect(); + const retried = deferred(); + const onStartup = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(retried.resolve); + const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); + await first.started; + await ClustersClient.deleteClient(clusterId); + const second = pauseNextConnect(); + const replacement = ClustersClient.getClient(clusterId); + await second.started; + + first.resolve(); + await retried.promise; + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(1); + expect(mockClose.mock.contexts[0]).toBe(mockConnect.mock.contexts[1]); + second.resolve(); + const client = await replacement; + await expect(waiter).resolves.toBe(client); + expect(onStartup.mock.calls[0][0]).not.toBe(client.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).toBe(client.connectionCorrelationId); + expect(client.generation).toBe(baseline.generation + 1); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledTimes(3); + closing.reject(new Error('private cleanup detail')); + await Promise.resolve(); + expect(ext.outputChannel.debug).toHaveBeenCalledWith( + `[ClustersClient] startup=${onStartup.mock.calls[0][0]} superseded client cleanup failed surface=extension`, + ); + }); + + it('reports the latch instead of a failed superseded handshake', async () => { + const handshake = pauseNextConnect(); + const waiter = ClustersClient.connectInteractive(clusterId); + await handshake.started; + ClustersClient.latch(clusterId, 'userDisconnected'); + handshake.reject(new Error('superseded failure')); + + await expect(waiter).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'userDisconnected' }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).toHaveBeenCalledOnce(); + expect(ClustersClient.getExistingClient(clusterId)).toBeUndefined(); + }); + + it('a stale driver failure does not replace the correlation ID of a newer failure', async () => { + const stale = pauseNextConnect(); + const waiter = ClustersClient.connectInteractive(clusterId); + await stale.started; + ClustersClient.invalidate(clusterId); + mockConnect.mockRejectedValueOnce(new Error('current failure')); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('current failure'); + const failedId = startupEvent().telemetry.properties.startupCorrelationId; + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); + stale.reject(new Error('superseded failure')); + const client = await waiter; + const retry = mockTelemetryEvents.find( + (event) => + event.eventName === 'connect.startup' && + event.telemetry.properties.startupCorrelationId === client.connectionCorrelationId, + ); + expect(retry?.telemetry.properties.previousFailedStartupCorrelationId).toBe(failedId); + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBeUndefined(); + }); + + it('removes the cached entry before closing and leaves a racing replacement alone', async () => { + const old = await ClustersClient.connectInteractive(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + const deletion = ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + const replacement = await ClustersClient.getClient(clusterId); + closing.resolve(); + await deletion; + expect(mockClose).toHaveBeenCalledTimes(1); + expect(mockClose.mock.contexts[0]).toBe(old.getMongoClient()); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }); + + it('closes a fenced client without advancing the epoch again or discarding the identity pin', async () => { + await ClustersClient.connectInteractive(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + expect(identity).toBeDefined(); + const epoch = ClustersClient.getEpoch(clusterId); + + ClustersClient.latch(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + + ClustersClient.unlatch(clusterId); + await expect(ClustersClient.getClient(clusterId)).resolves.toBeDefined(); + }); + + it.each([false, true])('a stale replacement waiter has only one retry (latched: %s)', async (latch) => { + const cached = await ClustersClient.connectInteractive(clusterId); + poolEvents.emit('topologyClosed'); + const replacement = pauseNextConnect(); + const onStartup = vi.fn(); + const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); + await replacement.started; + await ClustersClient.deleteClient(clusterId); + const retry = pauseNextConnect(); + replacement.reject(new Error('superseded replacement failed')); + await retry.started; + if (latch) { + ClustersClient.latch(clusterId, 'connectionRemoved'); + } else { + ClustersClient.invalidate(clusterId); + } + retry.resolve(); + if (latch) { + await expect(waiter).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'connectionRemoved', + }); + } else { + await expect(waiter).rejects.toMatchObject({ + constructor: Error, + message: 'The connection changed while it was opening. Try again.', + }); + } + expect(onStartup).toHaveBeenCalledTimes(2); + expect(onStartup.mock.calls[0][0]).not.toBe(cached.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).not.toBe(cached.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).not.toBe(onStartup.mock.calls[0][0]); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(MongoClient).toHaveBeenCalledTimes(3); + expect(mockClose).toHaveBeenCalledTimes(3); + expect(mockClose.mock.contexts[1]).toBe(mockConnect.mock.contexts[1]); + expect(mockClose.mock.contexts[2]).toBe(mockConnect.mock.contexts[2]); + }); + + it('latch blocks cold and cached calls before startup or driver reuse', async () => { + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + const onStartup = vi.fn(); + await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + message: 'The connection is unavailable.', + }); + expect(MongoClient).not.toHaveBeenCalled(); + ClustersClient.unlatch(clusterId); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 2); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + + await ClustersClient.connectInteractive(clusterId); + ClustersClient.latch(clusterId, 'credentialsChanged'); + await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(onStartup).not.toHaveBeenCalled(); + }); + + it('adds only bounded established-connection context by ID or client and does nothing without one', async () => { + const context: ITelemetryContext = { properties: { existing: 'kept' }, measurements: { existing: 1 } }; + addEstablishedConnectionContext(context, clusterId); + expect(context).toEqual({ properties: { existing: 'kept' }, measurements: { existing: 1 } }); + + const client = await ClustersClient.connectInteractive(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://replacement.example.com'); + vi.advanceTimersByTime(125); + addEstablishedConnectionContext(context, clusterId); + expect(context).toEqual({ + properties: { + existing: 'kept', + authMethod: AuthMethodId.MicrosoftEntraID, + connectionCorrelationId: client.connectionCorrelationId, + }, + measurements: { existing: 1, connectionAgeMs: 125, clientGeneration: client.generation }, + }); + expect(JSON.stringify(context)).not.toContain(client.fingerprint); + expect(JSON.stringify(context)).not.toContain('private-'); + + vi.advanceTimersByTime(25); + addEstablishedConnectionContext(context, client); + expect(context.measurements.connectionAgeMs).toBe(150); + await ClustersClient.deleteClient(clusterId); + vi.advanceTimersByTime(25); + addEstablishedConnectionContext(context, client); + expect(context.measurements.connectionAgeMs).toBe(150); + }); + afterEach(() => { + ClusterSession._sessions.clear(); + SchemaStore.getInstance().clearCluster(clusterId); + if (ClustersClient.getLatchReason(clusterId)) { + ClustersClient.unlatch(clusterId); + } + ClustersClient['_pendingStartups'].clear(); CredentialCache.deleteCredentials(clusterId); ClustersClient._clients.clear(); ClustersClient._lastFailedStartups.clear(); @@ -254,6 +1630,64 @@ describe('regular connection startup diagnostics', () => { vi.useRealTimers(); }); + it('records only allowed pool fields at Debug under the Entra startup ID, starting before connect', async () => { + const privateFields = { address: 'private-host:27017', error: new Error('private-error') }; + mockConnect.mockImplementationOnce(async (): Promise => { + poolEvents.emit('connectionCreated', { connectionId: 7, ...privateFields }); + poolEvents.emit('connectionReady', { connectionId: 7, ...privateFields }); + }); + const client = await ClustersClient.connectInteractive(clusterId); + poolEvents.emit('connectionClosed', { connectionId: 7, reason: 'idle', ...privateFields }); + poolEvents.emit('connectionCheckOutFailed', { reason: 'connectionError', ...privateFields }); + poolEvents.emit('connectionClosed', { connectionId: '', reason: 'private-reason', ...privateFields }); + poolEvents.emit('connectionCheckOutFailed', { reason: 'private-reason', ...privateFields }); + + const prefix = `[ClustersClient] startup=${client.connectionCorrelationId}`; + expect(vi.mocked(ext.outputChannel.debug).mock.calls).toEqual([ + [`${prefix} connectionCreated connectionId=7`], + [`${prefix} connectionReady connectionId=7`], + [`${prefix} connectionClosed connectionId=7 reason=idle`], + [`${prefix} connectionCheckOutFailed reason=connectionError`], + [`${prefix} connectionClosed`], + [`${prefix} connectionCheckOutFailed`], + ]); + }); + + it('logs only bounded listDatabases error details for Entra and rethrows each original error', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const serverError = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); + const networkError = new MongoNetworkError('private-network-message'); + networkError.code = 'private-code'; + const otherError = new Error('private-other-message'); + otherError.name = 'private-name'; + mockListDatabases + .mockRejectedValueOnce(serverError) + .mockRejectedValueOnce(networkError) + .mockRejectedValueOnce(otherError); + + await expect(client.listDatabases()).rejects.toBe(serverError); + await expect(client.listDatabases()).rejects.toBe(networkError); + await expect(client.listDatabases()).rejects.toBe(otherError); + + const prefix = `[ClustersClient] startup=${client.connectionCorrelationId} listDatabases.failed`; + expect(vi.mocked(ext.outputChannel.debug).mock.calls).toEqual([ + [`${prefix} kind=MongoServerError code=18`], + [`${prefix} kind=MongoNetworkError`], + [`${prefix} kind=other`], + ]); + }); + + it('does not attach pool diagnostics or log listDatabases failures for native auth', async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + const error = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); + mockListDatabases.mockRejectedValueOnce(error); + + expect(poolEvents.eventNames()).toEqual(['topologyClosed']); + await expect(client.listDatabases()).rejects.toBe(error); + expect(ext.outputChannel.debug).not.toHaveBeenCalled(); + }); + function startupEvent(): RecordedTelemetry { const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events).toHaveLength(1); @@ -275,8 +1709,9 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: `mongodb://${host}/`, options: {}, + verifiedIdentity, }); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); expect(vi.mocked(MongoClient).mock.calls[0]?.[1]?.appName).toBe(appName); }); @@ -301,7 +1736,7 @@ describe('regular connection startup diagnostics', () => { AuthMethodId.NoAuth, ])('summarizes a fresh %s connection with numbered stage timings', async (authMethod) => { CredentialCache.setAuthCredentials(clusterId, authMethod, 'mongodb://private-host:27017'); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId, undefined, undefined, 'other'); expect(startupEvent().telemetry).toMatchObject({ maskEntireErrorMessage: true, @@ -372,7 +1807,7 @@ describe('regular connection startup diagnostics', () => { undefined, { localQuickStartInstance }, ); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); await vi.dynamicImportSettled(); await vi.waitFor(() => expect(mockTelemetryEvents.map((event) => event.eventName)).toEqual( @@ -394,32 +1829,155 @@ describe('regular connection startup diagnostics', () => { [AuthMethodId.NativeAuth, NativeAuthHandler], [AuthMethodId.NoAuth, NoAuthHandler], ] as const)( - 'constructs the %s handler through the factory with the interactive policy', + 'constructs the %s handler through the factory with the caller policy', async (authMethod, handlerClass): Promise => { CredentialCache.setAuthCredentials(clusterId, authMethod, 'mongodb://private-host:27017'); - await ClustersClient.getClient(clusterId); + const interactive = authMethod === AuthMethodId.MicrosoftEntraID; + if (interactive) { + await ClustersClient.connectInteractive(clusterId); + } else { + await ClustersClient.getClient(clusterId); + } const factory = vi.mocked(authHandlerFactory.createAuthHandler); expect(factory).toHaveBeenCalledTimes(1); - expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), { - interactive: true, - }); + const policy = { + interactive, + ...(interactive + ? { getTokenLookupEpoch: expect.any(Function), onTokenLookup: expect.any(Function) } + : {}), + }; + expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), policy); const handler = factory.mock.results[0]?.value as unknown; expect(handler).toBeInstanceOf(handlerClass); - expect(handler).toHaveProperty('policy', { interactive: true }); + expect(handler).toHaveProperty('policy', policy); expect(handlerClass.prototype.configureAuth).toHaveBeenCalledTimes(1); }, ); + it('counts completed Entra lookups on the current client, independent of database acceptance', async () => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://example.mongocluster.cosmos.azure.com/', + ); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementation(configureEntraAuth); + vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, + }); + vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue({ + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', + }); + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const timedToken = `header.${Buffer.from(JSON.stringify({ iat: now - 600, exp: now + 3000 })).toString('base64url')}.signature`; + const account = { id: 'test-account', label: 'Test account' }; + const session = { id: 'test-session', account, accessToken: timedToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const getCallback = (): NonNullable => { + const options = vi.mocked(MongoClient).mock.lastCall?.[1]; + const callback = options?.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Expected an OIDC callback'); + } + return callback; + }; + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + const lookup = (): Promise => getCallback()(params); + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + const serverRejection = new MongoServerError({ code: 18, message: 'test server rejection' }); + + mockConnect.mockImplementationOnce(async () => { + await lookup(); + await lookup(); + throw serverRejection; + }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(serverRejection); + expect(renewalEvents()).toEqual([]); + + // Startup itself succeeds without calling the callback. Its first later callback counts. + const client = await ClustersClient.connectInteractive(clusterId); + expect(renewalEvents()).toEqual([]); + mockListDatabases.mockImplementationOnce(async () => { + expect(await lookup()).toEqual({ accessToken: timedToken, expiresInSeconds: 2999 }); + throw serverRejection; + }); + await expect(client.listDatabases()).rejects.toBe(serverRejection); + + vi.advanceTimersByTime(600_000); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await expect(lookup()).resolves.toEqual({ accessToken: 'opaque-test-token' }); + await getCallback()({ ...params, timeoutContext: AbortSignal.abort() }); + + const didStart = deferred(); + const finish = deferred(); + getSession.mockImplementationOnce(async () => { + didStart.resolve(); + await finish.promise; + return session; + }); + const spanningSave = lookup(); + await didStart.promise; + // An unchanged save latches and unlatches without retiring this client. + ClustersClient.latch(clusterId, 'credentialsUpdating'); + await lookup(); + ClustersClient.unlatch(clusterId); + finish.resolve(); + await spanningSave; + expect(renewalEvents()).toHaveLength(2); + expect(ClustersClient.getExistingClient(clusterId)).toBe(client); + + await lookup(); + expect(renewalEvents()).toHaveLength(3); + + const retiredLookup = getCallback(); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('driver closed')); + await retiredLookup(params); + expect(await ClustersClient.getClient(clusterId)).not.toBe(client); + await retiredLookup(params); + const closedLookup = getCallback(); + await ClustersClient.deleteClient(clusterId); + await closedLookup(params); + expect(renewalEvents()).toHaveLength(3); + + await ClustersClient.getClient(clusterId); + getSession.mockResolvedValueOnce(undefined); + await expect(lookup()).rejects.toBeInstanceOf(EntraSignInRequiredError); + expect( + renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error]), + ).toEqual([ + [ + { surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], + [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [ + { surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], + [{ surface: 'extension', renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + expect(renewalEvents()).toHaveLength(4); + }); + it('passes its startup ID to auth configuration', async (): Promise => { let traceContext: AuthTraceContext | undefined; vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce( async (_timings, context) => { traceContext = context; - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }, ); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); expect(traceContext).toEqual({ startupCorrelationId: client.connectionCorrelationId, surface: 'extension', @@ -431,12 +1989,12 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockRejectedValueOnce( new Error('private-failure'), ); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('private-failure'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('private-failure'); const failedId = startupEvent().telemetry.properties.startupCorrelationId; expect(failedId).toEqual(expect.any(String)); expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events[0].telemetry.properties.previousFailedStartupCorrelationId).toBeUndefined(); expect(events[1].telemetry.properties).toMatchObject({ @@ -448,7 +2006,7 @@ describe('regular connection startup diagnostics', () => { it('does not record a cancelled startup as a failure to follow up on', async () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockRejectedValueOnce(new UserCancelledError()); - await expect(ClustersClient.getClient(clusterId)).rejects.toBeInstanceOf(UserCancelledError); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBeInstanceOf(UserCancelledError); expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBeUndefined(); }); @@ -474,9 +2032,9 @@ describe('regular connection startup diagnostics', () => { ); throw new Error('private-resolution-failure'); }); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('private-resolution-failure'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('private-resolution-failure'); const failedProperties = { ...startupEvent().telemetry.properties }; - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events[0].telemetry.properties).toEqual(failedProperties); expect(failedProperties).toMatchObject({ @@ -499,7 +2057,7 @@ describe('regular connection startup diagnostics', () => { throw originalError; }); - await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toBe(originalError); + await expect(ClustersClient.connectInteractive(clusterId, undefined, onStartup)).rejects.toBe(originalError); expect(onStartup).toHaveBeenCalledExactlyOnceWith(startupEvent().telemetry.properties.connectionCorrelationId); expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Failed', @@ -519,9 +2077,9 @@ describe('regular connection startup diagnostics', () => { const stop = timings?.startTokenAcquire(); vi.advanceTimersByTime(20); stop?.(); - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); expect(startupEvent().telemetry.measurements).toMatchObject({ tokenAcquireDurationMs: 20, databaseConnectDurationMs: 30, @@ -553,60 +2111,98 @@ describe('regular connection startup diagnostics', () => { it('preserves driver failures and gives the retry a new correlation ID', async () => { const originalError = new Error('private-driver-error'); mockConnect.mockRejectedValueOnce(originalError); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(originalError); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(originalError); const firstEvent = startupEvent(); expect(firstEvent.telemetry.properties.lastStage).toBe('stage04ConnectingAndAuthenticating'); expect(JSON.stringify(firstEvent)).not.toContain('private-'); expect(mockClose).toHaveBeenCalled(); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events).toHaveLength(2); expect(client.connectionCorrelationId).not.toBe(firstEvent.telemetry.properties.connectionCorrelationId); }); - it('reports cancellation without swallowing the caller cancellation error', async () => { + it('does not start a connection for an already canceled waiter', async () => { const controller = new AbortController(); controller.abort(); - await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); - expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Canceled', startupOutcome: 'canceled' }); + const onStartup = vi.fn(); + await expect(ClustersClient.getClient(clusterId, controller.signal, onStartup)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(onStartup).not.toHaveBeenCalled(); + expect(mockTelemetryEvents.filter((e) => e.eventName === 'connect.startup')).toHaveLength(0); expect(ext.outputChannel.error).not.toHaveBeenCalled(); expect(mockConnect).not.toHaveBeenCalled(); }); - it('records cancellation during the driver handshake and retains cleanup', async () => { + it('records a canceled wait during the handshake but publishes the abandoned successful startup', async () => { const controller = new AbortController(); - mockConnect.mockImplementationOnce(async (): Promise => { - vi.advanceTimersByTime(25); - controller.abort(); - throw new Error('private-driver-abort'); - }); + const handshake = pauseNextConnect(); + const waiter = ClustersClient.connectInteractive(clusterId, controller.signal); + await handshake.started; + vi.advanceTimersByTime(25); + controller.abort(); + await expect(waiter).rejects.toBeInstanceOf(UserCancelledError); + handshake.resolve(); + await vi.advanceTimersByTimeAsync(0); - await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); expect(startupEvent().telemetry.properties).toMatchObject({ - result: 'Canceled', - startupOutcome: 'canceled', - lastStage: 'stage04ConnectingAndAuthenticating', + result: 'Succeeded', + startupOutcome: 'succeeded', + lastStage: 'stage05InitializingApis', }); expect(startupEvent().telemetry.measurements.stage04ConnectingAndAuthenticatingDurationMs).toBe(25); - expect(mockClose).toHaveBeenCalled(); + expect(mockClose).not.toHaveBeenCalled(); expect(ext.outputChannel.error).not.toHaveBeenCalled(); - expect(ClustersClient._clients.has(clusterId)).toBe(false); const startupId = startupEvent().telemetry.properties.startupCorrelationId as string; + expect(ClustersClient.getExistingClient(clusterId)?.connectionCorrelationId).toBe(startupId); expect(startupId).toMatch(/^[0-9a-f-]{36}$/); expect(ext.outputChannel.debug).toHaveBeenCalledWith( - `[ClustersClient] startup=${startupId} canceled by user surface=extension`, + `[ClustersClient] startup=${startupId} wait canceled by user surface=extension`, ); }); + it('reports and cleans up a genuine driver failure after both cold waiters leave', async () => { + const handshake = pauseNextConnect(); + const controllers = [new AbortController(), new AbortController()]; + const waits = [ + ClustersClient.connectInteractive(clusterId, controllers[0].signal), + ClustersClient.getClient(clusterId, controllers[1].signal), + ]; + await handshake.started; + controllers.forEach((controller) => controller.abort()); + await Promise.all(waits.map((wait) => expect(wait).rejects.toBeInstanceOf(UserCancelledError))); + expect(mockClose).not.toHaveBeenCalled(); + handshake.reject(new MongoNetworkError('private-driver-failure')); + await vi.advanceTimersByTimeAsync(0); + expect(startupEvent().telemetry.properties).toMatchObject({ + result: 'Failed', + startupOutcome: 'failed', + startupFailureCategory: 'network', + lastStage: 'stage04ConnectingAndAuthenticating', + }); + const failedId = startupEvent().telemetry.properties.startupCorrelationId; + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(1); + expect((await ClustersClient.connectInteractive(clusterId)).connectionCorrelationId).not.toBe(failedId); + }); + it('records a credentials failure before auth configuration', async () => { CredentialCache.deleteCredentials(clusterId); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('No credentials found'); + const waiter = ClustersClient.getClient(clusterId); + await expect(waiter).rejects.toBeInstanceOf(ConnectionUnavailableError); + await expect(waiter).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'credentialsMissing', + message: 'No credentials found.', + }); expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Failed', lastStage: 'stage01PreparingCredentials', - startupFailureType: 'Error', + startupFailureType: 'ConnectionUnavailableError', startupFailureCategory: 'credentialsUnavailable', startupTrigger: 'other', }); @@ -616,13 +2212,50 @@ describe('regular connection startup diagnostics', () => { expect(vi.mocked(MongoClient)).not.toHaveBeenCalled(); }); + it.each(['succeeded', 'failed', 'canceled'] as const)( + 'counts one explicit Reconnect startup when it %s', + async (outcome) => { + ClustersClient.latch(clusterId, 'userDisconnected'); + ClustersClient.unlatch(clusterId, 'requested-start'); + if (outcome !== 'succeeded') { + mockConnect.mockRejectedValueOnce( + outcome === 'canceled' ? new UserCancelledError() : new MongoNetworkError('offline'), + ); + } + const waits = await Promise.allSettled([ + ClustersClient.connectInteractive(clusterId), + ClustersClient.connectInteractive(clusterId), + ]); + expect(waits.map((wait) => wait.status)).toEqual( + outcome === 'succeeded' ? ['fulfilled', 'fulfilled'] : ['rejected', 'rejected'], + ); + expect(startupEvent().telemetry.properties).toMatchObject({ + startupCorrelationId: 'requested-start', + startupTrigger: 'explicitReconnect', + startupOutcome: outcome, + }); + if (outcome === 'failed') { + mockTelemetryEvents.length = 0; + await ClustersClient.connectInteractive(clusterId); + expect(startupEvent().telemetry.properties.startupTrigger).toBe('treeConnect'); + } + }, + ); + + it('does not attribute a new session to a superseded Reconnect request', async () => { + ClustersClient.unlatch(clusterId, 'superseded-start'); + ClustersClient.latch(clusterId, 'credentialsUpdating'); + ClustersClient.unlatch(clusterId); + await ClustersClient.connectInteractive(clusterId); + expect(startupEvent().telemetry.properties.startupTrigger).toBe('treeConnect'); + expect(startupEvent().telemetry.properties.startupCorrelationId).not.toBe('superseded-start'); + }); + it('records the original failure type, category and trigger under names whole-error masking keeps', async () => { const serverError = new MongoServerError({ message: 'private-user authentication failed', code: 18 }); mockConnect.mockRejectedValueOnce(serverError); - await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect')).rejects.toBe( - serverError, - ); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(serverError); const properties = startupEvent().telemetry.properties; expect(properties).toMatchObject({ startupFailureType: '18', @@ -638,8 +2271,8 @@ describe('regular connection startup diagnostics', () => { expect(JSON.stringify(startupEvent())).not.toContain('private-'); }); - it('records no failure properties on a successful or cancelled startup', async () => { - await ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll'); + it('records no failure properties on success and no startup event for pre-cancellation', async () => { + await ClustersClient.connectInteractive(clusterId, undefined, undefined, 'clusterDashboardPoll'); expect(startupEvent().telemetry.properties).toMatchObject({ startupTrigger: 'clusterDashboardPoll' }); expect(startupEvent().telemetry.properties.startupFailureType).toBeUndefined(); expect(startupEvent().telemetry.properties.startupFailureCategory).toBeUndefined(); @@ -649,7 +2282,7 @@ describe('regular connection startup diagnostics', () => { const controller = new AbortController(); controller.abort(); await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); - expect(startupEvent().telemetry.properties.startupFailureCategory).toBeUndefined(); + expect(mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup')).toHaveLength(0); }); it('hands the transient URI to the driver while metadata and credentials keep the original', async () => { @@ -661,6 +2294,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: original, options: {}, + verifiedIdentity, }); vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ connectionString: rewritten, @@ -668,7 +2302,7 @@ describe('regular connection startup diagnostics', () => { srvResolution: 'fallback', summary, }); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); expect(MongoClient).toHaveBeenCalledWith(rewritten, preparedOptions); expect(CredentialCache.getCredentials(clusterId)?.connectionString).toBe(original); const hosts = ['original.global.mongocluster.cosmos.azure.com']; @@ -686,6 +2320,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: original, options: {}, + verifiedIdentity, }); vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ connectionString: 'mongodb://resolved.example.com/', @@ -694,14 +2329,14 @@ describe('regular connection startup diagnostics', () => { }); const failure = new Error('ECONNREFUSED'); mockConnect.mockRejectedValueOnce(failure); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(failure); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(failure); expect(policy).toHaveBeenCalledWith(undefined, original); }); it('rethrows an SRV preparation failure without constructing a driver', async (): Promise => { const failure = new Error('original resolution failure'); vi.mocked(prepareDriverConnectionString).mockRejectedValueOnce(failure); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(failure); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(failure); expect(MongoClient).not.toHaveBeenCalled(); expect(startupEvent().telemetry.properties).toMatchObject({ startupOutcome: 'failed', diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index e95dc632a..07c8b9015 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -22,6 +22,10 @@ import { randomUUID } from 'crypto'; import { MongoBulkWriteError, MongoClient, + MongoError, + MongoNetworkError, + MongoNotConnectedError, + MongoServerError, ObjectId, type ClientSession, type Collection, @@ -32,17 +36,28 @@ import { type InsertManyResult, type ListDatabasesResult, type MongoClientOptions, + type OIDCResponse, type WithId, type WithoutId, } from 'mongodb'; +import * as vscode from 'vscode'; import { Links } from '../constants'; import { ext } from '../extensionVariables'; import { meterSilentCatch } from '../utils/accumulatingTelemetry'; import { type EmulatorConfiguration } from '../utils/emulatorConfiguration'; -import { AuthMethodId } from './auth/AuthMethod'; +import { nonNullValue } from '../utils/nonNull'; +import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; +import { AuthMethodId, isSupportedAuthMethod } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; +import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; +import { readJwtTimes } from './auth/tokenExpiry'; +import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; +import { getRetiredBindingReason, retireConnectionBindings } from './connectionBindingRetirement'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; +import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; import { QueryError } from './errors/QueryError'; import { @@ -59,7 +74,7 @@ import { SchemaStore } from './SchemaStore'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { ConnectionStartupTimings } from './utils/ConnectionStartupTimings'; -import { getHostsFromConnectionString } from './utils/connectionStringHelpers'; +import { getHostsFromConnectionString, getUserNameFromConnectionString } from './utils/connectionStringHelpers'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { getClusterMetadata, type ClusterMetadata } from './utils/getClusterMetadata'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -73,6 +88,29 @@ export interface DatabaseItemModel { empty?: boolean; } +export interface ConnectionBinding { + readonly clusterId: string; + readonly fingerprint: string; + readonly generation: number; +} + +interface ConnectionStatsEntry { + readonly client?: { + readonly generation: number; + readonly ageMs: number; + readonly authMethod?: AuthMethodId; + readonly startupId?: string; + readonly state: 'cached' | 'closed' | 'replaceOnNextForeground' | 'replaceOnRecovery'; + readonly socketTrace: boolean; + readonly lastEntraTokenExpiresAt?: string; + }; + readonly pending?: { readonly startupId: string; readonly superseded: boolean }; + readonly held?: ConnectionUnavailableReason; + readonly lastFailedStartupId?: string; +} + +export type VerifiedIdentity = VerifiedEntraIdentity | Exclude; + export interface CollectionItemModel { name: string; type?: string; @@ -158,6 +196,7 @@ type ClientStartupStage = interface ClientStartup { readonly id: string; + readonly expectedFingerprint?: string; readonly startedAt: number; readonly costTimings: ConnectionStartupTimings; readonly telemetry: ITelemetryContext; @@ -168,6 +207,42 @@ interface ClientStartup { credentialsMissing?: boolean; } +interface PendingStartup { + readonly id: string; + readonly epoch: number; + readonly promise: Promise; +} + +async function waitForClient( + promise: Promise, + signal: AbortSignal | undefined, + startupId: string | undefined, +): Promise { + if (!signal) { + return promise; + } + let onAbort!: () => void; + try { + return await new Promise((resolve, reject) => { + onAbort = (): void => { + ext.outputChannel.debug( + `[ClustersClient] startup=${startupId} wait canceled by user surface=extension`, + ); + reject(new UserCancelledError('abortConnection')); + }; + // Observe settlement even if this caller has already left. + void promise.then(resolve, reject); + if (signal.aborted) { + onAbort(); + } else { + signal.addEventListener('abort', onAbort, { once: true }); + } + }); + } finally { + signal.removeEventListener('abort', onAbort); + } +} + /** * Validates that a parsed BSON value is a plain object (not a scalar, array, or null). * Throws a QueryError if the value is not a plain object. @@ -179,6 +254,24 @@ function assertDocumentObject(value: unknown, errorCode: 'INVALID_PROJECTION' | return value as Document; } +function getVerifiedIdentity( + authMethod: AuthMethodId, + credentials: CachedClusterCredentials, + configuredUri: string, + verifiedIdentity: VerifiedEntraIdentity | undefined, +): VerifiedIdentity { + switch (authMethod) { + case AuthMethodId.NativeAuth: + return { kind: 'native', username: getUserNameFromConnectionString(configuredUri) }; + case AuthMethodId.ManagedIdentity: + return { kind: 'managedIdentity', clientId: credentials.managedIdentityConfig?.clientId }; + case AuthMethodId.MicrosoftEntraID: + return nonNullValue(verifiedIdentity, 'verifiedIdentity', 'ClustersClient.ts'); + case AuthMethodId.NoAuth: + return { kind: 'none' }; + } +} + export class ClustersClient { /** * Cache of active MongoDB clients, keyed by clusterId. @@ -195,7 +288,116 @@ export class ClustersClient { */ static _clients: Map = new Map(); + private static readonly _generations = new Map(); + private static readonly _epochs = new Map(); + private static readonly _latches = new Map(); + private static _onDidChangeLatch: vscode.EventEmitter | undefined; + private static readonly _pendingStartups = new Map(); + private static readonly _requestedReconnectStartups = new Map(); + private static readonly _lastVerifiedIdentities = new Map>(); + + /** Last successfully published identity, retained when the client is evicted. */ + public static getLastVerifiedIdentity(clusterId: string): VerifiedIdentity | undefined { + return ClustersClient._lastVerifiedIdentities.get(clusterId); + } + + public static clearLastVerifiedIdentity(clusterId: string): void { + ClustersClient._lastVerifiedIdentities.delete(clusterId); + } + + /** A saved, explicit tenant change must not silently use the previous tenant's pin. */ + public static discardEntraPinForDifferentTenant(clusterId: string, tenantId: string | undefined): void { + const identity = ClustersClient.getEntraPin(clusterId); + if (identity && identity.tenantId !== tenantId) { + ClustersClient._lastVerifiedIdentities.delete(clusterId); + } + } + + private static getEntraPin(clusterId: string): VerifiedEntraIdentity | undefined { + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + return identity?.kind === 'entra' ? identity : undefined; + } + + /** Compute from current credentials, not from a possibly stale cached client. */ + public static getExpectedFingerprint(clusterId: string, entraFallback?: VerifiedEntraIdentity): string | undefined { + const credentials = CredentialCache.getCredentials(clusterId); + if (!credentials) { + return undefined; + } + const method = credentials.authMechanism ?? AuthMethodId.NativeAuth; + const pin = ClustersClient.getEntraPin(clusterId) ?? entraFallback; + const tenantId = credentials.entraIdConfig?.tenantId; + if (method === AuthMethodId.MicrosoftEntraID && (!pin || pin.tenantId !== tenantId)) { + return undefined; + } + // The keyed fingerprint compares identities only in this host; it does not verify a password. + return computeConnectionFingerprint({ + connectionString: credentials.connectionString, + principal: getVerifiedIdentity( + method, + credentials, + credentials.connectionStringWithPassword ?? credentials.connectionString, + pin, + ), + }); + } + + public static getEpoch(clusterId: string): number { + return ClustersClient._epochs.get(clusterId) ?? 0; + } + + public static invalidate(clusterId: string): number { + ClustersClient._requestedReconnectStartups.delete(clusterId); + const epoch = ClustersClient.getEpoch(clusterId) + 1; + ClustersClient._epochs.set(clusterId, epoch); + return epoch; + } + + public static latch(clusterId: string, reason: ConnectionUnavailableReason): void { + ClustersClient._latches.set(clusterId, reason); + ClustersClient.invalidate(clusterId); + ClustersClient._onDidChangeLatch?.fire(clusterId); + } + + public static unlatch(clusterId: string, requestedReconnectStartupId?: string): void { + ClustersClient._latches.delete(clusterId); + ClustersClient.invalidate(clusterId); + if (requestedReconnectStartupId) { + ClustersClient._requestedReconnectStartups.set(clusterId, requestedReconnectStartupId); + } + ClustersClient._onDidChangeLatch?.fire(clusterId); + } + + public static get onDidChangeLatch(): vscode.Event { + ClustersClient._onDidChangeLatch ??= new vscode.EventEmitter(); + return ClustersClient._onDidChangeLatch.event; + } + + public static getLatchReason(clusterId: string): ConnectionUnavailableReason | undefined { + return ClustersClient._latches.get(clusterId); + } + + public static clearCredentialRejection(clusterId: string, epoch: number): boolean { + if ( + ClustersClient.getEpoch(clusterId) !== epoch || + ClustersClient.getLatchReason(clusterId) !== 'credentialsRejected' + ) { + return false; + } + ClustersClient.unlatch(clusterId); + return true; + } + + #startupCredentials: Readonly; + #verifiedIdentity: VerifiedIdentity; + private _fingerprint: string; + private _binding: ConnectionBinding; + private _createdAt: number; private _mongoClient: MongoClient; + private _closed = false; + private _replacement?: 'replaceOnNextForeground' | 'replaceOnRecovery'; + private _interactiveEntraStartupId?: string; + private _lastEntraTokenExpiresAt?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; private _clusterMetadataPromise: Promise | null = null; @@ -208,7 +410,7 @@ export class ClustersClient { /** * This client's startup ID, also published as `startupCorrelationId`. Links `connect.startup`, - * `connect.staticmetadata`, `connect.getmetadata` and SRV events. Generated once per `initClient` call. + * `connect.staticmetadata`, `connect.getmetadata` and SRV events. Generated once per cold startup. */ public connectionCorrelationId?: string; @@ -223,6 +425,38 @@ export class ClustersClient { return ClustersClient._lastFailedStartups.get(clusterId); } + public static getDiagnosticsSnapshot(): readonly ConnectionStatsEntry[] { + const now = Date.now(); + const clusterIds = new Set([ + ...ClustersClient._clients.keys(), + ...ClustersClient._pendingStartups.keys(), + ...ClustersClient._latches.keys(), + ...ClustersClient._lastFailedStartups.keys(), + ]); + return Array.from(clusterIds, (clusterId): ConnectionStatsEntry => { + const client = ClustersClient._clients.get(clusterId); + const pending = ClustersClient._pendingStartups.get(clusterId); + const authMethod = client?.authMethod; + return { + client: client && { + generation: client.generation, + ageMs: Math.max(0, now - client.createdAt), + authMethod: isSupportedAuthMethod(authMethod) ? authMethod : undefined, + startupId: client.connectionCorrelationId, + state: client._replacement ?? (client._closed ? 'closed' : 'cached'), + socketTrace: client._interactiveEntraStartupId !== undefined, + lastEntraTokenExpiresAt: client._lastEntraTokenExpiresAt, + }, + pending: pending && { + startupId: pending.id, + superseded: pending.epoch !== ClustersClient.getEpoch(clusterId), + }, + held: ClustersClient.getLatchReason(clusterId), + lastFailedStartupId: ClustersClient.getLastFailedStartupCorrelationId(clusterId), + }; + }); + } + /** * Private constructor - use getClient() instead. * Connections/Clients are being cached and reused. @@ -234,6 +468,26 @@ export class ClustersClient { return; } + public get binding(): ConnectionBinding { + return this._binding; + } + + public get createdAt(): number { + return this._createdAt; + } + + public get generation(): number { + return this.binding.generation; + } + + public get fingerprint(): string { + return this.binding.fingerprint; + } + + public get authMethod(): AuthMethodId { + return this.#startupCredentials.authMechanism ?? AuthMethodId.NativeAuth; + } + // TODO: add support for single databases via connection string. // // const databaseInConnectionString = getDatabaseNameFromConnectionString(this.account.connectionString); @@ -267,13 +521,14 @@ export class ClustersClient { } private async initClient( - abortSignal: AbortSignal | undefined, - onStartup: ((id: string) => void) | undefined, + startupId: string, trigger: ClientStartupTrigger, + epoch: number, + allowInteractive: boolean, + expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { - const startupId = randomUUID(); this.connectionCorrelationId = startupId; - onStartup?.(startupId); let originalFailure: { error: unknown } | undefined; try { @@ -295,6 +550,7 @@ export class ClustersClient { const startedAt = Date.now(); const startup: ClientStartup = { id: startupId, + expectedFingerprint, startedAt, costTimings: new ConnectionStartupTimings(), telemetry: context.telemetry, @@ -304,7 +560,7 @@ export class ClustersClient { }; try { - await this.initializeClient(startup, abortSignal); + await this.initializeClient(startup, epoch, allowInteractive, recoveredAuth); this.finishClientStartup(startup, 'succeeded'); } catch (error) { const canceled = error instanceof UserCancelledError; @@ -359,29 +615,68 @@ export class ClustersClient { ); } - private async initializeClient(startup: ClientStartup, abortSignal?: AbortSignal): Promise { - const credentials = CredentialCache.getCredentials(this.clusterId); - if (!credentials) { + private async initializeClient( + startup: ClientStartup, + epoch: number, + allowInteractive: boolean, + recoveredAuth?: AuthHandlerResponse, + ): Promise { + const cachedCredentials = CredentialCache.getCredentials(this.clusterId); + if (!cachedCredentials) { startup.credentialsMissing = true; - throw new Error(l10n.t('No credentials found for id {clusterId}', { clusterId: this.clusterId })); + throw new ConnectionUnavailableError('credentialsMissing'); + } + const credentials = structuredClone(cachedCredentials); + this.#startupCredentials = credentials; + + const reason = ClustersClient.getLatchReason(this.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + if (epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new Error(l10n.t('The connection changed while it was opening. Try again.')); } // default to NativeAuth if nothing is configured - const authMethod = credentials?.authMechanism ?? AuthMethodId.NativeAuth; + const authMethod = this.authMethod; startup.telemetry.properties.authMethod = authMethod; - // Ordinary connects may prompt (for example, Microsoft Entra ID sign-in). - const authHandler = createAuthHandler(authMethod, credentials, { interactive: true }); + const pinnedEntraIdentity = + authMethod === AuthMethodId.MicrosoftEntraID ? ClustersClient.getEntraPin(this.clusterId) : undefined; + if (authMethod === AuthMethodId.MicrosoftEntraID && !pinnedEntraIdentity && !allowInteractive) { + throw new EntraSignInRequiredError('noSession'); + } + const authHandler = createAuthHandler(authMethod, credentials, { + interactive: allowInteractive && !pinnedEntraIdentity, + ...(pinnedEntraIdentity ? { pinnedEntraIdentity } : {}), + ...(authMethod === AuthMethodId.MicrosoftEntraID + ? { + getTokenLookupEpoch: () => this.getTokenLookupEpoch(), + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), + } + : {}), + }); // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options } = await authHandler.configureAuth(startup.costTimings, { - startupCorrelationId: startup.id, - surface: 'extension', - startupProperties: startup.telemetry.properties, - }); + const { connectionString, options, verifiedIdentity } = + recoveredAuth ?? + (await authHandler.configureAuth(startup.costTimings, { + startupCorrelationId: startup.id, + surface: 'extension', + startupProperties: startup.telemetry.properties, + })); this.advanceClientStartup(startup, 'stage03PreparingClient'); + this.#verifiedIdentity = getVerifiedIdentity(authMethod, credentials, connectionString, verifiedIdentity); + // Keep the fingerprint on the host for binding comparisons, not in the driver credentials. + this._fingerprint = computeConnectionFingerprint({ + connectionString: credentials.connectionString, + principal: this.#verifiedIdentity, + }); + if (startup.expectedFingerprint !== undefined && this._fingerprint !== startup.expectedFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } const hosts = getHostsFromConnectionString(connectionString); const userAgentString = hosts.some((host) => getAzureHostSuffix(host)) ? appendExtensionUserAgent() : undefined; if (userAgentString) { @@ -412,18 +707,23 @@ export class ClustersClient { startupCorrelationId: startup.id, connectionCorrelationId: startup.id, }, - abortSignal, startupTelemetry: startup.telemetry, }); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } this._srvResolution = prepared.summary; await this.connect( startup, prepared.connectionString, prepared.options, + authMethod === AuthMethodId.MicrosoftEntraID, credentials.emulatorConfiguration, - abortSignal, connectionString, ); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } // Start metadata collection and store the promise this._clusterMetadataPromise = getClusterMetadata(this._mongoClient, hosts); @@ -442,49 +742,73 @@ export class ClustersClient { }); } + private traceInteractiveEntraPool(startupId: string): void { + const log = (event: string, connectionId?: number | '', reason?: string): void => { + const idField = typeof connectionId === 'number' ? ` connectionId=${connectionId}` : ''; + const reasonField = reason === undefined ? '' : ` reason=${reason}`; + ext.outputChannel?.debug(`[ClustersClient] startup=${startupId} ${event}${idField}${reasonField}`); + }; + this._mongoClient.on('connectionCreated', ({ connectionId }) => log('connectionCreated', connectionId)); + this._mongoClient.on('connectionReady', ({ connectionId }) => log('connectionReady', connectionId)); + this._mongoClient.on('connectionClosed', ({ connectionId, reason }) => { + log( + 'connectionClosed', + connectionId, + ['idle', 'stale', 'poolClosed', 'error'].includes(reason) ? reason : undefined, + ); + }); + this._mongoClient.on('connectionCheckOutFailed', ({ reason }) => { + log( + 'connectionCheckOutFailed', + undefined, + ['poolClosed', 'timeout', 'connectionError'].includes(reason) ? reason : undefined, + ); + }); + } + private async connect( startup: ClientStartup, connectionString: string, options: MongoClientOptions, + interactiveEntra: boolean, emulatorConfiguration?: EmulatorConfiguration, - abortSignal?: AbortSignal, originalConnectionString: string = connectionString, ): Promise { - // Create the client instance first so we hold a reference during connection. - // This allows callers to abort via abortSignal by closing the underlying client. + const authProperties = options.authMechanismProperties; + const callback = authProperties?.OIDC_CALLBACK; + if (callback) { + options = { + ...options, + authMechanismProperties: { + ...authProperties, + OIDC_CALLBACK: async (params): Promise => { + let response: OIDCResponse; + try { + response = await callback(params); + } catch (error) { + if (this._binding) { + this._replacement ??= 'replaceOnNextForeground'; + } + throw error; + } + if (interactiveEntra) { + const { expSec } = readJwtTimes(response.accessToken); + this._lastEntraTokenExpiresAt = + expSec === undefined ? undefined : (new Date(expSec * 1000).toJSON() ?? undefined); + } + return response; + }, + }, + }; + } this._mongoClient = new MongoClient(connectionString, options); - - if (abortSignal?.aborted) { - ext.outputChannel.debug( - `[ClustersClient] startup=${startup.id} canceled before connecting (already aborted signal) surface=extension`, - ); - await this._mongoClient.close(); - throw new UserCancelledError('abortConnection'); - } - - // Track whether connect() has resolved so the abort handler can avoid - // closing an already-connected client during the micro window between - // connect() resolving and removeEventListener firing. This window exists - // because abort events are dispatched synchronously when abort() is - // called: if abort() fires during the synchronous continuation after - // connect() resolves but before the listener is removed, the handler - // would close the now-connected client without this guard. - let connected = false; - - // Wire up abort: closing the client causes the pending connect() to reject - const onAbort = (): void => { - if (connected) { - // connect() already resolved — do not close the connected client. - return; - } - ext.outputChannel.debug( - `[ClustersClient] startup=${startup.id} abort requested; closing client to interrupt connection handshake surface=extension`, - ); - void this._mongoClient.close().catch(() => { - // Ignore close errors during abort cleanup - }); - }; - abortSignal?.addEventListener('abort', onAbort, { once: true }); + this._mongoClient.once('topologyClosed', (): void => { + this._closed = true; + }); + if (interactiveEntra) { + this._interactiveEntraStartupId = startup.id; + this.traceInteractiveEntraPool(startup.id); + } try { this.advanceClientStartup(startup, 'stage04ConnectingAndAuthenticating'); @@ -494,24 +818,10 @@ export class ClustersClient { } finally { stopDatabaseConnect(); } - connected = true; - - // Remove the abort listener immediately after connect() resolves so - // that a late cancellation during synchronous API init below cannot - // close an already-connected client while the method continues as - // "successful". The connected flag above serves as a belt-and-suspenders - // guard in case abort fires between the assignment and this removal. - abortSignal?.removeEventListener('abort', onAbort); - this.advanceClientStartup(startup, 'stage05InitializingApis'); this._llmEnhancedFeatureApis = new llmEnhancedFeatureApis(this._mongoClient); this._queryInsightsApis = new QueryInsightsApis(this._mongoClient); } catch (error) { - if (abortSignal?.aborted) { - ext.outputChannel.debug(`[ClustersClient] startup=${startup.id} canceled by user surface=extension`); - throw new UserCancelledError('abortConnection'); - } - const message = parseError(error).message; // Surface the friendly local-connection tips only for a genuinely local-ish connection // (emulator, OR a local connection that opted into the TLS exception — host-gated the @@ -537,13 +847,6 @@ export class ClustersClient { ); } throw error; - } finally { - // Clean up the abort listener if we didn't already remove it in the - // success path (i.e., connect() failed). In the success path the - // listener was already removed above. - if (abortSignal && !connected) { - abortSignal.removeEventListener('abort', onAbort); - } } } @@ -557,15 +860,16 @@ export class ClustersClient { } /** - * Retrieves an instance of `ClustersClient` based on the provided `clusterId`. + * Retrieves an instance of `ClustersClient` without opening sign-in UI. * * @param clusterId - A required string used to find the cached connection string to connect. * It is also used as a key to reuse existing clients. - * @param abortSignal - Optional signal to abort the connection attempt. When aborted, - * the in-progress connection is closed and a `UserCancelledError` is thrown. + * @param abortSignal - Optional signal that rejects the call with `UserCancelledError` on abort. + * Cancellation stops only this caller's wait, not the underlying connection. * @param onStartup - Called with the startup correlation ID of the attempt this call joins. * @param trigger - Which code path asks for the client; recorded as `startupTrigger` when this * call starts a new `connect.startup`. Callers that do not pass it are recorded as `other`. + * @param options - Background callers may reuse a client or join a startup, but never start one. * @returns A promise that resolves to an instance of `ClustersClient`. */ public static async getClient( @@ -573,65 +877,364 @@ export class ClustersClient { abortSignal?: AbortSignal, onStartup?: (id: string) => void, trigger: ClientStartupTrigger = 'other', + options?: { readonly background?: boolean }, + ): Promise { + return ClustersClient.acquireClient( + clusterId, + abortSignal, + onStartup, + trigger, + false, + options?.background === true, + ); + } + + /** A deliberate connect may open sign-in only when there is no verified Entra identity. */ + public static async connectInteractive( + clusterId: string, + abortSignal?: AbortSignal, + onStartup?: (id: string) => void, + trigger: ClientStartupTrigger = 'treeConnect', + ): Promise { + 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 async resolveBoundClient( + binding: ConnectionBinding, + options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, ): Promise { - if (ClustersClient._clients.has(clusterId)) { - const client = ClustersClient._clients.get(clusterId) as ClustersClient; - if (client.connectionCorrelationId) { - onStartup?.(client.connectionCorrelationId); + ClustersClient.assertBindingActive(binding); + const client = await ClustersClient.acquireClient( + binding.clusterId, + undefined, + undefined, + options?.trigger ?? 'other', + false, + options?.background === true, + binding.fingerprint, + ); + ClustersClient.assertBindingActive(binding); + return client; + } + + public static retireBoundViews(clusterId: string): number { + const generation = ClustersClient._generations.get(clusterId) ?? 0; + retireConnectionBindings(clusterId, generation); + return generation; + } + + public static assertBindingActive(binding: ConnectionBinding): void { + const reason = getRetiredBindingReason(binding) ?? ClustersClient.getLatchReason(binding.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } + + public static hasPendingStartup(clusterId: string): boolean { + return ClustersClient._pendingStartups.has(clusterId); + } + + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ + public static async startAfterSignIn( + clusterId: string, + epoch: number, + credentials: CachedClusterCredentials, + auth: AuthHandlerResponse, + ): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + epoch !== ClustersClient.getEpoch(clusterId) || + CredentialCache.getCredentials(clusterId) !== credentials || + credentials.authMechanism !== AuthMethodId.MicrosoftEntraID || + (reason && reason !== 'credentialsRejected') + ) { + return undefined; + } + if (reason && !ClustersClient.clearCredentialRejection(clusterId, epoch)) { + return undefined; + } + void ClustersClient.deleteClient(clusterId).catch(() => { + ext.outputChannel.debug('[ClustersClient] failed to close a client during sign-in recovery'); + }); + const startupEpoch = ClustersClient.getEpoch(clusterId); + try { + const { promise } = ClustersClient.getOrStartClient( + clusterId, + startupEpoch, + 'treeConnect', + false, + false, + undefined, + auth, + ); + const client = await promise; + return startupEpoch === ClustersClient.getEpoch(clusterId) ? client : undefined; + } catch (error) { + if (startupEpoch !== ClustersClient.getEpoch(clusterId)) { + return undefined; } + if ( + reason === 'credentialsRejected' || + classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected' + ) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + throw error; + } + } - // Wire up abort for cached client reconnection so the cancellable - // progress UI can also cancel a reconnection attempt. + private static async acquireClient( + clusterId: string, + abortSignal: AbortSignal | undefined, + onStartup: ((id: string) => void) | undefined, + trigger: ClientStartupTrigger, + allowInteractive: boolean, + background: boolean, + boundFingerprint?: string, + ): Promise { + for (let attempt = 0; ; attempt++) { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } if (abortSignal?.aborted) { throw new UserCancelledError('abortConnection'); } + if (attempt === 2) { + throw new Error(l10n.t('The connection changed while it was opening. Try again.')); + } - const onAbort = (): void => { - void client._mongoClient.close().catch(() => { - // Ignore close errors when aborting during reconnect - }); - }; - abortSignal?.addEventListener('abort', onAbort, { once: true }); + 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'); + } + if (cached?.canReuse()) { + const id = cached.connectionCorrelationId; + if (id) { + onStartup?.(id); + } + if (epoch !== ClustersClient.getEpoch(clusterId)) { + continue; + } + if (abortSignal?.aborted) { + ext.outputChannel.debug(`[ClustersClient] startup=${id} wait canceled by user surface=extension`); + throw new UserCancelledError('abortConnection'); + } + if (cached.canReuse()) { + return cached; + } + } + // Until a replacement succeeds, the old entry still pins the connection identity. + const { id, promise } = ClustersClient.getOrStartClient( + clusterId, + epoch, + trigger, + allowInteractive, + background, + boundFingerprint ?? cached?.fingerprint, + ); + onStartup?.(id); try { - // if the client is already connected, it's a NOOP. - // Note: connectionCorrelationId retains the value from the initial - // connection (set in initClient). This is by design — the correlation - // ID links the original connect/staticmetadata/getmetadata events. - // Cached reconnects don't emit new metadata events, so no new ID is needed. - await client._mongoClient.connect(); + 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) { - if (abortSignal?.aborted) { - throw new UserCancelledError('abortConnection'); + if (epoch === ClustersClient.getEpoch(clusterId)) { + throw error; } - throw error; - } finally { - abortSignal?.removeEventListener('abort', onAbort); } + // Both a stale success and a stale failure use the same retry, after checking the latch. + } + } - return client; + private static getOrStartClient( + clusterId: string, + epoch: number, + trigger: ClientStartupTrigger, + allowInteractive: boolean, + background: boolean, + expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, + ): PendingStartup { + const existing = ClustersClient._pendingStartups.get(clusterId); + if (existing?.epoch === epoch) { + return existing; } + const credentials = CredentialCache.getCredentials(clusterId); + if (background) { + if (!credentials) { + throw new ConnectionUnavailableError('credentialsMissing'); + } + // This caller didn't run anything on a client. Don't treat this as a driver close. + throw new ConnectionUnavailableError('unreachable'); + } + if ( + !allowInteractive && + credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && + !ClustersClient.getEntraPin(clusterId) + ) { + throw new EntraSignInRequiredError('noSession'); + } + + // Consume a Reconnect request only when creating a physical startup, never on a waiter or cached reuse. + const reconnectId = ClustersClient._requestedReconnectStartups.get(clusterId); + const id = reconnectId ?? randomUUID(); + ClustersClient._requestedReconnectStartups.delete(clusterId); + // Register before initialization or a caller's onStartup callback can re-enter getClient. + const promise = Promise.resolve().then(() => + ClustersClient.establishClient( + clusterId, + epoch, + id, + reconnectId ? 'explicitReconnect' : trigger, + allowInteractive, + expectedFingerprint, + recoveredAuth, + ), + ); + const pending = { id, epoch, promise }; + ClustersClient._pendingStartups.set(clusterId, pending); + const clear = (): void => { + if (ClustersClient._pendingStartups.get(clusterId) === pending) { + ClustersClient._pendingStartups.delete(clusterId); + } + }; + void promise.then(clear, clear); + return pending; + } + + private static async establishClient( + clusterId: string, + epoch: number, + id: string, + trigger: ClientStartupTrigger, + allowInteractive: boolean, + expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, + ): Promise { const client = new ClustersClient(clusterId); try { - // Cluster metadata is set in initClient - await client.initClient(abortSignal, onStartup, trigger); - ClustersClient._clients.set(clusterId, client); - ClustersClient._lastFailedStartups.delete(clusterId); + await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint, recoveredAuth); + if (client._closed) { + throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + } } catch (error) { - if (!(error instanceof UserCancelledError) && !abortSignal?.aborted && client.connectionCorrelationId) { - ClustersClient._lastFailedStartups.set(clusterId, client.connectionCorrelationId); + if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { + ClustersClient._lastFailedStartups.set(clusterId, id); + const previous = ClustersClient._clients.get(clusterId); + if ( + previous?.authMethod === AuthMethodId.MicrosoftEntraID && + previous.fingerprint === expectedFingerprint + ) { + const failure = classifyConnectionFailure(error, previous.authMethod); + if (failure.kind === 'credentialsRejected' && failure.generation === 'evict') { + ClustersClient.reportFailure(previous.binding, error); + } + } } - // On failure (including abort), clean up the partially-created client + client._closed = true; void client._mongoClient?.close().catch(() => { // Ignore close errors during cleanup }); throw error; } + if (epoch !== ClustersClient.getEpoch(clusterId)) { + client._closed = true; + void client._mongoClient.close().catch(() => { + meterSilentCatch('ClustersClient_supersededClientClose'); + ext.outputChannel.debug( + `[ClustersClient] startup=${id} superseded client cleanup failed surface=extension`, + ); + }); + } else { + const previous = ClustersClient._clients.get(clusterId); + const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; + client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); + client._createdAt = Date.now(); + ClustersClient._generations.set(clusterId, generation); + ClustersClient._lastVerifiedIdentities.set(clusterId, Object.freeze({ ...client.#verifiedIdentity })); + ClustersClient._clients.set(clusterId, client); + ClustersClient._lastFailedStartups.delete(clusterId); + if (previous && !previous._closed) { + previous._closed = true; + void previous._mongoClient.close(true).catch(() => { + // Closing a retired driver must not affect its replacement. + }); + } + } return client; } + private canReuse(): boolean { + return !this._closed && this._replacement === undefined; + } + + public getTokenLookupEpoch(): number | undefined { + if ( + !this.canReuse() || + ClustersClient.getExistingClient(this.clusterId) !== this || + ClustersClient.getLatchReason(this.clusterId) + ) { + return undefined; + } + return ClustersClient.getEpoch(this.clusterId); + } + + public static hasReusableClient(clusterId: string): boolean { + return ClustersClient._clients.get(clusterId)?.canReuse() ?? false; + } + + /** Reports an operation's failure against the generation that actually ran it. */ + public static reportFailure(binding: ConnectionBinding, error: unknown): ConnectionFailure['kind'] | undefined { + const { clusterId, fingerprint, generation } = binding; + const client = ClustersClient._clients.get(clusterId); + if ( + !client || + client.generation !== generation || + client.fingerprint !== fingerprint || + ClustersClient.getLatchReason(clusterId) + ) { + return undefined; + } + + const failure = classifyConnectionFailure(error, client.authMethod); + if (client._replacement === 'replaceOnRecovery') { + return failure.kind; + } + switch (failure.generation) { + case 'replaceOnNextForeground': + client._replacement = failure.generation; + break; + case 'replaceOnRecovery': + client._replacement = failure.generation; + // An already-started replacement must not bypass explicit recovery. + ClustersClient.invalidate(clusterId); + break; + case 'evict': + if (failure.kind === 'credentialsRejected') { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + void ClustersClient.deleteClient(clusterId).catch(() => { + meterSilentCatch('ClustersClient_evictedClientClose'); + ext.outputChannel.debug('[ClustersClient] failed to close an evicted client'); + }); + break; + } + return failure.kind; + } + /** * Retrieves cluster metadata for this client instance. * @@ -655,7 +1258,7 @@ export class ClustersClient { } /** - * Returns an existing client synchronously if it is already in the connection pool. + * Returns an existing client synchronously if it is already in the client cache. * Returns `undefined` if the client is not yet connected. This is useful for * accessing cached data (e.g., cached collection/database listings) without * triggering a connection or blocking on async operations. @@ -664,19 +1267,32 @@ export class ClustersClient { return ClustersClient._clients.get(clusterId); } + public static getBinding(clusterId: string): ConnectionBinding | undefined { + return ClustersClient.getExistingClient(clusterId)?.binding; + } + public static getSrvResolution(clusterId: string): SrvResolutionSummary | undefined { return ClustersClient._clients.get(clusterId)?._srvResolution; } - public static async deleteClient(clusterId: string): Promise { - if (ClustersClient._clients.has(clusterId)) { - const client = ClustersClient._clients.get(clusterId) as ClustersClient; - await client._mongoClient.close(true); + public static async deleteClient( + clusterId: string, + options?: { readonly alreadyInvalidated: boolean }, + ): Promise { + if (!options?.alreadyInvalidated) { + ClustersClient.invalidate(clusterId); + } + const client = ClustersClient._clients.get(clusterId); + if (client) { ClustersClient._clients.delete(clusterId); - - // Clear cached schema data for this cluster + client._closed = true; + } + if (client || options?.alreadyInvalidated) { SchemaStore.getInstance().clearCluster(clusterId); } + if (client) { + await client._mongoClient.close(true); + } } startTransaction(): ClientSession { @@ -790,7 +1406,24 @@ export class ClustersClient { // filter below relies on the `empty` field, which `nameOnly` omits (along with // `sizeOnDisk`). Keeping the full listing ensures an empty `admin` database stays // hidden while a non-empty `admin` (user-managed roles/collections) remains visible. - const rawDatabases: ListDatabasesResult = await this._mongoClient.db().admin().listDatabases(); + let rawDatabases: ListDatabasesResult; + try { + rawDatabases = await this._mongoClient.db().admin().listDatabases(); + } catch (error) { + if (this._interactiveEntraStartupId) { + let kind = 'other'; + if (error instanceof MongoServerError) { + kind = 'MongoServerError'; + } else if (error instanceof MongoNetworkError) { + kind = 'MongoNetworkError'; + } + const code = error instanceof MongoError && typeof error.code === 'number' ? ` code=${error.code}` : ''; + ext.outputChannel?.debug( + `[ClustersClient] startup=${this._interactiveEntraStartupId} listDatabases.failed kind=${kind}${code}`, + ); + } + throw error; + } const databases: DatabaseItemModel[] = rawDatabases.databases.filter( // Filter out the 'admin' database if it's empty (databaseInfo) => !(databaseInfo.name && databaseInfo.name.toLowerCase() === 'admin' && databaseInfo.empty), @@ -1475,3 +2108,15 @@ export class ClustersClient { return this._llmEnhancedFeatureApis.unhideIndex(databaseName, collectionName, indexName); } } + +export function addEstablishedConnectionContext(context: ITelemetryContext, cluster: string | ClustersClient): void { + const client = typeof cluster === 'string' ? ClustersClient.getExistingClient(cluster) : cluster; + if (!client || ClustersClient.getExistingClient(client.binding.clusterId) !== client) { + return; + } + + context.properties.authMethod = client.authMethod; + context.properties.connectionCorrelationId = client.connectionCorrelationId; + context.measurements.connectionAgeMs = Math.max(0, Date.now() - client.createdAt); + context.measurements.clientGeneration = client.generation; +} diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index ca92f92b0..477245c96 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -37,6 +37,7 @@ import { createMongoDocument } from '../commands/createDocument/createDocument'; import { deleteCollection } from '../commands/deleteCollection/deleteCollection'; import { deleteAzureDatabase } from '../commands/deleteDatabase/deleteDatabase'; import { diagnoseConnection } from '../commands/diagnoseConnection/diagnoseConnection'; +import { connectDisconnected, disconnect } from '../commands/disconnect/disconnect'; import { filterProviderContent } from '../commands/discoveryService.filterProviderContent/filterProviderContent'; import { manageCredentials } from '../commands/discoveryService.manageCredentials/manageCredentials'; import { exportEntireCollection, exportQueryResults } from '../commands/exportDocuments/exportDocuments'; @@ -67,6 +68,7 @@ import { openIndexManagementView } from '../commands/openIndexManagementView/ope import { openInteractiveShell, openInteractiveShellWithInput, + openUnauthenticatedShell, } from '../commands/openInteractiveShell/openInteractiveShell'; import { pasteCollection } from '../commands/pasteCollection/pasteCollection'; import { pasteIndexes } from '../commands/pasteIndexes/pasteIndexes'; @@ -85,9 +87,9 @@ import { removeConnection } from '../commands/removeConnection/removeConnection' import { removeDiscoveryRegistry } from '../commands/removeDiscoveryRegistry/removeDiscoveryRegistry'; import { retryAuthentication } from '../commands/retryAuthentication/retryAuthentication'; import { revealView } from '../commands/revealView/revealView'; -import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; -import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; +import { showConnectionStats } from '../commands/showConnectionStats/showConnectionStats'; import { showWorkerStats } from '../commands/showWorkerStats/showWorkerStats'; +import { signInAgain } from '../commands/signInAgain/signInAgain'; import { updateConnectionString } from '../commands/updateConnectionString/updateConnectionString'; import { updateCredentials } from '../commands/updateCredentials/updateCredentials'; import { isVCoreAndRURolloutEnabled } from '../extension'; @@ -113,7 +115,6 @@ import { disposeQuickStartOutputChannel } from '../services/localQuickStart/Cont import { QuickStartErrorExplainer } from '../services/localQuickStart/QuickStartErrorExplainer'; import { QuickStartService, sweepStaleQuickStartEnvFiles } from '../services/localQuickStart/QuickStartService'; import { maybeShowReleaseNotesNotification } from '../services/releaseNotesNotification'; -import { DemoTask } from '../services/taskService/tasks/DemoTask'; import { TaskService } from '../services/taskService/taskService'; import { TaskProgressReportingService } from '../services/taskService/UI/taskProgressReportingService'; import { maybeShowWelcomeScreen } from '../services/welcomeScreen'; @@ -145,6 +146,7 @@ import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; import { registerCollectionViewColumnContextMenuCommands } from '../webviews/documentdb/collectionView/collectionViewController'; import { EntraErrorExplainer } from './auth/entraErrors/EntraErrorExplainer'; +import { EntraSignInRequiredErrorExplainer } from './auth/entraErrors/EntraSignInRequiredErrorExplainer'; import { PLAYGROUND_FILE_EXTENSION, PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './playground/constants'; import { PlaygroundBlockHighlighter } from './playground/PlaygroundBlockHighlighter'; import { PlaygroundCodeLensProvider } from './playground/PlaygroundCodeLensProvider'; @@ -190,6 +192,7 @@ export class ClustersExtension implements vscode.Disposable { ErrorExplanationService.registerProvider(new AtlasErrorExplainer()); // First explanation wins, so source-specific explanations take priority over generic SRV failures. ErrorExplanationService.registerProvider(new SrvDnsErrorExplainer()); + ErrorExplanationService.registerProvider(new EntraSignInRequiredErrorExplainer()); ErrorExplanationService.registerProvider(new EntraErrorExplainer()); } @@ -623,13 +626,10 @@ export class ClustersExtension implements vscode.Disposable { }, ); - registerCommand('vscode-documentdb.command.clearSchemaCache', withCommandCorrelation(clearSchemaCache)); - registerCommand( - 'vscode-documentdb.command.showSchemaStoreStats', - withCommandCorrelation(showSchemaStoreStats), + 'vscode-documentdb.command.showConnectionStats', + withCommandCorrelation(showConnectionStats), ); - registerCommand('vscode-documentdb.command.showWorkerStats', withCommandCorrelation(showWorkerStats)); //// General Commands: @@ -1015,6 +1015,19 @@ export class ClustersExtension implements vscode.Disposable { 'vscode-documentdb.command.internal.retry', withTreeNodeCommandCorrelation(retryAuthentication), ); + registerCommandWithTreeNodeUnwrapping('vscode-documentdb.command.disconnect', disconnect); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.internal.connectDisconnected', + withTreeNodeCommandCorrelation(connectDisconnected), + ); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', + withTreeNodeCommandCorrelation(openUnauthenticatedShell), + ); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.signInAgain', + withTreeNodeCommandCorrelation(signInAgain), + ); registerCommandWithTreeNodeUnwrapping( 'vscode-documentdb.command.internal.revealView', withTreeNodeCommandCorrelation(revealView), @@ -1117,35 +1130,6 @@ export class ClustersExtension implements vscode.Disposable { withTreeNodeCommandCorrelation(exportEntireCollection), ); - // Testing command for DemoTask - registerCommand('vscode-documentdb.command.testing.startDemoTask', async (_context: IActionContext) => { - const failureOptions = [ - { - label: vscode.l10n.t('$(check) Success'), - description: vscode.l10n.t('Task will complete successfully'), - shouldFail: false, - }, - { - label: vscode.l10n.t('$(error) Failure'), - description: vscode.l10n.t('Task will fail at a random step for testing'), - shouldFail: true, - }, - ]; - - const selectedOption = await vscode.window.showQuickPick(failureOptions, { - title: vscode.l10n.t('Demo Task Configuration'), - placeHolder: vscode.l10n.t('Choose whether the task should succeed or fail'), - }); - - if (!selectedOption) { - return; // User cancelled - } - - const task = new DemoTask(vscode.l10n.t('Demo Task {0}', Date.now()), selectedOption.shouldFail); - TaskService.registerTask(task); - void task.start(); - }); - void maybeShowWelcomeScreen(); }, ); diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts new file mode 100644 index 000000000..4778e59a9 --- /dev/null +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; + +export type ConnectionUnavailableReason = + | 'signInRequired' + | 'credentialsRejected' + | 'credentialsMissing' + | 'credentialsUpdating' + | 'credentialsChanged' + | 'identityChanged' + | 'userDisconnected' + | 'connectionRemoved' + | 'unreachable' + | 'sessionEnded'; + +export function isDiagnosticAuthenticationHold(reason: ConnectionUnavailableReason | undefined): boolean { + return reason === 'credentialsRejected' || reason === 'signInRequired' || reason === 'credentialsMissing'; +} + +export class ConnectionUnavailableError extends Error { + constructor( + readonly reason: ConnectionUnavailableReason, + options?: ErrorOptions, + ) { + super( + reason === 'credentialsMissing' + ? l10n.t('No credentials found.') + : l10n.t('The connection is unavailable.'), + options, + ); + this.name = 'ConnectionUnavailableError'; + } +} diff --git a/src/documentdb/auth/AuthHandler.ts b/src/documentdb/auth/AuthHandler.ts index 7549d27df..1c8e7be5b 100644 --- a/src/documentdb/auth/AuthHandler.ts +++ b/src/documentdb/auth/AuthHandler.ts @@ -25,4 +25,13 @@ export interface AuthHandler { export interface AuthHandlerResponse { connectionString: string; options: MongoClientOptions; + verifiedIdentity?: VerifiedEntraIdentity; +} + +export interface VerifiedEntraIdentity { + readonly kind: 'entra'; + readonly providerId: string; + readonly accountId: string; + readonly accountLabel: string; + readonly tenantId?: string; } diff --git a/src/documentdb/auth/AuthMethod.ts b/src/documentdb/auth/AuthMethod.ts index e0c92b178..d32b7bc9d 100644 --- a/src/documentdb/auth/AuthMethod.ts +++ b/src/documentdb/auth/AuthMethod.ts @@ -5,26 +5,9 @@ import * as vscode from 'vscode'; import { getIconPath } from '../../utils/icons'; +import { AuthMethodId } from './AuthMethodId'; -/** - * Authentication method identifiers - */ -export enum AuthMethodId { - /** The regular, typical username+password and connection string authentication. */ - NativeAuth = 'NativeAuth', - /** Microsoft Entra ID (Azure AD) authentication. */ - MicrosoftEntraID = 'MicrosoftEntraID', - /** - * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. - * - * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` - * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by - * an explicit rule in `clusterHelpers.ts`. - */ - ManagedIdentity = 'ManagedIdentity', - /** Anonymous connection without a username, password, or Entra ID. */ - NoAuth = 'NoAuth', -} +export { AuthMethodId }; /** * Authentication method metadata diff --git a/src/documentdb/auth/AuthMethodId.ts b/src/documentdb/auth/AuthMethodId.ts new file mode 100644 index 000000000..d43a37ec5 --- /dev/null +++ b/src/documentdb/auth/AuthMethodId.ts @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export enum AuthMethodId { + /** The regular, typical username+password and connection string authentication. */ + NativeAuth = 'NativeAuth', + /** Microsoft Entra ID (Azure AD) authentication. */ + MicrosoftEntraID = 'MicrosoftEntraID', + /** + * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. + * + * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` + * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by + * an explicit rule in `clusterHelpers.ts`. + */ + ManagedIdentity = 'ManagedIdentity', + /** Anonymous connection without a username, password, or Entra ID. */ + NoAuth = 'NoAuth', +} diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index e5a8bb7c4..149f145db 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts @@ -15,6 +15,7 @@ import { type AuthPhaseObserver } from './authCallerPolicy'; import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import * as tokenResources from './documentdbTokenResource'; +import { TokenCallbackError } from './entraErrors/entraCallbackErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -22,6 +23,7 @@ import { resetEntraTokenFailuresForTests, } from './entraErrors/entraTokenFailures'; import { ManagedIdentityAuthHandler } from './ManagedIdentityAuthHandler'; +import { ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { expiresInSecondsFromTimestamp } from './tokenExpiry'; @@ -341,16 +343,7 @@ describe('ManagedIdentityAuthHandler', () => { expect(getManagedIdentityAccessToken.mock.calls[0][3]).toBe(getManagedIdentityAccessToken.mock.calls[1][3]); }); - it('propagates the provider readable failure', async () => { - getManagedIdentityAccessToken.mockRejectedValue(new Error('More than one managed identity is available.')); - const handler = new ManagedIdentityAuthHandler(buildCredentials()); - - const { options } = await handler.configureAuth(); - - await expect(invokeOidcCallback(options)).rejects.toThrow(/more than one managed identity/i); - }); - - it('records failures only inside the deferred token callback and rethrows the same error', async (): Promise => { + it('wraps and records failures only inside the deferred token callback', async (): Promise => { const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.us/'; const handler = new ManagedIdentityAuthHandler( buildCredentials({ connectionString, connectionStringWithPassword: connectionString }), @@ -367,7 +360,10 @@ describe('ManagedIdentityAuthHandler', () => { expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); expect(getManagedIdentityAccessToken).not.toHaveBeenCalled(); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + const callback = invokeOidcCallback(options); + await expect(callback).rejects.toBeInstanceOf(TokenCallbackError); + await expect(callback).rejects.toMatchObject({ authMethod: AuthMethodId.ManagedIdentity, cause: error }); + await expect(callback).rejects.not.toThrow(/AADSTS500011/); expect(startupProperties.entraFailureKind).toBe('tokenAcquisitionFailed'); expect(JSON.stringify(startupProperties)).not.toMatch(/cluster-1|AADSTS|https/); expect(getRecentEntraTokenFailure('cluster-1')).toEqual({ @@ -378,6 +374,24 @@ describe('ManagedIdentityAuthHandler', () => { }); }); + it('preserves the actionable managed identity message in the typed callback wrapper', async (): Promise => { + const message = + 'This machine has more than one managed identity, so the right one cannot be chosen automatically. Reconnect and enter the client ID you want to use.'; + const accessToken = 'private-access-token'; + const cause = Object.freeze(Object.assign(new ManagedIdentityGuidanceError(message), { accessToken })); + getManagedIdentityAccessToken.mockRejectedValueOnce(cause); + const { options } = await new ManagedIdentityAuthHandler(buildCredentials()).configureAuth(); + + const callback = invokeOidcCallback(options); + await expect(callback).rejects.toMatchObject({ + name: 'TokenCallbackError', + message, + authMethod: AuthMethodId.ManagedIdentity, + cause, + }); + await expect(callback).rejects.not.toThrow(accessToken); + }); + it('does not record token resource resolution errors as token-acquisition failures', async (): Promise => { const error = new tokenResources.TokenResourceResolutionError( 'Set the cloud resource.', @@ -416,11 +430,12 @@ describe('ManagedIdentityAuthHandler', () => { surface: 'extension', startupProperties: failedProperties, }); - await expect(invokeOidcCallback(failed.options)).rejects.toBe(error); + const callbackError: unknown = await invokeOidcCallback(failed.options).catch((failure: unknown) => failure); + expect(callbackError).toMatchObject({ cause: error }); const failure = getRecentEntraTokenFailure('cluster-1'); expect(failure).toMatchObject({ cloudCategory: 'usgov', authMethod: 'managedIdentity' }); const diagnostics = new EntraErrorExplainer(); - expect(await diagnostics.explain({ clusterId: 'cluster-1', error })).toContain( + expect(await diagnostics.explain({ clusterId: 'cluster-1', error: callbackError })).toContain( 'Sign-in failed in Azure US Government', ); @@ -600,14 +615,18 @@ describe('ManagedIdentityAuthHandler', () => { const error = new Error('AADSTS700016: identity not found'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); const events: string[] = []; + const onTokenFailed = vi.fn(() => { + events.push('tokenFailed'); + }); const handler = new ManagedIdentityAuthHandler(buildCredentials(), { interactive: false, - observer: recordingObserver(events), + observer: { ...recordingObserver(events), onTokenFailed }, }); const { options } = await handler.configureAuth(); expect(events).toEqual(['resolved:public:host:*.mongocluster.cosmos.azure.com']); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); + expect(onTokenFailed).toHaveBeenCalledExactlyOnceWith(error); expect(events).toEqual([ 'resolved:public:host:*.mongocluster.cosmos.azure.com', 'tokenStarted', @@ -655,7 +674,7 @@ describe('ManagedIdentityAuthHandler', () => { await expect(invokeOidcCallback(options)).resolves.toMatchObject({ accessToken: 'a-token' }); const error = new Error('token failure'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); }); }); }); diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.ts index aaad4b268..265d7f6d9 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.ts @@ -12,6 +12,7 @@ import { type CachedClusterCredentials } from '../CredentialCache'; import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { notifyAuthPhaseObserver, type AuthCallerPolicy, type AuthPhaseObserver } from './authCallerPolicy'; import { type AuthHandler, type AuthHandlerResponse } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveManagedIdentityTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; @@ -100,6 +101,7 @@ export class ManagedIdentityAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, + callbackAuthMethod: AuthMethodId.ManagedIdentity, oidcCallback: async (): Promise => { const currentDecision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(currentDecision, this.tokenCorrelationId, traceContext); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index d4b061e19..cef2bb0f5 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -3,12 +3,21 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { type PeerCertificate } from 'tls'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import type * as documentdbTokenResource from './documentdbTokenResource'; const getSessionFromVSCode = vi.fn(); +const getConfiguredAuthProviderId = vi.fn<() => string>(); +type AzureSignInSettings = Pick< + ReturnType, + 'name' | 'activeDirectoryEndpointUrl' +>; +const getConfiguredAzureEnv = vi.fn<() => AzureSignInSettings>(); +const account = { id: 'account-id', label: 'account-label' }; +const session = { accessToken: 'access-token', account }; const mockOutputChannel = { info: vi.fn(), error: vi.fn() }; vi.mock('../../extensionVariables', () => ({ ext: { @@ -18,8 +27,15 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]) => getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: (...args: unknown[]): unknown => getSessionFromVSCode(...args) }, +})); + +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getConfiguredAuthProviderId: (): string => getConfiguredAuthProviderId(), + getConfiguredAzureEnv: (): AzureSignInSettings => getConfiguredAzureEnv(), })); vi.mock('./documentdbTokenResource', async (importOriginal) => ({ @@ -31,8 +47,14 @@ import { type CachedClusterCredentials } from '../CredentialCache'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { AuthInputUnavailableError, type AuthPhaseObserver } from './authCallerPolicy'; import { buildAuthConnectionTarget } from './authConnectionTarget'; +import { type VerifiedEntraIdentity } from './AuthHandler'; import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -53,11 +75,24 @@ function buildCredentials(connectionString: string): CachedClusterCredentials { } describe('MicrosoftEntraIDAuthHandler', () => { + const pinnedEntraIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId: 'microsoft', + accountId: account.id, + accountLabel: account.label, + tenantId: 'pinned-tenant', + }; + beforeEach(() => { vi.clearAllMocks(); resetEntraTokenFailuresForTests(); getSessionFromVSCode.mockReset(); - getSessionFromVSCode.mockResolvedValue({ accessToken: 'access-token' }); + getSessionFromVSCode.mockResolvedValue(session); + getConfiguredAuthProviderId.mockReset().mockReturnValue('microsoft'); + getConfiguredAzureEnv.mockReset().mockReturnValue({ + name: 'AzureCloud', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.com/', + }); vi.mocked(resolveInteractiveTokenResource).mockResolvedValue({ resource: 'https://ossrdbms-aad.database.windows.net', scope: 'https://ossrdbms-aad.database.windows.net/.default', @@ -78,6 +113,55 @@ describe('MicrosoftEntraIDAuthHandler', () => { resetEntraTokenFailuresForTests(); }); + it.each(['pinned-tenant', undefined])('uses the pinned tenant %s, never the cached tenant', async (tenantId) => { + const pin = { ...pinnedEntraIdentity, tenantId }; + const result = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, pinnedEntraIdentity: pin }, + ).configureAuth(); + + const scopes = ['https://ossrdbms-aad.database.windows.net/.default']; + if (tenantId !== undefined) { + scopes.push(`VSCODE_TENANT:${tenantId}`); + } + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(pin.providerId, scopes, { silent: true, account }); + expect(result.verifiedIdentity).toEqual(pin); + }); + + it.each(['providerChanged', 'noSession', 'identityMismatch'] as const)( + 'fails closed on a pinned %s without changing the existing failure context', + async (failure) => { + const credentials = buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'); + recordEntraTokenFailure(credentials.clusterId, { cloudCategory: 'public', authMethod: 'interactive' }); + const previousFailure = getRecentEntraTokenFailure(credentials.clusterId); + const startupProperties: Record = {}; + if (failure === 'providerChanged') { + getConfiguredAuthProviderId.mockReturnValue('different-provider'); + } else if (failure === 'noSession') { + getSessionFromVSCode.mockResolvedValue(undefined); + } else { + getSessionFromVSCode.mockResolvedValue({ + ...session, + account: { ...account, id: 'different-account' }, + }); + } + + const configuring = new MicrosoftEntraIDAuthHandler(credentials, { + interactive: false, + pinnedEntraIdentity, + }).configureAuth(undefined, { startupCorrelationId: 'startup', surface: 'extension', startupProperties }); + if (failure === 'identityMismatch') { + await expect(configuring).rejects.toBeInstanceOf(EntraIdentityMismatchError); + } else { + await expect(configuring).rejects.toBeInstanceOf(EntraSignInRequiredError); + await expect(configuring).rejects.toMatchObject({ reason: failure }); + } + expect(getSessionFromVSCode).toHaveBeenCalledTimes(failure === 'providerChanged' ? 0 : 1); + expect(getRecentEntraTokenFailure(credentials.clusterId)).toBe(previousFailure); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + }, + ); + it.each([ 'mongodb://attacker.cloudapp.azure.com/', 'mongodb://cluster.mongocluster.cosmos.azure.com,attacker.example.com/', @@ -103,7 +187,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { getSessionFromVSCode.mockImplementationOnce(async () => { expect(resolveInteractiveTokenResource).toHaveBeenCalledExactlyOnceWith(connectionString); expect(mockOutputChannel.info.mock.calls[0][0]).toContain('entraDestination.evaluated'); - return { accessToken: 'access-token' }; + return session; }); const result = await new MicrosoftEntraIDAuthHandler(buildCredentials(connectionString)).configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); @@ -132,8 +216,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(result.connectionString).toContain('retryWrites=true'); expect(result.options.authMechanismProperties).toHaveProperty('OIDC_CALLBACK'); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { createIfNone: true }, ); const output = JSON.stringify(mockOutputChannel.info.mock.calls); @@ -193,16 +277,173 @@ describe('MicrosoftEntraIDAuthHandler', () => { }, ); - it('rechecks the eager captured-token callback and existing TLS hook after trust removal', async (): Promise => { + it('silently accepts the same still-valid token twice with the pinned identity and bounded diagnostics', async () => { + const now = Math.floor(Date.now() / 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 600 })).toString('base64url')}.signature`; + getSessionFromVSCode.mockResolvedValue({ accessToken, account }); + const onTokenLookup = vi.fn(); + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, + ); + const { options, verifiedIdentity } = await handler.configureAuth(undefined, { + startupCorrelationId: 'startup-id', + surface: 'extension', + }); + const callback = options.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Missing OIDC callback'); + } + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + + expect(verifiedIdentity).toEqual({ + kind: 'entra', + providerId: 'microsoft', + accountId: account.id, + accountLabel: account.label, + tenantId: 'tenant', + }); + const clock = vi.spyOn(Date, 'now').mockReturnValue(now * 1000); + try { + await expect(callback(params)).resolves.toEqual({ accessToken, expiresInSeconds: 600 }); + await expect(callback(params)).resolves.toEqual({ accessToken, expiresInSeconds: 600 }); + } finally { + clock.mockRestore(); + } + const scopes = ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant']; + expect(getSessionFromVSCode.mock.calls).toEqual([ + ['microsoft', scopes, { createIfNone: true }], + ['microsoft', scopes, { silent: true, account }], + ['microsoft', scopes, { silent: true, account }], + ]); + expect(onTokenLookup.mock.calls).toEqual([ + [{ outcome: 'returned', lifetimeSeconds: 660 }], + [{ outcome: 'returned', lifetimeSeconds: 660 }], + ]); + expect( + mockOutputChannel.info.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('interactiveEntra.oidcCallback')), + ).toEqual([ + '[Authentication] startup=startup-id surface=extension interactiveEntra.oidcCallback: {"invocation":1,"outcome":"returned"}', + '[Authentication] startup=startup-id surface=extension interactiveEntra.oidcCallback: {"invocation":2,"outcome":"returned"}', + ]); + }); + + it.each([false, true])( + 'reports a pending driver timeout once without changing the callback (later epoch change=%s)', + async (changeEpoch): Promise => { + let epoch = 0; + const onTokenLookup = vi.fn((): void => { + throw new Error('test lookup observer failure'); + }); + const onCallbackTokenObserved = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { + interactive: true, + getTokenLookupEpoch: (): number => epoch, + onTokenLookup, + observer: { onCallbackTokenObserved }, + }, + ).configureAuth(); + let finish!: (value: typeof session) => void; + getSessionFromVSCode.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }), + ); + const controller = new AbortController(); + const pending = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: controller.signal, + }); + await vi.waitFor(() => expect(getSessionFromVSCode).toHaveBeenCalledTimes(2)); + expect(onTokenLookup).not.toHaveBeenCalled(); + expect(onCallbackTokenObserved).not.toHaveBeenCalled(); + + expect(() => controller.abort()).not.toThrow(); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'timedOut' }]]); + if (changeEpoch) { + epoch++; + } + finish(session); + await expect(pending).resolves.toEqual({ accessToken: session.accessToken }); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'timedOut' }]]); + expect(onCallbackTokenObserved).toHaveBeenCalledExactlyOnceWith({ + outcome: 'acquired', + accessToken: session.accessToken, + tenantId: 'tenant', + }); + expect(getSessionFromVSCode.mock.calls[1]?.[2]).toEqual({ silent: true, account }); + }, + ); + + it('does not report a timeout after the pending lookup becomes stale', async (): Promise => { + let epoch = 0; + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: (): number => epoch, onTokenLookup }, + ).configureAuth(); + let finish!: (value: typeof session) => void; + getSessionFromVSCode.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }), + ); + const controller = new AbortController(); + const pending = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: controller.signal, + }); + await vi.waitFor(() => expect(getSessionFromVSCode).toHaveBeenCalledTimes(2)); + epoch++; + controller.abort(); + expect(onTokenLookup).not.toHaveBeenCalled(); + finish(session); + await expect(pending).resolves.toEqual({ accessToken: session.accessToken }); + expect(onTokenLookup).not.toHaveBeenCalled(); + }); + + it.each(['returned', 'failed'] as const)( + 'does not report a timeout after the callback has %s', + async (outcome): Promise => { + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: (): number => 0, onTokenLookup }, + ).configureAuth(); + if (outcome === 'failed') { + getSessionFromVSCode.mockRejectedValueOnce(new Error('test provider failure')); + } + const controller = new AbortController(); + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: controller.signal, + }); + if (outcome === 'failed') { + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + } else { + await expect(result).resolves.toEqual({ accessToken: session.accessToken }); + } + expect(onTokenLookup.mock.calls).toEqual([[{ outcome }]]); + controller.abort(); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome }]]); + }, + ); + + it('rechecks destination trust before the silent callback and applies the existing TLS hook', async (): Promise => { let suffix: string | undefined = 'database.example.com'; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn(), inspect: vi.fn(() => ({ globalValue: { hostnameSuffix: suffix } })), } as unknown as vscode.WorkspaceConfiguration); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.database.example.com/'), ).configureAuth(); const callback = options.authMechanismProperties!.OIDC_CALLBACK!; - await expect(callback({ version: 1, timeoutContext: new AbortController().signal })).resolves.toMatchObject({ + await expect(callback({ version: 1, timeoutContext: new AbortController().signal })).resolves.toEqual({ accessToken: 'access-token', }); suffix = undefined; @@ -212,7 +453,290 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(options.checkServerIdentity?.('cluster.database.example.com', {} as PeerCertificate)).toBeInstanceOf( EntraDestinationRejectedError, ); - expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + }); + + it('rechecks destination trust after a silent lookup, before returning its token', async () => { + let suffix: string | undefined = 'database.example.com'; + const onCallbackTokenObserved = vi.fn(); + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn(), + inspect: vi.fn(() => ({ globalValue: { hostnameSuffix: suffix } })), + } as unknown as vscode.WorkspaceConfiguration); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.database.example.com/'), + { interactive: false, observer: { onCallbackTokenObserved } }, + ).configureAuth(); + getSessionFromVSCode.mockImplementationOnce(async () => { + suffix = undefined; + return session; + }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).rejects.toBeInstanceOf(EntraDestinationRejectedError); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(onCallbackTokenObserved).not.toHaveBeenCalled(); + }); + + it('does not reject or repeat a lookup based on the token expiration claim', async () => { + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ).configureAuth(); + const accessToken = `header.${Buffer.from('{"exp":1}').toString('base64url')}.signature`; + getSessionFromVSCode.mockResolvedValueOnce({ accessToken, account }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).resolves.toEqual({ accessToken, expiresInSeconds: 0 }); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + }); + + it.each([ + ['noSession', 'noSession', EntraSignInRequiredError], + ['providerChanged', 'providerChanged', EntraSignInRequiredError], + ['identityMismatch', 'identityMismatch', EntraIdentityMismatchError], + ] as const)('rejects %s without prompting or recording a token failure', async (failure, outcome, errorType) => { + const onTokenLookup = vi.fn(); + const onCallbackTokenObserved = vi.fn>(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, + ).configureAuth(); + if (failure === 'providerChanged') { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + } else { + getSessionFromVSCode.mockResolvedValueOnce( + failure === 'noSession' ? undefined : { ...session, account: { ...account, id: 'different-account' } }, + ); + } + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toBeInstanceOf(errorType); + expect(onCallbackTokenObserved).toHaveBeenCalledOnce(); + const observed = onCallbackTokenObserved.mock.lastCall?.[0]; + expect(observed?.outcome).toBe('failed'); + await expect(result).rejects.toBe(observed?.outcome === 'failed' ? observed.error : undefined); + if (failure !== 'identityMismatch') { + await expect(result).rejects.toMatchObject({ reason: failure }); + } + if (failure === 'providerChanged') { + expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + } else { + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(getSessionFromVSCode.mock.calls[1]?.[2]).toEqual({ silent: true, account }); + } + expect(onTokenLookup.mock.calls).toEqual([[{ outcome }]]); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }); + + it.each([ + { + name: 'AzureChinaCloud', + activeDirectoryEndpointUrl: 'https://login.chinacloudapi.cn/', + }, + { + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }, + ])( + 'rejects a sovereign cloud switch to $name before lookup even when the provider ID is unchanged', + async (environment): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureUSGovernment', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.us/'), + ).configureAuth(); + getConfiguredAzureEnv.mockReturnValue(environment); + + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + expect(getSessionFromVSCode).toHaveBeenCalledOnce(); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }, + ); + + it.each(['returns', 'rejects'] as const)( + 'rejects same-cloud authority path drift when the silent lookup %s', + async (lookupOutcome): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/original/', + }); + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, + ).configureAuth(); + recordEntraTokenFailure('cluster-1', { cloudCategory: 'custom', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure('cluster-1'); + getSessionFromVSCode.mockImplementationOnce(async () => { + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/changed/', + }); + if (lookupOutcome === 'rejects') { + throw new Error('AADSTS65002: private-lookup-cause'); + } + return { ...session, accessToken: 'mismatched-token' }; + }); + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + await expect(result).rejects.not.toHaveProperty('cause'); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(getRecentEntraTokenFailure('cluster-1')).toBe(priorFailure); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'providerChanged' }]]); + const logs = JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls]); + expect(logs).not.toMatch(/authority\.example\.com|mismatched-token|private-lookup-cause|AADSTS65002/); + }, + ); + + it.each(['before', 'after'] as const)( + 'treats an unreadable environment %s the silent lookup as controlled drift', + async (when): Promise => { + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ).configureAuth(); + const makeEnvironmentUnreadable = (): void => { + getConfiguredAzureEnv.mockImplementationOnce(() => { + throw new Error('private-configuration-cause'); + }); + }; + if (when === 'before') { + makeEnvironmentUnreadable(); + } else { + getSessionFromVSCode.mockImplementationOnce(async () => { + makeEnvironmentUnreadable(); + return session; + }); + } + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + await expect(result).rejects.not.toHaveProperty('cause'); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(when === 'before' ? 1 : 2); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + const logs = JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls]); + expect(logs).not.toContain('private-configuration-cause'); + }, + ); + + it('does not request a session when the authority changes during resource resolution', async () => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/original/', + }); + const resolveResource = vi.mocked(resolveInteractiveTokenResource); + const resolveWithoutDrift = resolveResource.getMockImplementation()!; + resolveResource.mockImplementationOnce(async (connectionString) => { + const resolved = await resolveWithoutDrift(connectionString); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/changed/', + }); + return resolved; + }); + + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ); + await expect(handler.configureAuth()).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'providerChanged', + }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }); + + it.each([true, false])( + 'does not pin a session or change the prior failure if the initial lookup environment changes (interactive=%s)', + async (interactive): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureUSGovernment', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }); + recordEntraTokenFailure('cluster-1', { cloudCategory: 'usgov', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure('cluster-1'); + getSessionFromVSCode.mockImplementationOnce(async () => { + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureChinaCloud', + activeDirectoryEndpointUrl: 'https://login.chinacloudapi.cn/', + }); + return session; + }); + const onTokenAcquired = vi.fn(); + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.us/'), + { interactive, observer: { onTokenAcquired } }, + ); + + await expect(handler.configureAuth()).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'providerChanged', + }); + expect(onTokenAcquired).not.toHaveBeenCalled(); + expect(getRecentEntraTokenFailure('cluster-1')).toBe(priorFailure); + }, + ); + + it('wraps and records only an unexpected callback failure, without logging its cause', async () => { + const onTokenLookup = vi.fn(); + const onCallbackTokenObserved = vi.fn>(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, + ).configureAuth(); + const cause = new Error('AADSTS65002: private-cause'); + getSessionFromVSCode.mockRejectedValueOnce(cause); + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + await expect(result).rejects.toMatchObject({ + message: 'Failed to obtain a Microsoft Entra ID token.', + authMethod: AuthMethodId.MicrosoftEntraID, + cause, + }); + expect(onCallbackTokenObserved).toHaveBeenCalledOnce(); + const observed = onCallbackTokenObserved.mock.lastCall?.[0]; + expect(observed?.outcome).toBe('failed'); + await expect(result).rejects.toBe(observed?.outcome === 'failed' ? observed.error : undefined); + expect(getRecentEntraTokenFailure('cluster-1')).toMatchObject({ + authMethod: 'interactive', + ruleId: 'firstPartyPreauthorization', + }); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'failed' }]]); + expect(JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls])).not.toContain( + 'private-cause', + ); + expect(mockOutputChannel.info).toHaveBeenLastCalledWith( + expect.stringContaining('interactiveEntra.oidcCallback: {"invocation":1,"outcome":"threw"}'), + ); }); it('captures the original destination and tenant before resolving the audience', async (): Promise => { @@ -231,9 +755,11 @@ describe('MicrosoftEntraIDAuthHandler', () => { }); const { connectionString } = await new MicrosoftEntraIDAuthHandler(credentials).configureAuth(); expect(connectionString).toBe(original); - expect(getSessionFromVSCode).toHaveBeenCalledWith(['https://database.example/.default'], 'tenant', { - createIfNone: true, - }); + expect(getSessionFromVSCode).toHaveBeenCalledWith( + 'microsoft', + ['https://database.example/.default', 'VSCODE_TENANT:tenant'], + { createIfNone: true }, + ); }); it('requests the resolved US Government scope and records its category on the existing trace', async () => { @@ -248,7 +774,9 @@ describe('MicrosoftEntraIDAuthHandler', () => { const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.us/'; await new MicrosoftEntraIDAuthHandler(buildCredentials(connectionString)).configureAuth(); expect(resolveInteractiveTokenResource).toHaveBeenCalledWith(connectionString); - expect(getSessionFromVSCode).toHaveBeenCalledWith([scope], 'tenant', { createIfNone: true }); + expect(getSessionFromVSCode).toHaveBeenCalledWith('microsoft', [scope, 'VSCODE_TENANT:tenant'], { + createIfNone: true, + }); const output = mockOutputChannel.info.mock.calls.map((call) => String(call[0])).join('\n'); expect(output).toContain('"cloudCategory":"usgov"'); expect(output).toContain('"tokenResourceReason":"setting"'); @@ -405,7 +933,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { getSessionFromVSCode.mockImplementationOnce(async () => { expect(getRecentEntraTokenFailure('cluster-1')).toBe(failure); - return { accessToken: 'access-token' }; + return session; }); const successfulProperties: Record = {}; await handler.configureAuth(undefined, { @@ -488,7 +1016,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const timings = new ConnectionStartupTimings(() => now); getSessionFromVSCode.mockImplementationOnce(async () => { now = 25; - return { accessToken: 'access-token' }; + return session; }); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), @@ -572,8 +1100,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { ); await handler.configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { createIfNone: true }, ); const output = mockOutputChannel.info.mock.calls.map((call) => String(call[0])).join('\n'); @@ -591,8 +1119,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { const { options } = await handler.configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { silent: true }, ); const sessionOptions: unknown = getSessionFromVSCode.mock.calls[0]?.[2]; @@ -605,6 +1133,56 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(output).not.toContain('access-token'); }); + it.each(['success', 'noSession', 'rejection'] as const)( + 'keeps a non-interactive callback silent on %s', + async (outcome): Promise => { + const cause = new Error('provider rejected silent lookup'); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: false, pinnedEntraIdentity }, + ).configureAuth(); + if (outcome === 'noSession') { + getSessionFromVSCode.mockResolvedValueOnce(undefined); + } else if (outcome === 'rejection') { + getSessionFromVSCode.mockRejectedValueOnce(cause); + } + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + + if (outcome === 'success') { + await expect(result).resolves.toEqual({ accessToken: session.accessToken }); + } else if (outcome === 'noSession') { + await expect(result).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'noSession', + }); + } else { + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + } + expect(getSessionFromVSCode.mock.calls).toEqual([ + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + ]); + }, + ); + it('reports a missing silent session as unavailable input without recording a token failure', async () => { getSessionFromVSCode.mockResolvedValueOnce(undefined); const events: string[] = []; @@ -684,6 +1262,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { }); const events: string[] = []; const acquired: unknown[] = []; + const onCallbackTokenObserved = vi.fn(); const observer = recordingObserver(events); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), @@ -691,6 +1270,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { interactive: false, observer: { ...observer, + onCallbackTokenObserved, onTokenStarted: () => { expect(getSessionFromVSCode).not.toHaveBeenCalled(); observer.onTokenStarted?.(); @@ -703,7 +1283,18 @@ describe('MicrosoftEntraIDAuthHandler', () => { }, ); - await handler.configureAuth(); + const { options } = await handler.configureAuth(); + expect(onCallbackTokenObserved).not.toHaveBeenCalled(); + getSessionFromVSCode.mockResolvedValueOnce({ ...session, accessToken: 'callback-token' }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).resolves.toEqual({ accessToken: 'callback-token' }); + expect(onCallbackTokenObserved.mock.calls).toEqual([ + [{ outcome: 'acquired', accessToken: 'callback-token', tenantId: 'tenant' }], + ]); expect(events).toEqual([ 'resolved:*.mongocluster.cosmos.azure.com', @@ -717,7 +1308,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { tenantId: 'tenant', }, ]); - expect(JSON.stringify(mockOutputChannel.info.mock.calls)).not.toContain('access-token'); + expect(JSON.stringify(mockOutputChannel.info.mock.calls)).not.toMatch(/access-token|callback-token/); }); it('passes the resolver details and reason to the observer', async () => { @@ -786,6 +1377,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { onTokenStarted: throwing, onTokenAcquired: throwing, onTokenFailed: throwing, + onCallbackTokenObserved: throwing, }; const credentials = buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'); const expected = await new MicrosoftEntraIDAuthHandler(credentials, { interactive }).configureAuth(); @@ -799,6 +1391,11 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(result.options.authMechanismProperties?.ALLOWED_HOSTS).toEqual( expected.options.authMechanismProperties?.ALLOWED_HOSTS, ); + const callback = result.options.authMechanismProperties!.OIDC_CALLBACK!; + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + await expect(callback(params)).resolves.toEqual({ accessToken: session.accessToken }); + getSessionFromVSCode.mockResolvedValueOnce(undefined); + await expect(callback(params)).rejects.toBeInstanceOf(EntraSignInRequiredError); const error = new Error('token request failed'); getSessionFromVSCode.mockRejectedValueOnce(error); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index d253a24d1..4fcb7fa8d 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -3,13 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// eslint-disable-next-line import/no-internal-modules -import { getSessionFromVSCode } from '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode'; +import { isUserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import { type OIDCCallbackParams, type OIDCResponse } from 'mongodb'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { meterSilentCatch } from '../../utils/accumulatingTelemetry'; import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { type CachedClusterCredentials } from '../CredentialCache'; import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; @@ -19,19 +19,46 @@ import { type AuthCallerPolicy, type AuthPhaseObserver, } from './authCallerPolicy'; -import { type AuthHandler, type AuthHandlerResponse } from './AuthHandler'; +import { type AuthHandler, type AuthHandlerResponse, type VerifiedEntraIdentity } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; +import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { buildOidcClientConfiguration, createOidcDestinationPolicy } from './oidcClientOptions'; +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; + +function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefined): EntraSignInEnvironment { + let current: EntraSignInEnvironment; + try { + current = readEntraSignInEnvironment(); + } catch { + throw new EntraSignInRequiredError('providerChanged'); + } + if ( + !expected || + current.providerId !== expected.providerId || + current.cloudName !== expected.cloudName || + current.authority !== expected.authority + ) { + throw new EntraSignInRequiredError('providerChanged'); + } + return expected; +} /** * Handler for Microsoft Entra ID authentication via OIDC. * - * An interactive policy may open sign-in (`createIfNone`). A non-interactive policy only looks up - * an existing session silently and reports a missing one as {@link AuthInputUnavailableError}. + * An interactive policy may open sign-in (`createIfNone`) only without a pin. Pinned lookups and + * diagnostics are silent; only diagnostics report a missing session as {@link AuthInputUnavailableError}. */ export class MicrosoftEntraIDAuthHandler implements AuthHandler { constructor( @@ -43,19 +70,37 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { notifyAuthPhaseObserver(this.policy.observer, notify); } + private getTokenLookupEpoch(): number | undefined { + try { + return this.policy.onTokenLookup ? this.policy.getTokenLookupEpoch?.() : undefined; + } catch { + meterSilentCatch('MicrosoftEntraIDAuthHandler_getTokenLookupEpoch'); + // Telemetry eligibility must not affect authentication. + return undefined; + } + } + public async configureAuth( timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + acquireRecoverySession?: (request: Parameters[0]) => ReturnType, ): Promise { const authCorrelationId = randomUUID(); const { connectionString, clusterId } = this.clusterCredentials; - const tenantId = this.clusterCredentials.entraIdConfig?.tenantId; + const pin = this.policy.pinnedEntraIdentity; + const tenantId = pin ? pin.tenantId : this.clusterCredentials.entraIdConfig?.tenantId; const decision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(decision, authCorrelationId, traceContext); if (!decision.allowed) { throw new EntraDestinationRejectedError(decision); } const policy = createOidcDestinationPolicy(connectionString, getEntraCustomHostnameSuffix); + let environmentBeforeResolution: EntraSignInEnvironment | undefined; + try { + environmentBeforeResolution = readEntraSignInEnvironment(); + } catch { + // Let resource resolution report invalid cloud configuration with its existing diagnostics. + } let resolved: Awaited>; try { resolved = await resolveInteractiveTokenResource(connectionString); @@ -85,20 +130,33 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { // Get Microsoft Entra ID token. Only an interactive caller may open sign-in; a non-interactive // caller looks up an existing session silently and never forces a new one. - const interactive = this.policy.interactive; + const interactive = this.policy.interactive && !pin; let session: vscode.AuthenticationSession | undefined; + let signInEnvironment: EntraSignInEnvironment; + const resource = resolved.scope; this.notify((observer) => observer.onTokenStarted?.()); try { - session = await traceAuthOperation( + ({ session, signInEnvironment } = await traceAuthOperation( 'interactiveEntra.getSession', () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode( - [resolved.scope], - tenantId, - interactive ? { createIfNone: true } : { silent: true }, - ), - ), + withTokenAcquisitionTiming(timings, async () => { + const signInEnvironment = assertEntraSignInEnvironment(environmentBeforeResolution); + if (pin && pin.providerId !== signInEnvironment.providerId) { + throw new EntraSignInRequiredError('providerChanged'); + } + try { + const session = await (acquireRecoverySession ?? getEntraSession)({ + providerId: pin?.providerId ?? signInEnvironment.providerId, + resource, + tenantId, + account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, + mode: acquireRecoverySession ? 'forceNew' : interactive ? 'interactive' : 'silent', + }); + return { session, signInEnvironment }; + } finally { + assertEntraSignInEnvironment(signInEnvironment); + } + }), { tenantSpecified: !!tenantId, ...(interactive ? { createIfNone: true } : { silent: true }), @@ -107,7 +165,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { }, authCorrelationId, traceContext, - ); + )); if (!session) { traceAuthFlow( @@ -116,22 +174,32 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { authCorrelationId, traceContext, ); + if (pin) { + throw new EntraSignInRequiredError('noSession'); + } if (!interactive) { throw new AuthInputUnavailableError('entraSession'); } throw new Error(l10n.t('Failed to obtain Entra ID token.')); } + if (pin && !acquireRecoverySession && session.account.id !== pin.accountId) { + throw new EntraIdentityMismatchError(); + } } catch (error) { - // A silent lookup without a session is not a token failure: recording it would change how - // the next real connect's error is explained. - if (!(error instanceof AuthInputUnavailableError)) { + // Missing input or configuration drift must not alter the next connect's failure context. + if ( + !(error instanceof AuthInputUnavailableError) && + !(error instanceof EntraSignInRequiredError) && + !(error instanceof EntraIdentityMismatchError) + ) { if (traceContext?.startupProperties) { traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; } + const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; recordEntraTokenFailure(clusterId, { cloudCategory: resolved.cloudCategory, authMethod: 'interactive', - ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, + ruleId: classifyEntraError(message)?.ruleId, }); } this.notify((observer) => observer.onTokenFailed?.(error)); @@ -140,6 +208,16 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { policy.assertAllowed(); clearEntraTokenFailure(clusterId); + const { providerId } = signInEnvironment; + const { id: accountId, label: accountLabel } = session.account; + const verifiedIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId, + accountId, + accountLabel, + tenantId, + }; + const account: vscode.AuthenticationSessionAccountInformation = { id: accountId, label: accountLabel }; const acquiredSession = session; this.notify((observer) => observer.onTokenAcquired?.({ @@ -151,15 +229,130 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { }), ); + let invocation = 0; const configuration = buildOidcClientConfiguration({ connectionString, policy, - oidcCallback: (_params: OIDCCallbackParams): Promise => - Promise.resolve({ - accessToken: session.accessToken, - expiresInSeconds: 0, - }), + callbackAuthMethod: AuthMethodId.MicrosoftEntraID, + oidcCallback: async (_params: OIDCCallbackParams): Promise => { + const currentInvocation = ++invocation; + let returned = false; + try { + assertEntraSignInEnvironment(signInEnvironment); + let renewed: vscode.AuthenticationSession | undefined; + try { + renewed = await getEntraSession({ providerId, resource, tenantId, account, mode: 'silent' }); + } finally { + // Drift takes precedence even if the lookup rejects with an error from the new provider. + assertEntraSignInEnvironment(signInEnvironment); + } + if (!renewed) { + throw new EntraSignInRequiredError('noSession'); + } + if (renewed.account.id !== accountId) { + throw new EntraIdentityMismatchError(); + } + const { accessToken } = renewed; + const { expSec } = readJwtTimes(accessToken); + returned = true; + return expSec === undefined + ? { accessToken } + : { accessToken, expiresInSeconds: Math.max(0, Math.floor(expSec - Date.now() / 1000)) }; + } catch (error) { + if ( + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof EntraDestinationRejectedError + ) { + throw error; + } + recordEntraTokenFailure(clusterId, { + cloudCategory: resolved.cloudCategory, + authMethod: 'interactive', + ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, + }); + throw error; + } finally { + traceAuthFlow( + 'interactiveEntra.oidcCallback', + { + invocation: currentInvocation, + outcome: returned ? 'returned' : 'threw', + }, + authCorrelationId, + traceContext, + ); + } + }, }); + const properties = configuration.options.authMechanismProperties; + const callback = properties?.OIDC_CALLBACK; + if ((this.policy.onTokenLookup || this.policy.observer?.onCallbackTokenObserved) && properties && callback) { + properties.OIDC_CALLBACK = async (params): Promise => { + const lookupEpoch = this.getTokenLookupEpoch(); + const signal = params.timeoutContext; + const notifyLookup = (observation: EntraTokenLookupObservation): void => { + if ( + lookupEpoch !== undefined && + (observation.outcome === 'timedOut' || !signal?.aborted) && + this.getTokenLookupEpoch() === lookupEpoch + ) { + try { + this.policy.onTokenLookup?.(observation); + } catch { + meterSilentCatch('MicrosoftEntraIDAuthHandler_onTokenLookup'); + // Observers never change the auth flow. + } + } + }; + const onAbort = (): void => notifyLookup({ outcome: 'timedOut' }); + if (lookupEpoch !== undefined && signal && !signal.aborted) { + signal.addEventListener('abort', onAbort, { once: true }); + } + try { + // Report acquisition only after the configured callback re-checks destination trust. + const response = await callback(params); + if (lookupEpoch !== undefined) { + const lifetimeSeconds = jwtLifetimeSeconds(readJwtTimes(response.accessToken)); + notifyLookup({ + outcome: 'returned', + ...(lifetimeSeconds !== undefined ? { lifetimeSeconds } : {}), + }); + } + this.notify((observer) => + observer.onCallbackTokenObserved?.({ + outcome: 'acquired', + accessToken: response.accessToken, + tenantId, + }), + ); + return response; + } catch (error) { + if ( + !isUserCancelledError(error) && + !(error instanceof TokenCallbackError && isUserCancelledError(error.cause)) + ) { + let outcome: EntraTokenLookupObservation['outcome'] = 'failed'; + if (error instanceof EntraSignInRequiredError) { + outcome = error.reason; + } else if (error instanceof EntraIdentityMismatchError) { + outcome = 'identityMismatch'; + } + notifyLookup({ outcome }); + } + if ( + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof TokenCallbackError + ) { + this.notify((observer) => observer.onCallbackTokenObserved?.({ outcome: 'failed', error })); + } + throw error; + } finally { + signal?.removeEventListener('abort', onAbort); + } + }; + } if (configuration.ignoredTlsBypass || this.clusterCredentials.emulatorConfiguration?.disableEmulatorSecurity) { ext.outputChannel.info( l10n.t('[Auth] TLS validation bypass parameters are ignored for Microsoft Entra ID connections.'), @@ -175,6 +368,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { return { connectionString: configuration.connectionString, options: configuration.options, + verifiedIdentity, }; } } diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts new file mode 100644 index 000000000..257b6d25f --- /dev/null +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -0,0 +1,307 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { isUserCancelledError, UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { traceAuthFlow, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; +import { ClustersClient } from '../ClustersClient'; +import { + getWorkerAuthReason, + type MainToWorkerMessage, + type WorkerAuthReason, + type WorkerToMainMessage, +} from '../playground/workerTypes'; +import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; +import { type VerifiedEntraIdentity } from './AuthHandler'; +import { AuthMethodId } from './AuthMethodId'; +import { + resolveInteractiveTokenResource, + resolveManagedIdentityTokenResource, + TokenResourceResolutionError, + type ResolvedTokenResource, +} from './documentdbTokenResource'; +import { evaluateEntraDestinationFromSettings } from './entraDestinationSettings'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; +import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; +import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; +import { EntraDestinationRejectedError } from './oidcAllowedHosts'; +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { emitTokenRenewal, type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; + +export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { + return a.providerId === b.providerId && a.accountId === b.accountId && a.tenantId === b.tenantId; +} + +export function createWorkerAuthError(reason: WorkerAuthReason, method?: AuthMethodId): Error { + switch (reason) { + case 'signInRequired': + return new EntraSignInRequiredError('noSession'); + case 'identityMismatch': + return new EntraIdentityMismatchError(); + case 'destinationRejected': + return new EntraDestinationRejectedError({ hostCount: 0 }); + case 'refreshFailed': + return new TokenCallbackError(undefined, method === AuthMethodId.ManagedIdentity ? method : undefined); + } +} + +/** Host-only token relay for a single worker. The worker cannot select its own identity or destination. */ +export class WorkerTokenRelay { + private resource: ResolvedTokenResource | undefined; + private environment: EntraSignInEnvironment | undefined; + private pending: Promise = Promise.resolve(); + + constructor( + private readonly clusterId: string, + private readonly init: Extract, + readonly epoch: number, + private readonly correlationId: string, + private pin: VerifiedEntraIdentity | undefined, + private readonly onIdentity?: (identity: VerifiedEntraIdentity) => void, + ) {} + + async relay( + { requestId, driverAbortFlag }: Extract, + postResponse: (response: MainToWorkerMessage) => void, + isCurrentWorker: () => boolean, + timings?: ConnectionStartupTimings, + trace?: AuthTraceContext, + postStartup = false, + epoch = this.epoch, + ): Promise { + const isCurrentEpoch = (): boolean => + !ClustersClient.getLatchReason(this.clusterId) && ClustersClient.getEpoch(this.clusterId) === epoch; + const canReply = (): boolean => { + if (!isCurrentWorker()) { + return false; + } + if (!isCurrentEpoch()) { + // The driver is still waiting. Cancel via the supervisor, not an authentication error. + throw new UserCancelledError('workerTokenRelay'); + } + return true; + }; + const activeTrace = (): AuthTraceContext | undefined => + isCurrentWorker() && isCurrentEpoch() ? trace : undefined; + const { connectionString, authMechanism, tenantId, managedIdentityClientId, persistent } = this.init; + const managed = authMechanism === 'ManagedIdentity'; + const abortFlag = + driverAbortFlag instanceof SharedArrayBuffer && driverAbortFlag.byteLength === Int32Array.BYTES_PER_ELEMENT + ? new Int32Array(driverAbortFlag) + : undefined; + const shouldObserve = (): boolean => postStartup && authMechanism === 'MicrosoftEntraID'; + const surface = persistent ? 'shell' : 'playground'; + const assertDestination = (): void => { + const decision = evaluateEntraDestinationFromSettings(connectionString); + traceEntraDestination(decision, requestId, activeTrace()); + if (!decision.allowed) { + throw new EntraDestinationRejectedError(decision); + } + }; + const run = async (): Promise => { + if (!canReply()) { + return; + } + let mode: 'managedIdentity' | 'silent' | 'interactive' | undefined; + let acquiring = false; + try { + if (!managed && authMechanism !== 'MicrosoftEntraID') { + throw new Error('Token request from a non-OIDC worker'); + } + assertDestination(); + const pin = this.pin; + const readEnvironment = (): EntraSignInEnvironment => { + try { + return readEntraSignInEnvironment(); + } catch { + throw new EntraSignInRequiredError('providerChanged'); + } + }; + const assertEnvironment = (expected: EntraSignInEnvironment): string => { + const now = readEnvironment(); + if ( + (pin && (pin.providerId !== now.providerId || pin.tenantId !== tenantId)) || + expected.providerId !== now.providerId || + expected.cloudName !== now.cloudName || + expected.authority !== now.authority + ) { + throw new EntraSignInRequiredError('providerChanged'); + } + return expected.providerId; + }; + mode = managed ? 'managedIdentity' : pin ? 'silent' : 'interactive'; + let resolved = this.resource; + let environment = this.environment; + if (!resolved) { + const resolutionEnvironment = managed ? undefined : readEnvironment(); + if (resolutionEnvironment) { + assertEnvironment(resolutionEnvironment); + } + resolved = managed + ? await resolveManagedIdentityTokenResource(connectionString) + : await resolveInteractiveTokenResource(connectionString); + if (!canReply()) { + return; + } + if (resolutionEnvironment) { + assertEnvironment(resolutionEnvironment); + } + this.resource = resolved; + this.environment = resolutionEnvironment; + environment = resolutionEnvironment; + } else if (!managed) { + if (!environment) { + throw new EntraSignInRequiredError('providerChanged'); + } + assertEnvironment(environment); + } + if (!canReply()) { + return; + } + traceAuthFlow('entraCloud.resolved', resolved.details, requestId, activeTrace()); + let identity: VerifiedEntraIdentity | undefined; + let accessToken: string; + acquiring = true; + if (managed) { + const { getManagedIdentityAccessToken } = await import('./managedIdentityTokenProvider'); + if (!canReply()) { + return; + } + assertDestination(); + accessToken = ( + await withTokenAcquisitionTiming(timings, () => + getManagedIdentityAccessToken( + [resolved.scope], + managedIdentityClientId, + tenantId, + this.correlationId, + activeTrace(), + ), + ) + ).accessToken; + } else { + assertDestination(); + if (!environment) { + throw new EntraSignInRequiredError('providerChanged'); + } + const providerId = assertEnvironment(environment); + let session: Awaited>; + try { + session = await withTokenAcquisitionTiming(timings, () => + getEntraSession({ + providerId, + resource: resolved.scope, + tenantId, + account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, + mode: pin ? 'silent' : 'interactive', + }), + ); + } finally { + if (canReply()) { + assertEnvironment(environment); + } + } + if (!canReply()) { + return; + } + if (!session && pin) { + throw new EntraSignInRequiredError('noSession'); + } + if (!session?.account.id) { + throw new TokenCallbackError(undefined); + } + if (pin && session.account.id !== pin.accountId) { + throw new EntraIdentityMismatchError(); + } + identity = { + kind: 'entra', + providerId, + tenantId, + accountId: session.account.id, + accountLabel: session.account.label, + }; + accessToken = session.accessToken; + } + if (!canReply()) { + return; + } + assertDestination(); + if (identity) { + // The first interactive lookup may have overlapped a verified tree connection. + const verified = pin ? undefined : ClustersClient.getLastVerifiedIdentity(this.clusterId); + if (verified?.kind === 'entra' && !sameEntraIdentity(identity, verified)) { + throw new EntraIdentityMismatchError(); + } + this.onIdentity?.(identity); + this.pin = identity; + } + clearEntraTokenFailure(this.clusterId); + traceAuthFlow('workerTokenRelay.completed', { mode, outcome: 'returned' }, requestId, activeTrace()); + postResponse({ type: 'tokenResponse', requestId, accessToken }); + if (shouldObserve()) { + if (abortFlag && Atomics.load(abortFlag, 0) !== 0) { + emitTokenRenewal(surface, { outcome: 'timedOut' }); + } else { + emitTokenRenewal(surface, { + outcome: 'returned', + lifetimeSeconds: jwtLifetimeSeconds(readJwtTimes(accessToken)), + }); + } + } + } catch (error) { + if (!canReply()) { + return; + } + const reason = getWorkerAuthReason(error) ?? 'refreshFailed'; + if (error instanceof TokenResourceResolutionError) { + traceAuthFlow('entraCloud.unresolved', error.details, requestId, activeTrace()); + } + if (reason === 'refreshFailed' && acquiring && this.resource) { + if (trace?.startupProperties) { + trace.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; + } + recordEntraTokenFailure(this.clusterId, { + cloudCategory: this.resource.cloudCategory, + authMethod: managed ? 'managedIdentity' : 'interactive', + }); + } + traceAuthFlow( + 'workerTokenRelay.completed', + { mode: mode ?? 'none', outcome: reason }, + requestId, + activeTrace(), + ); + postResponse({ + type: 'tokenError', + requestId, + error: createWorkerAuthError(reason, authMechanism as AuthMethodId).message, + reason, + ...(reason === 'destinationRejected' + ? { errorName: 'EntraDestinationRejectedError' as const } + : {}), + }); + if (shouldObserve() && !isUserCancelledError(error)) { + let outcome: EntraTokenLookupObservation['outcome'] = 'failed'; + if (abortFlag && Atomics.load(abortFlag, 0) !== 0) { + outcome = 'timedOut'; + } else if (reason === 'signInRequired') { + outcome = error instanceof EntraSignInRequiredError ? error.reason : 'noSession'; + } else if (reason === 'identityMismatch') { + outcome = 'identityMismatch'; + } + emitTokenRenewal(surface, { outcome }); + } + } + }; + + // Serializing relays prevents two first requests from prompting before either has pinned an account. + const next = this.pending.then(run); + this.pending = next.catch(() => undefined); + await next; + } +} diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index 3aa76ad3e..a28b149f4 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -3,6 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { type VerifiedEntraIdentity } from './AuthHandler'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; + /** * Host-only callbacks that report the authentication phases in the order they really happen. * @@ -27,15 +30,24 @@ export interface AuthPhaseObserver { readonly tenantId?: string; }): void; onTokenFailed?(error: unknown): void; + /** Host-only: summarize callback tokens immediately; never store or log them. */ + onCallbackTokenObserved?( + observation: + | { readonly outcome: 'acquired'; readonly accessToken: string; readonly tenantId?: string } + | { readonly outcome: 'failed'; readonly error: unknown }, + ): void; } /** - * How the caller wants authentication to behave. Ordinary connects are interactive; connection - * diagnostics are not, and never open sign-in UI. + * Whether the caller can open sign-in UI and, for Entra reconnect, which identity must be used. */ export interface AuthCallerPolicy { readonly interactive: boolean; + readonly pinnedEntraIdentity?: VerifiedEntraIdentity; readonly observer?: AuthPhaseObserver; + /** Entra only. Returns the current client epoch, or undefined if renewal telemetry is not eligible. */ + readonly getTokenLookupEpoch?: () => number | undefined; + readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; } /** diff --git a/src/documentdb/auth/authConnectionTarget.test.ts b/src/documentdb/auth/authConnectionTarget.test.ts index 3ef6eadae..74ee620ac 100644 --- a/src/documentdb/auth/authConnectionTarget.test.ts +++ b/src/documentdb/auth/authConnectionTarget.test.ts @@ -7,11 +7,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import type * as documentdbTokenResource from './documentdbTokenResource'; -const getSessionFromVSCode = vi.hoisted(() => vi.fn()); +const getSession = vi.hoisted(() => vi.fn()); const getManagedIdentityAccessToken = vi.hoisted(() => vi.fn()); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode, +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession }, })); vi.mock('./managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken })); @@ -242,7 +243,7 @@ describe('buildAuthConnectionTarget', () => { ); } - expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(getSession).not.toHaveBeenCalled(); expect(getManagedIdentityAccessToken).not.toHaveBeenCalled(); expect(resolveInteractiveTokenResource).not.toHaveBeenCalled(); expect(resolveManagedIdentityTokenResource).not.toHaveBeenCalled(); diff --git a/src/documentdb/auth/documentdbTokenResource.test.ts b/src/documentdb/auth/documentdbTokenResource.test.ts index 31eafd01f..195eecc5d 100644 --- a/src/documentdb/auth/documentdbTokenResource.test.ts +++ b/src/documentdb/auth/documentdbTokenResource.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ // eslint-disable-next-line import/no-internal-modules -import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth/out/src/utils/configuredAzureEnv'; +import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { diff --git a/src/documentdb/auth/driverOidcContract.test.ts b/src/documentdb/auth/driverOidcContract.test.ts new file mode 100644 index 000000000..0f864bcee --- /dev/null +++ b/src/documentdb/auth/driverOidcContract.test.ts @@ -0,0 +1,165 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + BSON, + MongoNetworkError, + MongoServerError, + type Binary, + type MongoCredentials, + type MongoDBNamespace, + type OIDCCallbackFunction, + type OIDCResponse, +} from 'mongodb'; +// eslint-disable-next-line import/no-internal-modules -- Exercise the installed driver's real OIDC workflow. +import { AutomatedCallbackWorkflow as DriverWorkflow } from 'mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js'; +// eslint-disable-next-line import/no-internal-modules -- The workflow needs the driver's real token cache. +import { TokenCache as DriverTokenCache } from 'mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js'; +import { describe, expect, it, vi } from 'vitest'; +import { classifyConnectionFailure } from '../connectionFailures'; +import { AuthMethodId } from './AuthMethod'; + +// The driver's public declarations omit these internals. Type only the surface the suite uses. +interface SaslStart { + saslStart: number; + mechanism: string; + payload: Binary; +} + +interface FakeConnection { + command(namespace: MongoDBNamespace, command: SaslStart, options: undefined): Promise<{ ok: number }>; +} + +interface OidcTokenCache { + put(response: OIDCResponse): void; +} + +type WorkflowCredentials = Pick; + +interface OidcWorkflow { + fetchAccessToken(credentials: WorkflowCredentials): Promise; + speculativeAuth( + connection: FakeConnection, + credentials: WorkflowCredentials, + ): Promise<{ speculativeAuthenticate?: SaslStart & { db: string } }>; + execute(connection: FakeConnection, credentials: WorkflowCredentials): Promise; +} + +const TokenCache = DriverTokenCache as new () => OidcTokenCache; +const AutomatedCallbackWorkflow = DriverWorkflow as new ( + cache: OidcTokenCache, + callback: OIDCCallbackFunction, +) => OidcWorkflow; + +const credentials: WorkflowCredentials = { + source: '$external', + username: 'dummy-user', + mechanismProperties: {}, +}; + +describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { + it('rethrows the identical callback error on the next fetch without calling the callback again', async () => { + const error = new Error('dummy callback failure'); + const callback = vi.fn().mockRejectedValueOnce(error); + const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); + + await expect(workflow.fetchAccessToken(credentials)).rejects.toBe(error); + await expect(workflow.fetchAccessToken(credentials)).rejects.toBe(error); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('offers the cached token in speculative authentication after its advertised lifetime', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(1_000); + const cache = new TokenCache(); + cache.put({ accessToken: 'dummy-cached-token', expiresInSeconds: 1 }); + const callback = vi.fn(); + const workflow = new AutomatedCallbackWorkflow(cache, callback); + const command = vi.fn(); + vi.setSystemTime(3_000); + + const { speculativeAuthenticate } = await workflow.speculativeAuth({ command }, credentials); + + expect(speculativeAuthenticate).toMatchObject({ + db: '$external', + saslStart: 1, + mechanism: 'MONGODB-OIDC', + }); + expect(speculativeAuthenticate && BSON.deserialize(speculativeAuthenticate.payload.value())).toEqual({ + jwt: 'dummy-cached-token', + }); + expect(callback).not.toHaveBeenCalled(); + expect(command).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it('calls the callback again on code 18 and retries authentication with the new token', async () => { + const callback = vi + .fn() + .mockResolvedValueOnce({ accessToken: 'dummy-cached-token' }) + .mockResolvedValueOnce({ accessToken: 'dummy-renewed-token' }); + const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); + await workflow.execute( + { command: vi.fn().mockResolvedValue({ ok: 1 }) }, + credentials, + ); + expect(callback).toHaveBeenCalledTimes(1); + + const command = vi + .fn() + .mockRejectedValueOnce(new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' })) + .mockResolvedValue({ ok: 1 }); + await workflow.execute({ command }, credentials); + + expect(callback).toHaveBeenCalledTimes(2); + expect(command.mock.calls.map(([, request]) => BSON.deserialize(request.payload.value()))).toEqual([ + { jwt: 'dummy-cached-token' }, + { jwt: 'dummy-renewed-token' }, + ]); + }); + + it('propagates the final code 18 unchanged when the callback-supplied token is also rejected', async (): Promise => { + const cache = new TokenCache(); + cache.put({ accessToken: 'dummy-cached-token' }); + const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-callback-token' }); + const workflow = new AutomatedCallbackWorkflow(cache, callback); + const finalError = new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' }); + const command = vi + .fn() + .mockRejectedValueOnce(new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' })) + .mockRejectedValueOnce(finalError); + + await expect(workflow.execute({ command }, credentials)).rejects.toBe(finalError); + expect(classifyConnectionFailure(finalError, AuthMethodId.MicrosoftEntraID)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(callback).toHaveBeenCalledTimes(1); + expect(command.mock.calls.map(([, request]) => BSON.deserialize(request.payload.value()))).toEqual([ + { jwt: 'dummy-cached-token' }, + { jwt: 'dummy-callback-token' }, + ]); + }); + + it('propagates a network error without calling the callback again or retrying the command', async () => { + const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-cached-token' }); + const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); + await workflow.execute( + { command: vi.fn().mockResolvedValue({ ok: 1 }) }, + credentials, + ); + expect(callback).toHaveBeenCalledTimes(1); + + const error = new MongoNetworkError('dummy network failure'); + const command = vi.fn().mockRejectedValueOnce(error).mockResolvedValue({ ok: 1 }); + + await expect(workflow.execute({ command }, credentials)).rejects.toBe(error); + expect(callback).toHaveBeenCalledTimes(1); + expect(command).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts new file mode 100644 index 000000000..4b099fed6 --- /dev/null +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.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 { MongoNetworkError, MongoServerSelectionError, type TopologyDescription } from 'mongodb'; +import { describe, expect, it } from 'vitest'; +import { EntraIdentityMismatchError, EntraSignInRequiredError, TokenCallbackError } from './entraCallbackErrors'; +import { EntraSignInRequiredErrorExplainer } from './EntraSignInRequiredErrorExplainer'; + +describe('EntraSignInRequiredErrorExplainer', () => { + const explainer = new EntraSignInRequiredErrorExplainer(); + const clusterId = 'private-cluster'; + + const providerChangedMessage = + 'The Azure cloud or sign-in provider changed after this connection was established. Restore "microsoft-sovereign-cloud.environment" to the setting used then, and try again. If it used the Azure public cloud, reset the setting.'; + const signInRequiredMessage = 'Microsoft sign-in is required for this connection. Sign in again to continue.'; + + it('explains a provider change two causes deep without changing the errors', async () => { + const signIn = Object.freeze(new EntraSignInRequiredError('providerChanged')); + const wrapper = Object.freeze(new TokenCallbackError(signIn)); + const error = Object.freeze(new Error('private-detail', { cause: wrapper })); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe(providerChangedMessage); + expect(error.cause).toBe(wrapper); + expect(wrapper.cause).toBe(signIn); + }); + + it('does not claim expiry or a provider change for a missing session', async () => { + const error = new TokenCallbackError(new EntraSignInRequiredError('noSession')); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe(signInRequiredMessage); + }); + + it('uses neutral wording when a reconstructed sign-in error carries no reason', async () => { + const error = new Error('private-account'); + error.name = 'EntraSignInRequiredError'; + + await expect(explainer.explain({ clusterId, error })).resolves.toBe(signInRequiredMessage); + }); + + it('finds a provider change in the driver’s per-server errors', async () => { + const signIn = new EntraSignInRequiredError('providerChanged'); + const servers = new Map([ + ['private-host:27017', { error: new MongoNetworkError('private-detail', { cause: signIn }) }], + ]); + const error = new MongoServerSelectionError('selection failed', { servers } as unknown as TopologyDescription); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe(providerChangedMessage); + }); + + it('recognizes the bounded name on an Error reconstructed at a boundary', async () => { + const error = new Error('private-account'); + error.name = 'EntraIdentityMismatchError'; + + await expect(explainer.explain({ clusterId, error })).resolves.toBe( + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', + ); + }); + + it('finds a typed cause in the driver’s per-server errors', async () => { + const mismatch = new EntraIdentityMismatchError(); + const servers = new Map([ + ['private-host:27017', { error: new MongoNetworkError('private-detail', { cause: mismatch }) }], + ['unrelated-host:27017', { error: new MongoNetworkError('unrelated') }], + ]); + const error = new MongoServerSelectionError('selection failed', { servers } as unknown as TopologyDescription); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe( + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', + ); + }); + + it('declines strings, message-only matches, and unrelated cyclic callback errors', async () => { + const unrelated = new Error('EntraSignInRequiredError'); + const wrapper = new TokenCallbackError(unrelated); + unrelated.cause = wrapper; + + await expect(explainer.explain({ clusterId, error: 'EntraIdentityMismatchError' })).resolves.toBeUndefined(); + await expect(explainer.explain({ clusterId, error: wrapper })).resolves.toBeUndefined(); + }); +}); diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts new file mode 100644 index 000000000..e7947bd46 --- /dev/null +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { MongoServerSelectionError } from 'mongodb'; +import { type ErrorExplanationProvider, type ErrorExplanationRequest } from '../../../services/errorExplanationService'; + +export class EntraSignInRequiredErrorExplainer implements ErrorExplanationProvider { + public readonly id = 'entraSignInRequired'; + + public async explain({ error }: ErrorExplanationRequest): Promise { + const pending: unknown[] = [error]; + const visited = new Set(); + while (pending.length > 0) { + const current = pending.pop(); + if (!(current instanceof Error) || visited.has(current)) { + continue; + } + visited.add(current); + + switch (current.name) { + case 'EntraSignInRequiredError': + // A reconstructed error may carry only the name; without a known reason, do not claim a cause. + if ('reason' in current && current.reason === 'providerChanged') { + return l10n.t( + 'The Azure cloud or sign-in provider changed after this connection was established. Restore "microsoft-sovereign-cloud.environment" to the setting used then, and try again. If it used the Azure public cloud, reset the setting.', + ); + } + return l10n.t('Microsoft sign-in is required for this connection. Sign in again to continue.'); + case 'EntraIdentityMismatchError': + return l10n.t( + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', + ); + } + + if (current instanceof MongoServerSelectionError) { + const servers = current.reason?.servers; + if (servers instanceof Map) { + for (const description of servers.values()) { + pending.push(description?.error); + } + } + } + pending.push(current.cause); + } + return undefined; + } +} diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts new file mode 100644 index 000000000..9bbf609ba --- /dev/null +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { AuthMethodId } from '../AuthMethodId'; +import { ManagedIdentityGuidanceError } from '../managedIdentityErrors'; + +export class EntraSignInRequiredError extends Error { + constructor(public readonly reason: 'noSession' | 'providerChanged') { + super(l10n.t('Sign in again to continue using Microsoft Entra ID.')); + this.name = 'EntraSignInRequiredError'; + } +} + +export class EntraIdentityMismatchError extends Error { + constructor() { + super(l10n.t('Visual Studio Code returned a different Microsoft account for this connection.')); + this.name = 'EntraIdentityMismatchError'; + } +} + +type TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID | AuthMethodId.ManagedIdentity; + +export class TokenCallbackError extends Error { + constructor( + cause: unknown, + public readonly authMethod: TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID, + ) { + const message = + authMethod === AuthMethodId.ManagedIdentity && cause instanceof ManagedIdentityGuidanceError + ? cause.message + : l10n.t('Failed to obtain a Microsoft Entra ID token.'); + super(message, { cause }); + this.name = 'TokenCallbackError'; + } +} diff --git a/src/documentdb/auth/entraSession.test.ts b/src/documentdb/auth/entraSession.test.ts new file mode 100644 index 000000000..8456a447d --- /dev/null +++ b/src/documentdb/auth/entraSession.test.ts @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { getEntraSession } from './entraSession'; + +const { getSession } = vi.hoisted(() => ({ getSession: vi.fn() })); +vi.mock('vscode', () => ({ authentication: { getSession } })); + +it.each([ + ['interactive', { createIfNone: true }], + ['silent', { silent: true }], + ['forceNew', { forceNewSession: true }], +] as const)('uses the explicit provider, scopes and account in %s mode', async (mode, expectedOptions) => { + const account = { id: 'account-id', label: 'account-label' }; + const session = { id: 'session-id', accessToken: 'dummy', account, scopes: [] }; + getSession.mockResolvedValueOnce(session); + await expect( + getEntraSession({ + providerId: 'pinned-provider', + resource: mode === 'forceNew' ? 'https://resource.example/.default' : 'https://resource.example', + tenantId: 'tenant-id', + mode, + account, + }), + ).resolves.toBe(session); + expect(getSession).toHaveBeenLastCalledWith( + 'pinned-provider', + ['https://resource.example/.default', 'VSCODE_TENANT:tenant-id'], + { ...expectedOptions, account }, + ); +}); diff --git a/src/documentdb/auth/entraSession.ts b/src/documentdb/auth/entraSession.ts new file mode 100644 index 000000000..617a1cc8e --- /dev/null +++ b/src/documentdb/auth/entraSession.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getConfiguredAuthProviderId, getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; +import * as vscode from 'vscode'; +import { toEntraScope } from './entraScopes'; + +export interface EntraSignInEnvironment { + readonly providerId: string; + readonly cloudName: string; + readonly authority?: string; +} + +export function readEntraSignInEnvironment(): EntraSignInEnvironment { + const providerId = getConfiguredAuthProviderId(); + const { name: cloudName, activeDirectoryEndpointUrl: authority } = getConfiguredAzureEnv(); + return { providerId, cloudName, authority }; +} + +interface EntraSessionRequest { + providerId: string; + resource: string; + tenantId?: string; + account?: vscode.AuthenticationSessionAccountInformation; + mode: 'interactive' | 'silent' | 'forceNew'; +} + +export async function getEntraSession({ + providerId, + resource, + tenantId, + account, + mode, +}: EntraSessionRequest): Promise { + const scopes = [resource.endsWith('.default') ? resource : toEntraScope(resource)]; + if (tenantId) { + scopes.push(`VSCODE_TENANT:${tenantId}`); + } + const options = account ? { account } : {}; + switch (mode) { + case 'interactive': + return await vscode.authentication.getSession(providerId, scopes, { ...options, createIfNone: true }); + case 'silent': + return await vscode.authentication.getSession(providerId, scopes, { ...options, silent: true }); + case 'forceNew': + return await vscode.authentication.getSession(providerId, scopes, { ...options, forceNewSession: true }); + } +} diff --git a/src/documentdb/auth/managedIdentityErrors.ts b/src/documentdb/auth/managedIdentityErrors.ts index ce799e620..699eb8c77 100644 --- a/src/documentdb/auth/managedIdentityErrors.ts +++ b/src/documentdb/auth/managedIdentityErrors.ts @@ -5,6 +5,9 @@ import * as l10n from '@vscode/l10n'; +/** Marks localized recovery guidance, not an SDK error message. */ +export class ManagedIdentityGuidanceError extends Error {} + /** * Coarse classification of a managed identity token failure. * diff --git a/src/documentdb/auth/managedIdentityTenant.ts b/src/documentdb/auth/managedIdentityTenant.ts index 98ad06d2d..a1a0750e8 100644 --- a/src/documentdb/auth/managedIdentityTenant.ts +++ b/src/documentdb/auth/managedIdentityTenant.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; -import { describeManagedIdentityTenantMismatch } from './managedIdentityErrors'; +import { describeManagedIdentityTenantMismatch, ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { reportManagedIdentityFailureReason } from './managedIdentityTelemetry'; /** @@ -87,5 +87,5 @@ export function verifyManagedIdentityTenant( traceContext, ); reportManagedIdentityFailureReason('tenantMismatch', clientId, correlationId, traceContext); - throw new Error(describeManagedIdentityTenantMismatch(identityTenantId, clusterTenantId)); + throw new ManagedIdentityGuidanceError(describeManagedIdentityTenantMismatch(identityTenantId, clusterTenantId)); } diff --git a/src/documentdb/auth/managedIdentityTokenProvider.ts b/src/documentdb/auth/managedIdentityTokenProvider.ts index 908f1ddbc..f06b2b9cc 100644 --- a/src/documentdb/auth/managedIdentityTokenProvider.ts +++ b/src/documentdb/auth/managedIdentityTokenProvider.ts @@ -6,7 +6,11 @@ import { type TokenCredential } from '@azure/identity'; import { randomUUID } from 'crypto'; import { traceAuthFlow, traceAuthOperation, type AuthTraceContext } from '../../utils/authTrace'; -import { classifyManagedIdentityError, describeManagedIdentityError } from './managedIdentityErrors'; +import { + classifyManagedIdentityError, + describeManagedIdentityError, + ManagedIdentityGuidanceError, +} from './managedIdentityErrors'; import { reportManagedIdentityTokenFailure } from './managedIdentityTelemetry'; import { verifyManagedIdentityTenant } from './managedIdentityTenant'; @@ -50,14 +54,11 @@ export async function getManagedIdentityAccessToken( traceContext, ); } catch (error) { - traceAuthFlow( - 'managedIdentity.tokenFailure', - { reason: classifyManagedIdentityError(error) }, - tokenCorrelationId, - traceContext, - ); + const reason = classifyManagedIdentityError(error); + traceAuthFlow('managedIdentity.tokenFailure', { reason }, tokenCorrelationId, traceContext); reportManagedIdentityTokenFailure(error, clientId, tokenCorrelationId, traceContext); - throw new Error(describeManagedIdentityError(error, clientId)); + const message = describeManagedIdentityError(error, clientId); + throw reason === 'other' ? new Error(message) : new ManagedIdentityGuidanceError(message); } if (!token) { diff --git a/src/documentdb/auth/oidcClientOptions.test.ts b/src/documentdb/auth/oidcClientOptions.test.ts index 552f02746..da5736391 100644 --- a/src/documentdb/auth/oidcClientOptions.test.ts +++ b/src/documentdb/auth/oidcClientOptions.test.ts @@ -14,6 +14,10 @@ import { createOidcDestinationPolicy, } from './oidcClientOptions'; +vi.mock('vscode', () => { + throw new Error('Node workers must be able to load OIDC options without the VS Code host module.'); +}); + const host = 'cluster.mongocluster.cosmos.azure.com'; const connectionString = `mongodb://${host}/`; const patterns = ['*.mongocluster.cosmos.azure.com']; diff --git a/src/documentdb/auth/oidcClientOptions.ts b/src/documentdb/auth/oidcClientOptions.ts index 9cc953536..aa1a89d4e 100644 --- a/src/documentdb/auth/oidcClientOptions.ts +++ b/src/documentdb/auth/oidcClientOptions.ts @@ -6,10 +6,16 @@ import { type MongoClientOptions, type OIDCCallbackFunction, type OIDCResponse } from 'mongodb'; import { checkServerIdentity, type PeerCertificate } from 'tls'; import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { EntraDestinationRejectedError, evaluateEntraDestination, isEntraDestinationHostAllowed, + isEntraDestinationRejectedError, } from './oidcAllowedHosts'; const TLS_BYPASS_KEYS = new Set([ @@ -97,6 +103,7 @@ export function buildOidcClientConfiguration(input: { connectionString: string; policy: OidcDestinationPolicy; oidcCallback: OIDCCallbackFunction; + callbackAuthMethod?: TokenCallbackError['authMethod']; baseOptions?: MongoClientOptions; }): { connectionString: string; @@ -149,10 +156,23 @@ export function buildOidcClientConfiguration(input: { authMechanismProperties: { ALLOWED_HOSTS: [...input.policy.allowedHostPatterns], OIDC_CALLBACK: async (params): Promise => { - input.policy.assertAllowed(); - const response = await input.oidcCallback(params); - input.policy.assertAllowed(); - return response; + try { + input.policy.assertAllowed(); + const response = await input.oidcCallback(params); + input.policy.assertAllowed(); + return response; + } catch (error) { + if ( + input.callbackAuthMethod === undefined || + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof TokenCallbackError || + isEntraDestinationRejectedError(error) + ) { + throw error; + } + throw new TokenCallbackError(error, input.callbackAuthMethod); + } }, }, tls: true, diff --git a/src/documentdb/auth/sovereignAuth.integration.test.ts b/src/documentdb/auth/sovereignAuth.integration.test.ts index c0c9dab08..3e3405328 100644 --- a/src/documentdb/auth/sovereignAuth.integration.test.ts +++ b/src/documentdb/auth/sovereignAuth.integration.test.ts @@ -20,7 +20,7 @@ interface TokenWorker { } const workers = vi.hoisted((): TokenWorker[] => []); -const getSession = vi.hoisted(() => vi.fn()); +const getHandlerSession = vi.hoisted(() => vi.fn()); const getManagedToken = vi.hoisted(() => vi.fn()); const postedMessages = vi.hoisted((): MainToWorkerMessage[] => []); const events = vi.hoisted((): { eventName: string; telemetry: ITelemetryContext }[] => []); @@ -32,8 +32,9 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: getSession, +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: getHandlerSession }, })); vi.mock('./managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken: getManagedToken })); @@ -175,7 +176,10 @@ describe('sovereign authentication with real audience resolvers', () => { events.length = 0; selectedCloud = 'USGovernment'; resetEntraTokenFailuresForTests(); - getSession.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + getHandlerSession.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account-id', label: 'private-account' }, + }); getManagedToken.mockResolvedValue({ accessToken: 'private-token', expiresOnTimestamp: Date.now() + 3_600_000 }); const configuration = { get: vi.fn(), inspect: vi.fn(), has: vi.fn(), update: vi.fn() }; configuration.get.mockImplementation((key: string, defaultValue?: unknown): unknown => { @@ -201,7 +205,11 @@ describe('sovereign authentication with real audience resolvers', () => { const { options } = await new MicrosoftEntraIDAuthHandler( credentials(AuthMethodId.MicrosoftEntraID, cloud.suffix), ).configureAuth(undefined, { startupCorrelationId: 'startup-id', surface: 'extension', startupProperties }); - expect(getSession).toHaveBeenCalledExactlyOnceWith([cloud.scope], 'private-tenant', { createIfNone: true }); + expect(getHandlerSession).toHaveBeenCalledExactlyOnceWith( + cloud.setting === 'AzureCloud' ? 'microsoft' : 'microsoft-sovereign-cloud', + [cloud.scope, 'VSCODE_TENANT:private-tenant'], + { createIfNone: true }, + ); expect(options.authMechanismProperties?.ALLOWED_HOSTS).toEqual([`*.mongocluster.cosmos.azure.${cloud.suffix}`]); expect(startupProperties).toEqual({ entraDestinationClass: 'documentdbService', @@ -239,7 +247,7 @@ describe('sovereign authentication with real audience resolvers', () => { expect.any(String), undefined, ); - expect(getSession).not.toHaveBeenCalled(); + expect(getHandlerSession).not.toHaveBeenCalled(); }, ); @@ -290,8 +298,15 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'token-request', accessToken: 'private-token', }); - const provider = authMethod === AuthMethodId.ManagedIdentity ? getManagedToken : getSession; - expect(provider.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + if (authMethod === AuthMethodId.ManagedIdentity) { + expect(getManagedToken.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + } else { + expect(getHandlerSession).toHaveBeenCalledExactlyOnceWith( + 'microsoft-sovereign-cloud', + [clouds[0].scope, 'VSCODE_TENANT:private-tenant'], + { createIfNone: true }, + ); + } const startup = events.find((event) => event.eventName === 'worker.startup'); expect(startup?.telemetry.properties).toMatchObject({ surface, @@ -312,7 +327,20 @@ describe('sovereign authentication with real audience resolvers', () => { describe.each(workerSessions)('%s %s worker lifetime', (surface, authMethod) => { let manager: ShellSessionManager | PlaygroundEvaluator; const connection = { clusterId, clusterDisplayName: 'Test cluster', databaseName: 'test' }; - const provider = authMethod === AuthMethodId.ManagedIdentity ? getManagedToken : getSession; + const managed = authMethod === AuthMethodId.ManagedIdentity; + const provider = managed ? getManagedToken : getHandlerSession; + + function requestedScopes(): unknown[] { + return provider.mock.calls.map((args) => (managed ? args[0] : args[1])); + } + + function scopedTo(scope: string): string[] { + return managed ? [scope] : [scope, 'VSCODE_TENANT:private-tenant']; + } + + function newSurface(): ShellSessionManager | PlaygroundEvaluator { + return surface === 'shell' ? new ShellSessionManager(connection) : new PlaygroundEvaluator(); + } function storeCredentials(suffix: string): void { const stored = credentials(authMethod, suffix); @@ -346,7 +374,7 @@ describe('sovereign authentication with real audience resolvers', () => { beforeEach(() => { storeCredentials('us'); - manager = surface === 'shell' ? new ShellSessionManager(connection) : new PlaygroundEvaluator(); + manager = newSurface(); }); afterEach(() => manager.dispose()); @@ -362,12 +390,18 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'refresh-request', accessToken: 'private-token', }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([[clouds[0].scope], [clouds[0].scope]]); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope), scopedTo(clouds[0].scope)]); + if (!managed) { + expect(getHandlerSession.mock.calls[1]?.[2]).toEqual({ + silent: true, + account: { id: 'account-id', label: 'private-account' }, + }); + } }); - it('keeps the first audience after cloud configuration changes', async () => { + it('retains the audience and refuses Entra renewal after a cloud change', async () => { await initializeSession(); - if (authMethod === AuthMethodId.ManagedIdentity) { + if (managed) { customEndpoint = clouds[1].scope.replace('/.default', ''); } else { selectedCloud = 'ChinaCloud'; @@ -379,12 +413,23 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[0], 'refresh-request'); expect(workers).toHaveLength(1); - expect(postedMessages).toContainEqual({ - type: 'tokenResponse', - requestId: 'refresh-request', - accessToken: 'private-token', - }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([[clouds[0].scope], [clouds[0].scope]]); + if (managed) { + expect(postedMessages).toContainEqual({ + type: 'tokenResponse', + requestId: 'refresh-request', + accessToken: 'private-token', + }); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope), scopedTo(clouds[0].scope)]); + } else { + expect(postedMessages).toContainEqual( + expect.objectContaining({ + type: 'tokenError', + requestId: 'refresh-request', + reason: 'signInRequired', + }), + ); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope)]); + } }); it('retries audience resolution after a resolution failure', async () => { @@ -398,13 +443,13 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[0], 'failed-resolution'); - expect(postedMessages).toContainEqual({ - type: 'tokenError', - requestId: 'failed-resolution', - error: expect.stringContaining( - authMethod === AuthMethodId.ManagedIdentity ? 'HTTPS' : 'sign-in is set to', - ), - }); + expect(postedMessages).toContainEqual( + expect.objectContaining({ + type: 'tokenError', + requestId: 'failed-resolution', + reason: 'refreshFailed', + }), + ); expect(provider).not.toHaveBeenCalled(); expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); @@ -417,15 +462,20 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'retry-resolution', accessToken: 'private-token', }); - expect(provider.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope)]); }); - it('replaces the captured connection and audience when a new worker starts', async () => { + it('requires a new surface or binding to use a changed destination', async () => { await initializeSession(); manager.killWorker(); storeCredentials('cn'); selectedCloud = 'ChinaCloud'; + if (manager instanceof ShellSessionManager) { + await expect(initializeSession()).rejects.toMatchObject({ reason: 'credentialsChanged' }); + } + manager.dispose(); + manager = newSurface(); await initializeSession(); CredentialCache.deleteCredentials(clusterId); await refreshToken(workers[1], 'replacement-refresh'); @@ -436,10 +486,10 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'replacement-refresh', accessToken: 'private-token', }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([ - [clouds[0].scope], - [clouds[1].scope], - [clouds[1].scope], + expect(requestedScopes()).toEqual([ + scopedTo(clouds[0].scope), + scopedTo(clouds[1].scope), + scopedTo(clouds[1].scope), ]); }); @@ -506,9 +556,10 @@ describe('sovereign authentication with real audience resolvers', () => { await new Promise((resolve, reject) => { // Replace the worker before the old resolver's await continuation runs. queueMicrotask(() => { - manager.killWorker(); + manager.dispose(); storeCredentials('cn'); selectedCloud = 'ChinaCloud'; + manager = newSurface(); void initializeSession().then(resolve, reject); }); }); @@ -517,7 +568,7 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[1], 'replacement-refresh'); expect(workers).toHaveLength(2); - expect(provider.mock.calls.at(-1)?.[0]).toEqual([clouds[1].scope]); + expect(requestedScopes().at(-1)).toEqual(scopedTo(clouds[1].scope)); expect(postedMessages).not.toContainEqual(expect.objectContaining({ requestId: 'late-resolution' })); }); }); diff --git a/src/documentdb/auth/tokenExpiry.test.ts b/src/documentdb/auth/tokenExpiry.test.ts new file mode 100644 index 000000000..0642cc458 --- /dev/null +++ b/src/documentdb/auth/tokenExpiry.test.ts @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { readJwtTimes } from './tokenExpiry'; + +it.each([ + ['{"iat":100,"exp":200,"sub":"unused"}', { iatSec: 100, expSec: 200 }], + ['{"exp":200}', { expSec: 200 }], + ['{"iat":100,"exp":"200"}', { iatSec: 100 }], + ['{"iat":1e309,"exp":null}', {}], + ['not json', {}], +])('reads only finite numeric JWT times from %s', (payload, expected) => { + const token = `header.${Buffer.from(payload).toString('base64url')}.signature`; + expect(readJwtTimes(token)).toEqual(expected); +}); + +it('does not infer expiry from an opaque token', () => { + expect(readJwtTimes('opaque-token')).toEqual({}); +}); diff --git a/src/documentdb/auth/tokenExpiry.ts b/src/documentdb/auth/tokenExpiry.ts index 8a0747a17..c279ff99f 100644 --- a/src/documentdb/auth/tokenExpiry.ts +++ b/src/documentdb/auth/tokenExpiry.ts @@ -3,6 +3,36 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +/** Reads timing metadata only; this does not validate the token. */ +export function readJwtTimes(token: string): { iatSec?: number; expSec?: number } { + const parts = token.split('.'); + if (parts.length !== 3 || !parts[1]) { + return {}; + } + try { + const claims: unknown = JSON.parse(Buffer.from(parts[1], 'base64url').toString()); + if (typeof claims !== 'object' || claims === null) { + return {}; + } + return { + ...('iat' in claims && typeof claims.iat === 'number' && Number.isFinite(claims.iat) + ? { iatSec: claims.iat } + : {}), + ...('exp' in claims && typeof claims.exp === 'number' && Number.isFinite(claims.exp) + ? { expSec: claims.exp } + : {}), + }; + } catch { + return {}; + } +} + +/** The JWT's full lifetime, not its remaining validity or an opaque-token fallback. */ +export function jwtLifetimeSeconds({ iatSec, expSec }: ReturnType): number | undefined { + const lifetime = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; + return lifetime !== undefined && Number.isFinite(lifetime) && lifetime > 0 ? lifetime : undefined; +} + /** * Seconds until an absolute expiry timestamp (milliseconds since the epoch), floored at zero. * diff --git a/src/documentdb/auth/tokenRenewalTelemetry.ts b/src/documentdb/auth/tokenRenewalTelemetry.ts new file mode 100644 index 000000000..d2423645e --- /dev/null +++ b/src/documentdb/auth/tokenRenewalTelemetry.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; + +export interface EntraTokenLookupObservation { + readonly outcome: 'returned' | 'noSession' | 'providerChanged' | 'identityMismatch' | 'failed' | 'timedOut'; + readonly lifetimeSeconds?: number; +} + +export function emitTokenRenewal( + surface: 'extension' | 'shell' | 'playground', + { outcome, lifetimeSeconds }: EntraTokenLookupObservation, +): void { + void callWithTelemetryAndErrorHandling('connection.tokenRenewal', (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.properties.surface = surface; + context.telemetry.properties.renewalOutcome = outcome; + if ( + outcome === 'returned' && + lifetimeSeconds !== undefined && + Number.isFinite(lifetimeSeconds) && + lifetimeSeconds > 0 + ) { + context.telemetry.measurements.tokenLifetimeSeconds = lifetimeSeconds; + } + }).catch(() => { + // Telemetry delivery must not affect authentication. + }); +} diff --git a/src/documentdb/connectionBindingRetirement.test.ts b/src/documentdb/connectionBindingRetirement.test.ts new file mode 100644 index 000000000..07367415e --- /dev/null +++ b/src/documentdb/connectionBindingRetirement.test.ts @@ -0,0 +1,182 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + isLatestRetirement, + isRetiredConnectionBinding, + retireConnectionBindings, +} from './connectionBindingRetirement'; +import { runWithClient } from './runWithClient'; + +beforeEach((): void => { + vi.clearAllMocks(); +}); + +afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +it('keeps same-account physical replacements in one lifetime and aborts it synchronously on session end', (): void => { + const binding = { clusterId: 'lifetime-signal', fingerprint: 'same-account', generation: 1 }; + const replacement = { ...binding, generation: 2 }; + const signal = getBindingLifetimeSignal(binding); + const abort = vi.fn((): void => { + expect(getRetiredBindingReason(replacement)).toBe('sessionEnded'); + expect(isLatestRetirement(binding.clusterId, replacement.generation)).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 3 }).aborted).toBe(false); + }); + signal.addEventListener('abort', abort); + + expect(getBindingLifetimeSignal(replacement)).toBe(signal); + expect(isRetiredConnectionBinding(binding)).toBe(false); + expect(signal.aborted).toBe(false); + + retireConnectionBindings(binding.clusterId, replacement.generation); + + expect(abort).toHaveBeenCalledOnce(); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal(replacement).aborted).toBe(true); + const fresh = getBindingLifetimeSignal({ ...binding, generation: 3 }); + expect(fresh).not.toBe(signal); + expect(fresh.aborted).toBe(false); +}); + +it('keeps the cutoff monotonic without ending the fresh lifetime twice or reviving old bindings', (): void => { + const binding = { clusterId: 'lifetime-cutoff', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 2); + const freshSignal = getBindingLifetimeSignal({ ...binding, generation: 3 }); + const abort = vi.fn(); + freshSignal.addEventListener('abort', abort); + retireConnectionBindings(binding.clusterId, 1); + retireConnectionBindings(binding.clusterId, 2); + expect(freshSignal.aborted).toBe(false); + expect(abort).not.toHaveBeenCalled(); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + + retireConnectionBindings(binding.clusterId, 4); + expect(freshSignal.aborted).toBe(true); + expect(abort).toHaveBeenCalledOnce(); + expect(getRetiredBindingReason({ ...binding, generation: 2 })).toBe('sessionEnded'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('sessionEnded'); + expect(isRetiredConnectionBinding({ ...binding, generation: 4 })).toBe(true); + expect(getRetiredBindingReason({ ...binding, generation: 5 })).toBeUndefined(); +}); + +it('checks latest retirement ownership without reviving signals or affecting the next lifetime', (): void => { + const first = { clusterId: 'failed-removal-cutoff', fingerprint: 'same-account', generation: 1 }; + const firstSignal = getBindingLifetimeSignal(first); + retireConnectionBindings(first.clusterId, 1); + const second = { ...first, generation: 2 }; + const secondSignal = getBindingLifetimeSignal(second); + retireConnectionBindings(first.clusterId, 2); + const freshSignal = getBindingLifetimeSignal({ ...first, generation: 3 }); + + expect(isLatestRetirement(first.clusterId, 2)).toBe(true); + expect(getRetiredBindingReason(first)).toBe('sessionEnded'); + expect(getRetiredBindingReason(second)).toBe('sessionEnded'); + expect(firstSignal.aborted).toBe(true); + expect(secondSignal.aborted).toBe(true); + expect(getBindingLifetimeSignal(second).aborted).toBe(true); + expect(freshSignal.aborted).toBe(false); + expect(() => ClustersClient.assertBindingActive(second)).toThrow( + expect.objectContaining({ reason: 'sessionEnded' }), + ); + expect(isLatestRetirement(first.clusterId, 2)).toBe(true); +}); + +it('rejects ownership of a missing, wrong or superseded retirement generation', (): void => { + const binding = { clusterId: 'superseded-removal-cutoff', fingerprint: 'same-account', generation: 2 }; + expect(isLatestRetirement(binding.clusterId, 2)).toBe(false); + retireConnectionBindings(binding.clusterId, 2); + expect(isLatestRetirement(binding.clusterId, 1)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + retireConnectionBindings(binding.clusterId, 3); + expect(isLatestRetirement(binding.clusterId, 2)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('sessionEnded'); +}); + +it('retires generation zero while leaving a new lifetime active', (): void => { + const binding = { clusterId: 'generation-zero', fingerprint: 'same-account', generation: 0 }; + const signal = getBindingLifetimeSignal(binding); + expect(getRetiredBindingReason(binding)).toBeUndefined(); + expect(signal.aborted).toBe(false); + expect(isLatestRetirement(binding.clusterId, 0)).toBe(false); + retireConnectionBindings(binding.clusterId, 0); + expect(isLatestRetirement(binding.clusterId, 0)).toBe(true); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 1 }).aborted).toBe(false); +}); + +it('checks retirement before a later hold, while live bindings obey the current hold', (): void => { + const binding = { clusterId: 'lifetime-hold', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 1); + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue('credentialsRejected'); + expect(() => ClustersClient.assertBindingActive(binding)).toThrow( + expect.objectContaining({ reason: 'sessionEnded' }), + ); + expect(() => ClustersClient.assertBindingActive({ ...binding, generation: 2 })).toThrow( + expect.objectContaining({ reason: 'credentialsRejected' }), + ); +}); + +it('rejects a client resolved across retirement before it can reach a driver operation', async (): Promise => { + const binding = { clusterId: 'lifetime-pending-resolution', fingerprint: 'same-account', generation: 1 }; + let release!: (client: ClustersClient) => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const acquisition = vi + .spyOn(ClustersClient as unknown as { acquireClient: () => Promise }, 'acquireClient') + .mockReturnValue(pending); + const effect = vi.fn(); + const operation = runWithClient(binding, effect); + expect(acquisition).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, 1); + release({ binding: { ...binding, generation: 2 } } as ClustersClient); + await expect(operation).resolves.toEqual({ unavailable: { reason: 'sessionEnded' } }); + expect(effect).not.toHaveBeenCalled(); +}); + +it('never acquires, polls the database or prompts for an ended binding; a fresh background operation works once', async (): Promise => { + vi.useFakeTimers(); + const binding: ConnectionBinding = { + clusterId: 'lifetime-background', + fingerprint: 'same-account', + generation: 1, + }; + const replacement = { binding: { ...binding, generation: 2 } } as ClustersClient; + const acquisition = vi + .spyOn(ClustersClient as unknown as { acquireClient: () => Promise }, 'acquireClient') + .mockResolvedValue(replacement); + const database = vi.fn(async (): Promise => {}); + retireConnectionBindings(binding.clusterId, 1); + const poll = vi.fn(async (): Promise => { + await runWithClient(binding, database, { background: true }); + }); + const timer = setInterval(() => void poll(), 100); + try { + await vi.advanceTimersByTimeAsync(500); + } finally { + clearInterval(timer); + } + expect(poll).toHaveBeenCalledTimes(5); + expect(acquisition).not.toHaveBeenCalled(); + expect(database).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + await runWithClient(replacement.binding, database, { background: true }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(database).toHaveBeenCalledExactlyOnceWith(replacement); +}); diff --git a/src/documentdb/connectionBindingRetirement.ts b/src/documentdb/connectionBindingRetirement.ts new file mode 100644 index 000000000..dddad5cb6 --- /dev/null +++ b/src/documentdb/connectionBindingRetirement.ts @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type ConnectionBinding } from './ClustersClient'; + +interface BindingLifetime { + retiredThrough: number; + controller: AbortController; +} + +const lifetimes = new Map(); +const endedSignal = AbortSignal.abort(); + +export function retireConnectionBindings(clusterId: string, generation: number): void { + const lifetime: BindingLifetime = lifetimes.get(clusterId) ?? { + retiredThrough: -1, + controller: new AbortController(), + }; + if (generation <= lifetime.retiredThrough) { + return; + } + lifetime.retiredThrough = generation; + const controller = lifetime.controller; + lifetime.controller = new AbortController(); + lifetimes.set(clusterId, lifetime); + controller.abort(); +} + +export function getRetiredBindingReason({ clusterId, generation }: ConnectionBinding): 'sessionEnded' | undefined { + return generation <= (lifetimes.get(clusterId)?.retiredThrough ?? -1) ? 'sessionEnded' : undefined; +} + +export function isLatestRetirement(clusterId: string, generation: number): boolean { + return lifetimes.get(clusterId)?.retiredThrough === generation; +} + +export function isRetiredConnectionBinding(binding: ConnectionBinding): boolean { + return getRetiredBindingReason(binding) !== undefined; +} + +export function getBindingLifetimeSignal(binding: ConnectionBinding): AbortSignal { + if (isRetiredConnectionBinding(binding)) { + return endedSignal; + } + let lifetime = lifetimes.get(binding.clusterId); + if (!lifetime) { + lifetime = { retiredThrough: -1, controller: new AbortController() }; + lifetimes.set(binding.clusterId, lifetime); + } + return lifetime.controller.signal; +} diff --git a/src/documentdb/connectionFailures.test.ts b/src/documentdb/connectionFailures.test.ts new file mode 100644 index 000000000..4c55e2331 --- /dev/null +++ b/src/documentdb/connectionFailures.test.ts @@ -0,0 +1,268 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { + MongoAzureError, + MongoGCPError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoOIDCError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + TopologyType, + type ServerDescription, + type TopologyDescription, +} from 'mongodb'; +// eslint-disable-next-line import/no-internal-modules -- These constructors are not public runtime exports. +import { ServerDescription as DriverServerDescription } from 'mongodb/lib/sdam/server_description.js'; +// eslint-disable-next-line import/no-internal-modules -- Use the real .error getter, which aliases the first failed server. +import { TopologyDescription as DriverTopologyDescription } from 'mongodb/lib/sdam/topology_description.js'; +import { describe, expect, it } from 'vitest'; +import { AuthMethodId } from './auth/AuthMethod'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; +import { EntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { classifyConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +const makeServer = DriverServerDescription as new ( + address: string, + hello: undefined, + options: { error: Error | null }, +) => ServerDescription; +const makeTopology = DriverTopologyDescription as typeof TopologyDescription; + +function selectionError(...errors: (Error | null)[]): MongoServerSelectionError { + const servers = new Map( + errors.map((error, index): [string, ServerDescription] => { + const server = new makeServer(`example-${index}.test:27017`, undefined, { error }); + return [server.address, server]; + }), + ); + return new MongoServerSelectionError('Server selection timed out', new makeTopology(TopologyType.Unknown, servers)); +} + +const entra = AuthMethodId.MicrosoftEntraID; +const native = AuthMethodId.NativeAuth; +const rejected = new MongoServerError({ code: 18, errmsg: 'Authentication failed' }); +const network = new MongoNetworkError('connection closed'); +const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:27017'), { code: 'ECONNREFUSED' }); + +describe('classifyConnectionFailure', (): void => { + it.each(['noSession', 'providerChanged'] as const)('recognizes typed Entra sign-in: %s', (reason): void => { + const error = new Error('Wrapper', { cause: new EntraSignInRequiredError(reason) }); + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'other', generation: 'keep' }); + }); + + it('requires explicit recovery for a rejected Entra account without an auth-method gate', (): void => { + for (const authMethod of [undefined, entra, native, AuthMethodId.ManagedIdentity]) { + expect( + classifyConnectionFailure( + new Error('Wrapper', { cause: new EntraIdentityMismatchError() }), + authMethod, + ), + ).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + } + }); + + it('evicts a typed unavailable binding whose identity changed', (): void => { + expect( + classifyConnectionFailure( + new Error('Wrapper', { cause: new ConnectionUnavailableError('identityChanged') }), + ), + ).toEqual({ + kind: 'identityChanged', + generation: 'evict', + }); + }); + + it('reports missing credentials without inventing a generation to evict', (): void => { + expect(classifyConnectionFailure(new ConnectionUnavailableError('credentialsMissing'))).toEqual({ + kind: 'credentialsMissing', + generation: 'none', + }); + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity] as const)( + 'distinguishes a broken %s callback from its underlying network cause', + (authMethod): void => { + const error = new TokenCallbackError(network, authMethod); + expect(classifyConnectionFailure(error, authMethod)).toEqual({ + kind: 'transient', + generation: 'replaceOnNextForeground', + }); + }, + ); + + it.each([ + new MongoOIDCError('OIDC callback timed out after 60000ms.'), + new Error('Wrapper', { cause: selectionError(new MongoOIDCError('OIDC callback timed out after 12345ms.')) }), + ])('replaces a client after the driver callback timeout: %s', (error): void => { + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'transient', + generation: 'replaceOnNextForeground', + }); + }); + + it('does not reclassify other OIDC errors or derived error classes', (): void => { + for (const error of [ + new MongoOIDCError('OIDC callback returned an invalid response.'), + new MongoOIDCError('OIDC callback timed out after 60000ms'), + new MongoOIDCError('Unexpected OIDC callback timed out after 60000ms.'), + new MongoOIDCError('OIDC callback timed out after 60000ms. extra'), + Object.assign(new MongoOIDCError(''), { message: undefined }), + new MongoAzureError('OIDC callback timed out after 60000ms.'), + new MongoGCPError('OIDC callback timed out after 60000ms.'), + new Error('OIDC callback timed out after 60000ms.'), + ]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'other', generation: 'keep' }); + } + }); + + it('continues classifying the cause of a non-timeout OIDC error', (): void => { + const error = new MongoOIDCError('OIDC callback returned an invalid response.'); + error.cause = network; + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('classifies code 18 for native or RU key auth, including through real selection errors', (): void => { + const error = selectionError(rejected, null, new MongoServerError({ code: 18 })); + expect(error.cause).toBe(rejected); + expect(error.code).toBe(18); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'credentialsRejected', generation: 'evict' }); + }); + + it('evicts a rejected Entra client without classifying the failure as a missing session', (): void => { + expect(classifyConnectionFailure(selectionError(rejected), entra)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(classifyConnectionFailure(rejected, AuthMethodId.ManagedIdentity)).toEqual({ + kind: 'other', + generation: 'keep', + }); + }); + + it.each([ + new MongoTopologyClosedError(), + new MongoNotConnectedError('Client must be connected before running operations'), + ])('recognizes a typed closed client or topology: %s', (error): void => { + expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ + kind: 'clientClosed', + generation: 'replaceOnNextForeground', + }); + }); + + it.each([ + network, + new MongoNetworkError('Sign in again (AADSTS50058)'), + new MongoNetworkTimeoutError('timed out'), + new MongoOperationTimeoutError('Timed out during server selection', { cause: selectionError(null) }), + selectionError(new Error('unrecognized server error')), + ])('keeps an Entra client on plain network, timeout, or selection failures: %s', (error): void => { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('keeps the generation when a Kubernetes port-forward refuses the connection', (): void => { + const socketError = new MongoNetworkError(refused.message, { cause: refused }); + expect(classifyConnectionFailure(selectionError(socketError), native)).toEqual({ + kind: 'transient', + generation: 'keep', + }); + expect(classifyConnectionFailure(refused, native)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('does not treat the first server’s code 18 as authoritative when peers failed differently', (): void => { + const firstAuth = selectionError(rejected, network); + const firstNetwork = selectionError(network, rejected); + expect(firstAuth.cause).toBe(rejected); + expect(firstNetwork.cause).toBe(network); + for (const error of [firstAuth, firstNetwork]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('distinguishes consistent and mixed typed causes in constructed driver descriptions', (): void => { + // A MongoError can be retained by SDAM. The installed OIDC path does not create this wrapper. + const wrappedMiss = new MongoNetworkError('wrapped failure', { + cause: new EntraSignInRequiredError('noSession'), + }); + expect(classifyConnectionFailure(selectionError(null, wrappedMiss), entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + for (const error of [selectionError(wrappedMiss, network), selectionError(network, wrappedMiss)]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('leaves cancellation and destination rejection to their existing handlers', (): void => { + const cancellation = new TokenCallbackError(new UserCancelledError()); + const rejectedHost = new EntraDestinationRejectedError({ firstHost: 'not-allowed.test', hostCount: 1 }); + const tlsError = new MongoNetworkError('TLS failed', { cause: rejectedHost }); + + expect(classifyConnectionFailure(cancellation, entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'cancelled', + }); + expect(classifyConnectionFailure(selectionError(network, tlsError), entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'destinationRejected', + }); + const disconnected = new ConnectionUnavailableError('userDisconnected', { cause: rejected }); + expect(classifyConnectionFailure(disconnected)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'alreadyUnavailable', + }); + }); + + it('does not classify messages or an arbitrary code as typed failures', (): void => { + for (const error of [ + 'EntraSignInRequiredError', + new Error('Client must be connected before running operations'), + Object.assign(new Error('Sign in again (AADSTS50058)'), { code: 18 }), + ]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'other', generation: 'keep' }); + } + }); + + it('keeps the generation on cyclic or uninspected server evidence', (): void => { + const cyclic = new Error('cycle'); + cyclic.cause = cyclic; + const tooManyServers = Array(64).fill(null); + for (const error of [cyclic, selectionError(rejected, ...tooManyServers, network)]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'incompleteEvidence', + }); + } + }); +}); diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts new file mode 100644 index 000000000..3c7643554 --- /dev/null +++ b/src/documentdb/connectionFailures.ts @@ -0,0 +1,172 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { + MongoNetworkError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + type TopologyDescription, +} from 'mongodb'; +import { networkCode } from '../utils/connectionErrorClassification'; +import { AuthMethodId } from './auth/AuthMethod'; +import { isEntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +export interface ConnectionFailure { + readonly kind: + | 'signInRequired' + | 'identityChanged' + | 'credentialsMissing' + | 'credentialsRejected' + | 'clientClosed' + | 'transient' + | 'other'; + readonly generation: 'keep' | 'evict' | 'replaceOnRecovery' | 'replaceOnNextForeground' | 'none'; + readonly note?: + | 'cancelled' + | 'destinationRejected' + | 'alreadyUnavailable' + | 'mixedServerErrors' + | 'incompleteEvidence'; +} + +const OTHER: ConnectionFailure = { kind: 'other', generation: 'keep' }; +const TRANSIENT: ConnectionFailure = { kind: 'transient', generation: 'keep' }; +const INCOMPLETE: ConnectionFailure = { ...OTHER, note: 'incompleteEvidence' }; +const MAX_DEPTH = 8; +const MAX_NODES = 64; + +/** Classifies failures using the auth method actually used (RU key connections use NativeAuth). */ +export function classifyConnectionFailure(error: unknown, authMethod?: AuthMethodId): ConnectionFailure { + let remaining = MAX_NODES; + const path = new Set(); + + function inspect(candidate: unknown, depth: number): ConnectionFailure | undefined { + if (!(candidate instanceof Error)) { + return undefined; + } + if (depth >= MAX_DEPTH || remaining-- <= 0 || path.has(candidate)) { + return INCOMPLETE; + } + path.add(candidate); + try { + return classify(candidate, depth); + } finally { + path.delete(candidate); + } + } + + function classify(candidate: Error, depth: number): ConnectionFailure { + if (candidate instanceof UserCancelledError) { + return { ...OTHER, note: 'cancelled' }; + } + if (isEntraDestinationRejectedError(candidate)) { + return { ...OTHER, note: 'destinationRejected' }; + } + if (candidate instanceof ConnectionUnavailableError) { + switch (candidate.reason) { + case 'identityChanged': + return { kind: 'identityChanged', generation: 'evict' }; + case 'credentialsMissing': + return { kind: 'credentialsMissing', generation: 'none' }; + case 'credentialsRejected': + case 'signInRequired': + return { kind: candidate.reason, generation: 'none', note: 'alreadyUnavailable' }; + default: + return { ...OTHER, note: 'alreadyUnavailable' }; + } + } + if (candidate instanceof MongoServerSelectionError && candidate.reason?.servers instanceof Map) { + return classifyServers(candidate.reason.servers, depth + 1); + } + + const cause = inspect(candidate.cause, depth + 1); + if (cause?.note !== undefined) { + return cause; + } + switch (candidate.name) { + case 'EntraSignInRequiredError': + return authMethod === undefined || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'signInRequired', generation: 'replaceOnRecovery' } + : OTHER; + case 'EntraIdentityMismatchError': + return { kind: 'signInRequired', generation: 'replaceOnRecovery' }; + case 'TokenCallbackError': + return { kind: 'transient', generation: 'replaceOnNextForeground' }; + case 'MongoOIDCError': + if ( + typeof candidate.message === 'string' && + /^OIDC callback timed out after \d+ms\.$/.test(candidate.message) + ) { + return { kind: 'transient', generation: 'replaceOnNextForeground' }; + } + break; + } + if (candidate instanceof MongoServerError && candidate.code === 18) { + // The OIDC workflow already tries its callback after a cached token is rejected. + return authMethod === AuthMethodId.NativeAuth || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'credentialsRejected', generation: 'evict' } + : OTHER; + } + if (candidate instanceof MongoNotConnectedError || candidate instanceof MongoTopologyClosedError) { + return { kind: 'clientClosed', generation: 'replaceOnNextForeground' }; + } + if (cause && cause.kind !== 'other') { + return cause; + } + if ( + candidate instanceof MongoNetworkError || + candidate instanceof MongoOperationTimeoutError || + candidate instanceof MongoServerSelectionError || + networkCode(candidate) + ) { + return TRANSIENT; + } + return OTHER; + } + + function classifyServers(servers: TopologyDescription['servers'], depth: number): ConnectionFailure { + // In 7.2.0, selection.cause and .code summarize the *first* server error, not the topology. + // Consider the per-server errors instead, so reversing the map cannot change the verdict. + let agreed: ConnectionFailure | undefined; + let mixed = false; + let constraint: ConnectionFailure | undefined; + for (const server of servers.values()) { + if (remaining <= 0) { + return constraint ?? INCOMPLETE; + } + remaining--; // Bound map iteration even when descriptions have no error. + const result = inspect(server?.error, depth); + if (!result) { + continue; + } + if (result.note === 'cancelled' || result.note === 'destinationRejected') { + // Preserve both constraints without enlarging either policy. + constraint = result.note === 'cancelled' ? result : (constraint ?? result); + } + if (agreed) { + mixed ||= + result.kind !== agreed.kind || + result.generation !== agreed.generation || + result.note !== agreed.note; + } else { + agreed = result; + } + } + if (constraint) { + return constraint; + } + if (mixed) { + return { ...TRANSIENT, note: 'mixedServerErrors' }; + } + return agreed && (agreed.kind !== 'other' || agreed.note) ? agreed : TRANSIENT; + } + + return inspect(error, 0) ?? OTHER; +} diff --git a/src/documentdb/connectionFingerprint.test.ts b/src/documentdb/connectionFingerprint.test.ts new file mode 100644 index 000000000..4bec2eb91 --- /dev/null +++ b/src/documentdb/connectionFingerprint.test.ts @@ -0,0 +1,94 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it, vi } from 'vitest'; + +import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; + +describe('computeConnectionFingerprint', () => { + const connectionString = 'mongodb://user:test-password@Host.example:27017/db?authSource=admin&tls=true'; + const native = { kind: 'native', username: 'user' } as const; + const entra = { kind: 'entra', providerId: 'public', accountId: 'account', tenantId: 'tenant' } as const; + + it('returns the same 32-character lowercase hex fingerprint within a host', () => { + const fingerprint = computeConnectionFingerprint({ connectionString, principal: native }); + expect(fingerprint).toMatch(/^[a-f0-9]{32}$/); + expect(computeConnectionFingerprint({ connectionString, principal: { ...native } })).toBe(fingerprint); + }); + + it.each([ + ['mongodb+srv', 'user%40example.com', 'old%40%3A%2F%3F%23%25', 'new%3a%40%2f%3f%23%25'], + ['mongodb', 'account', 'dGVzdC9vbGQ%2B%2F%3D%3D', 'dGVzdC9uZXc%2B%2F%3D%3D'], + ])('ignores password or key rotation in %s URIs', (scheme, username, oldPassword, newPassword) => { + const principal = { kind: 'native', username } as const; + const suffix = '@host.example/db?appName=test@client'; + const before = `${scheme}://${username}:${oldPassword}${suffix}`; + const after = `${scheme}://${username}:${newPassword}${suffix}`; + const fingerprint = computeConnectionFingerprint({ connectionString: before, principal }); + expect(computeConnectionFingerprint({ connectionString: after, principal })).toBe(fingerprint); + }); + + it.each([ + ['username', 'user:', 'User:'], + ['host case', 'Host.example', 'host.example'], + ['port', ':27017', ':27018'], + ['database path', '/db?', '/other?'], + ['path escape spelling', '/db?', '/%64b?'], + ['authSource', 'authSource=admin', 'authSource=db'], + ['query order', 'authSource=admin&tls=true', 'tls=true&authSource=admin'], + ])('changes when the URI %s changes', (_edit, from, to) => { + const fingerprint = computeConnectionFingerprint({ connectionString, principal: native }); + expect( + computeConnectionFingerprint({ connectionString: connectionString.replace(from, to), principal: native }), + ).not.toBe(fingerprint); + }); + + it('preserves a literal @ in the query without misreading the host port as a password', () => { + const principal = { kind: 'none' } as const; + const before = 'mongodb://host.example:27017?appName=test@client'; + const after = 'mongodb://host.example:27018?appName=test@client'; + expect(computeConnectionFingerprint({ connectionString: before, principal })).not.toBe( + computeConnectionFingerprint({ connectionString: after, principal }), + ); + }); + + it('distinguishes all principal variants and each principal field', () => { + const principals: ConnectionPrincipal[] = [ + native, + { ...native, username: 'User' }, + entra, + { ...entra, providerId: 'government' }, + { ...entra, accountId: 'other' }, + { ...entra, tenantId: 'other' }, + { kind: 'entra', providerId: entra.providerId, accountId: entra.accountId }, + { kind: 'managedIdentity', clientId: 'client-a' }, + { kind: 'managedIdentity', clientId: 'client-b' }, + { kind: 'managedIdentity' }, + { kind: 'none' }, + ]; + const fingerprints = principals.map((principal) => + computeConnectionFingerprint({ connectionString, principal }), + ); + expect(new Set(fingerprints).size).toBe(principals.length); + }); + + it('keeps principal field boundaries unambiguous', () => { + const first = { ...entra, providerId: 'cloud:region', accountId: 'account' }; + const second = { ...entra, providerId: 'cloud', accountId: 'region:account' }; + expect(computeConnectionFingerprint({ connectionString, principal: first })).not.toBe( + computeConnectionFingerprint({ connectionString, principal: second }), + ); + }); + + it('does not reuse the fingerprint key after a fresh module load', async () => { + const input = { connectionString, principal: native }; + const originalFingerprint = computeConnectionFingerprint(input); + + vi.resetModules(); + const { computeConnectionFingerprint: computeFreshFingerprint } = await import('./connectionFingerprint'); + + expect(computeFreshFingerprint(input)).not.toBe(originalFingerprint); + }); +}); diff --git a/src/documentdb/connectionFingerprint.ts b/src/documentdb/connectionFingerprint.ts new file mode 100644 index 000000000..844135ef9 --- /dev/null +++ b/src/documentdb/connectionFingerprint.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 { createHmac, generateKeySync } from 'node:crypto'; + +const connectionFingerprintKey = generateKeySync('hmac', { length: 256 }); + +export type ConnectionPrincipal = + | { kind: 'native'; username: string } + | { kind: 'entra'; providerId: string; accountId: string; tenantId?: string } + | { kind: 'managedIdentity'; clientId?: string } + | { kind: 'none' }; + +/** An opaque equality key for the current extension host, not a password verifier. See .github/codeql-exceptions.md. */ +export function computeConnectionFingerprint(input: { + connectionString: string; + principal: ConnectionPrincipal; +}): string { + // Match only the password in the URI authority, without decoding or reserializing the URI. + const uriWithoutAuthorityPassword = input.connectionString.replace(/^([^:/?#]+:\/\/[^:/?#@]*:)[^/?#@]*(?=@)/, '$1'); + const identityMaterial = JSON.stringify([uriWithoutAuthorityPassword, principalParts(input.principal)]); + return createHmac('sha256', connectionFingerprintKey).update(identityMaterial).digest('hex').slice(0, 32); +} + +function principalParts(principal: ConnectionPrincipal): readonly (string | null)[] { + switch (principal.kind) { + case 'native': + return [principal.kind, principal.username]; + case 'entra': + return [principal.kind, principal.providerId, principal.accountId, principal.tenantId ?? null]; + case 'managedIdentity': + // A missing client ID denotes system-assigned, not a particular instance of that identity. + return [principal.kind, principal.clientId ?? null]; + case 'none': + return [principal.kind]; + } +} diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts new file mode 100644 index 000000000..47d039f63 --- /dev/null +++ b/src/documentdb/connectionSurfaces.test.ts @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * 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, + takeConnectionSurfaces, + 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([]); +}); + +it('detaches ended surfaces without disposing snapshots or letting their registrations remove fresh surfaces', (): void => { + const old: ConnectionSurface = { + clusterId: 'detached-cluster', + kind: 'documentView', + isDirty: () => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + const fresh: ConnectionSurface = { ...old, dispose: vi.fn() }; + const oldRegistration = registerConnectionSurface(old); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([old]); + expect(getConnectionSurfaces(old.clusterId)).toEqual([]); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([]); + const freshRegistration = registerConnectionSurface(fresh); + try { + oldRegistration.dispose(); + expect(getConnectionSurfaces(old.clusterId)).toEqual([fresh]); + expect(old.isDirty?.()).toBe(true); + expect(old.dispose).not.toHaveBeenCalled(); + expect(old.disable).not.toHaveBeenCalled(); + } finally { + oldRegistration.dispose(); + freshRegistration.dispose(); + } +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts new file mode 100644 index 000000000..be0ae0e4c --- /dev/null +++ b/src/documentdb/connectionSurfaces.ts @@ -0,0 +1,46 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; + readonly editable?: boolean; + 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.get(clusterId) === surfaces) { + surfacesByCluster.delete(clusterId); + } + }, + }; +} + +export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + return [...(surfacesByCluster.get(clusterId) ?? [])]; +} + +export function takeConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + const surfaces = getConnectionSurfaces(clusterId); + surfacesByCluster.delete(clusterId); + return surfaces; +} diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts new file mode 100644 index 000000000..4e9eab5ae --- /dev/null +++ b/src/documentdb/connectionTeardown.test.ts @@ -0,0 +1,916 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import * as l10n from '@vscode/l10n'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + retireConnectionBindings, +} from './connectionBindingRetirement'; +import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + commitTeardown, + confirmTeardown, + ensureDisconnectedForEdit, + latchForTeardown, + teardownConnection, + withConnectionRemoval, +} from './connectionTeardown'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +const mocks = vi.hoisted(() => ({ + getSetting: vi.fn(), + getConflictingTasks: vi.fn(), + getLatchReason: vi.fn(), + getEpoch: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), + retireBoundViews: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + deleteCredentials: vi.fn(), + clearEntraTokenFailure: vi.fn(), + getRegisteredShellTerminals: vi.fn(), + getPlaygroundEvaluators: vi.fn(), + stopPlaygroundEvaluator: vi.fn(), + clearRemovedPlaygroundConnections: vi.fn(), + event: vi.fn(), +})); + +vi.mock('@microsoft/vscode-azext-utils', () => ({ + UserCancelledError: class UserCancelledError extends Error {}, + callWithTelemetryAndErrorHandling: async ( + event: string, + callback: (context: { telemetry: object; errorHandling: object }) => Promise, + ): Promise => { + const telemetry = { properties: {}, measurements: {} }; + try { + await callback({ telemetry, errorHandling: {} }); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + throw error; + } + } finally { + mocks.event(event, telemetry); + } + }, +})); +vi.mock('../services/SettingsService', () => ({ SettingsService: { getSetting: mocks.getSetting } })); +vi.mock('../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: mocks.getConflictingTasks }, +})); +vi.mock('./ClustersClient', () => ({ ClustersClient: mocks })); +vi.mock('./CredentialCache', () => ({ CredentialCache: { deleteCredentials: mocks.deleteCredentials } })); +vi.mock('./auth/entraErrors/entraTokenFailures', () => ({ clearEntraTokenFailure: mocks.clearEntraTokenFailure })); +vi.mock('./shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals: mocks.getRegisteredShellTerminals, +})); +vi.mock('../commands/playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators: mocks.getPlaygroundEvaluators, + stopPlaygroundEvaluator: mocks.stopPlaygroundEvaluator, + clearRemovedPlaygroundConnections: mocks.clearRemovedPlaygroundConnections, +})); + +const clusterId = 'example-cluster'; +const otherId = 'other-cluster'; +const refreshTree = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const showError = vi.mocked(vscode.window.showErrorMessage); +const registrations: vscode.Disposable[] = []; + +function register( + kind: ConnectionSurface['kind'], + dirty = false, + target = clusterId, + editable = kind === 'documentView', +): ConnectionSurface { + const surface = { clusterId: target, kind, editable, isDirty: () => dirty, disable: vi.fn(), dispose: vi.fn() }; + registrations.push(registerConnectionSurface(surface)); + return surface; +} + +describe('connection teardown', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.getConflictingTasks.mockReturnValue([]); + mocks.exists.mockReturnValue(true); + mocks.hasPendingStartup.mockReturnValue(false); + mocks.retireBoundViews.mockReturnValue(1); + mocks.getRegisteredShellTerminals.mockReturnValue([]); + mocks.getPlaygroundEvaluators.mockReturnValue(new Map()); + vi.spyOn(vscode.l10n, 't').mockImplementation(l10n.t); + }); + + afterEach(() => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + vi.restoreAllMocks(); + }); + + it.each([false, true])( + 'does not remove connections when the user cancels (chose Close all: %s)', + async (choseClose) => { + const draft = register('documentView', true); + const remove = vi.fn(); + if (choseClose) { + showWarning.mockImplementationOnce(async (_title, _options, ...items) => items[0]); + } + + await expect(withConnectionRemoval([clusterId, otherId], remove)).rejects.toBeInstanceOf( + UserCancelledError, + ); + + expect(showWarning).toHaveBeenCalledTimes(choseClose ? 2 : 1); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(remove).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + }, + ); + + it('fences the whole batch before removal and leaves a surviving connection reconnectable', async () => { + const latches = new Map(); + const epochs = new Map(); + mocks.getLatchReason.mockImplementation((id: string) => latches.get(id)); + mocks.getEpoch.mockImplementation((id: string) => epochs.get(id) ?? 0); + mocks.latch.mockImplementation((id: string, reason: string) => { + latches.set(id, reason); + epochs.set(id, (epochs.get(id) ?? 0) + 1); + }); + mocks.unlatch.mockImplementation((id: string) => { + latches.delete(id); + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + const draft = register('documentView', true); + const binding = { clusterId, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); + return binding.generation; + }); + const untouchedView = register('documentView', true, otherId); + const failedDelete = new Error('Storage write failed'); + let fresh: ConnectionSurface | undefined; + + await expect( + withConnectionRemoval([clusterId, otherId], async (remove) => { + await remove(clusterId, async () => { + expect(latches.get(otherId)).toBe('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + fresh = register('collectionView'); + throw failedDelete; + }); + }), + ).rejects.toBe(failedDelete); + + expect(latches.get(clusterId)).toBe('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 2 }).aborted).toBe(false); + expect(getConnectionSurfaces(clusterId)).toEqual([fresh]); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(latches.has(otherId)).toBe(false); + expect(untouchedView.disable).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + }); + + it('skips the choice modal when there are no surfaces and leaves preflight read-only', async () => { + await expect(confirmTeardown(clusterId, 'userDisconnected')).resolves.toEqual({ + outcome: 'confirmed', + choice: 'close', + }); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }); + + it.each(['userDisconnected', 'connectionRemoved'] as const)( + 'always asks before discarding dirty editors for %s, even with closeAll configured', + async (reason) => { + const draft = register('documentView', true); + mocks.getSetting.mockReturnValue('closeAll'); + await expect(confirmTeardown(clusterId, reason)).resolves.toEqual({ outcome: 'cancelled' }); + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Discard unsaved document changes?', + expect.objectContaining({ modal: true }), + 'Discard changes', + ); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }, + ); + + it('closes read-only Document Views without discard confirmation', async (): Promise => { + const readOnly = register('documentView', false, clusterId, false); + mocks.getSetting.mockReturnValue('closeAll'); + + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + + expect(readOnly.dispose).toHaveBeenCalledOnce(); + expect(readOnly.disable).not.toHaveBeenCalled(); + expect(showWarning).not.toHaveBeenCalled(); + }); + + it.each(['disconnect', 'remove'] as const)( + 'cancels %s before mutation while a dirty report is delayed', + async (route): Promise => { + const draft = register('documentView'); + const hostDraft = { contents: 'original', dirty: false }; + const editedDraft = { contents: 'unsaved draft', dirty: true }; + vi.spyOn(draft, 'isDirty').mockImplementation(() => hostDraft.dirty); + let deliverReport!: (report: typeof hostDraft) => void; + const report = new Promise((resolve) => { + deliverReport = resolve; + }).then((value): void => { + Object.assign(hostDraft, value); + }); + showWarning.mockImplementationOnce(async () => { + expect(draft.isDirty?.()).toBe(false); + expect(hostDraft.contents).toBe('original'); + return undefined; + }); + mocks.getSetting.mockReturnValue('closeAll'); + const remove = vi.fn(); + const pending = + route === 'remove' + ? withConnectionRemoval([clusterId, otherId], remove) + : teardownConnection(clusterId, 'userDisconnected', refreshTree); + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + + expect(draft.isDirty?.()).toBe(false); + expect(hostDraft.contents).toBe('original'); + expect(getConnectionSurfaces(clusterId)).toEqual([draft]); + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Discard unsaved document changes?', + expect.objectContaining({ modal: true }), + 'Discard changes', + ); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(refreshTree).not.toHaveBeenCalled(); + expect(remove).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + + deliverReport(editedDraft); + await report; + expect(hostDraft.contents).toBe('unsaved draft'); + expect(draft.isDirty?.()).toBe(true); + expect(getConnectionSurfaces(clusterId)).toEqual([draft]); + }, + ); + + it.each(['disconnect', 'batch'] as const)( + 'only closes the exact editable surfaces confirmed before the discard modal for %s', + async (route): Promise => { + const draft = register('documentView'); + const readOnly = register('documentView', false, clusterId, false); + const collection = register('collectionView'); + const dashboard = register('clusterDashboard'); + const otherDraft = route === 'batch' ? register('documentView', false, otherId) : undefined; + const latches = new Map(); + mocks.getLatchReason.mockImplementation((id: string) => latches.get(id)); + mocks.getEpoch.mockReturnValue(1); + mocks.latch.mockImplementation((id: string, reason: ConnectionUnavailableReason): void => { + latches.set(id, reason); + }); + mocks.getSetting.mockReturnValue('closeAll'); + let late!: ConnectionSurface; + showWarning.mockImplementationOnce(async (_title, _options, ...items) => { + late = register('documentView'); + return items[0]; + }); + let afterLatch: ConnectionSurface | undefined; + const deleteStored = vi.fn(async (): Promise => { + afterLatch = register('documentView', false, otherId); + }); + if (route === 'batch') { + await withConnectionRemoval([clusterId, otherId], async (remove) => { + await remove(clusterId, deleteStored); + await remove(otherId, async () => {}); + }); + } else { + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + } + + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Discard unsaved document changes?', + expect.objectContaining({ modal: true }), + 'Discard changes', + ); + for (const surface of [draft, readOnly, collection, dashboard]) { + expect(surface.dispose).toHaveBeenCalledOnce(); + expect(surface.disable).not.toHaveBeenCalled(); + } + expect(late.dispose).not.toHaveBeenCalled(); + expect(late.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + if (route === 'batch') { + expect(otherDraft?.dispose).toHaveBeenCalledOnce(); + expect(otherDraft?.disable).not.toHaveBeenCalled(); + expect(afterLatch?.dispose).not.toHaveBeenCalled(); + expect(afterLatch?.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(deleteStored).toHaveBeenCalledOnce(); + expect(mocks.latch.mock.calls.map(([id]) => id)).toEqual([clusterId, otherId]); + } + }, + ); + + it('honors modal cancellation without changing the connection', async () => { + const draft = register('documentView', true); + await expect(teardownConnection(clusterId, 'userDisconnected', refreshTree)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Disconnect?', + expect.objectContaining({ modal: true }), + 'Close all', + 'Keep open', + ); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }); + + it('names a task before asking what to do with tabs', async () => { + register('collectionView'); + mocks.getConflictingTasks.mockReturnValue([{ taskName: 'Copy orders', taskType: 'copy' }]); + await expect(confirmTeardown(clusterId, 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(showError).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ modal: true, detail: expect.stringContaining('Copy orders') }), + ); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }); + + it('blocks a lease started during the modal without mutating surfaces, cache or workers', async () => { + const draft = register('documentView', true); + showWarning.mockImplementationOnce(async (_title, _options, ...items) => { + mocks.getConflictingTasks.mockReturnValue([{ taskName: 'Export documents', taskType: 'export' }]); + return items[1]; + }); + + await expect(teardownConnection(clusterId, 'userDisconnected', refreshTree)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(showError).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ modal: true, detail: expect.stringContaining('Export documents') }), + ); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + expect(refreshTree).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + expect(mocks.event).toHaveBeenCalledExactlyOnceWith( + 'connection.disconnect', + expect.objectContaining({ properties: expect.objectContaining({ blockedByTask: 'true' }) }), + ); + }); + + it('fences once, disables all matching surfaces, stops only matching workers, and keeps credentials and pin', async () => { + const surfaces = [register('documentView', true), register('collectionView'), register('clusterDashboard')]; + const unrelated = register('documentView', true, otherId); + const disconnect = vi.fn(); + const otherShell = vi.fn(); + mocks.getRegisteredShellTerminals.mockReturnValue([ + { info: { clusterId }, disconnect }, + { info: { clusterId: otherId }, disconnect: otherShell }, + ]); + mocks.getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + for (const surface of surfaces) { + expect(mocks.latch).toHaveBeenCalledBefore(vi.mocked(surface.disable)); + expect(surface.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(surface.dispose).not.toHaveBeenCalled(); + } + expect(unrelated.disable).not.toHaveBeenCalled(); + expect(disconnect).toHaveBeenCalledOnce(); + expect(otherShell).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); + expect(mocks.clearEntraTokenFailure).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + expect(refreshTree).toHaveBeenCalledOnce(); + expect(mocks.event).toHaveBeenCalledExactlyOnceWith('connection.disconnect', { + properties: { source: 'command', surfacesChoice: 'keepOpenDisabled', blockedByTask: 'false' }, + measurements: { surfaceCount: 3, shellCount: 1, playgroundCount: 1 }, + maskEntireErrorMessage: true, + }); + }); + + it('closes surfaces and drops credentials only when requested, without latching a fenced target again', async () => { + const draft = register('documentView', true); + mocks.getLatchReason.mockReturnValue('connectionRemoved'); + await expect( + commitTeardown(clusterId, { + reason: 'connectionRemoved', + choice: 'close', + discardConfirmed: new Set([draft]), + alreadyLatched: true, + dropCredentials: true, + refreshTree, + }), + ).resolves.toBe('committed'); + expect(showWarning).not.toHaveBeenCalled(); + expect(draft.dispose).toHaveBeenCalledOnce(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.clearLastVerifiedIdentity).toHaveBeenCalledExactlyOnceWith(clusterId); + }); + + it('does not partially latch a batch when a descendant is blocked', () => { + mocks.getConflictingTasks.mockImplementation(({ clusterId: id }: { clusterId: string }) => + id === otherId ? [{ taskName: 'Import', taskType: 'import' }] : [], + ); + expect(latchForTeardown([clusterId, otherId], 'connectionRemoved')).toBe(false); + expect(mocks.latch).not.toHaveBeenCalled(); + }); + + it.each([false, true])( + 'retires and detaches the lifetime before any surface, worker or asynchronous close (already latched: %s)', + async (alreadyLatched): Promise => { + const target = `ordered-teardown-${alreadyLatched}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + if (alreadyLatched) { + mocks.getLatchReason.mockReturnValue('connectionRemoved'); + } + mocks.retireBoundViews.mockImplementation((id: string): number => { + expect(alreadyLatched || mocks.latch.mock.calls.length === 1).toBe(true); + retireConnectionBindings(id, 1); + return 1; + }); + const onRetired = vi.fn((generation: number): void => { + expect(generation).toBe(1); + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + expect(draft.disable).not.toHaveBeenCalled(); + }); + vi.mocked(draft.disable).mockImplementation((): void => { + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + }); + const disconnect = vi.fn((): void => { + expect(signal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledOnce(); + }); + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId: target }, disconnect }]); + let finishClose!: () => void; + mocks.deleteClient.mockImplementation((): Promise => { + expect(signal.aborted).toBe(true); + return new Promise((resolve) => { + finishClose = resolve; + }); + }); + const teardown = commitTeardown(target, { + reason: 'connectionRemoved', + choice: 'keepOpenDisabled', + alreadyLatched, + onRetired, + refreshTree, + }); + expect(signal.aborted).toBe(true); + expect(onRetired).toHaveBeenCalledExactlyOnceWith(1); + expect(disconnect).toHaveBeenCalledOnce(); + expect(refreshTree).not.toHaveBeenCalled(); + finishClose(); + await expect(teardown).resolves.toBe('committed'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(target); + expect(draft.isDirty?.()).toBe(true); + }, + ); + + it.each(['userDisconnected', 'connectionRemoved'] as const)( + 'keeps an old dirty snapshot out of the next session %s Close all, dirty confirmation and counts', + async (reason): Promise => { + const draft = register('documentView', true); + const collection = register('collectionView'); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + const fresh = register('collectionView'); + mocks.getSetting.mockReturnValue('closeAll'); + await teardownConnection(clusterId, reason, refreshTree); + + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(collection.dispose).not.toHaveBeenCalled(); + expect(fresh.dispose).toHaveBeenCalledOnce(); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.event).toHaveBeenLastCalledWith( + 'connection.disconnect', + expect.objectContaining({ measurements: expect.objectContaining({ surfaceCount: 1 }) }), + ); + }, + ); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'requires Disconnect before editing with surviving %s', + async (survivor): Promise => { + let epoch = 7; + let latch: ConnectionUnavailableReason | undefined = 'credentialsRejected'; + mocks.exists.mockReturnValue(survivor === 'heldClient'); + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + const draft = survivor === 'surface' ? register('documentView', true) : undefined; + const disconnect = vi.fn(); + mocks.hasPendingStartup.mockReturnValue(survivor === 'startup'); + if (survivor === 'evaluator') { + mocks.getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + if (survivor === 'shell') { + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[1]); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).resolves.toBe(8); + + expect(showWarning).toHaveBeenNthCalledWith( + 1, + 'Disconnect?', + { + modal: true, + detail: 'You can only update credentials or the connection string while disconnected.', + }, + 'Disconnect and update', + ); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + expect(mocks.stopPlaygroundEvaluator).toHaveBeenCalledExactlyOnceWith(clusterId); + if (draft) { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.dispose).not.toHaveBeenCalled(); + } + if (survivor === 'shell') { + expect(disconnect).toHaveBeenCalledOnce(); + } + }, + ); + + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'blocks editing after %s', + async (outcome): Promise => { + let latch: ConnectionUnavailableReason | undefined; + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + }); + const draft = register('documentView', true); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + mocks.getConflictingTasks.mockReturnValue([task]); + } else if (outcome !== 'cancel offer') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[0]); + if (outcome === 'dirty close refusal') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[0]); + } else if (outcome === 'close failure') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[1]); + mocks.deleteClient.mockRejectedValueOnce(new Error('private driver connection details')); + } + } + + const pending = ensureDisconnectedForEdit(clusterId, refreshTree); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(refreshTree).not.toHaveBeenCalled(); + } + const warningCount = { + 'cancel offer': 1, + 'cancel tabs': 2, + 'active transfer': 0, + 'dirty close refusal': 3, + 'close failure': 2, + }[outcome]; + expect(showWarning).toHaveBeenCalledTimes(warningCount); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + + it.each(['userDisconnected', 'connectionRemoved', 'credentialsUpdating', undefined] as const)( + 'skips only terminal %s or a fully idle target', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + if (reason) { + register('collectionView'); + mocks.hasPendingStartup.mockReturnValue(true); + } + await expect( + commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'close', refreshTree }), + ).resolves.toBe('superseded'); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['epoch', 'latch', 'laterGeneration'] as const)( + 'does not correct a failed Remove superseded by %s during storage deletion', + async (superseding): Promise => { + const target = `superseded-removal-${superseding}`; + const old = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const later = { ...old, generation: 2 }; + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation(() => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, old.generation); + return old.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + const draft = register('documentView', true, target); + const oldSignal = getBindingLifetimeSignal(old); + let fresh: ConnectionSurface | undefined; + const failedDelete = new Error('Storage write failed'); + + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, async () => { + fresh = register('collectionView', false, target); + if (superseding === 'epoch') { + epoch++; + } else if (superseding === 'latch') { + latch = 'credentialsUpdating'; + } else { + retireConnectionBindings(target, later.generation); + } + throw failedDelete; + }); + }), + ).rejects.toBe(failedDelete); + + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(latch).toBe(superseding === 'latch' ? 'credentialsUpdating' : 'connectionRemoved'); + expect(getRetiredBindingReason(old)).toBe('sessionEnded'); + expect(getRetiredBindingReason(later)).toBe(superseding === 'laterGeneration' ? 'sessionEnded' : undefined); + expect(oldSignal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + }, + ); + + it.each(['disconnect', 'failedRemove', 'credentialsChanged'] as const)( + 'restores the still-stored connection after repeated same-generation failed Removes following %s', + async (preceding): Promise => { + const target = `repeated-removal-${preceding}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation((): ConnectionUnavailableReason | undefined => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); + return binding.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + if (preceding !== 'failedRemove') { + await expect( + commitTeardown(target, { + reason: preceding === 'disconnect' ? 'userDisconnected' : 'credentialsChanged', + choice: 'keepOpenDisabled', + refreshTree, + }), + ).resolves.toBe('committed'); + } + let nextSignal: AbortSignal | undefined; + for (let attempt = 0; attempt < 2; attempt++) { + const captured = register('documentView', true, target); + const fresh: ConnectionSurface = { + clusterId: target, + kind: 'collectionView', + disable: vi.fn(), + dispose: vi.fn(), + }; + let freshRegistration: vscode.Disposable | undefined; + const failedDelete = new Error('Storage write failed'); + const deleteStored = vi.fn(async (): Promise => { + freshRegistration = registerConnectionSurface(fresh); + throw failedDelete; + }); + try { + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }), + ).rejects.toBe(failedDelete); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(latch).toBe('userDisconnected'); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + const currentNextSignal = getBindingLifetimeSignal({ ...binding, generation: 2 }); + expect(currentNextSignal.aborted).toBe(false); + if (nextSignal) { + expect(currentNextSignal).toBe(nextSignal); + } + nextSignal = currentNextSignal; + expect(captured.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(captured.isDirty?.()).toBe(true); + expect(captured.dispose).not.toHaveBeenCalled(); + expect(fresh.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + } finally { + freshRegistration?.dispose(); + } + } + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + }, + ); + + it('leaves a successful Remove retirement unchanged and reports storage success only after deletion', async (): Promise => { + const target = 'successful-removal'; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + mocks.getEpoch.mockReturnValue(1); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + mocks.getLatchReason.mockReturnValue(reason); + }); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); + return binding.generation; + }); + const deleteStored = vi.fn(async (): Promise => { + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(signal.aborted).toBe(true); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + }); + await withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(mocks.clearRemovedPlaygroundConnections).toHaveBeenCalledExactlyOnceWith(target); + }); + + it('clears Playground selections once per successfully deleted connection', async (): Promise => { + const targets = ['successful-removal-1', 'successful-removal-2']; + const latches = new Map(); + mocks.getEpoch.mockReturnValue(1); + mocks.getLatchReason.mockImplementation((id: string) => latches.get(id)); + mocks.latch.mockImplementation((id: string, reason: ConnectionUnavailableReason): void => { + latches.set(id, reason); + }); + mocks.getSetting.mockReturnValue('closeAll'); + const deleteStored = targets.map((_, index) => + vi.fn(async (): Promise => { + expect(mocks.clearRemovedPlaygroundConnections).toHaveBeenCalledTimes(index); + }), + ); + + await withConnectionRemoval(targets, async (remove) => { + for (const [index, target] of targets.entries()) { + await remove(target, deleteStored[index]); + } + }); + + expect(mocks.clearRemovedPlaygroundConnections.mock.calls).toEqual(targets.map((target) => [target])); + for (const storedDelete of deleteStored) { + expect(storedDelete).toHaveBeenCalledOnce(); + } + }); + + it('returns the post-Disconnect epoch only after ordinary teardown finishes', async (): Promise => { + let epoch = 7; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + const draft = register('documentView', true); + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[1]); + let finishClose!: () => void; + const closingStarted = new Promise((resolve) => { + mocks.deleteClient.mockImplementationOnce((): Promise => { + resolve(); + return new Promise((finish) => { + finishClose = finish; + }); + }); + }); + const edited = vi.fn(); + const disconnecting = ensureDisconnectedForEdit(clusterId, refreshTree); + void disconnecting.then(edited); + await closingStarted; + expect(edited).not.toHaveBeenCalled(); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + finishClose(); + await expect(disconnecting).resolves.toBe(8); + expect(showWarning).toHaveBeenNthCalledWith( + 1, + 'Disconnect?', + { + modal: true, + detail: 'You can only update credentials or the connection string while disconnected.', + }, + 'Disconnect and update', + ); + expect(refreshTree).toHaveBeenCalledOnce(); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); + }); + + it.each(['userDisconnected', 'credentialsRejected', undefined] as const)( + 'captures the edit epoch without another teardown for %s', + async (reason): Promise => { + mocks.exists.mockReturnValue(reason === 'userDisconnected'); + mocks.getLatchReason.mockReturnValue(reason); + mocks.getEpoch.mockReturnValue(7); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).resolves.toBe(7); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['connectionRemoved', 'credentialsUpdating'] as const)( + 'does not edit a %s target even without a client', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).rejects.toThrow( + 'A connection is already being updated or removed. Try again when it finishes.', + ); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts new file mode 100644 index 000000000..fa079bddf --- /dev/null +++ b/src/documentdb/connectionTeardown.ts @@ -0,0 +1,422 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + callWithTelemetryAndErrorHandling, + UserCancelledError, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { + clearRemovedPlaygroundConnections, + getPlaygroundEvaluators, + stopPlaygroundEvaluator, +} from '../commands/playground/executePlaygroundCode'; +import { SettingsService } from '../services/SettingsService'; +import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; +import { TaskService } from '../services/taskService/taskService'; +import { settingsKeys } from '../settingsKeys'; +import { clearEntraTokenFailure } from './auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from './ClustersClient'; +import { isLatestRetirement } from './connectionBindingRetirement'; +import { getConnectionSurfaces, takeConnectionSurfaces, type ConnectionSurface } from './connectionSurfaces'; +import { CredentialCache } from './CredentialCache'; +import { getRegisteredShellTerminals } from './shell/ShellTerminalLinkProvider'; + +export type TeardownReason = 'userDisconnected' | 'connectionRemoved' | 'credentialsChanged'; +export type TeardownChoice = 'close' | 'keepOpenDisabled'; + +type TeardownConfirmation = + | { + readonly outcome: 'confirmed'; + readonly choice: TeardownChoice; + readonly discardConfirmed?: ReadonlySet; + } + | { readonly outcome: 'blockedByTask' | 'cancelled' }; + +export interface TeardownOptions { + readonly reason: TeardownReason; + readonly choice: TeardownChoice; + readonly discardConfirmed?: ReadonlySet; + readonly dropCredentials?: boolean; + /** A caller that fenced a batch or a save must still hold the matching latch. */ + readonly alreadyLatched?: boolean; + readonly onRetired?: (generation: number) => void; + readonly refreshTree: () => void; +} + +function clusterIds(target: string | readonly string[]): readonly string[] { + return typeof target === 'string' ? [target] : [...new Set(target)]; +} + +function operationName(intent: TeardownReason): string { + switch (intent) { + case 'connectionRemoved': + return vscode.l10n.t('remove this connection'); + case 'credentialsChanged': + return vscode.l10n.t('update this connection'); + case 'userDisconnected': + return vscode.l10n.t('disconnect this connection'); + } +} + +function isConnectionIdle(clusterId: string): boolean { + return ( + !ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId) + ); +} + +export function canSaveEdit(clusterId: string, epoch: number): boolean { + return ( + ClustersClient.getEpoch(clusterId) === epoch && + (ClustersClient.getLatchReason(clusterId) === 'userDisconnected' || isConnectionIdle(clusterId)) + ); +} + +export async function ensureDisconnectedForEdit(clusterId: string, refreshTree: () => void): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason === 'connectionRemoved' || reason === 'credentialsUpdating') { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (TaskService.getConflictingTasks({ clusterId }).length > 0) { + await checkCanProceedAndInformUser({ clusterId }, operationName('userDisconnected')); + throw new UserCancelledError(); + } + const epoch = ClustersClient.getEpoch(clusterId); + if (canSaveEdit(clusterId, epoch)) { + return epoch; + } + + const disconnectAndUpdate = vscode.l10n.t('Disconnect and update'); + const selected = await vscode.window.showWarningMessage( + vscode.l10n.t('Disconnect?'), + { + modal: true, + detail: vscode.l10n.t('You can only update credentials or the connection string while disconnected.'), + }, + disconnectAndUpdate, + ); + if (selected !== disconnectAndUpdate || ClustersClient.getEpoch(clusterId) !== epoch) { + throw new UserCancelledError(); + } + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + if (ClustersClient.getLatchReason(clusterId) !== 'userDisconnected') { + throw new UserCancelledError(); + } + return ClustersClient.getEpoch(clusterId); +} + +/** Read-only preflight. A folder can ask once for all its descendants. */ +export async function confirmTeardown( + target: string | readonly string[], + intent: TeardownReason, +): Promise { + const ids = clusterIds(target); + for (const clusterId of ids) { + if (!(await checkCanProceedAndInformUser({ clusterId }, operationName(intent)))) { + return { outcome: 'blockedByTask' }; + } + } + + if (intent === 'credentialsChanged') { + return { outcome: 'confirmed', choice: 'keepOpenDisabled' }; + } + + const setting = SettingsService.getSetting(settingsKeys.openTabsOnDisconnect); + let choice: TeardownChoice = setting === 'keepOpenDisabled' ? 'keepOpenDisabled' : 'close'; + const closeAll = vscode.l10n.t('Close all'); + if ( + setting !== 'closeAll' && + setting !== 'keepOpenDisabled' && + ids.some((id) => getConnectionSurfaces(id).length) + ) { + const keepOpen = vscode.l10n.t('Keep open'); + const selected = await vscode.window.showWarningMessage( + intent === 'connectionRemoved' ? vscode.l10n.t('Remove the connection?') : vscode.l10n.t('Disconnect?'), + { modal: true, detail: vscode.l10n.t('What should happen to the open tabs for this connection?') }, + closeAll, + keepOpen, + ); + if (selected !== closeAll && selected !== keepOpen) { + return { outcome: 'cancelled' }; + } + choice = selected === closeAll ? 'close' : 'keepOpenDisabled'; + } + + if (choice === 'close') { + const discardConfirmed = new Set( + ids.flatMap((id) => getConnectionSurfaces(id).filter((surface) => surface.editable)), + ); + if (discardConfirmed.size > 0) { + const discard = vscode.l10n.t('Discard changes'); + const selected = await vscode.window.showWarningMessage( + vscode.l10n.t('Discard unsaved document changes?'), + { modal: true, detail: vscode.l10n.t('Closing these tabs will discard their unsaved changes.') }, + discard, + ); + if (selected !== discard) { + return { outcome: 'cancelled' }; + } + return { outcome: 'confirmed', choice, discardConfirmed }; + } + } + + return { outcome: 'confirmed', choice }; +} + +/** Check the whole batch and fence it synchronously, before any resource is changed. */ +export function latchForTeardown( + target: string | readonly string[], + reason: TeardownReason | 'credentialsUpdating', +): boolean { + const ids = clusterIds(target); + if (ids.some((clusterId) => TaskService.getConflictingTasks({ clusterId }).length > 0)) { + return false; + } + for (const clusterId of ids) { + ClustersClient.latch(clusterId, reason); + } + return true; +} + +export async function commitTeardown( + clusterId: string, + options: TeardownOptions, +): Promise<'committed' | 'blockedByTask' | 'superseded'> { + const { reason, choice, discardConfirmed, dropCredentials, alreadyLatched, onRetired, refreshTree } = options; + if (alreadyLatched) { + if (ClustersClient.getLatchReason(clusterId) !== reason) { + return 'superseded'; + } + } else { + const latch = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'userDisconnected' && + (latch === 'userDisconnected' || + latch === 'connectionRemoved' || + latch === 'credentialsUpdating' || + isConnectionIdle(clusterId)) + ) { + return 'superseded'; + } + if (!latchForTeardown(clusterId, reason)) { + await checkCanProceedAndInformUser({ clusterId }, operationName(reason)); + return 'blockedByTask'; + } + } + + try { + const generation = ClustersClient.retireBoundViews(clusterId); + const surfaces = takeConnectionSurfaces(clusterId); + onRetired?.(generation); + for (const surface of surfaces) { + if (choice === 'close' && (!surface.editable || discardConfirmed?.has(surface))) { + surface.dispose(); + } else { + surface.disable('sessionEnded'); + } + } + + for (const shell of getRegisteredShellTerminals()) { + if (shell.info.clusterId === clusterId) { + shell.disconnect?.(); + } + } + stopPlaygroundEvaluator(clusterId); + + const closing = ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + clearEntraTokenFailure(clusterId); + if (dropCredentials) { + CredentialCache.deleteCredentials(clusterId); + ClustersClient.clearLastVerifiedIdentity(clusterId); + } + await closing; + } finally { + refreshTree(); + } + return 'committed'; +} + +export async function withConnectionRemoval( + ids: readonly string[], + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, +): Promise { + await reportTeardown(ids, 'connectionRemoved', async ({ telemetry }) => { + await removeConnections(ids, remove, telemetry.properties); + }); +} + +async function removeConnections( + ids: readonly string[], + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, + properties: IActionContext['telemetry']['properties'], +): Promise { + const confirmed = await confirmTeardown(ids, 'connectionRemoved'); + if (confirmed.outcome !== 'confirmed') { + properties.blockedByTask = confirmed.outcome === 'blockedByTask' ? 'true' : 'false'; + throw new UserCancelledError(); + } + properties.surfacesChoice = confirmed.choice; + + const targets = new Map( + clusterIds(ids).map((id) => [ + id, + { + previous: ClustersClient.getLatchReason(id), + epoch: 0, + started: false, + generation: undefined as number | undefined, + }, + ]), + ); + if ( + [...targets.values()].some( + ({ previous }) => previous === 'credentialsUpdating' || previous === 'connectionRemoved', + ) + ) { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (!latchForTeardown(ids, 'connectionRemoved')) { + properties.blockedByTask = 'true'; + for (const id of targets.keys()) { + if (!(await checkCanProceedAndInformUser({ clusterId: id }, operationName('connectionRemoved')))) { + break; + } + } + throw new UserCancelledError(); + } + for (const [id, target] of targets) { + target.epoch = ClustersClient.getEpoch(id); + } + + try { + await remove(async (id, deleteStored) => { + const target = targets.get(id); + if (!target || target.started || ClustersClient.getEpoch(id) !== target.epoch) { + throw new Error(vscode.l10n.t('The connections to remove changed. Refresh the tree and try again.')); + } + target.started = true; + const result = await commitTeardown(id, { + reason: 'connectionRemoved', + choice: confirmed.choice, + discardConfirmed: confirmed.discardConfirmed, + dropCredentials: true, + alreadyLatched: true, + onRetired: (generation): void => { + target.generation = generation; + }, + refreshTree: () => {}, + }); + if (result !== 'committed' || ClustersClient.getEpoch(id) !== target.epoch) { + throw new Error(vscode.l10n.t('The connections to remove changed. Refresh the tree and try again.')); + } + await deleteStored(); + clearRemovedPlaygroundConnections(id); + targets.delete(id); + }); + } finally { + for (const [id, target] of targets) { + if ( + ClustersClient.getEpoch(id) !== target.epoch || + ClustersClient.getLatchReason(id) !== 'connectionRemoved' + ) { + continue; + } + if (target.started) { + // A failed storage delete must not leave the surviving connection locked as removed. + if (target.generation !== undefined && isLatestRetirement(id, target.generation)) { + ClustersClient.latch(id, 'userDisconnected'); + } + } else if (target.previous) { + ClustersClient.latch(id, target.previous); + } else { + ClustersClient.unlatch(id); + } + } + } +} + +async function reportTeardown( + ids: readonly string[], + reason: TeardownReason, + operation: (context: IActionContext) => Promise, +): Promise { + let cancellation: UserCancelledError | undefined; + await callWithTelemetryAndErrorHandling('connection.disconnect', async (context) => { + context.errorHandling.suppressDisplay = true; + context.errorHandling.rethrow = true; + context.telemetry.maskEntireErrorMessage = true; + context.telemetry.properties.source = { + userDisconnected: 'command', + connectionRemoved: 'remove', + credentialsChanged: 'credentialsChanged', + }[reason]; + context.telemetry.properties.surfacesChoice = 'none'; + context.telemetry.properties.blockedByTask = 'false'; + const targets = new Set(ids); + context.telemetry.measurements.surfaceCount = [...targets].reduce( + (total, id) => total + getConnectionSurfaces(id).length, + 0, + ); + context.telemetry.measurements.shellCount = getRegisteredShellTerminals().filter((shell) => + targets.has(shell.info.clusterId), + ).length; + const playgrounds = getPlaygroundEvaluators(); + context.telemetry.measurements.playgroundCount = [...targets].filter((id) => playgrounds.has(id)).length; + try { + await operation(context); + } catch (error) { + if (error instanceof UserCancelledError) { + cancellation = error; + } + throw error; + } + }); + // The telemetry wrapper records cancellation but does not propagate it, even with rethrow set. + if (cancellation) { + throw cancellation; + } +} + +/** The single-cluster confirm/commit path, with one event covering both phases. */ +export async function teardownConnection( + clusterId: string, + reason: TeardownReason, + refreshTree: () => void, +): Promise { + await reportTeardown([clusterId], reason, async (context) => { + const confirmed = await confirmTeardown(clusterId, reason); + if (confirmed.outcome !== 'confirmed') { + context.telemetry.properties.blockedByTask = confirmed.outcome === 'blockedByTask' ? 'true' : 'false'; + throw new UserCancelledError(); + } + context.telemetry.properties.surfacesChoice = confirmed.choice; + try { + const result = await commitTeardown(clusterId, { + reason, + choice: confirmed.choice, + discardConfirmed: confirmed.discardConfirmed, + dropCredentials: reason === 'connectionRemoved', + refreshTree, + }); + if (result === 'committed') { + return; + } + context.telemetry.properties.blockedByTask = result === 'blockedByTask' ? 'true' : 'false'; + } catch { + // Driver cleanup failures may contain connection details. Keep both UI and event bounded. + throw new Error(vscode.l10n.t('Could not finish closing the connection.')); + } + throw new UserCancelledError(); + }); +} diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts index 5ffacb067..224a8ac9d 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts @@ -3,9 +3,10 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type * as vscode from 'vscode'; +import { ClustersClient } from '../ClustersClient'; import { PlaygroundCodeLensProvider } from './PlaygroundCodeLensProvider'; import { PlaygroundService } from './PlaygroundService'; import { PlaygroundCommandIds } from './constants'; @@ -31,6 +32,12 @@ function mockDocument(text: string): vscode.TextDocument { describe('PlaygroundCodeLensProvider', () => { let provider: PlaygroundCodeLensProvider; let service: PlaygroundService; + let latchTestSequence = 0; + const latchedClusterIds = new Set(); + + function uniqueLatchClusterId(prefix: string): string { + return `${prefix}-${++latchTestSequence}`; + } beforeEach(() => { service = PlaygroundService.getInstance(); @@ -38,6 +45,10 @@ describe('PlaygroundCodeLensProvider', () => { }); afterEach(() => { + for (const clusterId of latchedClusterIds) { + ClustersClient.unlatch(clusterId); + } + latchedClusterIds.clear(); provider.dispose(); service.dispose(); }); @@ -67,6 +78,62 @@ describe('PlaygroundCodeLensProvider', () => { expect(connectionLens.command?.title).toContain('MyCluster / orders'); }); + it('refreshes the connection lens immediately for an explicit disconnect and unlatch', () => { + const doc = mockDocument('db.test.find({})'); + const clusterId = uniqueLatchClusterId('playground-lens-disconnect'); + const connection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + service.setConnection(doc.uri, connection); + const refreshed = vi.fn(); + provider.onDidChangeCodeLenses(refreshed); + + latchedClusterIds.add(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + expect(refreshed).toHaveBeenCalledTimes(1); + const disconnected = provider.provideCodeLenses(doc)[0]; + expect(disconnected.command).toMatchObject({ + title: '$(warning) Disconnected', + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: 'This connection is disconnected. Reconnect from the tree, then run the script again.', + }); + expect(service.getConnection(doc.uri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + + ClustersClient.unlatch(clusterId); + + expect(refreshed).toHaveBeenCalledTimes(2); + const reconnected = provider.provideCodeLenses(doc)[0]; + expect(reconnected.command).toMatchObject({ + title: '$(plug) MyCluster / orders', + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: 'Connected to MyCluster / orders', + }); + expect(service.getConnection(doc.uri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + }); + + it.each(['signInRequired', 'unreachable', 'identityChanged'] as const)( + 'keeps the normal connection lens for the %s hold', + (reason) => { + const doc = mockDocument('db.test.find({})'); + const clusterId = uniqueLatchClusterId(`playground-lens-${reason}`); + service.setConnection(doc.uri, { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }); + latchedClusterIds.add(clusterId); + + ClustersClient.latch(clusterId, reason); + + expect(provider.provideCodeLenses(doc)[0].command?.title).toBe('$(plug) MyCluster / orders'); + }, + ); + it('provides Run All lens at line 0', () => { const doc = mockDocument('db.test.find({})'); const lenses = provider.provideCodeLenses(doc); diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.ts index d9d8aa85b..d26f1c527 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.ts @@ -66,7 +66,17 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco // 1. Connection status lens const displayName = service.getDisplayName(document.uri); - if (displayName) { + if (service.isUserDisconnected(document.uri)) { + lenses.push( + new vscode.CodeLens(topRange, { + title: `$(warning) ${l10n.t('Disconnected')}`, + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: l10n.t( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ), + }), + ); + } else if (displayName) { lenses.push( new vscode.CodeLens(topRange, { title: `$(plug) ${displayName}`, diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index 8acfe4746..8b2a4e01e 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -3,9 +3,14 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; -import { type callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { + UserCancelledError, + type callWithTelemetryAndErrorHandling, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; import { Int32 } from 'bson'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; @@ -23,10 +28,18 @@ import { resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; import { type getManagedIdentityAccessToken } from '../auth/managedIdentityTokenProvider'; +import { ClustersClient } from '../ClustersClient'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; import { type CachedClusterCredentials } from '../CredentialCache'; import { PlaygroundEvaluator } from './PlaygroundEvaluator'; +import { type PlaygroundWorkerBinding } from './types'; import { type WorkerSessionCallbacks } from './WorkerSessionManager'; -import { type MainToWorkerMessage, type SerializableExecutionResult, type WorkerToMainMessage } from './workerTypes'; +import { + getWorkerAuthReason, + type MainToWorkerMessage, + type SerializableExecutionResult, + type WorkerToMainMessage, +} from './workerTypes'; type InitMessage = Extract; type TokenRequest = Extract; @@ -37,18 +50,24 @@ const mocks = vi.hoisted(() => ({ interactiveToken: vi.fn< ( - scopes?: string | string[], - tenantId?: string, + provider: string, + scopes: readonly string[], options?: vscode.AuthenticationGetSessionOptions, ) => Promise >(), + configuredProvider: vi.fn<() => string>(), managedIdentityToken: vi.fn(), resolveInteractive: vi.fn(), resolveManagedIdentity: vi.fn(), callbacks: undefined as WorkerSessionCallbacks | undefined, initMessage: undefined as InitMessage | undefined, clusterId: undefined as string | undefined, - sendEval: vi.fn<() => Promise<{ result: SerializableExecutionResult }>>(), + startup: vi.fn<() => Promise>(), + worker: { + isConnectedTo: vi.fn<(clusterId: string) => boolean>(), + sendEval: vi.fn<(message: MainToWorkerMessage) => Promise<{ result: SerializableExecutionResult }>>(), + killWorker: vi.fn(), + }, })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -82,8 +101,15 @@ vi.mock('../CredentialCache', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: mocks.interactiveToken, +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getConfiguredAuthProviderId: mocks.configuredProvider, + getConfiguredAzureEnv: () => ({ name: 'AzureCloud' }), +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: mocks.interactiveToken }, })); vi.mock('../auth/managedIdentityTokenProvider', () => ({ @@ -100,15 +126,16 @@ vi.mock('./WorkerSessionManager', () => ({ WorkerSessionManager: vi.fn().mockImplementation(function (callbacks: WorkerSessionCallbacks) { mocks.callbacks = callbacks; return { - isConnectedTo: vi.fn(() => false), + ...mocks.worker, ensureWorker: vi.fn(async (clusterId: string, initMessage: InitMessage): Promise => { mocks.clusterId = clusterId; mocks.initMessage = initMessage; + await mocks.startup(); }), get workerClusterId(): string | undefined { return mocks.clusterId; }, - sendEval: mocks.sendEval, + shutdown: vi.fn(), dispose: vi.fn(), }; }), @@ -139,7 +166,10 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.callbacks = undefined; mocks.initMessage = undefined; mocks.clusterId = undefined; - mocks.sendEval.mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); + mocks.startup.mockReset(); + mocks.configuredProvider.mockReturnValue('microsoft'); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.worker.sendEval.mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); customSuffix = undefined; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn((_key: string, defaultValue: unknown): unknown => defaultValue), @@ -180,7 +210,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { if (!init) { throw new Error('Expected the evaluator to initialize its worker'); } - expect(mocks.getCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.getCredentials).toHaveBeenCalledWith(clusterId); // Token relays must never consult credentials changed since worker initialization. mocks.getCredentials.mockClear().mockImplementation((): never => { throw new Error('Live credential-cache reads are forbidden during token relay'); @@ -211,6 +241,346 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(mocks.managedIdentityToken).not.toHaveBeenCalled(); } + const connection = { clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }; + const learnedIdentity = { + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'private-account', + accountLabel, + } as const; + + function configureEntraStartup(): void { + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: learnedIdentity.tenantId }, + }); + } + + it('retains the first relay pin on startup failure without running the query', async (): Promise => { + const failure = new Error('database startup failed'); + const capture = vi.fn<(binding: PlaygroundWorkerBinding) => void>(); + configureEntraStartup(); + mocks.startup.mockImplementationOnce(async () => { + const response = await requestToken({ type: 'tokenRequest', requestId: 'startup' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + throw failure; + }); + + try { + await expect(evaluator.evaluate(connection, 'first Run', undefined, capture)).rejects.toBe(failure); + expect(capture).toHaveBeenCalledExactlyOnceWith({ + fingerprint: computeConnectionFingerprint({ + connectionString: originalConnection, + principal: learnedIdentity, + }), + entraIdentity: learnedIdentity, + }); + + evaluator.dispose(); + evaluator = new PlaygroundEvaluator(); + const verified = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue({ + ...learnedIdentity, + accountId: 'different-account', + }); + try { + await expect( + evaluator.evaluate({ ...connection, ...capture.mock.calls[0][0] }, 'next Run'), + ).rejects.toMatchObject({ reason: 'credentialsChanged' }); + } finally { + verified.mockRestore(); + } + expect(mocks.worker.sendEval).not.toHaveBeenCalled(); + } finally { + mocks.getCredentials.mockClear(); + } + }); + + it.each(['relay replaced', 'epoch changed', 'latched', 'cancelled'] as const)( + 'does not capture a learned pin on startup failure after %s', + async (invalidation): Promise => { + const failure = + invalidation === 'cancelled' ? new UserCancelledError('workerStartup') : new Error('startup failed'); + const capture = vi.fn(); + configureEntraStartup(); + const latch = vi.spyOn(ClustersClient, 'getLatchReason'); + mocks.startup.mockImplementationOnce(async () => { + const response = await requestToken({ type: 'tokenRequest', requestId: 'startup' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + if (invalidation === 'relay replaced') { + evaluator.killWorker(); + } else if (invalidation === 'epoch changed') { + ClustersClient.invalidate(clusterId); + } else if (invalidation === 'latched') { + latch.mockReturnValue('userDisconnected'); + } + throw failure; + }); + + try { + await expect(evaluator.evaluate(connection, 'first Run', undefined, capture)).rejects.toBe(failure); + expect(capture).not.toHaveBeenCalled(); + expect(mocks.worker.sendEval).not.toHaveBeenCalled(); + } finally { + mocks.getCredentials.mockClear(); + latch.mockRestore(); + } + }, + ); + + it('uses a verified cluster identity silently on the first relay', async (): Promise => { + const verified = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue({ + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'private-account', + accountLabel, + }); + try { + await initializeSession(AuthMethodId.MicrosoftEntraID); + const response = await requestToken({ type: 'tokenRequest', requestId: 'first-silent' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + expect(mocks.interactiveToken).toHaveBeenCalledExactlyOnceWith( + 'microsoft', + [resolution.scope, 'VSCODE_TENANT:interactive-tenant'], + { silent: true, account: { id: 'private-account', label: accountLabel } }, + ); + } finally { + verified.mockRestore(); + } + }); + + it('fails closed for a changed account or provider and does not return either token', async (): Promise => { + await initializeSession(AuthMethodId.MicrosoftEntraID); + await requestToken({ type: 'tokenRequest', requestId: 'first' }); + mocks.interactiveToken.mockResolvedValueOnce({ + id: 'other-session', + account: { id: 'other-account', label: 'other-account' }, + scopes: [resolution.scope], + accessToken: 'other-token', + }); + const mismatch = await requestToken({ type: 'tokenRequest', requestId: 'different-account' }); + expect(mismatch).toHaveBeenCalledWith( + expect.objectContaining({ type: 'tokenError', reason: 'identityMismatch' }), + ); + mocks.configuredProvider.mockReturnValue('microsoft-sovereign-cloud'); + const changed = await requestToken({ type: 'tokenRequest', requestId: 'different-provider' }); + expect(changed).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError', reason: 'signInRequired' })); + expect(mocks.interactiveToken).toHaveBeenCalledTimes(2); + expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); + }); + + it('checks a document fingerprint on warm runs without consulting the credentials cache', async (): Promise => { + await initializeSession(AuthMethodId.NoAuth); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + await evaluator.evaluate({ ...connection, ...binding }, '3'); + await expect(evaluator.evaluate({ ...connection, fingerprint: 'old-binding' }, '4')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expect(mocks.worker.sendEval).toHaveBeenCalledTimes(3); + }); + + it('rejects a latched Run or an old document binding after evaluator recreation', async (): Promise => { + await initializeSession(AuthMethodId.NoAuth); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '1', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + const oldDocument = { ...connection, ...binding }; + evaluator.dispose(); + evaluator = new PlaygroundEvaluator(); + mocks.worker.isConnectedTo.mockReturnValue(false); + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(evaluator.evaluate(oldDocument, '2')).rejects.toMatchObject({ reason: 'userDisconnected' }); + } finally { + ClustersClient.unlatch(clusterId); + } + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: 'mongodb://other.example.com/', + authMechanism: AuthMethodId.NoAuth, + }); + await evaluator.evaluate(connection, '3'); + mocks.worker.isConnectedTo.mockReturnValue(true); + await expect(evaluator.evaluate(oldDocument, '4')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + mocks.getCredentials.mockClear(); + }); + + it('lets a re-picked document replace one failed worker without moving its old identity', async (): Promise => { + const oldIdentity = { + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'account-a', + accountLabel: 'Account A', + } as const; + const newIdentity = { + ...oldIdentity, + accountId: 'account-b', + accountLabel: 'Account B', + } as const; + const identity = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(oldIdentity); + try { + await initializeSession(AuthMethodId.MicrosoftEntraID); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const oldBinding = { + ...connection, + ...(capture.mock.calls[0][0] as { fingerprint: string; entraIdentity?: typeof oldIdentity }), + }; + mocks.worker.sendEval.mockRejectedValueOnce( + Object.assign(new Error('sign in required'), { name: 'EntraSignInRequiredError' }), + ); + await expect(evaluator.evaluate(oldBinding, 'failed')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); + + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: 'interactive-tenant' }, + }); + identity.mockReturnValue(newIdentity); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId, + fingerprint: 'fingerprint-b', + generation: 2, + }); + const expected = vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue('fingerprint-b'); + + await expect(evaluator.evaluate(oldBinding, 'old-document')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + const replacement = { fingerprint: 'fingerprint-b' }; + const repicked = { + ...connection, + fingerprint: 'fingerprint-b', + entraIdentity: newIdentity, + workerReplacement: replacement, + }; + await evaluator.evaluate(repicked, 'replacement'); + await expect(evaluator.evaluate(oldBinding, 'still-old')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + mocks.worker.sendEval.mockRejectedValueOnce( + Object.assign(new Error('sign in required again'), { name: 'EntraSignInRequiredError' }), + ); + await expect(evaluator.evaluate(repicked, 'second-failure')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); + await expect(evaluator.evaluate(repicked, 'already-consumed')).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + }); + expect(expected).toHaveBeenCalled(); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', '2', 'failed', 'replacement', 'second-failure']); + mocks.getCredentials.mockClear(); + } finally { + vi.restoreAllMocks(); + } + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( + 'restarts %s at the next Run after refresh fails, without replaying the failed query', + async (authMechanism): Promise => { + await initializeSession(authMechanism); + await requestToken({ type: 'tokenRequest', requestId: 'first' }); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + const bound = { ...connection, ...binding }; + const failure = new Error('outer driver error', { + cause: Object.assign(new Error('private broker'), { name: 'TokenCallbackError' }), + }); + mocks.worker.sendEval.mockRejectedValueOnce(failure); + await expect(evaluator.evaluate(bound, 'failed')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'refreshFailed', + ); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism, + entraIdConfig: { tenantId: 'interactive-tenant' }, + managedIdentityConfig: { tenantId: 'managed-tenant', clientId: 'managed-client' }, + }); + await evaluator.evaluate(bound, 'next'); + mocks.worker.isConnectedTo.mockReturnValue(true); + mocks.getCredentials.mockClear(); + await evaluator.evaluate(bound, 'after'); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', '2', 'failed', 'next', 'after']); + }, + ); + + it('does not replay or rebind an old evaluation after Disconnect replaces its worker', async (): Promise => { + await initializeSession(AuthMethodId.MicrosoftEntraID); + await requestToken({ type: 'tokenRequest', requestId: 'pin' }); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, 'bind', undefined, capture); + const binding = capture.mock.calls[0][0] as PlaygroundWorkerBinding; + const bound = { ...connection, ...binding }; + + let rejectOld!: (error: Error) => void; + mocks.worker.sendEval.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectOld = reject; + }), + ); + const oldRun = evaluator.evaluate(bound, 'old'); + const oldOutcome = expect(oldRun).rejects.toThrow('Worker terminated'); + await vi.waitFor(() => + expect(mocks.worker.sendEval.mock.calls.at(-1)?.[0]).toMatchObject({ type: 'eval', code: 'old' }), + ); + + try { + ClustersClient.latch(clusterId, 'userDisconnected'); + evaluator.killWorker(); + ClustersClient.unlatch(clusterId); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: 'interactive-tenant' }, + }); + await evaluator.evaluate(bound, 'new'); + mocks.worker.isConnectedTo.mockReturnValue(true); + + rejectOld(new Error('Worker terminated')); + await oldOutcome; + const response = await requestToken({ type: 'tokenRequest', requestId: 'replacement-token' }); + expect(response).toHaveBeenCalledExactlyOnceWith({ + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken, + }); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', 'bind', 'old', 'new']); + expect(mocks.interactiveToken.mock.calls.at(-1)?.[2]).toEqual({ + silent: true, + account: { id: 'private-account', label: accountLabel }, + }); + } finally { + ClustersClient.unlatch(clusterId); + mocks.getCredentials.mockClear(); + } + }); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'uses the captured %s identity and original connection despite forged request fields', async (authMethod): Promise => { @@ -250,9 +620,12 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(mocks.resolveManagedIdentity).not.toHaveBeenCalled(); expect(mocks.managedIdentityToken).not.toHaveBeenCalled(); expect(mocks.interactiveToken).toHaveBeenCalledTimes(2); - for (const call of mocks.interactiveToken.mock.calls) { - expect(call).toEqual([[resolution.scope], init.tenantId, { createIfNone: true }]); - } + const scopes = [resolution.scope, `VSCODE_TENANT:${init.tenantId}`]; + expect(mocks.interactiveToken).toHaveBeenNthCalledWith(1, 'microsoft', scopes, { createIfNone: true }); + expect(mocks.interactiveToken).toHaveBeenNthCalledWith(2, 'microsoft', scopes, { + silent: true, + account: { id: 'private-account', label: accountLabel }, + }); } expect(response).toHaveBeenCalledExactlyOnceWith({ type: 'tokenResponse', @@ -294,6 +667,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'refresh', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); const output = JSON.stringify([ response.mock.calls, @@ -349,6 +723,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'pending', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); @@ -383,7 +758,8 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(response).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'native', - error: 'No credentials found for the query playground connection.', + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); }); @@ -403,6 +779,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'rejected', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); }, ); @@ -438,7 +815,7 @@ describe('PlaygroundEvaluator result deserialization', () => { ] satisfies readonly (readonly [SerializableExecutionResult, unknown, boolean | undefined])[])( 'copies the worker undefined flag without changing printable for %j', async (serialized, printable, printableIsUndefined) => { - mocks.sendEval.mockResolvedValue({ result: serialized }); + mocks.worker.sendEval.mockResolvedValue({ result: serialized }); const result = await evaluator.evaluate( { clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }, diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index f3b2cd9a2..b98cef318 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; +import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; // Static or `await import('bson')`, this is the driver's CommonJS copy: vite.config.ext.mjs and // vitest.config.ts alias `bson` to it. Without the alias an ES-module importer gets bson's ESM @@ -14,24 +14,27 @@ import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { meterSilentCatch } from '../../utils/accumulatingTelemetry'; -import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; -import { AuthMethodId } from '../auth/AuthMethod'; -import { - resolveInteractiveTokenResource, - resolveManagedIdentityTokenResource, - TokenResourceResolutionError, - type ResolvedTokenResource, -} from '../auth/documentdbTokenResource'; -import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; -import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; -import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; +import { AuthMethodId } from '../auth/AuthMethodId'; +import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; -import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; +import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; +import { addDomainInfoToProperties } from '../utils/getClusterMetadata'; import { resolveAllowInvalidCertificates } from '../utils/tlsException'; -import { type ExecutionResult, type PlaygroundConnection } from './types'; +import { type ExecutionResult, type PlaygroundConnection, type PlaygroundWorkerBinding } from './types'; import { WorkerSessionManager } from './WorkerSessionManager'; -import { type MainToWorkerMessage, type SerializableMongoClientOptions, type WorkerToMainMessage } from './workerTypes'; +import { + getWorkerAuthReason, + type MainToWorkerMessage, + type SerializableMongoClientOptions, + type WorkerAuthReason, +} from './workerTypes'; + +const consumedWorkerReplacements = new WeakSet(); /** * Evaluates query playground code in a persistent worker thread. @@ -78,7 +81,12 @@ import { type MainToWorkerMessage, type SerializableMongoClientOptions, type Wor export class PlaygroundEvaluator implements vscode.Disposable { private readonly _workerManager: WorkerSessionManager; private _sessionInitMessage: Extract | undefined; - private _resolvedTokenResource: ResolvedTokenResource | undefined; + private _relay: WorkerTokenRelay | undefined; + /** A worker snapshot, not a document binding. */ + private _workerFingerprint: string | undefined; + private _pinContext: { clusterId: string; identity: VerifiedEntraIdentity } | undefined; + private _authFailure: { clusterId: string; reason: WorkerAuthReason } | undefined; + private _disposed = false; /** * Telemetry session ID — generated on worker spawn, stable across evals within the @@ -92,6 +100,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { /** Auth mechanism used for the current worker session (for telemetry). */ private _sessionAuthMethod: string | undefined; + private _sessionDomainProperties: Record | undefined; /** Telemetry accessors — read by the command layer for telemetry properties. */ get sessionId(): string | undefined { @@ -103,6 +112,9 @@ export class PlaygroundEvaluator implements vscode.Disposable { get sessionAuthMethod(): string | undefined { return this._sessionAuthMethod; } + get sessionDomainProperties(): Readonly> | undefined { + return this._sessionDomainProperties; + } /** Duration of the last worker init (spawn + auth), in ms. 0 if worker was already alive. */ private _lastInitDurationMs: number = 0; @@ -162,13 +174,17 @@ export class PlaygroundEvaluator implements vscode.Disposable { break; } }, - onTokenRequest: ( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ) => this.handleTokenRequest(msg, postResponse, isCurrent, timings, traceContext), + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { + const relay = this._relay; + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + ); + }, onWorkerExit: (exitCode: number) => { ext.outputChannel.debug(`${logPrefix} Worker exited with code ${String(exitCode)}`); this.resetSession(); @@ -188,28 +204,114 @@ export class PlaygroundEvaluator implements vscode.Disposable { connection: PlaygroundConnection, code: string, onProgress?: (message: string) => void, + onFirstBinding?: (binding: PlaygroundWorkerBinding) => void, ): Promise { - // Ensure worker is alive and connected to the right cluster - const needsSpawn = !this._workerManager.isConnectedTo(connection.clusterId); - if (needsSpawn) { - onProgress?.(l10n.t('Initializing…')); - ext.outputChannel?.trace( - `[PlaygroundEvaluator] Spawning new worker for cluster=${connection.clusterId}, db=${connection.databaseName}`, - ); + const { clusterId, fingerprint } = connection; + this.assertConnectionAvailable(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const sameCluster = this._workerManager.isConnectedTo(clusterId); + const pin = this._pinContext?.clusterId === clusterId ? this._pinContext.identity : undefined; + const verified = ClustersClient.getLastVerifiedIdentity(clusterId); + const entraPin = verified?.kind === 'entra' ? verified : undefined; + const reason = + (this._authFailure?.clusterId === clusterId ? this._authFailure.reason : undefined) ?? + (sameCluster ? this._workerManager.authFailure : undefined); + const replacement = connection.workerReplacement; + let replaceFailedWorker = false; + let replacementFingerprint: string | undefined; + if ( + replacement && + !consumedWorkerReplacements.has(replacement) && + replacement.fingerprint === fingerprint && + (reason === 'signInRequired' || reason === 'identityMismatch') + ) { + replacementFingerprint = ClustersClient.getExpectedFingerprint(clusterId, connection.entraIdentity); + const currentFingerprint = ClustersClient.getBinding(clusterId)?.fingerprint; + if ( + replacementFingerprint === undefined || + fingerprint !== replacementFingerprint || + (currentFingerprint !== undefined && currentFingerprint !== fingerprint) + ) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + replaceFailedWorker = true; } + if (sameCluster && this._relay?.epoch === epoch) { + const currentFingerprint = ClustersClient.getBinding(clusterId)?.fingerprint; + if ( + (fingerprint !== undefined && + ((!replaceFailedWorker && fingerprint !== this._workerFingerprint) || + (currentFingerprint !== undefined && fingerprint !== currentFingerprint))) || + (!replaceFailedWorker && pin && entraPin && !sameEntraIdentity(pin, entraPin)) + ) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + } + if ( + !replaceFailedWorker && + (pin || fingerprint) && + (reason === 'signInRequired' || reason === 'identityMismatch') + ) { + throw createWorkerAuthError(reason); + } + if (replaceFailedWorker && replacement) { + consumedWorkerReplacements.add(replacement); + } + const needsSpawn = replaceFailedWorker || !sameCluster || !!reason || this._relay?.epoch !== epoch; const initStartTime = Date.now(); - const initMsg = this.buildInitMessage(connection); - - // Start a new telemetry session if we're spawning a new worker - if (needsSpawn) { + let learnedBinding: PlaygroundWorkerBinding | undefined; + let initMsg: Extract; + if (needsSpawn || !this._sessionInitMessage) { + onProgress?.(l10n.t('Initializing…')); + this.assertConnectionAvailable(clusterId); + const pinned = connection.entraIdentity ?? pin; + const expected = replacementFingerprint ?? ClustersClient.getExpectedFingerprint(clusterId, pinned); + if (fingerprint !== undefined && fingerprint !== expected) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (pin && entraPin && !sameEntraIdentity(pin, entraPin) && !fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + initMsg = this.buildInitMessage(connection); + if (this._workerManager.isAlive || this._workerManager.workerState === 'spawning') { + this._workerManager.killWorker(); + } + this.resetSession(); + const workerPin = initMsg.authMechanism === 'MicrosoftEntraID' ? (entraPin ?? pinned) : undefined; + this._pinContext = workerPin && { clusterId, identity: workerPin }; this._sessionInitMessage = initMsg; - this._resolvedTokenResource = undefined; + this._workerFingerprint = expected; this._sessionId = randomUUID(); - this._sessionEvalCount = 0; this._sessionAuthMethod = initMsg.authMechanism; + this._sessionDomainProperties = {}; + const originalUri = initMsg.connectionString; + try { + addDomainInfoToProperties(getHostsFromConnectionString(originalUri), this._sessionDomainProperties); + } catch { + meterSilentCatch('PlaygroundEvaluator_domainInfo'); + } + this._relay = new WorkerTokenRelay(clusterId, initMsg, epoch, this._sessionId, workerPin, (identity) => { + this._pinContext = { clusterId, identity }; + // Like the document binding, this keyed fingerprint is only compared in the host. + this._workerFingerprint = computeConnectionFingerprint({ + connectionString: originalUri, + principal: identity, + }); + learnedBinding = { fingerprint: this._workerFingerprint, entraIdentity: identity }; + }); + } else { + initMsg = this._sessionInitMessage; } + const relay = this._relay; + const isCurrentRelay = (): boolean => relay === this._relay && epoch === ClustersClient.getEpoch(clusterId); + const assertCurrent = (): void => { + this.assertConnectionAvailable(clusterId); + if (!isCurrentRelay()) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + }; onProgress?.(l10n.t('Authenticating…')); let originalFailure: { error: unknown } | undefined; try { @@ -219,7 +321,8 @@ export class PlaygroundEvaluator implements vscode.Disposable { context.telemetry.properties.authMethod = initMsg.authMechanism; context.telemetry.properties.needsSpawn = needsSpawn ? 'true' : 'false'; try { - await this._workerManager.ensureWorker(connection.clusterId, initMsg, getConnectionTimeoutMs(), { + assertCurrent(); + await this._workerManager.ensureWorker(clusterId, initMsg, getConnectionTimeoutMs(), { sessionId: this._sessionId, }); } catch (error) { @@ -228,12 +331,29 @@ export class PlaygroundEvaluator implements vscode.Disposable { } }); } catch (error) { - throw originalFailure ? originalFailure.error : error; + originalFailure ??= { error }; } // The telemetry wrapper swallows cancellation even when rethrow is enabled. if (originalFailure) { + this.recordWorkerFailure(clusterId, relay, originalFailure.error); + // Startup can fail after sign-in; keep the document pinned without replaying its query. + if ( + learnedBinding && + fingerprint === undefined && + !(originalFailure.error instanceof UserCancelledError) && + isCurrentRelay() && + !this._disposed && + !ClustersClient.getLatchReason(clusterId) + ) { + onFirstBinding?.(learnedBinding); + } throw originalFailure.error; } + assertCurrent(); + this._authFailure = undefined; + if (fingerprint === undefined && this._workerFingerprint !== undefined) { + onFirstBinding?.({ fingerprint: this._workerFingerprint, entraIdentity: this._pinContext?.identity }); + } this._lastInitDurationMs = needsSpawn ? Date.now() - initStartTime : 0; // Reset console output counter for this eval run @@ -241,6 +361,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { // Send eval message and await result onProgress?.(l10n.t('Running query…')); + assertCurrent(); this._sessionEvalCount++; @@ -252,8 +373,13 @@ export class PlaygroundEvaluator implements vscode.Disposable { displayBatchSize: getBatchSizeSetting(), }; - const workerResult = await this._workerManager.sendEval(evalMsg); - return this.deserializeResult(workerResult.result); + try { + const workerResult = await this._workerManager.sendEval(evalMsg); + return this.deserializeResult(workerResult.result); + } catch (error) { + this.recordWorkerFailure(clusterId, relay, error); + throw error; + } } /** @@ -262,8 +388,10 @@ export class PlaygroundEvaluator implements vscode.Disposable { */ async shutdown(): Promise { ext.outputChannel?.trace('[PlaygroundEvaluator] Shutting down worker'); - await this._workerManager.shutdown(); this.resetSession(); + this._pinContext = undefined; + this._authFailure = undefined; + await this._workerManager.shutdown(); } /** @@ -271,13 +399,40 @@ export class PlaygroundEvaluator implements vscode.Disposable { * Used for infinite loop recovery (timeout) and cancellation. */ killWorker(): void { + const clusterId = this._workerManager.workerClusterId; + const reason = this._workerManager.authFailure; + if (clusterId && reason) { + this._authFailure ??= { clusterId, reason }; + } this._workerManager.killWorker(); this.resetSession(); } dispose(): void { + this._disposed = true; this._workerManager.dispose(); this.resetSession(); + this._pinContext = undefined; + this._authFailure = undefined; + } + + private assertConnectionAvailable(clusterId: string): void { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason || this._disposed) { + throw new ConnectionUnavailableError(reason ?? 'connectionRemoved'); + } + } + + private recordWorkerFailure(clusterId: string, relay: WorkerTokenRelay | undefined, error: unknown): void { + const reason = getWorkerAuthReason(error); + if ( + reason && + relay === this._relay && + relay?.epoch === ClustersClient.getEpoch(clusterId) && + !ClustersClient.getLatchReason(clusterId) + ) { + this._authFailure = { clusterId, reason }; + } } // ─── Private: Init message ─────────────────────────────────────────────── @@ -376,153 +531,6 @@ export class PlaygroundEvaluator implements vscode.Disposable { }; } - // ─── Private: Token handling ───────────────────────────────────────────── - - /** - * Handle a token request from the worker (Entra ID OIDC). - * Token acquisition stays on the main thread so there is one credential and one cache per window. - */ - private async handleTokenRequest( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ): Promise { - try { - const clusterId = this._workerManager.workerClusterId; - const sessionInit = this._sessionInitMessage; - if ( - !clusterId || - !sessionInit || - (sessionInit.authMechanism !== 'MicrosoftEntraID' && sessionInit.authMechanism !== 'ManagedIdentity') - ) { - throw new Error(l10n.t('No credentials found for the query playground connection.')); - } - if (!isCurrent()) { - return; - } - const connectionString = sessionInit.connectionString; - const decision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(decision, msg.requestId, traceContext); - if (!decision.allowed) { - throw new EntraDestinationRejectedError(decision); - } - const usesManagedIdentity = sessionInit.authMechanism === 'ManagedIdentity'; - let resolved: ResolvedTokenResource; - try { - resolved = - this._resolvedTokenResource ?? - (usesManagedIdentity - ? await resolveManagedIdentityTokenResource(connectionString) - : await resolveInteractiveTokenResource(connectionString)); - if (isCurrent()) { - this._resolvedTokenResource = resolved; - } - traceAuthFlow('entraCloud.resolved', resolved.details, msg.requestId, traceContext); - } catch (error) { - if (error instanceof TokenResourceResolutionError) { - traceAuthFlow('entraCloud.unresolved', error.details, msg.requestId, traceContext); - } - throw error; - } - let accessToken: string; - - if (usesManagedIdentity) { - const { getManagedIdentityAccessToken } = await import('../auth/managedIdentityTokenProvider'); - this._sessionId ??= randomUUID(); - try { - accessToken = ( - await withTokenAcquisitionTiming(timings, () => - getManagedIdentityAccessToken( - [resolved.scope], - sessionInit.managedIdentityClientId, - sessionInit.tenantId, - this._sessionId, - traceContext, - ), - ) - ).accessToken; - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'managedIdentity', - }); - } - throw error; - } - } else { - const { getSessionFromVSCode } = await import( - // eslint-disable-next-line import/no-internal-modules - '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode' - ); - let session: vscode.AuthenticationSession | undefined; - try { - session = await traceAuthOperation( - 'interactiveEntra.getSession', - () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode([resolved.scope], sessionInit.tenantId, { createIfNone: true }), - ), - { - tenantSpecified: !!sessionInit.tenantId, - createIfNone: true, - cloudCategory: resolved.cloudCategory, - tokenResourceReason: resolved.reason, - }, - msg.requestId, - traceContext, - ); - - if (!session) { - throw new Error(l10n.t('Failed to obtain Entra ID token.')); - } - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'interactive', - }); - } - throw error; - } - - accessToken = session.accessToken; - } - - const currentDecision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(currentDecision, msg.requestId, traceContext); - if (!currentDecision.allowed) { - throw new EntraDestinationRejectedError(currentDecision); - } - if (isCurrent()) { - clearEntraTokenFailure(clusterId); - } - postResponse({ - type: 'tokenResponse', - requestId: msg.requestId, - accessToken, - }); - } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : String(error); - postResponse({ - type: 'tokenError', - requestId: msg.requestId, - error: errorMessage, - ...(error instanceof EntraDestinationRejectedError - ? { errorName: 'EntraDestinationRejectedError' as const } - : {}), - }); - } - } - // ─── Private: Session telemetry ────────────────────────────────────────── private resetSession(): void { @@ -538,7 +546,9 @@ export class PlaygroundEvaluator implements vscode.Disposable { } this._sessionInitMessage = undefined; - this._resolvedTokenResource = undefined; + this._sessionDomainProperties = undefined; + this._relay = undefined; + this._workerFingerprint = undefined; this._sessionId = undefined; this._sessionEvalCount = 0; this._sessionAuthMethod = undefined; diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index 52b844379..868587a0a 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -11,7 +11,9 @@ import { type PlaygroundConnection } from './types'; // Access the vscode mock (aliased to test/vitest/vscode.ts) import * as vscode from 'vscode'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; +import { PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './constants'; vi.mock('../CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn() }, @@ -21,16 +23,43 @@ const hasCredentialsMock = CredentialCache.hasCredentials as Mock; describe('PlaygroundService', () => { let service: PlaygroundService; + let latchTestSequence = 0; + const latchedClusterIds = new Set(); const mockUri = { toString: () => 'untitled:playground-1.documentdb.js' } as vscode.Uri; + function latch(clusterId: string, reason: Parameters[1]): void { + latchedClusterIds.add(clusterId); + ClustersClient.latch(clusterId, reason); + } + + function uniqueLatchClusterId(prefix: string): string { + return `${prefix}-${++latchTestSequence}`; + } + + function getCloseDocHandler(): (doc: Partial) => void { + const calls = vi.mocked(vscode.workspace.onDidCloseTextDocument).mock.calls; + return calls[calls.length - 1][0]; + } + + function getOpenDocHandler(): (doc: Partial) => void { + const calls = vi.mocked(vscode.workspace.onDidOpenTextDocument).mock.calls; + return calls[calls.length - 1][0]; + } + beforeEach(() => { // Reset singleton between tests service = PlaygroundService.getInstance(); }); afterEach(() => { + for (const clusterId of latchedClusterIds) { + ClustersClient.unlatch(clusterId); + } + latchedClusterIds.clear(); service.dispose(); + Object.assign(vscode.window, { activeTextEditor: undefined }); + vi.restoreAllMocks(); }); describe('singleton', () => { @@ -78,6 +107,48 @@ describe('PlaygroundService', () => { expect(service.getConnection(mockUri)).toBeUndefined(); }); + it('clears only removed-cluster selections and remembered bindings with one state change', () => { + const matchingUri = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; + const otherUri = { toString: () => 'untitled:playground-3.documentdb.js' } as vscode.Uri; + const otherConnection: PlaygroundConnection = { + clusterId: 'cluster-456', + clusterDisplayName: 'OtherCluster', + databaseName: 'products', + }; + const doc = { + uri: mockUri, + languageId: PLAYGROUND_LANGUAGE_ID, + getText: () => 'db.orders.find({})', + } as vscode.TextDocument; + Object.assign(vscode.window, { activeTextEditor: { document: doc } as vscode.TextEditor }); + service.setConnection(mockUri, connection); + service.setConnection(matchingUri, connection); + service.setConnection(otherUri, otherConnection); + getCloseDocHandler()({ uri: matchingUri, languageId: PLAYGROUND_LANGUAGE_ID }); + const listener = vi.fn(); + service.onDidChangeState(listener); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + hasCredentialsMock.mockReturnValue(true); + hasCredentialsMock.mockClear(); + + service.removeConnectionsForCluster(connection.clusterId); + + expect(service.getConnection(mockUri)).toBeUndefined(); + expect(service.getConnection(matchingUri)).toBeUndefined(); + expect(service.getConnection(otherUri)).toBe(otherConnection); + expect(listener).toHaveBeenCalledTimes(1); + expect(statusBar.command).toBe(PlaygroundCommandIds.connect); + expect(statusBar.text).toBe('$(warning) Connect database'); + expect(statusBar.tooltip).toBe('This playground has no connection. Click to connect it to a database.'); + expect(doc.getText()).toBe('db.orders.find({})'); + + getOpenDocHandler()({ uri: matchingUri, languageId: PLAYGROUND_LANGUAGE_ID }); + + expect(service.getConnection(matchingUri)).toBeUndefined(); + expect(hasCredentialsMock).not.toHaveBeenCalled(); + }); + it('fires onDidChangeState on setConnection', () => { const listener = vi.fn(); service.onDidChangeState(listener); @@ -110,6 +181,72 @@ describe('PlaygroundService', () => { expect(service.getDisplayName(uri2)).toBe('OtherCluster / products'); }); + it('captures the host binding when a tree selection is bound', () => { + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + } as const; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId: connection.clusterId, + fingerprint: 'fingerprint', + generation: 1, + }); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(identity); + + const bound = service.setConnectionFromHost(mockUri, connection); + + expect(bound).toEqual({ + ...connection, + fingerprint: 'fingerprint', + entraIdentity: identity, + }); + expect(service.getConnection(mockUri)).toBe(bound); + }); + + it('marks only the explicitly re-picked document for one failed-worker replacement', () => { + const uri2 = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId: connection.clusterId, + fingerprint: 'new-fingerprint', + generation: 2, + }); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(undefined); + service.setConnection(mockUri, connection); + service.setConnection(uri2, connection); + + const repicked = service.setConnectionFromHost(mockUri, { + ...connection, + databaseName: 'replacement', + }); + + expect(repicked.workerReplacement).toEqual({ fingerprint: 'new-fingerprint' }); + expect(service.getConnection(uri2)).toEqual({ + ...connection, + fingerprint: 'new-fingerprint', + }); + expect(service.getConnection(uri2)?.workerReplacement).toBeUndefined(); + }); + + it('captures a worker binding only while the original document binding is current', () => { + service.setConnection(mockUri, connection); + const replacement = { ...connection, databaseName: 'replacement' }; + const captured = service.captureWorkerBinding(mockUri, connection, { + fingerprint: 'worker-fingerprint', + }); + expect(captured?.fingerprint).toBe('worker-fingerprint'); + + service.setConnection(mockUri, replacement); + expect( + service.captureWorkerBinding(mockUri, connection, { + fingerprint: 'stale-fingerprint', + }), + ).toBeUndefined(); + expect(service.getConnection(mockUri)).toBe(replacement); + }); + it('getActiveClusterIds returns all unique cluster IDs', () => { const uri2 = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; const connection2: PlaygroundConnection = { @@ -182,6 +319,73 @@ describe('PlaygroundService', () => { // The StatusBarItem is created in the constructor; verify it was configured expect(vscode.window.createStatusBarItem).toHaveBeenCalledWith(vscode.StatusBarAlignment.Left, 100); }); + + it('immediately presents an explicit disconnect and restores the normal display on unlatch', () => { + const clusterId = uniqueLatchClusterId('playground-status-disconnect'); + const connection: PlaygroundConnection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + const doc = { + uri: mockUri, + languageId: PLAYGROUND_LANGUAGE_ID, + getText: () => 'db.orders.find({})', + } as vscode.TextDocument; + Object.assign(vscode.window, { activeTextEditor: { document: doc } as vscode.TextEditor }); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + service.setConnection(mockUri, connection); + const stateChanged = vi.fn(); + service.onDidChangeState(stateChanged); + + latch(clusterId, 'userDisconnected'); + + expect(stateChanged).toHaveBeenCalledTimes(1); + expect(statusBar.text).toBe('$(warning) Disconnected'); + expect(statusBar.tooltip).toBe( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ); + expect(statusBar.command).toBe(PlaygroundCommandIds.showConnectionInfo); + expect(service.getConnection(mockUri)).toBe(connection); + expect(service.isConnected(mockUri)).toBe(true); + expect(service.isExecuting()).toBe(false); + expect(doc.getText()).toBe('db.orders.find({})'); + + ClustersClient.unlatch(clusterId); + + expect(stateChanged).toHaveBeenCalledTimes(2); + expect(statusBar.text).toBe('$(plug) MyCluster / orders'); + expect(statusBar.tooltip).toBe('Query Playground connected to MyCluster / orders'); + expect(service.getConnection(mockUri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + }); + + it.each(['signInRequired', 'unreachable', 'identityChanged'] as const)( + 'does not label the %s hold as an explicit disconnect', + (reason) => { + const clusterId = uniqueLatchClusterId(`playground-status-${reason}`); + const connection: PlaygroundConnection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + Object.assign(vscode.window, { + activeTextEditor: { + document: { uri: mockUri, languageId: PLAYGROUND_LANGUAGE_ID }, + } as vscode.TextEditor, + }); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + service.setConnection(mockUri, connection); + + latch(clusterId, reason); + + expect(service.isUserDisconnected(mockUri)).toBe(false); + expect(statusBar.text).toBe('$(plug) MyCluster / orders'); + expect(statusBar.tooltip).toBe('Query Playground connected to MyCluster / orders'); + }, + ); }); describe('onDidCloseTextDocument cleanup', () => { @@ -245,6 +449,16 @@ describe('PlaygroundService', () => { clusterDisplayName: 'MyCluster', databaseName: 'orders', }; + const learnedBinding = { + fingerprint: 'worker-fingerprint', + entraIdentity: { + kind: 'entra', + providerId: 'microsoft', + accountId: 'worker-account', + accountLabel: 'Worker Account', + tenantId: 'tenant', + }, + } as const; function getSaveDocHandler(): (doc: Partial) => void { const calls = (vscode.workspace.onDidSaveTextDocument as Mock).mock.calls; @@ -314,6 +528,48 @@ describe('PlaygroundService', () => { expect(service.isConnected(oldFile.uri as vscode.Uri)).toBe(false); }); + it('remembers the first worker binding at the new URI after Save As', () => { + hasCredentialsMock.mockReturnValue(true); + const content = 'db.orders.find({})'; + const source = makeFileDoc('file:///home/u/orders.documentdb.js', content); + const saved = makeFileDoc('file:///home/u/orders-copy.documentdb.js', content); + const sourceUri = source.uri as vscode.Uri; + const savedUri = saved.uri as vscode.Uri; + const original = service.setConnectionFromHost(sourceUri, connection); + expect(original.fingerprint).toBeUndefined(); + setOpenDocuments([source, saved]); + getSaveDocHandler()(saved); + getCloseDocHandler()(source); + expect(service.getConnection(savedUri)).toBe(original); + + const bound = service.captureWorkerBinding(sourceUri, original, learnedBinding); + + expect(bound).toEqual({ ...original, ...learnedBinding }); + expect(service.getConnection(savedUri)).toBe(bound); + getCloseDocHandler()(saved); + getOpenDocHandler()(saved); + getOpenDocHandler()(source); + expect(service.getConnection(savedUri)).toBe(bound); + expect(service.getConnection(sourceUri)).toBeUndefined(); + }); + + it('rejects a worker binding after re-picking the same unpinned target at the saved URI', () => { + const content = 'db.orders.find({})'; + const source = makeFileDoc('file:///home/u/orders.documentdb.js', content); + const saved = makeFileDoc('file:///home/u/orders-copy.documentdb.js', content); + const sourceUri = source.uri as vscode.Uri; + const savedUri = saved.uri as vscode.Uri; + const original = service.setConnectionFromHost(sourceUri, connection); + setOpenDocuments([source, saved]); + getSaveDocHandler()(saved); + const repicked = service.setConnectionFromHost(savedUri, original); + + expect(service.captureWorkerBinding(sourceUri, original, learnedBinding)).toBeUndefined(); + expect(repicked).not.toBe(original); + expect(service.getConnection(savedUri)).toBe(repicked); + expect(repicked.fingerprint).toBeUndefined(); + }); + it('is a no-op when saving a file that already has a connection (regular save)', () => { const content = 'db.orders.find({})'; const fileDoc = makeFileDoc('file:///home/u/orders.documentdb.documentdb.js', content); @@ -383,16 +639,6 @@ describe('PlaygroundService', () => { databaseName: 'orders', }; - function getCloseDocHandler(): (doc: Partial) => void { - const calls = (vscode.workspace.onDidCloseTextDocument as Mock).mock.calls; - return calls[calls.length - 1][0] as (doc: Partial) => void; - } - - function getOpenDocHandler(): (doc: Partial) => void { - const calls = (vscode.workspace.onDidOpenTextDocument as Mock).mock.calls; - return calls[calls.length - 1][0] as (doc: Partial) => void; - } - const reopenDoc: Partial = { uri: mockUri, languageId: 'documentdb-playground' }; beforeEach(() => { diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index 3fa5d067d..1c88efe7c 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -6,9 +6,10 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './constants'; -import { type PlaygroundConnection } from './types'; +import { type PlaygroundConnection, type PlaygroundWorkerBinding } from './types'; /** * Normalize playground text for content correlation across an untitled→file save. @@ -50,6 +51,9 @@ export class PlaygroundService implements vscode.Disposable { /** Per-document connections keyed by `uri.toString()`. */ private readonly _connections = new Map(); + /** Save As moves the original object, which an in-flight worker may still hold. */ + private readonly _transferredConnectionKeys = new WeakMap(); + /** * Last-known binding per document URI, kept in memory only (never persisted). * @@ -90,6 +94,12 @@ export class PlaygroundService implements vscode.Disposable { }), ); + this._disposables.push( + ClustersClient.onDidChangeLatch(() => { + this._onDidChangeState.fire(); + }), + ); + // Clean up connection when a playground document is closed. this._disposables.push( vscode.workspace.onDidCloseTextDocument((doc) => { @@ -152,6 +162,7 @@ export class PlaygroundService implements vscode.Disposable { // ── Connection management ────────────────────────────────────────── setConnection(uri: vscode.Uri, connection: PlaygroundConnection): void { + connection = this.captureHostBinding(connection); ext.outputChannel?.trace( `[PlaygroundService] setConnection: ${uri.toString()} → cluster=${connection.clusterId}, db=${connection.databaseName}`, ); @@ -160,6 +171,65 @@ export class PlaygroundService implements vscode.Disposable { this._onDidChangeState.fire(); } + /** Bind a newly selected playground to the current connected host identity, when available. */ + setConnectionFromHost(uri: vscode.Uri, connection: PlaygroundConnection): PlaygroundConnection { + const key = uri.toString(); + const isRepick = this._connections.has(key); + // A selection is a new binding even if it targets the same unpinned cluster and database. + const bound = this.captureHostBinding({ ...connection }); + const activated = + isRepick && bound.fingerprint !== undefined + ? { ...bound, workerReplacement: { fingerprint: bound.fingerprint } } + : bound; + this.setConnection(uri, activated); + return this._connections.get(key) ?? activated; + } + + private captureHostBinding(connection: PlaygroundConnection): PlaygroundConnection { + const binding = ClustersClient.getBinding(connection.clusterId); + const verifiedIdentity = ClustersClient.getLastVerifiedIdentity(connection.clusterId); + const hostIdentityIsCompatible = + connection.fingerprint === undefined || connection.fingerprint === binding?.fingerprint; + return binding === undefined + ? connection + : { + ...connection, + fingerprint: connection.fingerprint ?? binding.fingerprint, + entraIdentity: + connection.entraIdentity ?? + (hostIdentityIsCompatible && verifiedIdentity?.kind === 'entra' ? verifiedIdentity : undefined), + }; + } + + /** Capture a worker-learned binding only while the originating connection is still current and unpinned. */ + captureWorkerBinding( + uri: vscode.Uri, + expectedConnection: PlaygroundConnection, + binding: PlaygroundWorkerBinding, + ): PlaygroundConnection | undefined { + const originalKey = uri.toString(); + const key = + this._connections.get(originalKey) === expectedConnection + ? originalKey + : this._transferredConnectionKeys.get(expectedConnection); + if ( + key === undefined || + this._connections.get(key) !== expectedConnection || + expectedConnection.fingerprint !== undefined + ) { + return undefined; + } + const bound = { + ...expectedConnection, + fingerprint: binding.fingerprint, + entraIdentity: binding.entraIdentity, + }; + this._connections.set(key, bound); + this._lastBindingByPath.set(key, bound); + this._onDidChangeState.fire(); + return bound; + } + removeConnection(uri: vscode.Uri): void { ext.outputChannel?.trace(`[PlaygroundService] removeConnection: ${uri.toString()}`); this._connections.delete(uri.toString()); @@ -169,6 +239,24 @@ export class PlaygroundService implements vscode.Disposable { this._onDidChangeState.fire(); } + public removeConnectionsForCluster(clusterId: string): void { + let clearedSelection = false; + for (const [key, connection] of this._connections) { + if (connection.clusterId === clusterId) { + this._connections.delete(key); + clearedSelection = true; + } + } + for (const [key, connection] of this._lastBindingByPath) { + if (connection.clusterId === clusterId) { + this._lastBindingByPath.delete(key); + } + } + if (clearedSelection) { + this._onDidChangeState.fire(); + } + } + /** * Re-key a connection onto a freshly saved `file:` playground. * @@ -228,6 +316,7 @@ export class PlaygroundService implements vscode.Disposable { this._connections.delete(sourceKey); this._connections.set(fileKey, connection); + this._transferredConnectionKeys.set(connection, fileKey); // Move the remembered binding onto the saved file too, so a later in-session // reopen of that file can be restored silently. this._lastBindingByPath.delete(sourceKey); @@ -246,6 +335,11 @@ export class PlaygroundService implements vscode.Disposable { return this._connections.get(uri.toString()); } + isUserDisconnected(uri: vscode.Uri): boolean { + const connection = this.getConnection(uri); + return connection !== undefined && ClustersClient.getLatchReason(connection.clusterId) === 'userDisconnected'; + } + /** * Attempt a silent, in-session restore of a previously remembered binding for * a reopened playground. No-ops unless: the document is currently unbound, @@ -351,7 +445,13 @@ export class PlaygroundService implements vscode.Disposable { } const displayName = this.getDisplayName(editor.document.uri); - if (displayName) { + if (this.isUserDisconnected(editor.document.uri)) { + this._statusBarItem.command = PlaygroundCommandIds.showConnectionInfo; + this._statusBarItem.text = `$(warning) ${l10n.t('Disconnected')}`; + this._statusBarItem.tooltip = l10n.t( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ); + } else if (displayName) { this._statusBarItem.command = PlaygroundCommandIds.showConnectionInfo; this._statusBarItem.text = `$(plug) ${displayName}`; this._statusBarItem.tooltip = l10n.t('Query Playground connected to {0}', displayName); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d1725634d..b8434dbb2 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -15,7 +15,18 @@ import { Worker } from 'worker_threads'; import { ext } from '../../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; import { AuthMethodId } from '../auth/AuthMethod'; +import * as tokenResource from '../auth/documentdbTokenResource'; +import { + getRecentEntraTokenFailure, + recordEntraTokenFailure, + resetEntraTokenFailuresForTests, +} from '../auth/entraErrors/entraTokenFailures'; +import * as entraSession from '../auth/entraSession'; +import * as managedIdentityProvider from '../auth/managedIdentityTokenProvider'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; +import { WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { ShellSessionManager } from '../shell/ShellSessionManager'; import { @@ -28,7 +39,7 @@ import { type WorkerSessionCallbacks, type WorkerStartupTelemetryContext, } from './WorkerSessionManager'; -import { type MainToWorkerMessage } from './workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage } from './workerTypes'; interface RecordedTelemetry { readonly eventName: string; @@ -744,6 +755,414 @@ describe('WorkerSessionManager', () => { expect(metadata).toMatchObject({ host: 'cluster.mongocluster.cosmos.azure.us', additionalHostCount: 0 }); session.dispose(); }); + + describe('diagnostic Shell startup', (): void => { + const clusterId = 'diagnostic-cluster'; + const authenticationHolds = ['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const; + const blockingReasons = [ + 'credentialsUpdating', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', + ] as const; + let session: ShellSessionManager; + let isolationSpies: MockInstance[]; + const reread = vi.fn<() => Promise>(); + + beforeEach((): void => { + reread.mockReset().mockResolvedValue(originalUri); + session = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'testdb' }, + undefined, + {}, + { connectionString: originalUri, reread }, + ); + isolationSpies = [ + vi.spyOn(ClustersClient, 'getExpectedFingerprint'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(WorkerTokenRelay.prototype, 'relay'), + vi.spyOn(entraSession, 'getEntraSession'), + vi.spyOn(managedIdentityProvider, 'getManagedIdentityAccessToken'), + vi.spyOn(ClustersClient, 'unlatch'), + ]; + }); + + afterEach((): void => { + try { + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getConnectionStringWithPassword).not.toHaveBeenCalled(); + expect(CredentialCache.getConnectionUser).not.toHaveBeenCalled(); + for (const spy of isolationSpies) { + expect(spy).not.toHaveBeenCalled(); + } + } finally { + session.dispose(); + for (const spy of isolationSpies) { + spy.mockRestore(); + } + ClustersClient.unlatch(clusterId); + } + }); + + it.each(authenticationHolds)( + 'spawns the real worker under %s without authentication or clearing the hold', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + const initializing = session.initialize(); + await vi.waitFor(() => expect(Worker).toHaveBeenCalledOnce()); + const posted = replyInit(); + await expect(initializing).resolves.toMatchObject({ + authMechanism: 'NoAuth', + username: undefined, + }); + expect(posted).toEqual({ + type: 'init', + requestId: expect.any(String), + connectionString: originalUri, + databaseName: 'testdb', + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { + serverSelectionTimeoutMS: undefined, + tlsAllowInvalidCertificates: undefined, + appName: undefined, + tls: undefined, + }, + oidcDestinationPolicy: undefined, + }); + workerMock()._emit('message', { type: 'tokenRequest', requestId: 'unexpected-token' }); + await Promise.resolve(); + expect(workerMock().postMessage).toHaveBeenCalledOnce(); + expect(session.pinnedEntraIdentity).toBeUndefined(); + expect(session.isInitialized).toBe(true); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each(authenticationHolds)( + 'keeps ordinary NoAuth worker startup strict under %s', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + const manager = new WorkerSessionManager(callbacks); + try { + await expect(manager.ensureWorker(clusterId, initMessage())).rejects.toMatchObject({ reason }); + expect(prepareDriverConnectionString).not.toHaveBeenCalled(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + } finally { + manager.dispose(); + } + }, + ); + + it.each(blockingReasons)('blocks %s before diagnostic startup', async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + await expect(session.initialize()).rejects.toMatchObject({ reason }); + expect(reread).not.toHaveBeenCalled(); + expect(prepareDriverConnectionString).not.toHaveBeenCalled(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }); + + it.each(blockingReasons)( + 'blocks %s introduced during diagnostic worker preparation', + async (reason): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const pending = deferred(); + vi.mocked(prepareDriverConnectionString).mockReturnValueOnce(pending.promise); + const initializing = session.initialize(); + await vi.waitFor(() => expect(prepareDriverConnectionString).toHaveBeenCalledOnce()); + ClustersClient.latch(clusterId, reason); + pending.resolve({ connectionString: originalUri, options: {}, srvResolution: 'notSrv' }); + await expect(initializing).rejects.toBeInstanceOf(ConnectionUnavailableError); + await expect(initializing).rejects.toMatchObject({ reason }); + expect(Worker).not.toHaveBeenCalled(); + expect(session.isInitialized).toBe(false); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each(['abort', 'epoch'] as const)( + 'preserves the %s guard during diagnostic worker preparation', + async (guard): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const pending = deferred(); + vi.mocked(prepareDriverConnectionString).mockReturnValueOnce(pending.promise); + const initializing = session.initialize(); + await vi.waitFor(() => expect(prepareDriverConnectionString).toHaveBeenCalledOnce()); + if (guard === 'abort') { + session.killWorker(); + expect(vi.mocked(prepareDriverConnectionString).mock.calls[0][0].abortSignal?.aborted).toBe( + true, + ); + } else { + ClustersClient.invalidate(clusterId); + } + pending.resolve({ connectionString: originalUri, options: {}, srvResolution: 'notSrv' }); + await expect(initializing).rejects.toBeInstanceOf(UserCancelledError); + expect(Worker).not.toHaveBeenCalled(); + expect(session.isInitialized).toBe(false); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + }, + ); + + it('preserves the original preparation failure through diagnostic startup', async (): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const failure = new Error('DNS preparation failed'); + vi.mocked(prepareDriverConnectionString).mockRejectedValueOnce(failure); + await expect(session.initialize()).rejects.toBe(failure); + expect(prepareDriverConnectionString).toHaveBeenCalledOnce(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + }); + }); + }); + + describe('worker token relay environment binding', () => { + const originalEnvironment = { + providerId: 'microsoft-sovereign-cloud', + cloudName: 'CustomCloud', + authority: 'https://authority.example.com/original/', + }; + const resolvedResource = { + resource: 'https://database.example.com', + scope: 'https://database.example.com/.default', + cloudCategory: 'custom', + reason: 'customLoginHost', + details: { + flow: 'interactive', + tokenResource: 'https://database.example.com', + }, + } as const; + + function createRelay(clusterId: string): WorkerTokenRelay { + return new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString: 'mongodb://cluster.mongocluster.cosmos.azure.com/', + clientOptions: {}, + databaseName: 'test', + authMechanism: 'MicrosoftEntraID', + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + } + + it.each([ + ['provider', (environment: typeof originalEnvironment) => ({ ...environment, providerId: 'changed' })], + ['cloud', (environment: typeof originalEnvironment) => ({ ...environment, cloudName: 'AzureCloud' })], + [ + 'authority', + (environment: typeof originalEnvironment) => ({ + ...environment, + authority: 'https://authority.example.com/changed/', + }), + ], + ] as const)('rejects later %s drift against the cached audience environment', async (_name, change) => { + let environment: typeof originalEnvironment = originalEnvironment; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockImplementation(() => environment); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ + id: 'session-id', + accessToken: 'access-token', + account: { id: 'account-id', label: 'Account' }, + scopes: [], + }); + const relay = createRelay(`relay-environment-${_name}`); + const responses: MainToWorkerMessage[] = []; + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'first' }, + (response) => responses.push(response), + () => true, + ); + environment = change(environment); + await relay.relay( + { type: 'tokenRequest', requestId: 'second' }, + (response) => responses.push(response), + () => true, + ); + + expect(responses).toEqual([ + { type: 'tokenResponse', requestId: 'first', accessToken: 'access-token' }, + expect.objectContaining({ + type: 'tokenError', + requestId: 'second', + reason: 'signInRequired', + }), + ]); + expect(resolver).toHaveBeenCalledTimes(1); + expect(lookup).toHaveBeenCalledTimes(1); + } finally { + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + + it('fails closed when the cached audience environment cannot be read later', async () => { + let readable = true; + const environmentSpy = vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockImplementation(() => { + if (!readable) { + throw new Error('private-configuration-cause'); + } + return originalEnvironment; + }); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ + id: 'session-id', + accessToken: 'access-token', + account: { id: 'account-id', label: 'Account' }, + scopes: [], + }); + const relay = createRelay('relay-unreadable-environment'); + const responses: MainToWorkerMessage[] = []; + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'first' }, + (response) => responses.push(response), + () => true, + ); + readable = false; + await relay.relay( + { type: 'tokenRequest', requestId: 'second' }, + (response) => responses.push(response), + () => true, + ); + + expect(responses.at(-1)).toMatchObject({ + type: 'tokenError', + requestId: 'second', + reason: 'signInRequired', + }); + expect(resolver).toHaveBeenCalledTimes(1); + expect(lookup).toHaveBeenCalledTimes(1); + expect(JSON.stringify(responses)).not.toContain('private-configuration-cause'); + } finally { + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + + it('validates the environment when the Entra lookup rejects', async () => { + const clusterId = 'relay-rejected-lookup'; + let environment: typeof originalEnvironment = originalEnvironment; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockImplementation(() => environment); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockImplementation(async () => { + environment = { + ...environment, + authority: 'https://authority.example.com/changed/', + }; + throw new Error('private-lookup-cause'); + }); + const relay = createRelay(clusterId); + const responses: MainToWorkerMessage[] = []; + const startupProperties: Record = {}; + recordEntraTokenFailure(clusterId, { cloudCategory: 'custom', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure(clusterId); + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'rejected' }, + (response) => responses.push(response), + () => true, + undefined, + { startupCorrelationId: 'relay-startup', surface: 'playground', startupProperties }, + ); + + expect(responses).toEqual([ + expect.objectContaining({ + type: 'tokenError', + requestId: 'rejected', + reason: 'signInRequired', + }), + ]); + expect(getRecentEntraTokenFailure(clusterId)).toBe(priorFailure); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + expect(JSON.stringify(responses)).not.toContain('private-lookup-cause'); + } finally { + resetEntraTokenFailuresForTests(); + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + + it.each(['oldWorker', 'epoch'] as const)( + 'does not validate or diagnose a rejected lookup from a stale %s', + async (staleBy) => { + const clusterId = `relay-stale-${staleBy}`; + let current = true; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockReturnValue(originalEnvironment); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); + let signalStarted!: () => void; + const started = new Promise((resolve) => { + signalStarted = resolve; + }); + let rejectLookup!: () => void; + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockImplementation( + async () => + await new Promise((_, reject) => { + rejectLookup = () => reject(new Error('obsolete lookup failure')); + signalStarted(); + }), + ); + const relay = createRelay(clusterId); + const responses: MainToWorkerMessage[] = []; + recordEntraTokenFailure(clusterId, { cloudCategory: 'china', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure(clusterId); + try { + const relaying = relay.relay( + { type: 'tokenRequest', requestId: 'stale' }, + (response) => responses.push(response), + () => current, + ); + const outcome = + staleBy === 'epoch' ? expect(relaying).rejects.toBeInstanceOf(UserCancelledError) : relaying; + await started; + const readsBeforeRejection = environmentSpy.mock.calls.length; + if (staleBy === 'oldWorker') { + current = false; + } else { + ClustersClient.invalidate(clusterId); + } + rejectLookup(); + await outcome; + + expect(responses).toEqual([]); + expect(environmentSpy).toHaveBeenCalledTimes(readsBeforeRejection); + expect(getRecentEntraTokenFailure(clusterId)).toBe(priorFailure); + } finally { + resetEntraTokenFailuresForTests(); + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }, + ); }); describe('startup tracking', () => { @@ -800,6 +1219,337 @@ describe('WorkerSessionManager', () => { return { manager, initPromise, requestId: initMessage.requestId, worker }; } + it.each([true, false])( + 'counts only checked post-startup Entra relay outcomes (persistent=%s)', + async (persistent) => { + const clusterId = 'test-cluster'; + const environment = { + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', + }; + const readEnvironment = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockReturnValue(environment); + const resolveResource = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, + }); + const account = { id: 'test-account', label: 'Test account' }; + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 3540 })).toString('base64url')}.signature`; + const session = { id: 'test-session', account, accessToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString: 'mongodb://example.mongocluster.cosmos.azure.com/', + clientOptions: {}, + databaseName: 'test', + authMechanism: AuthMethodId.MicrosoftEntraID, + persistent, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + const onTokenRequest = vi.fn>( + relay.relay.bind(relay), + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(persistent, {}, manager); + const request = async (requestId: string): Promise => { + active.worker._emit('message', { type: 'tokenRequest', requestId }); + await onTokenRequest.mock.results.at(-1)?.value; + }; + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + await request('startup-lookup'); + await request('another-startup-lookup'); + expect(renewalEvents()).toEqual([]); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + + await request('renewal-with-lifetime'); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await request('opaque-renewal'); + getSession.mockResolvedValueOnce(undefined); + await request('missing-session'); + getSession.mockResolvedValueOnce({ ...session, account: { ...account, id: 'different-account' } }); + await request('identity-mismatch'); + readEnvironment.mockReturnValueOnce({ ...environment, providerId: 'microsoft-sovereign-cloud' }); + await request('provider-changed'); + getSession.mockRejectedValueOnce(new Error('test provider failure')); + await request('refresh-failed'); + getSession.mockRejectedValueOnce(new UserCancelledError()); + await request('canceled-lookup'); + const driverAbortFlag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); + getSession.mockImplementationOnce(async () => { + Atomics.store(new Int32Array(driverAbortFlag), 0, 1); + return session; + }); + active.worker._emit('message', { + type: 'tokenRequest', + requestId: 'driver-stopped-waiting', + driverAbortFlag, + }); + await onTokenRequest.mock.results.at(-1)?.value; + ClustersClient.invalidate(clusterId); + await expect(request('stale-lookup')).rejects.toBeInstanceOf(UserCancelledError); + + const surface = persistent ? 'shell' : 'playground'; + expect( + renewalEvents().map(({ telemetry, error }) => [ + telemetry.properties, + telemetry.measurements, + error, + ]), + ).toEqual([ + [ + { surface, renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], + [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + [ + { surface, renewalOutcome: 'identityMismatch', result: 'Succeeded' }, + { duration: 0 }, + undefined, + ], + [ + { surface, renewalOutcome: 'providerChanged', result: 'Succeeded' }, + { duration: 0 }, + undefined, + ], + [{ surface, renewalOutcome: 'failed', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'timedOut', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + } finally { + manager.dispose(); + getSession.mockRestore(); + resolveResource.mockRestore(); + readEnvironment.mockRestore(); + } + }, + ); + + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( + 'reconstructs %s at both boundaries and marks a warm worker broken', + async (reason): Promise => { + const failed = await startWorker(); + failed.worker._emit('message', { + type: 'initResult', + requestId: failed.requestId, + success: false, + authReason: reason, + }); + await expect(failed.initPromise).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === reason, + ); + + const active = await startWorker(); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + const evaluating = active.manager.sendEval({ + type: 'eval', + requestId: '', + code: '1', + databaseName: 'test', + displayBatchSize: 20, + }); + const worker = vi.mocked(Worker).mock.results.at(-1)?.value as { postMessage: Mock }; + const evaluation = worker.postMessage.mock.calls.at(-1)?.[0] as MainToWorkerMessage; + active.worker._emit('message', { + type: 'evalError', + requestId: evaluation.requestId, + authReason: reason, + }); + await expect(evaluating).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === reason); + expect(active.manager.authFailure).toBe(reason); + active.manager.dispose(); + }, + ); + + it('does not deliver a held token reply after Disconnect replaces the worker', async (): Promise => { + let releaseOldReply!: () => void; + const oldReply = new Promise((resolve) => { + releaseOldReply = resolve; + }); + const onTokenRequest = vi.fn>( + async (message, postResponse) => { + if (message.requestId === 'old-token') { + await oldReply; + } + postResponse({ + type: 'tokenResponse', + requestId: message.requestId, + accessToken: `${message.requestId}-access-token`, + }); + }, + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const old = await startWorker(true, {}, manager); + old.worker._emit('message', { + type: 'initResult', + requestId: old.requestId, + success: true, + }); + await old.initPromise; + + old.worker._emit('message', { type: 'tokenRequest', requestId: 'old-token' }); + await vi.waitFor(() => expect(onTokenRequest).toHaveBeenCalledTimes(1)); + + ClustersClient.latch('test-cluster', 'userDisconnected'); + manager.killWorker(); + ClustersClient.unlatch('test-cluster'); + + const replacement = await startWorker(true, {}, manager); + replacement.worker._emit('message', { + type: 'initResult', + requestId: replacement.requestId, + success: true, + }); + await replacement.initPromise; + + releaseOldReply(); + await onTokenRequest.mock.results[0].value; + const postMessage = ( + workerThreads as unknown as { + _mockPostMessage: Mock; + } + )._mockPostMessage; + const tokenReplies = (): MainToWorkerMessage[] => + postMessage.mock.calls + .map(([message]) => message as MainToWorkerMessage) + .filter((message) => message.type === 'tokenResponse'); + expect(tokenReplies()).toEqual([]); + + replacement.worker._emit('message', { + type: 'tokenRequest', + requestId: 'replacement-token', + }); + await onTokenRequest.mock.results[1].value; + expect(tokenReplies()).toEqual([ + { + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken: 'replacement-token-access-token', + }, + ]); + expect(manager.isAlive).toBe(true); + } finally { + ClustersClient.unlatch('test-cluster'); + manager.dispose(); + } + }); + + it.each(['returned', 'failed'] as const)( + 'cancels a still-attached worker when an invalidated token lookup %s', + async (outcome): Promise => { + const clusterId = 'test-cluster'; + const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.com/'; + const resolver = vi.spyOn(tokenResource, 'resolveManagedIdentityTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + resource: 'https://ossrdbms-aad.database.windows.net', + scope: 'https://ossrdbms-aad.database.windows.net/.default', + details: {}, + }); + type Token = Awaited>; + let signalStarted!: () => void; + const started = new Promise((resolve) => { + signalStarted = resolve; + }); + let finishLookup!: () => void; + const lookup = new Promise((resolve, reject) => { + finishLookup = (): void => { + if (outcome === 'returned') { + resolve({ accessToken: 'must-not-send', expiresOnTimestamp: 0 }); + } else { + reject(new Error('obsolete provider failure')); + } + }; + }); + const provider = vi + .spyOn(managedIdentityProvider, 'getManagedIdentityAccessToken') + .mockImplementation(() => { + signalStarted(); + return lookup; + }); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString, + clientOptions: {}, + databaseName: 'test', + authMechanism: AuthMethodId.ManagedIdentity, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + callbacks.onTokenRequest = relay.relay.bind(relay); + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(true, {}, manager); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + const evalMessage = { + type: 'eval', + requestId: '', + code: '1', + databaseName: 'test', + displayBatchSize: 20, + } as const; + const evaluating = manager.sendEval(evalMessage); + const canceled = expect(evaluating).rejects.toBeInstanceOf(UserCancelledError); + active.worker._emit('message', { type: 'tokenRequest', requestId: 'obsolete-token' }); + await started; + ClustersClient.invalidate(clusterId); + resetEntraTokenFailuresForTests(); + if (outcome === 'returned') { + recordEntraTokenFailure(clusterId, { cloudCategory: 'china', authMethod: 'interactive' }); + } + const newerFailure = getRecentEntraTokenFailure(clusterId); + finishLookup(); + await canceled; + expect(manager.isAlive).toBe(false); + expect(manager.authFailure).toBeUndefined(); + expect(getRecentEntraTokenFailure(clusterId)).toBe(newerFailure); + + const replacement = await startWorker(true, {}, manager); + replacement.worker._emit('message', { + type: 'initResult', + requestId: replacement.requestId, + success: true, + }); + await replacement.initPromise; + const worker = vi.mocked(Worker).mock.results.at(-1)?.value as { postMessage: Mock }; + const messages = worker.postMessage.mock.calls as [MainToWorkerMessage][]; + expect(messages.map(([message]) => message.type)).toEqual(['init', 'eval', 'init']); + expect(manager.isAlive).toBe(true); + } finally { + manager.dispose(); + resetEntraTokenFailuresForTests(); + provider.mockRestore(); + resolver.mockRestore(); + } + }, + ); + it('reports a stalled token request with total and stage timings without connection details', async () => { const { initPromise, requestId, worker } = await startWorker(); vi.advanceTimersByTime(200); diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index 53ea35c56..e65c3180d 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -16,6 +16,7 @@ import { Worker } from 'worker_threads'; import { ext } from '../../extensionVariables'; import { settingsKeys } from '../../settingsKeys'; import { traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; +import { type AuthMethodId } from '../auth/AuthMethodId'; import { getEntraCustomHostnameSuffix } from '../auth/entraDestinationSettings'; import { removeConflictingOidcMechanism } from '../auth/nonOidcConnectionString'; import { @@ -24,13 +25,18 @@ import { normalizeCustomHostnameSuffix, } from '../auth/oidcAllowedHosts'; import { createOidcDestinationPolicy } from '../auth/oidcClientOptions'; +import { createWorkerAuthError } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError, isDiagnosticAuthenticationHold } from '../ConnectionUnavailableError'; import { SettingsHintError } from '../shell/SettingsHintError'; import { prepareDriverConnectionString } from '../srv/prepareDriverConnectionString'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { + isWorkerAuthReason, type MainToWorkerMessage, type SerializableExecutionResult, type SerializableOidcDestinationPolicy, + type WorkerAuthReason, type WorkerStartupStage, type WorkerToMainMessage, } from './workerTypes'; @@ -87,7 +93,8 @@ export interface WorkerSessionCallbacks { /** * Called when the worker requests an OIDC token (Entra ID auth). * The implementation must acquire the token via VS Code auth APIs - * and post it back to the worker. + * and post it back to the worker, or throw UserCancelledError if the + * still-attached worker's request was invalidated. */ onTokenRequest?: ( msg: Extract, @@ -95,6 +102,7 @@ export interface WorkerSessionCallbacks { isCurrent: () => boolean, timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + postStartup?: boolean, ) => Promise; /** Called when the worker exits (crash or termination). */ onWorkerExit?: (exitCode: number) => void; @@ -116,6 +124,9 @@ export class WorkerSessionManager implements vscode.Disposable { private _worker: Worker | undefined; private _workerState: WorkerState = 'idle'; private _workerClusterId: string | undefined; + private _workerAuthMethod: AuthMethodId | undefined; + private _authFailure: WorkerAuthReason | undefined; + private _shuttingDownWorker: Worker | undefined; private _startup: WorkerStartup | undefined; private _startupAbortController: AbortController | undefined; private _oidcDestinationPolicy: SerializableOidcDestinationPolicy | undefined; @@ -152,6 +163,10 @@ export class WorkerSessionManager implements vscode.Disposable { return this._workerClusterId; } + get authFailure(): WorkerAuthReason | undefined { + return this._authFailure; + } + /** * Whether the worker is alive and connected to the specified cluster. */ @@ -177,18 +192,22 @@ export class WorkerSessionManager implements vscode.Disposable { initMsg: MainToWorkerMessage & { type: 'init' }, initTimeoutMs: number = 30000, telemetryContext: WorkerStartupTelemetryContext = {}, + allowDiagnosticAuthenticationHold: boolean = false, ): Promise { // If worker is alive but connected to a different cluster, shut it down - if (this._worker && this._workerClusterId !== clusterId) { - ext.outputChannel?.trace( - `[WorkerSessionManager] Cluster changed (${String(this._workerClusterId)} → ${clusterId}), terminating old worker`, - ); + if (this._worker && (this._workerClusterId !== clusterId || this._authFailure || this._shuttingDownWorker)) { this.terminateWorker('intentional'); } // Callers must not overlap ensureWorker calls because SRV preparation runs before _worker is set. if (!this._worker || this._workerState === 'idle') { - await this.spawnWorker(clusterId, initMsg, initTimeoutMs, telemetryContext); + await this.spawnWorker( + clusterId, + initMsg, + initTimeoutMs, + telemetryContext, + allowDiagnosticAuthenticationHold, + ); } } @@ -198,13 +217,14 @@ export class WorkerSessionManager implements vscode.Disposable { * @returns The serializable execution result from the worker. */ async sendEval(evalMsg: MainToWorkerMessage & { type: 'eval' }): Promise<{ result: SerializableExecutionResult }> { + const worker = this._worker; this._workerState = 'executing'; try { const result = await this.sendRequest<{ result: SerializableExecutionResult }>(evalMsg); return result; } finally { - if (this._workerState === 'executing') { + if (this._worker === worker && this._workerState === 'executing') { this._workerState = 'ready'; } } @@ -221,13 +241,17 @@ export class WorkerSessionManager implements vscode.Disposable { } ext.outputChannel?.trace('[WorkerSessionManager] Graceful shutdown requested'); + const worker = this._worker; + this._shuttingDownWorker = worker; try { await this.sendRequest({ type: 'shutdown', requestId: '' }, 5000); } catch { // Shutdown timed out or failed — force-kill } - this.terminateWorker('intentional'); + if (this._worker === worker) { + this.terminateWorker('intentional'); + } } /** @@ -252,6 +276,7 @@ export class WorkerSessionManager implements vscode.Disposable { initMsg: MainToWorkerMessage & { type: 'init' }, initTimeoutMs: number, telemetryContext: WorkerStartupTelemetryContext, + allowDiagnosticAuthenticationHold: boolean, ): Promise { let originalFailure: { error: unknown } | undefined; const controller = new AbortController(); @@ -293,6 +318,7 @@ export class WorkerSessionManager implements vscode.Disposable { startup, controller.signal, telemetryContext, + allowDiagnosticAuthenticationHold, ); } catch (error) { if (this._startupAbortController === controller) { @@ -328,8 +354,20 @@ export class WorkerSessionManager implements vscode.Disposable { startup: WorkerStartup, abortSignal: AbortSignal, telemetryContext: WorkerStartupTelemetryContext, + allowDiagnosticAuthenticationHold: boolean, ): Promise { this._workerState = 'spawning'; + const epoch = ClustersClient.getEpoch(clusterId); + const assertAvailable = (): void => { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason && !(allowDiagnosticAuthenticationHold && isDiagnosticAuthenticationHold(reason))) { + throw new ConnectionUnavailableError(reason); + } + if (epoch !== ClustersClient.getEpoch(clusterId) || abortSignal.aborted) { + throw new UserCancelledError('workerStartup'); + } + }; + assertAvailable(); const options = { ...initMsg.clientOptions }; const usesOidc = initMsg.authMechanism === 'MicrosoftEntraID' || initMsg.authMechanism === 'ManagedIdentity'; const customHostnameSuffix = usesOidc @@ -406,12 +444,11 @@ export class WorkerSessionManager implements vscode.Disposable { // extension root, rather than this module's location, keeps the path independent of the // chunk this code is bundled into. const workerPath = path.join(ext.context.extensionPath, 'playgroundWorker.mjs'); - if (abortSignal.aborted) { - throw new UserCancelledError('workerStartup'); - } + assertAvailable(); const worker = new Worker(workerPath); this._worker = worker; this._workerClusterId = clusterId; + this._workerAuthMethod = initMsg.authMechanism as AuthMethodId; // Everything this worker reports stays tied to the startup that created it. const connection: AuthTraceContext = { startupCorrelationId: startup.requestId, @@ -421,7 +458,9 @@ export class WorkerSessionManager implements vscode.Disposable { // Listen for messages from the worker worker.on('message', (msg: WorkerToMainMessage) => { - this.handleWorkerMessage(msg, connection); + if (this._worker === worker) { + this.handleWorkerMessage(msg, connection, worker); + } }); // terminateWorker() detaches a worker before it exits, so only the current worker can exit unexpectedly. @@ -450,6 +489,10 @@ export class WorkerSessionManager implements vscode.Disposable { }); await this.sendRequest(preparedInitMsg, initTimeoutMs, settingsKeys.connectionTimeout); + assertAvailable(); + if (this._worker !== worker || this._shuttingDownWorker === worker) { + throw new UserCancelledError('workerStartup'); + } this.finishStartup('succeeded'); this._workerState = 'ready'; } @@ -586,7 +629,7 @@ export class WorkerSessionManager implements vscode.Disposable { /** * Handle an incoming message from the worker. */ - private handleWorkerMessage(msg: WorkerToMainMessage, connection: AuthTraceContext): void { + private handleWorkerMessage(msg: WorkerToMainMessage, connection: AuthTraceContext, worker: Worker): void { switch (msg.type) { case 'initTiming': { const startup = this._startup; @@ -620,12 +663,18 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); - if (msg.success) { + const reason = isWorkerAuthReason(msg.authReason) + ? msg.authReason + : msg.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : this._authFailure; + this._authFailure ??= reason; + if (msg.success && !reason) { pending.resolve(undefined); } else { pending.reject( - msg.errorName === 'EntraDestinationRejectedError' - ? new EntraDestinationRejectedError({ hostCount: 0 }) + reason + ? createWorkerAuthError(reason, this._workerAuthMethod) : new Error(msg.error ?? 'Worker init failed'), ); } @@ -637,6 +686,10 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); + if (isWorkerAuthReason(msg.authReason)) { + this._authFailure ??= msg.authReason; + } + // Never turn a successful (possibly side-effecting) command into a retry. pending.resolve(msg); } break; @@ -646,8 +699,12 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); - const error: Error & { code?: number } = new Error(msg.error); - if (msg.stack) { + const reason = isWorkerAuthReason(msg.authReason) ? msg.authReason : this._authFailure; + this._authFailure ??= reason; + const error: Error & { code?: number } = reason + ? createWorkerAuthError(reason, this._workerAuthMethod) + : new Error(msg.error); + if (!reason && msg.stack) { error.stack = msg.stack; } if (msg.code !== undefined) { @@ -668,20 +725,7 @@ export class WorkerSessionManager implements vscode.Disposable { } case 'tokenRequest': { - if (this._callbacks.onTokenRequest) { - const worker = this._worker; - void this._callbacks.onTokenRequest( - msg, - (response) => { - if (this._worker === worker) { - worker?.postMessage(response); - } - }, - () => this._worker === worker, - this._startup?.costTimings, - connection, - ); - } + void this.handleTokenRequest(msg, connection, worker); break; } @@ -697,12 +741,50 @@ export class WorkerSessionManager implements vscode.Disposable { } } + private async handleTokenRequest( + msg: Extract, + connection: AuthTraceContext, + worker: Worker, + ): Promise { + const isCurrent = (): boolean => this._worker === worker && this._shuttingDownWorker !== worker; + if (!isCurrent()) { + return; + } + try { + await this._callbacks.onTokenRequest?.( + msg, + (response) => { + if (isCurrent()) { + if (response.type === 'tokenError') { + this._authFailure ??= isWorkerAuthReason(response.reason) + ? response.reason + : response.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : 'refreshFailed'; + } + worker.postMessage(response); + } + }, + isCurrent, + this._startup?.costTimings, + connection, + // Snapshot at receipt: time spent queued in the relay cannot make a startup lookup a renewal. + this._workerState === 'ready' || this._workerState === 'executing', + ); + } catch (error) { + if (isCurrent()) { + // Reject the pending startup/eval and discard the driver blocked in its callback. + this.terminateWorker('intentional', error instanceof UserCancelledError ? error : undefined); + } + } + } + // ─── Private: Worker cleanup ───────────────────────────────────────────── - private terminateWorker(reason: 'intentional' | 'forced'): void { + private terminateWorker(reason: 'intentional' | 'forced', cancellation?: UserCancelledError): void { this.revokeOidcDestinationPolicy(); this._startupAbortController?.abort(); - this.finishStartup('terminated'); + this.finishStartup(cancellation ? 'canceled' : 'terminated'); const wasAlive = !!this._worker; if (this._worker) { @@ -712,10 +794,13 @@ export class WorkerSessionManager implements vscode.Disposable { this._workerState = 'idle'; this._workerClusterId = undefined; + this._workerAuthMethod = undefined; + this._authFailure = undefined; + this._shuttingDownWorker = undefined; // Reject all pending requests for (const [, entry] of this._pendingRequests) { - entry.reject(new Error('Worker terminated')); + entry.reject(cancellation ?? new Error('Worker terminated')); } this._pendingRequests.clear(); @@ -748,6 +833,9 @@ export class WorkerSessionManager implements vscode.Disposable { this._worker = undefined; this._workerState = 'idle'; this._workerClusterId = undefined; + this._workerAuthMethod = undefined; + this._authFailure = undefined; + this._shuttingDownWorker = undefined; // Reject any still-pending requests for (const [, entry] of this._pendingRequests) { diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index b4f2d48a9..a96836a19 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -17,6 +17,7 @@ const transport = vi.hoisted(() => ({ on: vi.fn(), postMessage: vi.fn() })); const driver = vi.hoisted(() => ({ construct: vi.fn<(connectionString: string, options: MongoClientOptions) => void>(), connect: vi.fn(), + evaluate: vi.fn(), })); vi.mock('worker_threads', () => ({ parentPort: transport })); @@ -32,7 +33,7 @@ vi.mock('mongodb', async () => { }); vi.mock('@documentdb-js/shell-runtime', () => ({ DocumentDBShellRuntime: vi.fn().mockImplementation(function () { - return {}; + return { evaluate: driver.evaluate }; }), })); @@ -127,13 +128,23 @@ describe('playground worker OIDC configuration at the driver boundary', () => { if (!callback) { throw new Error('Expected the OIDC callback'); } - const token = callback({ version: 1, timeoutContext: new AbortController().signal }); + const controller = new AbortController(); + const token = callback({ version: 1, timeoutContext: controller.signal }); const request = transport.postMessage.mock.calls .map((call) => call[0] as WorkerToMainMessage) .find((message) => message.type === 'tokenRequest'); expect(request).toBeDefined(); + if (authMechanism === 'MicrosoftEntraID') { + expect(request?.driverAbortFlag).toBeInstanceOf(SharedArrayBuffer); + const abortFlag = new Int32Array(request!.driverAbortFlag!); + expect(Atomics.load(abortFlag, 0)).toBe(0); + controller.abort(); + expect(Atomics.load(abortFlag, 0)).toBe(1); + } else { + expect(request?.driverAbortFlag).toBeUndefined(); + } receive({ type: 'tokenResponse', requestId: request!.requestId, accessToken: 'dummy-token' }); - await expect(token).resolves.toMatchObject({ accessToken: 'dummy-token' }); + await expect(token).resolves.toMatchObject({ accessToken: 'dummy-token', expiresInSeconds: 3500 }); }, ); @@ -257,9 +268,60 @@ describe('playground worker OIDC configuration at the driver boundary', () => { success: false, error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + authReason: 'destinationRejected', }); }); + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( + 'round trips %s during init and a warm eval even when the driver discards the callback error', + async (reason): Promise => { + const rejectCallback = async (): Promise => { + const callback = driver.construct.mock.calls.at(-1)?.[1].authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Expected worker OIDC callback'); + } + const pending = callback({ version: 1, timeoutContext: new AbortController().signal }); + const request = transport.postMessage.mock.calls + .map(([message]) => message as WorkerToMainMessage) + .findLast((message) => message.type === 'tokenRequest'); + expect(request).toBeDefined(); + receive({ type: 'tokenError', requestId: request!.requestId, error: 'private broker detail', reason }); + try { + await pending; + } catch { + throw new Error('Driver discarded the callback error'); + } + throw new Error('Unexpected successful callback'); + }; + driver.connect.mockImplementationOnce(rejectCallback); + init({ authMechanism: reason === 'refreshFailed' ? 'ManagedIdentity' : 'MicrosoftEntraID' }); + await waitForInit(); + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'initResult', success: false, authReason: reason }), + ); + + transport.postMessage.mockClear(); + init(); + await waitForInit(); + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'initResult', success: true }), + ); + driver.evaluate.mockImplementationOnce(rejectCallback); + receive({ + type: 'eval', + requestId: 'warm', + code: 'db.test.find()', + displayBatchSize: 20, + databaseName: 'test', + }); + await vi.waitFor(() => + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'evalError', requestId: 'warm', authReason: reason }), + ), + ); + }, + ); + it.each([ 'mongodb://attacker.cloudapp.azure.com/', 'mongodb://resolved.mongocluster.cosmos.azure.com,attacker.example.com/', @@ -278,6 +340,7 @@ describe('playground worker OIDC configuration at the driver boundary', () => { success: false, error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + authReason: 'destinationRejected', }); }, ); diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index a43dcd507..a9c998d5b 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -30,8 +30,16 @@ import { createOidcDestinationPolicy, type OidcDestinationPolicy, } from '../auth/oidcClientOptions'; -import { expiresInSecondsFromTimestamp } from '../auth/tokenExpiry'; -import { type MainToWorkerMessage, type WorkerStartupStage, type WorkerToMainMessage } from './workerTypes'; +import { expiresInSecondsFromTimestamp, readJwtTimes } from '../auth/tokenExpiry'; +import { + getWorkerAuthReason, + isWorkerAuthReason, + workerAuthErrorName, + type MainToWorkerMessage, + type WorkerAuthReason, + type WorkerStartupStage, + type WorkerToMainMessage, +} from './workerTypes'; if (!parentPort) { throw new Error('playgroundWorker.ts must be run as a worker_thread'); @@ -41,6 +49,17 @@ if (!parentPort) { let mongoClient: MongoClientType | undefined; let shellRuntime: DocumentDBShellRuntime | undefined; +// Some driver/runtime error paths discard the original callback error (including its cause). +let callbackFailure: WorkerAuthReason | undefined; + +function relayError(reason: WorkerAuthReason): Error { + if (reason === 'destinationRejected') { + return new EntraDestinationRejectedError({ hostCount: 0 }); + } + const error = new Error(reason); + error.name = workerAuthErrorName(reason); + return error; +} /** * Tracks the requestId of the currently executing eval message. @@ -75,6 +94,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { requestId: msg.requestId, success: false, error: errorMessage, + authReason: getWorkerAuthReason(err) ?? callbackFailure, ...(err instanceof EntraDestinationRejectedError ? { errorName: 'EntraDestinationRejectedError' as const } : {}), @@ -98,6 +118,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { error: errorMessage, stack, code, + authReason: getWorkerAuthReason(err) ?? callbackFailure, }; parentPort!.postMessage(response); }); @@ -120,6 +141,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { // ─── Init handler ──────────────────────────────────────────────────────────── async function handleInit(msg: Extract): Promise { + callbackFailure = undefined; let connecting = true; const reportTiming = (activity: 'databaseConnect' | 'tokenWait', activityId: string, started: boolean): void => { if (connecting) { @@ -186,17 +208,32 @@ async function handleInit(msg: Extract): connectionString, policy, baseOptions: options, - oidcCallback: async (): Promise<{ accessToken: string; expiresInSeconds: number }> => { + oidcCallback: async ({ timeoutContext }): Promise<{ accessToken: string; expiresInSeconds: number }> => { const requestId = randomUUID(); const tokenPromise = new Promise((resolve, reject) => { pendingTokenRequests.set(requestId, { resolve, reject }); }); + const driverAbortFlag = + !usesManagedIdentity && timeoutContext + ? new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT) + : undefined; + const abortFlag = driverAbortFlag && new Int32Array(driverAbortFlag); + const markAborted = (): void => { + if (abortFlag) Atomics.store(abortFlag, 0, 1); + }; + if (abortFlag) { + timeoutContext.addEventListener('abort', markAborted, { once: true }); + if (timeoutContext.aborted) { + markAborted(); + } + } const tokenRequest: WorkerToMainMessage = { type: 'tokenRequest', requestId, tenantId: msg.tenantId, source: usesManagedIdentity ? 'managedIdentity' : 'vscode', clientId: usesManagedIdentity ? msg.managedIdentityClientId : undefined, + ...(driverAbortFlag ? { driverAbortFlag } : {}), }; reportProgress('acquiringToken'); reportTiming('tokenWait', requestId, true); @@ -205,6 +242,9 @@ async function handleInit(msg: Extract): try { accessToken = await tokenPromise; } finally { + if (abortFlag) { + timeoutContext.removeEventListener('abort', markAborted); + } reportTiming('tokenWait', requestId, false); } reportProgress('authenticating'); @@ -212,26 +252,29 @@ async function handleInit(msg: Extract): // Parse the JWT exp claim for a meaningful cache duration. // This avoids re-acquiring the token on every database operation // in persistent shell sessions. - let expiresInSeconds = 3500; // Conservative default (~1 hour) - try { - const payload = accessToken.split('.')[1]; - if (payload) { - const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString()) as { - exp?: number; - }; - if (typeof decoded.exp === 'number') { - expiresInSeconds = expiresInSecondsFromTimestamp(decoded.exp * 1000); - } - } - } catch { - // JWT parsing failed — use conservative default - } + const { expSec } = readJwtTimes(accessToken); + const expiresInSeconds = expSec === undefined ? 3500 : expiresInSecondsFromTimestamp(expSec * 1000); return { accessToken, expiresInSeconds }; }, }); connectionString = configuration.connectionString; options = configuration.options; + const authProperties = options.authMechanismProperties; + const oidcCallback = authProperties?.OIDC_CALLBACK; + if (oidcCallback) { + authProperties.OIDC_CALLBACK = async (params) => { + if (callbackFailure) { + throw relayError(callbackFailure); + } + try { + return await oidcCallback(params); + } catch (error) { + callbackFailure ??= getWorkerAuthReason(error) ?? 'refreshFailed'; + throw error; + } + }; + } if (configuration.ignoredTlsBypass) { log('info', '[Auth] TLS validation bypass parameters are ignored for Microsoft Entra ID connections.'); } @@ -274,6 +317,7 @@ async function handleInit(msg: Extract): type: 'initResult', requestId: msg.requestId, success: true, + authReason: callbackFailure, }; parentPort!.postMessage(response); } @@ -281,6 +325,9 @@ async function handleInit(msg: Extract): // ─── Eval handler ──────────────────────────────────────────────────────────── async function handleEval(msg: Extract): Promise { + if (callbackFailure) { + throw relayError(callbackFailure); + } if (!mongoClient || !shellRuntime) { throw new Error('Worker not initialized — call init first'); } @@ -333,6 +380,7 @@ async function handleEval(msg: Extract): const response: WorkerToMainMessage = { type: 'evalResult', requestId: msg.requestId, + authReason: callbackFailure, result: { type: result.type, printable: printableStr, @@ -384,11 +432,12 @@ function handleTokenResponse(msg: Extract): void { const pending = pendingTokenRequests.get(msg.requestId); if (pending) { - pending.reject( - msg.errorName === 'EntraDestinationRejectedError' - ? new EntraDestinationRejectedError({ hostCount: 0 }) - : new Error(msg.error), - ); + const reason = isWorkerAuthReason(msg.reason) + ? msg.reason + : msg.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : 'refreshFailed'; + pending.reject(relayError(reason)); pendingTokenRequests.delete(msg.requestId); } } @@ -404,6 +453,7 @@ process.on('uncaughtException', (error: Error) => { requestId: currentEvalRequestId, error: `Uncaught exception: ${error.message}`, stack: error.stack, + authReason: getWorkerAuthReason(error) ?? callbackFailure, }; parentPort!.postMessage(response); currentEvalRequestId = undefined; @@ -436,6 +486,7 @@ process.on('unhandledRejection', (reason: unknown) => { requestId: currentEvalRequestId, error: `Unhandled rejection: ${message}`, stack, + authReason: getWorkerAuthReason(reason) ?? callbackFailure, }; parentPort!.postMessage(response); currentEvalRequestId = undefined; diff --git a/src/documentdb/playground/types.ts b/src/documentdb/playground/types.ts index 1f2b95fbb..5a7e74595 100644 --- a/src/documentdb/playground/types.ts +++ b/src/documentdb/playground/types.ts @@ -3,6 +3,19 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; + +/** In-memory binding owned by a document, including the pin if learned by a worker first. */ +export interface PlaygroundWorkerBinding { + readonly fingerprint: string; + readonly entraIdentity?: VerifiedEntraIdentity; +} + +/** One-shot activation created only by an explicit, successful connection re-pick. */ +export interface PlaygroundWorkerReplacement { + readonly fingerprint: string; +} + /** * Represents a query playground connection bound to a specific document. * Each playground document has its own connection to a cluster/database. @@ -14,6 +27,9 @@ export interface PlaygroundConnection { readonly clusterDisplayName: string; /** Target database name for query execution. */ readonly databaseName: string; + readonly fingerprint?: string; + readonly entraIdentity?: VerifiedEntraIdentity; + readonly workerReplacement?: PlaygroundWorkerReplacement; /** * Identifies which tree view this cluster belongs to. * Used by cross-feature navigation to open the correct branch data provider. diff --git a/src/documentdb/playground/workerTypes.ts b/src/documentdb/playground/workerTypes.ts index 685773698..9d49b622b 100644 --- a/src/documentdb/playground/workerTypes.ts +++ b/src/documentdb/playground/workerTypes.ts @@ -64,6 +64,63 @@ export interface SerializableOidcDestinationPolicy { readonly revoked: SharedArrayBuffer; } +export type WorkerAuthReason = 'signInRequired' | 'identityMismatch' | 'destinationRejected' | 'refreshFailed'; + +const authErrorNames = { + signInRequired: 'EntraSignInRequiredError', + identityMismatch: 'EntraIdentityMismatchError', + destinationRejected: 'EntraDestinationRejectedError', + refreshFailed: 'TokenCallbackError', +} as const satisfies Record; + +export function isWorkerAuthReason(reason: unknown): reason is WorkerAuthReason { + return typeof reason === 'string' && Object.hasOwn(authErrorNames, reason); +} + +export function workerAuthErrorName(reason: WorkerAuthReason): string { + return authErrorNames[reason]; +} + +/** Recognize only bounded callback failures, not driver message text. */ +export function getWorkerAuthReason(error: unknown): WorkerAuthReason | undefined { + const visited = new Set(); + const pending = [error]; + let reason: WorkerAuthReason | undefined; + while (pending.length) { + const current = pending.pop(); + if (typeof current !== 'object' || current === null || visited.has(current)) { + continue; + } + visited.add(current); + if ('name' in current) { + switch (current.name) { + case authErrorNames.signInRequired: + return 'signInRequired'; + case authErrorNames.identityMismatch: + return 'identityMismatch'; + case authErrorNames.destinationRejected: + return 'destinationRejected'; + case authErrorNames.refreshFailed: + reason = 'refreshFailed'; + } + } + if ('cause' in current) { + pending.push(current.cause); + } + // MongoServerSelectionError keeps per-server errors on its topology description. + if ('reason' in current) { + pending.push(current.reason); + } + if ('servers' in current && current.servers instanceof Map) { + pending.push(...current.servers.values()); + } + if ('error' in current) { + pending.push(current.error); + } + } + return reason; +} + export type MainToWorkerMessage = | { readonly type: 'init'; @@ -111,6 +168,7 @@ export type MainToWorkerMessage = readonly requestId: string; readonly error: string; readonly errorName?: 'EntraDestinationRejectedError'; + readonly reason?: WorkerAuthReason; }; // ─── Worker → Main messages ───────────────────────────────────────────────── @@ -142,11 +200,13 @@ export type WorkerToMainMessage = readonly success: boolean; readonly error?: string; readonly errorName?: 'EntraDestinationRejectedError'; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'evalResult'; readonly requestId: string; readonly result: SerializableExecutionResult; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'evalError'; @@ -155,6 +215,7 @@ export type WorkerToMainMessage = readonly stack?: string; /** Error code from the database (e.g. 50 for MaxTimeMSExpired). */ readonly code?: number; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'shutdownComplete'; @@ -168,6 +229,8 @@ export type WorkerToMainMessage = readonly source?: 'vscode' | 'managedIdentity'; /** Client ID of a user-assigned managed identity, when `source` is 'managedIdentity'. */ readonly clientId?: string; + /** One shared Int32 set to 1 if the driver stops waiting for this Entra lookup. Telemetry only. */ + readonly driverAbortFlag?: SharedArrayBuffer; } | { readonly type: 'log'; diff --git a/src/documentdb/query-language/playground-completions/CollectionNameCache.ts b/src/documentdb/query-language/playground-completions/CollectionNameCache.ts index e69fc0bd7..dd11c0ba3 100644 --- a/src/documentdb/query-language/playground-completions/CollectionNameCache.ts +++ b/src/documentdb/query-language/playground-completions/CollectionNameCache.ts @@ -128,7 +128,9 @@ export class CollectionNameCache implements vscode.Disposable { const fetchPromise = (async (): Promise => { try { - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'playgroundCompletion'); + const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'playgroundCompletion', { + background: true, + }); // This call populates ClustersClient._collectionsCache await client.listCollections(databaseName); } catch (error) { diff --git a/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts b/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts index 3c3f070b6..2585791fe 100644 --- a/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts +++ b/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts @@ -3,7 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterAll, beforeEach, describe, expect, test, vi, type Mock } from 'vitest'; +import { afterAll, beforeAll, beforeEach, describe, expect, test, vi, type Mock } from 'vitest'; +import { type Disposable, type Event } from 'vscode'; /** * TDD Behavior Tests — Dynamic Schema Integration (WI-3) @@ -39,6 +40,10 @@ const TEST_CONNECTION = { databaseName: 'testdb', }; +const onDidChangeLatch: Event = (_listener: (event: string) => unknown): Disposable => ({ + dispose: vi.fn(), +}); + // ===================================================================== // Tests: CollectionNameCache // ===================================================================== @@ -46,6 +51,13 @@ const TEST_CONNECTION = { describe('TDD: CollectionNameCache', () => { let cache: CollectionNameCache; + beforeAll(() => { + Object.defineProperty(ClustersClient, 'onDidChangeLatch', { + configurable: true, + get: (): Event => onDidChangeLatch, + }); + }); + beforeEach(() => { // Reset singleton for isolation CollectionNameCache.getInstance().dispose(); 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 new file mode 100644 index 000000000..70906fb25 --- /dev/null +++ b/src/documentdb/runWithClient.ts @@ -0,0 +1,67 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * 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 RunOptions { + readonly background?: boolean; + readonly trigger?: ClientStartupTrigger; +} + +interface Unavailable { + readonly unavailable: { readonly reason: ConnectionUnavailableReason }; +} + +function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailable | undefined { + switch (kind) { + case 'signInRequired': + case 'credentialsRejected': + case 'credentialsMissing': + case 'identityChanged': + return { unavailable: { reason: kind } }; + default: + return undefined; + } +} + +export async function runWithClient( + binding: ConnectionBinding, + op: (client: ClustersClient) => Promise, + options?: RunOptions, +): Promise { + const credentials = CredentialCache.getCredentials(binding.clusterId); + const authMethod = credentials ? (credentials.authMechanism ?? AuthMethodId.NativeAuth) : undefined; + let client: ClustersClient; + try { + 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, authMethod).kind); + if (unavailable) { + return unavailable; + } + throw error; + } + + try { + ClustersClient.assertBindingActive(binding); + return await op(client); + } catch (error) { + // Resolution can advance the generation without changing the surface's identity. + const unavailable = unavailableFor(ClustersClient.reportFailure(client.binding, error)); + if (unavailable) { + return unavailable; + } + throw error; + } +} diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 5911adea3..b077c30f8 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -8,15 +8,38 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockIn import { type UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; import { accumulateTelemetry } from '../../utils/accumulatingTelemetry'; import { AuthMethodId } from '../auth/AuthMethod'; import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; +import { SchemaStore } from '../SchemaStore'; import { DocumentDBShellPty, type DocumentDBShellPtyOptions } from './DocumentDBShellPty'; import { ShellCompletionProvider } from './ShellCompletionProvider'; +import { + ShellSessionManager, + type ShellConnectionInfo, + type ShellSessionCallbacks, + type UnauthenticatedShellEndpoint, +} from './ShellSessionManager'; import { ShellSpinner } from './ShellSpinner'; const mockSessionTelemetry: Record[] = []; +const workerSignIn = vi.hoisted(() => ({ + canRecover: vi.fn(), + recover: vi.fn(), + fingerprint: undefined as string | undefined, + pin: undefined as + | { + kind: 'entra'; + providerId: string; + accountId: string; + accountLabel: string; + tenantId: string; + } + | undefined, +})); // callWithTelemetryAndErrorHandling from @microsoft/vscode-azext-utils silently swallows // errors in the test environment because its internal error handling relies on extension @@ -75,6 +98,11 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ ), })); +vi.mock('../../commands/signInAgain/signInAgain', () => ({ + canSignInAgainForWorker: workerSignIn.canRecover, + signInAgainForWorker: workerSignIn.recover, +})); + // Mock ShellSessionManager const mockInitialize = vi.fn().mockResolvedValue({ host: 'test-host.documents.azure.com:10255', @@ -86,9 +114,15 @@ const mockEvaluate = vi.fn(); const mockDispose = vi.fn(); const mockKillWorker = vi.fn(); const mockSetActiveDatabase = vi.fn(); +const mockResetAfterSignIn = vi.fn(); vi.mock('./ShellSessionManager', () => ({ - ShellSessionManager: vi.fn().mockImplementation(function (_connectionInfo, callbacks) { + ShellSessionManager: vi.fn().mockImplementation(function ( + connectionInfo: ShellConnectionInfo, + callbacks: ShellSessionCallbacks, + _telemetry: unknown, + unauthenticated?: UnauthenticatedShellEndpoint, + ) { // Store callbacks so tests can trigger events (mockInitialize as Mock & { _callbacks?: unknown })._callbacks = callbacks; return { @@ -97,7 +131,20 @@ vi.mock('./ShellSessionManager', () => ({ dispose: mockDispose, killWorker: mockKillWorker, setActiveDatabase: mockSetActiveDatabase, + resetAfterSignIn: mockResetAfterSignIn, + pinnedEntraIdentity: workerSignIn.pin, + get fingerprint(): string | undefined { + return workerSignIn.fingerprint; + }, isInitialized: true, + getBlockingLatchReason: (): ReturnType => { + const reason = ClustersClient.getLatchReason(connectionInfo.clusterId); + return unauthenticated && + reason && + ['credentialsRejected', 'signInRequired', 'credentialsMissing'].includes(reason) + ? undefined + : reason; + }, }; }), })); @@ -121,6 +168,9 @@ describe('DocumentDBShellPty', () => { beforeEach(() => { vi.clearAllMocks(); mockSessionTelemetry.length = 0; + workerSignIn.pin = undefined; + workerSignIn.fingerprint = undefined; + workerSignIn.canRecover.mockReturnValue(false); written = ''; closeCode = undefined; terminalName = undefined; @@ -171,7 +221,793 @@ describe('DocumentDBShellPty', () => { vi.restoreAllMocks(); }); + describe('Playground handoff origins', () => { + it('has no origin before the shell learns its fingerprint', (): void => { + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + }); + + it('keeps the original pin and live origin through host-only same-account repair', (): void => { + pty.close(); + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + }; + workerSignIn.fingerprint = 'original-fingerprint'; + pty = new DocumentDBShellPty(defaultOptions); + const origin = pty.getPlaygroundOrigin(); + expect(origin).toMatchObject({ + kind: 'shell', + fingerprint: 'original-fingerprint', + entraIdentity: workerSignIn.pin, + }); + ClustersClient.invalidate(defaultOptions.connectionInfo.clusterId); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toMatchObject({ + kind: 'shell', + fingerprint: 'original-fingerprint', + }); + }); + + it('retires captured origins and terminal-info callbacks when the shell closes', (): void => { + workerSignIn.fingerprint = 'current-fingerprint'; + const origin = pty.getPlaygroundOrigin(); + const getPlaygroundOrigin = pty.getTerminalInfo().getPlaygroundOrigin; + + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + expect(getPlaygroundOrigin?.()).toMatchObject({ + kind: 'shell', + fingerprint: 'current-fingerprint', + }); + + pty.close(); + + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(false); + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + expect(getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + }); + + it('permanently retires old and newly rescanned origins after explicit disconnect without a host client', (): void => { + workerSignIn.fingerprint = 'password-identity-fingerprint'; + const host = vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(undefined); + const origin = pty.getPlaygroundOrigin(); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + pty.disconnect(); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(false); + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + // Restarting the worker cannot make this old terminal's scrollback a new origin. + workerSignIn.fingerprint = 'password-identity-fingerprint'; + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + expect(host).not.toHaveBeenCalled(); + expect(mockKillWorker).toHaveBeenCalledOnce(); + }); + }); + + describe('unauthenticated isolation', () => { + const unauthenticated: UnauthenticatedShellEndpoint = { + connectionString: 'mongodb://anonymous-host/', + reread: async (): Promise => 'mongodb://anonymous-host/', + }; + let noCache: MockInstance; + let noClient: MockInstance; + let noSchema: MockInstance; + let noExplanation: MockInstance; + let noPrewarm: MockInstance; + + beforeEach((): void => { + pty.close(); + noCache = vi.spyOn(CredentialCache, 'getCredentials'); + noClient = vi.spyOn(ClustersClient, 'getExistingClient'); + noSchema = vi.spyOn(SchemaStore, 'getInstance'); + noExplanation = vi.spyOn(ErrorExplanationService, 'explain'); + noPrewarm = vi.spyOn(ShellCompletionProvider.prototype, 'prewarmCollections'); + pty = new DocumentDBShellPty({ ...defaultOptions, unauthenticated }); + pty.onDidWrite((data): void => { + written += data; + }); + mockInitialize.mockResolvedValueOnce({ + host: 'anonymous-host', + additionalHostCount: 0, + authMechanism: 'NoAuth', + isEmulator: false, + }); + mockEvaluate.mockResolvedValue({ type: 'string', printable: '"x"', durationMs: 1 }); + }); + + afterEach((): void => { + pty.close(); + for (const spy of [noCache, noClient, noSchema, noExplanation, noPrewarm]) { + expect(spy).not.toHaveBeenCalled(); + } + }); + + async function openAnonymous(): Promise { + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + } + + it('never exposes a saved-auth Playground origin from the diagnostic shell', (): void => { + workerSignIn.fingerprint = 'saved-auth-fingerprint'; + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + }); + + it('passes the anonymous option to the session and metadata-free context to local completions', async (): Promise => { + const completions = vi.spyOn(ShellCompletionProvider.prototype, 'getCompletions'); + await openAnonymous(); + expect(vi.mocked(ShellSessionManager).mock.calls.at(-1)?.[3]).toBe(unauthenticated); + pty.handleInput('hel'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(completions).toHaveBeenCalledWith('hel', 3, { + clusterId: 'test-cluster-id', + databaseName: 'testdb', + includeClusterMetadata: false, + }); + pty.handleInput('\t'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockEvaluate).toHaveBeenLastCalledWith('help', 80); + }); + + it('keeps local history suggestions without schema hints', async (): Promise => { + settingOverrides['documentDB.shell.display.colorSupport'] = true; + await openAnonymous(); + pty.handleInput("db['restaurants-something'].find()"); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + written = ''; + pty.handleInput('db['); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(written).toContain("\x1b[2m'restaurants-something'].find()"); + }); + + it('keeps closing-bracket ghosts even when shared schema is unavailable', async (): Promise => { + await openAnonymous(); + pty.handleInput('db.c.find({ _id: 1 '); + await new Promise((resolve) => setTimeout(resolve, 80)); + pty.handleInput('\x1b[C'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockEvaluate).toHaveBeenLastCalledWith('db.c.find({ _id: 1 })', 80); + }); + + it('uses the shared anonymous latch policy and reports rejection without authenticated fallback', async (): Promise => { + await openAnonymous(); + ClustersClient.latch('test-cluster-id', 'credentialsRejected'); + try { + mockEvaluate.mockRejectedValueOnce(new Error('Command requires authentication')); + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toContain('Command requires authentication'); + expect(written).not.toContain('saved credentials were rejected'); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(workerSignIn.recover).not.toHaveBeenCalled(); + } finally { + ClustersClient.unlatch('test-cluster-id'); + } + }); + + it('does not prewarm after use or feed anonymous query documents into shared schema', async (): Promise => { + await openAnonymous(); + mockEvaluate.mockResolvedValueOnce({ type: 'string', printable: '"switched to db next"', durationMs: 1 }); + pty.handleInput('use next'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + mockEvaluate.mockResolvedValueOnce({ + type: 'Document', + printable: '{"_id":1,"name":"value"}', + durationMs: 1, + source: { namespace: { db: 'next', collection: 'users' } }, + }); + pty.handleInput('db.users.find()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockSetActiveDatabase).toHaveBeenCalledWith('next'); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + }); + + it('omits only the shared-schema ghost hint for unknown fields', async (): Promise => { + await openAnonymous(); + pty.handleInput('db.users.find({ nam'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(mockEvaluate).not.toHaveBeenCalled(); + expect(noSchema).not.toHaveBeenCalled(); + }); + + it('handles anonymous initialization failures without cache-backed explanations or redaction', async (): Promise => { + const notification = vi.spyOn(vscode.window, 'showErrorMessage'); + mockInitialize.mockReset().mockRejectedValueOnce(new Error('Server requires authentication')); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toContain('Server requires authentication'); + expect(ext.outputChannel.error).toHaveBeenCalled(); + expect(notification).not.toHaveBeenCalled(); + mockInitialize.mockResolvedValue({ + host: 'test-host.documents.azure.com:10255', + additionalHostCount: 0, + authMechanism: 'NativeAuth', + isEmulator: false, + }); + }); + }); + describe('open', () => { + it.each([false, true])( + 'offers one non-modal pinned recovery, respecting a superseding epoch (%s)', + async (superseded): Promise => { + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + workerSignIn.canRecover.mockReturnValue(true); + let epoch = 0; + vi.spyOn(ClustersClient, 'getEpoch').mockImplementation(() => epoch); + workerSignIn.recover.mockImplementationOnce(async () => { + const signInEpoch = ++epoch; + if (superseded) { + epoch++; + } + return { identity: workerSignIn.pin, epoch: signInEpoch }; + }); + pty = new DocumentDBShellPty(defaultOptions); + pty.onDidWrite((data) => { + written += data; + }); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + mockEvaluate.mockRejectedValueOnce( + Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), + ); + const action = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); + const modal = vi.spyOn(vscode.window, 'showErrorMessage'); + + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toContain('Microsoft sign-in is required for this shell. Sign in again to continue.'); + expect(written).not.toContain('private session miss'); + expect(action).toHaveBeenCalledExactlyOnceWith( + 'Microsoft sign-in is required for this shell. Sign in again to continue.', + 'Sign in again', + ); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledOnce(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + if (superseded) { + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + } else { + expect(mockResetAfterSignIn).toHaveBeenCalledExactlyOnceWith(workerSignIn.pin, 1); + } + }, + ); + + describe('stale sign-in notifications', () => { + let chooseAction: (choice: vscode.MessageItem | undefined) => void; + let warning: MockInstance; + let modal: MockInstance; + let getLatchReason: MockInstance; + let getEpoch: MockInstance; + let connectionStateCalls: MockInstance[]; + + beforeEach(async (): Promise => { + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + workerSignIn.canRecover.mockReturnValue(true); + getEpoch = vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(0); + getLatchReason = vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue(undefined); + pty = new DocumentDBShellPty(defaultOptions); + pty.onDidWrite((data): void => { + written += data; + }); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + warning = vi.spyOn(vscode.window, 'showWarningMessage').mockImplementationOnce( + () => + new Promise((resolve) => { + chooseAction = resolve; + }), + ); + modal = vi.spyOn(vscode.window, 'showErrorMessage'); + mockEvaluate.mockRejectedValueOnce( + Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), + ); + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(warning).toHaveBeenCalledOnce()); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + mockInitialize.mockClear(); + vi.mocked(ShellSessionManager).mockClear(); + connectionStateCalls = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'setCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'clearLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'startAfterSignIn'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(ClustersClient, 'latch'), + vi.spyOn(ClustersClient, 'unlatch'), + vi.spyOn(ClustersClient, 'invalidate'), + ]; + }); + + it.each([ + [ + 'before click', + 'connectionRemoved', + 'This connection was removed. Open a shell from another connection.', + ], + [ + 'before click', + 'credentialsChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'before click', + 'identityChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'during sign-in', + 'connectionRemoved', + 'This connection was removed. Open a shell from another connection.', + ], + [ + 'during sign-in', + 'credentialsChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'during sign-in', + 'identityChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + ] as const)( + 'explains %s %s on the existing terminal only', + async (stage, reason, message): Promise => { + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue(reason); + } else { + workerSignIn.recover.mockImplementationOnce(async (): Promise => { + getLatchReason.mockReturnValue(reason); + return undefined; + }); + } + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe(`\r\x1b[8C\x1b[J\r\n${message}\r\ntestdb> \r\x1b[8C\x1b[J`); + expect(warning).toHaveBeenCalledExactlyOnceWith( + 'Microsoft sign-in is required for this shell. Sign in again to continue.', + 'Sign in again', + ); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(ShellSessionManager).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(mockDispose).not.toHaveBeenCalled(); + expect(workerSignIn.canRecover).toHaveBeenCalledOnce(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }, + ); + + it.each([ + ['success', '', 0, 80, '\r\x1b[8C\x1b[J', '\r\x1b[8C\x1b[J', 'X'], + ['success', 'abcdef', 2, 80, '\r\x1b[8Cabcdef\x1b[J', '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', 'abXcdef'], + [ + 'before click', + 'abcdef', + 2, + 80, + '\r\x1b[8Cabcdef\x1b[J', + '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', + 'abXcdef', + ], + [ + 'during sign-in', + 'abcdef', + 2, + 80, + '\r\x1b[8Cabcdef\x1b[J', + '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', + 'abXcdef', + ], + [ + 'success', + 'db.collection.find()', + 15, + 20, + '\x1b[1A\r\x1b[8Cdb.collection.find()\x1b[J', + '\r\x1b[8Cdb.collection.find()\x1b[J\r\x1b[3C', + 'db.collection.fXind()', + ], + [ + 'before click', + 'db.collection.find()', + 2, + 20, + '\r\x1b[8Cdb.collection.find()\x1b[J', + '\r\x1b[8Cdb.collection.find()\x1b[J\r\x1b[1A\x1b[10C', + 'dbX.collection.find()', + ], + [ + 'during sign-in', + 'db.c.find(1)', + 0, + 20, + '\r\x1b[8Cdb.c.find(1)\x1b[J', + '\r\x1b[8Cdb.c.find(1)\x1b[J\r\x1b[8C', + 'Xdb.c.find(1)', + ], + ] as const)( + 'redraws %s feedback around "%s" at cursor %s, width %s without resetting or submitting it', + async (stage, input, cursor, columns, oldRender, newRender, nextCommand): Promise => { + const message = + stage === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This connection was removed. Open a shell from another connection.'; + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue('connectionRemoved'); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + if (stage === 'during sign-in') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + } + pty.setDimensions({ columns, rows: 24 }); + pty.handleInput(input); + pty.handleInput('\x1b[H'); + for (let i = 0; i < cursor; i++) { + pty.handleInput('\x1b[C'); + } + const resetLine = vi.spyOn(pty['_inputHandler'], 'resetLine'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe(`${oldRender}\r\n${message}\r\ntestdb> ${newRender}`); + expect(resetLine).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).toHaveBeenCalledTimes(stage === 'success' ? 1 : 0); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(modal).not.toHaveBeenCalled(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + + getLatchReason.mockReturnValue(undefined); + mockEvaluate.mockResolvedValueOnce({ type: 'string', printable: '"continued"', durationMs: 1 }); + pty.handleInput('X'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith(nextCommand, columns); + }, + ); + + it.each(['success', 'failure'] as const)( + 'preserves the continuation prompt and accumulated lines after delayed %s', + async (outcome): Promise => { + const message = + outcome === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This shell is bound to the previous connection. Open a new shell from the tree.'; + workerSignIn.recover.mockImplementationOnce(async () => { + if (outcome === 'failure') { + getLatchReason.mockReturnValue('identityChanged'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + pty.handleInput('db.test.find({'); + pty.handleInput('\r'); + pty.handleInput('name: "partial"'); + pty.handleInput('\x1b[H'); + const resetLine = vi.spyOn(pty['_inputHandler'], 'resetLine'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe( + `\r\x1b[4Cname: "partial"\x1b[J\r\n${message}\r\n┆ > \r\x1b[4Cname: "partial"\x1b[J\r\x1b[4C`, + ); + expect(resetLine).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + + getLatchReason.mockReturnValue(undefined); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('// '); + pty.handleInput('\r'); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(written.endsWith('\r\n┆ > ')).toBe(true); + pty.handleInput('})'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('db.test.find({\n// name: "partial"\n})', 80); + }, + ); + + it.each(['success', 'before click', 'during sign-in'] as const)( + 'defers %s feedback during evaluation until the next database prompt', + async (stage): Promise => { + let resolveEvaluation!: (result: unknown) => void; + mockEvaluate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveEvaluation = resolve; + }), + ); + pty.handleInput('use 日本語'); + pty.handleInput('\r'); + written = ''; + const message = + stage === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This connection was removed. Open a shell from another connection.'; + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue('connectionRemoved'); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + if (stage === 'during sign-in') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + } + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(''); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + resolveEvaluation({ type: null, printable: '"switched to db 日本語"', durationMs: 1 }); + await vi.waitFor(() => expect(written).toContain('日本語> ')); + + expect(written).toBe(`switched to db 日本語\r\n${message}\r\n日本語> `); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + getLatchReason.mockReturnValue(undefined); + written = ''; + pty.handleInput('\r'); + expect(written).toBe('\r\n日本語> '); + written = ''; + pty.handleInput('x'); + expect(written).toBe('\r\x1b[8Cx\x1b[J'); + }, + ); + + it.each([ + ['success', 'closed'], + ['success', 'disconnected'], + ['failure', 'closed'], + ['failure', 'disconnected'], + ] as const)( + 'discards queued %s feedback when the terminal is %s', + async (outcome, terminalState): Promise => { + let resolveEvaluation!: (result: unknown) => void; + mockEvaluate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveEvaluation = resolve; + }), + ); + pty.handleInput('pending()'); + pty.handleInput('\r'); + written = ''; + workerSignIn.recover.mockImplementationOnce(async () => { + if (outcome === 'failure') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toBe(''); + if (terminalState === 'closed') { + pty.close(); + } else { + pty.disconnect(); + } + const boundaryOutput = terminalState === 'closed' ? '' : 'Disconnected\r\ntestdb> '; + expect(written).toBe(boundaryOutput); + resolveEvaluation({ type: 'string', printable: '"obsolete result"', durationMs: 1 }); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(boundaryOutput); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + if (terminalState === 'disconnected') { + getLatchReason.mockReturnValue(undefined); + pty.handleInput('\r'); + expect(written).toBe(`${boundaryOutput}\r\ntestdb> `); + } + }, + ); + + it('waits for a safe prompt when input is disabled without an evaluation', async (): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + pty['_inputHandler'].setEnabled(false); + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(mockResetAfterSignIn).toHaveBeenCalledOnce()); + + expect(written).toBe(''); + expect(mockEvaluate).toHaveBeenCalledOnce(); + pty['_inputHandler'].setEnabled(true); + pty.handleInput('\r'); + expect(written).toBe('\r\nSign-in restored. Run your command again.\r\ntestdb> '); + written = ''; + pty.handleInput('\r'); + expect(written).toBe('\r\ntestdb> '); + }); + + it('keeps the history selection and its saved draft after delayed success', async (): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + pty.handleInput('draft()'); + pty.handleInput('\x1b[A'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain('Sign-in restored.')); + + expect(written).toBe( + '\r\x1b[8Cdb.stats()\x1b[J\r\nSign-in restored. Run your command again.\r\ntestdb> \r\x1b[8Cdb.stats()\x1b[J', + ); + expect(mockEvaluate).toHaveBeenCalledOnce(); + written = ''; + pty.handleInput('\x1b[B'); + expect(written).toBe('\r\x1b[8Cdraft()\x1b[J'); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('draft()', 80); + }); + + it.each(['pending ghost', 'visible ghost', 'completion list'] as const)( + 'clears %s without resurrecting or accepting a suggestion after delayed success', + async (suggestionState): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + const completions = vi.spyOn(ShellCompletionProvider.prototype, 'getCompletions').mockReturnValue({ + candidates: + suggestionState === 'completion list' + ? [ + { label: 'help', insertText: 'help', kind: 'method' }, + { label: 'hello', insertText: 'hello', kind: 'method' }, + ] + : [{ label: 'help', insertText: 'help', kind: 'method' }], + prefix: 'hel', + replacementStart: 0, + }); + pty.handleInput('hel'); + if (suggestionState === 'visible ghost') { + await vi.waitFor(() => expect(written).toContain('p\x1b[1D')); + } else if (suggestionState === 'completion list') { + pty.handleInput('\x09'); + expect(written).toContain('hello'); + } + completions.mockClear(); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain('Sign-in restored.')); + + const feedbackOutput = written; + expect(written).toBe( + `${suggestionState === 'visible ghost' ? '\x1b[K' : ''}\r\x1b[8Chel\x1b[J\r\nSign-in restored. Run your command again.\r\ntestdb> \r\x1b[8Chel\x1b[J`, + ); + expect(pty['_completionListVisible']).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(written).toBe(feedbackOutput); + expect(completions).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('\x1b[C'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('hel', 80); + }, + ); + + it.each([ + ['before click', 'cancelled'], + ['before click', 'closed'], + ['before click', 'revision changed'], + ['before click', 'epoch only'], + ['before click', 'unproven no latch'], + ['before click', 'already completed'], + ['during sign-in', 'cancelled'], + ['during sign-in', 'closed'], + ['during sign-in', 'revision changed'], + ['during sign-in', 'epoch only'], + ['during sign-in', 'unproven no latch'], + ['during sign-in', 'already completed'], + ] as const)('keeps %s %s quiet without reviving the worker', async (stage, outcome): Promise => { + const supersede = (): void => { + if (outcome === 'closed') { + pty.close(); + } else if (outcome === 'revision changed') { + pty.disconnect(); + } + getEpoch.mockReturnValue(2); + getLatchReason.mockReturnValue( + outcome === 'closed' || outcome === 'revision changed' || outcome === 'cancelled' + ? 'connectionRemoved' + : undefined, + ); + written = ''; + mockDispose.mockClear(); + mockKillWorker.mockClear(); + }; + if (stage === 'before click') { + supersede(); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + supersede(); + if (outcome === 'cancelled') { + const { UserCancelledError } = await import('@microsoft/vscode-azext-utils'); + throw new UserCancelledError('shell.signInAgain'); + } + return outcome === 'unproven no latch' ? undefined : { identity: workerSignIn.pin, epoch: 1 }; + }); + } + + chooseAction( + stage === 'before click' && outcome === 'cancelled' + ? undefined + : ('Sign in again' as unknown as vscode.MessageItem), + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(''); + expect(warning).toHaveBeenCalledOnce(); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(ShellSessionManager).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(mockDispose).not.toHaveBeenCalled(); + expect(workerSignIn.canRecover).toHaveBeenCalledOnce(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }); + }); + it('carries URL attribution into actual shell startup', async (): Promise => { const deepLink = { deepLinkCorrelationId: 'link-attempt', deepLinkSource: 'docs' }; pty = new DocumentDBShellPty({ ...defaultOptions, deepLink }); @@ -353,10 +1189,12 @@ describe('DocumentDBShellPty', () => { }); it('should show error and stay open on connection failure', async () => { + const notification = vi.spyOn(vscode.window, 'showErrorMessage'); mockInitialize.mockRejectedValue(new Error('Connection refused')); pty.open(undefined); await new Promise((resolve) => setTimeout(resolve, 10)); expect(written).toContain('Failed to connect: Connection refused'); + expect(notification).toHaveBeenCalledOnce(); // Closing would dispose the terminal and take the message with it; the prompt lets the // user retry, since evaluate() re-initializes an uninitialized session. expect(closeCode).toBeUndefined(); @@ -392,6 +1230,116 @@ describe('DocumentDBShellPty', () => { written = ''; // Reset to capture only subsequent output }); + it('should put a disconnect while idle on its own line with one new prompt', () => { + pty.disconnect(); + + expect(written).toBe('\r\nDisconnected\r\ntestdb> '); + expect(written.match(/Disconnected/g)).toHaveLength(1); + expect(written.match(/testdb> /g)).toHaveLength(1); + }); + + it('should preserve and visibly redraw partially typed single-line input after disconnect', async () => { + mockEvaluate.mockResolvedValue({ + type: 'string', + printable: '"continued"', + durationMs: 1, + }); + pty.handleInput('db.stats'); + written = ''; + + pty.disconnect(); + + expect(written).toBe('\r\nDisconnected\r\ntestdb> \r\x1b[8Cdb.stats\x1b[J'); + expect(written.match(/Disconnected/g)).toHaveLength(1); + expect(written.match(/testdb> /g)).toHaveLength(1); + + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('db.stats', 80); + }); + + it('should preserve the logical cursor in partially typed single-line input after disconnect', async () => { + mockEvaluate.mockResolvedValue({ + type: 'string', + printable: '"continued"', + durationMs: 1, + }); + pty.handleInput('abcdef'); + pty.handleInput('\x1b[H'); + pty.handleInput('\x1b[C'); + pty.handleInput('\x1b[C'); + + pty.disconnect(); + + expect(mockEvaluate).not.toHaveBeenCalled(); + pty.handleInput('X'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('abXcdef', 80); + }); + + it('should move to the end of a wrapped partial line before disconnect output', () => { + const input = 'db.collection.find()'; + expect(input).toHaveLength(20); + pty.setDimensions({ columns: 20, rows: 24 }); + pty.handleInput(input); + pty.handleInput('\x1b[H'); + written = ''; + + pty.disconnect(); + + expect(written).toBe( + `\r\x1b[8C${input}\x1b[J\r\nDisconnected\r\ntestdb> \r\x1b[8C${input}\x1b[J\r\x1b[1A\x1b[8C`, + ); + expect(mockEvaluate).not.toHaveBeenCalled(); + }); + + it('should stop an evaluation without an extra newline or late output after disconnect', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ); + + pty.handleInput('db.test.find()'); + pty.handleInput('\r'); + written = ''; + pty.disconnect(); + + expect(written).toBe('Disconnected\r\ntestdb> '); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(written).toBe('Disconnected\r\ntestdb> '); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('db.test.find()', 80); + }); + + it('should keep prior multi-line output but discard the pending line on disconnect', async () => { + pty.handleInput('db.test.find({'); + pty.handleInput('\r'); + pty.handleInput('name: "partial"'); + const priorOutput = written; + + pty.disconnect(); + + const disconnectOutput = written.slice(priorOutput.length); + expect(written.startsWith(priorOutput)).toBe(true); + expect(disconnectOutput).toBe('\r\nDisconnected\r\ntestdb> '); + + mockEvaluate.mockResolvedValue({ + type: null, + printable: '"fresh"', + durationMs: 1, + }); + pty.handleInput('fresh()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('fresh()', 80); + }); + it('should show new prompt on empty Enter', async () => { pty.handleInput('\r'); await new Promise((resolve) => setTimeout(resolve, 10)); @@ -426,6 +1374,70 @@ describe('DocumentDBShellPty', () => { expect(written).toContain('test result'); }); + it('should reset rejected input before the connection can reconnect', async () => { + const getLatchReason = vi + .spyOn(ClustersClient, 'getLatchReason') + .mockReturnValueOnce('userDisconnected') + .mockReturnValue(undefined); + mockEvaluate.mockResolvedValue({ + type: null, + printable: '"done"', + durationMs: 1, + }); + + pty.handleInput('rejected'); + pty.handleInput('\r'); + expect(written).toContain('Disconnected'); + expect(written).toContain('testdb> '); + + written = ''; + pty.handleInput('accepted'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('accepted', 80); + expect(getLatchReason).toHaveBeenCalled(); + }); + + it.each([ + ['userDisconnected', 'Disconnected. Reconnect from the tree, then run your command again.'], + ['unreachable', 'The connection is unavailable. Check the server or network, then run your command again.'], + [ + 'credentialsRejected', + 'The saved credentials were rejected. Update them from the tree, then run your command again.', + ], + [ + 'credentialsUpdating', + 'This connection is being updated. Run your command again when the update finishes.', + ], + ['connectionRemoved', 'This connection was removed. Open a shell from another connection.'], + ['credentialsChanged', 'This shell is bound to the previous connection. Open a new shell from the tree.'], + ['identityChanged', 'This shell is bound to the previous connection. Open a new shell from the tree.'], + [ + 'credentialsMissing', + 'This connection is unavailable. Reconnect from the tree, then run your command again.', + ], + ['signInRequired', 'This connection is unavailable. Reconnect from the tree, then run your command again.'], + ] as const)('uses %s guidance for latch and worker failures', async (reason, message) => { + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValueOnce(reason).mockReturnValue(undefined); + + pty.handleInput('blocked'); + pty.handleInput('\r'); + expect(written).toContain(message); + expect(mockEvaluate).not.toHaveBeenCalled(); + + written = ''; + const failure = new ConnectionUnavailableError(reason); + mockEvaluate.mockRejectedValueOnce(failure); + + pty.handleInput('retry'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toContain(message); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('retry', 80); + }); + it('should display error message on evaluation failure', async () => { mockEvaluate.mockRejectedValue(new Error('Syntax error')); @@ -436,6 +1448,27 @@ describe('DocumentDBShellPty', () => { expect(written).toContain('Syntax error'); }); + it('should suppress the worker termination error when Disconnect cancels evaluation', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ); + + pty.handleInput('db.test.find()'); + pty.handleInput('\r'); + pty.disconnect(); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(written).toContain('Disconnected'); + expect(written).not.toContain('Worker terminated'); + }); + it('should normalize bare \\n in multi-line error messages to \\r\\n', async () => { // Many driver / server error messages embed bare LFs to delimit // a multi-line explanation. Without normalization the terminal @@ -1528,6 +2561,32 @@ describe('DocumentDBShellPty', () => { expect(mockEvaluate).toHaveBeenNthCalledWith(1, 'show dbs', 80); expect(mockEvaluate).toHaveBeenNthCalledWith(2, 'use newdb', 80); }); + + it('should discard queued pasted commands when Disconnect cancels evaluation', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ) + .mockResolvedValue({ + type: null, + printable: '"done"', + durationMs: 1, + }); + + pty.handleInput('show dbs\nuse newdb\n'); + pty.disconnect(); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('show dbs', 80); + expect(written.split('testdb> ')).toHaveLength(2); + }); }); describe('multi-line paste dialog', () => { diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index a11ab46d3..a758b1d2a 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -7,6 +7,8 @@ import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsof import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; +import { type PlaygroundHandoffOrigin } from '../../commands/playground/newPlayground'; +import { canSignInAgainForWorker, signInAgainForWorker } from '../../commands/signInAgain/signInAgain'; import { type DeepLinkTelemetry, trackDeepLinkTelemetry } from '../../deepLinks/deepLinkTelemetry'; import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -17,9 +19,14 @@ import { COMPLETION_OFFERED_EVENT, type CompletionCategory } from '../../telemet import { accumulateTelemetry } from '../../utils/accumulatingTelemetry'; import { classifyCommand, extractRunCommandName } from '../../utils/classifyCommand'; import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { deserializeResultForSchema, feedResultToSchemaStore } from '../feedResultToSchemaStore'; -import { type SerializableExecutionResult } from '../playground/workerTypes'; +import { + getWorkerAuthReason, + type SerializableExecutionResult, + type WorkerAuthReason, +} from '../playground/workerTypes'; import { SchemaStore } from '../SchemaStore'; import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; import { addDomainInfoToProperties } from '../utils/getClusterMetadata'; @@ -31,7 +38,12 @@ import { findCommonPrefix, renderCompletionList } from './ShellCompletionRendere import { ShellGhostText } from './ShellGhostText'; import { ShellInputHandler } from './ShellInputHandler'; import { extractErrorCode, ShellOutputFormatter } from './ShellOutputFormatter'; -import { type ShellConnectionInfo, type ShellSessionCallbacks, ShellSessionManager } from './ShellSessionManager'; +import { + type ShellConnectionInfo, + type ShellSessionCallbacks, + ShellSessionManager, + type UnauthenticatedShellEndpoint, +} from './ShellSessionManager'; import { ShellSpinner } from './ShellSpinner'; import { ACTION_LINE_PREFIX, @@ -49,6 +61,7 @@ const COMPACT_CONNECTION_SUMMARY_MIN_COLUMNS = 100; * Configuration for the interactive shell Pseudoterminal. */ export interface DocumentDBShellPtyOptions { + readonly unauthenticated?: UnauthenticatedShellEndpoint; readonly deepLink?: DeepLinkTelemetry; /** Connection parameters for the shell session. */ readonly connectionInfo: ShellConnectionInfo; @@ -80,6 +93,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private readonly _inputHandler: ShellInputHandler; private readonly _outputFormatter: ShellOutputFormatter; private readonly _connectionInfo: ShellConnectionInfo; + private readonly _unauthenticated: UnauthenticatedShellEndpoint | undefined; /** Current database name — updated when `use ` changes it. */ private _currentDatabase: string; @@ -89,6 +103,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private _evaluating = false; /** Whether the shell has been closed. */ private _closed = false; + private readonly _deferredFeedback: string[] = []; /** Whether the current evaluation was cancelled by Ctrl+C. */ private _interrupted = false; /** Spinner shown during long-running evaluations. */ @@ -122,6 +137,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** Unique session ID for correlating all events within this shell session. */ private readonly _shellSessionId: string = randomUUID(); + private _disconnectRevision = 0; /** Extension client whose metadata describes this cluster, captured once when the shell is created. */ private readonly _connectionCorrelationId?: string; /** Running count of commands evaluated in this session (for commandIndex measurement). */ @@ -137,6 +153,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { constructor(options: DocumentDBShellPtyOptions) { this._deepLink = options.deepLink; this._connectionInfo = options.connectionInfo; + this._unauthenticated = options.unauthenticated; this._currentDatabase = options.connectionInfo.databaseName; this._initialInput = options.initialInput; @@ -175,13 +192,18 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { }, }; - this._connectionCorrelationId = ClustersClient.getExistingClient( - options.connectionInfo.clusterId, - )?.connectionCorrelationId; - this._sessionManager = new ShellSessionManager(options.connectionInfo, sessionCallbacks, { - shellSessionId: this._shellSessionId, - connectionCorrelationId: this._connectionCorrelationId, - }); + this._connectionCorrelationId = options.unauthenticated + ? undefined + : ClustersClient.getExistingClient(options.connectionInfo.clusterId)?.connectionCorrelationId; + this._sessionManager = new ShellSessionManager( + options.connectionInfo, + sessionCallbacks, + { + shellSessionId: this._shellSessionId, + connectionCorrelationId: this._connectionCorrelationId, + }, + options.unauthenticated, + ); this._outputFormatter = new ShellOutputFormatter(); @@ -230,6 +252,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { close(): void { this._closed = true; + this._deferredFeedback.length = 0; this._spinner?.stop(); this._spinner = undefined; if (this._ghostTextTimer) { @@ -263,6 +286,35 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { } } + /** Keep the terminal and its scrollback, but stop the database worker. */ + public disconnect(): void { + const wasEvaluating = this._evaluating; + const retainPartialInput = !wasEvaluating && !this._inputHandler.isInMultiLineMode; + const partialInput = retainPartialInput ? this._inputHandler.getBuffer() : ''; + const partialCursor = retainPartialInput ? this._inputHandler.getCursor() : 0; + + this._disconnectRevision += 1; + this._deferredFeedback.length = 0; + this.clearGhostState(); + this._spinner?.stop(); + this._spinner = undefined; + this._evaluating = false; + this._inputHandler.clearPendingInput(); + if (!wasEvaluating) { + this._inputHandler.handleInput('\x1b[F'); + this.writeLine(''); + } + this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + this._sessionManager.killWorker(); + this._inputHandler.setEnabled(true); + if (!this._closed) { + this.showPrompt(); + if (partialInput.length > 0) { + this._inputHandler.restoreLine(partialInput, partialCursor); + } + } + } + /** * Associate this PTY with its terminal instance. * Called by the command handler after `createTerminal()`. @@ -274,6 +326,19 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** * Returns current shell metadata for the terminal link provider and debug stats. */ + getPlaygroundOrigin(): PlaygroundHandoffOrigin { + const fingerprint = this._sessionManager.fingerprint; + if (this._closed || this._unauthenticated || !fingerprint || this._disconnectRevision > 0) { + return { kind: 'none' }; + } + return { + kind: 'shell', + fingerprint, + entraIdentity: this._sessionManager.pinnedEntraIdentity, + isCurrent: () => !this._closed && this._disconnectRevision === 0, + }; + } + getTerminalInfo(): ShellTerminalInfo { return { clusterId: this._connectionInfo.clusterId, @@ -284,6 +349,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { workerState: this._sessionManager.workerState, authMethod: this._sessionManager.authMethod, username: this._username, + getPlaygroundOrigin: () => this.getPlaygroundOrigin(), }; } @@ -484,6 +550,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // ─── Private: Session initialization ───────────────────────────────────── private async initializeSession(): Promise { + const disconnectRevision = this._disconnectRevision; try { const metadata = await callWithTelemetryAndErrorHandling('shell.sessionStart', async (context) => { context.errorHandling.suppressDisplay = true; @@ -502,14 +569,19 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { Object.assign(context.telemetry.properties, domainProps); return metadata; }); + if (disconnectRevision !== this._disconnectRevision) { + return; + } if (!metadata) { throw new UserCancelledError('shell.sessionStart'); } - void this._completionProvider.prewarmCollections({ - clusterId: this._connectionInfo.clusterId, - databaseName: this._currentDatabase, - }); + if (!this._unauthenticated) { + void this._completionProvider.prewarmCollections({ + clusterId: this._connectionInfo.clusterId, + databaseName: this._currentDatabase, + }); + } // Stop the connection spinner this._spinner?.stop(); @@ -605,10 +677,19 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._initialInput = undefined; } } catch (error: unknown) { + if (disconnectRevision !== this._disconnectRevision) { + return; + } // Stop the connection spinner on failure this._spinner?.stop(); this._spinner = undefined; + if (this.handleWorkerFailure(error)) { + this._inputHandler.setEnabled(true); + this.showPrompt(); + return; + } + const rawMessage = error instanceof Error ? error.message : String(error); // Strip technical error codes for clean user-facing output; // the extracted code is preserved for future telemetry. @@ -617,10 +698,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // Written as a separate line rather than merged into the message above, so the raw text // stays intact for extractErrorCode and the SettingsHintError check below. - const explanation = await ErrorExplanationService.explain({ - clusterId: this._connectionInfo.clusterId, - error, - }); + const explanation = this._unauthenticated + ? undefined + : await ErrorExplanationService.explain({ + clusterId: this._connectionInfo.clusterId, + error, + }); if (explanation) { this.writeLine(this._outputFormatter.formatError(explanation.message)); } @@ -642,13 +725,15 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // A notification as well: the terminal may be in the background, or closed by the user // before they read it. - void vscode.window.showErrorMessage( - explanation?.message ?? - l10n.t('Failed to connect to "{cluster}": {error}', { - cluster: this._connectionInfo.clusterDisplayName, - error: errorMessage, - }), - ); + if (!this._unauthenticated) { + void vscode.window.showErrorMessage( + explanation?.message ?? + l10n.t('Failed to connect to "{cluster}": {error}', { + cluster: this._connectionInfo.clusterDisplayName, + error: errorMessage, + }), + ); + } // Deliberately no _closeEmitter.fire(): disposing the terminal would take the message // with it. The session is still uninitialized, so ShellSessionManager.evaluate() re-runs @@ -666,6 +751,15 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // ─── Private: Line handling ────────────────────────────────────────────── private async handleLineInput(line: string): Promise { + const disconnectRevision = this._disconnectRevision; + const latchReason = this._sessionManager.getBlockingLatchReason(); + if (latchReason) { + this.handleWorkerFailure(new ConnectionUnavailableError(latchReason)); + if (!this._closed) { + this.showPrompt(); + } + return; + } const trimmed = line.trim(); // Empty line — just show a new prompt @@ -687,33 +781,37 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { try { await this.evaluateInput(trimmed); } catch (error: unknown) { - await this.handleEvalError(error); + if (disconnectRevision === this._disconnectRevision) { + await this.handleEvalError(error); + } } finally { - // Stop the spinner before writing results or the next prompt. - this._spinner?.stop(); - this._spinner = undefined; + if (disconnectRevision === this._disconnectRevision) { + this._spinner?.stop(); + this._spinner = undefined; - this._evaluating = false; + this._evaluating = false; - // If Ctrl+C was pressed, the interrupt handler already re-enabled - // input and showed a prompt — don't duplicate. - if (!this._interrupted) { - this._inputHandler.setEnabled(true); + // If Ctrl+C was pressed, the interrupt handler already re-enabled + // input and showed a prompt — don't duplicate. + if (!this._interrupted) { + this._inputHandler.setEnabled(true); - if (!this._closed) { - this.showPrompt(); + if (!this._closed) { + this.showPrompt(); - // Process any input that was queued during execution - // (e.g., remaining lines from a multi-line paste). - this._inputHandler.processPendingInput(); + // Process any input that was queued during execution + // (e.g., remaining lines from a multi-line paste). + this._inputHandler.processPendingInput(); + } } - } - this._interrupted = false; + this._interrupted = false; + } } } private async evaluateInput(input: string): Promise { + const disconnectRevision = this._disconnectRevision; this._commandCount++; const commandIndex = this._commandCount; const commandCategory = classifyCommand(input); @@ -739,25 +837,26 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { try { result = await this._sessionManager.evaluate(input, this._columns); } catch (evalError) { - // Ctrl+C kills the worker, producing a "Worker terminated" error. - // Re-classify as user cancellation for accurate telemetry. - if (this._interrupted) { + // Ctrl+C and Disconnect both kill the worker, producing a + // "Worker terminated" error. Re-classify intentional + // cancellation for accurate telemetry and UI behavior. + if (this._interrupted || disconnectRevision !== this._disconnectRevision) { throw new UserCancelledError('shell.eval'); } throw evalError; } - // Stop the spinner before writing any output so the spinner - // character doesn't collide with the result text. - this._spinner?.stop(); - this._spinner = undefined; - // If this eval was cancelled by Ctrl+C, skip output — the interrupt // handler already showed ^C and a new prompt. - if (this._interrupted) { + if (this._interrupted || disconnectRevision !== this._disconnectRevision) { return; } + // Stop the spinner before writing any output so the spinner + // character doesn't collide with the result text. + this._spinner?.stop(); + this._spinner = undefined; + // ── Post-eval telemetry ────────────────────────────────────── context.telemetry.properties.resultType = result.type ?? 'null'; @@ -794,9 +893,13 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._spinner?.stop(); this._spinner = undefined; - // Suppress errors from intentional Ctrl+C cancellation — the interrupt - // handler already showed ^C and a new prompt. - if (this._interrupted) { + // Suppress errors from intentional cancellation. Ctrl+C renders its own + // prompt, while Disconnect renders its own terminal status. + if (this._interrupted || error instanceof UserCancelledError) { + return; + } + + if (this.handleWorkerFailure(error)) { return; } @@ -810,10 +913,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // talks to gets stopped, a port-forward drops — and the next command is where they find // out. Written as a separate line so the raw text above stays intact for extractErrorCode // and the checks below. - const explanation = await ErrorExplanationService.explain({ - clusterId: this._connectionInfo.clusterId, - error, - }); + const explanation = this._unauthenticated + ? undefined + : await ErrorExplanationService.explain({ + clusterId: this._connectionInfo.clusterId, + error, + }); if (explanation) { this.writeLine(this._outputFormatter.formatError(explanation.message)); } @@ -833,6 +938,147 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { } } + private handleWorkerFailure(error: unknown): boolean { + const authReason = getWorkerAuthReason(error); + if (authReason) { + this.writeBoundedWorkerFailure(authReason); + return true; + } + if (error instanceof ConnectionUnavailableError) { + this.writeLine(this._outputFormatter.formatError(this.unavailableMessage(error.reason))); + return true; + } + return false; + } + + private unavailableMessage(reason: ConnectionUnavailableReason): string { + switch (reason) { + case 'userDisconnected': + return l10n.t('Disconnected. Reconnect from the tree, then run your command again.'); + case 'unreachable': + return l10n.t( + 'The connection is unavailable. Check the server or network, then run your command again.', + ); + case 'credentialsRejected': + return l10n.t( + 'The saved credentials were rejected. Update them from the tree, then run your command again.', + ); + case 'credentialsUpdating': + return l10n.t('This connection is being updated. Run your command again when the update finishes.'); + case 'connectionRemoved': + return l10n.t('This connection was removed. Open a shell from another connection.'); + case 'credentialsChanged': + case 'identityChanged': + return l10n.t('This shell is bound to the previous connection. Open a new shell from the tree.'); + default: + return l10n.t('This connection is unavailable. Reconnect from the tree, then run your command again.'); + } + } + + private writeBoundedWorkerFailure(reason: WorkerAuthReason): void { + const pin = this._sessionManager.pinnedEntraIdentity; + if (reason === 'signInRequired' && pin && canSignInAgainForWorker(this._connectionInfo.clusterId, pin)) { + const message = l10n.t('Microsoft sign-in is required for this shell. Sign in again to continue.'); + this.writeLine(this._outputFormatter.formatError(message)); + this.offerShellSignInAgain(pin, message); + return; + } + + let message: string; + switch (reason) { + case 'signInRequired': + message = l10n.t('Microsoft sign-in is required for this shell. Open a new shell from the tree.'); + break; + case 'identityMismatch': + message = l10n.t( + 'This shell is bound to a different Microsoft account. Open a new shell from the tree.', + ); + break; + case 'destinationRejected': + message = l10n.t( + 'This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.', + ); + break; + case 'refreshFailed': + message = l10n.t( + 'The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.', + ); + break; + } + this.writeLine(this._outputFormatter.formatError(message)); + } + + private offerShellSignInAgain( + identity: NonNullable, + message: string, + ): void { + const action = l10n.t('Sign in again'); + const { clusterId } = this._connectionInfo; + const revision = this._disconnectRevision; + const epoch = ClustersClient.getEpoch(clusterId); + void vscode.window.showWarningMessage(message, action).then(async (choice) => { + if ( + choice !== action || + this._closed || + revision !== this._disconnectRevision || + ClustersClient.getEpoch(clusterId) !== epoch + ) { + if (choice === action && !this._closed && revision === this._disconnectRevision) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + this.writeAsyncFeedback(this._outputFormatter.formatError(this.unavailableMessage(reason))); + } + } + return; + } + try { + await callWithTelemetryAndErrorHandling('shell.signInAgain', async (context) => { + context.errorHandling.suppressDisplay = true; + context.errorHandling.rethrow = true; + context.telemetry.properties.shellSessionId = this._shellSessionId; + const result = await signInAgainForWorker(context, clusterId, identity); + if ( + !result || + this._closed || + revision !== this._disconnectRevision || + ClustersClient.getEpoch(clusterId) !== result.epoch + ) { + if (!this._closed && revision === this._disconnectRevision) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + this.writeAsyncFeedback( + this._outputFormatter.formatError(this.unavailableMessage(reason)), + ); + } + } + return; + } + this._sessionManager.resetAfterSignIn(result.identity, result.epoch); + this.writeAsyncFeedback( + this._outputFormatter.formatSystemMessage(l10n.t('Sign-in restored. Run your command again.')), + ); + }); + } catch (error) { + if (error instanceof UserCancelledError) { + return; + } + if (!this._closed && revision === this._disconnectRevision) { + void vscode.window.showWarningMessage( + l10n.t('Could not sign in again. Open a new shell from the tree.'), + ); + } + } + }); + } + /** * Handle special intercepted results (exit, clear). * Returns true if the result was handled (no further output needed). @@ -890,10 +1136,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { if (newDb) { this._currentDatabase = newDb; this._sessionManager.setActiveDatabase(newDb); - void this._completionProvider.prewarmCollections({ - clusterId: this._connectionInfo.clusterId, - databaseName: newDb, - }); + if (!this._unauthenticated) { + void this._completionProvider.prewarmCollections({ + clusterId: this._connectionInfo.clusterId, + databaseName: newDb, + }); + } this.updateTerminalTitle(); } } @@ -938,7 +1186,41 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._ghostTextTimer = undefined; } + if (!this._closed) { + for (const line of this._deferredFeedback.splice(0)) { + this.writeLine(line); + } + } + this._writeEmitter.fire(prompt); + } + + private writeAsyncFeedback(line: string): void { + if (this._closed) { + return; + } + if (this._evaluating || !this._inputHandler.isEnabled) { + this._deferredFeedback.push(line); + return; + } + + const text = this._inputHandler.buffer; + const cursor = this._inputHandler.cursor; + this.clearGhostState(); + if (this._ghostTextTimer) { + clearTimeout(this._ghostTextTimer); + this._ghostTextTimer = undefined; + } + this._completionListVisible = false; + + // Use the old render origin to move past all wrapped input before writing feedback. + this._inputHandler.restoreLine(text, text.length); + this._writeEmitter.fire('\r\n'); + this.writeLine(line); + + const prompt = this._inputHandler.isInMultiLineMode ? '┆ > ' : `${this._currentDatabase}> `; + this._inputHandler.setPromptWidth(terminalDisplayWidth(prompt)); this._writeEmitter.fire(prompt); + this._inputHandler.restoreLine(text, cursor); } /** @@ -1056,6 +1338,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { * Failures are silently ignored — schema feeding is best-effort. */ private maybeFeedSchemaStore(result: SerializableExecutionResult): void { + if (this._unauthenticated) { + return; + } // Only Cursor and Document results with a namespace are worth parsing if (result.type !== 'Cursor' && result.type !== 'Document') { return; @@ -1183,6 +1468,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { return this._completionProvider.getCompletions(buffer, cursor, { clusterId: this._connectionInfo.clusterId, databaseName: this._currentDatabase, + ...(this._unauthenticated ? { includeClusterMetadata: false } : {}), }); } @@ -1343,7 +1629,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // No completions inside a method argument — show schema hint only if // SchemaStore has no fields for this collection (not just a typo/no match) - if (result.candidates.length === 0) { + if (!this._unauthenticated && result.candidates.length === 0) { const ctx = this._completionProvider.detectContext(buffer, cursor); if (ctx.kind === 'method-argument') { const fields = SchemaStore.getInstance().getKnownFields( @@ -1542,6 +1828,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** Cached secrets for this cluster, so they can be redacted before anything is logged. */ private credentialSecrets(): string[] { + if (this._unauthenticated) { + return [this._unauthenticated.connectionString]; + } const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); return [credentials?.nativeAuthConfig?.connectionPassword, credentials?.connectionString].filter( (secret): secret is string => !!secret, @@ -1554,11 +1843,13 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { */ private collectShellDomainTelemetry(properties: Record): void { try { - const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); - if (!credentials?.connectionString) { + const connectionString = this._unauthenticated + ? this._unauthenticated.connectionString + : CredentialCache.getCredentials(this._connectionInfo.clusterId)?.connectionString; + if (!connectionString) { return; } - const hosts = getHostsFromConnectionString(credentials.connectionString); + const hosts = getHostsFromConnectionString(connectionString); addDomainInfoToProperties(hosts, properties); } catch { // Domain info is best-effort — don't fail telemetry if parsing fails diff --git a/src/documentdb/shell/ShellCompletionProvider.test.ts b/src/documentdb/shell/ShellCompletionProvider.test.ts index 81e496fbe..d4efe02a4 100644 --- a/src/documentdb/shell/ShellCompletionProvider.test.ts +++ b/src/documentdb/shell/ShellCompletionProvider.test.ts @@ -63,6 +63,34 @@ describe('ShellCompletionProvider', () => { mockSchemaStore(); }); + describe('metadata-free completions', () => { + const context = { ...TEST_CONTEXT, includeClusterMetadata: false }; + + it.each(['use ', 'db[', "db['", 'db.users.find({ na'])( + 'does not consult shared clients or schema for %s', + async (input): Promise => { + expect(provider.getCompletions(input, input.length, context).candidates).toEqual([]); + await provider.prewarmCollections(context); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(SchemaStore.getInstance).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['hel', 'command'], + ['db.', 'method'], + ['db.users.', 'method'], + ['db.users.find({ $', 'operator'], + ['db.users.find({ _id: ', 'bson'], + ] as const)('retains local %s completions (%s)', (input, kind): void => { + const result = provider.getCompletions(input, input.length, context); + expect(result.candidates.length).toBeGreaterThan(0); + expect(result.candidates.some((candidate) => candidate.kind === kind)).toBe(true); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(SchemaStore.getInstance).not.toHaveBeenCalled(); + }); + }); + describe('context detection', () => { it('should detect empty buffer as top-level', () => { const ctx = provider.detectContext('', 0); diff --git a/src/documentdb/shell/ShellCompletionProvider.ts b/src/documentdb/shell/ShellCompletionProvider.ts index ec0861d75..03794440e 100644 --- a/src/documentdb/shell/ShellCompletionProvider.ts +++ b/src/documentdb/shell/ShellCompletionProvider.ts @@ -56,6 +56,7 @@ export interface CompletionCandidate { * Context required by the completion provider to resolve dynamic completions. */ export interface ShellCompletionContext { + readonly includeClusterMetadata?: boolean; /** Stable cluster ID for cache lookups. */ readonly clusterId: string; /** Current active database name. */ @@ -164,6 +165,9 @@ export class ShellCompletionProvider { * Warm the collection cache for a database without blocking shell input. */ async prewarmCollections(context: ShellCompletionContext): Promise { + if (context.includeClusterMetadata === false) { + return; + } const fetchKey = `colls:${context.clusterId}:${context.databaseName}`; if (this._backgroundFetchTriggered.has(fetchKey)) { return; @@ -584,6 +588,9 @@ export class ShellCompletionProvider { * Get database name candidates from ClustersClient cache + SchemaStore. */ private getDatabaseCandidates(context: ShellCompletionContext): CompletionCandidate[] { + if (context.includeClusterMetadata === false) { + return []; + } const candidates: CompletionCandidate[] = []; const seen = new Set(); @@ -651,7 +658,8 @@ export class ShellCompletionProvider { const seen = new Set(); // Collection names from ClustersClient cache - const client = ClustersClient.getExistingClient(context.clusterId); + const client = + context.includeClusterMetadata === false ? undefined : ClustersClient.getExistingClient(context.clusterId); if (client) { const cached = client.getCachedCollections(context.databaseName); if (cached) { @@ -668,15 +676,17 @@ export class ShellCompletionProvider { } // Collection names from SchemaStore - const store = SchemaStore.getInstance(); - const stats = store.getStats(); - const keyPrefix = `${context.clusterId}::${context.databaseName}::`; - for (const coll of stats.collections) { - if (coll.key.startsWith(keyPrefix)) { - const collName = coll.key.substring(keyPrefix.length); - if (collName && !seen.has(collName)) { - seen.add(collName); - candidates.push(this.makeCollectionCandidate(collName)); + if (context.includeClusterMetadata !== false) { + const store = SchemaStore.getInstance(); + const stats = store.getStats(); + const keyPrefix = `${context.clusterId}::${context.databaseName}::`; + for (const coll of stats.collections) { + if (coll.key.startsWith(keyPrefix)) { + const collName = coll.key.substring(keyPrefix.length); + if (collName && !seen.has(collName)) { + seen.add(collName); + candidates.push(this.makeCollectionCandidate(collName)); + } } } } @@ -712,6 +722,9 @@ export class ShellCompletionProvider { * `db['` inserts `restaurants']`. */ private getDbBracketCandidates(context: ShellCompletionContext, quote: '"' | "'" | ''): CompletionCandidate[] { + if (context.includeClusterMetadata === false) { + return []; + } const candidates: CompletionCandidate[] = []; const seen = new Set(); @@ -811,12 +824,13 @@ export class ShellCompletionProvider { } // Build a field type lookup from SchemaStore (pre-compute Map for O(1) lookups) - const fields = SchemaStore.getInstance().getKnownFields( - shellCtx.clusterId, - shellCtx.databaseName, - ctx.collectionName, + const fieldTypeByPath = new Map( + shellCtx.includeClusterMetadata === false + ? [] + : SchemaStore.getInstance() + .getKnownFields(shellCtx.clusterId, shellCtx.databaseName, ctx.collectionName) + .map((f) => [f.path, f.type]), ); - const fieldTypeByPath = new Map(fields.map((f) => [f.path, f.type])); const fieldLookup: FieldTypeLookup = (fieldName: string): string | undefined => { return fieldTypeByPath.get(fieldName); }; @@ -876,6 +890,9 @@ export class ShellCompletionProvider { context: ShellCompletionContext, collectionName: string, ): void { + if (context.includeClusterMetadata === false) { + return; + } const fields = SchemaStore.getInstance().getKnownFields( context.clusterId, context.databaseName, diff --git a/src/documentdb/shell/ShellInputHandler.test.ts b/src/documentdb/shell/ShellInputHandler.test.ts index 91c4a7178..439664c47 100644 --- a/src/documentdb/shell/ShellInputHandler.test.ts +++ b/src/documentdb/shell/ShellInputHandler.test.ts @@ -566,6 +566,51 @@ describe('ShellInputHandler', () => { }); }); + describe('restoreLine', () => { + it('should restore text and cursor without firing onBufferChange', () => { + let changeCount = 0; + const restoreHandler = new ShellInputHandler({ + write: () => {}, + onLine: () => {}, + onInterrupt: () => {}, + onContinuation: () => {}, + onBufferChange: () => { + changeCount++; + }, + }); + + restoreHandler.restoreLine('abcdef', 2); + restoreHandler.handleInput('X'); + + expect(restoreHandler.getBuffer()).toBe('abXcdef'); + expect(restoreHandler.getCursor()).toBe(3); + expect(changeCount).toBe(1); + }); + + it.each([ + [-1, 0], + [99, 6], + ])('should clamp cursor %s to %s', (cursor, expected) => { + handler.restoreLine('abcdef', cursor); + + expect(handler.getCursor()).toBe(expected); + }); + + it('should preserve multiline state and history', () => { + handler.handleInput('db.test.find({'); + handler.handleInput('\r'); + + handler.restoreLine('})', 2); + expect(handler.isInMultiLineMode).toBe(true); + handler.handleInput('\r'); + expect(lines).toEqual(['db.test.find({\n})']); + + handler.resetLine(); + handler.handleInput('\x1b[A'); + expect(handler.getBuffer()).toBe('db.test.find({ })'); + }); + }); + describe('replaceText', () => { it('should replace text before cursor with new text', () => { handler.handleInput('address.ci'); diff --git a/src/documentdb/shell/ShellInputHandler.ts b/src/documentdb/shell/ShellInputHandler.ts index b848ea808..fde86d182 100644 --- a/src/documentdb/shell/ShellInputHandler.ts +++ b/src/documentdb/shell/ShellInputHandler.ts @@ -213,6 +213,13 @@ export class ShellInputHandler { } } + /** + * Discard input queued behind an evaluation that will no longer resume. + */ + clearPendingInput(): void { + this._pendingInput = ''; + } + /** * Get the current line buffer content. */ @@ -277,6 +284,15 @@ export class ShellInputHandler { this.reRenderLine(); } + /** + * Restore the current line text and logical cursor position. + */ + restoreLine(text: string, cursor: number): void { + this._buffer = text; + this._cursor = Math.max(0, Math.min(cursor, text.length)); + this.reRenderLine(); + } + /** * Replace text before the cursor and insert new text. * Used by the PTY when a completion needs to replace the typed prefix diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 071210175..33cd2c9fc 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -3,7 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; +import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest'; import * as vscode from 'vscode'; import { type AuthenticationSession } from 'vscode'; @@ -21,15 +22,19 @@ import { recordEntraTokenFailure, resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PlaygroundEvaluator } from '../playground/PlaygroundEvaluator'; -import { type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; -import { type MainToWorkerMessage, type WorkerToMainMessage } from '../playground/workerTypes'; +import { WorkerSessionManager, type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; +import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from '../playground/workerTypes'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { ShellSessionManager } from './ShellSessionManager'; +import { toUnauthenticatedConnectionString } from './unauthenticatedEndpoint'; const mockGetSessionFromVSCode = vi.fn(); const mockGetManagedIdentityAccessToken = vi.fn(); +const sendEval = vi.fn(); +const killWorker = vi.fn(); let workerCallbacks: WorkerSessionCallbacks; let workerClusterId: string | undefined; let requestTokenOnInit = false; @@ -46,8 +51,15 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]) => mockGetSessionFromVSCode(...args), +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getConfiguredAuthProviderId: () => 'microsoft', + getConfiguredAzureEnv: () => ({ name: 'AzureCloud' }), +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: (...args: unknown[]) => mockGetSessionFromVSCode(...args) }, })); vi.mock('../auth/managedIdentityTokenProvider', () => ({ @@ -85,7 +97,7 @@ vi.mock('../playground/WorkerSessionManager', () => ({ }, ), isConnectedTo: vi.fn(() => false), - sendEval: vi.fn().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }), + sendEval, get isAlive(): boolean { return true; }, @@ -96,6 +108,7 @@ vi.mock('../playground/WorkerSessionManager', () => ({ return workerClusterId; }, dispose: vi.fn(), + killWorker, }; }), })); @@ -103,8 +116,25 @@ vi.mock('../playground/WorkerSessionManager', () => ({ describe('ShellSessionManager', () => { const clusterId = 'test-cluster-id'; + it('does not initialize or evaluate a worker while the cluster is disconnected', async () => { + const manager = new ShellSessionManager({ + clusterId, + clusterDisplayName: 'Test Cluster', + databaseName: 'test', + }); + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'userDisconnected' }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'userDisconnected' }); + } finally { + ClustersClient.unlatch(clusterId); + manager.dispose(); + } + }); + beforeEach(() => { vi.clearAllMocks(); + sendEval.mockReset().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); resetEntraTokenFailuresForTests(); workerClusterId = clusterId; requestTokenOnInit = false; @@ -139,6 +169,373 @@ describe('ShellSessionManager', () => { resetEntraTokenFailuresForTests(); }); + describe('unauthenticated sessions', () => { + const endpoint = 'mongodb://localhost:27017/test?tls=true&tlsCAFile=trust.pem'; + let manager: ShellSessionManager; + const reread = vi.fn<() => Promise>(); + let cacheSpies: MockInstance[]; + + function ensureWorker(): Mock { + const worker = vi.mocked(WorkerSessionManager).mock.results.at(-1)?.value as { ensureWorker: Mock }; + return worker.ensureWorker; + } + + beforeEach((): void => { + reread.mockReset().mockResolvedValue(endpoint); + manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + undefined, + {}, + { + connectionString: endpoint, + emulatorConfiguration: { isEmulator: true, disableEmulatorSecurity: true }, + reread, + }, + ); + cacheSpies = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'hasCredentials'), + vi.spyOn(CredentialCache, 'getConnectionUser'), + vi.spyOn(CredentialCache, 'getConnectionStringWithPassword'), + vi.spyOn(CredentialCache, 'getEmulatorConfiguration'), + vi.spyOn(CredentialCache, 'setAuthCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getExpectedFingerprint'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + ]; + }); + + afterEach((): void => { + for (const spy of cacheSpies) { + expect(spy).not.toHaveBeenCalled(); + } + manager.dispose(); + ClustersClient.unlatch(clusterId); + vi.restoreAllMocks(); + }); + + it('initializes NoAuth with server TLS intact and no identity relay or credential state', async (): Promise => { + const metadata = await manager.initialize(); + expect(metadata).toMatchObject({ authMechanism: 'NoAuth', username: undefined, isEmulator: true }); + expect(ensureWorker()).toHaveBeenCalledWith( + clusterId, + { + type: 'init', + requestId: '', + connectionString: endpoint, + databaseName: 'test', + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { serverSelectionTimeoutMS: 4000, tlsAllowInvalidCertificates: true }, + }, + expect.anything(), + {}, + true, + ); + expect(manager.pinnedEntraIdentity).toBeUndefined(); + const post = vi.fn(); + await workerCallbacks.onTokenRequest?.({ type: 'tokenRequest', requestId: 'token' }, post, () => true); + expect(post).not.toHaveBeenCalled(); + expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); + }); + + it('starts and evaluates when cached credentials have already been evicted', async (): Promise => { + vi.mocked(CredentialCache.deleteCredentials).mockRestore(); + CredentialCache.deleteCredentials(clusterId); + const deletion = vi.spyOn(CredentialCache, 'deleteCredentials'); + cacheSpies[6] = deletion; + await manager.initialize(); + await manager.evaluate('db.stats()'); + expect(sendEval).toHaveBeenCalledOnce(); + }); + + it.each([ + ['mongodb://127.0.0.1/?tls=true', true, 4000], + ['mongodb://public.example.com/?tls=true&tlsCAFile=trust.pem', undefined, undefined], + ] as const)('preserves host-gated TLS rules for %s', async (connectionString, tls, timeout): Promise => { + manager.dispose(); + manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + undefined, + {}, + { + connectionString, + emulatorConfiguration: { isEmulator: false, disableEmulatorSecurity: true }, + reread: async (): Promise => connectionString, + }, + ); + await expect(manager.initialize()).resolves.toMatchObject({ isEmulator: false }); + expect(ensureWorker().mock.calls[0][1]).toMatchObject({ + connectionString, + authMechanism: 'NoAuth', + clientOptions: { tlsAllowInvalidCertificates: tls, serverSelectionTimeoutMS: timeout }, + }); + }); + + it('surfaces anonymous startup rejection without authentication or a retry', async (): Promise => { + const rejection = Object.assign(new Error('Authentication required'), { code: 13 }); + ensureWorker().mockRejectedValueOnce(rejection); + await expect(manager.initialize()).rejects.toBe(rejection); + expect(ensureWorker()).toHaveBeenCalledOnce(); + expect(manager.isInitialized).toBe(false); + expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); + }); + + it.each(['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const)( + 'allows %s at initialization and evaluation without clearing the hold', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + expect(manager.getBlockingLatchReason()).toBeUndefined(); + await manager.initialize(); + await manager.evaluate('db.stats()'); + expect(sendEval).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each([ + 'credentialsUpdating', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', + ] as const)('blocks %s before endpoint reads, initialization and evaluation', async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + expect(manager.getBlockingLatchReason()).toBe(reason); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason }); + expect(reread).not.toHaveBeenCalled(); + expect(ensureWorker()).not.toHaveBeenCalled(); + expect(sendEval).not.toHaveBeenCalled(); + }); + + it.each([ + [undefined, 'connectionRemoved'], + ['mongodb://other-host/test', 'credentialsChanged'], + ] as const)('blocks endpoint %s before worker initialization', async (current, reason): Promise => { + reread.mockResolvedValue(current); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }); + + it.each([ + [undefined, 'connectionRemoved'], + ['mongodb://other-host/test', 'credentialsChanged'], + ] as const)( + 'blocks endpoint %s changed during worker initialization', + async (current, reason): Promise => { + reread.mockResolvedValueOnce(endpoint).mockResolvedValueOnce(current); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(manager.isInitialized).toBe(false); + }, + ); + + it.each(['endpointRead', 'workerInitialization'] as const)( + 'honors a superseding epoch during %s', + async (phase): Promise => { + let epoch = 0; + vi.spyOn(ClustersClient, 'getEpoch').mockImplementation(() => epoch); + const changeEpoch = async (): Promise => { + epoch++; + return endpoint; + }; + if (phase === 'endpointRead') { + reread.mockImplementationOnce(changeEpoch); + } else { + ensureWorker().mockImplementationOnce(changeEpoch); + } + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(manager.isInitialized).toBe(false); + }, + ); + + it.each(['credentialsUpdating', 'userDisconnected', 'connectionRemoved'] as const)( + 'honors %s introduced while awaiting the endpoint', + async (reason): Promise => { + reread.mockImplementationOnce(async (): Promise => { + ClustersClient.latch(clusterId, reason); + return endpoint; + }); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }, + ); + + it('does not finish or respawn a disposed session', async (): Promise => { + reread.mockImplementationOnce(async (): Promise => { + manager.dispose(); + return endpoint; + }); + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'connectionRemoved' }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'connectionRemoved' }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }); + + it('permits password-only edits on respawn but never switches endpoints', async (): Promise => { + await manager.initialize(); + manager.killWorker(); + reread.mockResolvedValue( + toUnauthenticatedConnectionString( + 'mongodb://user:new-password@localhost:27017/test?tls=true&tlsCAFile=trust.pem&authSource=admin', + ), + ); + await manager.evaluate('password-edit'); + manager.killWorker(); + reread.mockResolvedValue('mongodb://other-host/'); + await expect(manager.evaluate('changed-host')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(sendEval).toHaveBeenCalledOnce(); + }); + + it('surfaces anonymous database rejection without replay or authenticated fallback', async (): Promise => { + const rejection = Object.assign(new Error('Command requires authentication'), { code: 13 }); + await manager.initialize(); + sendEval.mockRejectedValueOnce(rejection); + await expect(manager.evaluate('db.stats()')).rejects.toBe(rejection); + expect(sendEval).toHaveBeenCalledOnce(); + expect(ensureWorker()).toHaveBeenCalledOnce(); + }); + + it('rejects a reply superseded by Disconnect', async (): Promise => { + await manager.initialize(); + sendEval.mockImplementationOnce(async (): Promise => { + ClustersClient.latch(clusterId, 'userDisconnected'); + return { result: { type: 'number', printable: '1', durationMs: 0 } }; + }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'userDisconnected' }); + }); + }); + + it('keeps ordinary Shell initialization authenticated with the saved native credentials', async (): Promise => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.NativeAuth, + 'mongodb://native.example.com/?tls=true', + { connectionUser: 'saved-user', connectionPassword: 'saved-password' }, + ); + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + const worker = vi.mocked(WorkerSessionManager).mock.results.at(-1)?.value as { ensureWorker: Mock }; + await expect(manager.initialize()).resolves.toMatchObject({ + authMechanism: 'NativeAuth', + username: 'saved-user', + }); + expect(worker.ensureWorker.mock.calls[0][1]).toMatchObject({ + authMechanism: 'NativeAuth', + connectionString: 'mongodb://saved-user:saved-password@native.example.com/?tls=true', + }); + manager.dispose(); + }); + + it('permits a password-only respawn but blocks a username change', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + const setNative = (connectionUser: string, connectionPassword: string): void => + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://native.example.com/', { + connectionUser, + connectionPassword, + }); + setNative('account-a', 'first'); + await manager.initialize(); + manager.killWorker(); + setNative('account-a', 'rotated'); + await manager.evaluate('password-only'); + manager.killWorker(); + setNative('account-b', 'rotated'); + await expect(manager.evaluate('different-account')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(sendEval).toHaveBeenCalledOnce(); + manager.dispose(); + }); + + it('keeps a healthy Shell and its pinned relay across a no-op save, but honors Disconnect', async (): Promise => { + const onReconnecting = vi.fn(); + const manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + { onReconnecting }, + ); + requestTokenOnInit = true; + const account = { id: 'account-a', label: 'Account A' }; + mockGetSessionFromVSCode.mockResolvedValue({ accessToken: 'private-token', account }); + await manager.initialize(); + await manager.evaluate('let keep = 1'); + + ClustersClient.latch(clusterId, 'credentialsUpdating'); + await expect(manager.evaluate('keep')).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + ClustersClient.unlatch(clusterId); + await manager.evaluate('keep'); + const reply = vi.fn(); + await workerCallbacks.onTokenRequest?.({ type: 'tokenRequest', requestId: 'refresh' }, reply, () => true); + expect(reply).toHaveBeenCalledWith({ + type: 'tokenResponse', + requestId: 'refresh', + accessToken: 'private-token', + }); + expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ silent: true, account }); + expect(killWorker).not.toHaveBeenCalled(); + expect(onReconnecting).not.toHaveBeenCalled(); + + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + manager.killWorker(); + await expect(manager.evaluate('keep')).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(killWorker).toHaveBeenCalledOnce(); + expect(sendEval).toHaveBeenCalledTimes(2); + } finally { + ClustersClient.unlatch(clusterId); + manager.dispose(); + } + }); + + it('holds a silent miss until the same account explicitly signs in and never replays the command', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + requestTokenOnInit = true; + mockGetSessionFromVSCode.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account-a', label: 'Account A' }, + }); + await manager.initialize(); + const identity = manager.pinnedEntraIdentity!; + const epoch = ClustersClient.getEpoch(clusterId); + sendEval.mockRejectedValueOnce(Object.assign(new Error('miss'), { name: 'EntraSignInRequiredError' })); + await expect(manager.evaluate('first')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); + await expect(manager.evaluate('blocked')).rejects.toMatchObject({ name: 'EntraSignInRequiredError' }); + expect(() => manager.resetAfterSignIn({ ...identity, accountId: 'account-b' }, epoch)).toThrow( + expect.objectContaining({ name: 'EntraIdentityMismatchError' }), + ); + manager.resetAfterSignIn(identity, epoch); + expect(sendEval).toHaveBeenCalledOnce(); + await manager.evaluate('next'); + expect(sendEval.mock.calls.map(([message]) => message.code)).toEqual(['first', 'next']); + expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ + silent: true, + account: { id: 'account-a', label: 'Account A' }, + }); + manager.dispose(); + }); + + it('retains the worker-learned fingerprint and Entra pin across a worker restart', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + requestTokenOnInit = true; + mockGetSessionFromVSCode.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account-a', label: 'Account A' }, + }); + try { + await manager.initialize(); + const fingerprint = manager.fingerprint; + const pin = manager.pinnedEntraIdentity; + expect(fingerprint).toEqual(expect.any(String)); + expect(pin).toMatchObject({ accountId: 'account-a' }); + manager.killWorker(); + ClustersClient.invalidate(clusterId); + await manager.initialize(); + expect(manager.fingerprint).toBe(fingerprint); + expect(manager.pinnedEntraIdentity).toEqual(pin); + } finally { + manager.dispose(); + } + }); + async function initializeSession( manager: ShellSessionManager | PlaygroundEvaluator, source?: 'vscode' | 'managedIdentity', @@ -162,6 +559,55 @@ describe('ShellSessionManager', () => { } } + it.each([ + ['shell', 'vscode', true], + ['shell', 'managedIdentity', false], + ['playground', 'vscode', false], + ['playground', 'managedIdentity', true], + ] as const)('ignores a late %s %s relay from an old epoch (rejects = %s)', async (surface, source, rejects) => { + const manager = + surface === 'shell' + ? new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }) + : new PlaygroundEvaluator(); + await initializeSession(manager, source); + const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; + const result = { accessToken: 'private-token', account: { id: 'account-a', label: 'Account A' } }; + let complete!: () => void; + provider.mockImplementationOnce(async () => { + await new Promise((resolve) => { + complete = resolve; + }); + if (rejects) { + throw new Error('private provider failure'); + } + return result; + }); + const reply = vi.fn(); + const startupProperties: Record = {}; + const pending = workerCallbacks.onTokenRequest?.( + { type: 'tokenRequest', requestId: 'old' }, + reply, + () => true, + undefined, + { startupCorrelationId: 'old-startup', surface, startupProperties }, + ); + await vi.waitFor(() => expect(provider).toHaveBeenCalledOnce()); + ClustersClient.latch(clusterId, 'userDisconnected'); + manager.killWorker(); + ClustersClient.unlatch(clusterId); + await initializeSession(manager, source); + if (!rejects) { + recordEntraTokenFailure(clusterId, { cloudCategory: 'public', authMethod: 'interactive' }); + } + const newerFailure = getRecentEntraTokenFailure(clusterId); + complete(); + await pending; + expect(reply).not.toHaveBeenCalled(); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + expect(getRecentEntraTokenFailure(clusterId)).toBe(newerFailure); + manager.dispose(); + }); + describe.each(['shell', 'playground'] as const)('%s relay destination enforcement', (surface) => { function createManager(): ShellSessionManager | PlaygroundEvaluator { return surface === 'shell' @@ -197,7 +643,10 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const postResponse = vi.fn(); const forged = { type: 'tokenRequest', @@ -223,8 +672,8 @@ describe('ShellSessionManager', () => { expect(resolveInteractiveTokenResource).toHaveBeenCalledExactlyOnceWith(original); expect(mockGetManagedIdentityAccessToken).not.toHaveBeenCalled(); expect(provider).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'original-tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:original-tenant'], { createIfNone: true }, ); } @@ -265,6 +714,7 @@ describe('ShellSessionManager', () => { requestId: 'rejected', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(startupProperties).toEqual({ entraDestinationClass: 'otherAzure', @@ -290,7 +740,10 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const postResponse = vi.fn(); await workerCallbacks.onTokenRequest?.( { type: 'tokenRequest', requestId: 'first' }, @@ -319,6 +772,7 @@ describe('ShellSessionManager', () => { requestId: 'refresh', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); manager.dispose(); }, @@ -347,7 +801,7 @@ describe('ShellSessionManager', () => { : mockGetSessionFromVSCode; provider.mockImplementationOnce(async () => { await gate; - return { accessToken: 'must-not-post', account: { label: 'private-account' } }; + return { accessToken: 'must-not-post', account: { id: 'account', label: 'private-account' } }; }); const response = vi.fn(); const startupProperties: Record = {}; @@ -367,6 +821,7 @@ describe('ShellSessionManager', () => { requestId: 'pending', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); @@ -472,7 +927,7 @@ describe('ShellSessionManager', () => { const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; provider.mockImplementationOnce(async () => { now = 40; - return { accessToken: 'private-token', account: { label: 'private-account' } }; + return { accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }; }); await initializeSession(manager, source); const stopDatabase = timings.startDatabaseConnect(); @@ -515,7 +970,7 @@ describe('ShellSessionManager', () => { } else { expect(ext.outputChannel.info).toHaveBeenCalledWith( expect.stringContaining( - `[Authentication] startup=startup-id surface=${surface} interactiveEntra.getSession`, + `[Authentication] startup=startup-id surface=${surface} workerTokenRelay.completed`, ), ); } @@ -550,7 +1005,10 @@ describe('ShellSessionManager', () => { }, }); const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; - provider.mockResolvedValueOnce({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValueOnce({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const manager = surface === 'shell' ? new ShellSessionManager({ clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }) @@ -574,7 +1032,10 @@ describe('ShellSessionManager', () => { entraFailureKind: 'none', }); expect(resolver).toHaveBeenCalledWith(connectionString); - expect(provider.mock.calls.at(-1)?.[0]).toEqual(['https://ossrdbms-aad.database.usgovcloudapi.net/.default']); + const args = provider.mock.calls.at(-1); + expect(args?.[source === 'vscode' ? 1 : 0]).toEqual([ + 'https://ossrdbms-aad.database.usgovcloudapi.net/.default', + ]); expect(postResponse).toHaveBeenCalledWith({ type: 'tokenResponse', requestId: 'token-request', @@ -623,7 +1084,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledWith({ type: 'tokenError', requestId: 'token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); manager.dispose(); }, @@ -675,7 +1137,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); expect(error.code).toBe('original-code'); expect(getRecentEntraTokenFailure(clusterId)).toEqual({ @@ -724,7 +1187,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenLastCalledWith({ type: 'tokenError', requestId: 'failed-token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); const failure = getRecentEntraTokenFailure(clusterId); expect(failure).toMatchObject({ @@ -736,7 +1200,7 @@ describe('ShellSessionManager', () => { provider.mockImplementationOnce(async () => { expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); - return { accessToken: 'private-token', account: { label: 'private-account' } }; + return { accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }; }); const successfulProperties: Record = {}; await workerCallbacks.onTokenRequest?.( @@ -785,7 +1249,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'token-request', - error: 'Failed to obtain Entra ID token.', + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); expect(getRecentEntraTokenFailure(clusterId)).toMatchObject({ cloudCategory: 'public', @@ -811,7 +1276,7 @@ describe('ShellSessionManager', () => { () => true, ); - expect(postResponse).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError' })); + expect(postResponse).not.toHaveBeenCalled(); expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); manager.dispose(); diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 8f7f9934c..233728a6a 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -7,31 +7,32 @@ import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; -import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; +import { type EmulatorConfiguration } from '../../utils/emulatorConfiguration'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; -import { CredentialCache } from '../CredentialCache'; -import { AuthMethodId } from '../auth/AuthMethod'; +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; +import { AuthMethodId } from '../auth/AuthMethodId'; +import { EntraIdentityMismatchError } from '../auth/entraErrors/entraCallbackErrors'; +import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; import { - resolveInteractiveTokenResource, - resolveManagedIdentityTokenResource, - TokenResourceResolutionError, - type ResolvedTokenResource, -} from '../auth/documentdbTokenResource'; -import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; -import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; -import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; + ConnectionUnavailableError, + isDiagnosticAuthenticationHold, + type ConnectionUnavailableReason, +} from '../ConnectionUnavailableError'; +import { CredentialCache } from '../CredentialCache'; import { WorkerSessionManager, type WorkerSessionCallbacks, type WorkerStartupTelemetryContext, } from '../playground/WorkerSessionManager'; import { + getWorkerAuthReason, type MainToWorkerMessage, type SerializableExecutionResult, type SerializableMongoClientOptions, - type WorkerToMainMessage, + type WorkerAuthReason, } from '../playground/workerTypes'; -import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; import { resolveAllowInvalidCertificates } from '../utils/tlsException'; @@ -47,6 +48,12 @@ export interface ShellConnectionInfo { readonly databaseName: string; } +export interface UnauthenticatedShellEndpoint { + readonly connectionString: string; + readonly emulatorConfiguration?: EmulatorConfiguration; + readonly reread: () => Promise; +} + /** * Connection metadata returned after successful initialization. * Used by the PTY to display connection summary in the terminal. @@ -92,8 +99,11 @@ export interface ShellSessionCallbacks { */ export class ShellSessionManager implements vscode.Disposable { private readonly _workerManager: WorkerSessionManager; - private _sessionInitMessage: Extract | undefined; - private _resolvedTokenResource: ResolvedTokenResource | undefined; + private _relay: WorkerTokenRelay | undefined; + private _fingerprint: string | undefined; + private _pin: VerifiedEntraIdentity | undefined; + private _authFailure: WorkerAuthReason | undefined; + private _disposed = false; private readonly _connectionInfo: ShellConnectionInfo; private readonly _callbacks: ShellSessionCallbacks | undefined; private readonly _managedIdentityTokenCorrelationId = randomUUID(); @@ -111,6 +121,7 @@ export class ShellSessionManager implements vscode.Disposable { connectionInfo: ShellConnectionInfo, callbacks?: ShellSessionCallbacks, private readonly _telemetryContext: WorkerStartupTelemetryContext = {}, + private readonly _unauthenticated?: UnauthenticatedShellEndpoint, ) { this._connectionInfo = connectionInfo; this._activeDatabase = connectionInfo.databaseName; @@ -141,13 +152,23 @@ export class ShellSessionManager implements vscode.Disposable { break; } }, - onTokenRequest: ( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ) => this.handleTokenRequest(msg, postResponse, isCurrent, timings, traceContext), + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { + const relay = this._relay; + // Warm Shells survive host-only invalidation. Fence each refresh at receipt; + // startup still uses the epoch captured before opening the connection. + const epoch = this._initialized + ? ClustersClient.getEpoch(this._connectionInfo.clusterId) + : relay?.epoch; + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + epoch, + ); + }, onWorkerExit: callbacks?.onWorkerExit, }; @@ -158,7 +179,9 @@ export class ShellSessionManager implements vscode.Disposable { * Whether the shell session has been initialized (worker spawned and connected). */ get isInitialized(): boolean { - return this._initialized && this._workerManager.isAlive; + return ( + this._initialized && this._workerManager.isAlive && !this._authFailure && !this._workerManager.authFailure + ); } /** @@ -189,6 +212,30 @@ export class ShellSessionManager implements vscode.Disposable { return this._authMethod; } + get pinnedEntraIdentity(): VerifiedEntraIdentity | undefined { + return this._pin; + } + + get fingerprint(): string | undefined { + return this._fingerprint; + } + + /** Accept only the same verified account; the next command reconnects and runs once. */ + public resetAfterSignIn(identity: VerifiedEntraIdentity, epoch: number): void { + this.assertConnectionAvailable(); + if (ClustersClient.getEpoch(this._connectionInfo.clusterId) !== epoch) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (!this._pin || !sameEntraIdentity(this._pin, identity)) { + throw new EntraIdentityMismatchError(); + } + if (ClustersClient.getExpectedFingerprint(this._connectionInfo.clusterId, this._pin) !== this._fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + this.killWorker(); + this._authFailure = undefined; + } + /** * Initialize the shell session: spawn the worker, connect to the cluster, * and set the initial database. @@ -197,19 +244,108 @@ export class ShellSessionManager implements vscode.Disposable { * @throws Error if initialization exceeds the configured timeout. */ async initialize(): Promise { + this._initPromise ??= this.initializeSession(); + const pending = this._initPromise; + try { + return await pending; + } finally { + if (this._initPromise === pending) { + this._initPromise = undefined; + } + } + } + + private async initializeSession(): Promise { + this.assertConnectionAvailable(); + this.assertAuthRecovery(); + const { clusterId } = this._connectionInfo; + const epoch = ClustersClient.getEpoch(clusterId); + const checkEndpoint = async (): Promise => { + if (!this._unauthenticated) { + return; + } + const current = await this._unauthenticated.reread(); + this.assertConnectionAvailable(); + if (epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (current === undefined) { + throw new ConnectionUnavailableError('connectionRemoved'); + } + if (current !== this._unauthenticated.connectionString) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + }; + if (this._unauthenticated) { + await checkEndpoint(); + this.assertConnectionAvailable(); + } + const fingerprint = this._unauthenticated + ? undefined + : ClustersClient.getExpectedFingerprint(clusterId, this._pin); + if (this._fingerprint !== undefined && this._fingerprint !== fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } const initMsg = this.buildInitMessage(); - if (!this._initialized || !this._workerManager.isAlive) { - this._sessionInitMessage = initMsg; - this._resolvedTokenResource = undefined; + if (!this.isInitialized) { + if (this._initialized && this._authFailure) { + this._workerManager.killWorker(); + } + this._initialized = false; + if (!this._unauthenticated) { + this._fingerprint ??= fingerprint; + const verified = ClustersClient.getLastVerifiedIdentity(clusterId); + const pin = this._pin ?? (verified?.kind === 'entra' ? verified : undefined); + if (initMsg.authMechanism === 'MicrosoftEntraID') { + this._pin = pin; + } + this._relay = new WorkerTokenRelay( + clusterId, + initMsg, + epoch, + this._managedIdentityTokenCorrelationId, + initMsg.authMechanism === 'MicrosoftEntraID' ? pin : undefined, + (identity) => { + this._pin = identity; + // The keyed fingerprint stays on the host for reconnect comparisons, not in worker messages. + this._fingerprint ??= computeConnectionFingerprint({ + connectionString: initMsg.connectionString, + principal: identity, + }); + this._displayName = identity.accountLabel || undefined; + }, + ); + } } - const timeoutMs = getConnectionTimeoutMs(); - await this._workerManager.ensureWorker( - this._connectionInfo.clusterId, - initMsg, - timeoutMs, - this._telemetryContext, - ); + const relay = this._relay; + try { + await this._workerManager.ensureWorker( + clusterId, + initMsg, + getConnectionTimeoutMs(), + this._telemetryContext, + this._unauthenticated !== undefined, + ); + } catch (error) { + if ( + relay === this._relay && + epoch === ClustersClient.getEpoch(clusterId) && + !ClustersClient.getLatchReason(clusterId) + ) { + this._authFailure ??= getWorkerAuthReason(error); + } + throw error; + } + this.assertConnectionAvailable(); + if (this._unauthenticated) { + await checkEndpoint(); + this.assertConnectionAvailable(); + } + if (relay !== this._relay || epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + this._authFailure = undefined; this._initialized = true; this._authMethod = initMsg.authMechanism; @@ -229,8 +365,10 @@ export class ShellSessionManager implements vscode.Disposable { // (`disableEmulatorSecurity` without `isEmulator`, design §7), which must not be // mislabeled "(Emulator)" in the banner or inflate the emulator telemetry metric. isEmulator: - CredentialCache.getCredentials(this._connectionInfo.clusterId)?.emulatorConfiguration?.isEmulator ?? - false, + (this._unauthenticated + ? this._unauthenticated.emulatorConfiguration?.isEmulator + : CredentialCache.getCredentials(this._connectionInfo.clusterId)?.emulatorConfiguration + ?.isEmulator) ?? false, username, displayName: this._displayName, }; @@ -248,17 +386,14 @@ export class ShellSessionManager implements vscode.Disposable { * @returns The serializable execution result from the worker. */ async evaluate(code: string, terminalColumns?: number): Promise { + this.assertConnectionAvailable(); // Reconnect if the worker is not alive — handles all cases: // timeout kills, Ctrl+C cancellation, unexpected worker crashes. - if (!this._initialized || !this._workerManager.isAlive) { - this._initialized = false; + if (!this.isInitialized) { + this.assertAuthRecovery(); this._callbacks?.onReconnecting?.(); - if (!this._initPromise) { - this._initPromise = this.initialize().finally(() => { - this._initPromise = undefined; - }); - } - await this._initPromise; + await this.initialize(); + this.assertConnectionAvailable(); this._callbacks?.onReconnected?.(); } @@ -271,34 +406,106 @@ export class ShellSessionManager implements vscode.Disposable { terminalColumns, }; - const workerResult = await this._workerManager.sendEval(evalMsg); - return workerResult.result; + const relay = this._relay; + const epoch = ClustersClient.getEpoch(this._connectionInfo.clusterId); + try { + const response = await this._workerManager.sendEval(evalMsg); + if (this._unauthenticated) { + this.assertConnectionAvailable(); + if (epoch !== ClustersClient.getEpoch(this._connectionInfo.clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + } + return response.result; + } catch (error) { + if ( + relay === this._relay && + epoch === ClustersClient.getEpoch(this._connectionInfo.clusterId) && + !ClustersClient.getLatchReason(this._connectionInfo.clusterId) + ) { + this._authFailure ??= getWorkerAuthReason(error); + } + throw error; + } } /** * Gracefully shut down the shell session. */ async shutdown(): Promise { - await this._workerManager.shutdown(); this._initialized = false; + this._relay = undefined; + this._initPromise = undefined; + await this._workerManager.shutdown(); } /** * Force-terminate the worker thread immediately. */ killWorker(): void { + this._authFailure ??= this._workerManager.authFailure; + this._relay = undefined; + this._initPromise = undefined; this._workerManager.killWorker(); this._initialized = false; } dispose(): void { + this._disposed = true; + this._relay = undefined; + this._initPromise = undefined; this._workerManager.dispose(); this._initialized = false; } + private assertConnectionAvailable(): void { + const reason = this.getBlockingLatchReason(); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + if (this._disposed) { + throw new ConnectionUnavailableError('connectionRemoved'); + } + } + + public getBlockingLatchReason(): ConnectionUnavailableReason | undefined { + const reason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + return this._unauthenticated && isDiagnosticAuthenticationHold(reason) ? undefined : reason; + } + + private assertAuthRecovery(): void { + if (this._unauthenticated) { + return; + } + const reason = this._authFailure ?? this._workerManager.authFailure; + if (this._pin && (reason === 'signInRequired' || reason === 'identityMismatch')) { + throw createWorkerAuthError(reason); + } + } + // ─── Private: Init message ─────────────────────────────────────────────── private buildInitMessage(): MainToWorkerMessage & { type: 'init' } { + if (this._unauthenticated) { + const { connectionString, emulatorConfiguration } = this._unauthenticated; + const allowInvalidCertificates = resolveAllowInvalidCertificates( + emulatorConfiguration?.disableEmulatorSecurity, + connectionString, + ); + return { + type: 'init', + requestId: '', + connectionString, + databaseName: this._activeDatabase, + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { + serverSelectionTimeoutMS: + emulatorConfiguration?.isEmulator || allowInvalidCertificates ? 4000 : undefined, + tlsAllowInvalidCertificates: allowInvalidCertificates, + }, + }; + } const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); if (!credentials) { throw new Error(l10n.t('No credentials found for cluster {0}', this._connectionInfo.clusterId)); @@ -349,8 +556,6 @@ export class ShellSessionManager implements vscode.Disposable { }; } - // ─── Private: Token handling ───────────────────────────────────────────── - /** * Extract the host portion from a connection string, stripping credentials. * Returns just the hostname:port for safe display. @@ -365,143 +570,4 @@ export class ShellSessionManager implements vscode.Disposable { return match?.[1].split(',') ?? ['unknown']; } } - - private async handleTokenRequest( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ): Promise { - try { - const sessionInit = this._sessionInitMessage; - if ( - !sessionInit || - (sessionInit.authMechanism !== 'MicrosoftEntraID' && sessionInit.authMechanism !== 'ManagedIdentity') - ) { - throw new Error(l10n.t('No credentials found for cluster {0}', this._connectionInfo.clusterId)); - } - if (!isCurrent()) { - return; - } - const connectionString = sessionInit.connectionString; - const decision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(decision, msg.requestId, traceContext); - if (!decision.allowed) { - throw new EntraDestinationRejectedError(decision); - } - const usesManagedIdentity = sessionInit.authMechanism === 'ManagedIdentity'; - let resolved: ResolvedTokenResource; - try { - resolved = - this._resolvedTokenResource ?? - (usesManagedIdentity - ? await resolveManagedIdentityTokenResource(connectionString) - : await resolveInteractiveTokenResource(connectionString)); - if (isCurrent()) { - this._resolvedTokenResource = resolved; - } - traceAuthFlow('entraCloud.resolved', resolved.details, msg.requestId, traceContext); - } catch (error) { - if (error instanceof TokenResourceResolutionError) { - traceAuthFlow('entraCloud.unresolved', error.details, msg.requestId, traceContext); - } - throw error; - } - let accessToken: string; - - if (usesManagedIdentity) { - const { getManagedIdentityAccessToken } = await import('../auth/managedIdentityTokenProvider'); - try { - accessToken = ( - await withTokenAcquisitionTiming(timings, () => - getManagedIdentityAccessToken( - [resolved.scope], - sessionInit.managedIdentityClientId, - sessionInit.tenantId, - this._managedIdentityTokenCorrelationId, - traceContext, - ), - ) - ).accessToken; - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(this._connectionInfo.clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'managedIdentity', - }); - } - throw error; - } - } else { - const { getSessionFromVSCode } = await import( - // eslint-disable-next-line import/no-internal-modules - '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode' - ); - let session: vscode.AuthenticationSession | undefined; - try { - session = await traceAuthOperation( - 'interactiveEntra.getSession', - () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode([resolved.scope], sessionInit.tenantId, { createIfNone: true }), - ), - { - tenantSpecified: !!sessionInit.tenantId, - createIfNone: true, - cloudCategory: resolved.cloudCategory, - tokenResourceReason: resolved.reason, - }, - msg.requestId, - traceContext, - ); - - if (!session) { - throw new Error(l10n.t('Failed to obtain Entra ID token.')); - } - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(this._connectionInfo.clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'interactive', - }); - } - throw error; - } - - accessToken = session.accessToken; - this._displayName = session.account.label || undefined; - } - - const currentDecision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(currentDecision, msg.requestId, traceContext); - if (!currentDecision.allowed) { - throw new EntraDestinationRejectedError(currentDecision); - } - if (isCurrent()) { - clearEntraTokenFailure(this._connectionInfo.clusterId); - } - postResponse({ - type: 'tokenResponse', - requestId: msg.requestId, - accessToken, - }); - } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : String(error); - postResponse({ - type: 'tokenError', - requestId: msg.requestId, - error: errorMessage, - ...(error instanceof EntraDestinationRejectedError - ? { errorName: 'EntraDestinationRejectedError' as const } - : {}), - }); - } - } } diff --git a/src/documentdb/shell/ShellTerminalLinkProvider.test.ts b/src/documentdb/shell/ShellTerminalLinkProvider.test.ts index dbd2a065a..413ce94f4 100644 --- a/src/documentdb/shell/ShellTerminalLinkProvider.test.ts +++ b/src/documentdb/shell/ShellTerminalLinkProvider.test.ts @@ -5,9 +5,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createTestActionContext } from '@microsoft/vscode-azext-utils'; import { EJSON } from 'bson'; +import { createTextDocument } from 'jest-mock-vscode'; import * as vscode from 'vscode'; import { HelpProvider } from '../../../packages/documentdb-js-shell-runtime/src/HelpProvider'; +import { newPlaygroundWithContent, type NewPlaygroundWithContentParams } from '../../commands/playground/newPlayground'; +import { ClustersClient } from '../ClustersClient'; +import { PlaygroundService } from '../playground/PlaygroundService'; +import { PLAYGROUND_LANGUAGE_ID } from '../playground/constants'; import { ShellOutputFormatter } from './ShellOutputFormatter'; import { ACTION_LINE_PREFIX, @@ -495,6 +501,7 @@ describe('ShellTerminalLinkProvider', () => { clusterId: 'my-cluster', databaseName: 'mydb', content: "db.getCollection('users').find({ })", + origin: { kind: 'none' }, }), ); spy.mockRestore(); @@ -504,6 +511,165 @@ describe('ShellTerminalLinkProvider', () => { }); }); + describe('Playground origin effects', () => { + let sequence = 0; + let service: PlaygroundService; + let document: vscode.TextDocument; + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + } as const; + + beforeEach((): void => { + sequence++; + const uri = vscode.Uri.parse(`untitled:shell-handoff-${sequence}.documentdb.js`); + document = createTextDocument(uri, "db.getCollection('users').find({})", PLAYGROUND_LANGUAGE_ID); + vi.spyOn(vscode.Uri, 'file').mockReturnValue(uri); + vi.spyOn(vscode.workspace, 'applyEdit').mockClear().mockResolvedValue(true); + vi.spyOn(vscode.workspace, 'openTextDocument').mockClear().mockResolvedValue(document); + vi.spyOn(vscode.window, 'showTextDocument') + .mockClear() + .mockResolvedValue({ document } as vscode.TextEditor); + vi.spyOn(vscode.window, 'showWarningMessage').mockClear().mockResolvedValue(undefined); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(undefined); + vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue('original'); + service = PlaygroundService.getInstance(); + vi.spyOn(service, 'setConnectionFromHost'); + vi.spyOn(service, 'removeConnection'); + vi.spyOn(vscode.commands, 'executeCommand') + .mockClear() + .mockImplementation(async (_command, ...args) => { + await newPlaygroundWithContent( + await createTestActionContext(), + args[0] as NewPlaygroundWithContentParams, + ); + return undefined; + }); + }); + + afterEach((): void => { + service.dispose(); + vi.restoreAllMocks(); + }); + + it.each(['open', 'show'] as const)( + 'leaves a retained Shell draft unbound when %s pauses across password-only teardown', + async (boundary): Promise => { + let current = true; + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + if (boundary === 'open') { + vi.mocked(vscode.workspace.openTextDocument).mockImplementationOnce(async () => { + await pause; + return document; + }); + } else { + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document } as vscode.TextEditor; + }); + } + const getOrigin = vi.fn(() => ({ + kind: 'shell' as const, + fingerprint: 'original', + entraIdentity: identity, + isCurrent: () => current, + })); + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: getOrigin, + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + expect(getOrigin).not.toHaveBeenCalled(); + provider.handleTerminalLink(link); + expect(getOrigin).toHaveBeenCalledOnce(); + await vi.waitFor(() => + expect( + boundary === 'open' ? vscode.workspace.openTextDocument : vscode.window.showTextDocument, + ).toHaveBeenCalledOnce(), + ); + current = false; + release(); + await vi.waitFor(() => expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce()); + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.getConnection(document.uri)).toBeUndefined(); + expect(vscode.window.showTextDocument).toHaveBeenCalledWith(document, { preview: true }); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }, + ); + + it('captures an old link at click time and never falls back to saved authentication', async (): Promise => { + let ended = false; + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: () => + ended + ? { kind: 'none' } + : { kind: 'shell', fingerprint: 'original', entraIdentity: identity, isCurrent: () => !ended }, + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + ended = true; + provider.handleTerminalLink(link); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(service.removeConnection).toHaveBeenCalledExactlyOnceWith(document.uri)); + expect(service.getConnection(document.uri)).toBeUndefined(); + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(ClustersClient.getExpectedFingerprint).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }); + + it('preserves the original Shell pin through host-only repair during display', async (): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document } as vscode.TextEditor; + }); + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: () => ({ + kind: 'shell', + fingerprint: 'original', + entraIdentity: identity, + isCurrent: () => true, + }), + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + provider.handleTerminalLink(link); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + ClustersClient.invalidate('shell-cluster'); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + clusterId: 'shell-cluster', + fingerprint: 'original', + generation: 2, + }); + release(); + await vi.waitFor(() => expect(service.setConnectionFromHost).toHaveBeenCalledOnce()); + expect(service.getConnection(document.uri)).toMatchObject({ + fingerprint: 'original', + entraIdentity: identity, + }); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }); + }); + describe('registry', () => { it('should not match after terminal is unregistered', () => { registerShellTerminal(mockTerminal, () => mockShellInfo('test-id')); diff --git a/src/documentdb/shell/ShellTerminalLinkProvider.ts b/src/documentdb/shell/ShellTerminalLinkProvider.ts index b300a6cc6..60c8d8cdc 100644 --- a/src/documentdb/shell/ShellTerminalLinkProvider.ts +++ b/src/documentdb/shell/ShellTerminalLinkProvider.ts @@ -5,6 +5,7 @@ import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { type PlaygroundHandoffOrigin } from '../../commands/playground/newPlayground'; import { settingsKeys } from '../../settingsKeys'; import { escapeJsString } from '../../utils/escapeJsString'; import { PlaygroundCommandIds } from '../playground/constants'; @@ -15,6 +16,7 @@ import { Views } from '../Views'; * for the link provider and debug stats command. */ export interface ShellTerminalInfo { + readonly getPlaygroundOrigin?: () => PlaygroundHandoffOrigin; /** Stable cluster ID for CredentialCache and session lookups. */ readonly clusterId: string; /** Human-readable cluster display name. */ @@ -39,7 +41,10 @@ export interface ShellTerminalInfo { * Populated by the shell command handler when a terminal is created, * queried by the link provider to build navigation actions. */ -const shellTerminalRegistry = new Map(); +const shellTerminalRegistry = new Map< + vscode.Terminal, + { readonly infoProvider: ShellTerminalInfoProvider; readonly disconnect?: () => void } +>(); /** * A function that returns the current {@link ShellTerminalInfo} for a shell terminal. @@ -51,8 +56,12 @@ export type ShellTerminalInfoProvider = () => ShellTerminalInfo; * Register a shell terminal in the link provider registry. * Call this after `vscode.window.createTerminal()` in the command handler. */ -export function registerShellTerminal(terminal: vscode.Terminal, infoProvider: ShellTerminalInfoProvider): void { - shellTerminalRegistry.set(terminal, infoProvider); +export function registerShellTerminal( + terminal: vscode.Terminal, + infoProvider: ShellTerminalInfoProvider, + disconnect?: () => void, +): void { + shellTerminalRegistry.set(terminal, { infoProvider, disconnect }); } /** @@ -70,10 +79,12 @@ export function unregisterShellTerminal(terminal: vscode.Terminal): void { export function getRegisteredShellTerminals(): ReadonlyArray<{ terminal: vscode.Terminal; info: ShellTerminalInfo; + disconnect?: () => void; }> { - return Array.from(shellTerminalRegistry.entries()).map(([terminal, provider]) => ({ + return Array.from(shellTerminalRegistry.entries()).map(([terminal, { infoProvider, disconnect }]) => ({ terminal, - info: provider(), + info: infoProvider(), + disconnect, })); } @@ -175,6 +186,7 @@ interface CollectionViewTerminalLink extends vscode.TerminalLink { * Terminal link that opens a Query Playground. */ interface PlaygroundTerminalLink extends vscode.TerminalLink { + readonly terminal?: vscode.Terminal; readonly linkType: 'playground'; /** Cluster ID for the playground connection. */ readonly clusterId: string; @@ -213,7 +225,7 @@ type ShellTerminalLink = CollectionViewTerminalLink | PlaygroundTerminalLink | S */ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { provideTerminalLinks(context: vscode.TerminalLinkContext): ShellTerminalLink[] { - const infoProvider = shellTerminalRegistry.get(context.terminal); + const infoProvider = shellTerminalRegistry.get(context.terminal)?.infoProvider; if (!infoProvider) { // Not a shell terminal — no links return []; @@ -247,6 +259,7 @@ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { @@ -311,6 +326,7 @@ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { + it('removes all spellings of database, proxy and client-certificate authentication', (): void => { + const keys = [ + 'authMechanism', + 'authSource', + 'authMechanismProperties', + 'proxyUsername', + 'proxyPassword', + 'tlsCertificateKeyFile', + 'tlsCertificateKeyFilePassword', + 'sslPEMKeyFile', + 'sslPEMKeyPassword', + 'sslCert', + 'sslCertificateKeyFile', + ]; + const options = keys.flatMap((key) => [`${key}=private`, `${key.toUpperCase()}=private`]).join('&'); + const result = toUnauthenticatedConnectionString(`mongodb://account:password@localhost:27017/db?${options}`); + expect(result).toBe('mongodb://localhost:27017/db'); + }); + + it.each(['mongodb://host-a:27017,host-b:27018/db', 'mongodb+srv://cluster.example.com/db'])( + 'preserves endpoints and server trust options for %s', + (endpoint): void => { + const result = new DocumentDBConnectionString( + toUnauthenticatedConnectionString( + `${endpoint}?tls=true&tlsCAFile=trust.pem&tlsAllowInvalidCertificates=false&tlsAllowInvalidHostnames=false&replicaSet=rs&directConnection=true`, + ), + ); + expect(result.hosts).toEqual(new DocumentDBConnectionString(endpoint).hosts); + expect(result.pathname).toBe('/db'); + expect([...result.searchParams.entries()]).toEqual([ + ['tls', 'true'], + ['tlsCAFile', 'trust.pem'], + ['tlsAllowInvalidCertificates', 'false'], + ['tlsAllowInvalidHostnames', 'false'], + ['replicaSet', 'rs'], + ['directConnection', 'true'], + ]); + }, + ); + + it.each(['mongodb://user:private@', 'mongodb://us[er:private@host/', 'not-a-uri-private'])( + 'discards unsafe constructor errors for %s', + (input): void => { + try { + toUnauthenticatedConnectionString(input); + expect.fail('Expected an invalid endpoint'); + } catch (error) { + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe('Invalid connection string.'); + expect((error as Error).cause).toBeUndefined(); + expect((error as Error).stack).not.toContain(input); + } + }, + ); +}); diff --git a/src/documentdb/shell/unauthenticatedEndpoint.ts b/src/documentdb/shell/unauthenticatedEndpoint.ts new file mode 100644 index 000000000..61636ff23 --- /dev/null +++ b/src/documentdb/shell/unauthenticatedEndpoint.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 * as l10n from '@vscode/l10n'; +import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; + +export function toUnauthenticatedConnectionString(connectionString: string): string { + let endpoint: DocumentDBConnectionString; + try { + endpoint = new DocumentDBConnectionString(connectionString); + } catch { + throw new Error(l10n.t('Invalid connection string.')); + } + endpoint.password = ''; + endpoint.username = ''; + const authenticationOptions = new Set([ + 'authmechanism', + 'authsource', + 'authmechanismproperties', + 'proxyusername', + 'proxypassword', + 'tlscertificatekeyfile', + 'tlscertificatekeyfilepassword', + 'sslpemkeyfile', + 'sslpemkeypassword', + 'sslcert', + 'sslcertificatekeyfile', + ]); + const keys = [...endpoint.searchParams.keys()].filter((key) => authenticationOptions.has(key.toLowerCase())); + for (const key of keys) { + endpoint.searchParams.delete(key); + } + return endpoint.toString(); +} diff --git a/src/documentdb/showClusterConnectFailure.test.ts b/src/documentdb/showClusterConnectFailure.test.ts index 2fbed1b08..19c74108c 100644 --- a/src/documentdb/showClusterConnectFailure.test.ts +++ b/src/documentdb/showClusterConnectFailure.test.ts @@ -8,6 +8,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { Links } from '../constants'; import { ErrorExplanationService } from '../services/errorExplanationService'; +import { AuthMethodId } from './auth/AuthMethod'; +import { TokenCallbackError } from './auth/entraErrors/entraCallbackErrors'; +import { ManagedIdentityGuidanceError } from './auth/managedIdentityErrors'; import { EntraDestinationRejectedError, evaluateEntraDestination } from './auth/oidcAllowedHosts'; import { showClusterConnectFailure } from './showClusterConnectFailure'; @@ -188,6 +191,35 @@ describe('showClusterConnectFailure', () => { }); }); + it('shows an actionable managed identity wrapper message without displaying SDK fields', async () => { + const context = createMockContext(); + const message = + 'This machine has more than one managed identity, so the right one cannot be chosen automatically. Reconnect and enter the client ID you want to use.'; + const accessToken = 'private-access-token'; + const cause = Object.assign(new ManagedIdentityGuidanceError(message), { accessToken }); + const error = new TokenCallbackError(cause, AuthMethodId.ManagedIdentity); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + + await showClusterConnectFailure({ + clusterId: 'stable-id', + clusterName: 'Test Cluster', + error, + context, + }); + + expect(showErrorMessage).toHaveBeenCalledWith('Failed to connect to "Test Cluster"', { + modal: true, + detail: `Revisit connection details and try again.\n\nError: ${message}`, + }); + expect(JSON.stringify(showErrorMessage.mock.calls)).not.toContain(accessToken); + expect(error).toMatchObject({ + name: 'TokenCallbackError', + message, + authMethod: AuthMethodId.ManagedIdentity, + cause, + }); + }); + it('stringifies non-Error failures without changing the diagnostics input', async () => { const context = createMockContext(); vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); 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/documentdb/utils/startupFailureTelemetry.test.ts b/src/documentdb/utils/startupFailureTelemetry.test.ts index c5420f9ca..5eafd636b 100644 --- a/src/documentdb/utils/startupFailureTelemetry.test.ts +++ b/src/documentdb/utils/startupFailureTelemetry.test.ts @@ -13,6 +13,11 @@ import { } from 'mongodb'; import { describe, expect, it, vi } from 'vitest'; import { allowListedErrorType, innermostCauseTypeOf } from '../../utils/telemetryErrorType'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from '../auth/entraErrors/entraCallbackErrors'; import { applyStartupFailureTelemetry, classifyStartupFailure } from './startupFailureTelemetry'; vi.mock('vscode', async (importOriginal) => { @@ -101,6 +106,17 @@ describe('classifyStartupFailure', (): void => { }); describe('applyStartupFailureTelemetry', (): void => { + it.each([ + ['a direct token callback error', new TokenCallbackError(nodeError('ECONNRESET'))], + ['a wrapped sign-in requirement', new Error('Wrapper', { cause: new EntraSignInRequiredError('noSession') })], + ['a server selection error wrapping an account mismatch', selectionError(new EntraIdentityMismatchError())], + ])('attributes %s to Entra during startup', (_label, error): void => { + const properties: ITelemetryContext['properties'] = { entraFailureKind: 'none' }; + applyStartupFailureTelemetry(properties, error); + expect(properties.startupFailureCategory).toBe('entraToken'); + expect(properties.entraFailureKind).toBe('none'); + }); + it('records only allow-listed values under names whole-error masking keeps', (): void => { const properties: ITelemetryContext['properties'] = {}; applyStartupFailureTelemetry(properties, new Error('private-host private-user')); diff --git a/src/documentdb/utils/startupFailureTelemetry.ts b/src/documentdb/utils/startupFailureTelemetry.ts index 325504b59..bb9409aec 100644 --- a/src/documentdb/utils/startupFailureTelemetry.ts +++ b/src/documentdb/utils/startupFailureTelemetry.ts @@ -29,6 +29,7 @@ export type StartupFailureCategory = (typeof STARTUP_FAILURE_CATEGORIES)[number] /** Which code path asked for the client; recorded as `startupTrigger` on `connect.startup`. */ export type ClientStartupTrigger = + | 'explicitReconnect' | 'treeConnect' | 'treeChildren' | 'collectionView' @@ -52,6 +53,9 @@ const CREDENTIALS_UNAVAILABLE_NAMES: ReadonlySet = new Set([ ]); const ENTRA_TOKEN_NAMES: ReadonlySet = new Set([ 'EntraDestinationRejectedError', + 'EntraIdentityMismatchError', + 'EntraSignInRequiredError', + 'TokenCallbackError', 'TokenResourceResolutionError', 'CredentialUnavailableError', 'AuthenticationRequiredError', diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts new file mode 100644 index 000000000..002764835 --- /dev/null +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts @@ -0,0 +1,375 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Environment } from '@azure/ms-rest-azure-env'; +import { + AzureSubscriptionProviderBase, + ExtendedEnvironment, + NotSignedInError, + VSCodeAzureSubscriptionProvider, + type AzureSubscription, + type AzureTenant, +} from '@microsoft/vscode-azext-azureauth'; +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ext } from '../../../extensionVariables'; +import { AzureSubscriptionProviderWithFilters } from './AzureSubscriptionProviderWithFilters'; + +interface RecordedTelemetryEvent { + callbackId: string; + measurements: Record; +} + +const recordedTelemetry = vi.hoisted(() => ({ + events: [] as RecordedTelemetryEvent[], +})); + +vi.mock(import('@microsoft/vscode-azext-utils'), async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + callWithTelemetryAndErrorHandling: ( + callbackId: string, + callback: (context: IActionContext) => T | PromiseLike, + ): Promise => { + const context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { suppressDisplay: false }, + } as unknown as IActionContext; + const result = callback(context); + recordedTelemetry.events.push({ + callbackId, + measurements: { ...context.telemetry.measurements }, + }); + return Promise.resolve(result); + }, + }; +}); + +vi.mock('../../../extensionVariables', () => ({ + ext: { outputChannel: { show: vi.fn(), warn: vi.fn() } }, +})); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + authentication: { + ...actual.authentication, + getAccounts: vi.fn(), + onDidChangeSessions: vi.fn(() => ({ dispose: vi.fn() })), + }, + window: { + ...actual.window, + showWarningMessage: vi.fn(), + }, + workspace: { + ...actual.workspace, + onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), + }, + }; +}); + +describe('AzureSubscriptionProviderWithFilters', () => { + beforeEach(() => { + vi.clearAllMocks(); + recordedTelemetry.events.length = 0; + vi.mocked(vscode.window.showWarningMessage).mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('bypasses the cache for one requested listing, not for routine listings', async () => { + const baseListing = vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAvailableSubscriptions'); + baseListing.mockResolvedValue([]); + const provider = new AzureSubscriptionProviderWithFilters(); + const options = { filter: true, maximumTenants: Number.POSITIVE_INFINITY }; + + await provider.getAvailableSubscriptions(options); + provider.requestFreshListing(); + const explicit = provider.getAvailableSubscriptions(options); + const routine = provider.getAvailableSubscriptions(options); + await Promise.all([explicit, routine]); + + expect(baseListing.mock.calls).toEqual([[options], [{ ...options, noCache: true }], [options]]); + expect(options).not.toHaveProperty('noCache'); + provider.dispose(); + }); + + it('returns an empty list only for the SDK no-session error', async () => { + const failure = new Error('ARM listing failed'); + vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAvailableSubscriptions') + .mockRejectedValueOnce(new NotSignedInError()) + .mockRejectedValueOnce(failure); + const provider = new AzureSubscriptionProviderWithFilters(); + + await expect(provider.getAvailableSubscriptions()).resolves.toEqual([]); + await expect(provider.getAvailableSubscriptions()).rejects.toBe(failure); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + expect(recordedTelemetry.events).toEqual([]); + provider.dispose(); + }); + + it('forces fresh account enumeration while preserving other account options', async () => { + const baseAccounts = vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAccounts').mockResolvedValue([]); + const provider = new AzureSubscriptionProviderWithFilters(); + const token = { isCancellationRequested: false, onCancellationRequested: vi.fn() }; + const options = { filter: false, noCache: false, token }; + + await provider.getAccounts(); + await provider.getAccounts(options); + + expect(baseAccounts.mock.calls).toEqual([[{ noCache: true }], [{ ...options, noCache: true }]]); + expect(options.noCache).toBe(false); + provider.dispose(); + }); + + it('finds newly signed-in accounts without an event while reusing existing tenant and subscription caches', async () => { + const getAccounts = vi.mocked(vscode.authentication.getAccounts); + const firstAccount = { id: 'first-account', label: 'First account' }; + const secondAccount = { id: 'second-account', label: 'Second account' }; + getAccounts.mockResolvedValueOnce([firstAccount]).mockResolvedValue([firstAccount, secondAccount]); + const getTenants = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getTenantsForAccount') + .mockImplementation(async (account) => [{ account, tenantId: `tenant-${account.id}` }]); + const getSubscriptions = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getSubscriptionsForTenant') + .mockImplementation(async ({ account, tenantId }) => [ + { + account, + tenantId, + subscriptionId: `subscription-${account.id}`, + name: account.label, + authentication: { getSession: vi.fn(), getSessionWithScopes: vi.fn() }, + credential: { getToken: vi.fn() }, + environment: account.environment, + isCustomCloud: false, + }, + ]); + const provider = new AzureSubscriptionProviderWithFilters(); + const options = { filter: false, noCache: false, maximumTenants: 20, dedupe: false }; + + try { + const first = await provider.getAvailableSubscriptions(options); + const second = await provider.getAvailableSubscriptions(options); + + expect(first.map((subscription) => subscription.subscriptionId)).toEqual(['subscription-first-account']); + expect(second.map((subscription) => subscription.subscriptionId)).toEqual([ + 'subscription-first-account', + 'subscription-second-account', + ]); + expect(getTenants.mock.calls.map(([account]) => account.id)).toEqual(['first-account', 'second-account']); + expect(getSubscriptions.mock.calls.map(([tenant]) => tenant.account.id)).toEqual([ + 'first-account', + 'second-account', + ]); + expect(getTenants.mock.calls.every(([, passedOptions]) => passedOptions === options)).toBe(true); + expect(getSubscriptions.mock.calls.every(([, passedOptions]) => passedOptions === options)).toBe(true); + expect(options.noCache).toBe(false); + + const freshOptions = { ...options, noCache: true }; + await provider.getAvailableSubscriptions(freshOptions); + expect(getTenants).toHaveBeenCalledTimes(4); + expect(getSubscriptions).toHaveBeenCalledTimes(4); + expect(getTenants.mock.calls.slice(2).every(([, passedOptions]) => passedOptions === freshOptions)).toBe( + true, + ); + expect( + getSubscriptions.mock.calls.slice(2).every(([, passedOptions]) => passedOptions === freshOptions), + ).toBe(true); + } finally { + provider.dispose(); + } + }); + + it.each(['cloud', 'session'] as const)('handles tenant and subscription caches after a %s change', async (kind) => { + const cloudListener = vi.mocked(vscode.workspace.onDidChangeConfiguration); + const sessionListener = vi.mocked(vscode.authentication.onDidChangeSessions); + const getAccounts = vi.mocked(vscode.authentication.getAccounts); + cloudListener.mockClear(); + sessionListener.mockClear(); + getAccounts.mockClear(); + getAccounts.mockResolvedValue([{ id: 'fixture-account', label: 'Fixture account' }]); + const getTenants = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getTenantsForAccount') + .mockImplementation(async (account) => [{ account, tenantId: 'fixture-tenant' }]); + const getSubscriptions = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getSubscriptionsForTenant') + .mockResolvedValue([]); + vi.useFakeTimers(); + const provider = new AzureSubscriptionProviderWithFilters(); + + try { + await provider.getAvailableSubscriptions({ filter: false }); + await provider.getAvailableSubscriptions({ filter: false }); + expect(getAccounts).toHaveBeenCalledTimes(2); + expect(getTenants).toHaveBeenCalledOnce(); + expect(getSubscriptions).toHaveBeenCalledOnce(); + + if (kind === 'cloud') { + cloudListener.mock.calls[0][0]({ + affectsConfiguration: (section): boolean => section === 'microsoft-sovereign-cloud', + }); + } else { + // The SDK suppresses session events during and just after account enumeration. + await vi.runOnlyPendingTimersAsync(); + sessionListener.mock.calls[0][0]({ provider: { id: 'microsoft', label: 'Microsoft' } }); + } + + await provider.getAvailableSubscriptions({ filter: false }); + expect(getAccounts).toHaveBeenCalledTimes(3); + expect(getTenants).toHaveBeenCalledTimes(kind === 'cloud' ? 2 : 1); + expect(getSubscriptions).toHaveBeenCalledTimes(kind === 'cloud' ? 2 : 1); + } finally { + provider.dispose(); + vi.useRealTimers(); + } + + expect(cloudListener.mock.results[0].value.dispose).toHaveBeenCalledOnce(); + expect(sessionListener.mock.results[0].value.dispose).toHaveBeenCalledOnce(); + }); + + it('keeps subscriptions beyond ten tenants and emits only bounded warnings for skipped failures', async () => { + const provider = new AzureSubscriptionProviderWithFilters(); + const environment = new ExtendedEnvironment(Environment.AzureCloud, false); + const account = { id: 'private-account-id', label: 'private-account-label', environment }; + const failedAccount = { ...account, id: 'failed-account-id' }; + const tenants: AzureTenant[] = Array.from({ length: 11 }, (_, index) => ({ + account, + tenantId: `private-tenant-${index}`, + })); + const subscription: AzureSubscription = { + account, + authentication: { getSession: vi.fn(), getSessionWithScopes: vi.fn() }, + credential: { getToken: vi.fn() }, + environment, + isCustomCloud: false, + name: 'Private subscription', + subscriptionId: 'private-subscription-id', + tenantId: tenants[10].tenantId, + }; + const failure = new Error('ARM error with private details'); + vi.spyOn(provider, 'getAccounts').mockResolvedValue([account, failedAccount]); + vi.mocked(vscode.window.showWarningMessage).mockResolvedValue('Show Output' as never); + vi.spyOn(provider, 'getTenantsForAccount').mockImplementation(async (requestedAccount) => { + if (requestedAccount === failedAccount) { + throw failure; + } + return tenants; + }); + const getSubscriptionsForTenant = vi + .spyOn(provider, 'getSubscriptionsForTenant') + .mockImplementation(async ({ tenantId }) => { + switch (tenantId) { + case tenants[0].tenantId: + throw failure; + case tenants[1].tenantId: + throw new NotSignedInError(); + case subscription.tenantId: + return [subscription]; + default: + return []; + } + }); + + await expect( + provider.getAvailableSubscriptions({ filter: false, maximumTenants: Number.POSITIVE_INFINITY }), + ).resolves.toEqual([subscription]); + + expect(getSubscriptionsForTenant).toHaveBeenCalledTimes(11); + const warnings = vi.mocked(ext.outputChannel.warn).mock.calls; + expect(warnings).toHaveLength(2); + expect(warnings).toEqual( + expect.arrayContaining([ + ['Skipped an Azure account because its tenants could not be listed.'], + ['Skipped an Azure tenant because its subscriptions could not be listed.'], + ]), + ); + expect(vscode.window.showWarningMessage).toHaveBeenCalledExactlyOnceWith( + 'Some Azure accounts or tenants could not be listed, so some subscriptions may be missing.', + 'Show Output', + ); + expect(recordedTelemetry.events).toEqual([ + { + callbackId: 'azureSubscriptions.partialListing', + measurements: { skippedAccounts: 1, skippedTenants: 1 }, + }, + ]); + await vi.waitFor(() => expect(ext.outputChannel.show).toHaveBeenCalledOnce()); + provider.dispose(); + }); + + it('attributes skipped counts only to an overlapping partial listing', async () => { + const provider = new AzureSubscriptionProviderWithFilters(); + const environment = new ExtendedEnvironment(Environment.AzureCloud, false); + const partialAccount = { id: 'partial-account-id', label: 'Partial account', environment }; + const completeAccount = { id: 'complete-account-id', label: 'Complete account', environment }; + const failedTenant = { account: partialAccount, tenantId: 'failed-tenant' }; + const heldTenant = { account: partialAccount, tenantId: 'held-tenant' }; + const completeTenant = { account: completeAccount, tenantId: 'complete-tenant' }; + const partialSubscription: AzureSubscription = { + account: partialAccount, + authentication: { getSession: vi.fn(), getSessionWithScopes: vi.fn() }, + credential: { getToken: vi.fn() }, + environment, + isCustomCloud: false, + name: 'Partial subscription', + subscriptionId: 'partial-subscription-id', + tenantId: heldTenant.tenantId, + }; + const completeSubscription: AzureSubscription = { + ...partialSubscription, + account: completeAccount, + name: 'Complete subscription', + subscriptionId: 'complete-subscription-id', + tenantId: completeTenant.tenantId, + }; + let releaseHeldTenant: () => void = () => undefined; + const heldTenantMayFinish = new Promise((resolve) => { + releaseHeldTenant = resolve; + }); + + vi.spyOn(provider, 'getAccounts').mockImplementation(async (options) => { + return options && 'maximumTenants' in options && options.maximumTenants === 2 + ? [partialAccount] + : [completeAccount]; + }); + vi.spyOn(provider, 'getTenantsForAccount').mockImplementation(async (account) => { + return account === partialAccount ? [failedTenant, heldTenant] : [completeTenant]; + }); + vi.spyOn(provider, 'getSubscriptionsForTenant').mockImplementation(async (tenant) => { + if (tenant === failedTenant) { + throw new Error('private tenant failure'); + } + if (tenant === heldTenant) { + await heldTenantMayFinish; + return [partialSubscription]; + } + return [completeSubscription]; + }); + + const partial = provider.getAvailableSubscriptions({ filter: false, maximumTenants: 2 }); + const complete = provider.getAvailableSubscriptions({ filter: false, maximumTenants: 3 }); + + await vi.waitFor(() => expect(ext.outputChannel.warn).toHaveBeenCalledOnce()); + await expect(complete).resolves.toEqual([completeSubscription]); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + expect(recordedTelemetry.events).toEqual([]); + + releaseHeldTenant(); + await expect(partial).resolves.toEqual([partialSubscription]); + expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + expect(recordedTelemetry.events).toEqual([ + { + callbackId: 'azureSubscriptions.partialListing', + measurements: { skippedAccounts: 0, skippedTenants: 1 }, + }, + ]); + provider.dispose(); + }); +}); diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts index f10fb19a2..1d86f6269 100644 --- a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts @@ -4,20 +4,70 @@ *--------------------------------------------------------------------------------------------*/ import { + isNotSignedInError, VSCodeAzureSubscriptionProvider, + type AzureAccount, type AzureSubscription, - type GetSubscriptionsFilter, + type AzureTenant, + type GetAccountsOptions, + type GetAvailableSubscriptionsOptions, type SubscriptionId, + type TenantIdAndAccount, } from '@microsoft/vscode-azext-azureauth'; +import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; +import { AsyncLocalStorage } from 'node:async_hooks'; import * as vscode from 'vscode'; import { ext } from '../../../extensionVariables'; +import { meterSilentCatch } from '../../../utils/accumulatingTelemetry'; + +export async function getUnfilteredAzureTenants( + provider: VSCodeAzureSubscriptionProvider, + noCache?: boolean, +): Promise { + const options = noCache ? { filter: false, noCache: true } : { filter: false }; + let accounts: AzureAccount[]; + try { + accounts = await provider.getAccounts(options); + } catch (error) { + if (isNotSignedInError(error)) { + return []; + } + throw error; + } + + const tenants: AzureTenant[] = []; + for (const account of accounts) { + try { + tenants.push(...(await provider.getTenantsForAccount(account, options))); + } catch (error) { + if (!isNotSignedInError(error)) { + throw error; + } + } + } + return tenants; +} /** * Extends VSCodeAzureSubscriptionProvider to customize tenant and subscription filters */ export class AzureSubscriptionProviderWithFilters extends VSCodeAzureSubscriptionProvider { - constructor(logger?: vscode.LogOutputChannel) { - super(logger); + private freshListingRequested = false; + private readonly listingSkips = new AsyncLocalStorage<{ + skippedAccounts: number; + skippedTenants: number; + }>(); + private readonly cacheRefreshSubscription: vscode.Disposable; + + constructor() { + super(); + // The SDK starts its cache invalidation listeners only when subscribed. + this.cacheRefreshSubscription = this.onRefreshSuggested(() => undefined); + } + + public override dispose(): void { + this.cacheRefreshSubscription.dispose(); + super.dispose(); } private getTenantAndSubscriptionFilters(): string[] { @@ -35,15 +85,73 @@ export class AzureSubscriptionProviderWithFilters extends VSCodeAzureSubscriptio return fullSubscriptionIds; } - /** - * Gets subscriptions from the Azure subscription provider. - * Note: Callers must explicitly call getTenantFilteredSubscriptions() if tenant filtering is needed. - * - * @param filter Whether to apply subscription filtering or a custom filter - * @returns List of subscriptions from the base provider (without tenant filtering) - */ - public override async getSubscriptions(filter?: boolean | GetSubscriptionsFilter): Promise { - return await super.getSubscriptions(filter); + public requestFreshListing(): void { + this.freshListingRequested = true; + } + + public override getAccounts(options?: GetAccountsOptions): Promise { + return super.getAccounts({ ...options, noCache: true }); + } + + public override async getAvailableSubscriptions( + options?: GetAvailableSubscriptionsOptions, + ): Promise { + if (this.freshListingRequested) { + this.freshListingRequested = false; + options = { ...options, noCache: true }; + } + + const counters = { skippedAccounts: 0, skippedTenants: 0 }; + try { + const subscriptions = await this.listingSkips.run(counters, () => super.getAvailableSubscriptions(options)); + if (counters.skippedAccounts > 0 || counters.skippedTenants > 0) { + void callWithTelemetryAndErrorHandling('azureSubscriptions.partialListing', (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.measurements.skippedAccounts = counters.skippedAccounts; + context.telemetry.measurements.skippedTenants = counters.skippedTenants; + }); + + const showOutput = vscode.l10n.t('Show Output'); + void Promise.resolve( + vscode.window.showWarningMessage( + vscode.l10n.t( + 'Some Azure accounts or tenants could not be listed, so some subscriptions may be missing.', + ), + showOutput, + ), + ) + .then((choice) => { + if (choice === showOutput) { + ext.outputChannel.show(); + } + }) + .catch(() => { + meterSilentCatch('AzureSubscriptionProviderWithFilters_partialListingHint'); + }); + } + return subscriptions; + } catch (error) { + if (isNotSignedInError(error)) { + return []; + } + throw error; + } + } + + protected override errorForAccount(_account: AzureAccount, _message: string, _error: unknown): void { + const counters = this.listingSkips.getStore(); + if (counters) { + counters.skippedAccounts++; + } + ext.outputChannel.warn(vscode.l10n.t('Skipped an Azure account because its tenants could not be listed.')); + } + + protected override errorForTenant(_tenant: TenantIdAndAccount, _message: string, _error: unknown): void { + const counters = this.listingSkips.getStore(); + if (counters) { + counters.skippedTenants++; + } + ext.outputChannel.warn(vscode.l10n.t('Skipped an Azure tenant because its subscriptions could not be listed.')); } /** diff --git a/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts b/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts index 4441c6894..8d0512fe6 100644 --- a/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts +++ b/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts @@ -140,7 +140,7 @@ export class AccountTenantsStep extends AzureWizardPromptStep ({ ext: { outputChannel: { info: vi.fn(), error: vi.fn() } } })); + +describe('SelectAccountStep', () => { + it('includes a newly invited tenant when opening Manage Azure Accounts with a warm tenant cache', async () => { + const account = { id: 'fixture-account', label: 'Fixture account' }; + const existing = { tenantId: 'existing-tenant', account }; + const invited = { tenantId: 'new-tenant', account }; + const getTenantsForAccount = vi.fn(async (_account: typeof account, options?: { noCache?: boolean }) => + options?.noCache ? [existing, invited] : [existing], + ); + const signIn = vi.fn().mockResolvedValue(true); + const showQuickPick = vi.fn(async (items: Promise) => + (await items).find((item) => item.account === account), + ); + const context = { + azureSubscriptionProvider: { + getAccounts: vi.fn().mockResolvedValue([account]), + getTenantsForAccount, + signIn, + }, + allAccountsWithTenantInfo: [], + telemetry: { properties: {}, measurements: {} }, + ui: { showQuickPick }, + } as unknown as CredentialsManagementWizardContext; + + await new SelectAccountStep().prompt(context); + + expect(context.selectedAccount).toBe(account); + expect(context.allAccountsWithTenantInfo[0].tenantsWithStatus.map(({ tenant }) => tenant)).toEqual([ + existing, + invited, + ]); + expect(signIn).toHaveBeenCalledWith({ tenantId: invited.tenantId, account }, { promptIfNeeded: false }); + }); +}); diff --git a/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts index 3d92b5027..eafe0e382 100644 --- a/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts +++ b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts @@ -8,6 +8,7 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ext } from '../../../../extensionVariables'; import { nonNullProp, nonNullValue } from '../../../../utils/nonNull'; +import { getUnfilteredAzureTenants } from '../AzureSubscriptionProviderWithFilters'; import { tenantSignInLimiter } from '../tenantSignInLimiter'; import { traceTenantLookup } from '../traceTenantLookup'; import { @@ -150,7 +151,7 @@ export class SelectAccountStep extends AzureWizardPromptStep - context.azureSubscriptionProvider.getTenants(), + getUnfilteredAzureTenants(context.azureSubscriptionProvider, true), ); // Check sign-in status for all tenants with bounded parallelism @@ -158,7 +159,10 @@ export class SelectAccountStep extends AzureWizardPromptStep { const tenantId = nonNullProp(tenant, 'tenantId', 'tenant.tenantId', 'SelectAccountStep.ts'); const isSignedIn = await tenantSignInLimiter(() => - context.azureSubscriptionProvider.isSignedIn(tenantId, tenant.account), + context.azureSubscriptionProvider.signIn( + { tenantId, account: tenant.account }, + { promptIfNeeded: false }, + ), ); return { tenant, isSignedIn }; }), @@ -196,7 +200,7 @@ export class SelectAccountStep extends AzureWizardPromptStep { try { ext.outputChannel.info(l10n.t('Starting Azure sign-in process…')); - const success = await context.azureSubscriptionProvider.signIn(); + const success = await context.azureSubscriptionProvider.signIn(undefined, { clearSessionPreference: true }); if (success) { ext.outputChannel.info(l10n.t('Azure sign-in completed successfully')); } else { diff --git a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts index ea3246165..ce9222e78 100644 --- a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts +++ b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts @@ -6,15 +6,18 @@ import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; import { AzureWizardPromptStep, + UserCancelledError, type IActionContext, type IWizardOptions, - UserCancelledError, } from '@microsoft/vscode-azext-utils'; import { type AzureSubscription } from '@microsoft/vscode-azureresources-api'; import * as l10n from '@vscode/l10n'; import { type QuickPickItem } from 'vscode'; import { askToConfigureCredentials } from '../askToConfigureCredentials'; -import { type AzureSubscriptionProviderWithFilters } from '../AzureSubscriptionProviderWithFilters'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../AzureSubscriptionProviderWithFilters'; import { tenantSignInLimiter } from '../tenantSignInLimiter'; import { type FilteringWizardContext } from './FilteringWizardContext'; import { FilterSubscriptionSubStep } from './FilterSubscriptionSubStep'; @@ -61,7 +64,7 @@ export class InitializeFilteringStep extends AzureWizardPromptStep - azureSubscriptionProvider.isSignedIn(tenant.tenantId, tenant.account), + azureSubscriptionProvider.signIn(tenant, { promptIfNeeded: false }), ); return { tenant, isSignedIn }; }), @@ -93,7 +96,10 @@ export class InitializeFilteringStep extends AzureWizardPromptStep => { // Note: No tenant filtering here, because this flow should allow the user to access everything with no filtering. - subscriptions = await subscriptionProvider.getSubscriptions(false); + subscriptions = await subscriptionProvider.getAvailableSubscriptions({ + filter: false, + maximumTenants: Number.POSITIVE_INFINITY, + }); // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = subscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(subscriptionProvider).catch(() => { + meterSilentCatch('SelectSubscriptionStep_getUnfilteredAzureTenants'); + return undefined; + }); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts index 85b124707..9bfed4e60 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts @@ -108,9 +108,13 @@ vi.mock('../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { - getClient: vi.fn(), + connectInteractive: vi.fn(), deleteClient: vi.fn(), + exists: vi.fn(() => false), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts index b315dd7c2..47ce2ccc0 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts @@ -183,6 +183,7 @@ export class AtlasClusterItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = monotonicNow(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -277,8 +278,7 @@ export class AtlasClusterItem extends ClusterItemBase { await this.showConnectionFailure(context, error); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } @@ -346,7 +346,7 @@ export class AtlasClusterItem extends ClusterItemBase { getTreeItem(): vscode.TreeItem { return { id: this.id, - contextValue: this.contextValue, + contextValue: this.getClusterTreeItemContextValue(), label: this.cluster.name, description: this.buildDescription(), tooltip: this.buildTooltip(), diff --git a/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts b/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts index aed9fabe1..f3ded2da6 100644 --- a/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts +++ b/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts @@ -34,6 +34,10 @@ export class AzureMongoRUDiscoveryProvider extends Disposable implements Discove this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { return new AzureMongoRUServiceRootItem(this.azureSubscriptionProvider, parentId); } @@ -71,6 +75,10 @@ export class AzureMongoRUDiscoveryProvider extends Disposable implements Discove const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts b/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts index 8908dec1d..a8a04ce94 100644 --- a/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts +++ b/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts @@ -3,37 +3,50 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; +import { meterSilentCatch } from '../../../utils/accumulatingTelemetry'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureMongoRUSubscriptionItem } from './AzureMongoRUSubscriptionItem'; export class AzureMongoRUServiceRootItem - implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren { public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;azureMongoRUService'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-mongo-ru-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a journey correlation ID for funnel telemetry tracking const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -54,9 +67,10 @@ export class AzureMongoRUServiceRootItem } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => { + meterSilentCatch('AzureMongoRUServiceRootItem_getUnfilteredAzureTenants'); + return undefined; + }); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts index c3087cc89..1244b4b17 100644 --- a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts +++ b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts @@ -82,12 +82,17 @@ export class MongoRUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the MongoDB cluster. * @returns An instance of ClustersClient if successful; otherwise, null. */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -161,8 +166,7 @@ export class MongoRUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts b/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts index 24b715f75..501881a57 100644 --- a/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts +++ b/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts @@ -35,6 +35,10 @@ export class AzureDiscoveryProvider extends Disposable implements DiscoveryProvi this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { return new AzureServiceRootItem(this.azureSubscriptionProvider, parentId); } @@ -77,6 +81,10 @@ export class AzureDiscoveryProvider extends Disposable implements DiscoveryProvi const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts b/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts index 319cc47a0..53c16e188 100644 --- a/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts +++ b/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts @@ -3,36 +3,51 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; +import { meterSilentCatch } from '../../../utils/accumulatingTelemetry'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureSubscriptionItem } from './AzureSubscriptionItem'; -export class AzureServiceRootItem implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren { +export class AzureServiceRootItem + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren +{ public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;discoveryAzureServiceRootItem'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-mongo-vcore-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a new journey correlation ID for telemetry funnel analysis // This ID is passed to all child items and included in their telemetry events const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -53,9 +68,10 @@ export class AzureServiceRootItem implements TreeElement, TreeElementWithContext } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => { + meterSilentCatch('AzureMongoVCoreServiceRootItem_getUnfilteredAzureTenants'); + return undefined; + }); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts index a50d347c6..8c68af0f6 100644 --- a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts +++ b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts @@ -102,6 +102,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -220,8 +221,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts b/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts index 025c3a686..f405d3f22 100644 --- a/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts +++ b/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts @@ -45,6 +45,10 @@ export class AzureVMDiscoveryProvider extends Disposable implements DiscoveryPro this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { // For now, reusing AzureServiceRootItem. This might need to be a new AzureVMServiceRootItem if tree structure diverges significantly. return new AzureServiceRootItem(this.azureSubscriptionProvider, parentId); @@ -83,6 +87,10 @@ export class AzureVMDiscoveryProvider extends Disposable implements DiscoveryPro const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts b/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts index b2cc5aa0f..f4af7a4c1 100644 --- a/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts @@ -3,35 +3,50 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; +import { meterSilentCatch } from '../../../utils/accumulatingTelemetry'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureSubscriptionItem } from './AzureSubscriptionItem'; -export class AzureServiceRootItem implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren { +export class AzureServiceRootItem + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren +{ public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;discoveryAzureVMRootItem'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-vm-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a journey correlation ID for funnel telemetry tracking const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -52,9 +67,10 @@ export class AzureServiceRootItem implements TreeElement, TreeElementWithContext } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => { + meterSilentCatch('AzureVMServiceRootItem_getUnfilteredAzureTenants'); + return undefined; + }); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts new file mode 100644 index 000000000..ffc1e2da0 --- /dev/null +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts @@ -0,0 +1,270 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { type AzureSubscription } from '@microsoft/vscode-azureresources-api'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../../../documentdb/ClustersClient'; +import { CredentialCache, type CachedClusterCredentials } from '../../../../documentdb/CredentialCache'; +import * as unauthenticatedEndpoint from '../../../../documentdb/shell/unauthenticatedEndpoint'; +import { showClusterConnectFailure } from '../../../../documentdb/showClusterConnectFailure'; +import { DocumentDBConnectionString } from '../../../../documentdb/utils/DocumentDBConnectionString'; +import { Views } from '../../../../documentdb/Views'; +import { type AuthenticateWizardContext } from '../../../../documentdb/wizards/authenticate/AuthenticateWizardContext'; +import { DocumentDBExperience } from '../../../../DocumentDBExperiences'; +import { type TreeCluster } from '../../../../tree/models/BaseClusterModel'; +import { AzureVMResourceItem, type VirtualMachineModel } from './AzureVMResourceItem'; + +const prompts = vi.hoisted(() => ({ + port: vi.fn(), + credentials: vi.fn<(context: AuthenticateWizardContext) => Promise>(), +})); + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + AzureWizard: class { + public constructor(private readonly context: AuthenticateWizardContext) {} + + public async prompt(): Promise { + await prompts.credentials(this.context); + } + }, + callWithTelemetryAndErrorHandling: vi.fn( + async (_name: string, callback: (context: IActionContext) => Promise): Promise => { + const context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + ui: { showInputBox: prompts.port }, + } as unknown as IActionContext; + try { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow) { + throw error; + } + return undefined; + } + }, + ), + }; +}); + +vi.mock('../../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), + exists: vi.fn(() => false), + getExistingClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + getLastVerifiedIdentity: vi.fn(), + deleteClient: vi.fn(), + }, +})); + +vi.mock('../../../../documentdb/showClusterConnectFailure', () => ({ + showClusterConnectFailure: vi.fn(), +})); + +vi.mock('../../../../extensionVariables', () => ({ + ext: { + outputChannel: { append: vi.fn(), appendLine: vi.fn(), debug: vi.fn() }, + }, +})); + +class TestAzureVMResourceItem extends AzureVMResourceItem { + public override authenticateAndConnect(): Promise { + return super.authenticateAndConnect(); + } +} + +const subscription = { subscriptionId: 'sub', tenantId: 'tenant' } as unknown as AzureSubscription; +const clusterId = 'azure-vm_vm'; + +function item(connectionString: string = 'mongodb://vm.example:27017/'): TestAzureVMResourceItem { + return new TestAzureVMResourceItem('journey', subscription, { + name: 'vm', + treeId: 'discovery/vm', + clusterId, + dbExperience: DocumentDBExperience, + viewId: Views.DiscoveryView, + azureResourceId: '/subscriptions/sub/vm', + connectionString, + fqdn: 'vm.example', + } as TreeCluster); +} + +describe('Azure VM attempted unauthenticated endpoint', (): void => { + beforeEach((): void => { + vi.clearAllMocks(); + CredentialCache.deleteCredentials(clusterId); + vi.spyOn(console, 'warn').mockImplementation((): void => {}); + prompts.port.mockReset().mockResolvedValue('27017'); + prompts.credentials.mockReset().mockImplementation(async (context): Promise => { + context.selectedUserName = 'entered-user'; + context.password = 'entered-password'; + }); + vi.mocked(ClustersClient.connectInteractive).mockReset().mockRejectedValue(new Error('Connection refused')); + vi.mocked(vscode.window.showInputBox).mockReset(); + }); + + afterEach((): void => { + CredentialCache.deleteCredentials(clusterId); + vi.restoreAllMocks(); + }); + + it.each(['27017', '10260'])( + 'retains the actually attempted port %s after failure evicts credentials', + async (port): Promise => { + const vm = item(); + prompts.port.mockResolvedValue(port); + let endpointAtConnect: string | undefined; + let credentialsAtConnect: CachedClusterCredentials | undefined; + vi.mocked(ClustersClient.connectInteractive).mockImplementationOnce(async (): Promise => { + endpointAtConnect = await vm.getUnauthenticatedEndpoint(); + credentialsAtConnect = CredentialCache.getCredentials(clusterId); + throw new Error('Connection refused'); + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + expect(endpointAtConnect).toBe(`mongodb://vm.example:${port}/`); + expect(credentialsAtConnect).toMatchObject({ + connectionString: `mongodb://entered-user@vm.example:${port}/`, + nativeAuthConfig: { connectionUser: 'entered-user', connectionPassword: 'entered-password' }, + }); + expect(ClustersClient.connectInteractive).toHaveBeenCalledOnce(); + expect(showClusterConnectFailure).toHaveBeenCalledOnce(); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + + const cacheRead = vi.spyOn(CredentialCache, 'getCredentials'); + const cachePasswordRead = vi.spyOn(CredentialCache, 'getConnectionStringWithPassword'); + const credentialsRead = vi.spyOn(vm, 'getCredentials'); + const diagnosticsRead = vi.spyOn(vm, 'getCredentialsForDiagnostics'); + prompts.port.mockClear(); + prompts.credentials.mockClear(); + vi.mocked(ClustersClient.connectInteractive).mockClear(); + + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe(`mongodb://vm.example:${port}/`); + + expect(cacheRead).not.toHaveBeenCalled(); + expect(cachePasswordRead).not.toHaveBeenCalled(); + expect(credentialsRead).not.toHaveBeenCalled(); + expect(diagnosticsRead).not.toHaveBeenCalled(); + expect(prompts.port).not.toHaveBeenCalled(); + expect(prompts.credentials).not.toHaveBeenCalled(); + expect(vscode.window.showInputBox).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }, + ); + + it('re-reads a later connection attempt rather than freezing the first port', async (): Promise => { + const vm = item(); + const reread = (): Promise => vm.getUnauthenticatedEndpoint(); + prompts.port.mockResolvedValueOnce('10260').mockResolvedValueOnce('27500'); + + await vm.authenticateAndConnect(); + await expect(reread()).resolves.toBe('mongodb://vm.example:10260/'); + await vm.authenticateAndConnect(); + await expect(reread()).resolves.toBe('mongodb://vm.example:27500/'); + expect(vm.cluster.connectionString).toBe('mongodb://vm.example:27017/'); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + }); + + it('fails closed for a new or recreated node even when the model and cache have endpoints', async (): Promise => { + const attempted = item(); + prompts.port.mockResolvedValue('10260'); + await attempted.authenticateAndConnect(); + await expect(attempted.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + CredentialCache.setCredentials(clusterId, 'mongodb://cached.example:27500/', 'cached-user', 'cached-password'); + const recreated = item(); + const cacheRead = vi.spyOn(CredentialCache, 'getCredentials'); + const credentialsRead = vi.spyOn(recreated, 'getCredentials'); + prompts.port.mockClear(); + prompts.credentials.mockClear(); + vi.mocked(ClustersClient.connectInteractive).mockClear(); + + await expect(recreated.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + + expect(cacheRead).not.toHaveBeenCalled(); + expect(credentialsRead).not.toHaveBeenCalled(); + expect(prompts.port).not.toHaveBeenCalled(); + expect(prompts.credentials).not.toHaveBeenCalled(); + expect(vscode.window.showInputBox).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }); + + it('strips original and prompted credentials and authentication options but preserves transport settings', async (): Promise => { + const vm = item( + 'mongodb://original-user:original-password@vm.example:27017/db?' + + 'authMechanism=SCRAM-SHA-256&authSource=admin&authMechanismProperties=private&' + + 'proxyUsername=proxy-user&proxyPassword=proxy-password&tlsCertificateKeyFile=private.pem&' + + 'tlsCertificateKeyFilePassword=private&tls=true&tlsCAFile=trust.pem&directConnection=true', + ); + prompts.port.mockResolvedValue('10260'); + + await vm.authenticateAndConnect(); + + const endpoint = await vm.getUnauthenticatedEndpoint(); + expect(endpoint).toBe('mongodb://vm.example:10260/db?tls=true&tlsCAFile=trust.pem&directConnection=true'); + const parsed = new DocumentDBConnectionString(endpoint ?? ''); + expect(parsed.username).toBe(''); + expect(parsed.password).toBe(''); + }); + + it('does not record a port when the credential wizard stops before connecting', async (): Promise => { + const vm = item(); + prompts.port.mockResolvedValue('10260'); + prompts.credentials.mockImplementationOnce(async (context): Promise => { + context.aborted = true; + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + }); + + it('does not record or replace an endpoint from a diagnostics-only port prompt', async (): Promise => { + const vm = item(); + vi.mocked(vscode.window.showInputBox).mockResolvedValue('27500'); + const read = { signal: new AbortController().signal }; + + await expect(vm.getCredentialsForDiagnostics(read)).resolves.toMatchObject({ + connectionString: 'mongodb://vm.example:27500/', + }); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + + prompts.port.mockResolvedValue('10260'); + await vm.authenticateAndConnect(); + await expect(vm.getCredentialsForDiagnostics(read)).resolves.toMatchObject({ + connectionString: 'mongodb://vm.example:27500/', + }); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + }); + + it('clears the old endpoint and reports a bounded sanitizer failure before starting a client', async (): Promise => { + const vm = item(); + prompts.port.mockResolvedValueOnce('10260').mockResolvedValueOnce('27500'); + await vm.authenticateAndConnect(); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + const error = new Error('Invalid connection string.'); + vi.spyOn(unauthenticatedEndpoint, 'toUnauthenticatedConnectionString').mockImplementationOnce((): never => { + throw error; + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + + expect(ClustersClient.connectInteractive).toHaveBeenCalledOnce(); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + expect(showClusterConnectFailure).toHaveBeenLastCalledWith(expect.objectContaining({ error })); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + expect(ClustersClient.deleteClient).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts index d38c83d0b..e55481234 100644 --- a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts @@ -15,6 +15,7 @@ import * as vscode from 'vscode'; import { AuthMethodId } from '../../../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../../../documentdb/ClustersClient'; import { CredentialCache } from '../../../../documentdb/CredentialCache'; +import { toUnauthenticatedConnectionString } from '../../../../documentdb/shell/unauthenticatedEndpoint'; import { showClusterConnectFailure } from '../../../../documentdb/showClusterConnectFailure'; import { maskSensitiveValuesInTelemetry } from '../../../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../../../documentdb/utils/DocumentDBConnectionString'; @@ -90,6 +91,8 @@ function sessionPort(connectionString: string | undefined): number | undefined { } export class AzureVMResourceItem extends ClusterItemBase { + private _attemptedEndpoint?: string; + iconPath = new vscode.ThemeIcon('server-environment'); constructor( @@ -140,6 +143,10 @@ export class AzureVMResourceItem extends ClusterItemBase { }); } + public override async getUnauthenticatedEndpoint(): Promise { + return this._attemptedEndpoint; + } + /** * The diagnostics read (decision 0035, refined in WI-16): the VM's discovery data has no port, so * a port the user already entered in this session is reused silently. Otherwise the existing port @@ -254,6 +261,7 @@ export class AzureVMResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; context.telemetry.properties.view = Views.DiscoveryView; if (this.journeyCorrelationId) { @@ -313,6 +321,10 @@ export class AzureVMResourceItem extends ClusterItemBase { let clustersClient: ClustersClient; try { + this._attemptedEndpoint = undefined; + this._attemptedEndpoint = toUnauthenticatedConnectionString( + nonNullValue(connectionString, 'connectionString', 'AzureVMResourceItem.ts'), + ); clustersClient = await this.getClientWithProgress(this.cluster.clusterId); } catch (error) { if (error instanceof UserCancelledError) { @@ -330,8 +342,7 @@ export class AzureVMResourceItem extends ClusterItemBase { error, context, }); - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts index f06310bd3..36dc654f5 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts @@ -126,10 +126,13 @@ vi.mock('../../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { exists: vi.fn().mockReturnValue(false), - getClient: (...args: unknown[]) => mockGetClient(...args), + connectInteractive: (...args: unknown[]) => mockGetClient(...args), deleteClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts index e117c9270..1ddf1100d 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts @@ -257,6 +257,8 @@ export class KubernetesResourceItem extends ClusterItemBase { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const { ClustersClient } = await import('../../../../documentdb/ClustersClient'); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); this.populateTelemetry(context); context.telemetry.properties.connectionInitiatedFrom = 'discoveryView'; @@ -367,9 +369,7 @@ export class KubernetesResourceItem extends ClusterItemBase { + 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/services/copilotService.test.ts b/src/services/copilotService.test.ts index 4719fe2e1..cb1586de3 100644 --- a/src/services/copilotService.test.ts +++ b/src/services/copilotService.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { type IActionContext, UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { getBindingLifetimeSignal, retireConnectionBindings } from '../documentdb/connectionBindingRetirement'; // Mock vscode-azext-utils — the real `callWithTelemetryAndErrorHandling` // returns `undefined` for unhandled errors; we simulate the success path and @@ -135,6 +136,56 @@ describe('CopilotService.streamMessage', () => { selectChatModelsMock.mockReset(); }); + describe('CopilotService.sendMessage cancellation during model selection', () => { + it.each(['request-abort', 'host-retirement', 'live-control'] as const)( + 'fences the actual model sendRequest across paused model selection: %s', + async (cancellation): Promise => { + selectChatModelsMock.mockReset(); + let releaseSelection!: (models: unknown[]) => void; + selectChatModelsMock.mockReturnValueOnce( + new Promise((resolve): void => { + releaseSelection = resolve; + }), + ); + const binding = { + clusterId: `copilot-model-selection-${cancellation}`, + fingerprint: 'original', + generation: 1, + }; + const controller = new AbortController(); + const signal = AbortSignal.any([getBindingLifetimeSignal(binding), controller.signal]); + const sendRequest = vi.fn().mockResolvedValue({ + text: (async function* (): AsyncGenerator { + yield 'Synthetic response'; + })(), + }); + const model = { ...(makeFakeModel([]) as object), sendRequest }; + const pending = CopilotService.sendMessage([makeUserMessage('Synthetic query context') as never], { + featureSource: 'queryGeneration', + signal, + }); + expect(selectChatModelsMock).toHaveBeenCalledExactlyOnceWith({ + vendor: 'copilot', + family: 'copilot-utility', + }); + if (cancellation === 'request-abort') { + controller.abort(); + } else if (cancellation === 'host-retirement') { + retireConnectionBindings(binding.clusterId, binding.generation); + } + releaseSelection([model]); + + if (cancellation === 'live-control') { + await expect(pending).resolves.toMatchObject({ text: 'Synthetic response' }); + expect(sendRequest).toHaveBeenCalledOnce(); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sendRequest).not.toHaveBeenCalled(); + } + }, + ); + }); + it('yields fragments in order and resolves completion with the full text + usage', async () => { const fragments = ['Hello, ', 'world', '!']; selectChatModelsMock.mockResolvedValueOnce([makeFakeModel(fragments)]); diff --git a/src/services/discoveryServices.ts b/src/services/discoveryServices.ts index 4fd2c9d41..f4ff3945a 100644 --- a/src/services/discoveryServices.ts +++ b/src/services/discoveryServices.ts @@ -62,6 +62,8 @@ export interface DiscoveryProvider extends ProviderDescription { */ getDiscoveryTreeRootItem(parentId: string): TreeElement; + prepareExplicitReload?(): void; + getLearnMoreUrl?(): string | undefined; configureTreeItemFilter?(context: IActionContext, node: TreeElement): Promise; diff --git a/src/services/localQuickStart/quickStartTypes.ts b/src/services/localQuickStart/quickStartTypes.ts index c727cc34b..14c5d3dc0 100644 --- a/src/services/localQuickStart/quickStartTypes.ts +++ b/src/services/localQuickStart/quickStartTypes.ts @@ -130,6 +130,11 @@ export function clusterId(alias: string): string { return `quickstart-${alias}`; } +/** Whether the stable cluster ID belongs to the supported managed instance. */ +export function isQuickStartClusterId(id: string): boolean { + return id === clusterId(DEFAULT_ALIAS); +} + /** Reduced lifecycle state set for the POC (design §6, decision D8). */ export enum InstanceState { NotInstalled = 'NotInstalled', diff --git a/src/services/taskService/README.md b/src/services/taskService/README.md index a11fbe0d2..742e6fe71 100644 --- a/src/services/taskService/README.md +++ b/src/services/taskService/README.md @@ -532,7 +532,6 @@ src/services/taskService/ │ ├── RetryOrchestrator.ts # Retry logic │ └── WriteStats.ts # Statistics aggregation └── tasks/ - ├── DemoTask.ts # Simple example task └── copy-and-paste/ ├── CopyPasteCollectionTask.ts # Main copy-paste task └── copyPasteConfig.ts # Configuration types diff --git a/src/services/taskService/taskService.test.ts b/src/services/taskService/taskService.test.ts index 7bb11e4d0..ce4da3236 100644 --- a/src/services/taskService/taskService.test.ts +++ b/src/services/taskService/taskService.test.ts @@ -6,6 +6,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Task, TaskService, TaskState, type TaskStatus } from './taskService'; +import { type ResourceDefinition, type ResourceTrackingTask } from './taskServiceResourceTracking'; + +const { latchReasons } = vi.hoisted(() => ({ + latchReasons: new Map(), +})); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { + getLatchReason: (clusterId: string): string | undefined => latchReasons.get(clusterId), + }, +})); // Mock extensionVariables (ext) module vi.mock('../../extensionVariables', () => ({ @@ -75,13 +86,14 @@ vi.mock('vscode', () => ({ /** * Simple test task implementation */ -class TestTask extends Task { +class TestTask extends Task implements ResourceTrackingTask { public readonly type = 'test'; public readonly name: string; private readonly workSteps: number; private readonly stepDuration: number; private readonly shouldFail: boolean; private readonly failAtStep?: number; + private readonly resources: ResourceDefinition[]; constructor( name: string, @@ -90,6 +102,7 @@ class TestTask extends Task { stepDuration?: number; shouldFail?: boolean; failAtStep?: number; + resources?: ResourceDefinition[]; } = {}, ) { super(); @@ -98,6 +111,11 @@ class TestTask extends Task { this.stepDuration = options.stepDuration ?? 20; this.shouldFail = options.shouldFail ?? false; this.failAtStep = options.failAtStep; + this.resources = options.resources ?? []; + } + + public getUsedResources(): ResourceDefinition[] { + return this.resources; } protected async doWork(signal: AbortSignal): Promise { @@ -160,6 +178,7 @@ describe('TaskService', () => { let taskService: typeof TaskService; beforeEach(() => { + latchReasons.clear(); // Clear the singleton state between tests taskService = TaskService; // Clear any existing tasks @@ -177,6 +196,75 @@ describe('TaskService', () => { expect(taskService.listTasks()).toContain(task); }); + it('exposes active resource leases to collection and folder conflict queries', () => { + const lease = taskService.acquireResourceLease( + { + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'collection', + }, + 'Export documents', + ); + + try { + expect( + taskService.getConflictingTasks({ + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toEqual([ + expect.objectContaining({ + taskName: 'Export documents', + taskType: 'resource-lease', + }), + ]); + expect(taskService.getConflictingTasks({ clusterId: 'lease-cluster' })).toHaveLength(1); + expect(taskService.findConflictingTasksForConnections(['lease-cluster'])).toHaveLength(1); + expect(taskService.findConflictingTasksForConnections(['other-cluster'])).toEqual([]); + expect( + taskService.getConflictingTasks({ + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'other-collection', + }), + ).toEqual([]); + } finally { + lease.dispose(); + lease.dispose(); + } + + expect(taskService.getConflictingTasks({ clusterId: 'lease-cluster' })).toEqual([]); + expect(taskService.findConflictingTasksForConnections(['lease-cluster'])).toEqual([]); + }); + + it('refuses task and lease admission with the cluster latch reason', async () => { + const resource = { + clusterId: 'latched-cluster', + databaseName: 'database', + collectionName: 'collection', + }; + const task = new TestTask('Blocked Task', { resources: [resource] }); + latchReasons.set(resource.clusterId, 'credentialsChanged'); + + expect(() => taskService.registerTask(task)).toThrowError( + expect.objectContaining({ name: 'ConnectionUnavailableError', reason: 'credentialsChanged' }), + ); + expect(() => taskService.acquireResourceLease(resource, 'Blocked transfer')).toThrowError( + expect.objectContaining({ name: 'ConnectionUnavailableError', reason: 'credentialsChanged' }), + ); + + latchReasons.delete(resource.clusterId); + taskService.registerTask(task); + latchReasons.set(resource.clusterId, 'connectionRemoved'); + + await expect(task.start()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'connectionRemoved', + }); + expect(task.getStatus().state).toBe(TaskState.Pending); + }); + it('should track task progress and state transitions in correct order', async () => { const task = new TestTask('Progress Task', { workSteps: 5, stepDuration: 10 }); taskService.registerTask(task); diff --git a/src/services/taskService/taskService.ts b/src/services/taskService/taskService.ts index 1a8b2a9f4..16a116586 100644 --- a/src/services/taskService/taskService.ts +++ b/src/services/taskService/taskService.ts @@ -5,6 +5,8 @@ import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; import { recordSurveyActivity } from '../survey/SurveyService'; import { @@ -99,6 +101,25 @@ export function isTerminalState(state: TaskState): boolean { return state === TaskState.Completed || state === TaskState.Failed || state === TaskState.Stopped; } +function getTaskUsedResources(task: Task): ResourceDefinition[] { + if (!('getUsedResources' in task) || typeof (task as ResourceTrackingTask).getUsedResources !== 'function') { + return []; + } + return (task as ResourceTrackingTask).getUsedResources(); +} + +function assertResourcesAdmitted(resources: ResourceDefinition[]): void { + for (const resource of resources) { + if (!resource.clusterId) { + continue; + } + const reason = ClustersClient.getLatchReason(resource.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } +} + /** * Abstract base class for long-running tasks managed by the TaskService. * @@ -270,6 +291,8 @@ export abstract class Task { throw new Error(vscode.l10n.t('Cannot start task in state: {0}', this._status.state)); } + assertResourcesAdmitted(getTaskUsedResources(this)); + ext.outputChannel.appendLine(vscode.l10n.t("○ Task '{taskName}' initializing...", { taskName: this.name })); this.updateStatus(TaskState.Initializing, vscode.l10n.t('Initializing task...'), 0); @@ -496,6 +519,15 @@ export interface TaskService { */ registerTask(task: Task): void; + /** + * Synchronously acquires a resource lease for work that is not represented by a Task. + * + * @param resource The resource used by the operation. + * @param label A user-readable operation label used in conflict reporting. + * @returns A disposable that releases the lease. Disposal is idempotent. + */ + acquireResourceLease(resource: ResourceDefinition, label: string): vscode.Disposable; + /** * Retrieves a task by its ID. * @@ -585,6 +617,10 @@ export interface TaskService { class TaskServiceImpl implements TaskService { private readonly tasks = new Map(); private readonly taskSubscriptions = new Map(); + private readonly resourceLeases = new Map< + string, + { readonly task: TaskInfo; readonly resource: ResourceDefinition } + >(); // Event emitters for the service events private readonly _onDidRegisterTask = new vscode.EventEmitter(); @@ -600,7 +636,11 @@ class TaskServiceImpl implements TaskService { public registerTask(task: Task): void { if (this.tasks.has(task.id)) { throw new Error(vscode.l10n.t('Task with ID {0} already exists', task.id)); - } // Subscribe to task events and aggregate them + } + + assertResourcesAdmitted(getTaskUsedResources(task)); + + // Subscribe to task events and aggregate them const subscriptions: vscode.Disposable[] = [ task.onDidChangeStatus((status) => { this._onDidChangeTaskStatus.fire({ taskId: task.id, status }); @@ -615,6 +655,30 @@ class TaskServiceImpl implements TaskService { this._onDidRegisterTask.fire(task); } + public acquireResourceLease(resource: ResourceDefinition, label: string): vscode.Disposable { + assertResourcesAdmitted([resource]); + + const leaseId = `resource-lease-${crypto.randomUUID()}`; + this.resourceLeases.set(leaseId, { + task: { + taskId: leaseId, + taskName: label, + taskType: 'resource-lease', + }, + resource: { ...resource }, + }); + + let disposed = false; + return { + dispose: (): void => { + if (!disposed) { + disposed = true; + this.resourceLeases.delete(leaseId); + } + }, + }; + } + public getTask(id: string): Task | undefined { return this.tasks.get(id); } @@ -654,20 +718,23 @@ class TaskServiceImpl implements TaskService { }); for (const task of activeTasks) { - // Check if task implements resource tracking - if ('getUsedResources' in task && typeof (task as ResourceTrackingTask).getUsedResources === 'function') { - const usedResources = (task as ResourceTrackingTask).getUsedResources(); + const usedResources = getTaskUsedResources(task); - // Check if any of the task's resources conflict with the requested resource - const hasConflict = usedResources.some((usedResource) => hasResourceConflict(resource, usedResource)); + // Check if any of the task's resources conflict with the requested resource + const hasConflict = usedResources.some((usedResource) => hasResourceConflict(resource, usedResource)); - if (hasConflict) { - conflictingTasks.push({ - taskId: task.id, - taskName: task.name, - taskType: task.type, - }); - } + if (hasConflict) { + conflictingTasks.push({ + taskId: task.id, + taskName: task.name, + taskType: task.type, + }); + } + } + + for (const lease of this.resourceLeases.values()) { + if (hasResourceConflict(resource, lease.resource)) { + conflictingTasks.push(lease.task); } } @@ -684,23 +751,24 @@ class TaskServiceImpl implements TaskService { }); for (const task of activeTasks) { - // Check if task implements resource tracking - if ('getUsedResources' in task && typeof (task as ResourceTrackingTask).getUsedResources === 'function') { - const resources = (task as ResourceTrackingTask).getUsedResources(); - - if (resources.length > 0) { - result.push({ - task: { - taskId: task.id, - taskName: task.name, - taskType: task.type, - }, - resources, - }); - } + const resources = getTaskUsedResources(task); + + if (resources.length > 0) { + result.push({ + task: { + taskId: task.id, + taskName: task.name, + taskType: task.type, + }, + resources, + }); } } + for (const lease of this.resourceLeases.values()) { + result.push({ task: lease.task, resources: [lease.resource] }); + } + return result; } diff --git a/src/services/taskService/tasks/DemoTask.ts b/src/services/taskService/tasks/DemoTask.ts deleted file mode 100644 index 5db1e3267..000000000 --- a/src/services/taskService/tasks/DemoTask.ts +++ /dev/null @@ -1,109 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import * as vscode from 'vscode'; -import { Task } from '../taskService'; - -/** - * A demo task implementation that demonstrates the Task abstract class. - * This task simulates work by using timeouts and provides progress updates over a 10-second duration. - * - * The base class handles all state management, allowing this implementation - * to focus solely on the business logic. - */ -export class DemoTask extends Task { - public readonly type: string = 'demo-task'; - public readonly name: string; - private readonly shouldFail: boolean; - - /** - * Creates a new DemoTask instance. - * - * @param name User-friendly name for the task. - * @param shouldFail Optional parameter to make the task fail after a random amount of time for testing purposes. - */ - constructor(name: string, shouldFail: boolean = false) { - super(); - this.name = name; - this.shouldFail = shouldFail; - } - - /** - * Implements the main task logic with progress updates. - * The base class handles all state transitions and error handling. - * - * @param signal AbortSignal to check for stop requests. - */ - protected async doWork(signal: AbortSignal): Promise { - const totalSteps = 10; - const stepDuration = 1000; // 1 second per step - - // If shouldFail is true, determine a random failure point between step 2 and 8 - const failureStep = this.shouldFail ? Math.floor(Math.random() * 7) + 2 : -1; // Random between 2-8 - - for (let step = 0; step < totalSteps; step++) { - // Check for abort signal - if (signal.aborted) { - // Perform cleanup when stopping - no need for separate message update - await this.cleanup(); - return; - } - - // Check if we should fail at this step - if (this.shouldFail && step === failureStep) { - throw new Error(vscode.l10n.t('Simulated failure at step {0} for testing purposes', step + 1)); - } - - // Update progress - const progress = ((step + 1) / totalSteps) * 100; - this.updateProgress(progress, vscode.l10n.t('Processing step {0} of {1}', step + 1, totalSteps)); - - // Simulate work - await this.sleep(stepDuration); - } - } - - /** - * Optional initialization logic. - * Called by the base class during start(). - * - * @param signal AbortSignal (not used in this demo, but part of the API) - */ - protected async onInitialize(_signal: AbortSignal): Promise { - console.log(`Initializing task: ${this.name}`); - // Could perform resource allocation, connection setup, etc. - await this.sleep(3000); // Simulate some initialization delay - } - - /** - * Optional cleanup logic when deleting. - * Called by the base class during delete(). - */ - protected async onDelete(): Promise { - console.log(`Deleting task: ${this.name}`); - // Could clean up temporary files, release resources, etc. - return this.sleep(2000); // Simulate cleanup delay - } - - /** - * Performs cleanup operations when the task is stopped. - * This is called from within doWork when AbortSignal is triggered. - */ - private async cleanup(): Promise { - console.log(`Cleaning up task: ${this.name}`); - // Could close connections, save state, etc. - return this.sleep(2000); // Simulate cleanup delay - longer to better demonstrate stopping state - // This demonstrates how to handle cleanup using AbortSignal instead of onStop - } - - /** - * Helper method to create a delay. - * - * @param ms Delay in milliseconds. - */ - private sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); - } -} diff --git a/src/settingsKeys.ts b/src/settingsKeys.ts index 7b40d5f22..db848c941 100644 --- a/src/settingsKeys.ts +++ b/src/settingsKeys.ts @@ -19,6 +19,7 @@ export namespace settingsKeys { // Connections & Discovery export const connectionTimeout = 'documentDB.connectionTimeout'; + export const openTabsOnDisconnect = 'documentDB.connections.openTabsOnDisconnect'; export const localPort = 'documentDB.local.port'; export const kubernetesLocalPortStrategy = 'documentDB.serviceDiscovery.kubernetes.portForward.localPortStrategy'; export const kubernetesLocalPortBase = 'documentDB.serviceDiscovery.kubernetes.portForward.localPortBase'; diff --git a/src/tree/BaseExtendedTreeDataProvider.ts b/src/tree/BaseExtendedTreeDataProvider.ts index 29e16a474..3b7625706 100644 --- a/src/tree/BaseExtendedTreeDataProvider.ts +++ b/src/tree/BaseExtendedTreeDataProvider.ts @@ -5,6 +5,7 @@ import { createContextValue, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { addEstablishedConnectionContext } from '../documentdb/ClustersClient'; import { ext } from '../extensionVariables'; import { ErrorExplanationService } from '../services/errorExplanationService'; import { dispose } from '../utils/vscodeUtils'; @@ -530,6 +531,12 @@ export abstract class BaseExtendedTreeDataProvider return this.failedChildrenCache.get(element.id); } + // Capture the established generation before expansion. A classified failure can evict it + // before the getChildren event is reported. + const clusterId = (element as { cluster?: { clusterId?: string } }).cluster?.clusterId; + if (clusterId) { + addEstablishedConnectionContext(context.telemetry, clusterId); + } // 2. Fetch the children of the current element const children = await this.fetchChildrenWithDiagnostics(element, context, childrenFetchFunc); context.telemetry.measurements.childrenCount = children?.length ?? 0; diff --git a/src/tree/TreeElementWithExplicitReload.ts b/src/tree/TreeElementWithExplicitReload.ts new file mode 100644 index 000000000..ddd0832b4 --- /dev/null +++ b/src/tree/TreeElementWithExplicitReload.ts @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface TreeElementWithExplicitReload { + prepareExplicitReload(): void; +} + +export function isTreeElementWithExplicitReload(value: unknown): value is TreeElementWithExplicitReload { + return ( + typeof value === 'object' && + value !== null && + 'prepareExplicitReload' in value && + typeof value.prepareExplicitReload === 'function' + ); +} diff --git a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts index ee2a224aa..a14655e1f 100644 --- a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts +++ b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts @@ -94,6 +94,7 @@ export class VCoreResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.view = Views.AzureResourcesView; context.telemetry.properties.branch = 'documentdb'; context.telemetry.properties.connectionInitiatedFrom = Views.AzureResourcesView; @@ -203,8 +204,7 @@ export class VCoreResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts index 3e8b8c631..312715fbf 100644 --- a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts +++ b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts @@ -71,10 +71,21 @@ vi.mock('../../../utils/azureClients', () => ({ createMongoClustersManagementClient: vi.fn(() => ({ mongoClusters: { get: getCluster } })), })); vi.mock('../../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + }, })); vi.mock('../../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { + getCredentials: vi.fn(), + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + }, })); vi.mock('../../../extensionVariables', () => ({ ext: { @@ -116,7 +127,9 @@ describe.each([ beforeEach((): void => { vi.clearAllMocks(); vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ inspect: vi.fn(), } as unknown as vscode.WorkspaceConfiguration); diff --git a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts index 5f62ee492..6eca8c5d7 100644 --- a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts +++ b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts @@ -78,6 +78,10 @@ export class RUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the Azure Cosmos DB for MongoDB (RU) cluster. * No authentication prompt as we're accessing the cluster with the default credentials. @@ -118,6 +122,7 @@ export class RUResourceItem extends ClusterItemBase { }), ); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); try { const clustersClient = await this.getClientWithProgress(this.cluster.clusterId); @@ -150,8 +155,7 @@ export class RUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts b/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts index 51072e26f..4432b34a4 100644 --- a/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts +++ b/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts @@ -76,14 +76,14 @@ describe('Connections recovery actions', () => { ...(reason ? ['vscode-documentdb.command.connectionsView.updateConnectionString'] : []), 'vscode-documentdb.command.connectionsView.updateCredentials', 'vscode-documentdb.command.diagnoseConnection', - 'vscode-documentdb.command.shell.open', + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', 'vscode-documentdb.command.internal.retry', ]); expect(treeItems.map((child) => child.label)).toEqual([ ...(reason ? ['Update connection string…'] : []), 'Update credentials…', 'Diagnose connection…', - 'Open shell', + 'Open shell without authentication', 'Retry', ]); expect(treeItems.every((child) => !!child.command)).toBe(true); diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index ac8c75c23..7be74551e 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { + UserCancelledError, type AzureWizard, type callWithTelemetryAndErrorHandling, type IActionContext, @@ -74,7 +75,10 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ }); try { return await callback(context); - } catch { + } catch (error) { + if (error instanceof UserCancelledError) { + context.telemetry.properties.result = 'Canceled'; + } return undefined; } }, @@ -84,10 +88,22 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + }, })); vi.mock('../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + getCredentials: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, @@ -120,7 +136,9 @@ describe('saved connection destination authentication', () => { beforeEach((): void => { vi.clearAllMocks(); vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ inspect: vi.fn(), } as unknown as vscode.WorkspaceConfiguration); @@ -132,12 +150,34 @@ describe('saved connection destination authentication', () => { ); }); + it.each([StorageZone.Clusters, StorageZone.Emulators])( + 'reads the current %s stored endpoint without preparing or authenticating it', + async (storageZone): Promise => { + const item = makeItem(); + item.cluster.storageZone = storageZone; + item.cluster.connectionString = 'mongodb://stale-model/'; + const getCredentials = vi.spyOn(item, 'getCredentials'); + vi.mocked(ConnectionStorageService.get) + .mockResolvedValueOnce(makeConnection('mongodb://user:password@current-host/')) + .mockResolvedValueOnce(undefined); + expect(await item.getUnauthenticatedEndpoint()).toBe('mongodb://user:password@current-host/'); + expect(await item.getUnauthenticatedEndpoint()).toBeUndefined(); + expect(ConnectionStorageService.get).toHaveBeenCalledWith('stable-id', storageZone); + expect(getCredentials).not.toHaveBeenCalled(); + expect(ConnectionReachabilityService.ensureReachable).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }, + ); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'reports a forced saved %s rejection without opening a picker or falling back', async (method): Promise => { const connection = makeConnection('mongodb://other.example.com/', method); vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); - vi.mocked(ClustersClient.getClient).mockRejectedValue( + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( new EntraDestinationRejectedError(evaluateEntraDestination(connection.secrets.connectionString)), ); const item = makeItem(); @@ -147,7 +187,7 @@ describe('saved connection destination authentication', () => { expect(wizardCreated).not.toHaveBeenCalled(); expect(prompt).not.toHaveBeenCalled(); expect(showQuickPick).not.toHaveBeenCalled(); - expect(ClustersClient.getClient).toHaveBeenCalledTimes(1); + expect(ClustersClient.connectInteractive).toHaveBeenCalledTimes(1); expect(CredentialCache.setAuthCredentials).toHaveBeenCalledWith( 'stable-id', method, @@ -216,7 +256,7 @@ describe('saved connection destination authentication', () => { const error = new EntraDestinationRejectedError( evaluateEntraDestination(connection.secrets.connectionString), ); - vi.mocked(ClustersClient.getClient).mockRejectedValue(error); + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue(error); showErrorMessage.mockResolvedValueOnce('Learn More'); if (outcome === 'false') { vi.mocked(vscode.env.openExternal).mockResolvedValueOnce(false); @@ -259,7 +299,7 @@ describe('connect request telemetry', () => { // The request returns no client after a failed connection, which the wrapper reports as // Succeeded; the outcome and the failed attempt's ID must be explicit. it('reports a failed connection with the ID of the attempt that failed', async (): Promise => { - vi.mocked(ClustersClient.getClient).mockImplementation(async (_clusterId, _signal, onStartup) => { + vi.mocked(ClustersClient.connectInteractive).mockImplementation(async (_clusterId, _signal, onStartup) => { onStartup?.('failed-attempt'); throw new Error('Authentication failed.'); }); @@ -269,13 +309,76 @@ describe('connect request telemetry', () => { expect(connectEvent()).toMatchObject({ connectionResult: 'failed', connectionCorrelationId: 'failed-attempt' }); }); + it('cancels the decoded-password retry without reporting another failure or clearing shared state', async (): Promise => { + const connection = makeConnection('mongodb://localhost:27017/', AuthMethodId.NativeAuth); + connection.secrets.nativeAuthConfig = { connectionUser: 'test-user', connectionPassword: 'test%40password' }; + vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); + const connectInteractive = vi.mocked(ClustersClient.connectInteractive); + connectInteractive + .mockRejectedValueOnce(new Error('Authentication failed.')) + .mockRejectedValueOnce(new UserCancelledError()); + showErrorMessage.mockResolvedValueOnce('Try with decoded password'); + const item = makeItem(); + + await expect(item.connect()).resolves.toBeNull(); + + expect(connectInteractive).toHaveBeenCalledTimes(2); + expect(showErrorMessage).toHaveBeenCalledExactlyOnceWith( + expect.any(String), + expect.objectContaining({ modal: true }), + 'Try with decoded password', + ); + const deleteClient = vi.mocked(ClustersClient.deleteClient); + expect(deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(deleteClient.mock.invocationCallOrder[0]).toBeLessThan(connectInteractive.mock.invocationCallOrder[1]); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(item.lastConnectionOutcome).toBe('canceled'); + expect(connectEvent()).toMatchObject({ + result: 'Canceled', + connectionResult: 'cancelled', + urlDecodePasswordResult: 'cancelled', + }); + }); + + it('does not save the decoded password when the saved-credentials offer is dismissed', async (): Promise => { + const connection = makeConnection('mongodb://localhost:27017/', AuthMethodId.NativeAuth); + connection.secrets.nativeAuthConfig = { connectionUser: 'test-user', connectionPassword: 'test%40password' }; + vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); + vi.mocked(ClustersClient.connectInteractive) + .mockRejectedValueOnce(new Error('Authentication failed.')) + .mockResolvedValueOnce({ connectionCorrelationId: 'retry' } as ClustersClient); + showErrorMessage.mockResolvedValueOnce('Try with decoded password'); + vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce(undefined); + + await expect(makeItem().connect()).resolves.toMatchObject({ connectionCorrelationId: 'retry' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'Connected to "Saved connection" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?', + { modal: false }, + 'Update saved password', + ); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + }); + it('reports a successful connection with its connection ID', async (): Promise => { - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); await expect(makeItem().connect()).resolves.toMatchObject({ connectionCorrelationId: 'attempt' }); expect(connectEvent()).toMatchObject({ connectionResult: 'success', connectionCorrelationId: 'attempt' }); }); + + it('does not drop startup settings for a transient connection error', async (): Promise => { + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( + Object.assign(new Error('connection refused'), { code: 'ECONNREFUSED' }), + ); + await expect(makeItem().connect()).resolves.toBeNull(); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(connectEvent()).toMatchObject({ connectionFailureKind: 'transient' }); + }); }); describe('DocumentDBClusterItem credential reachability', (): void => { diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index 2b6497b94..c3ad4dca3 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -54,6 +54,11 @@ export class DocumentDBClusterItem extends ClusterItemBase { + const connection = await ConnectionStorageService.get(this.storageId, resolveStorageZone(this.cluster)); + return connection && isConnection(connection) ? connection.secrets.connectionString : undefined; + } + public async getCredentials(options?: GetCredentialsOptions): Promise { const connectionType = resolveStorageZone(this.cluster); const connectionCredentials = await ConnectionStorageService.get(this.storageId, connectionType); @@ -262,6 +267,8 @@ export class DocumentDBClusterItem extends ClusterItemBase ({ const mockGetClient = vi.fn(); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), exists: vi.fn().mockReturnValue(false), - getClient: (...args: unknown[]) => mockGetClient(...args), + connectInteractive: (...args: unknown[]) => mockGetClient(...args), }, })); diff --git a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts index 9adb985a8..cc8f0094a 100644 --- a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts +++ b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts @@ -13,7 +13,7 @@ import path from 'path'; import * as vscode from 'vscode'; import { type IconPath } from 'vscode'; import { AuthMethodId } from '../../../documentdb/auth/AuthMethod'; -import { type ClustersClient } from '../../../documentdb/ClustersClient'; +import { ClustersClient } from '../../../documentdb/ClustersClient'; import { CredentialCache } from '../../../documentdb/CredentialCache'; import { maskSensitiveValuesInTelemetry } from '../../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../../documentdb/utils/DocumentDBConnectionString'; @@ -315,7 +315,11 @@ class QuickStartClusterItem extends ClusterItemBase { * state label (e.g. "Running"). */ public override getTreeItem(): vscode.TreeItem { - const treeItem = buildClusterTreeItem({ id: this.id, contextValue: this.contextValue, cluster: this.cluster }); + const treeItem = buildClusterTreeItem({ + id: this.id, + contextValue: this.getClusterTreeItemContextValue(), + cluster: this.cluster, + }); return { ...treeItem, description: this.descriptionOverride, @@ -327,7 +331,13 @@ class QuickStartClusterItem extends ClusterItemBase { } public override async getChildren(): Promise { + if (ClustersClient.getLatchReason(this.cluster.clusterId) === 'userDisconnected') { + return super.getChildren(); + } const preflight: QuickStartConnectionPreflightResult = await QuickStartService.prepareForConnection(this.alias); + if (ClustersClient.getLatchReason(this.cluster.clusterId) === 'userDisconnected') { + return super.getChildren(); + } if (preflight !== 'ready') { return buildPreflightChildren(this.id, preflight); } @@ -382,7 +392,10 @@ class QuickStartClusterItem extends ClusterItemBase { return result ?? null; } - protected override async getClientWithProgress(clusterId: string): Promise { + protected override async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { context.errorHandling.rethrow = true; context.errorHandling.suppressDisplay = true; @@ -391,7 +404,7 @@ class QuickStartClusterItem extends ClusterItemBase { if (connectionString) { maskSensitiveValuesInTelemetry(context, new DocumentDBConnectionString(connectionString)); } - return super.getClientWithProgress(clusterId); + return super.getClientWithProgress(clusterId, onReuse); }); return nonNullValue(result, 'connected client', 'QuickStartClusterItem.getClientWithProgress'); } diff --git a/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts b/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts index 30de44751..642eab353 100644 --- a/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts +++ b/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts @@ -5,10 +5,9 @@ import { Views } from '../../../documentdb/Views'; import { QuickStartService } from '../../../services/localQuickStart/QuickStartService'; -import { - clusterId as buildQuickStartClusterId, - DEFAULT_ALIAS, -} from '../../../services/localQuickStart/quickStartTypes'; +import { isQuickStartClusterId } from '../../../services/localQuickStart/quickStartTypes'; + +export { isQuickStartClusterId }; /** Builds the tree ID of the Quick Start root node. */ export function buildQuickStartTreeId(parentId: string = Views.ConnectionsView): string { @@ -20,11 +19,6 @@ export function buildQuickStartInstanceTreeId(parentId: string = Views.Connectio return `${buildQuickStartTreeId(parentId)}/instance`; } -/** Whether the stable cluster ID belongs to the currently supported managed instance. */ -export function isQuickStartClusterId(clusterId: string): boolean { - return clusterId === buildQuickStartClusterId(DEFAULT_ALIAS); -} - /** * Resolves the current managed instance's stable cluster ID to its synthetic tree ID. * diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index fac610fa9..a313f7ff4 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,10 +11,16 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { connectDisconnected, disconnect } from '../../commands/disconnect/disconnect'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; -import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { type Experience } from '../../DocumentDBExperiences'; +import { ext } from '../../extensionVariables'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; import { BaseExtendedTreeDataProvider } from '../BaseExtendedTreeDataProvider'; import { type BaseClusterModel, type TreeCluster } from '../models/BaseClusterModel'; @@ -26,7 +32,8 @@ import { ClusterItemBase, type EphemeralClusterCredentials } from './ClusterItem const mockTelemetryEvents: Array<{ eventName: string; properties: Record; suppressDisplay?: boolean }> = []; -vi.mock('@microsoft/vscode-azext-utils', () => ({ +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal>()), UserCancelledError: class UserCancelledError extends Error {}, callWithTelemetryAndErrorHandling: vi.fn( async ( @@ -67,13 +74,28 @@ const mockGetSetting = vi.fn().mockReturnValue(false); vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: (...args: unknown[]) => mockHasCredentials(...args), + getCredentials: vi.fn(), + deleteCredentials: vi.fn(), }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), + exists: vi.fn().mockReturnValue(false), + getExistingClient: vi.fn(), + getLatchReason: vi.fn(), + unlatch: vi.fn(), + getEpoch: vi.fn(() => 0), + getLastVerifiedIdentity: vi.fn(), + reportFailure: vi.fn(), + }, })); +vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); + +const notifyChildrenChanged = vi.fn(); vi.mock('../../extensionVariables', () => ({ ext: { settingsKeys: { @@ -83,6 +105,11 @@ vi.mock('../../extensionVariables', () => ({ appendLine: vi.fn(), debug: vi.fn(), }, + state: { notifyChildrenChanged: (...args: unknown[]) => notifyChildrenChanged(...args) }, + connectionsBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + discoveryBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + azureResourcesRUBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + azureResourcesVCoreBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, }, })); @@ -166,6 +193,21 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => ClustersClientMock.exists.mockReturnValue(false); }); + it('reads only the available model endpoint without authentication or client acquisition', async (): Promise => { + const cluster: TreeCluster = { + ...makeCluster(), + connectionString: 'mongodb://user:password@host/', + }; + const item = new TestClusterItem(cluster, null); + const credentials = vi.spyOn(item, 'getCredentials'); + expect(await item.getUnauthenticatedEndpoint()).toBe(cluster.connectionString); + cluster.connectionString = undefined; + expect(await item.getUnauthenticatedEndpoint()).toBeUndefined(); + expect(credentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); + }); + it('returns a retry node (and records telemetry) when listDatabases is rejected', async () => { const listDatabases = vi .fn() @@ -198,8 +240,8 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => expect(children[1].id).toBe('cluster-1/open-shell'); expect(children[1].contextValue).toBe('error'); - expect(children[1].label).toBe('Open shell'); - expect(children[1].commandId).toBe(ShellCommandIds.open); + expect(children[1].label).toBe('Open shell without authentication'); + expect(children[1].commandId).toBe('vscode-documentdb.command.internal.shell.openWithoutAuthentication'); expect(children[1].commandArgs).toEqual([item]); // The branch data provider detects (and caches) the error state via hasRetryNode(). @@ -216,7 +258,10 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => 'cluster-1/open-shell', 'cluster-1/retry', ]); - expect(children[1]).toMatchObject({ commandId: ShellCommandIds.open, commandArgs: [item] }); + expect(children[1]).toMatchObject({ + commandId: 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', + commandArgs: [item], + }); }); it.each(['authentication', 'listDatabases'] as const)( @@ -348,7 +393,7 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => it('does not reopen the dashboard on refresh or when the tree node is recreated', async () => { mockGetSetting.mockReturnValue(true); const client = makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])); - ClustersClientMock.getClient.mockResolvedValue(client); + ClustersClientMock.connectInteractive.mockResolvedValue(client); const item = new TestClusterItem(makeCluster(), client); await item.getChildren(); @@ -365,7 +410,7 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => mockGetSetting.mockReturnValue(true); mockHasCredentials.mockReturnValue(true); const client = makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])); - ClustersClientMock.getClient.mockResolvedValue(client); + ClustersClientMock.connectInteractive.mockResolvedValue(client); ClustersClientMock.exists.mockReturnValueOnce(true).mockReturnValueOnce(false); const item = new TestClusterItem(makeCluster(), client); @@ -424,7 +469,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl mockHasCredentials.mockReturnValue(true); // jest-mock-vscode's withProgress is a no-op vi.fn(); make it actually run the task so - // getClientWithProgress() exercises ClustersClient.getClient() and surfaces its rejection. + // getClientWithProgress() exercises ClustersClient.connectInteractive() and surfaces its rejection. (vscode.window.withProgress as unknown as Mock).mockImplementation( ( _options: unknown, @@ -436,8 +481,216 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); + it('shows only Connect while user-disconnected and uses cached settings on the same node after the click', async () => { + const node = new TestClusterItem({ ...makeCluster(), treeId: 'connectionsView/folder/cluster-1' }, null); + const context = {} as IActionContext; + const stableId = node.cluster.clusterId; + const treeId = node.id; + ClustersClientMock.exists.mockReturnValue(true); + expect(node.getTreeItem().contextValue?.split(';')).toContain('connected'); + ClustersClientMock.exists.mockReturnValue(false); + ClustersClientMock.getLatchReason.mockReturnValue('userDisconnected'); + + try { + expect(await node.getChildren()).toEqual([ + expect.objectContaining({ label: 'Reconnect', id: `${treeId}/connect`, commandArgs: [node] }), + ]); + expect(node.getTreeItem().contextValue?.split(';')).not.toContain('connected'); + expect(mockHasCredentials).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + + connectDisconnected(context, node); + expect(ClustersClientMock.unlatch).toHaveBeenCalledExactlyOnceWith(stableId); + expect(notifyChildrenChanged).toHaveBeenCalledExactlyOnceWith(treeId); + + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + ClustersClientMock.connectInteractive.mockResolvedValueOnce( + makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])), + ); + expect(await node.getChildren()).toEqual([expect.objectContaining({ id: 'database' })]); + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledExactlyOnceWith( + stableId, + expect.any(AbortSignal), + expect.any(Function), + 'treeConnect', + ); + expect(node.getTreeItem().id).toBe(treeId); + + ClustersClientMock.getLatchReason.mockReturnValue('connectionRemoved'); + connectDisconnected(context, node); + expect(ClustersClientMock.unlatch).toHaveBeenCalledOnce(); + } finally { + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + } + }); + + it('clears and refreshes only the owning discovery provider after Disconnect', async () => { + const node = new TestClusterItem({ ...makeCluster(), treeId: 'discoveryView/custom-source/cluster-1' }, null); + const context = { telemetry: { suppressAll: false } } as IActionContext; + ClustersClientMock.exists.mockReturnValue(true); + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + + await disconnect(context, node); + + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + node.cluster.clusterId, + 'userDisconnected', + expect.any(Function), + ); + const refreshTree = vi.mocked(teardownConnection).mock.calls[0][2]; + refreshTree(); + + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + + it.each(['signInRequired', 'credentialsRejected'] as const)( + 'offers Retry sign-in instead of Retry for %s and keeps the failed-expansion marker', + async (reason): Promise => { + if (reason === 'credentialsRejected') { + ClustersClientMock.getLatchReason.mockReturnValueOnce(reason); + } + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError(reason)); + vi.mocked(CredentialCache.getCredentials).mockReturnValue({ + clusterId: 'cluster-1', + connectionString: 'mongodb://example.test', + authMechanism: AuthMethodId.MicrosoftEntraID, + }); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValue({ + kind: 'entra', + providerId: 'microsoft', + accountLabel: 'test', + accountId: 'id', + }); + const item = new TestClusterItem(makeCluster(), null); + + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual([ + 'cluster-1/sign-in-again', + 'cluster-1/diagnose', + 'cluster-1/open-shell', + ]); + expect(children[0]).toMatchObject({ label: 'Retry sign-in' }); + if (reason === 'credentialsRejected') { + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Retry sign-in to continue.', + }); + } + expect(item.hasRetryNode(children)).toBe(true); + expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + vi.mocked(CredentialCache.getCredentials).mockReset(); + ClustersClientMock.getLastVerifiedIdentity.mockReset(); + }, + ); + + it('does not publish a database listing from a different identity', async (): Promise => { + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { + ...makeClient(vi.fn().mockResolvedValue([{ name: 'old-database' }])), + binding, + } as ClustersClient; + const replacement = { ...client, fingerprint: 'new' } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.getExistingClient.mockReturnValueOnce(replacement); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it.each(['diagnose', 'sign-in-again'])( + 'does not mistake a database named %s for a recovery action', + (name): void => { + const item = new TestClusterItem(makeCluster(), null); + const child = { + id: `cluster-1/${name}`, + contextValue: 'treeItem_documentdbdatabase', + getTreeItem: (): vscode.TreeItem => ({ label: name }), + }; + + expect(item.hasRetryNode([child])).toBe(false); + }, + ); + + it('keeps actionable recovery children without an inert Retry for stored credentials', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); + try { + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual(['cluster-1/diagnose', 'cluster-1/open-shell']); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Update credentials to continue.', + }); + expect(item.hasRetryNode(children)).toBe(true); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + + it('keeps Retry for a synthetic Connections view item without a credential editor', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); + item.contextValue = 'treeItem_quickStartInstance'; + try { + expect((await item.getChildren()).map(({ id }) => id)).toEqual([ + 'cluster-1/diagnose', + 'cluster-1/open-shell', + 'cluster-1/retry', + ]); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Retry to reload them.', + }); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + + it('explains how to reload a rejected Azure key', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.AzureResourcesView }, null); + item.readReplacementKey = vi.fn(); + try { + await item.getChildren(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the key. Choose Retry to read the key from Azure again.', + }); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { + const error = new Error('deprecated generation'); + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { ...makeClient(vi.fn().mockRejectedValue(error)), binding } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.reportFailure.mockReturnValueOnce(undefined); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(ClustersClientMock.reportFailure).toHaveBeenCalledExactlyOnceWith(binding, error); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + it('returns a retry node when reusing the cached client fails (without listing databases)', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); // listDatabases must never be reached when the cached client cannot connect. const listDatabases = vi.fn(); @@ -456,7 +709,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('uses the trusted-server modal and preserves action-only recovery for a cached rejection', async (): Promise => { - ClustersClientMock.getClient.mockRejectedValue( + ClustersClientMock.connectInteractive.mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'other.example.com:27017', hostCount: 2 }), ); const cluster = makeCluster(); @@ -465,7 +718,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl const children = await item.getChildren(); - expect(ClustersClientMock.getClient).toHaveBeenCalledWith( + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledWith( 'cluster-1', expect.anything(), expect.any(Function), @@ -492,19 +745,19 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ]); expect(children.map((child) => (child as TreeElement & { commandId: string }).commandId)).toEqual([ 'vscode-documentdb.command.diagnoseConnection', - 'vscode-documentdb.command.shell.open', + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', 'vscode-documentdb.command.internal.retry', ]); }); it('clears the destination rejection reason after a successful cached retry', async (): Promise => { const item = new TestClusterItem(makeCluster(), null); - ClustersClientMock.getClient.mockRejectedValueOnce( + ClustersClientMock.connectInteractive.mockRejectedValueOnce( new EntraDestinationRejectedError({ firstHost: 'other.example.com', hostCount: 1 }), ); await item.getChildren(); expect(item.lastConnectionFailureReason).toBe('entraDestinationRejected'); - ClustersClientMock.getClient.mockResolvedValueOnce(makeClient(vi.fn().mockResolvedValue([]))); + ClustersClientMock.connectInteractive.mockResolvedValueOnce(makeClient(vi.fn().mockResolvedValue([]))); await item.getChildren(); @@ -513,7 +766,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('surfaces a modal and records telemetry with failurePhase=cachedClientConnect', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); const item = new TestClusterItem(makeCluster(), makeClient(vi.fn())); @@ -536,7 +789,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('returns an empty array (no retry node) when the user cancels the cached connection', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new UserCancelledError()); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new UserCancelledError()); const item = new TestClusterItem(makeCluster(), makeClient(vi.fn())); @@ -601,7 +854,7 @@ describe('ClusterItemBase.connect', () => { mockTelemetryEvents.length = 0; // jest-mock-vscode's withProgress is a no-op vi.fn(); make it run the task so the - // cached path actually reaches ClustersClient.getClient(). + // cached path actually reaches ClustersClient.connectInteractive(). (vscode.window.withProgress as unknown as Mock).mockImplementation( ( _options: unknown, @@ -619,7 +872,7 @@ describe('ClusterItemBase.connect', () => { const item = new ConnectTestClusterItem(makeCluster(), null); item.lastConnectionOutcome = 'canceled'; item.lastConnectionCorrelationId = 'previous-attempt'; - ClustersClientMock.getClient.mockImplementationOnce( + ClustersClientMock.connectInteractive.mockImplementationOnce( async (_clusterId, _signal, onAttempt): Promise => { expect(item.lastConnectionOutcome).toBeUndefined(); expect(item.lastConnectionCorrelationId).toBeUndefined(); @@ -640,7 +893,7 @@ describe('ClusterItemBase.connect', () => { it('keys the credential cache and the client on clusterId, never on the tree position', async () => { mockHasCredentials.mockReturnValue(true); const cached = makeClient(vi.fn()); - (ClustersClientMock.getClient as Mock).mockResolvedValue(cached); + (ClustersClientMock.connectInteractive as Mock).mockResolvedValue(cached); const cluster = makeMovedCluster(); const item = new ConnectTestClusterItem(cluster, null); @@ -651,7 +904,7 @@ describe('ClusterItemBase.connect', () => { // Keying either lookup on the tree position opens a second, duplicate connection. expect(mockHasCredentials).toHaveBeenCalledWith(cluster.clusterId); expect(mockHasCredentials).not.toHaveBeenCalledWith(cluster.treeId); - expect(ClustersClientMock.getClient).toHaveBeenCalledWith( + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledWith( cluster.clusterId, expect.anything(), expect.any(Function), @@ -667,12 +920,12 @@ describe('ClusterItemBase.connect', () => { await expect(item.connect()).resolves.toBe(fresh); expect(item.authenticateCalls).toBe(1); expect(item.beforeCachedCalls).toBe(0); - expect(ClustersClientMock.getClient).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); }); it('returns null when the user cancels the progress notification on the cached path', async () => { mockHasCredentials.mockReturnValue(true); - (ClustersClientMock.getClient as Mock).mockRejectedValue(new UserCancelledError()); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new UserCancelledError()); const item = new ConnectTestClusterItem(makeCluster(), null); @@ -684,7 +937,7 @@ describe('ClusterItemBase.connect', () => { it('propagates a genuine failure on the cached path so the command can report it', async () => { mockHasCredentials.mockReturnValue(true); - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); const item = new ConnectTestClusterItem(makeCluster(), null); @@ -694,7 +947,7 @@ describe('ClusterItemBase.connect', () => { it('reports a cached destination rejection through the same modal without reauthenticating', async (): Promise => { mockHasCredentials.mockReturnValue(true); - ClustersClientMock.getClient.mockRejectedValue( + ClustersClientMock.connectInteractive.mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'other.example.com', hostCount: 1 }), ); const item = new ConnectTestClusterItem(makeMovedCluster(), null); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index c743a61bb..8a458e698 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -4,35 +4,41 @@ *--------------------------------------------------------------------------------------------*/ import { - UserCancelledError, callWithTelemetryAndErrorHandling, createContextValue, createGenericElement, + UserCancelledError, type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { type IconPath } from 'vscode'; import { type Experience } from '../../DocumentDBExperiences'; -import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { + addEstablishedConnectionContext, + ClustersClient, + type DatabaseItemModel, +} from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { type EntraIdAuthConfig, type ManagedIdentityAuthConfig, type NativeAuthConfig, } from '../../documentdb/auth/AuthConfig'; -import { type AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; -import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; import { ErrorExplanationService } from '../../services/errorExplanationService'; +import { isQuickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; import { settingsKeys } from '../../settingsKeys'; import { regionToDisplayName } from '../../utils/regionToDisplayName'; import { withDelayedProgress } from '../../utils/withProgress'; import { type TreeElement } from '../TreeElement'; -import { type TreeElementWithContextValue } from '../TreeElementWithContextValue'; +import { isTreeElementWithContextValue, type TreeElementWithContextValue } from '../TreeElementWithContextValue'; import { type TreeElementWithExperience } from '../TreeElementWithExperience'; import { type TreeElementWithRetryChildren } from '../TreeElementWithRetryChildren'; import { createGenericElementWithContext } from '../api/createGenericElementWithContext'; @@ -103,6 +109,7 @@ export abstract class ClusterItemBase { context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + addEstablishedConnectionContext(context.telemetry, this.cluster.clusterId); context.telemetry.properties.connectionResult = 'failed'; context.telemetry.properties.experience = this.experience.api; context.telemetry.properties.failurePhase = 'cachedClientConnect'; @@ -208,6 +222,10 @@ export abstract class ClusterItemBase; + public async getUnauthenticatedEndpoint(): Promise { + return this.cluster.connectionString; + } + /** * Reads the connection details for connection diagnostics: no UI, no tunnels, typed * failures (see `diagnosticCredentialRead.ts`). `undefined` means the connection no longer exists. @@ -222,7 +240,7 @@ export abstract class ClusterItemBase { + protected async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const abortController = new AbortController(); - const clientPromise = ClustersClient.getClient( + const clientPromise = ClustersClient.connectInteractive( clusterId, abortController.signal, (id) => { this.lastConnectionCorrelationId = id; + if (onReuse) { + const client = ClustersClient.getExistingClient(clusterId); + onReuse(client?.connectionCorrelationId === id ? client : undefined); + } }, 'treeConnect', ); @@ -285,24 +310,119 @@ export abstract class ClusterItemBase { + const { clusterId } = this.cluster; + const failure = this.classifyTreeFailure(error); + context.telemetry.properties.connectionFailureKind = failure.kind; + addEstablishedConnectionContext(context.telemetry, clusterId); + if (ClustersClient.getEpoch(clusterId) !== epoch || failure.note === 'cancelled') { + return; + } + this.lastConnectionFailureKind = failure.kind; + if (ClustersClient.getLatchReason(clusterId)) { + return; + } + const retainedEntraSettings = failure.kind === 'credentialsRejected' && this.canSignInAgain(); + if (failure.kind === 'other' || (failure.kind === 'credentialsRejected' && !retainedEntraSettings)) { + CredentialCache.deleteCredentials(clusterId); + } + if (retainedEntraSettings || (failure.kind === 'credentialsRejected' && this.readReplacementKey)) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + await ClustersClient.deleteClient(clusterId); + } + + /** Only the two Azure RU item types can replace a rejected database key from ARM. */ + public readReplacementKey?(context: IActionContext): Promise; + + public canRetryRejectedCredentials(): boolean { + const { clusterId, viewId } = this.cluster; + if (viewId === String(Views.ConnectionsView)) { + return isQuickStartClusterId(clusterId); + } + if (viewId !== String(Views.DiscoveryView) && viewId !== String(Views.AzureResourcesView)) { + return false; + } + const credentials = CredentialCache.getCredentials(clusterId); + return ( + credentials !== undefined && + (credentials.authMechanism ?? AuthMethodId.NativeAuth) === AuthMethodId.NativeAuth + ); + } + + private classifyTreeFailure(error: unknown): ConnectionFailure { + const method = CredentialCache.getCredentials(this.cluster.clusterId)?.authMechanism ?? AuthMethodId.NativeAuth; + return classifyConnectionFailure(error, method); + } + + private canSignInAgain(): boolean { + const { clusterId } = this.cluster; + const credentials = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + return ( + credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && + identity?.kind === 'entra' && + identity.tenantId === credentials.entraIdConfig?.tenantId + ); + } + + private hasStoredCredentialEditor(): boolean { + return ( + this.cluster.viewId === String(Views.ConnectionsView) && + this.contextValue.split(';').includes(CLUSTER_ITEM_CONTEXT_VALUE) + ); + } + + private describeCredentialRejection(): string { + if (this.canSignInAgain()) { + return vscode.l10n.t('The database rejected the credentials. Choose Retry sign-in to continue.'); + } + if (this.readReplacementKey) { + return vscode.l10n.t('The database rejected the key. Choose Retry to read the key from Azure again.'); + } + if (this.hasStoredCredentialEditor()) { + return vscode.l10n.t('The database rejected the credentials. Choose Update credentials to continue.'); + } + return vscode.l10n.t('The database rejected the credentials. Choose Retry to reload them.'); + } + /** * Builds the FAILURE-TYPE error-recovery nodes owned by the element layer. * - * Always includes the canonical "retry" node (see {@link createRetryNode}), a diagnosis - * action that opens diagnostics without connecting, and an "open shell" node. `hasRetryNode` - * and the provider detect the error state via the retry node. The shell is offered for every + * Includes diagnosis and "open shell", plus any applicable Retry action. `hasRetryNode` + * lets the provider detect the error state even without Retry. The shell is offered for every * failure, including sign-in failures, so experts can investigate with the shell's own * connection and error output. View-specific recovery actions (e.g. "update credentials") are * added separately by the provider via `errorRecoveryActions`. * * Error-recovery nodes in this tree are produced by two layers: - * - The ELEMENT layer (this class) owns FAILURE-TYPE nodes: "retry", "diagnose" and + * - The ELEMENT layer (this class) owns FAILURE-TYPE nodes: "sign in again" or "retry", "diagnose" and * "open shell", for any failure. * - The PROVIDER layer (a BranchDataProvider) owns VIEW-SPECIFIC nodes (e.g. "update * credentials") via `errorRecoveryActions`, gated by the failing element's contextValue. */ private createErrorRecoveryChildren(): TreeElement[] { + const needsSignIn = + (this.lastConnectionFailureKind === 'signInRequired' || + this.lastConnectionFailureKind === 'credentialsRejected') && + this.canSignInAgain(); + const rejectedStoredCredentials = + this.hasStoredCredentialEditor() && + ClustersClient.getLatchReason(this.cluster.clusterId) === 'credentialsRejected'; return [ + ...(needsSignIn + ? [ + createGenericElementWithContext({ + contextValue: 'error', + id: `${this.id}/sign-in-again`, + label: vscode.l10n.t('Retry sign-in'), + iconPath: new vscode.ThemeIcon('sign-in'), + commandId: 'vscode-documentdb.command.signInAgain', + commandArgs: [this], + }), + ] + : []), createGenericElementWithContext({ contextValue: 'error', id: `${this.id}/diagnose`, @@ -314,15 +434,104 @@ export abstract class ClusterItemBase { + const { clusterId, name } = this.cluster; + const failure = failedClient + ? classifyConnectionFailure(error, failedClient.authMethod) + : this.classifyTreeFailure(error); + const destinationRejected = isEntraDestinationRejectedError(error); + let children: TreeElement[] = []; + const telemetry = callWithTelemetryAndErrorHandling('connect', async (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + context.telemetry.properties.connectionResult = failure.note === 'cancelled' ? 'cancelled' : 'failed'; + context.telemetry.properties.source = 'treeExpansion'; + context.telemetry.properties.experience = this.experience.api; + context.telemetry.properties.failurePhase = phase; + if (failedClient?.binding) { + addEstablishedConnectionContext(context.telemetry, failedClient); + const kind = ClustersClient.reportFailure(failedClient.binding, error); + if (!kind && failure.note !== 'cancelled') { + return; + } + this.lastConnectionFailureKind = kind; + } else { + if ( + acquisitionEpoch !== undefined && + ClustersClient.getEpoch(clusterId) !== acquisitionEpoch && + failure.note !== 'cancelled' && + failure.note !== 'alreadyUnavailable' + ) { + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + this.lastConnectionFailureKind = failure.kind; + if (this.lastConnectionCorrelationId) { + context.telemetry.properties.connectionCorrelationId = this.lastConnectionCorrelationId; + } + // A failed replacement startup has no published generation of its own. + if ( + failure.kind === 'credentialsRejected' && + !failure.note && + (this.canSignInAgain() || this.readReplacementKey) && + !ClustersClient.getLatchReason(clusterId) + ) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + } + context.telemetry.properties.connectionFailureKind = failure.kind; + if (failure.note === 'cancelled') { + this.lastConnectionOutcome = 'canceled'; + throw error; + } + this.lastConnectionOutcome = 'failed'; + this.lastConnectionFailureReason = destinationRejected ? 'entraDestinationRejected' : undefined; + children = this.createErrorRecoveryChildren(); + if (destinationRejected) { + await showClusterConnectFailure({ clusterId, clusterName: name, error, context }); + } else { + const renderingEpoch = ClustersClient.getEpoch(clusterId); + const explanation = await ErrorExplanationService.explain({ clusterId, error }); + if (ClustersClient.getEpoch(clusterId) !== renderingEpoch) { + children = []; + return; + } + context.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; + const heading = + explanation?.message ?? + (phase === 'listDatabases' + ? vscode.l10n.t('Failed to load databases for "{0}"', name) + : vscode.l10n.t('Failed to connect to "{0}"', name)); + let detail = error instanceof Error ? error.message : String(error); + if (failure.note === 'alreadyUnavailable') { + if (failure.kind === 'signInRequired') { + detail = vscode.l10n.t('Sign in again to continue using this connection.'); + } else if (failure.kind === 'credentialsRejected') { + detail = this.describeCredentialRejection(); + } + } + void vscode.window.showErrorMessage(heading, { modal: true, detail }); + } + throw error; + }); + await telemetry; + return children; + } + /** * Authenticates and connects to the cluster to list all available databases. * Here, the MongoDB client is created and cached for future use. @@ -337,111 +546,52 @@ export abstract class ClusterItemBase { + const clusterId = this.cluster.clusterId; + const disconnected = (): boolean => ClustersClient.getLatchReason(clusterId) === 'userDisconnected'; + if (disconnected()) { + return this.createDisconnectedChildren(); + } ext.outputChannel.appendLine(l10n.t('Loading cluster details for "{cluster}"', { cluster: this.cluster.name })); const wasConnected = ClustersClient.exists(this.cluster.clusterId); this.lastConnectionOutcome = undefined; this.lastConnectionFailureReason = undefined; + this.lastConnectionFailureKind = undefined; this.lastConnectionCorrelationId = undefined; let clustersClient: ClustersClient | null; // Check if credentials are cached, and return the cached client if available // Use clusterId for cache lookups - stable across folder moves - if (CredentialCache.hasCredentials(this.cluster.clusterId)) { + if (CredentialCache.hasCredentials(clusterId) || ClustersClient.getLatchReason(clusterId)) { ext.outputChannel.appendLine( l10n.t('Reusing active connection for "{cluster}".', { cluster: this.cluster.name, }), ); + let reusedClient: ClustersClient | undefined; + let acquisitionEpoch = ClustersClient.getEpoch(clusterId); try { - await this.beforeCachedClientConnect(); - clustersClient = await this.getClientWithProgress(this.cluster.clusterId); - } catch (error) { - if (error instanceof UserCancelledError) { - this.lastConnectionOutcome = 'canceled'; - ext.outputChannel.appendLine( - l10n.t('Connection to "{cluster}" was cancelled.', { cluster: this.cluster.name }), - ); - - void callWithTelemetryAndErrorHandling('connect', (context) => { - context.telemetry.properties.connectionResult = 'cancelled'; - context.telemetry.properties.source = 'treeExpansion'; - context.telemetry.properties.experience = this.experience.api; - throw error; - }); - - return []; + if (!ClustersClient.getLatchReason(clusterId)) { + await this.beforeCachedClientConnect(); } - - // Reusing a cached client can still fail (server down, stale credentials, dropped - // tunnel, TLS/auth renegotiation, …). If we let the rejection propagate out of - // getChildren(), the tree expansion would end with no children and — crucially — - // no retry affordance, leaving the user stuck. Mirror the `!clustersClient` and - // listDatabases branches: record telemetry, surface a modal, and return a retry - // node. We intentionally keep the cached credentials so the retry can re-attempt - // the connection without forcing the user to re-enter credentials (the failure may - // be transient). - const errorMessage = error instanceof Error ? error.message : String(error); - const entraRejected = isEntraDestinationRejectedError(error); - const explanation = entraRejected - ? undefined - : await ErrorExplanationService.explain({ - clusterId: this.cluster.clusterId, - error, - }); - - const telemetryPromise = callWithTelemetryAndErrorHandling('connect', async (telemetryContext) => { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'cachedClientConnect'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection being reused, so the failure joins its destination. - const reusedConnectionId = ClustersClient.getExistingClient( - this.cluster.clusterId, - )?.connectionCorrelationId; - if (reusedConnectionId) { - telemetryContext.telemetry.properties.connectionCorrelationId = reusedConnectionId; - } - if (entraRejected) { - await showClusterConnectFailure({ - clusterId: this.cluster.clusterId, - clusterName: this.cluster.name, - error, - context: telemetryContext, - }); - } - throw error; + acquisitionEpoch = ClustersClient.getEpoch(clusterId); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { + reusedClient = client; }); - if (entraRejected) { - await telemetryPromise; - } - - ext.outputChannel.appendLine( - l10n.t('Failed to reuse the active connection for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - if (!entraRejected) { - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to connect to "{0}"', this.cluster.name), - { - modal: true, - detail: errorMessage, - }, - ); + } catch (error) { + if (disconnected()) { + return this.createDisconnectedChildren(); } - - return this.createErrorRecoveryChildren(); + return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } } else { // Call to the abstract method to authenticate and connect to the cluster clustersClient = await this.authenticateAndConnect(); } + if (disconnected()) { + return this.createDisconnectedChildren(); + } // If authentication failed or cancelled, return the error element if (!clustersClient) { this.lastConnectionOutcome ??= 'failed'; @@ -463,45 +613,17 @@ export abstract class ClusterItemBase { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'listDatabases'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection that worked but was refused the listing, so the failure joins its destination. - if (connectedClient.connectionCorrelationId) { - telemetryContext.telemetry.properties.connectionCorrelationId = - connectedClient.connectionCorrelationId; - } - throw error; - }); - - ext.outputChannel.appendLine( - l10n.t('Failed to list databases for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to load databases for "{0}"', this.cluster.name), - { modal: true, detail: errorMessage }, - ); - - return this.createErrorRecoveryChildren(); + if (disconnected()) { + return this.createDisconnectedChildren(); + } + return this.renderExpansionFailure(error, 'listDatabases', connectedClient); + } + const binding = connectedClient.binding; + const isCurrentIdentity = (): boolean => + !ClustersClient.getLatchReason(clusterId) && + (!binding || ClustersClient.getExistingClient(clusterId)?.fingerprint === binding.fingerprint); + if (!isCurrentIdentity()) { + return disconnected() ? this.createDisconnectedChildren() : []; } // A deep link that opens the dashboard itself suppresses the automatic open; that is not a skip. @@ -510,6 +632,9 @@ export abstract class ClusterItemBase + child.id === `${this.id}/diagnose` && + isTreeElementWithContextValue(child) && + child.contextValue === 'error', + ) === true + ); } /** @@ -569,7 +724,7 @@ export abstract class ClusterItemBase ({ @@ -90,6 +91,25 @@ describe('CollectionItem', () => { expect(children[1].id).toBe('connectionsView/cluster-1/db1/coll1/indexes'); }); + it('loads the count in the background using the stable cluster ID', async () => { + const estimateDocumentCount = vi.fn().mockResolvedValue(0); + vi.mocked(ClustersClient.getClient) + .mockClear() + .mockResolvedValueOnce({ estimateDocumentCount } as unknown as ClustersClient); + const item = new CollectionItem(cluster as never, databaseInfo as never, collectionInfo as never); + + item.loadDocumentCount(); + + await vi.waitFor(() => expect(estimateDocumentCount).toHaveBeenCalledExactlyOnceWith('db1', 'coll1')); + expect(ClustersClient.getClient).toHaveBeenCalledExactlyOnceWith( + 'cluster-1', + undefined, + undefined, + 'treeChildren', + { background: true }, + ); + }); + it('keeps shard key fields with backticks inside their code span', () => { const item = new CollectionItem( cluster as never, diff --git a/src/tree/documentdb/CollectionItem.ts b/src/tree/documentdb/CollectionItem.ts index d7f957124..39d9bf006 100644 --- a/src/tree/documentdb/CollectionItem.ts +++ b/src/tree/documentdb/CollectionItem.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient, type CollectionItemModel, type DatabaseItemModel } from '../../documentdb/ClustersClient'; import { type Experience } from '../../DocumentDBExperiences'; import { ext } from '../../extensionVariables'; +import { meterSilentCatch } from '../../utils/accumulatingTelemetry'; import { createConcurrencyLimiter, type LimitedRunner } from '../../utils/concurrencyLimiter'; import { getCountPrefix } from '../../utils/countPrefix'; import { formatDocumentCount } from '../../utils/formatDocumentCount'; @@ -132,10 +133,13 @@ export class CollectionItem implements TreeElement, TreeElementWithExperience, T if (!isCurrent()) { return null; } - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren'); + const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + }); return client.estimateDocumentCount(dbName, collName); }); } catch { + meterSilentCatch('CollectionItem_documentCount'); // On error, fall through and let the post-await stale-check decide // whether to record the failure on this instance. result = null; diff --git a/src/tree/documentdb/DatabaseItem.test.ts b/src/tree/documentdb/DatabaseItem.test.ts index 6c40addd4..b57d029a6 100644 --- a/src/tree/documentdb/DatabaseItem.test.ts +++ b/src/tree/documentdb/DatabaseItem.test.ts @@ -35,6 +35,7 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getClient: vi.fn(), + reportFailure: vi.fn(), }, })); @@ -65,12 +66,25 @@ describe('DatabaseItem - async collection count loading', () => { estimateDocumentCountMock = vi.fn().mockResolvedValue(0); (ClustersClient.getClient as Mock).mockResolvedValue({ + binding: { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, listCollections: listCollectionsMock, countCollections: countCollectionsMock, estimateDocumentCount: estimateDocumentCountMock, }); }); + it('reports the failed list against its own binding and preserves the error', async (): Promise => { + const error = new Error('List collections failed'); + listCollectionsMock.mockRejectedValueOnce(error); + + await expect(new DatabaseItem(cluster, databaseInfo).getChildren()).rejects.toBe(error); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith( + { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, + error, + ); + expect(listCollectionsMock).toHaveBeenCalledOnce(); + }); + function flushAsync(): Promise { return new Promise((resolve) => setImmediate(resolve)); } @@ -81,6 +95,13 @@ describe('DatabaseItem - async collection count loading', () => { item.loadCollectionCount(); await flushAsync(); + expect(ClustersClient.getClient).toHaveBeenCalledExactlyOnceWith( + cluster.clusterId, + undefined, + undefined, + 'treeChildren', + { background: true }, + ); expect(countCollectionsMock).toHaveBeenCalledWith('testdb', COLLECTION_COUNT_LIMIT); expect(listCollectionsMock).not.toHaveBeenCalled(); expect(notifyChildrenChangedMock).toHaveBeenCalledWith(item.id); @@ -124,6 +145,13 @@ describe('DatabaseItem - async collection count loading', () => { // Now expand the node, which fetches the full list const children = await item.getChildren(); + expect(ClustersClient.getClient).toHaveBeenNthCalledWith( + 2, + cluster.clusterId, + undefined, + undefined, + 'treeChildren', + ); expect(listCollectionsMock).toHaveBeenCalledTimes(1); expect(children).toHaveLength(3); // Description now shows exact count, no "+" diff --git a/src/tree/documentdb/DatabaseItem.ts b/src/tree/documentdb/DatabaseItem.ts index 1c9536726..90f33a7c3 100644 --- a/src/tree/documentdb/DatabaseItem.ts +++ b/src/tree/documentdb/DatabaseItem.ts @@ -76,7 +76,10 @@ export class DatabaseItem implements TreeElement, TreeElementWithExperience, Tre undefined, 'treeChildren', ); - const collections = await client.listCollections(this.databaseInfo.name); + const collections = await client.listCollections(this.databaseInfo.name).catch((error: unknown) => { + ClustersClient.reportFailure(client.binding, error); + throw error; + }); // Update the collection count from the full list we just fetched. This // is the exact value, so mark it authoritative: a still-running @@ -136,7 +139,15 @@ export class DatabaseItem implements TreeElement, TreeElementWithExperience, Tre private async fetchAndUpdateCount(): Promise { try { - const client = await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren'); + const client = await ClustersClient.getClient( + this.cluster.clusterId, + undefined, + undefined, + 'treeChildren', + { + background: true, + }, + ); const { count, hasMore } = await client.countCollections(this.databaseInfo.name, COLLECTION_COUNT_LIMIT); // `getChildren()` may have run while this request was in flight and // established the exact count. Never replace an exact count with diff --git a/src/tree/documentdb/IndexesItem.test.ts b/src/tree/documentdb/IndexesItem.test.ts index 10975db16..51dc55fa2 100644 --- a/src/tree/documentdb/IndexesItem.test.ts +++ b/src/tree/documentdb/IndexesItem.test.ts @@ -35,6 +35,7 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getClient: vi.fn(), + reportFailure: vi.fn(), }, getIndexExclusionReason: vi.fn(() => undefined), })); @@ -98,7 +99,7 @@ describe('compareIndexNames', () => { describe('IndexesItem - async index loading', () => { const cluster = { - treeId: 'cluster1', + treeId: 'folder/cluster1', clusterId: 'cluster1', dbExperience: { api: 'MongoDB' } as unknown as Experience, } as TreeCluster; @@ -122,11 +123,28 @@ describe('IndexesItem - async index loading', () => { listSearchIndexesMock = vi.fn().mockRejectedValue(new Error('not supported')); (ClustersClient.getClient as Mock).mockResolvedValue({ + binding: { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, listIndexes: listIndexesMock, listSearchIndexesForAtlas: listSearchIndexesMock, }); }); + it('reports only foreground index failures and preserves the original error', async (): Promise => { + const error = new Error('List indexes failed'); + listIndexesMock.mockRejectedValue(error); + const item = new IndexesItem(cluster, databaseInfo, collectionInfo); + item.loadIndexCount(); + await flushAsync(); + expect(ClustersClient.reportFailure).not.toHaveBeenCalled(); + + await expect(item.getChildren()).rejects.toBe(error); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith( + { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, + error, + ); + expect(listIndexesMock).toHaveBeenCalledTimes(2); + }); + function flushAsync(): Promise { return new Promise((resolve) => setImmediate(resolve)); } @@ -144,6 +162,9 @@ describe('IndexesItem - async index loading', () => { item.loadIndexCount(); await flushAsync(); + expect(ClustersClient.getClient).toHaveBeenCalledWith(cluster.clusterId, undefined, undefined, 'treeChildren', { + background: true, + }); expect(listIndexesMock).toHaveBeenCalledTimes(1); expect(notifyChildrenChangedMock).toHaveBeenCalledWith(item.id); expect(item.getTreeItem().description).toContain('3'); @@ -165,6 +186,7 @@ describe('IndexesItem - async index loading', () => { const children = await item.getChildren(); + expect(ClustersClient.getClient).toHaveBeenCalledWith(cluster.clusterId, undefined, undefined, 'treeChildren'); expect(listIndexesMock).toHaveBeenCalledTimes(1); expect(children).toHaveLength(3); expect(item.getTreeItem().description).toContain('3'); diff --git a/src/tree/documentdb/IndexesItem.ts b/src/tree/documentdb/IndexesItem.ts index 651178323..0bf40b9f2 100644 --- a/src/tree/documentdb/IndexesItem.ts +++ b/src/tree/documentdb/IndexesItem.ts @@ -98,7 +98,7 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree private async fetchAndUpdateCount(): Promise { try { - const indexes = await this.fetchIndexes(); + const indexes = await this.fetchIndexes({ background: true }); this.indexCount = indexes.length; } catch { meterSilentCatch('IndexesItem_loadIndexCount'); @@ -111,14 +111,18 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree } } - private async fetchIndexes(): Promise { - const client: ClustersClient = await ClustersClient.getClient( - this.cluster.clusterId, - undefined, - undefined, - 'treeChildren', - ); - const indexes = await client.listIndexes(this.databaseInfo.name, this.collectionInfo.name); + private async fetchIndexes(options?: { readonly background?: boolean }): Promise { + const client: ClustersClient = options + ? await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren', options) + : await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren'); + const indexes = await client + .listIndexes(this.databaseInfo.name, this.collectionInfo.name) + .catch((error: unknown) => { + if (!options?.background) { + ClustersClient.reportFailure(client.binding, error); + } + throw error; + }); // Try to get search indexes, but silently fail if not supported by the platform try { @@ -128,6 +132,7 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree ); indexes.push(...searchIndexes); } catch { + meterSilentCatch('IndexesItem_searchIndexes'); // Search indexes not supported on this platform, continue without them } diff --git a/src/utils/azureClients.test.ts b/src/utils/azureClients.test.ts new file mode 100644 index 000000000..b5566190f --- /dev/null +++ b/src/utils/azureClients.test.ts @@ -0,0 +1,167 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createHttpHeaders } from '@azure/core-rest-pipeline'; +import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; +import { registerAzureUtilsExtensionVariables } from '@microsoft/vscode-azext-azureutils'; +import { TestOutputChannel, TestUserInput } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; + +import { AzureSubscriptionProviderWithFilters } from '../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; +import { createResourceManagementClient } from './azureClients'; + +import { type HttpClient, type PipelineResponse } from '@azure/core-rest-pipeline'; +import { type AzureSubscription, type TenantIdAndAccount } from '@microsoft/vscode-azext-azureauth'; +import { type IActionContext } from '@microsoft/vscode-azext-utils'; + +const { getSession, getAccounts } = vi.hoisted(() => { + // Keep the real Azure utilities' extension registration from sending telemetry. + vi.stubEnv('DEBUGTELEMETRY', 'true'); + return { + getSession: + vi.fn< + ( + providerId: string, + scopes: readonly string[] | vscode.AuthenticationWwwAuthenticateRequest, + options?: vscode.AuthenticationGetSessionOptions, + ) => Promise + >(), + getAccounts: vi.fn(async (): Promise => []), + }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal }>(); + const authentication = { + getSession, + getAccounts, + onDidChangeSessions: vi.fn(() => ({ dispose: vi.fn() })), + }; + // Share the fixture with both Vite's ESM alias and the setup hook for CommonJS require('vscode'). + actual.default.authentication = authentication; + return { ...actual, authentication }; +}); + +class TestSubscriptionProvider extends AzureSubscriptionProviderWithFilters { + public getSubscriptionAuth(tenant: TenantIdAndAccount): Pick { + return this.getSubscriptionContext(tenant); + } +} + +function idToken(expiry: number): string { + // azureauth reads the numeric exp claim in seconds from the ID token, not the access token. + const payload = Buffer.from(JSON.stringify({ exp: expiry / 1000 })).toString('base64url'); + return `eyJhbGciOiJub25lIn0.${payload}.`; +} + +afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); + vi.unstubAllEnvs(); +}); + +it('silently renews the bearer token across ARM operations on the same stored subscription', async (): Promise => { + const now = Date.UTC(2026, 0, 1); + const expiry = now + 60 * 60 * 1000; + vi.useFakeTimers({ now }); + + const showQuickPick = vi.spyOn(vscode.window, 'showQuickPick'); + const createQuickPick = vi.spyOn(vscode.window, 'createQuickPick'); + + registerAzureUtilsExtensionVariables({ + prefix: 'fixture', + context: { + extension: { + packageJSON: { name: 'fixture', version: '0.0.0', publisher: 'fixture', aiKey: 'fixture' }, + }, + } as vscode.ExtensionContext, + outputChannel: new TestOutputChannel(), + }); + const context: IActionContext = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + ui: new TestUserInput(vscode), + valuesToMask: [], + }; + + const provider = new TestSubscriptionProvider(); + try { + const listSubscriptions = vi.spyOn(provider, 'getAvailableSubscriptions'); + const listTenants = vi.spyOn(provider, 'getTenantsForAccount'); + const listTenantSubscriptions = vi.spyOn(provider, 'getSubscriptionsForTenant'); + const environment = getConfiguredAzureEnv(); + const account = { id: 'fixture-account', label: 'Fixture account', environment }; + const tenant = { tenantId: '00000000-0000-4000-8000-000000000001', account }; + const subscription: AzureSubscription = { + ...tenant, + ...provider.getSubscriptionAuth(tenant), + environment, + isCustomCloud: environment.isCustomCloud, + name: 'Fixture subscription', + subscriptionId: '00000000-0000-4000-8000-000000000002', + }; + const acquiredTokens: string[] = []; + getSession.mockImplementation(async (): Promise => { + const expired = Date.now() >= expiry; + const accessToken = expired ? 'fixture-B' : 'fixture-A'; + acquiredTokens.push(accessToken); + return { + id: 'fixture-session', + account, + scopes: [], + accessToken, + idToken: idToken(expired ? expiry + 60 * 60 * 1000 : expiry), + }; + }); + + const authorizations: (string | undefined)[] = []; + const transport: HttpClient = { + async sendRequest(request): Promise { + authorizations.push(request.headers.get('authorization')); + return { + request, + status: 200, + headers: createHttpHeaders({ 'content-type': 'application/json' }), + bodyAsText: JSON.stringify({ name: 'fixture-group', location: 'fixture-region' }), + }; + }, + }; + async function readResourceGroup(): Promise { + const client = await createResourceManagementClient(context, subscription); + // Substitute only the transport; the SDK still runs every pipeline policy. + const sendRequest = client.pipeline.sendRequest.bind(client.pipeline); + vi.spyOn(client.pipeline, 'sendRequest').mockImplementation( + (_transport, request): Promise => sendRequest(transport, request), + ); + await client.resourceGroups.get('fixture-group'); + } + + await readResourceGroup(); + expect(authorizations).toEqual(['Bearer fixture-A']); + expect(getSession).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(expiry - now + 1000); + await readResourceGroup(); + + expect(acquiredTokens).toEqual(['fixture-A', 'fixture-B']); + for (const [authProviderId, scopes, options] of getSession.mock.calls) { + expect(authProviderId).toBe('microsoft'); + expect(scopes).toContain(`VSCODE_TENANT:${tenant.tenantId}`); + expect(options).toMatchObject({ account, silent: true }); + expect(options?.createIfNone).toBeFalsy(); + expect(options).not.toHaveProperty('forceNewSession'); + } + expect(getAccounts).not.toHaveBeenCalled(); + expect(listTenants).not.toHaveBeenCalled(); + expect(listTenantSubscriptions).not.toHaveBeenCalled(); + expect(listSubscriptions).not.toHaveBeenCalled(); + expect(showQuickPick).not.toHaveBeenCalled(); + expect(createQuickPick).not.toHaveBeenCalled(); + expect(authorizations).toEqual(['Bearer fixture-A', 'Bearer fixture-B']); + } finally { + provider.dispose(); + } +}); diff --git a/src/utils/azureClients.ts b/src/utils/azureClients.ts index 65013668e..7bc1873ad 100644 --- a/src/utils/azureClients.ts +++ b/src/utils/azureClients.ts @@ -42,10 +42,8 @@ export async function createMongoClustersManagementClient( const subContext = createSubscriptionContext(subscription); return createAzureClient( [context, subContext], - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error (await import('@azure/arm-mongocluster')).MongoClusterManagementClient, - ) as unknown as MongoClusterManagementClient; + ); } export async function createComputeManagementClient( diff --git a/src/utils/commandErrorHandling.test.ts b/src/utils/commandErrorHandling.test.ts new file mode 100644 index 000000000..a15002d81 --- /dev/null +++ b/src/utils/commandErrorHandling.test.ts @@ -0,0 +1,327 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + createTestActionContext, + registerCommand, + UserCancelledError, + type IActionContext, + type TreeNodeCommandCallback, +} from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { rethrowBoundCommandUnavailable } from '../commands/rethrowBoundCommandUnavailable'; +import { ConnectionUnavailableError } from '../documentdb/ConnectionUnavailableError'; +import { ErrorExplanationService } from '../services/errorExplanationService'; +import { + markCommandErrorPresented, + registerCommandWithTreeNodeUnwrappingAndDiagnostics, + UserFacingError, +} from './commandErrorHandling'; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, registerCommand: vi.fn() }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal & { default: Record }>(); + // The shared VS Code mock omits this constructor, which the real parseError uses. + class CancellationError extends Error {} + actual.default.CancellationError = CancellationError; + return { ...actual, CancellationError }; +}); + +vi.mock('../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +interface TestNode { + readonly id: string; + readonly cluster?: { readonly clusterId: string }; +} + +const node: TestNode = { id: 'folder/tree-node', cluster: { clusterId: 'stable-cluster' } }; +const explanation = { providerId: 'test-provider', message: 'Check the connection infrastructure.' }; + +function registerHandler( + handler: TreeNodeCommandCallback, +): (context: IActionContext, ...args: unknown[]) => unknown { + registerCommandWithTreeNodeUnwrappingAndDiagnostics('test.databaseAction', handler); + const callback = vi.mocked(registerCommand).mock.calls.at(-1)?.[1]; + if (!callback) { + throw new Error('Command was not registered.'); + } + return callback; +} + +describe('tree command failure feedback', () => { + let context: IActionContext; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined); + context = await createTestActionContext(); + context.errorHandling.suppressDisplay = false; + context.errorHandling.rethrow = true; + }); + + it('passes unwrapped tree selections to the handler and preserves successful results', async () => { + const result = { completed: true }; + const handler = vi.fn(() => result); + const command = registerHandler(handler); + + await expect(command(context, { unwrap: () => node }, [{ unwrap: () => node }])).resolves.toBe(result); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, [node]); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + }); + + it('shows one translated tree modal with separate detail and rethrows the original error', async () => { + const cause = Object.freeze(new Error('Original cause')); + const error: Error = Object.freeze(new Error('Driver failure', { cause })); + const handler = vi.fn(() => { + throw error; + }); + const command = registerHandler(handler); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, { unwrap: () => node }, [{ unwrap: () => node }])).rejects.toBe(error); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, [node]); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(explanation.message, { + modal: true, + detail: 'Driver failure', + }); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + expect(error.cause).toBe(cause); + }); + + it.each([new Error('Presented failure'), 'Presented primitive failure'])( + 'does not duplicate feedback marked for the same error: %#', + async (error) => { + const rejectFailure = vi.fn<() => Promise>().mockRejectedValue(error); + const command = registerHandler(async (actionContext) => { + actionContext.errorHandling.suppressDisplay = true; + await vscode.window.showErrorMessage('Callback feedback.', { modal: true }); + markCommandErrorPresented(actionContext, error); + return rejectFailure(); + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Callback feedback.', { + modal: true, + }); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + }, + ); + + it('does not treat suppressDisplay without a presentation marker as feedback ownership', async () => { + const error = new ConnectionUnavailableError('identityChanged'); + const command = registerHandler((actionContext) => { + rethrowBoundCommandUnavailable(actionContext, error); + }); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail: error.message, + }); + expect(context.errorHandling.suppressDisplay).toBe(true); + }); + + it('shows a different error thrown during cleanup after the original error was presented', async () => { + const original = new Error('Original failure'); + const cleanup = new Error('Cleanup failure'); + const failCleanup = (): never => { + throw cleanup; + }; + const command = registerHandler(async (actionContext) => { + try { + throw original; + } catch (error) { + await vscode.window.showErrorMessage('Original callback feedback.', { modal: true }); + markCommandErrorPresented(actionContext, error); + throw error; + } finally { + failCleanup(); + } + }); + + await expect(command(context, node, [node])).rejects.toBe(cleanup); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(2); + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(2, 'Unable to complete this tree action.', { + modal: true, + detail: cleanup.message, + }); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error: cleanup, + }); + }); + + it.each([ + { error: new Error('Driver failure'), detail: 'Driver failure' }, + { error: { error: { message: 'Structured driver failure' } }, detail: 'Structured driver failure' }, + ])('shows one fallback tree modal with parsed detail: $detail', async ({ error, detail }) => { + const command = registerHandler(vi.fn().mockRejectedValue(error)); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail, + }); + expect(vscode.l10n.t).toHaveBeenCalledWith('Unable to complete this tree action.'); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBeUndefined(); + }); + + it('preserves UserFacingError content and details in the tree modal without translating it', async () => { + const cause = new Error('Underlying cause'); + const error = new UserFacingError('Repair the connection.', { cause, details: 'Existing detail.' }); + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(error.message, { + modal: true, + detail: error.options.details, + }); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(error.options.cause).toBe(cause); + }); + + it.each(['collectionView', 'clusterDashboard'])( + 'keeps explained %s failures non-modal and passes origin metadata through real unwrapping', + async (view) => { + const error = new Error('Driver failure'); + const metadata = { source: `webview;${view}`, binding: { clusterId: 'stable-cluster' } }; + const handler = vi.fn(() => { + throw error; + }); + const command = registerHandler(handler); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, { unwrap: () => node }, null, metadata)).rejects.toBe(error); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, undefined, metadata); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + `${explanation.message} (${error.message})`, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + }, + ); + + it('keeps webview notification behavior for an error marked by its callback', async () => { + const error = new Error('Driver failure'); + const command = registerHandler((actionContext) => { + markCommandErrorPresented(actionContext, error); + throw error; + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, node, null, { source: 'webview;collectionView' })).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + `${explanation.message} (${error.message})`, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + }); + + it('keeps unexplained webview failures on the default notification path', async () => { + const error = new Error('Driver failure'); + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, null, { source: 'webview;collectionView' })).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + expect(context.errorHandling.rethrow).toBe(true); + }); + + it('keeps webview UserFacingError content and actions on the default notification path', async () => { + const error = new UserFacingError('Existing message.', { details: 'Existing detail.' }); + const buttons = [{ title: 'Existing action', callback: vi.fn(async (): Promise => {}) }]; + context.errorHandling.buttons = buttons; + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, null, { source: 'webview;clusterDashboard' })).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + expect(context.errorHandling.buttons).toBe(buttons); + expect(error.message).toBe('Existing message.'); + expect(error.options.details).toBe('Existing detail.'); + }); + + it.each([new Error('Unassociated failure'), new UserFacingError('Unassociated user-facing failure')])( + 'keeps failures with no associated cluster on the default path: $message', + async (error) => { + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, { id: 'no-cluster' }, [])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + }, + ); + + it.each([ + { error: new UserCancelledError(), suppressDisplay: false }, + { error: new UserCancelledError(), suppressDisplay: true }, + { + error: { _isUserCancelledError: true, message: 'Cancelled by another package copy.' }, + suppressDisplay: false, + }, + ])('rethrows cancellation silently without changing suppression: %#', async ({ error, suppressDisplay }) => { + context.errorHandling.suppressDisplay = suppressDisplay; + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + const command = registerHandler(vi.fn().mockRejectedValue(error)); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(suppressDisplay); + expect(context.errorHandling.rethrow).toBe(true); + }); +}); diff --git a/src/utils/commandErrorHandling.ts b/src/utils/commandErrorHandling.ts index 5e201349e..91fe0e919 100644 --- a/src/utils/commandErrorHandling.ts +++ b/src/utils/commandErrorHandling.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { + parseError, registerCommand, type CommandCallback, type IActionContext, @@ -13,6 +14,12 @@ import { unwrapArgs } from '@microsoft/vscode-azureresources-api'; import * as vscode from 'vscode'; import { ErrorExplanationService } from '../services/errorExplanationService'; +const presentedCommandErrors = new WeakMap(); + +export function markCommandErrorPresented(context: IActionContext, error: unknown): void { + presentedCommandErrors.set(context, error); +} + /** * UserFacingError represents an error that should be prominently displayed to the user * in a modal dialog rather than a notification. Use this for critical errors that @@ -101,14 +108,20 @@ export function registerCommandWithModalErrors( ); } +function isWebviewInvocation(args: unknown[]): boolean { + const metadata = args[2]; + return ( + typeof metadata === 'object' && + metadata !== null && + 'source' in metadata && + typeof metadata.source === 'string' && + metadata.source.startsWith('webview;') + ); +} + /** - * Registers a tree-node command that explains infrastructure-caused failures, without changing how - * anything else is reported. - * - * Separate from {@link registerCommandWithTreeNodeUnwrappingAndModalErrors}: the database commands - * (create, drop, import, export, index) report their failures as notifications today, and a - * explanation is not a reason to start blocking the user with a modal. Only the wording changes, and - * only when a provider recognises the cluster. + * Registers a tree-node command that explains infrastructure-caused failures. Tree-origin failures + * associated with a cluster use a modal; shared webview calls retain their notification behavior. * * @param commandId The command ID to register * @param callback The command handler function that expects unwrapped tree node arguments @@ -124,22 +137,48 @@ export function registerCommandWithTreeNodeUnwrappingAndDiagnostics( registerCommand( commandId, async (context: IActionContext, ...args: unknown[]) => { + const webviewInvocation = isWebviewInvocation(args); let unwrappedArgs: ReturnType> = []; try { unwrappedArgs = unwrapArgs(args); return await callback(context, ...unwrappedArgs); } catch (error) { - // A UserFacingError already says what it needs to; leave it to default handling. + const presented = presentedCommandErrors.has(context) && presentedCommandErrors.get(context) === error; + const clusterId = (unwrappedArgs[0] as unknown as { cluster?: { clusterId?: string } } | undefined) + ?.cluster?.clusterId; + const treeError = !webviewInvocation && clusterId ? parseError(error) : undefined; + if (treeError?.isUserCancelledError) { + throw error; + } + if (error instanceof UserFacingError) { + if (treeError) { + context.errorHandling.suppressDisplay = true; + if (!presented) { + await vscode.window.showErrorMessage(error.message, { + modal: true, + detail: error.options.details, + }); + } + } throw error; } - const clusterId = (unwrappedArgs[0] as unknown as { cluster?: { clusterId?: string } } | undefined) - ?.cluster?.clusterId; const explanation = clusterId ? await ErrorExplanationService.explain({ clusterId, error }) : undefined; if (explanation) { context.telemetry.properties.explanationProviderId = explanation.providerId; + } + + if (treeError) { + context.errorHandling.suppressDisplay = true; + if (!presented) { + await vscode.window.showErrorMessage( + explanation?.message ?? vscode.l10n.t('Unable to complete this tree action.'), + { modal: true, detail: treeError.message }, + ); + } + } else if (explanation) { context.errorHandling.suppressDisplay = true; // `detail` is only rendered for modal messages, so the raw text is appended. const cause = error instanceof Error ? error.message : String(error); diff --git a/src/webviews/_integration/commonDialogs.test.ts b/src/webviews/_integration/commonDialogs.test.ts index da2cf8ccf..1d0ba86af 100644 --- a/src/webviews/_integration/commonDialogs.test.ts +++ b/src/webviews/_integration/commonDialogs.test.ts @@ -77,3 +77,24 @@ describe('common.confirm', () => { ); }); }); + +describe('common.displayErrorMessage', () => { + beforeEach(() => { + vi.mocked(vscode.window.showErrorMessage).mockReset(); + }); + + it('renders non-modal title and detail without host call-site formatting', async () => { + await expect( + caller.common.displayErrorMessage({ + message: 'Sign-in required', + modal: false, + cause: 'Sign in from the connection tree.', + }), + ).resolves.toEqual({ action: undefined }); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Sign-in required (Sign in from the connection tree.)', + { modal: false, detail: undefined }, + ); + }); +}); diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts new file mode 100644 index 000000000..70433b3d8 --- /dev/null +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -0,0 +1,81 @@ +/*--------------------------------------------------------------------------------------------- + * 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 connectionUnavailableReasons = [ + 'signInRequired', + 'credentialsRejected', + 'credentialsMissing', + 'credentialsUpdating', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', + 'sessionEnded', +] as const satisfies readonly ConnectionUnavailableReason[]; + +export const terminalUnavailableReasons = [ + 'userDisconnected', + 'connectionRemoved', + 'credentialsChanged', + 'identityChanged', + 'sessionEnded', +] as const satisfies readonly ConnectionUnavailableReason[]; + +export interface ConnectionUnavailableDetails { + readonly reason: ConnectionUnavailableReason; + readonly title: string; + readonly detail: string; +} + +export interface ConnectionUnavailableResponse { + readonly unavailable: ConnectionUnavailableDetails; +} + +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' + ); +} + +export function isTerminalUnavailable(details: ConnectionUnavailableDetails): boolean { + return terminalUnavailableReasons.some((reason) => reason === details.reason); +} + +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..1f583c1dd --- /dev/null +++ b/src/webviews/_integration/describeUnavailableConnection.test.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 { expect, it } from 'vitest'; +import { + isConnectionUnavailableMessage, + isConnectionUnavailableResponse, + isTerminalUnavailable, +} from './connectionUnavailable'; +import { describeUnavailableConnection } from './describeUnavailableConnection'; + +it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credentialsUpdating', 'unreachable'] as const)( + 'directs repair without a Retry workflow for %s', + (reason): void => { + const { unavailable } = describeUnavailableConnection(reason); + expect(unavailable).toMatchObject({ reason }); + expect(unavailable.detail).not.toContain('then click Retry'); + }, +); + +it('describes a retired binding as terminal through both response and notification parsing', (): void => { + const response = describeUnavailableConnection('sessionEnded'); + expect(response.unavailable).toEqual({ + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', + }); + expect(isConnectionUnavailableResponse(response)).toBe(true); + expect( + isConnectionUnavailableMessage({ + type: 'documentView.connectionUnavailable', + ...response, + }), + ).toBe(true); + expect(isTerminalUnavailable(response.unavailable)).toBe(true); +}); + +it.each(['userDisconnected', 'identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( + 'permanently describes ended sessions for %s', + (reason): void => { + expect(describeUnavailableConnection(reason).unavailable).toEqual({ + reason, + title: 'Disconnected', + detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + }); + }, +); diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts new file mode 100644 index 000000000..066ea3586 --- /dev/null +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -0,0 +1,74 @@ +/*--------------------------------------------------------------------------------------------- + * 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.'), + }, + }; + case 'credentialsRejected': + return { + unavailable: { + reason, + title: l10n.t('Authentication failed'), + detail: l10n.t('Repair the connection in the tree.'), + }, + }; + case 'credentialsMissing': + return { + unavailable: { + reason, + title: l10n.t('Disconnected'), + detail: l10n.t('Connect from the connection tree.'), + }, + }; + case 'credentialsUpdating': + return { + unavailable: { + reason, + title: l10n.t('Connection update in progress'), + detail: l10n.t('Wait for the update to finish.'), + }, + }; + case 'sessionEnded': + return { + unavailable: { + reason, + title: l10n.t('Session ended'), + detail: l10n.t('Copy what you need and open a new tab.'), + }, + }; + case 'userDisconnected': + case 'identityChanged': + case 'credentialsChanged': + case 'connectionRemoved': + return { + unavailable: { + reason, + title: l10n.t('Disconnected'), + detail: l10n.t( + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + ), + }, + }; + case 'unreachable': + return { + unavailable: { + reason, + title: l10n.t('Connection lost'), + detail: l10n.t('Check the network or server.'), + }, + }; + } +} diff --git a/src/webviews/_integration/trpc.test.ts b/src/webviews/_integration/trpc.test.ts index f0121a3dc..f1de0f947 100644 --- a/src/webviews/_integration/trpc.test.ts +++ b/src/webviews/_integration/trpc.test.ts @@ -7,6 +7,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import { TRPCError } from '@trpc/server'; import { MongoServerError } from 'mongodb'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { describeUnavailableConnection } from './describeUnavailableConnection'; import { createCallerFactory, publicProcedureWithTelemetry, router } from './trpc'; const recordedContexts = vi.hoisted((): IActionContext[] => []); @@ -72,6 +73,23 @@ describe('destination RPC attribution', () => { }); }); +const unavailableResponse = { + unavailable: { + reason: 'credentialsRejected', + title: 'Reconnect', + detail: 'The saved credentials were rejected.', + }, +} as const; +const ordinaryResponse = { value: 'loaded' } as const; +const endedResponse = describeUnavailableConnection('sessionEnded'); +const malformedUnavailableResponse = { + unavailable: { + reason: 'tokenExpired', + title: 'Reconnect', + detail: 'The connection token expired.', + }, +} as const; + const testRouter = router({ dismissed: publicProcedureWithTelemetry.mutation((): never => { throw new UserCancelledError(); @@ -87,6 +105,10 @@ const testRouter = router({ rejected: publicProcedureWithTelemetry.mutation((): never => { throw new TRPCError({ code: 'BAD_REQUEST', message: 'rejected' }); }), + unavailable: publicProcedureWithTelemetry.query(() => unavailableResponse), + ended: publicProcedureWithTelemetry.query(() => endedResponse), + ordinary: publicProcedureWithTelemetry.query(() => ordinaryResponse), + malformedUnavailable: publicProcedureWithTelemetry.query(() => malformedUnavailableResponse), }); const createCaller = createCallerFactory(testRouter); @@ -125,4 +147,32 @@ describe('publicProcedureWithTelemetry', (): void => { expect(recordedContexts[0].telemetry.properties.result).toBe('Failed'); expect(recordedContexts[0].telemetry.properties.causeType).toBeUndefined(); }); + + it('records the bounded reason from an unavailable response without changing the RPC result', async (): Promise => { + await expect(caller().unavailable()).resolves.toBe(unavailableResponse); + expect(recordedContexts).toHaveLength(1); + expect(recordedContexts[0].telemetry.properties).toMatchObject({ + result: 'Succeeded', + unavailableReason: 'credentialsRejected', + }); + }); + + it('records sessionEnded through the existing safe reason pipeline without adding error fields', async (): Promise => { + await expect(caller().ended()).resolves.toBe(endedResponse); + expect(recordedContexts).toHaveLength(1); + expect(recordedContexts[0].telemetry.properties).toEqual({ + result: 'Succeeded', + unavailableReason: 'sessionEnded', + }); + }); + + it.each([ + ['ordinary', ordinaryResponse], + ['malformed unavailable', malformedUnavailableResponse], + ] as const)('does not add unavailableReason for an %s response', async (procedure, expected): Promise => { + const result = procedure === 'ordinary' ? await caller().ordinary() : await caller().malformedUnavailable(); + expect(result).toBe(expected); + expect(recordedContexts).toHaveLength(1); + expect(recordedContexts[0].telemetry.properties.unavailableReason).toBeUndefined(); + }); }); diff --git a/src/webviews/_integration/trpc.ts b/src/webviews/_integration/trpc.ts index b1e76c12e..63608fb40 100644 --- a/src/webviews/_integration/trpc.ts +++ b/src/webviews/_integration/trpc.ts @@ -59,6 +59,7 @@ import { } from '../../deepLinks/deepLinkTelemetry'; import { innermostCauseTypeOf } from '../../utils/telemetryErrorType'; import { WEBVIEW_CONFIG } from './configuration'; +import { isConnectionUnavailableResponse } from './connectionUnavailable'; /** * The single tRPC instance for this extension, bound to the framework's @@ -168,6 +169,12 @@ const documentDbTelemetryRunner: TelemetryRunner = { if (causeType !== undefined) { actionContext.telemetry.properties.causeType = causeType; } + } else if ( + middlewareResult.ok && + 'data' in middlewareResult && + isConnectionUnavailableResponse(middlewareResult.data) + ) { + actionContext.telemetry.properties.unavailableReason = middlewareResult.data.unavailable.reason; } return middlewareResult; diff --git a/src/webviews/components/DisconnectedOverlay.scss b/src/webviews/components/DisconnectedOverlay.scss new file mode 100644 index 000000000..dcf508633 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.scss @@ -0,0 +1,3 @@ +.disconnectedOverlayBackground { + display: contents; +} diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx new file mode 100644 index 000000000..e017653e5 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -0,0 +1,242 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { beforeEach, 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 } } }), +})); + +const unavailable: ConnectionUnavailableDetails = { + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', +}; + +beforeEach((): void => { + confirm.mockReset(); +}); + +it('dismisses only the notice and never enables terminal content actions', async (): Promise => { + const onClose = vi.fn(); + const onDismiss = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + const render = async (failure?: ConnectionUnavailableDetails): Promise => { + await act(async () => + root.render( + +