Shell: Integrate Cloudshell to existing shells (#2098)

* first draft

* refactored code

* ux fix

* add custom header support and fix ui

* minor changes

* hide last command also

* remove logger

* bug fixes

* updated loick file

* fix tests

* moved files

* update readme

* documentation update

* fix compilationerror

* undefined check handle

* format fix

* format fix

* fix lints

* format fix

* fix unrelatred test

* code refator

* fix format

* ut fix

* cgmanifest

* Revert "cgmanifest"

This reverts commit 2e76a6926ee0d3d4e0510f2e04e03446c2ca8c47.

* fix snap

* test fix

* formatting code

* updated xterm

* include username in command

* cloudshell add exit

* fix test

* format fix

* tets fix

* fix multiple open cloudshell calls

* socket time out after 20 min

* remove unused code

* 120 min

* Addressed comments
This commit is contained in:
Sourabh Jain 2025-05-01 01:49:01 +05:30 committed by GitHub
parent bb66deb3a4
commit 205355bf55
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
35 changed files with 2664 additions and 90 deletions

15
package-lock.json generated
View File

@ -51,6 +51,8 @@
"@types/mkdirp": "1.0.1",
"@types/node-fetch": "2.5.7",
"@xmldom/xmldom": "0.7.13",
"@xterm/addon-fit": "0.10.0",
"@xterm/xterm": "5.5.0",
"allotment": "1.20.2",
"applicationinsights": "1.8.0",
"bootstrap": "3.4.1",
@ -13240,6 +13242,19 @@
"node": ">=10.0.0"
}
},
"node_modules/@xterm/addon-fit": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz",
"integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==",
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
},
"node_modules/@xterm/xterm": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
"integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A=="
},
"node_modules/@xtuc/ieee754": {
"version": "1.2.0",
"license": "BSD-3-Clause"

View File

@ -46,6 +46,8 @@
"@types/mkdirp": "1.0.1",
"@types/node-fetch": "2.5.7",
"@xmldom/xmldom": "0.7.13",
"@xterm/xterm": "5.5.0",
"@xterm/addon-fit": "0.10.0",
"allotment": "1.20.2",
"applicationinsights": "1.8.0",
"bootstrap": "3.4.1",

View File

@ -257,6 +257,7 @@ export class Areas {
public static ShareDialog: string = "Share Access Dialog";
public static Notebook: string = "Notebook";
public static Copilot: string = "Copilot";
public static CloudShell: string = "Cloud Shell";
}
export class HttpHeaders {

View File

@ -103,17 +103,23 @@ export const createCollectionContextMenuButton = (
iconSrc: HostedTerminalIcon,
onClick: () => {
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
if (useNotebook.getState().isShellEnabled) {
if (useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell) {
container.openNotebookTerminal(ViewModels.TerminalKind.Mongo);
} else {
selectedCollection && selectedCollection.onNewMongoShellClick();
}
},
label: useNotebook.getState().isShellEnabled ? "Open Mongo Shell" : "New Shell",
label:
useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell
? "Open Mongo Shell"
: "New Shell",
});
}
if (useNotebook.getState().isShellEnabled && userContext.apiType === "Cassandra") {
if (
(useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell) &&
userContext.apiType === "Cassandra"
) {
items.push({
iconSrc: HostedTerminalIcon,
onClick: () => {

View File

@ -910,7 +910,9 @@ export default class Explorer {
}
public async openNotebookTerminal(kind: ViewModels.TerminalKind): Promise<void> {
if (useNotebook.getState().isPhoenixFeatures) {
if (userContext.features.enableCloudShell) {
this.connectToNotebookTerminal(kind);
} else if (useNotebook.getState().isPhoenixFeatures) {
await this.allocateContainer(PoolIdType.DefaultPoolId);
const notebookServerInfo = useNotebook.getState().notebookServerInfo;
if (notebookServerInfo && notebookServerInfo.notebookServerEndpoint !== undefined) {

View File

@ -126,13 +126,14 @@ export function createContextCommandBarButtons(
const buttons: CommandButtonComponentProps[] = [];
if (!selectedNodeState.isDatabaseNodeOrNoneSelected() && userContext.apiType === "Mongo") {
const label = useNotebook.getState().isShellEnabled ? "Open Mongo Shell" : "New Shell";
const label =
useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell ? "Open Mongo Shell" : "New Shell";
const newMongoShellBtn: CommandButtonComponentProps = {
iconSrc: HostedTerminalIcon,
iconAlt: label,
onCommandClick: () => {
const selectedCollection: ViewModels.Collection = selectedNodeState.findSelectedCollection();
if (useNotebook.getState().isShellEnabled) {
if (useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell) {
container.openNotebookTerminal(ViewModels.TerminalKind.Mongo);
} else {
selectedCollection && selectedCollection.onNewMongoShellClick();
@ -146,7 +147,7 @@ export function createContextCommandBarButtons(
}
if (
useNotebook.getState().isShellEnabled &&
(useNotebook.getState().isShellEnabled || userContext.features.enableCloudShell) &&
!selectedNodeState.isDatabaseNodeOrNoneSelected() &&
userContext.apiType === "Cassandra"
) {
@ -455,7 +456,7 @@ function createOpenTerminalButtonByKind(
iconSrc: HostedTerminalIcon,
iconAlt: label,
onCommandClick: () => {
if (useNotebook.getState().isNotebookEnabled) {
if (useNotebook.getState().isNotebookEnabled || userContext.features.enableCloudShell) {
container.openNotebookTerminal(terminalKind);
}
},

View File

@ -0,0 +1,80 @@
import { FitAddon } from "@xterm/addon-fit";
import { Terminal } from "@xterm/xterm";
import React, { useEffect, useRef } from "react";
import "xterm/css/xterm.css";
import { DatabaseAccount } from "../../../Contracts/DataModels";
import { TerminalKind } from "../../../Contracts/ViewModels";
import { startCloudShellTerminal } from "./CloudShellTerminalCore";
export interface CloudShellTerminalComponentProps {
databaseAccount: DatabaseAccount;
tabId: string;
username?: string;
shellType?: TerminalKind;
}
export const CloudShellTerminalComponent: React.FC<CloudShellTerminalComponentProps> = (props) => {
const terminalRef = useRef(null); // Reference for terminal container
const xtermRef = useRef(null); // Reference for XTerm instance
const socketRef = useRef(null); // Reference for WebSocket
useEffect(() => {
// Initialize XTerm instance
const terminal = new Terminal({
cursorBlink: true,
cursorStyle: "bar",
fontFamily: "monospace",
fontSize: 11,
theme: {
background: "#1e1e1e",
foreground: "#d4d4d4",
cursor: "#ffcc00",
},
scrollback: 1000,
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
// Attach terminal to the DOM
if (terminalRef.current) {
terminal.open(terminalRef.current);
xtermRef.current = terminal;
}
// Defer terminal sizing until after DOM rendering is complete
setTimeout(() => {
fitAddon.fit();
}, 0);
// Use ResizeObserver instead of window resize
const resizeObserver = new ResizeObserver(() => {
const container = terminalRef.current;
if (container && container.offsetWidth > 0 && container.offsetHeight > 0) {
try {
fitAddon.fit();
} catch (e) {
console.warn("Fit failed on resize:", e);
}
}
});
resizeObserver.observe(terminalRef.current);
socketRef.current = startCloudShellTerminal(terminal, props.shellType);
// Cleanup function to close WebSocket and dispose terminal
return () => {
if (!socketRef.current) {
return;
}
if (socketRef.current && socketRef.current.readyState && socketRef.current.readyState === WebSocket.OPEN) {
socketRef.current.close(); // Close WebSocket connection
}
if (resizeObserver && terminalRef.current) {
resizeObserver.unobserve(terminalRef.current);
}
terminal.dispose(); // Clean up XTerm instance
};
}, []);
return <div ref={terminalRef} style={{ width: "100%", height: "500px" }} />;
};

View File

@ -0,0 +1,290 @@
import { Terminal } from "@xterm/xterm";
import { Areas } from "../../../Common/Constants";
import { getErrorMessage, getErrorStack } from "../../../Common/ErrorHandlingUtils";
import { TerminalKind } from "../../../Contracts/ViewModels";
import { Action, ActionModifiers } from "../../../Shared/Telemetry/TelemetryConstants";
import * as TelemetryProcessor from "../../../Shared/Telemetry/TelemetryProcessor";
import { userContext } from "../../../UserContext";
import {
connectTerminal,
provisionConsole,
putEphemeralUserSettings,
registerCloudShellProvider,
verifyCloudShellProviderRegistration,
} from "./Data/CloudShellClient";
import { CloudShellProviderInfo, ProvisionConsoleResponse } from "./Models/DataModels";
import { AbstractShellHandler, START_MARKER } from "./ShellTypes/AbstractShellHandler";
import { getHandler } from "./ShellTypes/ShellTypeFactory";
import { AttachAddon } from "./Utils/AttachAddOn";
import { askConfirmation, wait } from "./Utils/CommonUtils";
import { getNormalizedRegion } from "./Utils/RegionUtils";
import { formatErrorMessage, formatInfoMessage, formatWarningMessage } from "./Utils/TerminalLogFormats";
// Constants
const DEFAULT_CLOUDSHELL_REGION = "westus";
const POLLING_INTERVAL_MS = 2000;
const MAX_RETRY_COUNT = 10;
const MAX_PING_COUNT = 120 * 60; // 120 minutes (60 seconds/minute)
let pingCount = 0;
let keepAliveID: NodeJS.Timeout = null;
/**
* Main function to start a CloudShell terminal
*/
export const startCloudShellTerminal = async (terminal: Terminal, shellType: TerminalKind): Promise<WebSocket> => {
const startKey = TelemetryProcessor.traceStart(Action.CloudShellTerminalSession, {
shellType: TerminalKind[shellType],
dataExplorerArea: Areas.CloudShell,
});
let resolvedRegion: string;
try {
await ensureCloudShellProviderRegistered();
resolvedRegion = determineCloudShellRegion();
// Ask for user consent for region
const consentGranted = await askConfirmation(
terminal,
formatWarningMessage(
"The shell environment may be operating in a region different from that of the database, which could impact performance or data compliance. Do you wish to proceed?",
),
);
// Track user decision
TelemetryProcessor.trace(
Action.CloudShellUserConsent,
consentGranted ? ActionModifiers.Success : ActionModifiers.Cancel,
{ dataExplorerArea: Areas.CloudShell },
);
if (!consentGranted) {
TelemetryProcessor.traceCancel(
Action.CloudShellTerminalSession,
{
shellType: TerminalKind[shellType],
dataExplorerArea: Areas.CloudShell,
region: resolvedRegion,
isConsent: false,
},
startKey,
);
terminal.writeln(
formatErrorMessage("Session ended. Please close this tab and initiate a new shell session if needed."),
);
return null; // Exit if user declined
}
terminal.writeln(formatInfoMessage("Connecting to CloudShell. This may take a moment. Please wait..."));
const sessionDetails: {
socketUri?: string;
provisionConsoleResponse?: ProvisionConsoleResponse;
targetUri?: string;
} = await provisionCloudShellSession(resolvedRegion, terminal);
if (!sessionDetails.socketUri) {
terminal.writeln(formatErrorMessage("Failed to establish a connection. Please try again later."));
return null;
}
// Get the shell handler for this type
const shellHandler = await getHandler(shellType);
// Configure WebSocket connection with shell-specific commands
const socket = await establishTerminalConnection(terminal, shellHandler, sessionDetails.socketUri);
TelemetryProcessor.traceSuccess(
Action.CloudShellTerminalSession,
{
shellType: TerminalKind[shellType],
dataExplorerArea: Areas.CloudShell,
region: resolvedRegion,
socketUri: sessionDetails.socketUri,
},
startKey,
);
return socket;
} catch (err) {
TelemetryProcessor.traceFailure(
Action.CloudShellTerminalSession,
{
shellType: TerminalKind[shellType],
dataExplorerArea: Areas.CloudShell,
region: resolvedRegion,
error: getErrorMessage(err),
errorStack: getErrorStack(err),
},
startKey,
);
terminal.writeln(formatErrorMessage(`Failed with error.${getErrorMessage(err)}`));
return null;
}
};
/**
* Ensures that the CloudShell provider is registered for the current subscription
*/
export const ensureCloudShellProviderRegistered = async (): Promise<void> => {
const response: CloudShellProviderInfo = await verifyCloudShellProviderRegistration(userContext.subscriptionId);
if (response.registrationState !== "Registered") {
await registerCloudShellProvider(userContext.subscriptionId);
}
};
/**
* Determines the appropriate CloudShell region
*/
export const determineCloudShellRegion = (): string => {
return getNormalizedRegion(userContext.databaseAccount?.location, DEFAULT_CLOUDSHELL_REGION);
};
/**
* Provisions a CloudShell session
*/
export const provisionCloudShellSession = async (
resolvedRegion: string,
terminal: Terminal,
): Promise<{ socketUri?: string; provisionConsoleResponse?: ProvisionConsoleResponse; targetUri?: string }> => {
// Apply user settings
await putEphemeralUserSettings(userContext.subscriptionId, resolvedRegion);
// Provision console
let provisionConsoleResponse;
let attemptCounter = 0;
do {
provisionConsoleResponse = await provisionConsole(resolvedRegion);
attemptCounter++;
if (provisionConsoleResponse.properties.provisioningState === "Failed") {
break;
}
if (provisionConsoleResponse.properties.provisioningState !== "Succeeded") {
await wait(POLLING_INTERVAL_MS);
}
} while (provisionConsoleResponse.properties.provisioningState !== "Succeeded" && attemptCounter < MAX_RETRY_COUNT);
if (provisionConsoleResponse.properties.provisioningState !== "Succeeded") {
throw new Error(`Provisioning failed: ${provisionConsoleResponse.properties.provisioningState}`);
}
// Connect terminal
const connectTerminalResponse = await connectTerminal(provisionConsoleResponse.properties.uri, {
rows: terminal.rows,
cols: terminal.cols,
});
const targetUri = `${provisionConsoleResponse.properties.uri}/terminals?cols=${terminal.cols}&rows=${terminal.rows}&version=2019-01-01&shell=bash`;
const termId = connectTerminalResponse.id;
// Determine socket URI
let socketUri = connectTerminalResponse.socketUri.replace(":443/", "");
const targetUriBody = targetUri.replace("https://", "").split("?")[0];
// This socket URI transformation logic handles different Azure service endpoint formats.
// If the returned socketUri doesn't contain the expected host, we construct it manually.
// This ensures compatibility across different Azure regions and deployment configurations.
if (socketUri.indexOf(targetUriBody) === -1) {
socketUri = `wss://${targetUriBody}/${termId}`;
}
// Special handling for ServiceBus-based endpoints which require a specific URI format
// with the hierarchical connection ($hc) path segment for terminal connections
if (targetUriBody.includes("servicebus")) {
const targetUriBodyArr = targetUriBody.split("/");
socketUri = `wss://${targetUriBodyArr[0]}/$hc/${targetUriBodyArr[1]}/terminals/${termId}`;
}
return { socketUri, provisionConsoleResponse, targetUri };
};
/**
* Establishes a terminal connection via WebSocket
*/
export const establishTerminalConnection = async (
terminal: Terminal,
shellHandler: AbstractShellHandler,
socketUri: string,
): Promise<WebSocket> => {
let socket = new WebSocket(socketUri);
// Get shell-specific initial commands
const initCommands = shellHandler.getInitialCommands();
// Configure the socket
socket = await configureSocketConnection(socket, socketUri, terminal, initCommands, 0);
const options = {
startMarker: START_MARKER,
shellHandler: shellHandler,
};
// Attach the terminal addon
const attachAddon = new AttachAddon(socket, options);
terminal.loadAddon(attachAddon);
return socket;
};
/**
* Configures a WebSocket connection for the terminal
*/
export const configureSocketConnection = async (
socket: WebSocket,
uri: string,
terminal: Terminal,
initCommands: string,
socketRetryCount: number,
): Promise<WebSocket> => {
sendTerminalStartupCommands(socket, initCommands);
socket.onerror = async () => {
if (socketRetryCount < MAX_RETRY_COUNT && socket.readyState !== WebSocket.CLOSED) {
await configureSocketConnection(socket, uri, terminal, initCommands, socketRetryCount + 1);
} else {
socket.close();
}
};
socket.onclose = () => {
if (keepAliveID) {
clearTimeout(keepAliveID);
pingCount = 0;
}
};
return socket;
};
export const sendTerminalStartupCommands = (socket: WebSocket, initCommands: string): void => {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(initCommands);
} else {
socket.onopen = () => {
socket.send(initCommands);
// ensures connections don't remain open indefinitely by implementing an automatic timeout after 20 minutes.
const keepSocketAlive = (socket: WebSocket) => {
if (socket.readyState === WebSocket.OPEN) {
if (pingCount >= MAX_PING_COUNT) {
socket.close();
} else {
socket.send("");
pingCount++;
// The code uses a recursive setTimeout pattern rather than setInterval,
// which ensures each new ping only happens after the previous one completes
// and naturally stops if the socket closes.
keepAliveID = setTimeout(() => keepSocketAlive(socket), 1000);
}
}
};
keepSocketAlive(socket);
};
}
};

View File

@ -0,0 +1,337 @@
import { armRequest } from "../../../../Utils/arm/request";
import { NetworkType, OsType, SessionType, ShellType } from "../Models/DataModels";
import {
connectTerminal,
getUserSettings,
provisionConsole,
putEphemeralUserSettings,
registerCloudShellProvider,
verifyCloudShellProviderRegistration,
} from "./CloudShellClient";
// Instead of redeclaring fetch, modify the global context
/* eslint-disable @typescript-eslint/no-namespace */
declare global {
namespace NodeJS {
interface Global {
fetch: jest.Mock;
}
}
}
/* eslint-enable @typescript-eslint/no-namespace */
// Define mock endpoint
const MOCK_ARM_ENDPOINT = "https://mock-management.azure.com";
// Mock dependencies
jest.mock("uuid", () => ({
v4: jest.fn().mockReturnValue("mocked-uuid"),
}));
jest.mock("../../../../ConfigContext", () => ({
configContext: {
ARM_ENDPOINT: "https://mock-management.azure.com",
},
}));
jest.mock("../../../../UserContext", () => ({
userContext: {
authorizationToken: "Bearer mock-token",
},
}));
jest.mock("../../../../Utils/arm/request");
jest.mock("../Utils/CommonUtils", () => ({
getLocale: jest.fn().mockReturnValue("en-US"),
}));
// Properly mock fetch with correct typings
const mockJsonPromise = jest.fn();
global.fetch = jest.fn().mockImplementationOnce(() => {
return {
ok: true,
status: 200,
json: mockJsonPromise,
text: jest.fn().mockResolvedValue(""),
headers: new Headers(),
} as unknown as Promise<Response>;
}) as jest.Mock;
describe("CloudShellClient", () => {
beforeEach(() => {
jest.clearAllMocks();
mockJsonPromise.mockClear();
});
// Reset all mocks after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
if (global.fetch) {
delete global.fetch;
}
});
describe("getUserSettings", () => {
it("should call armRequest with correct parameters and return settings", async () => {
const mockSettings = { properties: { preferredLocation: "eastus" } };
(armRequest as jest.Mock).mockResolvedValueOnce(mockSettings);
const result = await getUserSettings();
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/providers/Microsoft.Portal/userSettings/cloudconsole",
method: "GET",
apiVersion: "2023-02-01-preview",
});
expect(result).toEqual(mockSettings);
});
it("should handle errors when settings retrieval fails", async () => {
const mockError = new Error("Failed to get user settings");
(armRequest as jest.Mock).mockRejectedValueOnce(mockError);
await expect(getUserSettings()).rejects.toThrow("Failed to get user settings");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/providers/Microsoft.Portal/userSettings/cloudconsole",
method: "GET",
apiVersion: "2023-02-01-preview",
});
});
});
describe("putEphemeralUserSettings", () => {
it("should call armRequest with default network settings", async () => {
const mockResponse = { id: "settings-id" };
(armRequest as jest.Mock).mockResolvedValueOnce(mockResponse);
const result = await putEphemeralUserSettings("sub-id", "eastus");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/providers/Microsoft.Portal/userSettings/cloudconsole",
method: "PUT",
apiVersion: "2023-02-01-preview",
body: {
properties: {
preferredOsType: OsType.Linux,
preferredShellType: ShellType.Bash,
preferredLocation: "eastus",
networkType: NetworkType.Default,
sessionType: SessionType.Ephemeral,
userSubscription: "sub-id",
vnetSettings: {},
},
},
});
expect(result).toEqual(mockResponse);
});
it("should call armRequest with isolated network settings", async () => {
const mockVNetSettings = { subnetId: "test-subnet" };
const mockResponse = { id: "settings-id" };
(armRequest as jest.Mock).mockResolvedValueOnce(mockResponse);
await putEphemeralUserSettings("sub-id", "eastus", mockVNetSettings);
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/providers/Microsoft.Portal/userSettings/cloudconsole",
method: "PUT",
apiVersion: "2023-02-01-preview",
body: {
properties: {
preferredOsType: OsType.Linux,
preferredShellType: ShellType.Bash,
preferredLocation: "eastus",
networkType: NetworkType.Isolated,
sessionType: SessionType.Ephemeral,
userSubscription: "sub-id",
vnetSettings: mockVNetSettings,
},
},
});
});
it("should handle errors when updating settings fails", async () => {
const mockError = new Error("Failed to update user settings");
(armRequest as jest.Mock).mockRejectedValueOnce(mockError);
await expect(putEphemeralUserSettings("sub-id", "eastus")).rejects.toThrow("Failed to update user settings");
expect(armRequest).toHaveBeenCalled();
});
});
describe("verifyCloudShellProviderRegistration", () => {
it("should call armRequest with correct parameters", async () => {
const mockResponse = { registrationState: "Registered" };
(armRequest as jest.Mock).mockResolvedValueOnce(mockResponse);
const result = await verifyCloudShellProviderRegistration("sub-id");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/subscriptions/sub-id/providers/Microsoft.CloudShell",
method: "GET",
apiVersion: "2022-12-01",
});
expect(result).toEqual(mockResponse);
});
it("should handle errors when verification fails", async () => {
const mockError = new Error("Failed to verify provider registration");
(armRequest as jest.Mock).mockRejectedValueOnce(mockError);
await expect(verifyCloudShellProviderRegistration("sub-id")).rejects.toThrow(
"Failed to verify provider registration",
);
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/subscriptions/sub-id/providers/Microsoft.CloudShell",
method: "GET",
apiVersion: "2022-12-01",
});
});
});
describe("registerCloudShellProvider", () => {
it("should call armRequest with correct parameters", async () => {
const mockResponse = { operationId: "op-id" };
(armRequest as jest.Mock).mockResolvedValueOnce(mockResponse);
const result = await registerCloudShellProvider("sub-id");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/subscriptions/sub-id/providers/Microsoft.CloudShell/register",
method: "POST",
apiVersion: "2022-12-01",
});
expect(result).toEqual(mockResponse);
});
it("should handle errors when registration fails", async () => {
const mockError = new Error("Failed to register provider");
(armRequest as jest.Mock).mockRejectedValueOnce(mockError);
await expect(registerCloudShellProvider("sub-id")).rejects.toThrow("Failed to register provider");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "/subscriptions/sub-id/providers/Microsoft.CloudShell/register",
method: "POST",
apiVersion: "2022-12-01",
});
});
});
describe("provisionConsole", () => {
it("should call armRequest with correct parameters", async () => {
const mockResponse = { uri: "https://shell.azure.com/console123" };
(armRequest as jest.Mock).mockResolvedValueOnce(mockResponse);
const result = await provisionConsole("eastus");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "providers/Microsoft.Portal/consoles/default",
method: "PUT",
apiVersion: "2023-02-01-preview",
customHeaders: {
"x-ms-console-preferred-location": "eastus",
},
body: {
properties: {
osType: OsType.Linux,
},
},
});
expect(result).toEqual(mockResponse);
});
it("should handle errors when console provisioning fails", async () => {
const mockError = new Error("Failed to provision console");
(armRequest as jest.Mock).mockRejectedValueOnce(mockError);
await expect(provisionConsole("eastus")).rejects.toThrow("Failed to provision console");
expect(armRequest).toHaveBeenCalledWith({
host: MOCK_ARM_ENDPOINT,
path: "providers/Microsoft.Portal/consoles/default",
method: "PUT",
apiVersion: "2023-02-01-preview",
customHeaders: {
"x-ms-console-preferred-location": "eastus",
},
body: {
properties: {
osType: OsType.Linux,
},
},
});
});
});
describe("connectTerminal", () => {
it("should call fetch with correct parameters", async () => {
const consoleUri = "https://shell.azure.com/console123";
const size = { rows: 24, cols: 80 };
const mockTerminalResponse = { id: "terminal-id", socketUri: "wss://shell.azure.com/socket" };
// Setup the mock response
mockJsonPromise.mockResolvedValueOnce(mockTerminalResponse);
const result = await connectTerminal(consoleUri, size);
expect(global.fetch).toHaveBeenCalledWith(
"https://shell.azure.com/console123/terminals?cols=80&rows=24&version=2019-01-01&shell=bash",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Content-Length": "2",
Authorization: "Bearer mock-token",
"x-ms-client-request-id": "mocked-uuid",
"Accept-Language": "en-US",
},
body: "{}",
},
);
expect(mockJsonPromise).toHaveBeenCalled();
expect(result).toEqual(mockTerminalResponse);
});
it("should handle errors when terminal connection fails", async () => {
const consoleUri = "https://shell.azure.com/console123";
const size = { rows: 24, cols: 80 };
// Mock fetch to return a failed response
global.fetch = jest.fn().mockImplementationOnce(() => {
return {
ok: false,
status: 500,
statusText: "Internal Server Error",
json: jest.fn().mockRejectedValue(new Error("Failed to parse JSON")),
text: jest.fn().mockResolvedValue("Server Error"),
headers: new Headers(),
} as unknown as Promise<Response>;
});
await expect(connectTerminal(consoleUri, size)).rejects.toThrow(
"Failed to connect to terminal: 500 Internal Server Error",
);
expect(global.fetch).toHaveBeenCalledWith(
"https://shell.azure.com/console123/terminals?cols=80&rows=24&version=2019-01-01&shell=bash",
expect.any(Object),
);
});
});
});

