Update Api end points and add brs for allowlist (#1161)

* Update Api end points and add brs for allowlist
This commit is contained in:
Karthik chakravarthy 2021-12-13 09:23:33 -05:00 committed by GitHub
parent 469cd866e0
commit b327bfd0d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 130 additions and 195 deletions

View File

@ -1,3 +1,4 @@
{ {
"JUNO_ENDPOINT": "https://tools-staging.cosmos.azure.com" "JUNO_ENDPOINT": "https://tools-staging.cosmos.azure.com",
"isTerminalEnabled" : true
} }

View File

@ -1,3 +1,4 @@
{ {
"JUNO_ENDPOINT": "https://tools.cosmos.azure.com" "JUNO_ENDPOINT": "https://tools.cosmos.azure.com",
"isTerminalEnabled" : false
} }

View File

@ -27,6 +27,7 @@ export interface ConfigContext {
GITHUB_CLIENT_ID: string; GITHUB_CLIENT_ID: string;
GITHUB_TEST_ENV_CLIENT_ID: string; GITHUB_TEST_ENV_CLIENT_ID: string;
GITHUB_CLIENT_SECRET?: string; // No need to inject secret for prod. Juno already knows it. GITHUB_CLIENT_SECRET?: string; // No need to inject secret for prod. Juno already knows it.
isTerminalEnabled: boolean;
hostedExplorerURL: string; hostedExplorerURL: string;
armAPIVersion?: string; armAPIVersion?: string;
allowedJunoOrigins: string[]; allowedJunoOrigins: string[];
@ -59,6 +60,7 @@ let configContext: Readonly<ConfigContext> = {
GITHUB_TEST_ENV_CLIENT_ID: "b63fc8cbf87fd3c6e2eb", // Registered OAuth app: https://github.com/organizations/AzureCosmosDBNotebooks/settings/applications/1777772 GITHUB_TEST_ENV_CLIENT_ID: "b63fc8cbf87fd3c6e2eb", // Registered OAuth app: https://github.com/organizations/AzureCosmosDBNotebooks/settings/applications/1777772
JUNO_ENDPOINT: "https://tools.cosmos.azure.com", JUNO_ENDPOINT: "https://tools.cosmos.azure.com",
BACKEND_ENDPOINT: "https://main.documentdb.ext.azure.com", BACKEND_ENDPOINT: "https://main.documentdb.ext.azure.com",
isTerminalEnabled: false,
allowedJunoOrigins: [ allowedJunoOrigins: [
JunoEndpoints.Test, JunoEndpoints.Test,
JunoEndpoints.Test2, JunoEndpoints.Test2,

View File

@ -438,14 +438,10 @@ export interface ContainerInfo {
} }
export interface IProvisionData { export interface IProvisionData {
subscriptionId: string;
resourceGroup: string;
dbAccountName: string;
cosmosEndpoint: string; cosmosEndpoint: string;
} }
export interface IContainerData { export interface IContainerData {
dbAccountName: string;
forwardingId: string; forwardingId: string;
} }

View File

@ -17,7 +17,6 @@ import Explorer from "../../Explorer";
import { NotebookClientV2 } from "../../Notebook/NotebookClientV2"; import { NotebookClientV2 } from "../../Notebook/NotebookClientV2";
import { NotebookComponentBootstrapper } from "../../Notebook/NotebookComponent/NotebookComponentBootstrapper"; import { NotebookComponentBootstrapper } from "../../Notebook/NotebookComponent/NotebookComponentBootstrapper";
import NotebookReadOnlyRenderer from "../../Notebook/NotebookRenderer/NotebookReadOnlyRenderer"; import NotebookReadOnlyRenderer from "../../Notebook/NotebookRenderer/NotebookReadOnlyRenderer";
import { NotebookUtil } from "../../Notebook/NotebookUtil";
import { useNotebook } from "../../Notebook/useNotebook"; import { useNotebook } from "../../Notebook/useNotebook";
import { Dialog, TextFieldProps, useDialog } from "../Dialog"; import { Dialog, TextFieldProps, useDialog } from "../Dialog";
import { NotebookMetadataComponent } from "./NotebookMetadataComponent"; import { NotebookMetadataComponent } from "./NotebookMetadataComponent";
@ -148,9 +147,7 @@ export class NotebookViewerComponent
<NotebookMetadataComponent <NotebookMetadataComponent
data={this.state.galleryItem} data={this.state.galleryItem}
isFavorite={this.state.isFavorite} isFavorite={this.state.isFavorite}
downloadButtonText={ downloadButtonText={this.props.container && `Download to ${useNotebook.getState().notebookFolderName}`}
this.props.container && NotebookUtil.getNotebookBtnTitle(useNotebook.getState().notebookFolderName)
}
onTagClick={this.props.onTagClick} onTagClick={this.props.onTagClick}
onFavoriteClick={this.favoriteItem} onFavoriteClick={this.favoriteItem}
onUnfavoriteClick={this.unfavoriteItem} onUnfavoriteClick={this.unfavoriteItem}

View File

@ -14,7 +14,12 @@ import { getErrorMessage, getErrorStack, handleError } from "../Common/ErrorHand
import * as Logger from "../Common/Logger"; import * as Logger from "../Common/Logger";
import { QueriesClient } from "../Common/QueriesClient"; import { QueriesClient } from "../Common/QueriesClient";
import * as DataModels from "../Contracts/DataModels"; import * as DataModels from "../Contracts/DataModels";
import { ContainerConnectionInfo, IPhoenixConnectionInfoResult, IResponse } from "../Contracts/DataModels"; import {
ContainerConnectionInfo,
IPhoenixConnectionInfoResult,
IProvisionData,
IResponse,
} from "../Contracts/DataModels";
import * as ViewModels from "../Contracts/ViewModels"; import * as ViewModels from "../Contracts/ViewModels";
import { GitHubOAuthService } from "../GitHub/GitHubOAuthService"; import { GitHubOAuthService } from "../GitHub/GitHubOAuthService";
import { useSidePanel } from "../hooks/useSidePanel"; import { useSidePanel } from "../hooks/useSidePanel";
@ -30,7 +35,6 @@ import { update } from "../Utils/arm/generatedClients/cosmos/databaseAccounts";
import { import {
get as getWorkspace, get as getWorkspace,
listByDatabaseAccount, listByDatabaseAccount,
listConnectionInfo,
start, start,
} from "../Utils/arm/generatedClients/cosmosNotebooks/notebookWorkspaces"; } from "../Utils/arm/generatedClients/cosmosNotebooks/notebookWorkspaces";
import { stringToBlob } from "../Utils/BlobUtils"; import { stringToBlob } from "../Utils/BlobUtils";
@ -352,24 +356,7 @@ export default class Explorer {
return; return;
} }
this._isInitializingNotebooks = true; this._isInitializingNotebooks = true;
if (userContext.features.phoenix === false) {
await this.ensureNotebookWorkspaceRunning();
const connectionInfo = await listConnectionInfo(
userContext.subscriptionId,
userContext.resourceGroup,
databaseAccount.name,
"default"
);
useNotebook.getState().setNotebookServerInfo({
notebookServerEndpoint: userContext.features.notebookServerUrl || connectionInfo.notebookServerEndpoint,
authToken: userContext.features.notebookServerToken || connectionInfo.authToken,
forwardingId: undefined,
});
}
this.refreshNotebookList(); this.refreshNotebookList();
this._isInitializingNotebooks = false; this._isInitializingNotebooks = false;
} }
@ -381,10 +368,7 @@ export default class Explorer {
(notebookServerInfo === undefined || (notebookServerInfo === undefined ||
(notebookServerInfo && notebookServerInfo.notebookServerEndpoint === undefined)) (notebookServerInfo && notebookServerInfo.notebookServerEndpoint === undefined))
) { ) {
const provisionData = { const provisionData: IProvisionData = {
subscriptionId: userContext.subscriptionId,
resourceGroup: userContext.resourceGroup,
dbAccountName: userContext.databaseAccount.name,
cosmosEndpoint: userContext.databaseAccount.properties.documentEndpoint, cosmosEndpoint: userContext.databaseAccount.properties.documentEndpoint,
}; };
const connectionStatus: ContainerConnectionInfo = { const connectionStatus: ContainerConnectionInfo = {
@ -455,7 +439,7 @@ export default class Explorer {
); );
return; return;
} }
const dialogContent = NotebookUtil.isPhoenixEnabled() const dialogContent = useNotebook.getState().isPhoenix
? "Notebooks saved in the temporary workspace will be deleted. Do you want to proceed?" ? "Notebooks saved in the temporary workspace will be deleted. Do you want to proceed?"
: "This lets you keep your notebook files and the workspace will be restored to default. Proceed anyway?"; : "This lets you keep your notebook files and the workspace will be restored to default. Proceed anyway?";
@ -532,7 +516,7 @@ export default class Explorer {
TelemetryProcessor.traceStart(Action.PhoenixResetWorkspace, { TelemetryProcessor.traceStart(Action.PhoenixResetWorkspace, {
dataExplorerArea: Areas.Notebook, dataExplorerArea: Areas.Notebook,
}); });
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
useTabs.getState().closeAllNotebookTabs(true); useTabs.getState().closeAllNotebookTabs(true);
connectionStatus = { connectionStatus = {
status: ConnectionStatusType.Connecting, status: ConnectionStatusType.Connecting,
@ -546,7 +530,7 @@ export default class Explorer {
if (!connectionInfo?.data?.notebookServerUrl) { if (!connectionInfo?.data?.notebookServerUrl) {
throw new Error(`Reset Workspace: NotebookServerUrl is invalid!`); throw new Error(`Reset Workspace: NotebookServerUrl is invalid!`);
} }
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
await this.setNotebookInfo(connectionInfo, connectionStatus); await this.setNotebookInfo(connectionInfo, connectionStatus);
useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed); useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed);
} }
@ -561,7 +545,7 @@ export default class Explorer {
error: getErrorMessage(error), error: getErrorMessage(error),
errorStack: getErrorStack(error), errorStack: getErrorStack(error),
}); });
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
connectionStatus = { connectionStatus = {
status: ConnectionStatusType.Failed, status: ConnectionStatusType.Failed,
}; };
@ -759,7 +743,7 @@ export default class Explorer {
if (!notebookContentItem || !notebookContentItem.path) { if (!notebookContentItem || !notebookContentItem.path) {
throw new Error(`Invalid notebookContentItem: ${notebookContentItem}`); throw new Error(`Invalid notebookContentItem: ${notebookContentItem}`);
} }
if (notebookContentItem.type === NotebookContentItemType.Notebook && NotebookUtil.isPhoenixEnabled()) { if (notebookContentItem.type === NotebookContentItemType.Notebook && useNotebook.getState().isPhoenix) {
await this.allocateContainer(); await this.allocateContainer();
} }
@ -983,8 +967,7 @@ export default class Explorer {
handleError(error, "Explorer/onNewNotebookClicked"); handleError(error, "Explorer/onNewNotebookClicked");
throw new Error(error); throw new Error(error);
} }
const isPhoenixEnabled = NotebookUtil.isPhoenixEnabled(); if (useNotebook.getState().isPhoenix) {
if (isPhoenixEnabled) {
if (isGithubTree) { if (isGithubTree) {
await this.allocateContainer(); await this.allocateContainer();
parent = parent || this.resourceTree.myNotebooksContentRoot; parent = parent || this.resourceTree.myNotebooksContentRoot;
@ -1073,7 +1056,7 @@ export default class Explorer {
} }
public async openNotebookTerminal(kind: ViewModels.TerminalKind): Promise<void> { public async openNotebookTerminal(kind: ViewModels.TerminalKind): Promise<void> {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
await this.allocateContainer(); await this.allocateContainer();
const notebookServerInfo = useNotebook.getState().notebookServerInfo; const notebookServerInfo = useNotebook.getState().notebookServerInfo;
if (notebookServerInfo && notebookServerInfo.notebookServerEndpoint !== undefined) { if (notebookServerInfo && notebookServerInfo.notebookServerEndpoint !== undefined) {
@ -1214,7 +1197,7 @@ export default class Explorer {
} }
public async handleOpenFileAction(path: string): Promise<void> { public async handleOpenFileAction(path: string): Promise<void> {
if (userContext.features.phoenix) { if (useNotebook.getState().isPhoenix) {
await this.allocateContainer(); await this.allocateContainer();
} else if (!(await this._containsDefaultNotebookWorkspace(userContext.databaseAccount))) { } else if (!(await this._containsDefaultNotebookWorkspace(userContext.databaseAccount))) {
this._openSetupNotebooksPaneForQuickstart(); this._openSetupNotebooksPaneForQuickstart();
@ -1248,7 +1231,7 @@ export default class Explorer {
} }
public openUploadFilePanel(parent?: NotebookContentItem): void { public openUploadFilePanel(parent?: NotebookContentItem): void {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
useDialog.getState().showOkCancelModalDialog( useDialog.getState().showOkCancelModalDialog(
Notebook.newNotebookUploadModalTitle, Notebook.newNotebookUploadModalTitle,
undefined, undefined,
@ -1278,7 +1261,7 @@ export default class Explorer {
} }
public getDownloadModalConent(fileName: string): JSX.Element { public getDownloadModalConent(fileName: string): JSX.Element {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
return ( return (
<> <>
<p>{Notebook.galleryNotebookDownloadContent1}</p> <p>{Notebook.galleryNotebookDownloadContent1}</p>
@ -1302,22 +1285,17 @@ export default class Explorer {
await useNotebook.getState().refreshNotebooksEnabledStateForAccount(); await useNotebook.getState().refreshNotebooksEnabledStateForAccount();
// TODO: remove reference to isNotebookEnabled and isNotebooksEnabledForAccount // TODO: remove reference to isNotebookEnabled and isNotebooksEnabledForAccount
const isNotebookEnabled = userContext.features.notebooksDownBanner || userContext.features.phoenix; const isNotebookEnabled = userContext.features.notebooksDownBanner || useNotebook.getState().isPhoenix;
useNotebook.getState().setIsNotebookEnabled(isNotebookEnabled); useNotebook.getState().setIsNotebookEnabled(isNotebookEnabled);
useNotebook.getState().setIsShellEnabled(userContext.features.phoenix && isPublicInternetAccessAllowed()); useNotebook.getState().setIsShellEnabled(useNotebook.getState().isPhoenix && isPublicInternetAccessAllowed());
TelemetryProcessor.trace(Action.NotebookEnabled, ActionModifiers.Mark, { TelemetryProcessor.trace(Action.NotebookEnabled, ActionModifiers.Mark, {
isNotebookEnabled, isNotebookEnabled,
dataExplorerArea: Constants.Areas.Notebook, dataExplorerArea: Constants.Areas.Notebook,
}); });
if (!userContext.features.notebooksTemporarilyDown) { if (useNotebook.getState().isPhoenix) {
if (isNotebookEnabled) { await this.initNotebooks(userContext.databaseAccount);
await this.initNotebooks(userContext.databaseAccount);
} else if (this.notebookToImport) {
// if notebooks is not enabled but the user is trying to do a quickstart setup with notebooks, open the SetupNotebooksPane
this._openSetupNotebooksPaneForQuickstart();
}
} }
} }
} }

View File

@ -4,15 +4,12 @@
* and update any knockout observables passed from the parent. * and update any knockout observables passed from the parent.
*/ */
import { CommandBar as FluentCommandBar, ICommandBarItemProps } from "@fluentui/react"; import { CommandBar as FluentCommandBar, ICommandBarItemProps } from "@fluentui/react";
import { useNotebook } from "Explorer/Notebook/useNotebook";
import * as React from "react"; import * as React from "react";
import create, { UseStore } from "zustand"; import create, { UseStore } from "zustand";
import { StyleConstants } from "../../../Common/Constants"; import { StyleConstants } from "../../../Common/Constants";
import * as ViewModels from "../../../Contracts/ViewModels";
import { useTabs } from "../../../hooks/useTabs";
import { userContext } from "../../../UserContext";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent"; import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
import Explorer from "../../Explorer"; import Explorer from "../../Explorer";
import { NotebookUtil } from "../../Notebook/NotebookUtil";
import { useSelectedNode } from "../../useSelectedNode"; import { useSelectedNode } from "../../useSelectedNode";
import * as CommandBarComponentButtonFactory from "./CommandBarComponentButtonFactory"; import * as CommandBarComponentButtonFactory from "./CommandBarComponentButtonFactory";
import * as CommandBarUtil from "./CommandBarUtil"; import * as CommandBarUtil from "./CommandBarUtil";
@ -56,18 +53,10 @@ export const CommandBar: React.FC<Props> = ({ container }: Props) => {
const uiFabricControlButtons = CommandBarUtil.convertButton(controlButtons, backgroundColor); const uiFabricControlButtons = CommandBarUtil.convertButton(controlButtons, backgroundColor);
uiFabricControlButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true)); uiFabricControlButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true));
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
uiFabricControlButtons.unshift(CommandBarUtil.createConnectionStatus(container, "connectionStatus")); uiFabricControlButtons.unshift(CommandBarUtil.createConnectionStatus(container, "connectionStatus"));
} }
if (
userContext.features.phoenix === false &&
userContext.features.notebooksTemporarilyDown === false &&
useTabs.getState().activeTab?.tabKind === ViewModels.CollectionTabKind.NotebookV2
) {
uiFabricControlButtons.unshift(CommandBarUtil.createMemoryTracker("memoryTracker"));
}
return ( return (
<div className="commandBarContainer"> <div className="commandBarContainer">
<FluentCommandBar <FluentCommandBar

View File

@ -78,8 +78,9 @@ export function createStaticCommandBarButtons(
if (container.notebookManager?.gitHubOAuthService) { if (container.notebookManager?.gitHubOAuthService) {
notebookButtons.push(createManageGitHubAccountButton(container)); notebookButtons.push(createManageGitHubAccountButton(container));
} }
if (useNotebook.getState().isPhoenix && configContext.isTerminalEnabled) {
notebookButtons.push(createOpenTerminalButton(container)); notebookButtons.push(createOpenTerminalButton(container));
}
if (selectedNodeState.isConnectedToContainer()) { if (selectedNodeState.isConnectedToContainer()) {
notebookButtons.push(createNotebookWorkspaceResetButton(container)); notebookButtons.push(createNotebookWorkspaceResetButton(container));
} }

View File

@ -8,17 +8,10 @@ import { ConnectionStatusType, HttpHeaders, HttpStatusCodes, Notebook } from "..
import { getErrorMessage } from "../../Common/ErrorHandlingUtils"; import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
import * as Logger from "../../Common/Logger"; import * as Logger from "../../Common/Logger";
import * as DataModels from "../../Contracts/DataModels"; import * as DataModels from "../../Contracts/DataModels";
import { import { IPhoenixConnectionInfoResult, IProvisionData, IResponse } from "../../Contracts/DataModels";
ContainerConnectionInfo,
IPhoenixConnectionInfoResult,
IProvisionData,
IResponse,
} from "../../Contracts/DataModels";
import { userContext } from "../../UserContext"; import { userContext } from "../../UserContext";
import { createOrUpdate, destroy } from "../../Utils/arm/generatedClients/cosmosNotebooks/notebookWorkspaces";
import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils"; import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils"; import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import { NotebookUtil } from "./NotebookUtil";
import { useNotebook } from "./useNotebook"; import { useNotebook } from "./useNotebook";
export class NotebookContainerClient { export class NotebookContainerClient {
@ -55,21 +48,11 @@ export class NotebookContainerClient {
*/ */
private scheduleHeartbeat(delayMs: number): void { private scheduleHeartbeat(delayMs: number): void {
setTimeout(async () => { setTimeout(async () => {
try { const memoryUsageInfo = await this.getMemoryUsage();
const memoryUsageInfo = await this.getMemoryUsage(); useNotebook.getState().setMemoryUsageInfo(memoryUsageInfo);
useNotebook.getState().setMemoryUsageInfo(memoryUsageInfo); const notebookServerInfo = useNotebook.getState().notebookServerInfo;
const notebookServerInfo = useNotebook.getState().notebookServerInfo; if (notebookServerInfo?.notebookServerEndpoint) {
if (notebookServerInfo?.notebookServerEndpoint) { this.scheduleHeartbeat(Constants.Notebook.heartbeatDelayMs);
this.scheduleHeartbeat(Constants.Notebook.heartbeatDelayMs);
}
} catch (exception) {
if (NotebookUtil.isPhoenixEnabled()) {
const connectionStatus: ContainerConnectionInfo = {
status: ConnectionStatusType.Failed,
};
useNotebook.getState().resetContainerConnection(connectionStatus);
useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed);
}
} }
}, delayMs); }, delayMs);
} }
@ -108,7 +91,7 @@ export class NotebookContainerClient {
notebookServerEndpoint: string, notebookServerEndpoint: string,
authToken: string authToken: string
): Promise<DataModels.MemoryUsageInfo> { ): Promise<DataModels.MemoryUsageInfo> {
if (this.checkStatus()) { if (this.shouldExecuteMemoryCall()) {
const response = await fetch(`${notebookServerEndpoint}api/metrics/memory`, { const response = await fetch(`${notebookServerEndpoint}api/metrics/memory`, {
method: "GET", method: "GET",
headers: { headers: {
@ -131,24 +114,17 @@ export class NotebookContainerClient {
} else if (response.status === HttpStatusCodes.NotFound) { } else if (response.status === HttpStatusCodes.NotFound) {
throw new AbortError(response.statusText); throw new AbortError(response.statusText);
} }
throw new Error(); throw new Error(response.statusText);
} else { } else {
return undefined; return undefined;
} }
} }
private checkStatus(): boolean { private shouldExecuteMemoryCall(): boolean {
if (NotebookUtil.isPhoenixEnabled()) { return (
if (useNotebook.getState().containerStatus?.status === Constants.ContainerStatusType.Disconnected) { useNotebook.getState().containerStatus?.status === Constants.ContainerStatusType.Active &&
const connectionStatus: ContainerConnectionInfo = { useNotebook.getState().connectionInfo?.status === ConnectionStatusType.Connected
status: ConnectionStatusType.Reconnect, );
};
useNotebook.getState().resetContainerConnection(connectionStatus);
useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed);
return false;
}
}
return true;
} }
public async resetWorkspace(): Promise<IResponse<IPhoenixConnectionInfoResult>> { public async resetWorkspace(): Promise<IResponse<IPhoenixConnectionInfoResult>> {
@ -173,11 +149,8 @@ export class NotebookContainerClient {
} }
try { try {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
const provisionData: IProvisionData = { const provisionData: IProvisionData = {
subscriptionId: userContext.subscriptionId,
resourceGroup: userContext.resourceGroup,
dbAccountName: userContext.databaseAccount.name,
cosmosEndpoint: userContext.databaseAccount.properties.documentEndpoint, cosmosEndpoint: userContext.databaseAccount.properties.documentEndpoint,
}; };
return await this.phoenixClient.resetContainer(provisionData); return await this.phoenixClient.resetContainer(provisionData);
@ -185,9 +158,6 @@ export class NotebookContainerClient {
return null; return null;
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "NotebookContainerClient/resetWorkspace"); Logger.logError(getErrorMessage(error), "NotebookContainerClient/resetWorkspace");
if (!NotebookUtil.isPhoenixEnabled()) {
await this.recreateNotebookWorkspaceAsync();
}
throw error; throw error;
} }
} }
@ -202,25 +172,6 @@ export class NotebookContainerClient {
}; };
} }
private async recreateNotebookWorkspaceAsync(): Promise<void> {
const { databaseAccount } = userContext;
if (!databaseAccount?.id) {
throw new Error("DataExplorer not initialized");
}
try {
await destroy(userContext.subscriptionId, userContext.resourceGroup, userContext.databaseAccount.name, "default");
await createOrUpdate(
userContext.subscriptionId,
userContext.resourceGroup,
userContext.databaseAccount.name,
"default"
);
} catch (error) {
Logger.logError(getErrorMessage(error), "NotebookContainerClient/recreateNotebookWorkspaceAsync");
return Promise.reject(error);
}
}
private getHeaders(): HeadersInit { private getHeaders(): HeadersInit {
const authorizationHeader = getAuthorizationHeader(); const authorizationHeader = getAuthorizationHeader();
return { return {

View File

@ -3,7 +3,6 @@ import { AppState, selectors } from "@nteract/core";
import domtoimage from "dom-to-image"; import domtoimage from "dom-to-image";
import Html2Canvas from "html2canvas"; import Html2Canvas from "html2canvas";
import path from "path"; import path from "path";
import { userContext } from "../../UserContext";
import * as GitHubUtils from "../../Utils/GitHubUtils"; import * as GitHubUtils from "../../Utils/GitHubUtils";
import * as StringUtils from "../../Utils/StringUtils"; import * as StringUtils from "../../Utils/StringUtils";
import { SnapshotFragment } from "./NotebookComponent/types"; import { SnapshotFragment } from "./NotebookComponent/types";
@ -329,16 +328,4 @@ export class NotebookUtil {
link.click(); link.click();
document.body.removeChild(link); document.body.removeChild(link);
} }
public static getNotebookBtnTitle(fileName: string): string {
if (this.isPhoenixEnabled()) {
return `Download to ${fileName}`;
} else {
return `Download to my notebooks`;
}
}
public static isPhoenixEnabled(): boolean {
return userContext.features.notebooksTemporarilyDown === false && userContext.features.phoenix === true;
}
} }

View File

@ -1,4 +1,5 @@
import { cloneDeep } from "lodash"; import { cloneDeep } from "lodash";
import { PhoenixClient } from "Phoenix/PhoenixClient";
import create, { UseStore } from "zustand"; import create, { UseStore } from "zustand";
import { AuthType } from "../../AuthType"; import { AuthType } from "../../AuthType";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
@ -17,7 +18,6 @@ import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils";
import * as GitHubUtils from "../../Utils/GitHubUtils"; import * as GitHubUtils from "../../Utils/GitHubUtils";
import { NotebookContentItem, NotebookContentItemType } from "./NotebookContentItem"; import { NotebookContentItem, NotebookContentItemType } from "./NotebookContentItem";
import NotebookManager from "./NotebookManager"; import NotebookManager from "./NotebookManager";
import { NotebookUtil } from "./NotebookUtil";
interface NotebookState { interface NotebookState {
isNotebookEnabled: boolean; isNotebookEnabled: boolean;
@ -37,6 +37,7 @@ interface NotebookState {
isAllocating: boolean; isAllocating: boolean;
isRefreshed: boolean; isRefreshed: boolean;
containerStatus: ContainerInfo; containerStatus: ContainerInfo;
isPhoenix: boolean;
setIsNotebookEnabled: (isNotebookEnabled: boolean) => void; setIsNotebookEnabled: (isNotebookEnabled: boolean) => void;
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => void; setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => void;
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) => void; setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) => void;
@ -58,6 +59,8 @@ interface NotebookState {
resetContainerConnection: (connectionStatus: ContainerConnectionInfo) => void; resetContainerConnection: (connectionStatus: ContainerConnectionInfo) => void;
setIsRefreshed: (isAllocating: boolean) => void; setIsRefreshed: (isAllocating: boolean) => void;
setContainerStatus: (containerStatus: ContainerInfo) => void; setContainerStatus: (containerStatus: ContainerInfo) => void;
getPhoenixStatus: () => Promise<void>;
setIsPhoenix: (isPhoenix: boolean) => void;
} }
export const useNotebook: UseStore<NotebookState> = create((set, get) => ({ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
@ -92,6 +95,7 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
durationLeftInMinutes: undefined, durationLeftInMinutes: undefined,
notebookServerInfo: undefined, notebookServerInfo: undefined,
}, },
isPhoenix: undefined,
setIsNotebookEnabled: (isNotebookEnabled: boolean) => set({ isNotebookEnabled }), setIsNotebookEnabled: (isNotebookEnabled: boolean) => set({ isNotebookEnabled }),
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => set({ isNotebooksEnabledForAccount }), setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => set({ isNotebooksEnabledForAccount }),
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) => setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) =>
@ -104,6 +108,7 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
setNotebookBasePath: (notebookBasePath: string) => set({ notebookBasePath }), setNotebookBasePath: (notebookBasePath: string) => set({ notebookBasePath }),
setNotebookFolderName: (notebookFolderName: string) => set({ notebookFolderName }), setNotebookFolderName: (notebookFolderName: string) => set({ notebookFolderName }),
refreshNotebooksEnabledStateForAccount: async (): Promise<void> => { refreshNotebooksEnabledStateForAccount: async (): Promise<void> => {
await get().getPhoenixStatus();
const { databaseAccount, authType } = userContext; const { databaseAccount, authType } = userContext;
if ( if (
authType === AuthType.EncryptedToken || authType === AuthType.EncryptedToken ||
@ -196,7 +201,7 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
isGithubTree ? set({ gitHubNotebooksContentRoot: root }) : set({ myNotebooksContentRoot: root }); isGithubTree ? set({ gitHubNotebooksContentRoot: root }) : set({ myNotebooksContentRoot: root });
}, },
initializeNotebooksTree: async (notebookManager: NotebookManager): Promise<void> => { initializeNotebooksTree: async (notebookManager: NotebookManager): Promise<void> => {
const notebookFolderName = NotebookUtil.isPhoenixEnabled() === true ? "Temporary Notebooks" : "My Notebooks"; const notebookFolderName = get().isPhoenix ? "Temporary Notebooks" : "My Notebooks";
set({ notebookFolderName }); set({ notebookFolderName });
const myNotebooksContentRoot = { const myNotebooksContentRoot = {
name: get().notebookFolderName, name: get().notebookFolderName,
@ -292,4 +297,15 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
}, },
setIsRefreshed: (isRefreshed: boolean) => set({ isRefreshed }), setIsRefreshed: (isRefreshed: boolean) => set({ isRefreshed }),
setContainerStatus: (containerStatus: ContainerInfo) => set({ containerStatus }), setContainerStatus: (containerStatus: ContainerInfo) => set({ containerStatus }),
getPhoenixStatus: async () => {
if (get().isPhoenix === undefined) {
let isPhoenix = false;
if (userContext.features.phoenix) {
const phoenixClient = new PhoenixClient();
isPhoenix = await phoenixClient.isDbAcountWhitelisted();
}
set({ isPhoenix });
}
},
setIsPhoenix: (isPhoenix: boolean) => set({ isPhoenix }),
})); }));

View File

@ -5,7 +5,6 @@ import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils
import { GitHubOAuthService } from "../../../GitHub/GitHubOAuthService"; import { GitHubOAuthService } from "../../../GitHub/GitHubOAuthService";
import { useSidePanel } from "../../../hooks/useSidePanel"; import { useSidePanel } from "../../../hooks/useSidePanel";
import { IPinnedRepo, JunoClient } from "../../../Juno/JunoClient"; import { IPinnedRepo, JunoClient } from "../../../Juno/JunoClient";
import { userContext } from "../../../UserContext";
import * as GitHubUtils from "../../../Utils/GitHubUtils"; import * as GitHubUtils from "../../../Utils/GitHubUtils";
import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils";
import Explorer from "../../Explorer"; import Explorer from "../../Explorer";
@ -76,7 +75,7 @@ export const CopyNotebookPane: FunctionComponent<CopyNotebookPanelProps> = ({
selectedLocation.owner, selectedLocation.owner,
selectedLocation.repo selectedLocation.repo
)} - ${selectedLocation.branch}`; )} - ${selectedLocation.branch}`;
} else if (selectedLocation.type === "MyNotebooks" && userContext.features.phoenix) { } else if (selectedLocation.type === "MyNotebooks" && useNotebook.getState().isPhoenix) {
destination = useNotebook.getState().notebookFolderName; destination = useNotebook.getState().notebookFolderName;
} }

View File

@ -84,9 +84,7 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
const mainItems = this.createMainItems(); const mainItems = this.createMainItems();
const commonTaskItems = this.createCommonTaskItems(); const commonTaskItems = this.createCommonTaskItems();
let recentItems = this.createRecentItems(); let recentItems = this.createRecentItems();
if (userContext.features.notebooksTemporarilyDown) { recentItems = recentItems.filter((item) => item.description !== "Notebook");
recentItems = recentItems.filter((item) => item.description !== "Notebook");
}
const tipsItems = this.createTipsItems(); const tipsItems = this.createTipsItems();
const onClearRecent = this.clearMostRecent; const onClearRecent = this.clearMostRecent;

View File

@ -1,5 +1,5 @@
import { Resource, StoredProcedureDefinition, TriggerDefinition, UserDefinedFunctionDefinition } from "@azure/cosmos"; import { Resource, StoredProcedureDefinition, TriggerDefinition, UserDefinedFunctionDefinition } from "@azure/cosmos";
import { NotebookUtil } from "Explorer/Notebook/NotebookUtil"; import { useNotebook } from "Explorer/Notebook/useNotebook";
import * as ko from "knockout"; import * as ko from "knockout";
import * as _ from "underscore"; import * as _ from "underscore";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
@ -529,7 +529,7 @@ export default class Collection implements ViewModels.Collection {
}; };
public onSchemaAnalyzerClick = async () => { public onSchemaAnalyzerClick = async () => {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
await this.container.allocateContainer(); await this.container.allocateContainer();
} }
useSelectedNode.getState().setSelectedNode(this); useSelectedNode.getState().setSelectedNode(this);

View File

@ -130,9 +130,8 @@ export const ResourceTree: React.FC<ResourceTreeProps> = ({ container }: Resourc
if ( if (
myNotebooksContentRoot && myNotebooksContentRoot &&
((NotebookUtil.isPhoenixEnabled() && useNotebook.getState().isPhoenix &&
useNotebook.getState().connectionInfo.status === ConnectionStatusType.Connected) || useNotebook.getState().connectionInfo.status === ConnectionStatusType.Connected
userContext.features.phoenix === false)
) { ) {
notebooksTree.children.push(buildMyNotebooksTree()); notebooksTree.children.push(buildMyNotebooksTree());
} }
@ -166,15 +165,7 @@ export const ResourceTree: React.FC<ResourceTreeProps> = ({ container }: Resourc
const myNotebooksTree: TreeNode = buildNotebookDirectoryNode( const myNotebooksTree: TreeNode = buildNotebookDirectoryNode(
myNotebooksContentRoot, myNotebooksContentRoot,
(item: NotebookContentItem) => { (item: NotebookContentItem) => {
container.openNotebook(item).then((hasOpened) => { container.openNotebook(item);
if (
hasOpened &&
userContext.features.notebooksTemporarilyDown === false &&
userContext.features.phoenix === false
) {
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
}
});
} }
); );
@ -189,15 +180,7 @@ export const ResourceTree: React.FC<ResourceTreeProps> = ({ container }: Resourc
const gitHubNotebooksTree: TreeNode = buildNotebookDirectoryNode( const gitHubNotebooksTree: TreeNode = buildNotebookDirectoryNode(
gitHubNotebooksContentRoot, gitHubNotebooksContentRoot,
(item: NotebookContentItem) => { (item: NotebookContentItem) => {
container.openNotebook(item).then((hasOpened) => { container.openNotebook(item);
if (
hasOpened &&
userContext.features.notebooksTemporarilyDown === false &&
userContext.features.phoenix === false
) {
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
}
});
}, },
true true
); );

View File

@ -1,9 +1,18 @@
import promiseRetry, { AbortError } from "p-retry"; import promiseRetry, { AbortError } from "p-retry";
import { ContainerStatusType, HttpHeaders, HttpStatusCodes, Notebook } from "../Common/Constants"; import { Action } from "Shared/Telemetry/TelemetryConstants";
import {
Areas,
ConnectionStatusType,
ContainerStatusType,
HttpHeaders,
HttpStatusCodes,
Notebook,
} from "../Common/Constants";
import { getErrorMessage } from "../Common/ErrorHandlingUtils"; import { getErrorMessage } from "../Common/ErrorHandlingUtils";
import * as Logger from "../Common/Logger"; import * as Logger from "../Common/Logger";
import { configContext } from "../ConfigContext"; import { configContext } from "../ConfigContext";
import { import {
ContainerConnectionInfo,
ContainerInfo, ContainerInfo,
IContainerData, IContainerData,
IPhoenixConnectionInfoResult, IPhoenixConnectionInfoResult,
@ -11,6 +20,7 @@ import {
IResponse, IResponse,
} from "../Contracts/DataModels"; } from "../Contracts/DataModels";
import { useNotebook } from "../Explorer/Notebook/useNotebook"; import { useNotebook } from "../Explorer/Notebook/useNotebook";
import * as TelemetryProcessor from "../Shared/Telemetry/TelemetryProcessor";
import { userContext } from "../UserContext"; import { userContext } from "../UserContext";
import { getAuthorizationHeader } from "../Utils/AuthorizationUtils"; import { getAuthorizationHeader } from "../Utils/AuthorizationUtils";
@ -35,8 +45,8 @@ export class PhoenixClient {
operation: string operation: string
): Promise<IResponse<IPhoenixConnectionInfoResult>> { ): Promise<IResponse<IPhoenixConnectionInfoResult>> {
try { try {
const response = await fetch(`${this.getPhoenixContainerPoolingEndPoint()}/${operation}`, { const response = await fetch(`${this.getPhoenixControlPlanePathPrefix()}/containerconnections`, {
method: "POST", method: operation === "allocate" ? "POST" : "PATCH",
headers: PhoenixClient.getHeaders(), headers: PhoenixClient.getHeaders(),
body: JSON.stringify(provisionData), body: JSON.stringify(provisionData),
}); });
@ -55,7 +65,7 @@ export class PhoenixClient {
} }
} }
public async initiateContainerHeartBeat(containerData: { forwardingId: string; dbAccountName: string }) { public async initiateContainerHeartBeat(containerData: IContainerData) {
if (this.containerHealthHandler) { if (this.containerHealthHandler) {
clearTimeout(this.containerHealthHandler); clearTimeout(this.containerHealthHandler);
} }
@ -72,7 +82,7 @@ export class PhoenixClient {
try { try {
const runContainerStatusAsync = async () => { const runContainerStatusAsync = async () => {
const response = await window.fetch( const response = await window.fetch(
`${this.getPhoenixContainerPoolingEndPoint()}/${containerData.dbAccountName}/${containerData.forwardingId}`, `${this.getPhoenixControlPlanePathPrefix()}/${containerData.forwardingId}`,
{ {
method: "GET", method: "GET",
headers: PhoenixClient.getHeaders(), headers: PhoenixClient.getHeaders(),
@ -86,13 +96,32 @@ export class PhoenixClient {
status: ContainerStatusType.Active, status: ContainerStatusType.Active,
}; };
} else if (response.status === HttpStatusCodes.NotFound) { } else if (response.status === HttpStatusCodes.NotFound) {
const error = "Disconnected from compute workspace";
Logger.logError(error, "");
const connectionStatus: ContainerConnectionInfo = {
status: ConnectionStatusType.Reconnect,
};
TelemetryProcessor.traceMark(Action.PhoenixHeartBeat, {
dataExplorerArea: Areas.Notebook,
message: getErrorMessage(error),
});
useNotebook.getState().resetContainerConnection(connectionStatus);
useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed);
throw new AbortError(response.statusText); throw new AbortError(response.statusText);
} }
throw new Error(response.statusText); throw new Error(response.statusText);
}; };
return await promiseRetry(runContainerStatusAsync, this.retryOptions); return await promiseRetry(runContainerStatusAsync, this.retryOptions);
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "PhoenixClient/getContainerStatus"); TelemetryProcessor.traceFailure(Action.PhoenixHeartBeat, {
dataExplorerArea: Areas.Notebook,
});
Logger.logError(getErrorMessage(error), "");
const connectionStatus: ContainerConnectionInfo = {
status: ConnectionStatusType.Failed,
};
useNotebook.getState().resetContainerConnection(connectionStatus);
useNotebook.getState().setIsRefreshed(!useNotebook.getState().isRefreshed);
return { return {
durationLeftInMinutes: undefined, durationLeftInMinutes: undefined,
notebookServerInfo: undefined, notebookServerInfo: undefined,
@ -101,19 +130,24 @@ export class PhoenixClient {
} }
} }
private async getContainerHealth(delayMs: number, containerData: { forwardingId: string; dbAccountName: string }) { private async getContainerHealth(delayMs: number, containerData: IContainerData) {
const containerInfo = await this.getContainerStatusAsync(containerData);
useNotebook.getState().setContainerStatus(containerInfo);
if (useNotebook.getState().containerStatus?.status === ContainerStatusType.Active) {
this.scheduleContainerHeartbeat(delayMs, containerData);
}
}
public async isDbAcountWhitelisted(): Promise<boolean> {
try { try {
const containerInfo = await this.getContainerStatusAsync(containerData); const response = await window.fetch(`${this.getPhoenixControlPlanePathPrefix()}`, {
useNotebook.getState().setContainerStatus(containerInfo); method: "GET",
if (useNotebook.getState().containerStatus?.status === ContainerStatusType.Active) { headers: PhoenixClient.getHeaders(),
this.scheduleContainerHeartbeat(delayMs, containerData);
}
} catch (exception) {
useNotebook.getState().setContainerStatus({
durationLeftInMinutes: undefined,
notebookServerInfo: undefined,
status: ContainerStatusType.Disconnected,
}); });
return response.status === HttpStatusCodes.OK;
} catch (error) {
Logger.logError(getErrorMessage(error), "PhoenixClient/IsDbAcountWhitelisted");
return false;
} }
} }
@ -129,8 +163,10 @@ export class PhoenixClient {
return phoenixEndpoint; return phoenixEndpoint;
} }
public getPhoenixContainerPoolingEndPoint(): string { public getPhoenixControlPlanePathPrefix(): string {
return `${PhoenixClient.getPhoenixEndpoint()}/api/controlplane/toolscontainer`; return `${PhoenixClient.getPhoenixEndpoint()}/api/controlplane/toolscontainer/cosmosaccounts${
userContext.databaseAccount.id
}`;
} }
private static getHeaders(): HeadersInit { private static getHeaders(): HeadersInit {

View File

@ -82,6 +82,7 @@ export enum Action {
NotebooksMoveCellUpFromMenu, NotebooksMoveCellUpFromMenu,
NotebooksMoveCellDownFromMenu, NotebooksMoveCellDownFromMenu,
PhoenixConnection, PhoenixConnection,
PhoenixHeartBeat,
PhoenixResetWorkspace, PhoenixResetWorkspace,
DeleteCellFromMenu, DeleteCellFromMenu,
OpenTerminal, OpenTerminal,

View File

@ -10,7 +10,6 @@ import {
SortBy, SortBy,
} from "../Explorer/Controls/NotebookGallery/GalleryViewerComponent"; } from "../Explorer/Controls/NotebookGallery/GalleryViewerComponent";
import Explorer from "../Explorer/Explorer"; import Explorer from "../Explorer/Explorer";
import { NotebookUtil } from "../Explorer/Notebook/NotebookUtil";
import { useNotebook } from "../Explorer/Notebook/useNotebook"; import { useNotebook } from "../Explorer/Notebook/useNotebook";
import { IGalleryItem, JunoClient } from "../Juno/JunoClient"; import { IGalleryItem, JunoClient } from "../Juno/JunoClient";
import { Action, ActionModifiers } from "../Shared/Telemetry/TelemetryConstants"; import { Action, ActionModifiers } from "../Shared/Telemetry/TelemetryConstants";
@ -229,7 +228,7 @@ export function downloadItem(
undefined, undefined,
"Download", "Download",
async () => { async () => {
if (NotebookUtil.isPhoenixEnabled()) { if (useNotebook.getState().isPhoenix) {
await container.allocateContainer(); await container.allocateContainer();
} }
const notebookServerInfo = useNotebook.getState().notebookServerInfo; const notebookServerInfo = useNotebook.getState().notebookServerInfo;