View File

@ -0,0 +1,117 @@
import { v4 as uuidv4 } from "uuid";
import { configContext } from "../../../../ConfigContext";
import { userContext } from "../../../../UserContext";
import { armRequest } from "../../../../Utils/arm/request";
import {
CloudShellProviderInfo,
CloudShellSettings,
ConnectTerminalResponse,
NetworkType,
OsType,
ProvisionConsoleResponse,
SessionType,
ShellType,
} from "../Models/DataModels";
import { getLocale } from "../Utils/CommonUtils";
export const getUserSettings = async (): Promise<CloudShellSettings> => {
return await armRequest<CloudShellSettings>({
host: configContext.ARM_ENDPOINT,
path: `/providers/Microsoft.Portal/userSettings/cloudconsole`,
method: "GET",
apiVersion: "2023-02-01-preview",
});
};
export const putEphemeralUserSettings = async (
userSubscriptionId: string,
userRegion: string,
vNetSettings?: object,
) => {
const ephemeralSettings: CloudShellSettings = {
properties: {
preferredOsType: OsType.Linux,
preferredShellType: ShellType.Bash,
preferredLocation: userRegion,
networkType:
!vNetSettings || Object.keys(vNetSettings).length === 0
? NetworkType.Default
: vNetSettings
? NetworkType.Isolated
: NetworkType.Default,
sessionType: SessionType.Ephemeral,
userSubscription: userSubscriptionId,
vnetSettings: vNetSettings ?? {},
},
};
return await armRequest({
host: configContext.ARM_ENDPOINT,
path: `/providers/Microsoft.Portal/userSettings/cloudconsole`,
method: "PUT",
apiVersion: "2023-02-01-preview",
body: ephemeralSettings,
});
};
export const verifyCloudShellProviderRegistration = async (subscriptionId: string): Promise<CloudShellProviderInfo> => {
return await armRequest({
host: configContext.ARM_ENDPOINT,
path: `/subscriptions/${subscriptionId}/providers/Microsoft.CloudShell`,
method: "GET",
apiVersion: "2022-12-01",
});
};
export const registerCloudShellProvider = async (subscriptionId: string) => {
return await armRequest({
host: configContext.ARM_ENDPOINT,
path: `/subscriptions/${subscriptionId}/providers/Microsoft.CloudShell/register`,
method: "POST",
apiVersion: "2022-12-01",
});
};
export const provisionConsole = async (consoleLocation: string): Promise<ProvisionConsoleResponse> => {
const data = {
properties: {
osType: OsType.Linux,
},
};
return await armRequest<ProvisionConsoleResponse>({
host: configContext.ARM_ENDPOINT,
path: `providers/Microsoft.Portal/consoles/default`,
method: "PUT",
apiVersion: "2023-02-01-preview",
customHeaders: {
"x-ms-console-preferred-location": consoleLocation,
},
body: data,
});
};
export const connectTerminal = async (
consoleUri: string,
size: { rows: number; cols: number },
): Promise<ConnectTerminalResponse> => {
const targetUri = consoleUri + `/terminals?cols=${size.cols}&rows=${size.rows}&version=2019-01-01&shell=bash`;
const resp = await fetch(targetUri, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Content-Length": "2",
Authorization: userContext.authorizationToken,
"x-ms-client-request-id": uuidv4(),
"Accept-Language": getLocale(),
},
body: "{}", // empty body is necessary
});
if (!resp.ok) {
throw new Error(`Failed to connect to terminal: ${resp.status} ${resp.statusText}`);
}
return resp.json();
};

View File

@ -0,0 +1,91 @@
export const enum OsType {
Linux = "linux",
Windows = "windows",
}
export const enum ShellType {
Bash = "bash",
PowerShellCore = "pwsh",
}
export const enum NetworkType {
Default = "Default",
Isolated = "Isolated",
}
/**
* Azure CloudShell session types:
* - Mounted: Sessions with persistent storage via an Azure File Share mount.
* Files and configurations are preserved between sessions, allowing for
* continuity of work across multiple CloudShell sessions.
*
* - Ephemeral: Temporary sessions without persistent storage.
* All files and changes are discarded when the session ends.
* These sessions start faster but don't retain user data.
*
* The session type affects resource allocation, startup time,
* and whether user files/configurations persist between sessions.
*/
export const enum SessionType {
Mounted = "Mounted",
Ephemeral = "Ephemeral",
}
export type CloudShellSettings = {
properties: UserSettingProperties;
};
export type UserSettingProperties = {
networkType: string;
preferredLocation: string;
preferredOsType: OsType;
preferredShellType: ShellType;
userSubscription: string;
sessionType: SessionType;
vnetSettings: object;
};
export type ProvisionConsoleResponse = {
properties: {
osType: OsType;
provisioningState: string;
uri: string;
};
};
export type Authorization = {
token: string;
};
export type ConnectTerminalResponse = {
id: string;
idleTimeout: string;
rootDirectory: string;
socketUri: string;
tokenUpdated: boolean;
};
export type ProviderAuthorization = {
applicationId: string;
roleDefinitionId: string;
};
export type ProviderResourceType = {
resourceType: string;
locations: string[];
apiVersions: string[];
defaultApiVersion?: string;
capabilities?: string;
};
export type RegistrationState = "Registered" | "NotRegistered" | "Registering" | "Unregistering";
export type RegistrationPolicy = "RegistrationRequired" | "RegistrationOptional";
export type CloudShellProviderInfo = {
id: string;
namespace: string;
authorizations?: ProviderAuthorization[];
resourceTypes: ProviderResourceType[];
registrationState: RegistrationState;
registrationPolicy: RegistrationPolicy;
};

View File

@ -0,0 +1,282 @@
# Migrate Mongo(RU/vCore)/Postgres/Cassandra shell to CloudShell Design
## CloudShell Overview
Cloud Shell provides an integrated terminal experience directly within Cosmos Explorer, allowing users to interact with different database engines using their native command-line interfaces.
## Component Architecture
```mermaid
classDiagram
class FeatureRegistration {
<<Registers a new flag for switching shell to CloudShell>>
+enableCloudShell: boolean
}
class ShellTypeHandlerFactory {
<<Initialize corresponding handler based on the type of shell>>
+getHandler(terminalKind: TerminalKind): ShellTypeHandler
+getKey(): string
}
class AbstractShellHandler {
<<interface>>
+getShellName(): string
+getSetUpCommands(): string[]
+getConnectionCommand(): string
+getEndpoint(): string
+getTerminalSuppressedData(): string[]
+getInitialCommands(): string
}
class CloudShellTerminalComponent {
<<React Component to Render CloudShell>>
-terminalKind: TerminalKind
-shellHandler: AbstractShellHandler
+render(): ReactElement
}
class CloudShellTerminalCore {
<<Initialize CloudShell>>
+startCloudShellTerminal()
}
class CloudShellClient {
<Initialize CloudShell APIs>
+getUserSettings(): Promise
+putEphemeralUserSettings(): void
+verifyCloudShellProviderRegistration: void
+registerCloudShellProvider(): void
+provisionConsole(): ProvisionConsoleResponse
+connectTerminal(): ConnectTerminalResponse
+authorizeSession(): Authorization
}
class CloudShellTerminalComponentAdapter {
+getDatabaseAccount: DataModels.DatabaseAccount,
+getTabId: string,
+getUsername: string,
+isAllPublicIPAddressesEnabled: ko.Observable<boolean>,
+kind: ViewModels.TerminalKind,
}
class TerminalTab {
-cloudShellTerminalComponentAdapter: CloudShellTerminalComponentAdapter
}
class ContextMenuButtonFactory {
+getCloudShellButton(): ReactElement
+isCloudShellEnabled(): boolean
}
UserContext --> FeatureRegistration : contains
FeatureRegistration ..> ContextMenuButtonFactory : controls UI visibility
FeatureRegistration ..> CloudShellTerminalComponentAdapter : enables tab creation
FeatureRegistration ..> CloudShellClient : permits API calls
TerminalTab --> CloudShellTerminalComponentAdapter : manages
ContextMenuButtonFactory --> TerminalTab : creates
TerminalTab --> CloudShellTerminalComponent : renders
CloudShellTerminalComponent --> CloudShellTerminalCore : contains
CloudShellTerminalComponent --> ShellTypeHandlerFactory : uses
CloudShellTerminalCore --> CloudShellClient : communicates with
CloudShellTerminalCore --> AbstractShellHandler : uses configuration from
ShellTypeHandlerFactory --> AbstractShellHandler : creates
class MongoShellHandler {
-key: string
+getShellName(): string
+getSetUpCommands(): string[]
+getConnectionCommand(): string
+getEndpoint(): string
+getTerminalSuppressedData(): string[]
+getInitialCommands(): string
class VCoreMongoShellHandler {
+getShellName(): string
+getSetUpCommands(): string[]
+getConnectionCommand(): string
+getEndpoint(): string
+getTerminalSuppressedData(): string[]
+getInitialCommands(): string
}
class CassandraShellHandler {
-key: string
+getShellName(): string
+getSetUpCommands(): string[]
+getConnectionCommand(): string
+getEndpoint(): string
+getTerminalSuppressedData(): string[]
+getInitialCommands(): string
}
class PostgresShellHandler {
+getShellName(): string
+getSetUpCommands(): string[]
+getConnectionCommand(): string
+getEndpoint(): string
+getTerminalSuppressedData(): string[]
+getInitialCommands(): string
}
AbstractShellHandler <|.. MongoShellHandler
AbstractShellHandler <|.. VCoreMongoShellHandler
AbstractShellHandler <|.. CassandraShellHandler
AbstractShellHandler <|.. PostgresShellHandler
```
## Changes
The CloudShell functionality is controlled by the feature flag `userContext.features.enableCloudShell`. When this flag is **enabled** (set to true), the following occurs in the application:
1. **UI Components Become Available:** There is "Open Mongo Shell" or similar button appears on data explorer or quick start window.
2. **Service Capabilities Are Activated:**
- Backend API calls to CloudShell services are permitted
- Terminal connection endpoints become accessible
3. **Database-Specific Features Are Unlocked:**
- Terminal experiences tailored to each database type become available
- Shell handlers are instantiated based on the database type
4. **Telemetry Collection Begins:**
- When CloudShell Starts
- User Consent to access shell out of the region
- When shell is connected
- When there is an error during CloudShell initialization
The feature can be enabled by putting `feature.enableCloudShell=true` in url.
When disabled, all CloudShell functionality is hidden and inaccessible, ensuring a consistent user experience regardless of the feature's state. These shell would be talking to tools federation.
## Supported Shell Types
| Terminal Kind | Handler Class | Description |
|---------------|--------------|-------------|
| Mongo | MongoShellHandler | Handles MongoDB RU shell connections |
| VCoreMongo | VCoreMongoShellHandler | Handles for VCore MongoDB shell connections |
| Cassandra | CassandraShellHandler | Handles Cassandra shell connections |
| Postgres | PostgresShellHandler | Handles PostgreSQL shell connections |
## Implementation Details
The CloudShell implementation uses the Factory pattern to create appropriate shell handlers based on the database type. Each handler implements the common interface but provides specialized behavior for connecting to different database engines.
### Key Components
1. **ShellTypeHandlerFactory**: Creates the appropriate handler based on terminal kind
- Retrieves authentication keys from Azure Resource Manager
- Instantiates specialized handlers with configuration
2. **ShellTypeHandler Interface i.e. AbstractShellHandler**: Defines the contract for all shell handlers
- `getConnectionCommand()`: Returns shell command to connect to database
- `getSetUpCommands()`: Returns list of scripts required to set up the environment
- `getEndpoint()`: Returns database connection end point
- `getTerminalSuppressedData()`: Returns a string which needs to be suppressed
3. **Specialized Handlers**: Implement specific connection logic for each database type
- Handle authentication differences
- Provide appropriate shell arguments
- Format connection strings correctly
4. **CloudShellTerminalComponent**: React component that renders the terminal interface
- Receives the terminal type as a property
- Uses ShellTypeHandlerFactory to get the appropriate handler
- Renders the CloudShellTerminalCore with the handler's configuration
- Manages component lifecycle and state
5. **CloudShellTerminalCore**: Core terminal implementation
- Handles low-level terminal operations
- Uses the configuration from ShellTypeHandler to initialize the terminal
- Manages input/output streams between the user interface and the shell process
- Handles terminal events (resize, data, etc.)
- Implements terminal UI and styling
6. **CloudShellClient**: Client for interacting with CloudShell backend services
- Initializes the terminal session with backend services
- Manages communication between the terminal UI and the backend shell process
- Handles authentication and security for the terminal session
7. **ContextMenuButtonFactory**: Creates CloudShell UI entry points
- Checks if CloudShell is enabled via `userContext.features.enableCloudShell`
- Generates appropriate terminal buttons based on database type
- Handles conditional rendering of CloudShell options
8. **TerminalTab**: Container component for terminal experiences
- Renders appropriate terminal type based on the selected database
- Manages terminal tab state and lifecycle
- Provides the integration point between the terminal and the rest of the Cosmos Explorer UI
## Telemetry Collection
CloudShell components utilize `TelemetryProcessor.trace` to collect usage data and diagnostics information that help improve the service and troubleshoot issues.
### Telemetry Events
- When CloudShell Starts
- User Consent to access shell out of the region
- When shell is connected
- When there is an error during CloudShell initialization
| Action Name | Description | Collected Data |
|------------|------------|----------------|
| CloudShellTerminalSession/Start | Triggered when user starts a CloudShell session | Shell Type, dataExplorerArea as <i>CloudShell</i>|
| CloudShellUserConsent/(Success/Failure) | Records user consent to get cloudshell in other region | |
| CloudShellTerminalSession/Success | Records if Terminal creation is successful | Shell Type, Shell Region |
| CloudShellTerminalSession/Failure | Records of terminal creation is failed | Shell Type, Shell region (if available), error message |
### Real-time Use Cases
1. **Performance Monitoring**:
- Track shell initialization times across different regions and database types
2. **Error Detection and Resolution**:
- Detect increased error rates in real-time
- Identify patterns in failures
- Correlate errors with specific client configurations
3. **Feature Adoption Analysis**:
- Measure adoption rates of different terminal types
4. **User Experience Optimization**:
- Analyze session duration to understand engagement
- Identify abandoned sessions and potential pain points
- Measure the impact of new features on usage patterns
- Track command completion rates and error recovery
## Limitations and Regional Availability
### Network Isolation
Network isolation (such as private endpoints, service endpoints, and VNet integration) is not currently supported for CloudShell connections. All connections to database instances through CloudShell require the database to be accessible through public endpoints.
Key limitations:
- Cannot connect to databases with public network access disabled
- No support for private link resources
- No integration with Azure Virtual Networks
- IP-based firewall rules must include CloudShell service IPs
### Data Residency
Data residency requirements may not be fully satisfied when using CloudShell due to limited regional availability. CloudShell services are currently available in the following regions:
| Geography | Regions |
|-----------|---------|
| Americas | East US, West US 2, South Central US, West Central US |
| Europe | West Europe, North Europe |
| Asia Pacific | Southeast Asia, Japan East, Australia East |
| Middle East | UAE North |
**Note:** For up-to-date supported regions, refer to the region configuration in:
`src/Explorer/CloudShell/Configuration/RegionConfig.ts`
### Implications for Compliance
Organizations with strict data residency or network isolation requirements should be aware of these limitations:
1. Data may transit through regions different from the database region
2. Terminal session data is processed in CloudShell regions, not necessarily the database region
3. Commands and queries are executed through CloudShell services, not directly against the database
4. Connection strings contain database endpoints and are processed by CloudShell services
These limitations are important considerations for workloads with specific compliance or regulatory requirements.

View File

@ -0,0 +1,96 @@
import { AbstractShellHandler, DISABLE_HISTORY, START_MARKER, EXIT_COMMAND } from "./AbstractShellHandler";
// Mock implementation for testing
class MockShellHandler extends AbstractShellHandler {
getShellName(): string {
return "MockShell";
}
getSetUpCommands(): string[] {
return ["setup-command-1", "setup-command-2"];
}
getConnectionCommand(): string {
return "mock-connection-command";
}
getEndpoint(): string {
return "mock-endpoint";
}
getTerminalSuppressedData(): string {
return "suppressed-data";
}
}
describe("AbstractShellHandler", () => {
let shellHandler: MockShellHandler;
// Reset all mocks and spies before each test
beforeEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
shellHandler = new MockShellHandler();
});
// Reset everything after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
// Cleanup after each test
afterEach(() => {
jest.clearAllMocks();
});
describe("getInitialCommands", () => {
it("should combine commands in the correct order", () => {
// Spy on abstract methods to ensure they're called
const getSetUpCommandsSpy = jest.spyOn(shellHandler, "getSetUpCommands");
const getConnectionCommandSpy = jest.spyOn(shellHandler, "getConnectionCommand");
const result = shellHandler.getInitialCommands();
// Verify abstract methods were called
expect(getSetUpCommandsSpy).toHaveBeenCalled();
expect(getConnectionCommandSpy).toHaveBeenCalled();
// Verify output format and content
const expectedOutput = [
START_MARKER,
DISABLE_HISTORY,
"setup-command-1",
"setup-command-2",
`{ mock-connection-command; } || true;${EXIT_COMMAND}`,
]
.join("\n")
.concat("\n");
expect(result).toBe(expectedOutput);
});
});
describe("abstract methods implementation", () => {
it("should return the correct shell name", () => {
expect(shellHandler.getShellName()).toBe("MockShell");
});
it("should return the setup commands", () => {
expect(shellHandler.getSetUpCommands()).toEqual(["setup-command-1", "setup-command-2"]);
});
it("should return the connection command", () => {
expect(shellHandler.getConnectionCommand()).toBe("mock-connection-command");
});
it("should return the endpoint", () => {
expect(shellHandler.getEndpoint()).toBe("mock-endpoint");
});
it("should return the terminal suppressed data", () => {
expect(shellHandler.getTerminalSuppressedData()).toBe("suppressed-data");
});
});
});

View File

@ -0,0 +1,59 @@
/**
* Command that serves as a marker to indicate the start of shell initialization.
* Outputs to /dev/null to prevent displaying in the terminal.
*/
export const START_MARKER = `echo "START INITIALIZATION" > /dev/null`;
/**
* Command to disable command history recording in the shell.
* Prevents initialization commands from appearing in history.
*/
export const DISABLE_HISTORY = `set +o history`;
/**
* Command that displays an error message and exits the shell session.
* Used when shell initialization or connection fails.
*/
export const EXIT_COMMAND = ` printf "\\033[1;31mSession ended. Please close this tab and initiate a new shell session if needed.\\033[0m\\n" && exit`;
/**
* Abstract class that defines the interface for shell-specific handlers
* in the CloudShell terminal implementation. Each supported shell type
* (Mongo, PG, etc.) should extend this class and implement
* the required methods.
*/
export abstract class AbstractShellHandler {
abstract getShellName(): string;
abstract getSetUpCommands(): string[];
abstract getConnectionCommand(): string;
abstract getTerminalSuppressedData(): string;
/**
* Constructs the complete initialization command sequence for the shell.
*
* This method:
* 1. Starts with the initialization marker
* 2. Disables command history
* 3. Adds shell-specific setup commands
* 4. Adds the connection command with error handling
* 5. Adds a fallback exit command if connection fails
*
* The connection command is wrapped in a construct that prevents
* errors from terminating the entire session immediately, allowing
* the friendly exit message to be displayed.
*
* @returns {string} Complete initialization command sequence with newlines
*/
public getInitialCommands(): string {
const setupCommands = this.getSetUpCommands();
const connectionCommand = this.getConnectionCommand();
const allCommands = [
START_MARKER,
DISABLE_HISTORY,
...setupCommands,
`{ ${connectionCommand}; } || true;${EXIT_COMMAND}`,
];
return allCommands.join("\n").concat("\n");
}
}

View File

@ -0,0 +1,148 @@
import * as CommonUtils from "../Utils/CommonUtils";
import { CassandraShellHandler } from "./CassandraShellHandler";
// Define interfaces for the database account structure
interface DatabaseAccountProperties {
cassandraEndpoint?: string;
}
interface DatabaseAccount {
name?: string;
properties?: DatabaseAccountProperties;
}
// Define mock state that can be modified by tests
const mockState = {
databaseAccount: {
name: "test-account",
properties: {
cassandraEndpoint: "https://test-endpoint.cassandra.cosmos.azure.com:443/",
},
} as DatabaseAccount,
};
// Mock dependencies using factory functions
jest.mock("../../../../UserContext", () => ({
get userContext() {
return {
get databaseAccount() {
return mockState.databaseAccount;
},
};
},
}));
// Reset all modules before running tests
beforeAll(() => {
jest.resetModules();
});
jest.mock("../Utils/CommonUtils", () => ({
getHostFromUrl: jest.fn().mockReturnValue("test-endpoint.cassandra.cosmos.azure.com"),
}));
describe("CassandraShellHandler", () => {
const testKey = "test-key";
let handler: CassandraShellHandler;
beforeEach(() => {
jest.clearAllMocks();
handler = new CassandraShellHandler(testKey);
// Reset mock state before each test
mockState.databaseAccount = {
name: "test-account",
properties: {
cassandraEndpoint: "https://test-endpoint.cassandra.cosmos.azure.com:443/",
},
};
});
// Clean up after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
describe("Positive test cases", () => {
test("should return 'Cassandra' as shell name", () => {
expect(handler.getShellName()).toBe("Cassandra");
});
test("should return an array of setup commands", () => {
const commands = handler.getSetUpCommands();
expect(Array.isArray(commands)).toBe(true);
expect(commands.length).toBe(5);
expect(commands).toContain("source ~/.bashrc");
expect(
commands.some((cmd) =>
cmd.includes("if ! command -v cqlsh &> /dev/null; then echo '⚠️ cqlsh not found. Installing...'; fi"),
),
).toBe(true);
expect(commands.some((cmd) => cmd.includes("pip3 install --user cqlsh==6.2.0"))).toBe(true);
expect(commands.some((cmd) => cmd.includes("export SSL_VERSION=TLSv1_2"))).toBe(true);
expect(commands.some((cmd) => cmd.includes("export SSL_VALIDATE=false"))).toBe(true);
});
test("should return correct connection command", () => {
const expectedCommand = "cqlsh test-endpoint.cassandra.cosmos.azure.com 10350 -u test-account -p test-key --ssl";
expect(handler.getConnectionCommand()).toBe(expectedCommand);
expect(CommonUtils.getHostFromUrl).toHaveBeenCalledWith("https://test-endpoint.cassandra.cosmos.azure.com:443/");
});
test("should return the correct terminal suppressed data", () => {
expect(handler.getTerminalSuppressedData()).toBe("");
});
test("should include the correct package version in setup commands", () => {
const commands = handler.getSetUpCommands();
const hasCorrectPackageVersion = commands.some((cmd) => cmd.includes("cqlsh==6.2.0"));
expect(hasCorrectPackageVersion).toBe(true);
});
});
describe("Negative test cases", () => {
test("should handle empty host from URL", () => {
(CommonUtils.getHostFromUrl as jest.Mock).mockReturnValueOnce("");
const command = handler.getConnectionCommand();
expect(command).toBe("cqlsh 10350 -u test-account -p test-key --ssl");
});
test("should handle empty key", () => {
const emptyKeyHandler = new CassandraShellHandler("");
expect(emptyKeyHandler.getConnectionCommand()).toBe(
"cqlsh test-endpoint.cassandra.cosmos.azure.com 10350 -u test-account -p --ssl",
);
});
test("should handle undefined account name", () => {
mockState.databaseAccount = {
properties: { cassandraEndpoint: "https://test-endpoint.cassandra.cosmos.azure.com:443/" },
};
expect(handler.getConnectionCommand()).toBe("echo 'Database name not found.'");
});
test("should handle undefined database account", () => {
mockState.databaseAccount = undefined;
expect(handler.getConnectionCommand()).toBe("echo 'Database name not found.'");
});
test("should handle missing cassandra endpoint", () => {
mockState.databaseAccount = {
name: "test-account",
properties: {},
};
expect(handler.getConnectionCommand()).toBe("echo 'Cassandra endpoint not found.'");
});
});
});

View File

@ -0,0 +1,47 @@
import { userContext } from "../../../../UserContext";
import { getHostFromUrl } from "../Utils/CommonUtils";
import { AbstractShellHandler } from "./AbstractShellHandler";
const PACKAGE_VERSION: string = "6.2.0";
export class CassandraShellHandler extends AbstractShellHandler {
private _key: string;
private _endpoint: string | undefined;
constructor(private key: string) {
super();
this._key = key;
this._endpoint = userContext?.databaseAccount?.properties?.cassandraEndpoint;
}
public getShellName(): string {
return "Cassandra";
}
public getSetUpCommands(): string[] {
return [
"if ! command -v cqlsh &> /dev/null; then echo '⚠️ cqlsh not found. Installing...'; fi",
`if ! command -v cqlsh &> /dev/null; then pip3 install --user cqlsh==${PACKAGE_VERSION} ; fi`,
"echo 'export SSL_VERSION=TLSv1_2' >> ~/.bashrc",
"echo 'export SSL_VALIDATE=false' >> ~/.bashrc",
"source ~/.bashrc",
];
}
public getConnectionCommand(): string {
if (!this._endpoint) {
return `echo '${this.getShellName()} endpoint not found.'`;
}
const dbName = userContext?.databaseAccount?.name;
if (!dbName) {
return "echo 'Database name not found.'";
}
return `cqlsh ${getHostFromUrl(this._endpoint)} 10350 -u ${dbName} -p ${this._key} --ssl`;
}
public getTerminalSuppressedData(): string {
return "";
}
}

View File

@ -0,0 +1,130 @@
import { userContext } from "../../../../UserContext";
import * as CommonUtils from "../Utils/CommonUtils";
import { MongoShellHandler } from "./MongoShellHandler";
// Define interfaces for type safety
interface DatabaseAccountProperties {
mongoEndpoint?: string;
}
interface DatabaseAccount {
id?: string;
name: string;
location?: string;
type?: string;
kind?: string;
properties: DatabaseAccountProperties;
}
interface UserContextType {
databaseAccount: DatabaseAccount;
}
// Mock dependencies
jest.mock("../../../../UserContext", () => ({
userContext: {
databaseAccount: {
name: "test-account",
properties: {
mongoEndpoint: "https://test-mongo.documents.azure.com:443/",
},
},
},
}));
jest.mock("../Utils/CommonUtils", () => ({
getHostFromUrl: jest.fn().mockReturnValue("test-mongo.documents.azure.com"),
}));
describe("MongoShellHandler", () => {
const testKey = "test-key";
let mongoShellHandler: MongoShellHandler;
beforeEach(() => {
mongoShellHandler = new MongoShellHandler(testKey);
jest.clearAllMocks();
});
// Clean up after each test
afterEach(() => {
jest.clearAllMocks();
});
// Clean up after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
describe("getShellName", () => {
it("should return MongoDB", () => {
expect(mongoShellHandler.getShellName()).toBe("MongoDB");
});
});
describe("getSetUpCommands", () => {
it("should return an array of setup commands", () => {
const commands = mongoShellHandler.getSetUpCommands();
expect(Array.isArray(commands)).toBe(true);
expect(commands.length).toBe(6);
expect(commands[1]).toContain("mongosh-2.5.0-linux-x64.tgz");
});
});
describe("getConnectionCommand", () => {
it("should return the correct connection command", () => {
// Save original databaseAccount
const originalDatabaseAccount = userContext.databaseAccount;
// Directly assign the modified databaseAccount
(userContext as UserContextType).databaseAccount = {
id: "test-id",
name: "test-account",
location: "test-location",
type: "test-type",
kind: "test-kind",
properties: { mongoEndpoint: "https://test-mongo.documents.azure.com:443/" },
};
const command = mongoShellHandler.getConnectionCommand();
expect(command).toBe(
"mongosh --host test-mongo.documents.azure.com --port 10255 --username test-account --password test-key --tls --tlsAllowInvalidCertificates",
);
expect(CommonUtils.getHostFromUrl).toHaveBeenCalledWith("https://test-mongo.documents.azure.com:443/");
// Restore original
(userContext as UserContextType).databaseAccount = originalDatabaseAccount;
});
it("should handle missing database account name", () => {
// Save original databaseAccount
const originalDatabaseAccount = userContext.databaseAccount;
// Directly assign the modified databaseAccount
(userContext as UserContextType).databaseAccount = {
id: "test-id",
name: "", // Empty name to simulate missing name
location: "test-location",
type: "test-type",
kind: "test-kind",
properties: { mongoEndpoint: "https://test.com" },
};
const command = mongoShellHandler.getConnectionCommand();
expect(command).toBe("echo 'Database name not found.'");
// Restore original
(userContext as UserContextType).databaseAccount = originalDatabaseAccount;
});
});
describe("getTerminalSuppressedData", () => {
it("should return the correct warning message", () => {
expect(mongoShellHandler.getTerminalSuppressedData()).toBe("Warning: Non-Genuine MongoDB Detected");
});
});
});

View File

@ -0,0 +1,48 @@
import { userContext } from "../../../../UserContext";
import { getHostFromUrl } from "../Utils/CommonUtils";
import { AbstractShellHandler } from "./AbstractShellHandler";
const PACKAGE_VERSION: string = "2.5.0";
export class MongoShellHandler extends AbstractShellHandler {
private _key: string;
private _endpoint: string | undefined;
constructor(private key: string) {
super();
this._key = key;
this._endpoint = userContext?.databaseAccount?.properties?.mongoEndpoint;
}
public getShellName(): string {
return "MongoDB";
}
public getSetUpCommands(): string[] {
return [
"if ! command -v mongosh &> /dev/null; then echo '⚠️ mongosh not found. Installing...'; fi",
`if ! command -v mongosh &> /dev/null; then curl -LO https://downloads.mongodb.com/compass/mongosh-${PACKAGE_VERSION}-linux-x64.tgz; fi`,
`if ! command -v mongosh &> /dev/null; then tar -xvzf mongosh-${PACKAGE_VERSION}-linux-x64.tgz; fi`,
`if ! command -v mongosh &> /dev/null; then mkdir -p ~/mongosh && mv mongosh-${PACKAGE_VERSION}-linux-x64/* ~/mongosh/; fi`,
"if ! command -v mongosh &> /dev/null; then echo 'export PATH=$HOME/mongosh/bin:$PATH' >> ~/.bashrc; fi",
"source ~/.bashrc",
];
}
public getConnectionCommand(): string {
if (!this._endpoint) {
return `echo '${this.getShellName()} endpoint not found.'`;
}
const dbName = userContext?.databaseAccount?.name;
if (!dbName) {
return "echo 'Database name not found.'";
}
return `mongosh --host ${getHostFromUrl(this._endpoint)} --port 10255 --username ${dbName} --password ${
this._key
} --tls --tlsAllowInvalidCertificates`;
}
public getTerminalSuppressedData(): string {
return "Warning: Non-Genuine MongoDB Detected";
}
}

View File

@ -0,0 +1,64 @@
import { PostgresShellHandler } from "./PostgresShellHandler";
// Mock dependencies
jest.mock("../../../../UserContext", () => ({
userContext: {
databaseAccount: {
properties: {
postgresqlEndpoint: "test-postgres.postgres.database.azure.com",
},
},
postgresConnectionStrParams: {
adminLogin: "test-admin",
},
},
}));
describe("PostgresShellHandler", () => {
let postgresShellHandler: PostgresShellHandler;
beforeEach(() => {
postgresShellHandler = new PostgresShellHandler();
jest.clearAllMocks();
});
// Clean up after each test
afterEach(() => {
jest.clearAllMocks();
});
// Clean up after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
// Positive test cases
describe("Positive Tests", () => {
it("should return correct shell name", () => {
expect(postgresShellHandler.getShellName()).toBe("PostgreSQL");
});
it("should return array of setup commands with correct package version", () => {
const commands = postgresShellHandler.getSetUpCommands();
expect(Array.isArray(commands)).toBe(true);
expect(commands.length).toBe(9);
expect(commands[1]).toContain("postgresql-15.2.tar.bz2");
expect(commands[0]).toContain("psql not found");
});
it("should generate proper connection command with endpoint", () => {
const connectionCommand = postgresShellHandler.getConnectionCommand();
expect(connectionCommand).toContain('-h "test-postgres.postgres.database.azure.com"');
expect(connectionCommand).toContain("-p 5432");
expect(connectionCommand).toContain("--set=sslmode=require");
});
it("should return empty string for terminal suppressed data", () => {
expect(postgresShellHandler.getTerminalSuppressedData()).toBe("");
});
});
});

View File

@ -0,0 +1,63 @@
import { userContext } from "../../../../UserContext";
import { AbstractShellHandler } from "./AbstractShellHandler";
const PACKAGE_VERSION: string = "15.2";
export class PostgresShellHandler extends AbstractShellHandler {
private _endpoint: string | undefined;
constructor() {
super();
this._endpoint = userContext?.databaseAccount?.properties?.postgresqlEndpoint;
}
public getShellName(): string {
return "PostgreSQL";
}
/**
* PostgreSQL setup commands for CloudShell:
*
* 1. Check if psql client is already installed
* 2. Download PostgreSQL source package if needed
* 3. Extract the PostgreSQL package
* 4. Create installation directory
* 5. Download and extract readline dependency
* 6. Configure readline with appropriate installation path
* 7. Add PostgreSQL binaries to system PATH
* 8. Apply PATH changes
*
* All installation steps run conditionally only if
* psql is not already available in the environment.
*/
public getSetUpCommands(): string[] {
return [
"if ! command -v psql &> /dev/null; then echo '⚠️ psql not found. Installing...'; fi",
`if ! command -v psql &> /dev/null; then curl -LO https://ftp.postgresql.org/pub/source/v${PACKAGE_VERSION}/postgresql-${PACKAGE_VERSION}.tar.bz2; fi`,
`if ! command -v psql &> /dev/null; then tar -xvjf postgresql-${PACKAGE_VERSION}.tar.bz2; fi`,
"if ! command -v psql &> /dev/null; then mkdir -p ~/pgsql; fi",
"if ! command -v psql &> /dev/null; then curl -LO https://ftp.gnu.org/gnu/readline/readline-8.1.tar.gz; fi",
"if ! command -v psql &> /dev/null; then tar -xvzf readline-8.1.tar.gz; fi",
"if ! command -v psql &> /dev/null; then cd readline-8.1 && ./configure --prefix=$HOME/pgsql; fi",
"if ! command -v psql &> /dev/null; then echo 'export PATH=$HOME/pgsql/bin:$PATH' >> ~/.bashrc; fi",
"source ~/.bashrc",
];
}
public getConnectionCommand(): string {
if (!this._endpoint) {
return `echo '${this.getShellName()} endpoint not found.'`;
}
// Database name is hardcoded as "citus" because Azure Cosmos DB for PostgreSQL
// uses Citus as its distributed database extension with this default database name.
// All Azure Cosmos DB PostgreSQL deployments follow this convention.
// Ref. https://learn.microsoft.com/en-us/azure/cosmos-db/postgresql/reference-limits#database-creation
const loginName = userContext.postgresConnectionStrParams.adminLogin;
return `psql -h "${this._endpoint}" -p 5432 -d "citus" -U "${loginName}" --set=sslmode=require`;
}
public getTerminalSuppressedData(): string {
return "";
}
}

View File

@ -0,0 +1,113 @@
import { TerminalKind } from "../../../../Contracts/ViewModels";
import { userContext } from "../../../../UserContext";
import { listKeys } from "../../../../Utils/arm/generatedClients/cosmos/databaseAccounts";
import { CassandraShellHandler } from "./CassandraShellHandler";
import { MongoShellHandler } from "./MongoShellHandler";
import { PostgresShellHandler } from "./PostgresShellHandler";
import { getHandler, getKey } from "./ShellTypeFactory";
import { VCoreMongoShellHandler } from "./VCoreMongoShellHandler";
// Mock dependencies
jest.mock("../../../../UserContext", () => ({
userContext: {
databaseAccount: { name: "testDbName" },
subscriptionId: "testSubId",
resourceGroup: "testResourceGroup",
},
}));
jest.mock("../../../../Utils/arm/generatedClients/cosmos/databaseAccounts", () => ({
listKeys: jest.fn(),
}));
describe("ShellTypeHandlerFactory", () => {
const mockKey = "testKey";
beforeEach(() => {
(listKeys as jest.Mock).mockResolvedValue({ primaryMasterKey: mockKey });
});
afterEach(() => {
jest.clearAllMocks();
});
// Clean up after each test
afterEach(() => {
jest.clearAllMocks();
});
// Clean up after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
// Negative test cases
describe("Negative test cases", () => {
it("should throw an error for unsupported terminal kind", async () => {
await expect(getHandler("UnsupportedKind" as unknown as TerminalKind)).rejects.toThrow(
"Unsupported shell type: UnsupportedKind",
);
});
it("should return empty string when database name is missing", async () => {
// Temporarily modify the mock
const originalName = userContext.databaseAccount.name;
type DatabaseAccountType = { name: string };
(userContext.databaseAccount as DatabaseAccountType).name = "";
const key = await getKey();
expect(key).toBe("");
expect(listKeys).not.toHaveBeenCalled();
// Restore the mock
(userContext.databaseAccount as DatabaseAccountType).name = originalName;
});
it("should return empty string when listKeys returns null", async () => {
(listKeys as jest.Mock).mockResolvedValue(null);
const key = await getKey();
expect(key).toBe("");
});
it("should return empty string when primaryMasterKey is missing", async () => {
(listKeys as jest.Mock).mockResolvedValue({
/* no primaryMasterKey */
});
const key = await getKey();
expect(key).toBe("");
});
});
// Positive test cases
describe("Positive test cases", () => {
it("should return PostgresShellHandler for Postgres terminal kind", async () => {
const handler = await getHandler(TerminalKind.Postgres);
expect(handler).toBeInstanceOf(PostgresShellHandler);
});
it("should return MongoShellHandler with key for Mongo terminal kind", async () => {
const handler = await getHandler(TerminalKind.Mongo);
expect(handler).toBeInstanceOf(MongoShellHandler);
});
it("should return VCoreMongoShellHandler for VCoreMongo terminal kind", async () => {
const handler = await getHandler(TerminalKind.VCoreMongo);
expect(handler).toBeInstanceOf(VCoreMongoShellHandler);
});
it("should return CassandraShellHandler with key for Cassandra terminal kind", async () => {
const handler = await getHandler(TerminalKind.Cassandra);
expect(handler).toBeInstanceOf(CassandraShellHandler);
});
it("should get key successfully when database name exists", async () => {
const key = await getKey();
expect(key).toBe(mockKey);
expect(listKeys).toHaveBeenCalledWith("testSubId", "testResourceGroup", "testDbName");
});
});
});

View File

@ -0,0 +1,36 @@
import { TerminalKind } from "../../../../Contracts/ViewModels";
import { userContext } from "../../../../UserContext";
import { listKeys } from "../../../../Utils/arm/generatedClients/cosmos/databaseAccounts";
import { AbstractShellHandler } from "./AbstractShellHandler";
import { CassandraShellHandler } from "./CassandraShellHandler";
import { MongoShellHandler } from "./MongoShellHandler";
import { PostgresShellHandler } from "./PostgresShellHandler";
import { VCoreMongoShellHandler } from "./VCoreMongoShellHandler";
/**
* Gets the appropriate handler for the given shell type
*/
export async function getHandler(shellType: TerminalKind): Promise<AbstractShellHandler> {
switch (shellType) {
case TerminalKind.Postgres:
return new PostgresShellHandler();
case TerminalKind.Mongo:
return new MongoShellHandler(await getKey());
case TerminalKind.VCoreMongo:
return new VCoreMongoShellHandler();
case TerminalKind.Cassandra:
return new CassandraShellHandler(await getKey());
default:
throw new Error(`Unsupported shell type: ${shellType}`);
}
}
export async function getKey(): Promise<string> {
const dbName = userContext.databaseAccount.name;
if (!dbName) {
return "";
}
const keys = await listKeys(userContext.subscriptionId, userContext.resourceGroup, dbName);
return keys?.primaryMasterKey || "";
}

View File

@ -0,0 +1,63 @@
import { VCoreMongoShellHandler } from "./VCoreMongoShellHandler";
// Mock dependencies
jest.mock("../../../../UserContext", () => ({
userContext: {
databaseAccount: {
properties: {
vcoreMongoEndpoint: "test-vcore-mongo.mongo.cosmos.azure.com",
},
},
vcoreMongoConnectionParams: {
adminLogin: "username",
},
},
}));
describe("VCoreMongoShellHandler", () => {
let vcoreMongoShellHandler: VCoreMongoShellHandler;
beforeEach(() => {
vcoreMongoShellHandler = new VCoreMongoShellHandler();
jest.clearAllMocks();
});
// Clean up after each test
afterEach(() => {
jest.clearAllMocks();
});
// Clean up after all tests
afterAll(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
jest.resetModules();
});
// Positive test cases
describe("Positive Tests", () => {
it("should return correct shell name", () => {
expect(vcoreMongoShellHandler.getShellName()).toBe("MongoDB VCore");
});
it("should return array of setup commands with correct package version", () => {
const commands = vcoreMongoShellHandler.getSetUpCommands();
expect(Array.isArray(commands)).toBe(true);
expect(commands.length).toBe(6);
expect(commands[1]).toContain("mongosh-2.5.0-linux-x64.tgz");
expect(commands[0]).toContain("mongosh not found");
});
it("should generate proper connection command with endpoint", () => {
const connectionCommand = vcoreMongoShellHandler.getConnectionCommand();
expect(connectionCommand).toContain("mongodb+srv://username:@test-vcore-mongo.mongo.cosmos.azure.com");
expect(connectionCommand).toContain("authMechanism=SCRAM-SHA-256");
});
it("should return the correct terminal suppressed data", () => {
expect(vcoreMongoShellHandler.getTerminalSuppressedData()).toBe("Warning: Non-Genuine MongoDB Detected");
});
});
});

View File

@ -0,0 +1,54 @@
import { userContext } from "../../../../UserContext";
import { AbstractShellHandler } from "./AbstractShellHandler";
const PACKAGE_VERSION: string = "2.5.0";
export class VCoreMongoShellHandler extends AbstractShellHandler {
private _endpoint: string | undefined;
constructor() {
super();
this._endpoint = userContext?.databaseAccount?.properties?.vcoreMongoEndpoint;
}
public getShellName(): string {
return "MongoDB VCore";
}
/**
* Setup commands for MongoDB VCore shell:
*
* 1. Check if mongosh is already installed
* 2. Download mongosh package if not installed
* 3. Extract the package to access mongosh binaries
* 4. Move extracted files to ~/mongosh directory
* 5. Add mongosh binary path to system PATH
* 6. Apply PATH changes by sourcing .bashrc
*
* Each command runs conditionally only if mongosh
* is not already present in the environment.
*/
public getSetUpCommands(): string[] {
return [
"if ! command -v mongosh &> /dev/null; then echo '⚠️ mongosh not found. Installing...'; fi",
`if ! command -v mongosh &> /dev/null; then curl -LO https://downloads.mongodb.com/compass/mongosh-${PACKAGE_VERSION}-linux-x64.tgz; fi`,
`if ! command -v mongosh &> /dev/null; then tar -xvzf mongosh-${PACKAGE_VERSION}-linux-x64.tgz; fi`,
`if ! command -v mongosh &> /dev/null; then mkdir -p ~/mongosh && mv mongosh-${PACKAGE_VERSION}-linux-x64/* ~/mongosh/; fi`,
"if ! command -v mongosh &> /dev/null; then echo 'export PATH=$HOME/mongosh/bin:$PATH' >> ~/.bashrc; fi",
"source ~/.bashrc",
];
}
public getConnectionCommand(): string {
if (!this._endpoint) {
return `echo '${this.getShellName()} endpoint not found.'`;
}
const userName = userContext.vcoreMongoConnectionParams.adminLogin;
return `mongosh "mongodb+srv://${userName}:@${this._endpoint}/?authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"`;
}
public getTerminalSuppressedData(): string {
return "Warning: Non-Genuine MongoDB Detected";
}
}

View File

@ -0,0 +1,207 @@
import { AbstractShellHandler } from "Explorer/Tabs/CloudShellTab/ShellTypes/AbstractShellHandler";
import { IDisposable, ITerminalAddon, Terminal } from "@xterm/xterm";
interface IAttachOptions {
bidirectional?: boolean;
startMarker?: string;
shellHandler?: AbstractShellHandler;
}
/**
* Terminal addon that attaches a terminal to a WebSocket for bidirectional
* communication with Azure CloudShell.
*
* Features:
* - Manages bidirectional data flow between terminal and CloudShell WebSocket
* - Processes special status messages within the data stream
* - Controls terminal output display during shell initialization
* - Supports shell-specific customizations via AbstractShellHandler
*
* @implements {ITerminalAddon}
*/
export class AttachAddon implements ITerminalAddon {
private _socket: WebSocket;
private _bidirectional: boolean;
private _disposables: IDisposable[] = [];
private _socketData: string;
private _allowTerminalWrite: boolean = true;
private _startMarker: string;
private _shellHandler: AbstractShellHandler;
constructor(socket: WebSocket, options?: IAttachOptions) {
this._socket = socket;
// always set binary type to arraybuffer, we do not handle blobs
this._socket.binaryType = "arraybuffer";
this._bidirectional = !(options && options.bidirectional === false);
this._startMarker = options?.startMarker;
this._shellHandler = options?.shellHandler;
this._socketData = "";
this._allowTerminalWrite = true;
}
/**
* Activates the addon with the provided terminal
*
* Sets up event listeners for terminal input and WebSocket messages.
* Links the terminal input to the WebSocket and vice versa.
*
* @param {Terminal} terminal - The XTerm terminal instance
*/
public activate(terminal: Terminal): void {
this.addMessageListener(terminal);
if (this._bidirectional) {
this._disposables.push(terminal.onData((data) => this._sendData(data)));
this._disposables.push(terminal.onBinary((data) => this._sendBinary(data)));
}
this._disposables.push(addSocketListener(this._socket, "close", () => this.dispose()));
this._disposables.push(addSocketListener(this._socket, "error", () => this.dispose()));
}
/**
* Adds a message listener to process data from the WebSocket
*
* Handles:
* - Status message extraction (between ie_us and ie_ue markers)
* - Partial message accumulation
* - Shell initialization messages
* - Suppression of unwanted shell output
*
* @param {Terminal} terminal - The XTerm terminal instance
*/
public addMessageListener(terminal: Terminal): void {
this._disposables.push(
addSocketListener(this._socket, "message", (ev) => {
let data: ArrayBuffer | string = ev.data;
const startStatusJson = "ie_us";
const endStatusJson = "ie_ue";
if (typeof data === "object") {
const enc = new TextDecoder("utf-8");
data = enc.decode(ev.data as ArrayBuffer);
}
// for example of json object look in TerminalHelper in the socket.onMessage
if (data.includes(startStatusJson) && data.includes(endStatusJson)) {
// process as one line
const statusData = data.split(startStatusJson)[1].split(endStatusJson)[0];
data = data.replace(statusData, "");
data = data.replace(startStatusJson, "");
data = data.replace(endStatusJson, "");
} else if (data.includes(startStatusJson)) {
// check for start
const partialStatusData = data.split(startStatusJson)[1];
this._socketData += partialStatusData;
data = data.replace(partialStatusData, "");
data = data.replace(startStatusJson, "");
} else if (data.includes(endStatusJson)) {
// check for end and process the command
const partialStatusData = data.split(endStatusJson)[0];
this._socketData += partialStatusData;
data = data.replace(partialStatusData, "");
data = data.replace(endStatusJson, "");
this._socketData = "";
} else if (this._socketData.length > 0) {
// check if the line is all data then just concatenate
this._socketData += data;
data = "";
}
if (this._allowTerminalWrite && data.includes(this._startMarker)) {
this._allowTerminalWrite = false;
terminal.write(`Preparing ${this._shellHandler.getShellName()} environment...\r\n`);
}
if (this._allowTerminalWrite) {
const suppressedData = this._shellHandler?.getTerminalSuppressedData();
const hasSuppressedData = suppressedData && suppressedData.length > 0;
if (!hasSuppressedData || !data.includes(suppressedData)) {
terminal.write(data);
}
}
if (data.includes(this._shellHandler.getConnectionCommand())) {
this._allowTerminalWrite = true;
}
}),
);
}
public dispose(): void {
for (const d of this._disposables) {
d.dispose();
}
}
/**
* Sends string data from the terminal to the WebSocket
*
* @param {string} data - The data to send
*/
private _sendData(data: string): void {
if (!this._checkOpenSocket()) {
return;
}
this._socket.send(data);
}
/**
* Sends binary data from the terminal to the WebSocket
*
* @param {string} data - The string data to convert to binary and send
*/
private _sendBinary(data: string): void {
if (!this._checkOpenSocket()) {
return;
}
const buffer = new Uint8Array(data.length);
for (let i = 0; i < data.length; ++i) {
buffer[i] = data.charCodeAt(i) & 255;
}
this._socket.send(buffer);
}
private _checkOpenSocket(): boolean {
switch (this._socket.readyState) {
case WebSocket.OPEN:
return true;
case WebSocket.CONNECTING:
throw new Error("Attach addon was loaded before socket was open");
case WebSocket.CLOSING:
return false;
case WebSocket.CLOSED:
throw new Error("Attach addon socket is closed");
default:
throw new Error("Unexpected socket state");
}
}
}
/**
* Adds an event listener to a WebSocket and returns a disposable object
* for cleanup
*
* @param {WebSocket} socket - The WebSocket instance
* @param {K} type - The event type to listen for
* @param {Function} handler - The event handler function
* @returns {IDisposable} An object with a dispose method to remove the listener
*/
function addSocketListener<K extends keyof WebSocketEventMap>(
socket: WebSocket,
type: K,
handler: (this: WebSocket, ev: WebSocketEventMap[K]) => void,
): IDisposable {
socket.addEventListener(type, handler);
return {
dispose: () => {
if (!handler) {
// Already disposed
return;
}
socket.removeEventListener(type, handler);
},
};
}

View File

@ -0,0 +1,52 @@
import { Terminal } from "@xterm/xterm";
import { TerminalKind } from "../../../../Contracts/ViewModels";
/**
* Utility function to wait for a specified duration
*/
export const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
/**
* Extract host from a URL
*/
export const getHostFromUrl = (url: string): string => {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch (error) {
console.error("Invalid URL:", error);
return "";
}
};
export const askConfirmation = async (terminal: Terminal, question: string): Promise<boolean> => {
terminal.writeln(`\n${question} (Y/N)`);
terminal.focus();
return new Promise<boolean>((resolve) => {
const keyListener = terminal.onKey(({ key }: { key: string }) => {
keyListener.dispose();
terminal.writeln(key);
return resolve(key.toLowerCase() === "y");
});
});
};
/**
* Gets the current locale for API requests
*/
export const getLocale = (): string => {
const langLocale = navigator.language;
return langLocale && langLocale.length > 2 ? langLocale : "en-us";
};
export const getShellNameForDisplay = (terminalKind: TerminalKind): string => {
switch (terminalKind) {
case TerminalKind.Postgres:
return "PostgreSQL";
case TerminalKind.Mongo:
case TerminalKind.VCoreMongo:
return "MongoDB";
default:
return "";
}
};

View File

@ -0,0 +1,48 @@
// Check this list for regional availability https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/table
const validCloudShellRegions = new Set([
"westus",
"southcentralus",
"eastus",
"northeurope",
"westeurope",
"centralindia",
"southeastasia",
"westcentralus",
]);
/**
* Normalizes a region name to ensure compatibility with Azure CloudShell.
*
* Azure CloudShell is only available in specific regions. This function:
* 1. Maps certain regions to their CloudShell-supported equivalents (e.g., centralus westcentralus)
* 2. Validates if the region is supported by CloudShell
* 3. Falls back to the default region if the provided region is unsupported
*
* This ensures users can connect to CloudShell even when their database is in a region
* where CloudShell isn't directly available, by routing to the nearest supported region.
*
* @param region - The source region (typically from the user's database account location)
* @param defaultCloudshellRegion - Fallback region to use if the provided region is not supported
* @returns A valid CloudShell region name that's as close as possible to the requested region
*
* @example
* // Returns "westcentralus" (mapped region)
* getNormalizedRegion("centralus", "westus")
*
* @example
* // Returns "westus" (default region) since "antarctica" isn't supported
* getNormalizedRegion("antarctica", "westus")
*/
export const getNormalizedRegion = (region: string, defaultCloudshellRegion: string) => {
if (!region) {
return defaultCloudshellRegion;
}
const regionMap: Record<string, string> = {
centralus: "westcentralus",
eastus2: "eastus",
};
const normalizedRegion = regionMap[region.toLowerCase()] || region;
return validCloudShellRegions.has(normalizedRegion.toLowerCase()) ? normalizedRegion : defaultCloudshellRegion;
};

View File

@ -0,0 +1,39 @@
// This file contains utility functions and constants for formatting terminal messages in a cloud shell environment.
// It includes ANSI escape codes for colors and functions to format messages for different log levels (info, success, warning, error).
export const TERMINAL_COLORS = {
RESET: "\x1b[0m",
BRIGHT: "\x1b[1m",
DIM: "\x1b[2m",
BLACK: "\x1b[30m",
RED: "\x1b[31m",
GREEN: "\x1b[32m",
YELLOW: "\x1b[33m",
BLUE: "\x1b[34m",
MAGENTA: "\x1b[35m",
CYAN: "\x1b[36m",
WHITE: "\x1b[37m",
BG_BLACK: "\x1b[40m",
BG_RED: "\x1b[41m",
BG_GREEN: "\x1b[42m",
BG_YELLOW: "\x1b[43m",
BG_BLUE: "\x1b[44m",
BG_MAGENTA: "\x1b[45m",
BG_CYAN: "\x1b[46m",
BG_WHITE: "\x1b[47m",
};
export const START_MARKER = `echo "START INITIALIZATION" > /dev/null`;
export const END_MARKER = `echo "END INITIALIZATION" > /dev/null`;
// Terminal message formatting functions
export const formatInfoMessage = (message: string): string =>
`${TERMINAL_COLORS.BRIGHT}${TERMINAL_COLORS.CYAN}${message}${TERMINAL_COLORS.RESET}`;
export const formatSuccessMessage = (message: string): string =>
`${TERMINAL_COLORS.BRIGHT}${TERMINAL_COLORS.GREEN}${message}${TERMINAL_COLORS.RESET}`;
export const formatWarningMessage = (message: string): string =>
`${TERMINAL_COLORS.BRIGHT}${TERMINAL_COLORS.YELLOW}${message}${TERMINAL_COLORS.RESET}`;
export const formatErrorMessage = (message: string): string =>
`${TERMINAL_COLORS.BRIGHT}${TERMINAL_COLORS.RED}${message}${TERMINAL_COLORS.RESET}`;

View File

@ -0,0 +1,62 @@
import { Spinner, SpinnerSize } from "@fluentui/react";
import { MessageTypes } from "Contracts/ExplorerContracts";
import { QuickstartFirewallNotification } from "Explorer/Quickstart/QuickstartFirewallNotification";
import { getShellNameForDisplay } from "Explorer/Tabs/CloudShellTab/Utils/CommonUtils";
import * as React from "react";
import FirewallRuleScreenshot from "../../../../images/firewallRule.png";
import VcoreFirewallRuleScreenshot from "../../../../images/vcoreMongoFirewallRule.png";
import { ReactAdapter } from "../../../Bindings/ReactBindingHandler";
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
/**
* Base terminal component adapter
*/
export abstract class BaseTerminalComponentAdapter implements ReactAdapter {
// parameters: true: show, false: hide
public parameters: ko.Computed<boolean>;
constructor(
protected getDatabaseAccount: () => DataModels.DatabaseAccount,
protected getTabId: () => string,
protected getUsername: () => string,
protected isAllPublicIPAddressesEnabled: ko.Observable<boolean>,
protected kind: ViewModels.TerminalKind,
) {}
public renderComponent(): JSX.Element {
if (!this.isAllPublicIPAddressesEnabled()) {
return (
<QuickstartFirewallNotification
messageType={this.getMessageType()}
screenshot={
this.kind === ViewModels.TerminalKind.Mongo || this.kind === ViewModels.TerminalKind.VCoreMongo
? VcoreFirewallRuleScreenshot
: FirewallRuleScreenshot
}
shellName={getShellNameForDisplay(this.kind)}
/>
);
}
return this.parameters() ? (
this.renderTerminalComponent()
) : (
<Spinner styles={{ root: { marginTop: 10 } }} size={SpinnerSize.large}></Spinner>
);
}
private getMessageType(): MessageTypes {
switch (this.kind) {
case ViewModels.TerminalKind.Postgres:
return MessageTypes.OpenPostgresNetworkingBlade;
case ViewModels.TerminalKind.Mongo:
case ViewModels.TerminalKind.VCoreMongo:
return MessageTypes.OpenVCoreMongoNetworkingBlade;
default:
return MessageTypes.OpenPostgresNetworkingBlade;
}
}
protected abstract renderTerminalComponent(): JSX.Element;
}

View File

@ -0,0 +1,19 @@
import { CloudShellTerminalComponent } from "Explorer/Tabs/CloudShellTab/CloudShellTerminalComponent";
import * as React from "react";
import { BaseTerminalComponentAdapter } from "./BaseTerminalComponentAdapter";
/**
* CloudShell terminal tab
*/
export class CloudShellTerminalComponentAdapter extends BaseTerminalComponentAdapter {
protected renderTerminalComponent(): JSX.Element {
return (
<CloudShellTerminalComponent
databaseAccount={this.getDatabaseAccount()}
tabId={this.getTabId()}
shellType={this.kind}
username={this.getUsername()}
/>
);
}
}

View File

@ -0,0 +1,32 @@
import { NotebookTerminalComponent } from "Explorer/Controls/Notebook/NotebookTerminalComponent";
import * as React from "react";
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
import { BaseTerminalComponentAdapter } from "./BaseTerminalComponentAdapter";
/**
* Notebook terminal tab
*/
export class NotebookTerminalComponentAdapter extends BaseTerminalComponentAdapter {
constructor(
private getNotebookServerInfo: () => DataModels.NotebookWorkspaceConnectionInfo,
getDatabaseAccount: () => DataModels.DatabaseAccount,
getTabId: () => string,
getUsername: () => string,
isAllPublicIPAddressesEnabled: ko.Observable<boolean>,
kind: ViewModels.TerminalKind,
) {
super(getDatabaseAccount, getTabId, getUsername, isAllPublicIPAddressesEnabled, kind);
}
protected renderTerminalComponent(): JSX.Element {
return (
<NotebookTerminalComponent
notebookServerInfo={this.getNotebookServerInfo()}
databaseAccount={this.getDatabaseAccount()}
tabId={this.getTabId()}
username={this.getUsername()}
/>
);
}
}

View File

@ -1,19 +1,14 @@
import { Spinner, SpinnerSize } from "@fluentui/react";
import { MessageTypes } from "Contracts/ExplorerContracts";
import { QuickstartFirewallNotification } from "Explorer/Quickstart/QuickstartFirewallNotification";
import { checkFirewallRules } from "Explorer/Tabs/Shared/CheckFirewallRules";
import { CloudShellTerminalComponentAdapter } from "Explorer/Tabs/ShellAdapters/CloudShellTerminalComponentAdapter";
import * as ko from "knockout";
import * as React from "react";
import FirewallRuleScreenshot from "../../../images/firewallRule.png";
import VcoreFirewallRuleScreenshot from "../../../images/vcoreMongoFirewallRule.png";
import { ReactAdapter } from "../../Bindings/ReactBindingHandler";
import * as DataModels from "../../Contracts/DataModels";
import * as ViewModels from "../../Contracts/ViewModels";
import { userContext } from "../../UserContext";
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
import { NotebookTerminalComponent } from "../Controls/Notebook/NotebookTerminalComponent";
import Explorer from "../Explorer";
import { useNotebook } from "../Notebook/useNotebook";
import { NotebookTerminalComponentAdapter } from "./ShellAdapters/NotebookTerminalComponentAdapter";
import TabsBase from "./TabsBase";
export interface TerminalTabOptions extends ViewModels.TabOptions {
@ -23,90 +18,52 @@ export interface TerminalTabOptions extends ViewModels.TabOptions {
username?: string;
}
/**
* Notebook terminal tab
*/
class NotebookTerminalComponentAdapter implements ReactAdapter {
// parameters: true: show, false: hide
public parameters: ko.Computed<boolean>;
constructor(
private getNotebookServerInfo: () => DataModels.NotebookWorkspaceConnectionInfo,
private getDatabaseAccount: () => DataModels.DatabaseAccount,
private getTabId: () => string,
private getUsername: () => string,
private isAllPublicIPAddressesEnabled: ko.Observable<boolean>,
private kind: ViewModels.TerminalKind,
) {}
public renderComponent(): JSX.Element {
if (!this.isAllPublicIPAddressesEnabled()) {
return (
<QuickstartFirewallNotification
messageType={MessageTypes.OpenPostgresNetworkingBlade}
screenshot={
this.kind === ViewModels.TerminalKind.Mongo || this.kind === ViewModels.TerminalKind.VCoreMongo
? VcoreFirewallRuleScreenshot
: FirewallRuleScreenshot
}
shellName={this.getShellNameForDisplay(this.kind)}
/>
);
}
return this.parameters() ? (
<NotebookTerminalComponent
notebookServerInfo={this.getNotebookServerInfo()}
databaseAccount={this.getDatabaseAccount()}
tabId={this.getTabId()}
username={this.getUsername()}
/>
) : (
<Spinner styles={{ root: { marginTop: 10 } }} size={SpinnerSize.large}></Spinner>
);
}
private getShellNameForDisplay(terminalKind: ViewModels.TerminalKind): string {
switch (terminalKind) {
case ViewModels.TerminalKind.Postgres:
return "PostgreSQL";
case ViewModels.TerminalKind.Mongo:
case ViewModels.TerminalKind.VCoreMongo:
return "MongoDB";
default:
return "";
}
}
}
export default class TerminalTab extends TabsBase {
public readonly html = '<div style="height: 100%" data-bind="react:notebookTerminalComponentAdapter"></div> ';
private container: Explorer;
private notebookTerminalComponentAdapter: NotebookTerminalComponentAdapter;
private notebookTerminalComponentAdapter: ReactAdapter;
private isAllPublicIPAddressesEnabled: ko.Observable<boolean>;
constructor(options: TerminalTabOptions) {
super(options);
this.container = options.container;
this.isAllPublicIPAddressesEnabled = ko.observable(true);
this.notebookTerminalComponentAdapter = new NotebookTerminalComponentAdapter(
() => this.getNotebookServerInfo(options),
const commonArgs: [
() => DataModels.DatabaseAccount,
() => string,
() => string,
ko.Observable<boolean>,
ViewModels.TerminalKind,
] = [
() => userContext?.databaseAccount,
() => this.tabId,
() => this.getUsername(),
this.isAllPublicIPAddressesEnabled,
options.kind,
);
this.notebookTerminalComponentAdapter.parameters = ko.computed<boolean>(() => {
if (
this.isTemplateReady() &&
useNotebook.getState().isNotebookEnabled &&
useNotebook.getState().notebookServerInfo?.notebookServerEndpoint &&
this.isAllPublicIPAddressesEnabled()
) {
return true;
}
return false;
});
];
if (userContext.features.enableCloudShell) {
this.notebookTerminalComponentAdapter = new CloudShellTerminalComponentAdapter(...commonArgs);
this.notebookTerminalComponentAdapter.parameters = ko.computed<boolean>(() => {
return this.isTemplateReady() && this.isAllPublicIPAddressesEnabled();
});
} else {
this.notebookTerminalComponentAdapter = new NotebookTerminalComponentAdapter(
() => this.getNotebookServerInfo(options),
...commonArgs,
);
this.notebookTerminalComponentAdapter.parameters = ko.computed<boolean>(() => {
return (
this.isTemplateReady() &&
useNotebook.getState().isNotebookEnabled &&
useNotebook.getState().notebookServerInfo?.notebookServerEndpoint &&
this.isAllPublicIPAddressesEnabled()
);
});
}
if (options.kind === ViewModels.TerminalKind.Postgres) {
checkFirewallRules(

View File

@ -39,6 +39,7 @@ export type Features = {
readonly copilotChatFixedMonacoEditorHeight: boolean;
readonly enablePriorityBasedExecution: boolean;
readonly disableConnectionStringLogin: boolean;
readonly enableCloudShell: boolean;
// can be set via both flight and feature flag
autoscaleDefault: boolean;
@ -110,6 +111,7 @@ export function extractFeatures(given = new URLSearchParams(window.location.sear
copilotChatFixedMonacoEditorHeight: "true" === get("copilotchatfixedmonacoeditorheight"),
enablePriorityBasedExecution: "true" === get("enableprioritybasedexecution"),
disableConnectionStringLogin: "true" === get("disableconnectionstringlogin"),
enableCloudShell: "true" === get("enablecloudshell"),
};
}

View File

@ -89,6 +89,7 @@ export enum Action {
PhoenixDBAccountAllowed,
DeleteCellFromMenu,
OpenTerminal,
OpenCloudShellTerminal,
CreateMongoCollectionWithWildcardIndex,
ClickCommandBarButton,
RefreshResourceTreeMyNotebooks,
@ -146,6 +147,8 @@ export enum Action {
SavePersistedTabState,
DeletePersistedTabState,
UploadDocuments, // Used in Fabric. Please do not rename.
CloudShellUserConsent,
CloudShellTerminalSession,
}
export const ActionModifiers = {

View File

@ -47,6 +47,7 @@ interface Options {
body?: unknown;
queryParams?: ARMQueryParams;
contentType?: string;
customHeaders?: Record<string, string>;
}
export async function armRequestWithoutPolling<T>({
@ -57,6 +58,7 @@ export async function armRequestWithoutPolling<T>({
body: requestBody,
queryParams,
contentType,
customHeaders,
}: Options): Promise<{ result: T; operationStatusUrl: string }> {
const url = new URL(path, host);
url.searchParams.append("api-version", configContext.armAPIVersion || apiVersion);
@ -65,18 +67,22 @@ export async function armRequestWithoutPolling<T>({
queryParams.metricNames && url.searchParams.append("metricnames", queryParams.metricNames);
}
if (!userContext.authorizationToken) {
if (!userContext?.authorizationToken && !customHeaders?.["Authorization"]) {
throw new Error("No authority token provided");
}
const headers: Record<string, string> = {
Authorization: userContext.authorizationToken || customHeaders?.["Authorization"] || "",
[HttpHeaders.contentType]: contentType || "application/json",
...(customHeaders || {}),
};
const response = await window.fetch(url.href, {
method,
headers: {
Authorization: userContext.authorizationToken,
[HttpHeaders.contentType]: contentType || "application/json",
},
headers,
body: requestBody ? JSON.stringify(requestBody) : undefined,
});
if (!response.ok) {
let error: ARMError;
try {
@ -109,6 +115,7 @@ export async function armRequest<T>({
body: requestBody,
queryParams,
contentType,
customHeaders,
}: Options): Promise<T> {
const armRequestResult = await armRequestWithoutPolling<T>({
host,
@ -118,6 +125,7 @@ export async function armRequest<T>({
body: requestBody,
queryParams,
contentType,
customHeaders,
});
const operationStatusUrl = armRequestResult.operationStatusUrl;
if (operationStatusUrl) {