Compare commits

..

2 Commits

Author SHA1 Message Date
Steve Faulkner
123ec2e45c Fix commas 2020-10-29 19:20:30 -05:00
Steve Faulkner
2f4abfa796 Remove rupm 2020-10-29 19:15:08 -05:00
138 changed files with 1091 additions and 1687 deletions

View File

@@ -1,10 +1,7 @@
# These options are only needed when if running end to end tests locally
PORTAL_RUNNER_USERNAME= PORTAL_RUNNER_USERNAME=
PORTAL_RUNNER_PASSWORD= PORTAL_RUNNER_PASSWORD=
PORTAL_RUNNER_SUBSCRIPTION= PORTAL_RUNNER_SUBSCRIPTION=
PORTAL_RUNNER_RESOURCE_GROUP= PORTAL_RUNNER_RESOURCE_GROUP=
PORTAL_RUNNER_DATABASE_ACCOUNT= PORTAL_RUNNER_DATABASE_ACCOUNT=
PORTAL_RUNNER_CONNECTION_STRING= PORTAL_RUNNER_CONNECTION_STRING=
CASSANDRA_CONNECTION_STRING=
MONGO_CONNECTION_STRING=
TABLES_CONNECTION_STRING=
DATA_EXPLORER_ENDPOINT=https://localhost:1234/hostedExplorer.html

View File

@@ -15,6 +15,8 @@ src/Common/DeleteFeedback.ts
src/Common/DocumentClientUtilityBase.ts src/Common/DocumentClientUtilityBase.ts
src/Common/EditableUtility.ts src/Common/EditableUtility.ts
src/Common/EnvironmentUtility.ts src/Common/EnvironmentUtility.ts
src/Common/ErrorParserUtility.test.ts
src/Common/ErrorParserUtility.ts
src/Common/HashMap.test.ts src/Common/HashMap.test.ts
src/Common/HashMap.ts src/Common/HashMap.ts
src/Common/HeadersUtility.test.ts src/Common/HeadersUtility.test.ts

View File

@@ -150,12 +150,6 @@ jobs:
PORTAL_RUNNER_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_SQL }} PORTAL_RUNNER_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_SQL }}
MONGO_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_MONGO }} MONGO_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_MONGO }}
CASSANDRA_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_CASSANDRA }} CASSANDRA_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_CASSANDRA }}
TABLES_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_TABLE }}
DATA_EXPLORER_ENDPOINT: "https://localhost:1234/hostedExplorer.html"
- uses: actions/upload-artifact@v2
with:
name: screenshots
path: failed-*
nuget: nuget:
name: Publish Nuget name: Publish Nuget
if: github.ref == 'refs/heads/master' || contains(github.ref, 'hotfix/') || contains(github.ref, 'release/') if: github.ref == 'refs/heads/master' || contains(github.ref, 'hotfix/') || contains(github.ref, 'release/')

View File

@@ -33,7 +33,7 @@ To run pure hosted mode, in `webpack.config.js` change index HtmlWebpackPlugin t
### Emulator Development ### Emulator Development
In a window environment, running `npm run build` will automatically copy the built files from `/dist` over to the default emulator install paths. In a non-windows environment you can specify an alternate endpoint using `EMULATOR_ENDPOINT` and webpack dev server will proxy requests for you. In a window environment, running `npm run build` will automatically copy the built files from `/dist` over to the default emulator install paths. In a non-windows enironment you can specify an alternate endpoint using `EMULATOR_ENDPOINT` and webpack dev server will proxy requests for you.
`PLATFORM=Emulator EMULATOR_ENDPOINT=https://my-vm.azure.com:8081 npm run watch` `PLATFORM=Emulator EMULATOR_ENDPOINT=https://my-vm.azure.com:8081 npm run watch`
@@ -60,7 +60,7 @@ The Cosmos Portal that consumes this repo is not currently open source. If you h
You can however load a local running instance of data explorer in the production portal. You can however load a local running instance of data explorer in the production portal.
1. Turn off browser SSL validation for localhost: chrome://flags/#allow-insecure-localhost OR Install valid SSL certs for localhost (on IE, follow these [instructions](https://www.technipages.com/ie-bypass-problem-with-this-websites-security-certificate) to install the localhost certificate in the right place) 1. Turn off browser SSL validation for localhost: chrome://flags/#allow-insecure-localhost OR Install valid SSL certs for localhost (on IE, follow these [instructions](https://www.technipages.com/ie-bypass-problem-with-this-websites-security-certificate) to install the localhost certificate in the right place)
2. Allowlist `https://localhost:1234` domain for CORS in the Azure Cosmos DB portal 2. Whitelist `https://localhost:1234` domain for CORS in the Azure Cosmos DB portal
3. Start the project in portal mode: `PLATFORM=Portal npm run watch` 3. Start the project in portal mode: `PLATFORM=Portal npm run watch`
4. Load the portal using the following link: https://ms.portal.azure.com/?dataExplorerSource=https%3A%2F%2Flocalhost%3A1234%2Fexplorer.html 4. Load the portal using the following link: https://ms.portal.azure.com/?dataExplorerSource=https%3A%2F%2Flocalhost%3A1234%2Fexplorer.html
@@ -84,19 +84,16 @@ Unit tests are located adjacent to the code under test and run with [Jest](https
4. Install dependencies: `npm install` 4. Install dependencies: `npm install`
5. Run cypress headless(`npm run test`) or in interactive mode(`npm run test:debug`) 5. Run cypress headless(`npm run test`) or in interactive mode(`npm run test:debug`)
#### End to End Production Tests #### End to End Production Runners
Jest and Puppeteer are used for end to end production runners and are contained in `test/`. To run these tests locally: Jest and Puppeteer are used for end to end production runners and are contained in `test/`. To run these tests locally:
1. Copy .env.example to .env 1. Copy .env.example to .env and fill in all variables
2. Update the values in .env including your local data explorer endpoint (ask a teammate/codeowner for help with .env values) 2. Run `npm run test:e2e`
3. Make sure all packages are installed `npm install`
4. Run the server `npm run start` and wait for it to start
5. Run `npm run test:e2e`
### Releasing ### Releasing
We generally adhere to the release strategy [documented by the Azure SDK Guidelines](https://azure.github.io/azure-sdk/policies_repobranching.html#release-branches). Most releases should happen from the master branch. If master contains commits that cannot be released, you may create a release from a `release/` or `hotfix/` branch. See linked documentation for more details. We generally adhear to the release strategy [documented by the Azure SDK Guidelines](https://azure.github.io/azure-sdk/policies_repobranching.html#release-branches). Most releases should happen from the master branch. If master contains commits that cannot be released, you may create a release from a `release/` or `hotfix/` branch. See linked documentation for more details.
# Contributing # Contributing

48
package-lock.json generated
View File

@@ -2803,13 +2803,12 @@
} }
}, },
"@nteract/monaco-editor": { "@nteract/monaco-editor": {
"version": "3.2.2", "version": "3.2.0",
"resolved": "https://registry.npmjs.org/@nteract/monaco-editor/-/monaco-editor-3.2.2.tgz", "resolved": "https://registry.npmjs.org/@nteract/monaco-editor/-/monaco-editor-3.2.0.tgz",
"integrity": "sha512-51Pxt6v6qaAlbDY0BgEydk/Jxuu93t+uB8Geg3vJfE6VDphTEakB0wocBIfvcTKVV55Lx53/rTSp6QHqtaHiGg==", "integrity": "sha512-PGEUvy/GTBMECy4RUfh4wxO7GfA9YDBSV3hGt8MyrVz/GxUDtjB7FqrYS0ZhmVQPYl8hnV2i48F3YlypC+xIXA==",
"requires": { "requires": {
"@nteract/core": "^14.0.0", "@nteract/core": "^14.0.0",
"@nteract/messaging": "^7.0.12", "@nteract/messaging": "^7.0.10",
"lodash.debounce": "^4.0.6",
"monaco-editor": "0.18.1", "monaco-editor": "0.18.1",
"rxjs": "^6.3.3" "rxjs": "^6.3.3"
}, },
@@ -2858,40 +2857,6 @@
"rxjs": "^6.3.3" "rxjs": "^6.3.3"
} }
}, },
"@nteract/messaging": {
"version": "7.0.12",
"resolved": "https://registry.npmjs.org/@nteract/messaging/-/messaging-7.0.12.tgz",
"integrity": "sha512-5z2Ffd1hj7AsGBJTAoqJshLlUZ+ISJBjiZAdNDjb70PNEv0x8UOMk/di80RI3WBLK5MKxSJkGXfs4jfzfdW6bA==",
"requires": {
"@nteract/types": "^7.1.2",
"@types/uuid": "^8.0.0",
"lodash.clonedeep": "^4.5.0",
"rxjs": "^6.6.0",
"uuid": "^8.0.0"
},
"dependencies": {
"@nteract/commutable": {
"version": "7.3.4",
"resolved": "https://registry.npmjs.org/@nteract/commutable/-/commutable-7.3.4.tgz",
"integrity": "sha512-Z6aUtIZN0CKUMJwbZjUUqaaBhT6P0RiEG5nHso+oG/FOXF20Qv+hf/TyvYhw9SXQVmmacaMk4zj0iOID20pIng==",
"requires": {
"immutable": "^4.0.0-rc.12",
"uuid": "^8.0.0"
}
},
"@nteract/types": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/@nteract/types/-/types-7.1.2.tgz",
"integrity": "sha512-I/1TvaUC/m9I/LFk1HemsOUqB0eNdagu0KRLA1YEtChPh9pk5F9flglA7m5+0/j31gLXBISj5+6tL8ikA8BxOQ==",
"requires": {
"@nteract/commutable": "^7.3.4",
"immutable": "^4.0.0-rc.12",
"rxjs": "^6.6.0",
"uuid": "^8.0.0"
}
}
}
},
"@nteract/mythic-notifications": { "@nteract/mythic-notifications": {
"version": "0.1.9", "version": "0.1.9",
"resolved": "https://registry.npmjs.org/@nteract/mythic-notifications/-/mythic-notifications-0.1.9.tgz", "resolved": "https://registry.npmjs.org/@nteract/mythic-notifications/-/mythic-notifications-0.1.9.tgz",
@@ -14457,11 +14422,6 @@
"resolved": "https://registry.npmjs.org/lodash.curry/-/lodash.curry-4.1.1.tgz", "resolved": "https://registry.npmjs.org/lodash.curry/-/lodash.curry-4.1.1.tgz",
"integrity": "sha1-JI42By7ekGUB11lmIAqG2riyMXA=" "integrity": "sha1-JI42By7ekGUB11lmIAqG2riyMXA="
}, },
"lodash.debounce": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz",
"integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168="
},
"lodash.defaults": { "lodash.defaults": {
"version": "4.2.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",

View File

@@ -21,7 +21,7 @@
"@nteract/jupyter-widgets": "2.0.0", "@nteract/jupyter-widgets": "2.0.0",
"@nteract/logos": "1.0.0", "@nteract/logos": "1.0.0",
"@nteract/markdown": "4.4.0", "@nteract/markdown": "4.4.0",
"@nteract/monaco-editor": "3.2.2", "@nteract/monaco-editor": "3.2.0",
"@nteract/octicons": "2.0.0", "@nteract/octicons": "2.0.0",
"@nteract/outputs": "3.0.9", "@nteract/outputs": "3.0.9",
"@nteract/presentational-components": "3.0.7", "@nteract/presentational-components": "3.0.7",

View File

@@ -3,7 +3,6 @@
"offerThroughput": 400, "offerThroughput": 400,
"databaseLevelThroughput": false, "databaseLevelThroughput": false,
"collectionId": "Persons", "collectionId": "Persons",
"rupmEnabled": false,
"partitionKey": { "kind": "Hash", "paths": ["/name"] }, "partitionKey": { "kind": "Hash", "paths": ["/name"] },
"data": [ "data": [
"g.addV('person').property(id, '1').property('name', 'Eva').property('age', 44)", "g.addV('person').property(id, '1').property('name', 'Eva').property('age', 44)",

View File

@@ -108,7 +108,6 @@ export class CapabilityNames {
export class Features { export class Features {
public static readonly cosmosdb = "cosmosdb"; public static readonly cosmosdb = "cosmosdb";
public static readonly enableChangeFeedPolicy = "enablechangefeedpolicy"; public static readonly enableChangeFeedPolicy = "enablechangefeedpolicy";
public static readonly enableRupm = "enablerupm";
public static readonly executeSproc = "dataexplorerexecutesproc"; public static readonly executeSproc = "dataexplorerexecutesproc";
public static readonly hostedDataExplorer = "hosteddataexplorerenabled"; public static readonly hostedDataExplorer = "hosteddataexplorerenabled";
public static readonly enableTtl = "enablettl"; public static readonly enableTtl = "enablettl";
@@ -178,12 +177,6 @@ export class CassandraBackend {
public static readonly schemaApi: string = "api/cassandra/schema"; public static readonly schemaApi: string = "api/cassandra/schema";
public static readonly guestSchemaApi: string = "api/guest/cassandra/schema"; public static readonly guestSchemaApi: string = "api/guest/cassandra/schema";
} }
export class RUPMStates {
public static on: string = "on";
public static off: string = "off";
}
export class Queries { export class Queries {
public static CustomPageOption: string = "custom"; public static CustomPageOption: string = "custom";
public static UnlimitedPageOption: string = "unlimited"; public static UnlimitedPageOption: string = "unlimited";

View File

@@ -1,7 +1,6 @@
import * as Cosmos from "@azure/cosmos"; import * as Cosmos from "@azure/cosmos";
import { RequestInfo, setAuthorizationTokenHeaderUsingMasterKey } from "@azure/cosmos"; import { RequestInfo, setAuthorizationTokenHeaderUsingMasterKey } from "@azure/cosmos";
import { configContext, Platform } from "../ConfigContext"; import { configContext, Platform } from "../ConfigContext";
import { getErrorMessage } from "./ErrorHandlingUtils";
import { logConsoleError } from "../Utils/NotificationConsoleUtils"; import { logConsoleError } from "../Utils/NotificationConsoleUtils";
import { EmulatorMasterKey, HttpHeaders } from "./Constants"; import { EmulatorMasterKey, HttpHeaders } from "./Constants";
import { userContext } from "../UserContext"; import { userContext } from "../UserContext";
@@ -70,7 +69,7 @@ export async function getTokenFromAuthService(verb: string, resourceType: string
const result = JSON.parse(await response.json()); const result = JSON.parse(await response.json());
return result; return result;
} catch (error) { } catch (error) {
logConsoleError(`Failed to get authorization headers for ${resourceType}: ${getErrorMessage(error)}`); logConsoleError(`Failed to get authorization headers for ${resourceType}: ${error.message}`);
return Promise.reject(error); return Promise.reject(error);
} }
} }

View File

@@ -58,8 +58,8 @@ export function executeStoredProcedure(
(error: any) => { (error: any) => {
handleError( handleError(
error, error,
"ExecuteStoredProcedure", `Failed to execute stored procedure ${storedProcedure.id()} for container ${storedProcedure.collection.id()}`,
`Failed to execute stored procedure ${storedProcedure.id()} for container ${storedProcedure.collection.id()}` "ExecuteStoredProcedure"
); );
deferred.reject(error); deferred.reject(error);
} }
@@ -88,7 +88,7 @@ export function queryDocumentsPage(
deferred.resolve(result); deferred.resolve(result);
}, },
(error: any) => { (error: any) => {
handleError(error, "QueryDocumentsPage", `Failed to query ${entityName} for container ${resourceName}`); handleError(error, `Failed to query ${entityName} for container ${resourceName}`, "QueryDocumentsPage");
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -109,7 +109,7 @@ export function readDocument(collection: ViewModels.CollectionBase, documentId:
deferred.resolve(document); deferred.resolve(document);
}, },
(error: any) => { (error: any) => {
handleError(error, "ReadDocument", `Failed to read ${entityName} ${documentId.id()}`); handleError(error, `Failed to read ${entityName} ${documentId.id()}`, "ReadDocument");
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -135,7 +135,7 @@ export function updateDocument(
deferred.resolve(updatedDocument); deferred.resolve(updatedDocument);
}, },
(error: any) => { (error: any) => {
handleError(error, "UpdateDocument", `Failed to update ${entityName} ${documentId.id()}`); handleError(error, `Failed to update ${entityName} ${documentId.id()}`, "UpdateDocument");
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -157,7 +157,7 @@ export function createDocument(collection: ViewModels.CollectionBase, newDocumen
deferred.resolve(savedDocument); deferred.resolve(savedDocument);
}, },
(error: any) => { (error: any) => {
handleError(error, "CreateDocument", `Error while creating new ${entityName} for container ${collection.id()}`); handleError(error, `Error while creating new ${entityName} for container ${collection.id()}`, "CreateDocument");
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -179,7 +179,7 @@ export function deleteDocument(collection: ViewModels.CollectionBase, documentId
deferred.resolve(response); deferred.resolve(response);
}, },
(error: any) => { (error: any) => {
handleError(error, "DeleteDocument", `Error while deleting ${entityName} ${documentId.id()}`); handleError(error, `Error while deleting ${entityName} ${documentId.id()}`, "DeleteDocument");
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -205,7 +205,7 @@ export function deleteConflict(
deferred.resolve(response); deferred.resolve(response);
}, },
(error: any) => { (error: any) => {
handleError(error, "DeleteConflict", `Error while deleting conflict ${conflictId.id()}`); handleError(error, `Error while deleting conflict ${conflictId.id()}`, "DeleteConflict");
deferred.reject(error); deferred.reject(error);
} }
) )

View File

@@ -1,56 +1,11 @@
import { ARMError } from "../Utils/arm/request"; import { CosmosError, sendNotificationForError } from "./dataAccess/sendNotificationForError";
import { HttpStatusCodes } from "./Constants";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { SubscriptionType } from "../Contracts/ViewModels";
import { logConsoleError } from "../Utils/NotificationConsoleUtils"; import { logConsoleError } from "../Utils/NotificationConsoleUtils";
import { logError } from "./Logger"; import { logError } from "./Logger";
import { sendMessage } from "./MessageHandler"; import { replaceKnownError } from "./ErrorParserUtility";
export const handleError = (error: string | ARMError | Error, area: string, consoleErrorPrefix?: string): void => { export const handleError = (error: CosmosError, consoleErrorPrefix: string, area: string): void => {
const errorMessage = getErrorMessage(error); const sanitizedErrorMsg = replaceKnownError(error.message);
const errorCode = error instanceof ARMError ? error.code : undefined; logConsoleError(`${consoleErrorPrefix}:\n ${sanitizedErrorMsg}`);
logError(sanitizedErrorMsg, area, error.code);
// logs error to data explorer console sendNotificationForError(error);
const consoleErrorMessage = consoleErrorPrefix ? `${consoleErrorPrefix}:\n ${errorMessage}` : errorMessage;
logConsoleError(consoleErrorMessage);
// logs error to both app insight and kusto
logError(errorMessage, area, errorCode);
// checks for errors caused by firewall and sends them to portal to handle
sendNotificationForError(errorMessage, errorCode);
};
export const getErrorMessage = (error: string | Error): string => {
const errorMessage = typeof error === "string" ? error : error.message;
return replaceKnownError(errorMessage);
};
export const getErrorStack = (error: string | Error): string => {
return typeof error === "string" ? undefined : error.stack;
};
const sendNotificationForError = (errorMessage: string, errorCode: number | string): void => {
if (errorCode === HttpStatusCodes.Forbidden) {
if (errorMessage?.toLowerCase().indexOf("sharedoffer is disabled for your account") > 0) {
return;
}
sendMessage({
type: MessageTypes.ForbiddenError,
reason: errorMessage
});
}
};
const replaceKnownError = (errorMessage: string): string => {
if (
window.dataExplorer?.subscriptionType() === SubscriptionType.Internal &&
errorMessage.indexOf("SharedOffer is Disabled for your account") >= 0
) {
return "Database throughput is not supported for internal subscriptions.";
} else if (errorMessage.indexOf("Partition key paths must contain only valid") >= 0) {
return "Partition key paths must contain only valid characters and not contain a trailing slash or wildcard character.";
}
return errorMessage;
}; };

View File

@@ -0,0 +1,24 @@
import * as ErrorParserUtility from "./ErrorParserUtility";
describe("Error Parser Utility", () => {
describe("shouldEnableCrossPartitionKeyForResourceWithPartitionKey()", () => {
it("should parse a backend error correctly", () => {
// A fake error matching what is thrown by the SDK on a bad collection create request
const innerMessage =
"The partition key component definition path '/asdwqr31 @#$#$WRadf' could not be accepted, failed near position '10'. Partition key paths must contain only valid characters and not contain a trailing slash or wildcard character.";
const message = `Message: {\"Errors\":[\"${innerMessage}\"]}\r\nActivityId: 97b2e684-7505-4921-85f6-2513b9b28220, Request URI: /apps/89fdcf25-2a0b-4d2a-aab6-e161e565b26f/services/54911149-7bb1-4e7d-a1fa-22c8b36a4bb9/partitions/cc2a7a04-5f5a-4709-bcf7-8509b264963f/replicas/132304018743619218p, RequestStats: , SDK: Microsoft.Azure.Documents.Common/2.10.0`;
const err = new Error(message) as any;
err.code = 400;
err.body = {
code: "BadRequest",
message
};
err.headers = {};
err.activityId = "97b2e684-7505-4921-85f6-2513b9b28220";
const parsedError = ErrorParserUtility.parse(err);
expect(parsedError.length).toBe(1);
expect(parsedError[0].message).toBe(innerMessage);
});
});
});

View File

@@ -0,0 +1,69 @@
import * as DataModels from "../Contracts/DataModels";
import * as ViewModels from "../Contracts/ViewModels";
export function replaceKnownError(err: string): string {
if (
window.dataExplorer.subscriptionType() === ViewModels.SubscriptionType.Internal &&
err.indexOf("SharedOffer is Disabled for your account") >= 0
) {
return "Database throughput is not supported for internal subscriptions.";
} else if (err.indexOf("Partition key paths must contain only valid") >= 0) {
return "Partition key paths must contain only valid characters and not contain a trailing slash or wildcard character.";
}
return err;
}
export function parse(err: any): DataModels.ErrorDataModel[] {
try {
return _parse(err);
} catch (e) {
return [<DataModels.ErrorDataModel>{ message: JSON.stringify(err) }];
}
}
function _parse(err: any): DataModels.ErrorDataModel[] {
var normalizedErrors: DataModels.ErrorDataModel[] = [];
if (err.message && !err.code) {
normalizedErrors.push(err);
} else {
const innerErrors: any[] = _getInnerErrors(err.message);
normalizedErrors = innerErrors.map(innerError =>
typeof innerError === "string" ? { message: innerError } : innerError
);
}
return normalizedErrors;
}
function _getInnerErrors(message: string): any[] {
/*
The backend error message has an inner-message which is a stringified object.
For SQL errors, the "errors" property is an array of SqlErrorDataModel.
Example:
"Message: {"Errors":["Resource with specified id or name already exists"]}\r\nActivityId: 80005000008d40b6a, Request URI: /apps/19000c000c0a0005/services/mctestdocdbprod-MasterService-0-00066ab9937/partitions/900005f9000e676fb8/replicas/13000000000955p"
For non-SQL errors the "Errors" propery is an array of string.
Example:
"Message: {"errors":[{"severity":"Error","location":{"start":7,"end":8},"code":"SC1001","message":"Syntax error, incorrect syntax near '.'."}]}\r\nActivityId: d3300016d4084e310a, Request URI: /apps/12401f9e1df77/services/dc100232b1f44545/partitions/f86f3bc0001a2f78/replicas/13085003638s"
*/
let innerMessage: any = null;
const singleLineMessage = message.replace(/[\r\n]|\r|\n/g, "");
try {
// Multi-Partition error flavor
const regExp = /^(.*)ActivityId: (.*)/g;
const regString = regExp.exec(singleLineMessage);
const innerMessageString = regString[1];
innerMessage = JSON.parse(innerMessageString);
} catch (e) {
// Single-partition error flavor
const regExp = /^Message: (.*)ActivityId: (.*), Request URI: (.*)/g;
const regString = regExp.exec(singleLineMessage);
const innerMessageString = regString[1];
innerMessage = JSON.parse(innerMessageString);
}
return innerMessage.errors ? innerMessage.errors : innerMessage.Errors;
}

View File

@@ -21,8 +21,14 @@ export function logWarning(message: string, area: string, code?: number): void {
return _logEntry(entry); return _logEntry(entry);
} }
export function logError(errorMessage: string, area: string, code?: number | string): void { export function logError(message: string | Error, area: string, code?: number): void {
const entry: Diagnostics.LogEntry = _generateLogEntry(Diagnostics.LogEntryLevel.Error, errorMessage, area, code); let logMessage: string;
if (typeof message === "string") {
logMessage = message;
} else {
logMessage = JSON.stringify(message, Object.getOwnPropertyNames(message));
}
const entry: Diagnostics.LogEntry = _generateLogEntry(Diagnostics.LogEntryLevel.Error, logMessage, area, code);
return _logEntry(entry); return _logEntry(entry);
} }
@@ -53,7 +59,7 @@ function _generateLogEntry(
level: Diagnostics.LogEntryLevel, level: Diagnostics.LogEntryLevel,
message: string, message: string,
area: string, area: string,
code?: number | string code?: number
): Diagnostics.LogEntry { ): Diagnostics.LogEntry {
return { return {
timestamp: new Date().getUTCSeconds(), timestamp: new Date().getUTCSeconds(),

View File

@@ -12,7 +12,8 @@ import { BackendDefaults, HttpStatusCodes, SavedQueries } from "./Constants";
import { userContext } from "../UserContext"; import { userContext } from "../UserContext";
import { createDocument, deleteDocument, queryDocuments, queryDocumentsPage } from "./DocumentClientUtilityBase"; import { createDocument, deleteDocument, queryDocuments, queryDocumentsPage } from "./DocumentClientUtilityBase";
import { createCollection } from "./dataAccess/createCollection"; import { createCollection } from "./dataAccess/createCollection";
import { handleError } from "./ErrorHandlingUtils"; import * as ErrorParserUtility from "./ErrorParserUtility";
import * as Logger from "./Logger";
export class QueriesClient { export class QueriesClient {
private static readonly PartitionKey: DataModels.PartitionKey = { private static readonly PartitionKey: DataModels.PartitionKey = {
@@ -52,8 +53,13 @@ export class QueriesClient {
return Promise.resolve(collection); return Promise.resolve(collection);
}, },
(error: any) => { (error: any) => {
handleError(error, "setupQueriesCollection", "Failed to set up account for saving queries"); const stringifiedError: string = error.message;
return Promise.reject(error); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Failed to set up account for saving queries: ${stringifiedError}`
);
Logger.logError(stringifiedError, "setupQueriesCollection");
return Promise.reject(stringifiedError);
} }
) )
.finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id)); .finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id));
@@ -96,11 +102,19 @@ export class QueriesClient {
return Promise.resolve(); return Promise.resolve();
}, },
(error: any) => { (error: any) => {
if (error.code === HttpStatusCodes.Conflict.toString()) { let errorMessage: string;
error = `Query ${query.queryName} already exists`; const parsedError: DataModels.ErrorDataModel = ErrorParserUtility.parse(error)[0];
if (parsedError.code === HttpStatusCodes.Conflict.toString()) {
errorMessage = `Query ${query.queryName} already exists`;
} else {
errorMessage = parsedError.message;
} }
handleError(error, "saveQuery", `Failed to save query ${query.queryName}`); NotificationConsoleUtils.logConsoleMessage(
return Promise.reject(error); ConsoleDataType.Error,
`Failed to save query ${query.queryName}: ${errorMessage}`
);
Logger.logError(JSON.stringify(parsedError), "saveQuery");
return Promise.reject(errorMessage);
} }
) )
.finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id)); .finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id));
@@ -149,15 +163,25 @@ export class QueriesClient {
return Promise.resolve(queries); return Promise.resolve(queries);
}, },
(error: any) => { (error: any) => {
handleError(error, "getSavedQueries", "Failed to fetch saved queries"); const stringifiedError: string = error.message;
return Promise.reject(error); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Failed to fetch saved queries: ${stringifiedError}`
);
Logger.logError(stringifiedError, "getSavedQueries");
return Promise.reject(stringifiedError);
} }
); );
}, },
(error: any) => { (error: any) => {
// should never get into this state but we handle this regardless // should never get into this state but we handle this regardless
handleError(error, "getSavedQueries", "Failed to fetch saved queries"); const stringifiedError: string = error.message;
return Promise.reject(error); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Failed to fetch saved queries: ${stringifiedError}`
);
Logger.logError(stringifiedError, "getSavedQueries");
return Promise.reject(stringifiedError);
} }
) )
.finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id)); .finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id));
@@ -208,8 +232,13 @@ export class QueriesClient {
return Promise.resolve(); return Promise.resolve();
}, },
(error: any) => { (error: any) => {
handleError(error, "deleteQuery", `Failed to delete query ${query.queryName}`); const stringifiedError: string = error.message;
return Promise.reject(error); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Failed to delete query ${query.queryName}: ${stringifiedError}`
);
Logger.logError(stringifiedError, "deleteQuery");
return Promise.reject(stringifiedError);
} }
) )
.finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id)); .finally(() => NotificationConsoleUtils.clearInProgressMessageWithId(id));

View File

@@ -55,7 +55,7 @@ export const createCollection = async (params: DataModels.CreateCollectionParams
logConsoleInfo(`Successfully created container ${params.collectionId}`); logConsoleInfo(`Successfully created container ${params.collectionId}`);
return collection; return collection;
} catch (error) { } catch (error) {
handleError(error, "CreateCollection", `Error while creating container ${params.collectionId}`); handleError(error, `Error while creating container ${params.collectionId}`, "CreateCollection");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -41,7 +41,7 @@ export async function createDatabase(params: DataModels.CreateDatabaseParams): P
logConsoleInfo(`Successfully created database ${params.databaseId}`); logConsoleInfo(`Successfully created database ${params.databaseId}`);
return database; return database;
} catch (error) { } catch (error) {
handleError(error, "CreateDatabase", `Error while creating database ${params.databaseId}`); handleError(error, `Error while creating database ${params.databaseId}`, "CreateDatabase");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -70,7 +70,7 @@ export async function createStoredProcedure(
.scripts.storedProcedures.create(storedProcedure); .scripts.storedProcedures.create(storedProcedure);
return response?.resource; return response?.resource;
} catch (error) { } catch (error) {
handleError(error, "CreateStoredProcedure", `Error while creating stored procedure ${storedProcedure.id}`); handleError(error, `Error while creating stored procedure ${storedProcedure.id}`, "CreateStoredProcedure");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -7,8 +7,9 @@ import {
} from "../../Utils/arm/generatedClients/2020-04-01/types"; } from "../../Utils/arm/generatedClients/2020-04-01/types";
import { client } from "../CosmosClient"; import { client } from "../CosmosClient";
import { createUpdateSqlTrigger, getSqlTrigger } from "../../Utils/arm/generatedClients/2020-04-01/sqlResources"; import { createUpdateSqlTrigger, getSqlTrigger } from "../../Utils/arm/generatedClients/2020-04-01/sqlResources";
import { handleError } from "../ErrorHandlingUtils"; import { logConsoleError, logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils"; import { logError } from "../Logger";
import { sendNotificationForError } from "./sendNotificationForError";
import { userContext } from "../../UserContext"; import { userContext } from "../../UserContext";
export async function createTrigger( export async function createTrigger(
@@ -65,7 +66,9 @@ export async function createTrigger(
.scripts.triggers.create(trigger); .scripts.triggers.create(trigger);
return response.resource; return response.resource;
} catch (error) { } catch (error) {
handleError(error, "CreateTrigger", `Error while creating trigger ${trigger.id}`); logConsoleError(`Error while creating trigger ${trigger.id}:\n ${error.message}`);
logError(error.message, "CreateTrigger", error.code);
sendNotificationForError(error);
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -72,8 +72,8 @@ export async function createUserDefinedFunction(
} catch (error) { } catch (error) {
handleError( handleError(
error, error,
"CreateUserupdateUserDefinedFunction", `Error while creating user defined function ${userDefinedFunction.id}`,
`Error while creating user defined function ${userDefinedFunction.id}` "CreateUserupdateUserDefinedFunction"
); );
throw error; throw error;
} finally { } finally {

View File

@@ -23,7 +23,7 @@ export async function deleteCollection(databaseId: string, collectionId: string)
} }
logConsoleInfo(`Successfully deleted container ${collectionId}`); logConsoleInfo(`Successfully deleted container ${collectionId}`);
} catch (error) { } catch (error) {
handleError(error, "DeleteCollection", `Error while deleting container ${collectionId}`); handleError(error, `Error while deleting container ${collectionId}`, "DeleteCollection");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -25,7 +25,7 @@ export async function deleteDatabase(databaseId: string): Promise<void> {
} }
logConsoleInfo(`Successfully deleted database ${databaseId}`); logConsoleInfo(`Successfully deleted database ${databaseId}`);
} catch (error) { } catch (error) {
handleError(error, "DeleteDatabase", `Error while deleting database ${databaseId}`); handleError(error, `Error while deleting database ${databaseId}`, "DeleteDatabase");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -34,7 +34,7 @@ export async function deleteStoredProcedure(
.delete(); .delete();
} }
} catch (error) { } catch (error) {
handleError(error, "DeleteStoredProcedure", `Error while deleting stored procedure ${storedProcedureId}`); handleError(error, `Error while deleting stored procedure ${storedProcedureId}`, "DeleteStoredProcedure");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -30,7 +30,7 @@ export async function deleteTrigger(databaseId: string, collectionId: string, tr
.delete(); .delete();
} }
} catch (error) { } catch (error) {
handleError(error, "DeleteTrigger", `Error while deleting trigger ${triggerId}`); handleError(error, `Error while deleting trigger ${triggerId}`, "DeleteTrigger");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -30,7 +30,7 @@ export async function deleteUserDefinedFunction(databaseId: string, collectionId
.delete(); .delete();
} }
} catch (error) { } catch (error) {
handleError(error, "DeleteUserDefinedFunction", `Error while deleting user defined function ${id}`); handleError(error, `Error while deleting user defined function ${id}`, "DeleteUserDefinedFunction");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -1,28 +0,0 @@
import { client } from "../CosmosClient";
import { handleError } from "../ErrorHandlingUtils";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import * as Constants from "../Constants";
import { AuthType } from "../../AuthType";
export async function getIndexTransformationProgress(databaseId: string, collectionId: string): Promise<number> {
if (window.authType !== AuthType.AAD) {
return undefined;
}
let indexTransformationPercentage: number;
const clearMessage = logConsoleProgress(`Reading container ${collectionId}`);
try {
const response = await client()
.database(databaseId)
.container(collectionId)
.read({ populateQuotaInfo: true });
indexTransformationPercentage = parseInt(
response.headers[Constants.HttpHeaders.collectionIndexTransformationProgress] as string
);
} catch (error) {
handleError(error, "ReadMongoDBCollection", `Error while reading container ${collectionId}`);
throw error;
}
clearMessage();
return indexTransformationPercentage;
}

View File

@@ -13,7 +13,7 @@ export async function readCollection(databaseId: string, collectionId: string):
.read(); .read();
collection = response.resource as DataModels.Collection; collection = response.resource as DataModels.Collection;
} catch (error) { } catch (error) {
handleError(error, "ReadCollection", `Error while querying container ${collectionId}`); handleError(error, `Error while querying container ${collectionId}`, "ReadCollection");
throw error; throw error;
} }
clearMessage(); clearMessage();

View File

@@ -56,7 +56,7 @@ export const readCollectionOffer = async (
} }
); );
} catch (error) { } catch (error) {
handleError(error, "ReadCollectionOffer", `Error while querying offer for collection ${params.collectionId}`); handleError(error, `Error while querying offer for collection ${params.collectionId}`, "ReadCollectionOffer");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -37,7 +37,7 @@ export const readCollectionQuotaInfo = async (
return quota; return quota;
} catch (error) { } catch (error) {
handleError(error, "ReadCollectionQuotaInfo", `Error while querying quota info for container ${collection.id}`); handleError(error, `Error while querying quota info for container ${collection.id}`, "ReadCollectionQuotaInfo");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -29,7 +29,7 @@ export async function readCollections(databaseId: string): Promise<DataModels.Co
.fetchAll(); .fetchAll();
return sdkResponse.resources as DataModels.Collection[]; return sdkResponse.resources as DataModels.Collection[];
} catch (error) { } catch (error) {
handleError(error, "ReadCollections", `Error while querying containers for database ${databaseId}`); handleError(error, `Error while querying containers for database ${databaseId}`, "ReadCollections");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -47,7 +47,7 @@ export const readDatabaseOffer = async (
} }
); );
} catch (error) { } catch (error) {
handleError(error, "ReadDatabaseOffer", `Error while querying offer for database ${params.databaseId}`); handleError(error, `Error while querying offer for database ${params.databaseId}`, "ReadDatabaseOffer");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -27,7 +27,7 @@ export async function readDatabases(): Promise<DataModels.Database[]> {
databases = sdkResponse.resources as DataModels.Database[]; databases = sdkResponse.resources as DataModels.Database[];
} }
} catch (error) { } catch (error) {
handleError(error, "ReadDatabases", `Error while querying databases`); handleError(error, `Error while querying databases`, "ReadDatabases");
throw error; throw error;
} }
clearMessage(); clearMessage();

View File

@@ -2,6 +2,8 @@ import { userContext } from "../../UserContext";
import { getMongoDBCollection } from "../../Utils/arm/generatedClients/2020-04-01/mongoDBResources"; import { getMongoDBCollection } from "../../Utils/arm/generatedClients/2020-04-01/mongoDBResources";
import { MongoDBCollectionResource } from "../../Utils/arm/generatedClients/2020-04-01/types"; import { MongoDBCollectionResource } from "../../Utils/arm/generatedClients/2020-04-01/types";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils"; import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import * as Constants from "../Constants";
import { client } from "../CosmosClient";
import { handleError } from "../ErrorHandlingUtils"; import { handleError } from "../ErrorHandlingUtils";
import { AuthType } from "../../AuthType"; import { AuthType } from "../../AuthType";
@@ -22,9 +24,35 @@ export async function readMongoDBCollectionThroughRP(
const response = await getMongoDBCollection(subscriptionId, resourceGroup, accountName, databaseId, collectionId); const response = await getMongoDBCollection(subscriptionId, resourceGroup, accountName, databaseId, collectionId);
collection = response.properties.resource; collection = response.properties.resource;
} catch (error) { } catch (error) {
handleError(error, "ReadMongoDBCollection", `Error while reading container ${collectionId}`); handleError(error, `Error while reading container ${collectionId}`, "ReadMongoDBCollection");
throw error; throw error;
} }
clearMessage(); clearMessage();
return collection; return collection;
} }
export async function getMongoDBCollectionIndexTransformationProgress(
databaseId: string,
collectionId: string
): Promise<number> {
if (window.authType !== AuthType.AAD) {
return undefined;
}
let indexTransformationPercentage: number;
const clearMessage = logConsoleProgress(`Reading container ${collectionId}`);
try {
const response = await client()
.database(databaseId)
.container(collectionId)
.read({ populateQuotaInfo: true });
indexTransformationPercentage = parseInt(
response.headers[Constants.HttpHeaders.collectionIndexTransformationProgress] as string
);
} catch (error) {
handleError(error, `Error while reading container ${collectionId}`, "ReadMongoDBCollection");
throw error;
}
clearMessage();
return indexTransformationPercentage;
}

View File

@@ -1,7 +1,7 @@
import { Offer } from "../../Contracts/DataModels"; import { Offer } from "../../Contracts/DataModels";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils"; import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import { client } from "../CosmosClient"; import { client } from "../CosmosClient";
import { handleError, getErrorMessage } from "../ErrorHandlingUtils"; import { handleError } from "../ErrorHandlingUtils";
export const readOffers = async (): Promise<Offer[]> => { export const readOffers = async (): Promise<Offer[]> => {
const clearMessage = logConsoleProgress(`Querying offers`); const clearMessage = logConsoleProgress(`Querying offers`);
@@ -13,11 +13,11 @@ export const readOffers = async (): Promise<Offer[]> => {
return response?.resources; return response?.resources;
} catch (error) { } catch (error) {
// This should be removed when we can correctly identify if an account is serverless when connected using connection string too. // This should be removed when we can correctly identify if an account is serverless when connected using connection string too.
if (getErrorMessage(error)?.includes("Reading or replacing offers is not supported for serverless accounts")) { if (error.message.includes("Reading or replacing offers is not supported for serverless accounts")) {
return []; return [];
} }
handleError(error, "ReadOffers", `Error while querying offers`); handleError(error, `Error while querying offers`, "ReadOffers");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -35,7 +35,7 @@ export async function readStoredProcedures(
.fetchAll(); .fetchAll();
return response?.resources; return response?.resources;
} catch (error) { } catch (error) {
handleError(error, "ReadStoredProcedures", `Failed to query stored procedures for container ${collectionId}`); handleError(error, `Failed to query stored procedures for container ${collectionId}`, "ReadStoredProcedures");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -35,7 +35,7 @@ export async function readTriggers(
.fetchAll(); .fetchAll();
return response?.resources; return response?.resources;
} catch (error) { } catch (error) {
handleError(error, "ReadTriggers", `Failed to query triggers for container ${collectionId}`); handleError(error, `Failed to query triggers for container ${collectionId}`, "ReadTriggers");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -37,8 +37,8 @@ export async function readUserDefinedFunctions(
} catch (error) { } catch (error) {
handleError( handleError(
error, error,
"ReadUserDefinedFunctions", `Failed to query user defined functions for container ${collectionId}`,
`Failed to query user defined functions for container ${collectionId}` "ReadUserDefinedFunctions"
); );
throw error; throw error;
} finally { } finally {

View File

@@ -0,0 +1,20 @@
import * as Constants from "../Constants";
import { sendMessage } from "../MessageHandler";
import { MessageTypes } from "../../Contracts/ExplorerContracts";
export interface CosmosError {
code: number;
message?: string;
}
export function sendNotificationForError(error: CosmosError): void {
if (error && error.code === Constants.HttpStatusCodes.Forbidden) {
if (error.message && error.message.toLowerCase().indexOf("sharedoffer is disabled for your account") > 0) {
return;
}
sendMessage({
type: MessageTypes.ForbiddenError,
reason: error && error.message ? error.message : error
});
}
}

View File

@@ -59,7 +59,7 @@ export async function updateCollection(
logConsoleInfo(`Successfully updated container ${collectionId}`); logConsoleInfo(`Successfully updated container ${collectionId}`);
return collection; return collection;
} catch (error) { } catch (error) {
handleError(error, "UpdateCollection", `Failed to update container ${collectionId}`); handleError(error, `Failed to update container ${collectionId}`, "UpdateCollection");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -72,7 +72,7 @@ export const updateOffer = async (params: UpdateOfferParams): Promise<Offer> =>
logConsoleInfo(`Successfully updated offer for ${offerResourceText}`); logConsoleInfo(`Successfully updated offer for ${offerResourceText}`);
return updatedOffer; return updatedOffer;
} catch (error) { } catch (error) {
handleError(error, "UpdateCollection", `Error updating offer for ${offerResourceText}`); handleError(error, `Error updating offer for ${offerResourceText}`, "UpdateCollection");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();
@@ -376,8 +376,7 @@ const updateOfferWithSDK = async (params: UpdateOfferParams): Promise<Offer> =>
const currentOffer = params.currentOffer; const currentOffer = params.currentOffer;
const newOffer: Offer = { const newOffer: Offer = {
content: { content: {
offerThroughput: undefined, offerThroughput: undefined
offerIsRUPerMinuteThroughputEnabled: false
}, },
_etag: undefined, _etag: undefined,
_ts: undefined, _ts: undefined,

View File

@@ -17,8 +17,7 @@ describe("updateOfferThroughputBeyondLimit", () => {
resourceGroup: "foo", resourceGroup: "foo",
databaseAccountName: "foo", databaseAccountName: "foo",
databaseName: "foo", databaseName: "foo",
throughput: 1000000000, throughput: 1000000000
offerIsRUPerMinuteThroughputEnabled: false
}); });
expect(window.fetch).toHaveBeenCalled(); expect(window.fetch).toHaveBeenCalled();
}); });

View File

@@ -1,9 +1,8 @@
import { Platform, configContext } from "../../ConfigContext"; import { Platform, configContext } from "../../ConfigContext";
import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils"; import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils";
import { AutoPilotOfferSettings } from "../../Contracts/DataModels"; import { AutoPilotOfferSettings } from "../../Contracts/DataModels";
import { logConsoleProgress, logConsoleInfo } from "../../Utils/NotificationConsoleUtils"; import { logConsoleProgress, logConsoleInfo, logConsoleError } from "../../Utils/NotificationConsoleUtils";
import { HttpHeaders } from "../Constants"; import { HttpHeaders } from "../Constants";
import { handleError } from "../ErrorHandlingUtils";
interface UpdateOfferThroughputRequest { interface UpdateOfferThroughputRequest {
subscriptionId: string; subscriptionId: string;
@@ -12,7 +11,6 @@ interface UpdateOfferThroughputRequest {
databaseName: string; databaseName: string;
collectionName?: string; collectionName?: string;
throughput: number; throughput: number;
offerIsRUPerMinuteThroughputEnabled: boolean;
offerAutopilotSettings?: AutoPilotOfferSettings; offerAutopilotSettings?: AutoPilotOfferSettings;
} }
@@ -45,13 +43,8 @@ export async function updateOfferThroughputBeyondLimit(request: UpdateOfferThrou
clearMessage(); clearMessage();
return undefined; return undefined;
} }
const error = await response.json(); const error = await response.json();
handleError( logConsoleError(`Failed to request an increase in throughput for ${request.throughput}: ${error.message}`);
error,
"updateOfferThroughputBeyondLimit",
`Failed to request an increase in throughput for ${request.throughput}`
);
clearMessage(); clearMessage();
throw error; throw new Error(error.message);
} }

View File

@@ -64,7 +64,7 @@ export async function updateStoredProcedure(
.replace(storedProcedure); .replace(storedProcedure);
return response?.resource; return response?.resource;
} catch (error) { } catch (error) {
handleError(error, "UpdateStoredProcedure", `Error while updating stored procedure ${storedProcedure.id}`); handleError(error, `Error while updating stored procedure ${storedProcedure.id}`, "UpdateStoredProcedure");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -61,7 +61,7 @@ export async function updateTrigger(
.replace(trigger); .replace(trigger);
return response?.resource; return response?.resource;
} catch (error) { } catch (error) {
handleError(error, "UpdateTrigger", `Error while updating trigger ${trigger.id}`); handleError(error, `Error while updating trigger ${trigger.id}`, "UpdateTrigger");
throw error; throw error;
} finally { } finally {
clearMessage(); clearMessage();

View File

@@ -66,8 +66,8 @@ export async function updateUserDefinedFunction(
} catch (error) { } catch (error) {
handleError( handleError(
error, error,
"UpdateUserupdateUserDefinedFunction", `Error while updating user defined function ${userDefinedFunction.id}`,
`Error while updating user defined function ${userDefinedFunction.id}` "UpdateUserupdateUserDefinedFunction"
); );
throw error; throw error;
} finally { } finally {

View File

@@ -179,7 +179,6 @@ export interface Offer extends Resource {
offerType?: string; offerType?: string;
content?: { content?: {
offerThroughput: number; offerThroughput: number;
offerIsRUPerMinuteThroughputEnabled: boolean;
collectionThroughputInfo?: OfferThroughputInfo; collectionThroughputInfo?: OfferThroughputInfo;
offerAutopilotSettings?: AutoPilotOfferSettings; offerAutopilotSettings?: AutoPilotOfferSettings;
}; };
@@ -216,12 +215,23 @@ export interface UniqueKey {
paths: string[]; paths: string[];
} }
// Returned by DocumentDb client proxy
// Inner errors in BackendErrorDataModel when error is in SQL syntax
export interface ErrorDataModel {
message: string;
severity?: string;
location?: {
start: string;
end: string;
};
code?: string;
}
export interface CreateDatabaseAndCollectionRequest { export interface CreateDatabaseAndCollectionRequest {
databaseId: string; databaseId: string;
collectionId: string; collectionId: string;
offerThroughput: number; offerThroughput: number;
databaseLevelThroughput: boolean; databaseLevelThroughput: boolean;
rupmEnabled?: boolean;
partitionKey?: PartitionKey; partitionKey?: PartitionKey;
indexingPolicy?: IndexingPolicy; indexingPolicy?: IndexingPolicy;
uniqueKeyPolicy?: UniqueKeyPolicy; uniqueKeyPolicy?: UniqueKeyPolicy;

View File

@@ -46,7 +46,7 @@ export interface LogEntry {
/** /**
* The message code. * The message code.
*/ */
code?: number | string; code?: number;
/** /**
* Any additional data to be logged. * Any additional data to be logged.
*/ */

View File

@@ -162,7 +162,6 @@ export interface Collection extends CollectionBase {
loadStoredProcedures(): Promise<any>; loadStoredProcedures(): Promise<any>;
loadTriggers(): Promise<any>; loadTriggers(): Promise<any>;
loadOffer(): Promise<void>; loadOffer(): Promise<void>;
loadAutopilotOfferWithRetry(): Promise<DataModels.Offer>;
createStoredProcedureNode(data: StoredProcedureDefinition & Resource): StoredProcedure; createStoredProcedureNode(data: StoredProcedureDefinition & Resource): StoredProcedure;
createUserDefinedFunctionNode(data: UserDefinedFunctionDefinition & Resource): UserDefinedFunction; createUserDefinedFunctionNode(data: UserDefinedFunctionDefinition & Resource): UserDefinedFunction;

View File

@@ -1,9 +1,12 @@
import * as React from "react"; import * as React from "react";
import { ArcadiaWorkspace, SparkPool } from "../../../Contracts/DataModels"; import { ArcadiaWorkspace, SparkPool } from "../../../Contracts/DataModels";
import { DefaultButton, IButtonStyles } from "office-ui-fabric-react/lib/Button"; import { DefaultButton, IButtonStyles } from "office-ui-fabric-react/lib/Button";
import { IContextualMenuItem, IContextualMenuProps } from "office-ui-fabric-react/lib/ContextualMenu"; import {
IContextualMenuItem,
IContextualMenuProps,
ContextualMenuItemType
} from "office-ui-fabric-react/lib/ContextualMenu";
import * as Logger from "../../../Common/Logger"; import * as Logger from "../../../Common/Logger";
import { getErrorMessage } from "../../../Common/ErrorHandlingUtils";
export interface ArcadiaMenuPickerProps { export interface ArcadiaMenuPickerProps {
selectText?: string; selectText?: string;
@@ -44,7 +47,7 @@ export class ArcadiaMenuPicker extends React.Component<ArcadiaMenuPickerProps, A
selectedSparkPool: item.text selectedSparkPool: item.text
}); });
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "ArcadiaMenuPicker/_onSparkPoolClicked"); Logger.logError(error, "ArcadiaMenuPicker/_onSparkPoolClicked");
throw error; throw error;
} }
}; };

View File

@@ -44,7 +44,6 @@ export const FeaturePanelComponent: React.FunctionComponent = () => {
onChange?: (_?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => void; onChange?: (_?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => void;
}[] = [ }[] = [
{ key: "feature.enablechangefeedpolicy", label: "Enable change feed policy", value: "true" }, { key: "feature.enablechangefeedpolicy", label: "Enable change feed policy", value: "true" },
{ key: "feature.enablerupm", label: "Enable RUPM", value: "true" },
{ key: "feature.dataexplorerexecutesproc", label: "Execute stored procedure", value: "true" }, { key: "feature.dataexplorerexecutesproc", label: "Execute stored procedure", value: "true" },
{ key: "feature.hosteddataexplorerenabled", label: "Hosted Data Explorer (deprecated?)", value: "true" }, { key: "feature.hosteddataexplorerenabled", label: "Hosted Data Explorer (deprecated?)", value: "true" },
{ key: "feature.enablettl", label: "Enable TTL", value: "true" }, { key: "feature.enablettl", label: "Enable TTL", value: "true" },

View File

@@ -131,12 +131,6 @@ exports[`Feature panel renders all flags 1`] = `
label="Enable change feed policy" label="Enable change feed policy"
onChange={[Function]} onChange={[Function]}
/> />
<StyledCheckboxBase
checked={false}
key="feature.enablerupm"
label="Enable RUPM"
onChange={[Function]}
/>
<StyledCheckboxBase <StyledCheckboxBase
checked={false} checked={false}
key="feature.dataexplorerexecutesproc" key="feature.dataexplorerexecutesproc"

View File

@@ -4,10 +4,12 @@
import * as React from "react"; import * as React from "react";
import * as DataModels from "../../../Contracts/DataModels"; import * as DataModels from "../../../Contracts/DataModels";
import * as Logger from "../../../Common/Logger";
import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils";
import { ConsoleDataType } from "../../Menus/NotificationConsole/NotificationConsoleComponent";
import { StringUtils } from "../../../Utils/StringUtils"; import { StringUtils } from "../../../Utils/StringUtils";
import { userContext } from "../../../UserContext"; import { userContext } from "../../../UserContext";
import { TerminalQueryParams } from "../../../Common/Constants"; import { TerminalQueryParams } from "../../../Common/Constants";
import { handleError } from "../../../Common/ErrorHandlingUtils";
export interface NotebookTerminalComponentProps { export interface NotebookTerminalComponentProps {
notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo; notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo;
@@ -69,10 +71,9 @@ export class NotebookTerminalComponent extends React.Component<NotebookTerminalC
params: Map<string, string> params: Map<string, string>
): string { ): string {
if (!serverInfo.notebookServerEndpoint) { if (!serverInfo.notebookServerEndpoint) {
handleError( const error = "Notebook server endpoint not defined. Terminal will fail to connect to jupyter server.";
"Notebook server endpoint not defined. Terminal will fail to connect to jupyter server.", Logger.logError(error, "NotebookTerminalComponent/createNotebookAppSrc");
"NotebookTerminalComponent/createNotebookAppSrc" NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
);
return ""; return "";
} }

View File

@@ -1,8 +1,9 @@
import * as React from "react"; import * as React from "react";
import { JunoClient } from "../../../Juno/JunoClient"; import { JunoClient } from "../../../Juno/JunoClient";
import { HttpStatusCodes, CodeOfConductEndpoints } from "../../../Common/Constants"; import { HttpStatusCodes, CodeOfConductEndpoints } from "../../../Common/Constants";
import * as Logger from "../../../Common/Logger";
import { logConsoleError } from "../../../Utils/NotificationConsoleUtils";
import { Stack, Text, Checkbox, PrimaryButton, Link } from "office-ui-fabric-react"; import { Stack, Text, Checkbox, PrimaryButton, Link } from "office-ui-fabric-react";
import { handleError } from "../../../Common/ErrorHandlingUtils";
export interface CodeOfConductComponentProps { export interface CodeOfConductComponentProps {
junoClient: JunoClient; junoClient: JunoClient;
@@ -44,7 +45,9 @@ export class CodeOfConductComponent extends React.Component<CodeOfConductCompone
this.props.onAcceptCodeOfConduct(response.data); this.props.onAcceptCodeOfConduct(response.data);
} catch (error) { } catch (error) {
handleError(error, "CodeOfConductComponent/acceptCodeOfConduct", "Failed to accept code of conduct"); const message = `Failed to accept code of conduct: ${error}`;
Logger.logError(message, "CodeOfConductComponent/acceptCodeOfConduct");
logConsoleError(message);
} }
} }

View File

@@ -16,8 +16,11 @@ import {
Text Text
} from "office-ui-fabric-react"; } from "office-ui-fabric-react";
import * as React from "react"; import * as React from "react";
import * as Logger from "../../../Common/Logger";
import { IGalleryItem, JunoClient, IJunoResponse, IPublicGalleryData } from "../../../Juno/JunoClient"; import { IGalleryItem, JunoClient, IJunoResponse, IPublicGalleryData } from "../../../Juno/JunoClient";
import * as GalleryUtils from "../../../Utils/GalleryUtils"; import * as GalleryUtils from "../../../Utils/GalleryUtils";
import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils";
import { ConsoleDataType } from "../../Menus/NotificationConsole/NotificationConsoleComponent";
import { DialogComponent, DialogProps } from "../DialogReactComponent/DialogComponent"; import { DialogComponent, DialogProps } from "../DialogReactComponent/DialogComponent";
import { GalleryCardComponent, GalleryCardComponentProps } from "./Cards/GalleryCardComponent"; import { GalleryCardComponent, GalleryCardComponentProps } from "./Cards/GalleryCardComponent";
import "./GalleryViewerComponent.less"; import "./GalleryViewerComponent.less";
@@ -25,7 +28,6 @@ import { HttpStatusCodes } from "../../../Common/Constants";
import Explorer from "../../Explorer"; import Explorer from "../../Explorer";
import { CodeOfConductComponent } from "./CodeOfConductComponent"; import { CodeOfConductComponent } from "./CodeOfConductComponent";
import { InfoComponent } from "./InfoComponent/InfoComponent"; import { InfoComponent } from "./InfoComponent/InfoComponent";
import { handleError } from "../../../Common/ErrorHandlingUtils";
export interface GalleryViewerComponentProps { export interface GalleryViewerComponentProps {
container?: Explorer; container?: Explorer;
@@ -352,7 +354,9 @@ export class GalleryViewerComponent extends React.Component<GalleryViewerCompone
this.sampleNotebooks = response.data; this.sampleNotebooks = response.data;
} catch (error) { } catch (error) {
handleError(error, "GalleryViewerComponent/loadSampleNotebooks", "Failed to load sample notebooks"); const message = `Failed to load sample notebooks: ${error}`;
Logger.logError(message, "GalleryViewerComponent/loadSampleNotebooks");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }
@@ -378,7 +382,9 @@ export class GalleryViewerComponent extends React.Component<GalleryViewerCompone
throw new Error(`Received HTTP ${response.status} when loading public notebooks`); throw new Error(`Received HTTP ${response.status} when loading public notebooks`);
} }
} catch (error) { } catch (error) {
handleError(error, "GalleryViewerComponent/loadPublicNotebooks", "Failed to load public notebooks"); const message = `Failed to load public notebooks: ${error}`;
Logger.logError(message, "GalleryViewerComponent/loadPublicNotebooks");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }
@@ -398,7 +404,9 @@ export class GalleryViewerComponent extends React.Component<GalleryViewerCompone
this.favoriteNotebooks = response.data; this.favoriteNotebooks = response.data;
} catch (error) { } catch (error) {
handleError(error, "GalleryViewerComponent/loadFavoriteNotebooks", "Failed to load favorite notebooks"); const message = `Failed to load favorite notebooks: ${error}`;
Logger.logError(message, "GalleryViewerComponent/loadFavoriteNotebooks");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }
@@ -424,7 +432,9 @@ export class GalleryViewerComponent extends React.Component<GalleryViewerCompone
this.publishedNotebooks = response.data; this.publishedNotebooks = response.data;
} catch (error) { } catch (error) {
handleError(error, "GalleryViewerComponent/loadPublishedNotebooks", "Failed to load published notebooks"); const message = `Failed to load published notebooks: ${error}`;
Logger.logError(message, "GalleryViewerComponent/loadPublishedNotebooks");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }

View File

@@ -21,7 +21,6 @@ import Explorer from "../../Explorer";
import { NotebookV4 } from "@nteract/commutable/lib/v4"; import { NotebookV4 } from "@nteract/commutable/lib/v4";
import { SessionStorageUtility } from "../../../Shared/StorageUtility"; import { SessionStorageUtility } from "../../../Shared/StorageUtility";
import { DialogHost } from "../../../Utils/GalleryUtils"; import { DialogHost } from "../../../Utils/GalleryUtils";
import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils";
export interface NotebookViewerComponentProps { export interface NotebookViewerComponentProps {
container?: Explorer; container?: Explorer;
@@ -101,7 +100,9 @@ export class NotebookViewerComponent extends React.Component<NotebookViewerCompo
} }
} catch (error) { } catch (error) {
this.setState({ showProgressBar: false }); this.setState({ showProgressBar: false });
handleError(error, "NotebookViewerComponent/loadNotebookContent", "Failed to load notebook content"); const message = `Failed to load notebook content: ${error}`;
Logger.logError(message, "NotebookViewerComponent/loadNotebookContent");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }

View File

@@ -28,7 +28,6 @@ import * as TelemetryProcessor from "../../../Shared/Telemetry/TelemetryProcesso
import SaveQueryBannerIcon from "../../../../images/save_query_banner.png"; import SaveQueryBannerIcon from "../../../../images/save_query_banner.png";
import { QueriesClient } from "../../../Common/QueriesClient"; import { QueriesClient } from "../../../Common/QueriesClient";
import { getErrorMessage, getErrorStack } from "../../../Common/ErrorHandlingUtils";
export interface QueriesGridComponentProps { export interface QueriesGridComponentProps {
queriesClient: QueriesClient; queriesClient: QueriesClient;
@@ -245,9 +244,7 @@ export class QueriesGridComponent extends React.Component<QueriesGridComponentPr
databaseAccountName: container && container.databaseAccount().name, databaseAccountName: container && container.databaseAccount().name,
defaultExperience: container && container.defaultExperience(), defaultExperience: container && container.defaultExperience(),
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
paneTitle: container && container.browseQueriesPane.title(), paneTitle: container && container.browseQueriesPane.title()
error: getErrorMessage(error),
errorStack: getErrorStack(error)
}, },
startKey startKey
); );

View File

@@ -8,8 +8,8 @@ import * as DataModels from "../../../Contracts/DataModels";
import ko from "knockout"; import ko from "knockout";
import { TtlType, isDirty } from "./SettingsUtils"; import { TtlType, isDirty } from "./SettingsUtils";
import Explorer from "../../Explorer"; import Explorer from "../../Explorer";
jest.mock("../../../Common/dataAccess/getIndexTransformationProgress", () => ({ jest.mock("../../../Common/dataAccess/readMongoDBCollection", () => ({
getIndexTransformationProgress: jest.fn().mockReturnValue(undefined) getMongoDBCollectionIndexTransformationProgress: jest.fn().mockReturnValue(undefined)
})); }));
import { updateCollection, updateMongoDBCollectionThroughRP } from "../../../Common/dataAccess/updateCollection"; import { updateCollection, updateMongoDBCollectionThroughRP } from "../../../Common/dataAccess/updateCollection";
jest.mock("../../../Common/dataAccess/updateCollection", () => ({ jest.mock("../../../Common/dataAccess/updateCollection", () => ({

View File

@@ -46,9 +46,10 @@ import { Pivot, PivotItem, IPivotProps, IPivotItemProps } from "office-ui-fabric
import "./SettingsComponent.less"; import "./SettingsComponent.less";
import { IndexingPolicyComponent, IndexingPolicyComponentProps } from "./SettingsSubComponents/IndexingPolicyComponent"; import { IndexingPolicyComponent, IndexingPolicyComponentProps } from "./SettingsSubComponents/IndexingPolicyComponent";
import { MongoDBCollectionResource, MongoIndex } from "../../../Utils/arm/generatedClients/2020-04-01/types"; import { MongoDBCollectionResource, MongoIndex } from "../../../Utils/arm/generatedClients/2020-04-01/types";
import { readMongoDBCollectionThroughRP } from "../../../Common/dataAccess/readMongoDBCollection"; import {
import { getIndexTransformationProgress } from "../../../Common/dataAccess/getIndexTransformationProgress"; getMongoDBCollectionIndexTransformationProgress,
import { getErrorMessage, getErrorStack } from "../../../Common/ErrorHandlingUtils"; readMongoDBCollectionThroughRP
} from "../../../Common/dataAccess/readMongoDBCollection";
interface SettingsV2TabInfo { interface SettingsV2TabInfo {
tab: SettingsV2TabTypes; tab: SettingsV2TabTypes;
@@ -210,7 +211,6 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
} }
componentDidMount(): void { componentDidMount(): void {
this.refreshIndexTransformationProgress();
this.loadMongoIndexes(); this.loadMongoIndexes();
this.setAutoPilotStates(); this.setAutoPilotStates();
this.setBaseline(); this.setBaseline();
@@ -232,6 +232,8 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
this.container.isEnableMongoCapabilityPresent() && this.container.isEnableMongoCapabilityPresent() &&
this.container.databaseAccount() this.container.databaseAccount()
) { ) {
await this.refreshIndexTransformationProgress();
this.mongoDBCollectionResource = await readMongoDBCollectionThroughRP( this.mongoDBCollectionResource = await readMongoDBCollectionThroughRP(
this.collection.databaseId, this.collection.databaseId,
this.collection.id() this.collection.id()
@@ -246,7 +248,10 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
}; };
public refreshIndexTransformationProgress = async (): Promise<void> => { public refreshIndexTransformationProgress = async (): Promise<void> => {
const currentProgress = await getIndexTransformationProgress(this.collection.databaseId, this.collection.id()); const currentProgress = await getMongoDBCollectionIndexTransformationProgress(
this.collection.databaseId,
this.collection.id()
);
this.setState({ indexTransformationProgress: currentProgress }); this.setState({ indexTransformationProgress: currentProgress });
}; };
@@ -346,7 +351,6 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
break; break;
} }
const wasIndexingPolicyModified = this.state.isIndexingPolicyDirty;
newCollection.defaultTtl = defaultTtl; newCollection.defaultTtl = defaultTtl;
newCollection.indexingPolicy = this.state.indexingPolicyContent; newCollection.indexingPolicy = this.state.indexingPolicyContent;
@@ -382,11 +386,6 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
this.collection.conflictResolutionPolicy(updatedCollection.conflictResolutionPolicy); this.collection.conflictResolutionPolicy(updatedCollection.conflictResolutionPolicy);
this.collection.changeFeedPolicy(updatedCollection.changeFeedPolicy); this.collection.changeFeedPolicy(updatedCollection.changeFeedPolicy);
this.collection.geospatialConfig(updatedCollection.geospatialConfig); this.collection.geospatialConfig(updatedCollection.geospatialConfig);
if (wasIndexingPolicyModified) {
await this.refreshIndexTransformationProgress();
}
this.setState({ this.setState({
isSubSettingsSaveable: false, isSubSettingsSaveable: false,
isSubSettingsDiscardable: false, isSubSettingsDiscardable: false,
@@ -438,8 +437,7 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab, dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle(), tabTitle: this.props.settingsTab.tabTitle(),
error: getErrorMessage(error), error: error.message
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -456,8 +454,7 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
newOffer.content.offerThroughput = newThroughput; newOffer.content.offerThroughput = newThroughput;
} else { } else {
newOffer.content = { newOffer.content = {
offerThroughput: newThroughput, offerThroughput: newThroughput
offerIsRUPerMinuteThroughputEnabled: false
}; };
} }
@@ -500,8 +497,7 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
resourceGroup: userContext.resourceGroup, resourceGroup: userContext.resourceGroup,
databaseName: this.collection.databaseId, databaseName: this.collection.databaseId,
collectionName: this.collection.id(), collectionName: this.collection.id(),
throughput: newThroughput, throughput: newThroughput
offerIsRUPerMinuteThroughputEnabled: false
}; };
await updateOfferThroughputBeyondLimit(requestPayload); await updateOfferThroughputBeyondLimit(requestPayload);
@@ -532,12 +528,11 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
} }
const updatedOffer: DataModels.Offer = await updateOffer(updateOfferParams); const updatedOffer: DataModels.Offer = await updateOffer(updateOfferParams);
this.collection.offer(updatedOffer); this.collection.offer(updatedOffer);
this.setState({ isScaleSaveable: false, isScaleDiscardable: false });
if (this.state.isAutoPilotSelected) { if (this.state.isAutoPilotSelected) {
const autoPilotOffer = await this.collection.loadAutopilotOfferWithRetry();
this.setState({ this.setState({
autoPilotThroughput: autoPilotOffer.content.offerAutopilotSettings.maxThroughput, autoPilotThroughput: updatedOffer.content.offerAutopilotSettings.maxThroughput,
autoPilotThroughputBaseline: autoPilotOffer.content.offerAutopilotSettings.maxThroughput autoPilotThroughputBaseline: updatedOffer.content.offerAutopilotSettings.maxThroughput
}); });
} else { } else {
this.setState({ this.setState({
@@ -545,8 +540,6 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
throughputBaseline: updatedOffer.content.offerThroughput throughputBaseline: updatedOffer.content.offerThroughput
}); });
} }
this.setState({ isScaleSaveable: false, isScaleDiscardable: false });
} }
} }
this.container.isRefreshingExplorer(false); this.container.isRefreshingExplorer(false);
@@ -564,10 +557,10 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
}, },
startKey startKey
); );
} catch (error) { } catch (reason) {
this.container.isRefreshingExplorer(false); this.container.isRefreshingExplorer(false);
this.props.settingsTab.isExecutionError(true); this.props.settingsTab.isExecutionError(true);
console.error(error); console.error(reason);
traceFailure( traceFailure(
Action.SettingsV2Updated, Action.SettingsV2Updated,
{ {
@@ -577,8 +570,7 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab, dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle(), tabTitle: this.props.settingsTab.tabTitle(),
error: getErrorMessage(error), error: reason.message
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -951,8 +943,6 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
indexingPolicyContentBaseline: this.state.indexingPolicyContentBaseline, indexingPolicyContentBaseline: this.state.indexingPolicyContentBaseline,
onIndexingPolicyContentChange: this.onIndexingPolicyContentChange, onIndexingPolicyContentChange: this.onIndexingPolicyContentChange,
logIndexingPolicySuccessMessage: this.logIndexingPolicySuccessMessage, logIndexingPolicySuccessMessage: this.logIndexingPolicySuccessMessage,
indexTransformationProgress: this.state.indexTransformationProgress,
refreshIndexTransformationProgress: this.refreshIndexTransformationProgress,
onIndexingPolicyDirtyChange: this.onIndexingPolicyDirtyChange onIndexingPolicyDirtyChange: this.onIndexingPolicyDirtyChange
}; };

View File

@@ -6,7 +6,7 @@ import {
getEstimatedAutoscaleSpendElement, getEstimatedAutoscaleSpendElement,
manualToAutoscaleDisclaimerElement, manualToAutoscaleDisclaimerElement,
ttlWarning, ttlWarning,
indexingPolicynUnsavedWarningMessage, indexingPolicyTTLWarningMessage,
updateThroughputBeyondLimitWarningMessage, updateThroughputBeyondLimitWarningMessage,
updateThroughputDelayedApplyWarningMessage, updateThroughputDelayedApplyWarningMessage,
getThroughputApplyDelayedMessage, getThroughputApplyDelayedMessage,
@@ -31,13 +31,13 @@ class SettingsRenderUtilsTestComponent extends React.Component {
{getAutoPilotV3SpendElement(1000, true)} {getAutoPilotV3SpendElement(1000, true)}
{getAutoPilotV3SpendElement(undefined, true)} {getAutoPilotV3SpendElement(undefined, true)}
{getEstimatedSpendElement(1000, "mooncake", 2, false, true)} {getEstimatedSpendElement(1000, "mooncake", 2, false)}
{getEstimatedAutoscaleSpendElement(1000, "mooncake", 2, false)} {getEstimatedAutoscaleSpendElement(1000, "mooncake", 2, false)}
{manualToAutoscaleDisclaimerElement} {manualToAutoscaleDisclaimerElement}
{ttlWarning} {ttlWarning}
{indexingPolicynUnsavedWarningMessage} {indexingPolicyTTLWarningMessage}
{updateThroughputBeyondLimitWarningMessage} {updateThroughputBeyondLimitWarningMessage}
{updateThroughputDelayedApplyWarningMessage} {updateThroughputDelayedApplyWarningMessage}

View File

@@ -36,7 +36,7 @@ import {
} from "office-ui-fabric-react"; } from "office-ui-fabric-react";
import { isDirtyTypes, isDirty } from "./SettingsUtils"; import { isDirtyTypes, isDirty } from "./SettingsUtils";
export const infoAndToolTipTextStyle: ITextStyles = { root: { fontSize: 12 } }; const infoAndToolTipTextStyle: ITextStyles = { root: { fontSize: 12 } };
export const noLeftPaddingCheckBoxStyle: ICheckboxStyles = { export const noLeftPaddingCheckBoxStyle: ICheckboxStyles = {
label: { label: {
@@ -199,10 +199,9 @@ export const getEstimatedSpendElement = (
throughput: number, throughput: number,
serverId: string, serverId: string,
regions: number, regions: number,
multimaster: boolean, multimaster: boolean
rupmEnabled: boolean
): JSX.Element => { ): JSX.Element => {
const hourlyPrice: number = computeRUUsagePriceHourly(serverId, rupmEnabled, throughput, regions, multimaster); const hourlyPrice: number = computeRUUsagePriceHourly(serverId, throughput, regions, multimaster);
const dailyPrice: number = hourlyPrice * 24; const dailyPrice: number = hourlyPrice * 24;
const monthlyPrice: number = hourlyPrice * hoursInAMonth; const monthlyPrice: number = hourlyPrice * hoursInAMonth;
const currency: string = getPriceCurrency(serverId); const currency: string = getPriceCurrency(serverId);
@@ -245,9 +244,15 @@ export const ttlWarning: JSX.Element = (
</Text> </Text>
); );
export const indexingPolicynUnsavedWarningMessage: JSX.Element = ( export const indexingPolicyTTLWarningMessage: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}> <Text styles={infoAndToolTipTextStyle}>
You have not saved the latest changes made to your indexing policy. Please click save to confirm the changes. Changing the Indexing Policy impacts query results while the index transformation occurs. When a change is made and
the indexing mode is set to consistent or lazy, queries return eventual results until the operation completes. For
more information see,{" "}
<Link target="_blank" href="https://aka.ms/cosmosdb/modify-index-policy">
Modifying Indexing Policies
</Link>
.
</Text> </Text>
); );
@@ -404,8 +409,8 @@ export const mongoIndexingPolicyAADError: JSX.Element = (
export const mongoIndexTransformationRefreshingMessage: JSX.Element = ( export const mongoIndexTransformationRefreshingMessage: JSX.Element = (
<Stack horizontal {...mongoWarningStackProps}> <Stack horizontal {...mongoWarningStackProps}>
<Text styles={infoAndToolTipTextStyle}>Refreshing index transformation progress</Text> <Text>Refreshing index transformation progress</Text>
<Spinner size={SpinnerSize.small} /> <Spinner size={SpinnerSize.medium} />
</Stack> </Stack>
); );
@@ -415,14 +420,14 @@ export const renderMongoIndexTransformationRefreshMessage = (
): JSX.Element => { ): JSX.Element => {
if (progress === 0) { if (progress === 0) {
return ( return (
<Text styles={infoAndToolTipTextStyle}> <Text>
{"You can make more indexing changes once the current index transformation is complete. "} {"You can make more indexing changes once the current index transformation is complete. "}
<Link onClick={performRefresh}>{"Refresh to check if it has completed."}</Link> <Link onClick={performRefresh}>{"Refresh to check if it has completed."}</Link>
</Text> </Text>
); );
} else { } else {
return ( return (
<Text styles={infoAndToolTipTextStyle}> <Text>
{`You can make more indexing changes once the current index transformation has completed. It is ${progress}% complete. `} {`You can make more indexing changes once the current index transformation has completed. It is ${progress}% complete. `}
<Link onClick={performRefresh}>{"Refresh to check the progress."}</Link> <Link onClick={performRefresh}>{"Refresh to check the progress."}</Link>
</Text> </Text>

View File

@@ -25,9 +25,7 @@ describe("IndexingPolicyComponent", () => {
}, },
onIndexingPolicyDirtyChange: () => { onIndexingPolicyDirtyChange: () => {
return; return;
}, }
indexTransformationProgress: undefined,
refreshIndexTransformationProgress: () => new Promise(jest.fn())
}; };
it("renders", () => { it("renders", () => {

View File

@@ -1,10 +1,9 @@
import * as React from "react"; import * as React from "react";
import * as DataModels from "../../../../Contracts/DataModels"; import * as DataModels from "../../../../Contracts/DataModels";
import * as monaco from "monaco-editor"; import * as monaco from "monaco-editor";
import { isDirty, isIndexTransforming } from "../SettingsUtils"; import { isDirty } from "../SettingsUtils";
import { MessageBar, MessageBarType, Stack } from "office-ui-fabric-react"; import { MessageBar, MessageBarType, Stack } from "office-ui-fabric-react";
import { indexingPolicynUnsavedWarningMessage, titleAndInputStackProps } from "../SettingsRenderUtils"; import { indexingPolicyTTLWarningMessage, titleAndInputStackProps } from "../SettingsRenderUtils";
import { IndexingPolicyRefreshComponent } from "./IndexingPolicyRefresh/IndexingPolicyRefreshComponent";
export interface IndexingPolicyComponentProps { export interface IndexingPolicyComponentProps {
shouldDiscardIndexingPolicy: boolean; shouldDiscardIndexingPolicy: boolean;
@@ -13,8 +12,6 @@ export interface IndexingPolicyComponentProps {
indexingPolicyContentBaseline: DataModels.IndexingPolicy; indexingPolicyContentBaseline: DataModels.IndexingPolicy;
onIndexingPolicyContentChange: (newIndexingPolicy: DataModels.IndexingPolicy) => void; onIndexingPolicyContentChange: (newIndexingPolicy: DataModels.IndexingPolicy) => void;
logIndexingPolicySuccessMessage: () => void; logIndexingPolicySuccessMessage: () => void;
indexTransformationProgress: number;
refreshIndexTransformationProgress: () => Promise<void>;
onIndexingPolicyDirtyChange: (isIndexingPolicyDirty: boolean) => void; onIndexingPolicyDirtyChange: (isIndexingPolicyDirty: boolean) => void;
} }
@@ -54,9 +51,6 @@ export class IndexingPolicyComponent extends React.Component<
if (!this.indexingPolicyEditor) { if (!this.indexingPolicyEditor) {
this.createIndexingPolicyEditor(); this.createIndexingPolicyEditor();
} else { } else {
this.indexingPolicyEditor.updateOptions({
readOnly: isIndexTransforming(this.props.indexTransformationProgress)
});
const indexingPolicyEditorModel = this.indexingPolicyEditor.getModel(); const indexingPolicyEditorModel = this.indexingPolicyEditor.getModel();
const value: string = JSON.stringify(this.props.indexingPolicyContent, undefined, 4); const value: string = JSON.stringify(this.props.indexingPolicyContent, undefined, 4);
indexingPolicyEditorModel.setValue(value); indexingPolicyEditorModel.setValue(value);
@@ -90,7 +84,7 @@ export class IndexingPolicyComponent extends React.Component<
this.indexingPolicyEditor = monaco.editor.create(this.indexingPolicyDiv.current, { this.indexingPolicyEditor = monaco.editor.create(this.indexingPolicyDiv.current, {
value: value, value: value,
language: "json", language: "json",
readOnly: isIndexTransforming(this.props.indexTransformationProgress), readOnly: false,
ariaLabel: "Indexing Policy" ariaLabel: "Indexing Policy"
}); });
if (this.indexingPolicyEditor) { if (this.indexingPolicyEditor) {
@@ -114,12 +108,8 @@ export class IndexingPolicyComponent extends React.Component<
public render(): JSX.Element { public render(): JSX.Element {
return ( return (
<Stack {...titleAndInputStackProps}> <Stack {...titleAndInputStackProps}>
<IndexingPolicyRefreshComponent
indexTransformationProgress={this.props.indexTransformationProgress}
refreshIndexTransformationProgress={this.props.refreshIndexTransformationProgress}
/>
{isDirty(this.props.indexingPolicyContent, this.props.indexingPolicyContentBaseline) && ( {isDirty(this.props.indexingPolicyContent, this.props.indexingPolicyContentBaseline) && (
<MessageBar messageBarType={MessageBarType.warning}>{indexingPolicynUnsavedWarningMessage}</MessageBar> <MessageBar messageBarType={MessageBarType.warning}>{indexingPolicyTTLWarningMessage}</MessageBar>
)} )}
<div className="settingsV2IndexingPolicyEditor" tabIndex={0} ref={this.indexingPolicyDiv}></div> <div className="settingsV2IndexingPolicyEditor" tabIndex={0} ref={this.indexingPolicyDiv}></div>
</Stack> </Stack>

View File

@@ -1,15 +0,0 @@
import { shallow } from "enzyme";
import React from "react";
import { IndexingPolicyRefreshComponentProps, IndexingPolicyRefreshComponent } from "./IndexingPolicyRefreshComponent";
describe("IndexingPolicyRefreshComponent", () => {
it("renders", () => {
const props: IndexingPolicyRefreshComponentProps = {
indexTransformationProgress: 90,
refreshIndexTransformationProgress: () => new Promise(jest.fn())
};
const wrapper = shallow(<IndexingPolicyRefreshComponent {...props} />);
expect(wrapper).toMatchSnapshot();
});
});

View File

@@ -1,62 +0,0 @@
import * as React from "react";
import { MessageBar, MessageBarType } from "office-ui-fabric-react";
import {
mongoIndexTransformationRefreshingMessage,
renderMongoIndexTransformationRefreshMessage
} from "../../SettingsRenderUtils";
import { handleError } from "../../../../../Common/ErrorHandlingUtils";
import { isIndexTransforming } from "../../SettingsUtils";
export interface IndexingPolicyRefreshComponentProps {
indexTransformationProgress: number;
refreshIndexTransformationProgress: () => Promise<void>;
}
interface IndexingPolicyRefreshComponentState {
isRefreshing: boolean;
}
export class IndexingPolicyRefreshComponent extends React.Component<
IndexingPolicyRefreshComponentProps,
IndexingPolicyRefreshComponentState
> {
constructor(props: IndexingPolicyRefreshComponentProps) {
super(props);
this.state = {
isRefreshing: false
};
}
private onClickRefreshIndexingTransformationLink = async () => await this.refreshIndexTransformationProgress();
private renderIndexTransformationWarning = (): JSX.Element => {
if (this.state.isRefreshing) {
return mongoIndexTransformationRefreshingMessage;
} else if (isIndexTransforming(this.props.indexTransformationProgress)) {
return renderMongoIndexTransformationRefreshMessage(
this.props.indexTransformationProgress,
this.onClickRefreshIndexingTransformationLink
);
}
return undefined;
};
private refreshIndexTransformationProgress = async () => {
this.setState({ isRefreshing: true });
try {
await this.props.refreshIndexTransformationProgress();
} catch (error) {
handleError(error, "RefreshIndexTransformationProgress", "Refreshing index transformation progress failed");
} finally {
this.setState({ isRefreshing: false });
}
};
public render(): JSX.Element {
return this.renderIndexTransformationWarning() ? (
<MessageBar messageBarType={MessageBarType.warning}>{this.renderIndexTransformationWarning()}</MessageBar>
) : (
<></>
);
}
}

View File

@@ -1,24 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`IndexingPolicyRefreshComponent renders 1`] = `
<StyledMessageBarBase
messageBarType={5}
>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
You can make more indexing changes once the current index transformation has completed. It is 90% complete.
<StyledLinkBase
onClick={[Function]}
>
Refresh to check the progress.
</StyledLinkBase>
</Text>
</StyledMessageBarBase>
`;

View File

@@ -2,7 +2,6 @@ import { shallow } from "enzyme";
import React from "react"; import React from "react";
import { MongoIndexTypes, MongoNotificationMessage, MongoNotificationType } from "../../SettingsUtils"; import { MongoIndexTypes, MongoNotificationMessage, MongoNotificationType } from "../../SettingsUtils";
import { MongoIndexingPolicyComponent, MongoIndexingPolicyComponentProps } from "./MongoIndexingPolicyComponent"; import { MongoIndexingPolicyComponent, MongoIndexingPolicyComponentProps } from "./MongoIndexingPolicyComponent";
import { renderToString } from "react-dom/server";
describe("MongoIndexingPolicyComponent", () => { describe("MongoIndexingPolicyComponent", () => {
const baseProps: MongoIndexingPolicyComponentProps = { const baseProps: MongoIndexingPolicyComponentProps = {
@@ -22,7 +21,10 @@ describe("MongoIndexingPolicyComponent", () => {
return; return;
}, },
indexTransformationProgress: undefined, indexTransformationProgress: undefined,
refreshIndexTransformationProgress: () => new Promise(jest.fn()), refreshIndexTransformationProgress: () =>
new Promise(() => {
return;
}),
onMongoIndexingPolicySaveableChange: () => { onMongoIndexingPolicySaveableChange: () => {
return; return;
}, },
@@ -36,6 +38,16 @@ describe("MongoIndexingPolicyComponent", () => {
expect(wrapper).toMatchSnapshot(); expect(wrapper).toMatchSnapshot();
}); });
it("isIndexingTransforming", () => {
const wrapper = shallow(<MongoIndexingPolicyComponent {...baseProps} />);
const mongoIndexingPolicyComponent = wrapper.instance() as MongoIndexingPolicyComponent;
expect(mongoIndexingPolicyComponent.isIndexingTransforming()).toEqual(false);
wrapper.setProps({ indexTransformationProgress: 50 });
expect(mongoIndexingPolicyComponent.isIndexingTransforming()).toEqual(true);
wrapper.setProps({ indexTransformationProgress: 100 });
expect(mongoIndexingPolicyComponent.isIndexingTransforming()).toEqual(false);
});
describe("AddMongoIndexProps test", () => { describe("AddMongoIndexProps test", () => {
const wrapper = shallow(<MongoIndexingPolicyComponent {...baseProps} />); const wrapper = shallow(<MongoIndexingPolicyComponent {...baseProps} />);
const mongoIndexingPolicyComponent = wrapper.instance() as MongoIndexingPolicyComponent; const mongoIndexingPolicyComponent = wrapper.instance() as MongoIndexingPolicyComponent;
@@ -43,7 +55,7 @@ describe("MongoIndexingPolicyComponent", () => {
it("defaults", () => { it("defaults", () => {
expect(mongoIndexingPolicyComponent.isMongoIndexingPolicySaveable()).toEqual(false); expect(mongoIndexingPolicyComponent.isMongoIndexingPolicySaveable()).toEqual(false);
expect(mongoIndexingPolicyComponent.isMongoIndexingPolicyDiscardable()).toEqual(false); expect(mongoIndexingPolicyComponent.isMongoIndexingPolicyDiscardable()).toEqual(false);
expect(mongoIndexingPolicyComponent.getMongoWarningNotificationMessage()).toBeUndefined(); expect(mongoIndexingPolicyComponent.getMongoWarningNotificationMessage()).toEqual(undefined);
}); });
const sampleWarning = "sampleWarning"; const sampleWarning = "sampleWarning";
@@ -101,12 +113,9 @@ describe("MongoIndexingPolicyComponent", () => {
expect(mongoIndexingPolicyComponent.isMongoIndexingPolicyDiscardable()).toEqual( expect(mongoIndexingPolicyComponent.isMongoIndexingPolicyDiscardable()).toEqual(
isMongoIndexingPolicyDiscardable isMongoIndexingPolicyDiscardable
); );
if (mongoWarningNotificationMessage) { expect(mongoIndexingPolicyComponent.getMongoWarningNotificationMessage()).toEqual(
const elementAsString = renderToString(mongoIndexingPolicyComponent.getMongoWarningNotificationMessage()); mongoWarningNotificationMessage
expect(elementAsString).toContain(mongoWarningNotificationMessage); );
} else {
expect(mongoIndexingPolicyComponent.getMongoWarningNotificationMessage()).toBeUndefined();
}
} }
); );
}); });

View File

@@ -25,8 +25,8 @@ import {
createAndAddMongoIndexStackProps, createAndAddMongoIndexStackProps,
separatorStyles, separatorStyles,
mongoIndexingPolicyAADError, mongoIndexingPolicyAADError,
indexingPolicynUnsavedWarningMessage, mongoIndexTransformationRefreshingMessage,
infoAndToolTipTextStyle renderMongoIndexTransformationRefreshMessage
} from "../../SettingsRenderUtils"; } from "../../SettingsRenderUtils";
import { MongoIndex } from "../../../../../Utils/arm/generatedClients/2020-04-01/types"; import { MongoIndex } from "../../../../../Utils/arm/generatedClients/2020-04-01/types";
import { import {
@@ -35,13 +35,12 @@ import {
MongoIndexIdField, MongoIndexIdField,
MongoNotificationType, MongoNotificationType,
getMongoIndexType, getMongoIndexType,
getMongoIndexTypeText, getMongoIndexTypeText
isIndexTransforming
} from "../../SettingsUtils"; } from "../../SettingsUtils";
import { AddMongoIndexComponent } from "./AddMongoIndexComponent"; import { AddMongoIndexComponent } from "./AddMongoIndexComponent";
import { CollapsibleSectionComponent } from "../../../CollapsiblePanel/CollapsibleSectionComponent"; import { CollapsibleSectionComponent } from "../../../CollapsiblePanel/CollapsibleSectionComponent";
import { handleError } from "../../../../../Common/ErrorHandlingUtils";
import { AuthType } from "../../../../../AuthType"; import { AuthType } from "../../../../../AuthType";
import { IndexingPolicyRefreshComponent } from "../IndexingPolicyRefresh/IndexingPolicyRefreshComponent";
export interface MongoIndexingPolicyComponentProps { export interface MongoIndexingPolicyComponentProps {
mongoIndexes: MongoIndex[]; mongoIndexes: MongoIndex[];
@@ -57,13 +56,20 @@ export interface MongoIndexingPolicyComponentProps {
onMongoIndexingPolicyDiscardableChange: (isMongoIndexingPolicyDiscardable: boolean) => void; onMongoIndexingPolicyDiscardableChange: (isMongoIndexingPolicyDiscardable: boolean) => void;
} }
interface MongoIndexingPolicyComponentState {
isRefreshingIndexTransformationProgress: boolean;
}
interface MongoIndexDisplayProps { interface MongoIndexDisplayProps {
definition: JSX.Element; definition: JSX.Element;
type: JSX.Element; type: JSX.Element;
actionButton: JSX.Element; actionButton: JSX.Element;
} }
export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingPolicyComponentProps> { export class MongoIndexingPolicyComponent extends React.Component<
MongoIndexingPolicyComponentProps,
MongoIndexingPolicyComponentState
> {
private shouldCheckComponentIsDirty = true; private shouldCheckComponentIsDirty = true;
private addMongoIndexComponentRefs: React.RefObject<AddMongoIndexComponent>[] = []; private addMongoIndexComponentRefs: React.RefObject<AddMongoIndexComponent>[] = [];
private initialIndexesColumns: IColumn[] = [ private initialIndexesColumns: IColumn[] = [
@@ -92,6 +98,13 @@ export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingP
} }
]; ];
constructor(props: MongoIndexingPolicyComponentProps) {
super(props);
this.state = {
isRefreshingIndexTransformationProgress: false
};
}
componentDidUpdate(prevProps: MongoIndexingPolicyComponentProps): void { componentDidUpdate(prevProps: MongoIndexingPolicyComponentProps): void {
if (this.props.indexesToAdd.length > prevProps.indexesToAdd.length) { if (this.props.indexesToAdd.length > prevProps.indexesToAdd.length) {
this.addMongoIndexComponentRefs[prevProps.indexesToAdd.length]?.current?.focus(); this.addMongoIndexComponentRefs[prevProps.indexesToAdd.length]?.current?.focus();
@@ -131,15 +144,10 @@ export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingP
return this.props.indexesToAdd.length > 0 || this.props.indexesToDrop.length > 0; return this.props.indexesToAdd.length > 0 || this.props.indexesToDrop.length > 0;
}; };
public getMongoWarningNotificationMessage = (): JSX.Element => { public getMongoWarningNotificationMessage = (): string => {
const warningMessage = this.props.indexesToAdd.find( return this.props.indexesToAdd.find(
addMongoIndexProps => addMongoIndexProps.notification?.type === MongoNotificationType.Warning addMongoIndexProps => addMongoIndexProps.notification?.type === MongoNotificationType.Warning
)?.notification.message; )?.notification.message;
if (warningMessage) {
return <Text styles={infoAndToolTipTextStyle}>{warningMessage}</Text>;
}
return undefined;
}; };
private onRenderRow = (props: IDetailsRowProps): JSX.Element => { private onRenderRow = (props: IDetailsRowProps): JSX.Element => {
@@ -151,7 +159,7 @@ export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingP
<IconButton <IconButton
ariaLabel="Delete index Button" ariaLabel="Delete index Button"
iconProps={{ iconName: "Delete" }} iconProps={{ iconName: "Delete" }}
disabled={isIndexTransforming(this.props.indexTransformationProgress)} disabled={this.isIndexingTransforming()}
onClick={() => { onClick={() => {
this.props.onIndexDrop(arrayPosition); this.props.onIndexDrop(arrayPosition);
}} }}
@@ -222,7 +230,7 @@ export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingP
<AddMongoIndexComponent <AddMongoIndexComponent
ref={this.addMongoIndexComponentRefs[indexesToAddLength]} ref={this.addMongoIndexComponentRefs[indexesToAddLength]}
disabled={isIndexTransforming(this.props.indexTransformationProgress)} disabled={this.isIndexingTransforming()}
position={indexesToAddLength} position={indexesToAddLength}
key={indexesToAddLength} key={indexesToAddLength}
description={undefined} description={undefined}
@@ -290,21 +298,55 @@ export class MongoIndexingPolicyComponent extends React.Component<MongoIndexingP
); );
}; };
private refreshIndexTransformationProgress = async () => {
this.setState({ isRefreshingIndexTransformationProgress: true });
try {
await this.props.refreshIndexTransformationProgress();
} catch (error) {
handleError(error, "Refreshing index transformation progress failed.", "RefreshIndexTransformationProgress");
} finally {
this.setState({ isRefreshingIndexTransformationProgress: false });
}
};
public isIndexingTransforming = (): boolean =>
// index transformation progress can be 0
this.props.indexTransformationProgress !== undefined && this.props.indexTransformationProgress !== 100;
private onClickRefreshIndexingTransformationLink = async () => await this.refreshIndexTransformationProgress();
private renderIndexTransformationWarning = (): JSX.Element => {
if (this.state.isRefreshingIndexTransformationProgress) {
return mongoIndexTransformationRefreshingMessage;
} else if (this.isIndexingTransforming()) {
return renderMongoIndexTransformationRefreshMessage(
this.props.indexTransformationProgress,
this.onClickRefreshIndexingTransformationLink
);
}
return undefined;
};
private renderWarningMessage = (): JSX.Element => { private renderWarningMessage = (): JSX.Element => {
let warningMessage: JSX.Element; let warningMessage: string;
if (this.getMongoWarningNotificationMessage()) { if (this.getMongoWarningNotificationMessage()) {
warningMessage = this.getMongoWarningNotificationMessage(); warningMessage = this.getMongoWarningNotificationMessage();
} else if (this.isMongoIndexingPolicySaveable()) { } else if (this.isMongoIndexingPolicySaveable()) {
warningMessage = indexingPolicynUnsavedWarningMessage; warningMessage =
"You have not saved the latest changes made to your indexing policy. Please click save to confirm the changes.";
} }
return ( return (
<> <>
<IndexingPolicyRefreshComponent {this.renderIndexTransformationWarning() && (
indexTransformationProgress={this.props.indexTransformationProgress} <MessageBar messageBarType={MessageBarType.warning}>{this.renderIndexTransformationWarning()}</MessageBar>
refreshIndexTransformationProgress={this.props.refreshIndexTransformationProgress} )}
/>
{warningMessage && <MessageBar messageBarType={MessageBarType.warning}>{warningMessage}</MessageBar>} {warningMessage && (
<MessageBar messageBarType={MessageBarType.warning}>
<Text>{warningMessage}</Text>
</MessageBar>
)}
</> </>
); );
}; };

View File

@@ -8,9 +8,6 @@ exports[`MongoIndexingPolicyComponent renders 1`] = `
} }
} }
> >
<IndexingPolicyRefreshComponent
refreshIndexTransformationProgress={[Function]}
/>
<Text> <Text>
For queries that filter on multiple properties, create multiple single field indexes instead of a compound index. For queries that filter on multiple properties, create multiple single field indexes instead of a compound index.
<StyledLinkBase <StyledLinkBase

View File

@@ -174,8 +174,7 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
this.overrideWithAutoPilotSettings() ? this.props.maxAutoPilotThroughput : offerThroughput, this.overrideWithAutoPilotSettings() ? this.props.maxAutoPilotThroughput : offerThroughput,
serverId, serverId,
regions, regions,
multimaster, multimaster
false
); );
} else { } else {
estimatedSpend = getEstimatedAutoscaleSpendElement( estimatedSpend = getEstimatedAutoscaleSpendElement(

View File

@@ -8,9 +8,6 @@ exports[`IndexingPolicyComponent renders 1`] = `
} }
} }
> >
<IndexingPolicyRefreshComponent
refreshIndexTransformationProgress={[Function]}
/>
<div <div
className="settingsV2IndexingPolicyEditor" className="settingsV2IndexingPolicyEditor"
tabIndex={0} tabIndex={0}

View File

@@ -15,8 +15,7 @@ import {
MongoWildcardPlaceHolder, MongoWildcardPlaceHolder,
getMongoIndexTypeText, getMongoIndexTypeText,
SingleFieldText, SingleFieldText,
WildcardText, WildcardText
isIndexTransforming
} from "./SettingsUtils"; } from "./SettingsUtils";
import * as DataModels from "../../../Contracts/DataModels"; import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels"; import * as ViewModels from "../../../Contracts/ViewModels";
@@ -140,10 +139,3 @@ describe("SettingsUtils", () => {
expect(notification.type).toEqual(MongoNotificationType.Error); expect(notification.type).toEqual(MongoNotificationType.Error);
}); });
}); });
it("isIndexingTransforming", () => {
expect(isIndexTransforming(undefined)).toBeFalsy();
expect(isIndexTransforming(0)).toBeTruthy();
expect(isIndexTransforming(90)).toBeTruthy();
expect(isIndexTransforming(100)).toBeFalsy();
});

View File

@@ -250,7 +250,3 @@ export const getMongoIndexTypeText = (index: MongoIndexTypes): string => {
} }
return WildcardText; return WildcardText;
}; };
export const isIndexTransforming = (indexTransformationProgress: number): boolean =>
// index transformation progress can be 0
indexTransformationProgress !== undefined && indexTransformationProgress !== 100;

View File

@@ -22,7 +22,6 @@ export const collection = ({
offer: ko.observable<DataModels.Offer>({ offer: ko.observable<DataModels.Offer>({
content: { content: {
offerThroughput: 10000, offerThroughput: 10000,
offerIsRUPerMinuteThroughputEnabled: false,
collectionThroughputInfo: { collectionThroughputInfo: {
minimumRUForCollection: 6000, minimumRUForCollection: 6000,
numPhysicalPartitions: 4 numPhysicalPartitions: 4

View File

@@ -133,8 +133,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -622,8 +620,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -1413,8 +1409,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -1902,8 +1896,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -2706,8 +2698,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -3195,8 +3185,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -3986,8 +3974,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -4475,8 +4461,6 @@ exports[`SettingsComponent renders 1`] = `
"partitionKeyVisible": [Function], "partitionKeyVisible": [Function],
"requestUnitsUsageCost": [Function], "requestUnitsUsageCost": [Function],
"ruToolTipText": [Function], "ruToolTipText": [Function],
"rupm": [Function],
"rupmVisible": [Function],
"sharedAutoPilotThroughput": [Function], "sharedAutoPilotThroughput": [Function],
"sharedThroughputRangeText": [Function], "sharedThroughputRangeText": [Function],
"shouldCreateMongoWildcardIndex": [Function], "shouldCreateMongoWildcardIndex": [Function],
@@ -5189,7 +5173,6 @@ exports[`SettingsComponent renders 1`] = `
logIndexingPolicySuccessMessage={[Function]} logIndexingPolicySuccessMessage={[Function]}
onIndexingPolicyContentChange={[Function]} onIndexingPolicyContentChange={[Function]}
onIndexingPolicyDirtyChange={[Function]} onIndexingPolicyDirtyChange={[Function]}
refreshIndexTransformationProgress={[Function]}
resetShouldDiscardIndexingPolicy={[Function]} resetShouldDiscardIndexingPolicy={[Function]}
shouldDiscardIndexingPolicy={false} shouldDiscardIndexingPolicy={false}
/> />

View File

@@ -69,15 +69,15 @@ exports[`SettingsUtils functions render 1`] = `
<b> <b>
¥ ¥
1.29 1.02
hourly hourly
/ /
¥ ¥
31.06 24.48
daily daily
/ /
¥ ¥
944.60 744.60
monthly monthly
</b> </b>
@@ -166,7 +166,15 @@ exports[`SettingsUtils functions render 1`] = `
} }
} }
> >
You have not saved the latest changes made to your indexing policy. Please click save to confirm the changes. Changing the Indexing Policy impacts query results while the index transformation occurs. When a change is made and the indexing mode is set to consistent or lazy, queries return eventual results until the operation completes. For more information see,
<StyledLinkBase
href="https://aka.ms/cosmosdb/modify-index-policy"
target="_blank"
>
Modifying Indexing Policies
</StyledLinkBase>
.
</Text> </Text>
<Text <Text
id="updateThroughputBeyondLimitWarningMessage" id="updateThroughputBeyondLimitWarningMessage"
@@ -333,30 +341,14 @@ exports[`SettingsUtils functions render 1`] = `
} }
} }
> >
<Text <Text>
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
Refreshing index transformation progress Refreshing index transformation progress
</Text> </Text>
<StyledSpinnerBase <StyledSpinnerBase
size={1} size={2}
/> />
</Stack> </Stack>
<Text <Text>
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
You can make more indexing changes once the current index transformation is complete. You can make more indexing changes once the current index transformation is complete.
<StyledLinkBase <StyledLinkBase
onClick={[Function]} onClick={[Function]}
@@ -364,15 +356,7 @@ exports[`SettingsUtils functions render 1`] = `
Refresh to check if it has completed. Refresh to check if it has completed.
</StyledLinkBase> </StyledLinkBase>
</Text> </Text>
<Text <Text>
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
You can make more indexing changes once the current index transformation has completed. It is 90% complete. You can make more indexing changes once the current index transformation has completed. It is 90% complete.
<StyledLinkBase <StyledLinkBase
onClick={[Function]} onClick={[Function]}

View File

@@ -86,7 +86,6 @@ import { CommandButtonComponentProps } from "./Controls/CommandButton/CommandBut
import { updateUserContext, userContext } from "../UserContext"; import { updateUserContext, userContext } from "../UserContext";
import { stringToBlob } from "../Utils/BlobUtils"; import { stringToBlob } from "../Utils/BlobUtils";
import { IChoiceGroupProps } from "office-ui-fabric-react"; import { IChoiceGroupProps } from "office-ui-fabric-react";
import { getErrorMessage, handleError, getErrorStack } from "../Common/ErrorHandlingUtils";
BindingHandlersRegisterer.registerBindingHandlers(); BindingHandlersRegisterer.registerBindingHandlers();
// Hold a reference to ComponentRegisterer to prevent transpiler to ignore import // Hold a reference to ComponentRegisterer to prevent transpiler to ignore import
@@ -1040,11 +1039,11 @@ export default class Explorer {
); );
TelemetryProcessor.traceSuccess(Action.EnableAzureSynapseLink, startTime); TelemetryProcessor.traceSuccess(Action.EnableAzureSynapseLink, startTime);
this.databaseAccount(databaseAccount); this.databaseAccount(databaseAccount);
} catch (error) { } catch (e) {
NotificationConsoleUtils.clearInProgressMessageWithId(logId); NotificationConsoleUtils.clearInProgressMessageWithId(logId);
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error, ConsoleDataType.Error,
`Enabling Azure Synapse Link for this account failed. ${getErrorMessage(error)}` `Enabling Azure Synapse Link for this account failed. ${e.message || JSON.stringify(e)}`
); );
TelemetryProcessor.traceFailure(Action.EnableAzureSynapseLink, startTime); TelemetryProcessor.traceFailure(Action.EnableAzureSynapseLink, startTime);
} finally { } finally {
@@ -1113,7 +1112,7 @@ export default class Explorer {
); );
this.renewExplorerShareAccess(this, this.tokenForRenewal()) this.renewExplorerShareAccess(this, this.tokenForRenewal())
.fail((error: any) => { .fail((error: any) => {
const stringifiedError: string = getErrorMessage(error); const stringifiedError: string = error.message;
this.renewTokenError("Invalid connection string specified"); this.renewTokenError("Invalid connection string specified");
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error, ConsoleDataType.Error,
@@ -1142,7 +1141,7 @@ export default class Explorer {
NotificationConsoleUtils.clearInProgressMessageWithId(id); NotificationConsoleUtils.clearInProgressMessageWithId(id);
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error, ConsoleDataType.Error,
`Failed to generate share url: ${getErrorMessage(error)}` `Failed to generate share url: ${error.message}`
); );
console.error(error); console.error(error);
} }
@@ -1167,10 +1166,7 @@ export default class Explorer {
deferred.resolve(); deferred.resolve();
}, },
(error: any) => { (error: any) => {
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, `Failed to connect: ${error.message}`);
ConsoleDataType.Error,
`Failed to connect: ${getErrorMessage(error)}`
);
deferred.reject(error); deferred.reject(error);
} }
) )
@@ -1444,21 +1440,19 @@ export default class Explorer {
this._setLoadingStatusText("Failed to fetch databases."); this._setLoadingStatusText("Failed to fetch databases.");
this.isRefreshingExplorer(false); this.isRefreshingExplorer(false);
deferred.reject(error); deferred.reject(error);
const errorMessage = getErrorMessage(error);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.LoadDatabases, Action.LoadDatabases,
{ {
databaseAccountName: this.databaseAccount().name, databaseAccountName: this.databaseAccount().name,
defaultExperience: this.defaultExperience(), defaultExperience: this.defaultExperience(),
dataExplorerArea: Constants.Areas.ResourceTree, dataExplorerArea: Constants.Areas.ResourceTree,
error: errorMessage, error: error.message
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error, ConsoleDataType.Error,
`Error while refreshing databases: ${errorMessage}` `Error while refreshing databases: ${error.message}`
); );
} }
); );
@@ -1477,7 +1471,7 @@ export default class Explorer {
); );
} }
}, },
error => { reason => {
if (resourceTreeStartKey != null) { if (resourceTreeStartKey != null) {
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.LoadResourceTree, Action.LoadResourceTree,
@@ -1485,8 +1479,7 @@ export default class Explorer {
databaseAccountName: this.databaseAccount() && this.databaseAccount().name, databaseAccountName: this.databaseAccount() && this.databaseAccount().name,
defaultExperience: this.defaultExperience && this.defaultExperience(), defaultExperience: this.defaultExperience && this.defaultExperience(),
dataExplorerArea: Constants.Areas.ResourceTree, dataExplorerArea: Constants.Areas.ResourceTree,
error: getErrorMessage(error), error: reason
errorStack: getErrorStack(error)
}, },
resourceTreeStartKey resourceTreeStartKey
); );
@@ -1535,7 +1528,7 @@ export default class Explorer {
resolve(token); resolve(token);
}, },
(error: any) => { (error: any) => {
Logger.logError(getErrorMessage(error), "Explorer/getArcadiaToken"); Logger.logError(error, "Explorer/getArcadiaToken");
resolve(undefined); resolve(undefined);
} }
); );
@@ -1553,7 +1546,7 @@ export default class Explorer {
workspaceItems[i] = { ...workspace, sparkPools: sparkpools }; workspaceItems[i] = { ...workspace, sparkPools: sparkpools };
}, },
error => { error => {
Logger.logError(getErrorMessage(error), "Explorer/this._arcadiaManager.listSparkPoolsAsync"); Logger.logError(error, "Explorer/this._arcadiaManager.listSparkPoolsAsync");
} }
); );
sparkPromises.push(promise); sparkPromises.push(promise);
@@ -1561,7 +1554,8 @@ export default class Explorer {
return Promise.all(sparkPromises).then(() => workspaceItems); return Promise.all(sparkPromises).then(() => workspaceItems);
} catch (error) { } catch (error) {
handleError(error, "Explorer/this._arcadiaManager.listWorkspacesAsync", "Get Arcadia workspaces failed"); Logger.logError(error, "Explorer/this._arcadiaManager.listWorkspacesAsync");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error.message);
return Promise.resolve([]); return Promise.resolve([]);
} }
} }
@@ -1596,10 +1590,10 @@ export default class Explorer {
); );
} catch (error) { } catch (error) {
this._isInitializingNotebooks = false; this._isInitializingNotebooks = false;
handleError( Logger.logError(error, "initNotebooks/getNotebookConnectionInfoAsync");
error, NotificationConsoleUtils.logConsoleMessage(
"initNotebooks/getNotebookConnectionInfoAsync", ConsoleDataType.Error,
`Failed to get notebook workspace connection info: ${getErrorMessage(error)}` `Failed to get notebook workspace connection info: ${error.message}`
); );
throw error; throw error;
} finally { } finally {
@@ -1622,10 +1616,9 @@ export default class Explorer {
public resetNotebookWorkspace() { public resetNotebookWorkspace() {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookClient) {
handleError( const error = "Attempt to reset notebook workspace, but notebook is not enabled";
"Attempt to reset notebook workspace, but notebook is not enabled", Logger.logError(error, "Explorer/resetNotebookWorkspace");
"Explorer/resetNotebookWorkspace" NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
);
return; return;
} }
const resetConfirmationDialogProps: DialogProps = { const resetConfirmationDialogProps: DialogProps = {
@@ -1650,7 +1643,7 @@ export default class Explorer {
const workspaces = await this.notebookWorkspaceManager.getNotebookWorkspacesAsync(databaseAccount?.id); const workspaces = await this.notebookWorkspaceManager.getNotebookWorkspacesAsync(databaseAccount?.id);
return workspaces && workspaces.length > 0 && workspaces.some(workspace => workspace.name === "default"); return workspaces && workspaces.length > 0 && workspaces.some(workspace => workspace.name === "default");
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "Explorer/_containsDefaultNotebookWorkspace"); Logger.logError(error, "Explorer/_containsDefaultNotebookWorkspace");
return false; return false;
} }
} }
@@ -1676,7 +1669,8 @@ export default class Explorer {
await this.notebookWorkspaceManager.startNotebookWorkspaceAsync(this.databaseAccount().id, "default"); await this.notebookWorkspaceManager.startNotebookWorkspaceAsync(this.databaseAccount().id, "default");
} }
} catch (error) { } catch (error) {
handleError(error, "Explorer/ensureNotebookWorkspaceRunning", "Failed to initialize notebook workspace"); Logger.logError(error, "Explorer/ensureNotebookWorkspaceRunning");
NotificationConsoleUtils.logConsoleError(`Failed to initialize notebook workspace: ${error.message}`);
} finally { } finally {
clearMessage && clearMessage(); clearMessage && clearMessage();
} }
@@ -1691,10 +1685,7 @@ export default class Explorer {
TelemetryProcessor.traceSuccess(Action.ResetNotebookWorkspace); TelemetryProcessor.traceSuccess(Action.ResetNotebookWorkspace);
} catch (error) { } catch (error) {
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, `Failed to reset notebook workspace: ${error}`); NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, `Failed to reset notebook workspace: ${error}`);
TelemetryProcessor.traceFailure(Action.ResetNotebookWorkspace, { TelemetryProcessor.traceFailure(Action.ResetNotebookWorkspace, error);
error: getErrorMessage(error),
errorStack: getErrorStack(error)
});
throw error; throw error;
} finally { } finally {
NotificationConsoleUtils.clearInProgressMessageWithId(id); NotificationConsoleUtils.clearInProgressMessageWithId(id);
@@ -2061,8 +2052,7 @@ export default class Explorer {
databaseAccountName: this.databaseAccount() && this.databaseAccount().name, databaseAccountName: this.databaseAccount() && this.databaseAccount().name,
defaultExperience: this.defaultExperience && this.defaultExperience(), defaultExperience: this.defaultExperience && this.defaultExperience(),
dataExplorerArea: Constants.Areas.ResourceTree, dataExplorerArea: Constants.Areas.ResourceTree,
error: getErrorMessage(error), trace: error.message
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -2228,7 +2218,8 @@ export default class Explorer {
public uploadFile(name: string, content: string, parent: NotebookContentItem): Promise<NotebookContentItem> { public uploadFile(name: string, content: string, parent: NotebookContentItem): Promise<NotebookContentItem> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to upload notebook, but notebook is not enabled"; const error = "Attempt to upload notebook, but notebook is not enabled";
handleError(error, "Explorer/uploadFile"); Logger.logError(error, "Explorer/uploadFile");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2409,7 +2400,8 @@ export default class Explorer {
public renameNotebook(notebookFile: NotebookContentItem): Q.Promise<NotebookContentItem> { public renameNotebook(notebookFile: NotebookContentItem): Q.Promise<NotebookContentItem> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to rename notebook, but notebook is not enabled"; const error = "Attempt to rename notebook, but notebook is not enabled";
handleError(error, "Explorer/renameNotebook"); Logger.logError(error, "Explorer/renameNotebook");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2457,7 +2449,8 @@ export default class Explorer {
public onCreateDirectory(parent: NotebookContentItem): Q.Promise<NotebookContentItem> { public onCreateDirectory(parent: NotebookContentItem): Q.Promise<NotebookContentItem> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to create notebook directory, but notebook is not enabled"; const error = "Attempt to create notebook directory, but notebook is not enabled";
handleError(error, "Explorer/onCreateDirectory"); Logger.logError(error, "Explorer/onCreateDirectory");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2478,7 +2471,8 @@ export default class Explorer {
public readFile(notebookFile: NotebookContentItem): Promise<string> { public readFile(notebookFile: NotebookContentItem): Promise<string> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to read file, but notebook is not enabled"; const error = "Attempt to read file, but notebook is not enabled";
handleError(error, "Explorer/downloadFile"); Logger.logError(error, "Explorer/downloadFile");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2488,7 +2482,8 @@ export default class Explorer {
public downloadFile(notebookFile: NotebookContentItem): Promise<void> { public downloadFile(notebookFile: NotebookContentItem): Promise<void> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to download file, but notebook is not enabled"; const error = "Attempt to download file, but notebook is not enabled";
handleError(error, "Explorer/downloadFile"); Logger.logError(error, "Explorer/downloadFile");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2519,7 +2514,7 @@ export default class Explorer {
(error: any) => { (error: any) => {
NotificationConsoleUtils.logConsoleMessage( NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error, ConsoleDataType.Error,
`Could not download notebook ${getErrorMessage(error)}` `Could not download notebook ${error.message}`
); );
clearMessage(); clearMessage();
@@ -2569,7 +2564,7 @@ export default class Explorer {
); );
this.isNotebooksEnabledForAccount(isAccountInAllowedLocation); this.isNotebooksEnabledForAccount(isAccountInAllowedLocation);
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "Explorer/isNotebooksEnabledForAccount"); Logger.logError(error, "Explorer/isNotebooksEnabledForAccount");
this.isNotebooksEnabledForAccount(false); this.isNotebooksEnabledForAccount(false);
} }
} }
@@ -2598,7 +2593,7 @@ export default class Explorer {
false; false;
this.isSparkEnabledForAccount(isEnabled); this.isSparkEnabledForAccount(isEnabled);
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "Explorer/isSparkEnabledForAccount"); Logger.logError(error, "Explorer/isSparkEnabledForAccount");
this.isSparkEnabledForAccount(false); this.isSparkEnabledForAccount(false);
} }
}; };
@@ -2623,7 +2618,7 @@ export default class Explorer {
(featureStatus && featureStatus.properties && featureStatus.properties.state === "Registered") || false; (featureStatus && featureStatus.properties && featureStatus.properties.state === "Registered") || false;
return isEnabled; return isEnabled;
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "Explorer/isSparkEnabledForAccount"); Logger.logError(error, "Explorer/isSparkEnabledForAccount");
return false; return false;
} }
}; };
@@ -2642,7 +2637,8 @@ export default class Explorer {
public deleteNotebookFile(item: NotebookContentItem): Promise<void> { public deleteNotebookFile(item: NotebookContentItem): Promise<void> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to delete notebook file, but notebook is not enabled"; const error = "Attempt to delete notebook file, but notebook is not enabled";
handleError(error, "Explorer/deleteNotebookFile"); Logger.logError(error, "Explorer/deleteNotebookFile");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2691,7 +2687,8 @@ export default class Explorer {
public onNewNotebookClicked(parent?: NotebookContentItem): void { public onNewNotebookClicked(parent?: NotebookContentItem): void {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to create new notebook, but notebook is not enabled"; const error = "Attempt to create new notebook, but notebook is not enabled";
handleError(error, "Explorer/onNewNotebookClicked"); Logger.logError(error, "Explorer/onNewNotebookClicked");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
throw new Error(error); throw new Error(error);
} }
@@ -2724,17 +2721,16 @@ export default class Explorer {
return this.openNotebook(newFile); return this.openNotebook(newFile);
}) })
.then(() => this.resourceTree.triggerRender()) .then(() => this.resourceTree.triggerRender())
.catch((error: any) => { .catch((reason: any) => {
const errorMessage = `Failed to create a new notebook: ${getErrorMessage(error)}`; const error = `Failed to create a new notebook: ${reason}`;
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, errorMessage); NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.CreateNewNotebook, Action.CreateNewNotebook,
{ {
databaseAccountName: this.databaseAccount().name, databaseAccountName: this.databaseAccount().name,
defaultExperience: this.defaultExperience(), defaultExperience: this.defaultExperience(),
dataExplorerArea: Constants.Areas.Notebook, dataExplorerArea: Constants.Areas.Notebook,
error: errorMessage, error
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -2777,7 +2773,8 @@ export default class Explorer {
public refreshContentItem(item: NotebookContentItem): Promise<void> { public refreshContentItem(item: NotebookContentItem): Promise<void> {
if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) { if (!this.isNotebookEnabled() || !this.notebookManager?.notebookContentClient) {
const error = "Attempt to refresh notebook list, but notebook is not enabled"; const error = "Attempt to refresh notebook list, but notebook is not enabled";
handleError(error, "Explorer/refreshContentItem"); Logger.logError(error, "Explorer/refreshContentItem");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, error);
return Promise.reject(new Error(error)); return Promise.reject(new Error(error));
} }
@@ -2963,7 +2960,7 @@ export default class Explorer {
} }
return tokenRefreshInterval; return tokenRefreshInterval;
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "Explorer/getTokenRefreshInterval"); Logger.logError(error, "Explorer/getTokenRefreshInterval");
return tokenRefreshInterval; return tokenRefreshInterval;
} }
} }

View File

@@ -29,7 +29,6 @@ import { InputProperty } from "../../../Contracts/ViewModels";
import { QueryIterator, ItemDefinition, Resource } from "@azure/cosmos"; import { QueryIterator, ItemDefinition, Resource } from "@azure/cosmos";
import LoadingIndicatorIcon from "../../../../images/LoadingIndicator_3Squares.gif"; import LoadingIndicatorIcon from "../../../../images/LoadingIndicator_3Squares.gif";
import { queryDocuments, queryDocumentsPage } from "../../../Common/DocumentClientUtilityBase"; import { queryDocuments, queryDocumentsPage } from "../../../Common/DocumentClientUtilityBase";
import { getErrorMessage } from "../../../Common/ErrorHandlingUtils";
export interface GraphAccessor { export interface GraphAccessor {
applyFilter: () => void; applyFilter: () => void;
@@ -893,7 +892,7 @@ export class GraphExplorer extends React.Component<GraphExplorerProps, GraphExpl
backendPromise.then( backendPromise.then(
(result: UserQueryResult) => (this.queryTotalRequestCharge = result.requestCharge), (result: UserQueryResult) => (this.queryTotalRequestCharge = result.requestCharge),
(error: any) => { (error: any) => {
const errorMsg = `Failure in submitting query: ${query}: ${getErrorMessage(error)}`; const errorMsg = `Failure in submitting query: ${query}: ${error.message}`;
GraphExplorer.reportToConsole(ConsoleDataType.Error, errorMsg); GraphExplorer.reportToConsole(ConsoleDataType.Error, errorMsg);
this.setState({ this.setState({
filterQueryError: errorMsg filterQueryError: errorMsg
@@ -1827,7 +1826,7 @@ export class GraphExplorer extends React.Component<GraphExplorerProps, GraphExpl
promise promise
.then((result: GremlinClient.GremlinRequestResult) => this.processGremlinQueryResults(result)) .then((result: GremlinClient.GremlinRequestResult) => this.processGremlinQueryResults(result))
.catch((error: any) => { .catch((error: any) => {
const errorMsg = `Failed to process query result: ${getErrorMessage(error)}`; const errorMsg = `Failed to process query result: ${error.message}`;
GraphExplorer.reportToConsole(ConsoleDataType.Error, errorMsg); GraphExplorer.reportToConsole(ConsoleDataType.Error, errorMsg);
this.setState({ this.setState({
filterQueryError: errorMsg filterQueryError: errorMsg

View File

@@ -94,7 +94,7 @@ describe("Gremlin Client", () => {
it("should log and display error out on unknown requestId", () => { it("should log and display error out on unknown requestId", () => {
const gremlinClient = new GremlinClient(); const gremlinClient = new GremlinClient();
const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleError"); const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleMessage");
const logErrorSpy = sinon.spy(Logger, "logError"); const logErrorSpy = sinon.spy(Logger, "logError");
gremlinClient.initialize(emptyParams); gremlinClient.initialize(emptyParams);
@@ -122,7 +122,7 @@ describe("Gremlin Client", () => {
}); });
it("should not aggregate RU if not a number and reset totalRequestCharge to undefined", done => { it("should not aggregate RU if not a number and reset totalRequestCharge to undefined", done => {
const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleError"); const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleMessage");
const logErrorSpy = sinon.spy(Logger, "logError"); const logErrorSpy = sinon.spy(Logger, "logError");
const gremlinClient = new GremlinClient(); const gremlinClient = new GremlinClient();
@@ -165,7 +165,7 @@ describe("Gremlin Client", () => {
}); });
it("should not aggregate RU if undefined and reset totalRequestCharge to undefined", done => { it("should not aggregate RU if undefined and reset totalRequestCharge to undefined", done => {
const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleError"); const logConsoleSpy = sinon.spy(NotificationConsoleUtils, "logConsoleMessage");
const logErrorSpy = sinon.spy(Logger, "logError"); const logErrorSpy = sinon.spy(Logger, "logError");
const gremlinClient = new GremlinClient(); const gremlinClient = new GremlinClient();

View File

@@ -7,7 +7,7 @@ import { GremlinSimpleClient, Result } from "./GremlinSimpleClient";
import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../../Utils/NotificationConsoleUtils";
import { ConsoleDataType } from "../../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../../Menus/NotificationConsole/NotificationConsoleComponent";
import { HashMap } from "../../../Common/HashMap"; import { HashMap } from "../../../Common/HashMap";
import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils"; import * as Logger from "../../../Common/Logger";
export interface GremlinClientParameters { export interface GremlinClientParameters {
endpoint: string; endpoint: string;
@@ -58,23 +58,26 @@ export class GremlinClient {
} }
}, },
failureCallback: (result: Result, error: any) => { failureCallback: (result: Result, error: any) => {
const errorMessage = getErrorMessage(error); if (typeof error !== "string") {
error = error.message;
}
const requestId = result.requestId; const requestId = result.requestId;
if (!requestId || !this.pendingResults.has(requestId)) { if (!requestId || !this.pendingResults.has(requestId)) {
const errorMsg = `Error: ${errorMessage}, unknown requestId:${requestId} ${GremlinClient.getRequestChargeString( const msg = `Error: ${error}, unknown requestId:${requestId} ${GremlinClient.getRequestChargeString(
result.requestCharge result.requestCharge
)}`; )}`;
handleError(errorMsg, GremlinClient.LOG_AREA); GremlinClient.reportError(msg);
// Fail all pending requests if no request id (fatal) // Fail all pending requests if no request id (fatal)
if (!requestId) { if (!requestId) {
this.pendingResults.keys().forEach((reqId: string) => { this.pendingResults.keys().forEach((reqId: string) => {
this.abortPendingRequest(reqId, errorMessage, null); this.abortPendingRequest(reqId, error, null);
}); });
} }
} else { } else {
this.abortPendingRequest(requestId, errorMessage, result.requestCharge); this.abortPendingRequest(requestId, error, result.requestCharge);
} }
}, },
infoCallback: (msg: string) => { infoCallback: (msg: string) => {
@@ -129,16 +132,15 @@ export class GremlinClient {
deferred.reject(error); deferred.reject(error);
this.pendingResults.delete(requestId); this.pendingResults.delete(requestId);
const errorMsg = `Aborting pending request ${requestId}. Error:${error} ${GremlinClient.getRequestChargeString( GremlinClient.reportError(
requestCharge `Aborting pending request ${requestId}. Error:${error} ${GremlinClient.getRequestChargeString(requestCharge)}`
)}`; );
handleError(errorMsg, GremlinClient.LOG_AREA);
} }
private flushResult(requestId: string) { private flushResult(requestId: string) {
if (!this.pendingResults.has(requestId)) { if (!this.pendingResults.has(requestId)) {
const errorMsg = `Unknown requestId:${requestId}`; const msg = `Unknown requestId:${requestId}`;
handleError(errorMsg, GremlinClient.LOG_AREA); GremlinClient.reportError(msg);
return; return;
} }
@@ -156,8 +158,8 @@ export class GremlinClient {
*/ */
private storePendingResult(result: Result): boolean { private storePendingResult(result: Result): boolean {
if (!this.pendingResults.has(result.requestId)) { if (!this.pendingResults.has(result.requestId)) {
const errorMsg = `Dropping result for unknown requestId:${result.requestId}`; const msg = `Dropping result for unknown requestId:${result.requestId}`;
handleError(errorMsg, GremlinClient.LOG_AREA); GremlinClient.reportError(msg);
return false; return false;
} }
const pendingResults = this.pendingResults.get(result.requestId).result; const pendingResults = this.pendingResults.get(result.requestId).result;
@@ -177,8 +179,9 @@ export class GremlinClient {
if (result.requestCharge === undefined || typeof result.requestCharge !== "number") { if (result.requestCharge === undefined || typeof result.requestCharge !== "number") {
// Clear totalRequestCharge, even if it was a valid number as the total might be incomplete therefore incorrect // Clear totalRequestCharge, even if it was a valid number as the total might be incomplete therefore incorrect
pendingResults.totalRequestCharge = undefined; pendingResults.totalRequestCharge = undefined;
const errorMsg = `Unable to perform RU aggregation calculation with non numbers. Result request charge: ${result.requestCharge}. RequestId: ${result.requestId}`; GremlinClient.reportError(
handleError(errorMsg, GremlinClient.LOG_AREA); `Unable to perform RU aggregation calculation with non numbers. Result request charge: ${result.requestCharge}. RequestId: ${result.requestId}`
);
} else { } else {
if (pendingResults.totalRequestCharge === undefined) { if (pendingResults.totalRequestCharge === undefined) {
pendingResults.totalRequestCharge = 0; pendingResults.totalRequestCharge = 0;
@@ -187,4 +190,9 @@ export class GremlinClient {
} }
return pendingResults.isIncomplete; return pendingResults.isIncomplete;
} }
private static reportError(msg: string): void {
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, msg);
Logger.logError(msg, GremlinClient.LOG_AREA);
}
} }

View File

@@ -6,7 +6,6 @@ import * as Constants from "../../Common/Constants";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as Logger from "../../Common/Logger"; import * as Logger from "../../Common/Logger";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
export class NotebookContainerClient { export class NotebookContainerClient {
private reconnectingNotificationId: string; private reconnectingNotificationId: string;
@@ -75,7 +74,7 @@ export class NotebookContainerClient {
} }
return undefined; return undefined;
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "NotebookContainerClient/getMemoryUsage"); Logger.logError(error, "NotebookContainerClient/getMemoryUsage");
if (!this.reconnectingNotificationId) { if (!this.reconnectingNotificationId) {
this.reconnectingNotificationId = NotificationConsoleUtils.logConsoleMessage( this.reconnectingNotificationId = NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.InProgress, ConsoleDataType.InProgress,
@@ -111,7 +110,7 @@ export class NotebookContainerClient {
headers: { Authorization: authToken } headers: { Authorization: authToken }
}); });
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "NotebookContainerClient/resetWorkspace"); Logger.logError(error, "NotebookContainerClient/resetWorkspace");
await this.recreateNotebookWorkspaceAsync(); await this.recreateNotebookWorkspaceAsync();
} }
} }
@@ -141,7 +140,7 @@ export class NotebookContainerClient {
await notebookWorkspaceManager.deleteNotebookWorkspaceAsync(explorer.databaseAccount().id, "default"); await notebookWorkspaceManager.deleteNotebookWorkspaceAsync(explorer.databaseAccount().id, "default");
await notebookWorkspaceManager.createNotebookWorkspaceAsync(explorer.databaseAccount().id, "default"); await notebookWorkspaceManager.createNotebookWorkspaceAsync(explorer.databaseAccount().id, "default");
} catch (error) { } catch (error) {
Logger.logError(getErrorMessage(error), "NotebookContainerClient/recreateNotebookWorkspaceAsync"); Logger.logError(error, "NotebookContainerClient/recreateNotebookWorkspaceAsync");
return Promise.reject(error); return Promise.reject(error);
} }
} }

View File

@@ -26,7 +26,6 @@ import { ImmutableNotebook } from "@nteract/commutable";
import Explorer from "../Explorer"; import Explorer from "../Explorer";
import { ContextualPaneBase } from "../Panes/ContextualPaneBase"; import { ContextualPaneBase } from "../Panes/ContextualPaneBase";
import { CopyNotebookPaneAdapter } from "../Panes/CopyNotebookPane"; import { CopyNotebookPaneAdapter } from "../Panes/CopyNotebookPane";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
export interface NotebookManagerOptions { export interface NotebookManagerOptions {
container: Explorer; container: Explorer;
@@ -148,7 +147,7 @@ export default class NotebookManager {
// Octokit's error handler uses any // Octokit's error handler uses any
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
private onGitHubClientError = (error: any): void => { private onGitHubClientError = (error: any): void => {
Logger.logError(getErrorMessage(error), "NotebookManager/onGitHubClientError"); Logger.logError(error, "NotebookManager/onGitHubClientError");
if (error.status === HttpStatusCodes.Unauthorized) { if (error.status === HttpStatusCodes.Unauthorized) {
this.gitHubOAuthService.resetToken(); this.gitHubOAuthService.resetToken();

View File

@@ -243,38 +243,6 @@
</div> </div>
<!-- Unlimited Button Content - Start --> <!-- Unlimited Button Content - Start -->
<div class="tabcontent" data-bind="visible: isUnlimitedStorageSelected() || databaseHasSharedOffer()"> <div class="tabcontent" data-bind="visible: isUnlimitedStorageSelected() || databaseHasSharedOffer()">
<div data-bind="visible: rupmVisible">
<div class="tabs">
<p>
<span class="mandatoryStar">*</span>
<span class="addCollectionLabel">RU/m</span>
<span class="infoTooltip" role="tooltip" tabindex="0">
<img class="infoImg" src="/info-bubble.svg" alt="More information">
<span class="tooltiptext throughputRuInfo">
For each 100 Request Units per second (RU/s) provisioned, 1,000 Request Units
per
minute
(RU/m) can be provisioned. E.g.: for a container with 5,000 RU/s provisioned
with
RU/m
enabled, the RU/m budget will be 50,000 RU/m.
</span>
</span>
</p>
<div tabindex="0" data-bind="event: { keydown: onRupmOptionsKeyDown }" aria-label="RU/m">
<div class="tab">
<input type="radio" id="rupmOn2" name="rupmcoll2" value="on" class="radio"
data-bind="checked: rupm">
<label for="rupmOn2">ON</label>
</div>
<div class="tab">
<input type="radio" id="rupmOff2" name="rupmcoll2" value="off" class="radio"
data-bind="checked: rupm">
<label for="rupmOff2">OFF</label>
</div>
</div>
</div>
</div>
<div data-bind="visible: partitionKeyVisible"> <div data-bind="visible: partitionKeyVisible">
<p> <p>
<span class="mandatoryStar">*</span> <span class="mandatoryStar">*</span>
@@ -288,7 +256,7 @@
range of values and is likely to have evenly distributed access patterns.</span> range of values and is likely to have evenly distributed access patterns.</span>
</span> </span>
</p> </p>
<input type="text" id="partitionKeyValue" data-test="addCollection-partitionKeyValue" aria-required="true" size="40" <input type="text" data-test="addCollection-partitionKeyValue" aria-required="true" size="40"
class="textfontclr collid" data-bind="textInput: partitionKey, class="textfontclr collid" data-bind="textInput: partitionKey,
attr: { attr: {
placeholder: partitionKeyPlaceholder, placeholder: partitionKeyPlaceholder,

View File

@@ -3,6 +3,7 @@ import * as AddCollectionUtility from "../../Shared/AddCollectionUtility";
import * as AutoPilotUtils from "../../Utils/AutoPilotUtils"; import * as AutoPilotUtils from "../../Utils/AutoPilotUtils";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import * as DataModels from "../../Contracts/DataModels"; import * as DataModels from "../../Contracts/DataModels";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import * as ko from "knockout"; import * as ko from "knockout";
import * as PricingUtils from "../../Utils/PricingUtils"; import * as PricingUtils from "../../Utils/PricingUtils";
import * as SharedConstants from "../../Shared/Constants"; import * as SharedConstants from "../../Shared/Constants";
@@ -14,7 +15,6 @@ import { configContext, Platform } from "../../ConfigContext";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
import { DynamicListItem } from "../Controls/DynamicList/DynamicListComponent"; import { DynamicListItem } from "../Controls/DynamicList/DynamicListComponent";
import { createCollection } from "../../Common/dataAccess/createCollection"; import { createCollection } from "../../Common/dataAccess/createCollection";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export interface AddCollectionPaneOptions extends ViewModels.PaneOptions { export interface AddCollectionPaneOptions extends ViewModels.PaneOptions {
isPreferredApiTable: ko.Computed<boolean>; isPreferredApiTable: ko.Computed<boolean>;
@@ -41,8 +41,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
public partitionKeyVisible: ko.Computed<boolean>; public partitionKeyVisible: ko.Computed<boolean>;
public partitionKeyPattern: ko.Computed<string>; public partitionKeyPattern: ko.Computed<string>;
public partitionKeyTitle: ko.Computed<string>; public partitionKeyTitle: ko.Computed<string>;
public rupm: ko.Observable<string>;
public rupmVisible: ko.Observable<boolean>;
public storage: ko.Observable<string>; public storage: ko.Observable<string>;
public throughputSinglePartition: ViewModels.Editable<number>; public throughputSinglePartition: ViewModels.Editable<number>;
public throughputMultiPartition: ViewModels.Editable<number>; public throughputMultiPartition: ViewModels.Editable<number>;
@@ -142,12 +140,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
} }
return ""; return "";
}); });
this.rupm = ko.observable<string>(Constants.RUPMStates.off);
this.rupmVisible = ko.observable<boolean>(false);
const featureSubcription = this.container.features.subscribe(() => {
this.rupmVisible(this.container.isFeatureEnabled(Constants.Features.enableRupm));
featureSubcription.dispose();
});
this.canExceedMaximumValue = ko.pureComputed(() => this.container.canExceedMaximumValue()); this.canExceedMaximumValue = ko.pureComputed(() => this.container.canExceedMaximumValue());
@@ -200,7 +192,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
account.properties.readLocations.length) || account.properties.readLocations.length) ||
1; 1;
const multimaster = (account && account.properties && account.properties.enableMultipleWriteLocations) || false; const multimaster = (account && account.properties && account.properties.enableMultipleWriteLocations) || false;
const rupmEnabled: boolean = this.rupm() === Constants.RUPMStates.on;
let throughputSpendAckText: string; let throughputSpendAckText: string;
let estimatedSpend: string; let estimatedSpend: string;
@@ -210,23 +201,15 @@ export default class AddCollectionPane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
rupmEnabled,
this.isSharedAutoPilotSelected() this.isSharedAutoPilotSelected()
); );
estimatedSpend = PricingUtils.getEstimatedSpendHtml( estimatedSpend = PricingUtils.getEstimatedSpendHtml(offerThroughput, serverId, regions, multimaster);
offerThroughput,
serverId,
regions,
multimaster,
rupmEnabled
);
} else { } else {
throughputSpendAckText = PricingUtils.getEstimatedSpendAcknowledgeString( throughputSpendAckText = PricingUtils.getEstimatedSpendAcknowledgeString(
this.sharedAutoPilotThroughput(), this.sharedAutoPilotThroughput(),
serverId, serverId,
regions, regions,
multimaster, multimaster,
rupmEnabled,
this.isSharedAutoPilotSelected() this.isSharedAutoPilotSelected()
); );
estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml( estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml(
@@ -263,7 +246,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
account.properties.readLocations.length) || account.properties.readLocations.length) ||
1; 1;
const multimaster = (account && account.properties && account.properties.enableMultipleWriteLocations) || false; const multimaster = (account && account.properties && account.properties.enableMultipleWriteLocations) || false;
const rupmEnabled: boolean = this.rupm() === Constants.RUPMStates.on;
let throughputSpendAckText: string; let throughputSpendAckText: string;
let estimatedSpend: string; let estimatedSpend: string;
@@ -273,15 +255,13 @@ export default class AddCollectionPane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
rupmEnabled,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
estimatedSpend = PricingUtils.getEstimatedSpendHtml( estimatedSpend = PricingUtils.getEstimatedSpendHtml(
this.throughputMultiPartition(), this.throughputMultiPartition(),
serverId, serverId,
regions, regions,
multimaster, multimaster
rupmEnabled
); );
} else { } else {
throughputSpendAckText = PricingUtils.getEstimatedSpendAcknowledgeString( throughputSpendAckText = PricingUtils.getEstimatedSpendAcknowledgeString(
@@ -289,7 +269,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
rupmEnabled,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml( estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml(
@@ -687,8 +666,7 @@ export default class AddCollectionPane extends ContextualPaneBase {
storage: this.storage(), storage: this.storage(),
offerThroughput: this._getThroughput(), offerThroughput: this._getThroughput(),
partitionKey: this.partitionKey(), partitionKey: this.partitionKey(),
databaseId: this.databaseId(), databaseId: this.databaseId()
rupm: this.rupm()
}), }),
subscriptionType: ViewModels.SubscriptionType[this.container.subscriptionType()], subscriptionType: ViewModels.SubscriptionType[this.container.subscriptionType()],
subscriptionQuotaId: this.container.quotaId(), subscriptionQuotaId: this.container.quotaId(),
@@ -789,7 +767,7 @@ export default class AddCollectionPane extends ContextualPaneBase {
id: this.collectionId(), id: this.collectionId(),
storage: this.storage(), storage: this.storage(),
partitionKey, partitionKey,
rupm: this.rupm(),
uniqueKeyPolicy, uniqueKeyPolicy,
collectionWithThroughputInShared: this.collectionWithThroughputInShared() collectionWithThroughputInShared: this.collectionWithThroughputInShared()
}), }),
@@ -864,7 +842,7 @@ export default class AddCollectionPane extends ContextualPaneBase {
id: this.collectionId(), id: this.collectionId(),
storage: this.storage(), storage: this.storage(),
partitionKey, partitionKey,
rupm: this.rupm(),
uniqueKeyPolicy, uniqueKeyPolicy,
collectionWithThroughputInShared: this.collectionWithThroughputInShared() collectionWithThroughputInShared: this.collectionWithThroughputInShared()
}), }),
@@ -881,9 +859,10 @@ export default class AddCollectionPane extends ContextualPaneBase {
this.resetData(); this.resetData();
this.container.refreshAllDatabases(); this.container.refreshAllDatabases();
}, },
(error: any) => { (reason: any) => {
this.isExecuting(false); this.isExecuting(false);
const errorMessage: string = getErrorMessage(error); const message = ErrorParserUtility.parse(reason);
const errorMessage = ErrorParserUtility.replaceKnownError(message[0].message);
this.formErrors(errorMessage); this.formErrors(errorMessage);
this.formErrorsDetails(errorMessage); this.formErrorsDetails(errorMessage);
const addCollectionPaneFailedMessage = { const addCollectionPaneFailedMessage = {
@@ -899,7 +878,7 @@ export default class AddCollectionPane extends ContextualPaneBase {
id: this.collectionId(), id: this.collectionId(),
storage: this.storage(), storage: this.storage(),
partitionKey, partitionKey,
rupm: this.rupm(),
uniqueKeyPolicy, uniqueKeyPolicy,
collectionWithThroughputInShared: this.collectionWithThroughputInShared() collectionWithThroughputInShared: this.collectionWithThroughputInShared()
}, },
@@ -911,8 +890,7 @@ export default class AddCollectionPane extends ContextualPaneBase {
flight: this.container.flight() flight: this.container.flight()
}, },
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
error: errorMessage, error: reason
errorStack: getErrorStack(error)
}; };
TelemetryProcessor.traceFailure(Action.CreateCollection, addCollectionPaneFailedMessage, startKey); TelemetryProcessor.traceFailure(Action.CreateCollection, addCollectionPaneFailedMessage, startKey);
} }
@@ -982,20 +960,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
return true; return true;
} }
public onRupmOptionsKeyDown(source: any, event: KeyboardEvent): boolean {
if (event.key === "ArrowRight") {
this.rupm("off");
return false;
}
if (event.key === "ArrowLeft") {
this.rupm("on");
return false;
}
return true;
}
public onEnableSynapseLinkButtonClicked() { public onEnableSynapseLinkButtonClicked() {
this.container.openEnableSynapseLinkDialog(); this.container.openEnableSynapseLinkDialog();
} }
@@ -1019,15 +983,6 @@ export default class AddCollectionPane extends ContextualPaneBase {
} }
const throughput = this._getThroughput(); const throughput = this._getThroughput();
const maxThroughputWithRUPM =
SharedConstants.CollectionCreation.MaxRUPMPerPartition * this._calculateNumberOfPartitions();
if (this.rupm() === Constants.RUPMStates.on && throughput > maxThroughputWithRUPM) {
this.formErrors(
`The maximum supported provisioned throughput with RU/m enabled is ${maxThroughputWithRUPM} RU/s. Please turn off RU/m to incease thoughput above ${maxThroughputWithRUPM} RU/s.`
);
return false;
}
if (throughput > SharedConstants.CollectionCreation.DefaultCollectionRUs100K && !this.throughputSpendAck()) { if (throughput > SharedConstants.CollectionCreation.DefaultCollectionRUs100K && !this.throughputSpendAck()) {
this.formErrors(`Please acknowledge the estimated daily spend.`); this.formErrors(`Please acknowledge the estimated daily spend.`);

View File

@@ -1,6 +1,7 @@
import * as AutoPilotUtils from "../../Utils/AutoPilotUtils"; import * as AutoPilotUtils from "../../Utils/AutoPilotUtils";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import * as DataModels from "../../Contracts/DataModels"; import * as DataModels from "../../Contracts/DataModels";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import * as ko from "knockout"; import * as ko from "knockout";
import * as PricingUtils from "../../Utils/PricingUtils"; import * as PricingUtils from "../../Utils/PricingUtils";
import * as SharedConstants from "../../Shared/Constants"; import * as SharedConstants from "../../Shared/Constants";
@@ -11,7 +12,6 @@ import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstan
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
import { createDatabase } from "../../Common/dataAccess/createDatabase"; import { createDatabase } from "../../Common/dataAccess/createDatabase";
import { configContext, Platform } from "../../ConfigContext"; import { configContext, Platform } from "../../ConfigContext";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export default class AddDatabasePane extends ContextualPaneBase { export default class AddDatabasePane extends ContextualPaneBase {
public defaultExperience: ko.Computed<string>; public defaultExperience: ko.Computed<string>;
@@ -132,19 +132,12 @@ export default class AddDatabasePane extends ContextualPaneBase {
let estimatedSpendAcknowledge: string; let estimatedSpendAcknowledge: string;
let estimatedSpend: string; let estimatedSpend: string;
if (!this.isAutoPilotSelected()) { if (!this.isAutoPilotSelected()) {
estimatedSpend = PricingUtils.getEstimatedSpendHtml( estimatedSpend = PricingUtils.getEstimatedSpendHtml(offerThroughput, serverId, regions, multimaster);
offerThroughput,
serverId,
regions,
multimaster,
false /*rupmEnabled*/
);
estimatedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString( estimatedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString(
offerThroughput, offerThroughput,
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
} else { } else {
@@ -159,7 +152,6 @@ export default class AddDatabasePane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
} }
@@ -296,22 +288,18 @@ export default class AddDatabasePane extends ContextualPaneBase {
this.isExecuting(true); this.isExecuting(true);
const createDatabaseParams: DataModels.CreateDatabaseParams = { const createDatabaseParams: DataModels.CreateDatabaseParams = {
autoPilotMaxThroughput: this.maxAutoPilotThroughputSet(),
databaseId: addDatabasePaneStartMessage.database.id, databaseId: addDatabasePaneStartMessage.database.id,
databaseLevelThroughput: addDatabasePaneStartMessage.database.shared databaseLevelThroughput: addDatabasePaneStartMessage.database.shared,
offerThroughput: addDatabasePaneStartMessage.offerThroughput
}; };
if (this.isAutoPilotSelected()) {
createDatabaseParams.autoPilotMaxThroughput = this.maxAutoPilotThroughputSet();
} else {
createDatabaseParams.offerThroughput = addDatabasePaneStartMessage.offerThroughput;
}
createDatabase(createDatabaseParams).then( createDatabase(createDatabaseParams).then(
(database: DataModels.Database) => { (database: DataModels.Database) => {
this._onCreateDatabaseSuccess(offerThroughput, startKey); this._onCreateDatabaseSuccess(offerThroughput, startKey);
}, },
(error: any) => { (reason: any) => {
this._onCreateDatabaseFailure(error, offerThroughput, startKey); this._onCreateDatabaseFailure(reason, offerThroughput, reason);
} }
); );
} }
@@ -360,11 +348,11 @@ export default class AddDatabasePane extends ContextualPaneBase {
this.resetData(); this.resetData();
} }
private _onCreateDatabaseFailure(error: any, offerThroughput: number, startKey: number): void { private _onCreateDatabaseFailure(reason: any, offerThroughput: number, startKey: number): void {
this.isExecuting(false); this.isExecuting(false);
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(reason);
this.formErrors(errorMessage); this.formErrors(message[0].message);
this.formErrorsDetails(errorMessage); this.formErrorsDetails(message[0].message);
const addDatabasePaneFailedMessage = { const addDatabasePaneFailedMessage = {
databaseAccountName: this.container.databaseAccount().name, databaseAccountName: this.container.databaseAccount().name,
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
@@ -379,8 +367,7 @@ export default class AddDatabasePane extends ContextualPaneBase {
flight: this.container.flight() flight: this.container.flight()
}, },
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
error: errorMessage, error: reason
errorStack: getErrorStack(error)
}; };
TelemetryProcessor.traceFailure(Action.CreateDatabase, addDatabasePaneFailedMessage, startKey); TelemetryProcessor.traceFailure(Action.CreateDatabase, addDatabasePaneFailedMessage, startKey);
} }

View File

@@ -7,7 +7,6 @@ import * as Logger from "../../Common/Logger";
import { QueriesGridComponentAdapter } from "../Controls/QueriesGridReactComponent/QueriesGridComponentAdapter"; import { QueriesGridComponentAdapter } from "../Controls/QueriesGridReactComponent/QueriesGridComponentAdapter";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import QueryTab from "../Tabs/QueryTab"; import QueryTab from "../Tabs/QueryTab";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export class BrowseQueriesPane extends ContextualPaneBase { export class BrowseQueriesPane extends ContextualPaneBase {
public queriesGridComponentAdapter: QueriesGridComponentAdapter; public queriesGridComponentAdapter: QueriesGridComponentAdapter;
@@ -61,20 +60,17 @@ export class BrowseQueriesPane extends ContextualPaneBase {
startKey startKey
); );
} catch (error) { } catch (error) {
const errorMessage = getErrorMessage(error);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.SetupSavedQueries, Action.SetupSavedQueries,
{ {
databaseAccountName: this.container && this.container.databaseAccount().name, databaseAccountName: this.container && this.container.databaseAccount().name,
defaultExperience: this.container && this.container.defaultExperience(), defaultExperience: this.container && this.container.defaultExperience(),
dataExplorerArea: Areas.ContextualPane, dataExplorerArea: Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title()
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
this.formErrors(`Failed to setup a collection for saved queries: ${errorMessage}`); this.formErrors(`Failed to setup a collection for saved queries: ${error.message}`);
} finally { } finally {
this.isExecuting(false); this.isExecuting(false);
} }

View File

@@ -13,7 +13,6 @@ import { CassandraAPIDataClient } from "../Tables/TableDataClient";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
import { HashMap } from "../../Common/HashMap"; import { HashMap } from "../../Common/HashMap";
import { configContext, Platform } from "../../ConfigContext"; import { configContext, Platform } from "../../ConfigContext";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export default class CassandraAddCollectionPane extends ContextualPaneBase { export default class CassandraAddCollectionPane extends ContextualPaneBase {
public createTableQuery: ko.Observable<string>; public createTableQuery: ko.Observable<string>;
@@ -137,19 +136,12 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
let estimatedSpend: string; let estimatedSpend: string;
let estimatedDedicatedSpendAcknowledge: string; let estimatedDedicatedSpendAcknowledge: string;
if (!this.isAutoPilotSelected()) { if (!this.isAutoPilotSelected()) {
estimatedSpend = PricingUtils.getEstimatedSpendHtml( estimatedSpend = PricingUtils.getEstimatedSpendHtml(offerThroughput, serverId, regions, multimaster);
offerThroughput,
serverId,
regions,
multimaster,
false /*rupmEnabled*/
);
estimatedDedicatedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString( estimatedDedicatedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString(
offerThroughput, offerThroughput,
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
} else { } else {
@@ -164,7 +156,6 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isAutoPilotSelected() this.isAutoPilotSelected()
); );
} }
@@ -189,19 +180,12 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
let estimatedSpend: string; let estimatedSpend: string;
let estimatedSharedSpendAcknowledge: string; let estimatedSharedSpendAcknowledge: string;
if (!this.isSharedAutoPilotSelected()) { if (!this.isSharedAutoPilotSelected()) {
estimatedSpend = PricingUtils.getEstimatedSpendHtml( estimatedSpend = PricingUtils.getEstimatedSpendHtml(this.keyspaceThroughput(), serverId, regions, multimaster);
this.keyspaceThroughput(),
serverId,
regions,
multimaster,
false /*rupmEnabled*/
);
estimatedSharedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString( estimatedSharedSpendAcknowledge = PricingUtils.getEstimatedSpendAcknowledgeString(
this.keyspaceThroughput(), this.keyspaceThroughput(),
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isSharedAutoPilotSelected() this.isSharedAutoPilotSelected()
); );
} else { } else {
@@ -216,7 +200,6 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
serverId, serverId,
regions, regions,
multimaster, multimaster,
false /*rupmEnabled*/,
this.isSharedAutoPilotSelected() this.isSharedAutoPilotSelected()
); );
} }
@@ -311,8 +294,7 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
storage: Constants.BackendDefaults.multiPartitionStorageInGb, storage: Constants.BackendDefaults.multiPartitionStorageInGb,
offerThroughput: this.throughput(), offerThroughput: this.throughput(),
partitionKey: "", partitionKey: "",
databaseId: this.keyspaceId(), databaseId: this.keyspaceId()
rupm: false
}), }),
subscriptionType: ViewModels.SubscriptionType[this.container.subscriptionType()], subscriptionType: ViewModels.SubscriptionType[this.container.subscriptionType()],
subscriptionQuotaId: this.container.quotaId(), subscriptionQuotaId: this.container.quotaId(),
@@ -365,7 +347,6 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
offerThroughput: this.throughput(), offerThroughput: this.throughput(),
partitionKey: "", partitionKey: "",
databaseId: this.keyspaceId(), databaseId: this.keyspaceId(),
rupm: false,
hasDedicatedThroughput: this.dedicateTableThroughput() hasDedicatedThroughput: this.dedicateTableThroughput()
}), }),
keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(), keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(),
@@ -412,7 +393,6 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
offerThroughput: this.throughput(), offerThroughput: this.throughput(),
partitionKey: "", partitionKey: "",
databaseId: this.keyspaceId(), databaseId: this.keyspaceId(),
rupm: false,
hasDedicatedThroughput: this.dedicateTableThroughput() hasDedicatedThroughput: this.dedicateTableThroughput()
}), }),
keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(), keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(),
@@ -430,9 +410,8 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
}; };
TelemetryProcessor.traceSuccess(Action.CreateCollection, addCollectionPaneSuccessMessage, startKey); TelemetryProcessor.traceSuccess(Action.CreateCollection, addCollectionPaneSuccessMessage, startKey);
}, },
error => { reason => {
const errorMessage = getErrorMessage(error); this.formErrors(reason.exceptionMessage);
this.formErrors(errorMessage);
this.isExecuting(false); this.isExecuting(false);
const addCollectionPaneFailedMessage = { const addCollectionPaneFailedMessage = {
databaseAccountName: this.container.databaseAccount().name, databaseAccountName: this.container.databaseAccount().name,
@@ -443,7 +422,6 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
offerThroughput: this.throughput(), offerThroughput: this.throughput(),
partitionKey: "", partitionKey: "",
databaseId: this.keyspaceId(), databaseId: this.keyspaceId(),
rupm: false,
hasDedicatedThroughput: this.dedicateTableThroughput() hasDedicatedThroughput: this.dedicateTableThroughput()
}, },
keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(), keyspaceHasSharedOffer: this.keyspaceHasSharedOffer(),
@@ -458,8 +436,7 @@ export default class CassandraAddCollectionPane extends ContextualPaneBase {
toCreateKeyspace: toCreateKeyspace, toCreateKeyspace: toCreateKeyspace,
createKeyspaceQuery: createKeyspaceQuery, createKeyspaceQuery: createKeyspaceQuery,
createTableQuery: createTableQuery, createTableQuery: createTableQuery,
error: errorMessage, error: reason
errorStack: getErrorStack(error)
}; };
TelemetryProcessor.traceFailure(Action.CreateCollection, addCollectionPaneFailedMessage, startKey); TelemetryProcessor.traceFailure(Action.CreateCollection, addCollectionPaneFailedMessage, startKey);
} }

View File

@@ -1,6 +1,7 @@
import ko from "knockout"; import ko from "knockout";
import * as React from "react"; import * as React from "react";
import { ReactAdapter } from "../../Bindings/ReactBindingHandler"; import { ReactAdapter } from "../../Bindings/ReactBindingHandler";
import * as Logger from "../../Common/Logger";
import { JunoClient, IPinnedRepo } from "../../Juno/JunoClient"; import { JunoClient, IPinnedRepo } from "../../Juno/JunoClient";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import Explorer from "../Explorer"; import Explorer from "../Explorer";
@@ -12,7 +13,6 @@ import { HttpStatusCodes } from "../../Common/Constants";
import * as GitHubUtils from "../../Utils/GitHubUtils"; import * as GitHubUtils from "../../Utils/GitHubUtils";
import { NotebookContentItemType, NotebookContentItem } from "../Notebook/NotebookContentItem"; import { NotebookContentItemType, NotebookContentItem } from "../Notebook/NotebookContentItem";
import { ResourceTreeAdapter } from "../Tree/ResourceTreeAdapter"; import { ResourceTreeAdapter } from "../Tree/ResourceTreeAdapter";
import { handleError, getErrorMessage } from "../../Common/ErrorHandlingUtils";
interface Location { interface Location {
type: "MyNotebooks" | "GitHub"; type: "MyNotebooks" | "GitHub";
@@ -90,7 +90,9 @@ export class CopyNotebookPaneAdapter implements ReactAdapter {
if (this.gitHubOAuthService.isLoggedIn()) { if (this.gitHubOAuthService.isLoggedIn()) {
const response = await this.junoClient.getPinnedRepos(this.gitHubOAuthService.getTokenObservable()()?.scope); const response = await this.junoClient.getPinnedRepos(this.gitHubOAuthService.getTokenObservable()()?.scope);
if (response.status !== HttpStatusCodes.OK && response.status !== HttpStatusCodes.NoContent) { if (response.status !== HttpStatusCodes.OK && response.status !== HttpStatusCodes.NoContent) {
handleError(`Received HTTP ${response.status} when fetching pinned repos`, "CopyNotebookPaneAdapter/submit"); const message = `Received HTTP ${response.status} when fetching pinned repos`;
Logger.logError(message, "CopyNotebookPaneAdapter/submit");
NotificationConsoleUtils.logConsoleError(message);
} }
if (response.data?.length > 0) { if (response.data?.length > 0) {
@@ -132,10 +134,12 @@ export class CopyNotebookPaneAdapter implements ReactAdapter {
NotificationConsoleUtils.logConsoleInfo(`Successfully copied ${this.name} to ${destination}`); NotificationConsoleUtils.logConsoleInfo(`Successfully copied ${this.name} to ${destination}`);
} catch (error) { } catch (error) {
const errorMessage = getErrorMessage(error);
this.formError = `Failed to copy ${this.name} to ${destination}`; this.formError = `Failed to copy ${this.name} to ${destination}`;
this.formErrorDetail = `${errorMessage}`; this.formErrorDetail = `${error}`;
handleError(errorMessage, "CopyNotebookPaneAdapter/submit", this.formError);
const message = `${this.formError}: ${this.formErrorDetail}`;
Logger.logError(message, "CopyNotebookPaneAdapter/submit");
NotificationConsoleUtils.logConsoleError(message);
return; return;
} finally { } finally {
clearMessage && clearMessage(); clearMessage && clearMessage();

View File

@@ -3,6 +3,7 @@ import Q from "q";
import * as ViewModels from "../../Contracts/ViewModels"; import * as ViewModels from "../../Contracts/ViewModels";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants"; import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import { CassandraAPIDataClient } from "../Tables/TableDataClient"; import { CassandraAPIDataClient } from "../Tables/TableDataClient";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
@@ -11,7 +12,6 @@ import DeleteFeedback from "../../Common/DeleteFeedback";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { deleteCollection } from "../../Common/dataAccess/deleteCollection"; import { deleteCollection } from "../../Common/dataAccess/deleteCollection";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export default class DeleteCollectionConfirmationPane extends ContextualPaneBase { export default class DeleteCollectionConfirmationPane extends ContextualPaneBase {
public collectionIdConfirmationText: ko.Observable<string>; public collectionIdConfirmationText: ko.Observable<string>;
@@ -99,11 +99,11 @@ export default class DeleteCollectionConfirmationPane extends ContextualPaneBase
this.containerDeleteFeedback(""); this.containerDeleteFeedback("");
} }
}, },
(error: any) => { (reason: any) => {
this.isExecuting(false); this.isExecuting(false);
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(reason);
this.formErrors(errorMessage); this.formErrors(message[0].message);
this.formErrorsDetails(errorMessage); this.formErrorsDetails(message[0].message);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.DeleteCollection, Action.DeleteCollection,
{ {
@@ -111,9 +111,7 @@ export default class DeleteCollectionConfirmationPane extends ContextualPaneBase
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
collectionId: selectedCollection.id(), collectionId: selectedCollection.id(),
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title()
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );

View File

@@ -3,6 +3,7 @@ import Q from "q";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import * as ViewModels from "../../Contracts/ViewModels"; import * as ViewModels from "../../Contracts/ViewModels";
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants"; import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import { CassandraAPIDataClient } from "../Tables/TableDataClient"; import { CassandraAPIDataClient } from "../Tables/TableDataClient";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
@@ -13,7 +14,6 @@ import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { deleteDatabase } from "../../Common/dataAccess/deleteDatabase"; import { deleteDatabase } from "../../Common/dataAccess/deleteDatabase";
import { ARMError } from "../../Utils/arm/request"; import { ARMError } from "../../Utils/arm/request";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export default class DeleteDatabaseConfirmationPane extends ContextualPaneBase { export default class DeleteDatabaseConfirmationPane extends ContextualPaneBase {
public databaseIdConfirmationText: ko.Observable<string>; public databaseIdConfirmationText: ko.Observable<string>;
@@ -108,11 +108,12 @@ export default class DeleteDatabaseConfirmationPane extends ContextualPaneBase {
this.databaseDeleteFeedback(""); this.databaseDeleteFeedback("");
} }
}, },
(error: any) => { (reason: unknown) => {
this.isExecuting(false); this.isExecuting(false);
const errorMessage = getErrorMessage(error);
this.formErrors(errorMessage); const message = reason instanceof ARMError ? reason.message : ErrorParserUtility.parse(reason)[0].message;
this.formErrorsDetails(errorMessage); this.formErrors(message);
this.formErrorsDetails(message);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.DeleteDatabase, Action.DeleteDatabase,
{ {
@@ -120,9 +121,7 @@ export default class DeleteDatabaseConfirmationPane extends ContextualPaneBase {
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
databaseId: selectedDatabase.id(), databaseId: selectedDatabase.id(),
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title()
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );

View File

@@ -1,5 +1,6 @@
import _ from "underscore"; import _ from "underscore";
import { Areas, HttpStatusCodes } from "../../Common/Constants"; import { Areas, HttpStatusCodes } from "../../Common/Constants";
import * as Logger from "../../Common/Logger";
import * as ViewModels from "../../Contracts/ViewModels"; import * as ViewModels from "../../Contracts/ViewModels";
import { GitHubClient, IGitHubPageInfo, IGitHubRepo } from "../../GitHub/GitHubClient"; import { GitHubClient, IGitHubPageInfo, IGitHubRepo } from "../../GitHub/GitHubClient";
import { IPinnedRepo, JunoClient } from "../../Juno/JunoClient"; import { IPinnedRepo, JunoClient } from "../../Juno/JunoClient";
@@ -7,12 +8,13 @@ import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstan
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import * as GitHubUtils from "../../Utils/GitHubUtils"; import * as GitHubUtils from "../../Utils/GitHubUtils";
import { JunoUtils } from "../../Utils/JunoUtils"; import { JunoUtils } from "../../Utils/JunoUtils";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { AuthorizeAccessComponent } from "../Controls/GitHub/AuthorizeAccessComponent"; import { AuthorizeAccessComponent } from "../Controls/GitHub/AuthorizeAccessComponent";
import { GitHubReposComponent, GitHubReposComponentProps, RepoListItem } from "../Controls/GitHub/GitHubReposComponent"; import { GitHubReposComponent, GitHubReposComponentProps, RepoListItem } from "../Controls/GitHub/GitHubReposComponent";
import { GitHubReposComponentAdapter } from "../Controls/GitHub/GitHubReposComponentAdapter"; import { GitHubReposComponentAdapter } from "../Controls/GitHub/GitHubReposComponentAdapter";
import { BranchesProps, PinnedReposProps, UnpinnedReposProps } from "../Controls/GitHub/ReposListComponent"; import { BranchesProps, PinnedReposProps, UnpinnedReposProps } from "../Controls/GitHub/ReposListComponent";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
import { handleError } from "../../Common/ErrorHandlingUtils";
interface GitHubReposPaneOptions extends ViewModels.PaneOptions { interface GitHubReposPaneOptions extends ViewModels.PaneOptions {
gitHubClient: GitHubClient; gitHubClient: GitHubClient;
@@ -103,7 +105,9 @@ export class GitHubReposPane extends ContextualPaneBase {
throw new Error(`Received HTTP ${response.status} when saving pinned repos`); throw new Error(`Received HTTP ${response.status} when saving pinned repos`);
} }
} catch (error) { } catch (error) {
handleError(error, "GitHubReposPane/submit", "Failed to save pinned repos"); const message = `Failed to save pinned repos: ${error}`;
Logger.logError(message, "GitHubReposPane/submit");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }
} }
@@ -202,7 +206,9 @@ export class GitHubReposPane extends ContextualPaneBase {
branchesProps.lastPageInfo = response.pageInfo; branchesProps.lastPageInfo = response.pageInfo;
} }
} catch (error) { } catch (error) {
handleError(error, "GitHubReposPane/loadMoreBranches", "Failed to fetch branches"); const message = `Failed to fetch branches: ${error}`;
Logger.logError(message, "GitHubReposPane/loadMoreBranches");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
branchesProps.isLoading = false; branchesProps.isLoading = false;
@@ -230,7 +236,9 @@ export class GitHubReposPane extends ContextualPaneBase {
this.unpinnedReposProps.repos = this.calculateUnpinnedRepos(); this.unpinnedReposProps.repos = this.calculateUnpinnedRepos();
} }
} catch (error) { } catch (error) {
handleError(error, "GitHubReposPane/loadMoreUnpinnedRepos", "Failed to fetch unpinned repos"); const message = `Failed to fetch unpinned repos: ${error}`;
Logger.logError(message, "GitHubReposPane/loadMoreUnpinnedRepos");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
this.unpinnedReposProps.isLoading = false; this.unpinnedReposProps.isLoading = false;
@@ -247,7 +255,9 @@ export class GitHubReposPane extends ContextualPaneBase {
return response.data; return response.data;
} catch (error) { } catch (error) {
handleError(error, "GitHubReposPane/getRepo", "Failed to fetch repo"); const message = `Failed to fetch repo: ${error}`;
Logger.logError(message, "GitHubReposPane/getRepo");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
return Promise.resolve(undefined); return Promise.resolve(undefined);
} }
} }
@@ -310,7 +320,9 @@ export class GitHubReposPane extends ContextualPaneBase {
this.triggerRender(); this.triggerRender();
} }
} catch (error) { } catch (error) {
handleError(error, "GitHubReposPane/refreshPinnedReposListItems", "Failed to fetch pinned repos"); const message = `Failed to fetch pinned repos: ${error}`;
Logger.logError(message, "GitHubReposPane/refreshPinnedReposListItems");
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
} }
} }

View File

@@ -1,16 +1,17 @@
import ko from "knockout"; import ko from "knockout";
import * as React from "react"; import * as React from "react";
import { ReactAdapter } from "../../Bindings/ReactBindingHandler"; import { ReactAdapter } from "../../Bindings/ReactBindingHandler";
import * as Logger from "../../Common/Logger";
import Explorer from "../Explorer"; import Explorer from "../Explorer";
import { JunoClient } from "../../Juno/JunoClient"; import { JunoClient } from "../../Juno/JunoClient";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { GenericRightPaneComponent, GenericRightPaneProps } from "./GenericRightPaneComponent"; import { GenericRightPaneComponent, GenericRightPaneProps } from "./GenericRightPaneComponent";
import { PublishNotebookPaneComponent, PublishNotebookPaneProps } from "./PublishNotebookPaneComponent"; import { PublishNotebookPaneComponent, PublishNotebookPaneProps } from "./PublishNotebookPaneComponent";
import { ImmutableNotebook } from "@nteract/commutable/src"; import { ImmutableNotebook } from "@nteract/commutable/src";
import { toJS } from "@nteract/commutable"; import { toJS } from "@nteract/commutable";
import { CodeOfConductComponent } from "../Controls/NotebookGallery/CodeOfConductComponent"; import { CodeOfConductComponent } from "../Controls/NotebookGallery/CodeOfConductComponent";
import { HttpStatusCodes } from "../../Common/Constants"; import { HttpStatusCodes } from "../../Common/Constants";
import { handleError, getErrorMessage } from "../../Common/ErrorHandlingUtils";
export class PublishNotebookPaneAdapter implements ReactAdapter { export class PublishNotebookPaneAdapter implements ReactAdapter {
parameters: ko.Observable<number>; parameters: ko.Observable<number>;
@@ -110,11 +111,9 @@ export class PublishNotebookPaneAdapter implements ReactAdapter {
this.isCodeOfConductAccepted = response.data; this.isCodeOfConductAccepted = response.data;
} catch (error) { } catch (error) {
handleError( const message = `Failed to check if code of conduct was accepted: ${error}`;
error, Logger.logError(message, "PublishNotebookPaneAdapter/isCodeOfConductAccepted");
"PublishNotebookPaneAdapter/isCodeOfConductAccepted", NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
"Failed to check if code of conduct was accepted"
);
} }
} else { } else {
this.isCodeOfConductAccepted = true; this.isCodeOfConductAccepted = true;
@@ -171,10 +170,12 @@ export class PublishNotebookPaneAdapter implements ReactAdapter {
} }
} }
} catch (error) { } catch (error) {
const errorMessage = getErrorMessage(error);
this.formError = `Failed to publish ${this.name} to gallery`; this.formError = `Failed to publish ${this.name} to gallery`;
this.formErrorDetail = `${errorMessage}`; this.formErrorDetail = `${error}`;
handleError(errorMessage, "PublishNotebookPaneAdapter/submit", this.formError);
const message = `${this.formError}: ${this.formErrorDetail}`;
Logger.logError(message, "PublishNotebookPaneAdapter/submit");
NotificationConsoleUtils.logConsoleError(message);
return; return;
} finally { } finally {
clearPublishingMessage(); clearPublishingMessage();
@@ -188,7 +189,10 @@ export class PublishNotebookPaneAdapter implements ReactAdapter {
private createFormErrorForLargeImageSelection = (formError: string, formErrorDetail: string, area: string): void => { private createFormErrorForLargeImageSelection = (formError: string, formErrorDetail: string, area: string): void => {
this.formError = formError; this.formError = formError;
this.formErrorDetail = formErrorDetail; this.formErrorDetail = formErrorDetail;
handleError(formErrorDetail, area, formError);
const message = `${this.formError}: ${this.formErrorDetail}`;
Logger.logError(message, area);
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, message);
this.triggerRender(); this.triggerRender();
}; };

View File

@@ -7,7 +7,6 @@ import { ContextualPaneBase } from "./ContextualPaneBase";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { DefaultExperienceUtility } from "../../Shared/DefaultExperienceUtility"; import { DefaultExperienceUtility } from "../../Shared/DefaultExperienceUtility";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
export class RenewAdHocAccessPane extends ContextualPaneBase { export class RenewAdHocAccessPane extends ContextualPaneBase {
public accessKey: ko.Observable<string>; public accessKey: ko.Observable<string>;
@@ -83,7 +82,7 @@ export class RenewAdHocAccessPane extends ContextualPaneBase {
this.container this.container
.renewShareAccess(this.accessKey()) .renewShareAccess(this.accessKey())
.fail((error: any) => { .fail((error: any) => {
const errorMessage: string = getErrorMessage(error); const errorMessage: string = error.message;
NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, `Failed to connect: ${errorMessage}`); NotificationConsoleUtils.logConsoleMessage(ConsoleDataType.Error, `Failed to connect: ${errorMessage}`);
this.formErrors(errorMessage); this.formErrors(errorMessage);
this.formErrorsDetails(errorMessage); this.formErrorsDetails(errorMessage);

View File

@@ -8,7 +8,6 @@ import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsol
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import QueryTab from "../Tabs/QueryTab"; import QueryTab from "../Tabs/QueryTab";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export class SaveQueryPane extends ContextualPaneBase { export class SaveQueryPane extends ContextualPaneBase {
public queryName: ko.Observable<string>; public queryName: ko.Observable<string>;
@@ -88,18 +87,18 @@ export class SaveQueryPane extends ContextualPaneBase {
}, },
(error: any) => { (error: any) => {
this.isExecuting(false); this.isExecuting(false);
const errorMessage = getErrorMessage(error); if (typeof error != "string") {
error = error.message;
}
this.formErrors("Failed to save query"); this.formErrors("Failed to save query");
this.formErrorsDetails(`Failed to save query: ${errorMessage}`); this.formErrorsDetails(`Failed to save query: ${error}`);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.SaveQuery, Action.SaveQuery,
{ {
databaseAccountName: this.container.databaseAccount().name, databaseAccountName: this.container.databaseAccount().name,
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title()
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -133,21 +132,18 @@ export class SaveQueryPane extends ContextualPaneBase {
startKey startKey
); );
} catch (error) { } catch (error) {
const errorMessage = getErrorMessage(error);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.SetupSavedQueries, Action.SetupSavedQueries,
{ {
databaseAccountName: this.container && this.container.databaseAccount().name, databaseAccountName: this.container && this.container.databaseAccount().name,
defaultExperience: this.container && this.container.defaultExperience(), defaultExperience: this.container && this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.ContextualPane, dataExplorerArea: Constants.Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title()
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
this.formErrors("Failed to setup a container for saved queries"); this.formErrors("Failed to setup a container for saved queries");
this.formErrorsDetails(`Failed to setup a container for saved queries: ${errorMessage}`); this.formErrors(`Failed to setup a container for saved queries: ${error.message}`);
} finally { } finally {
this.isExecuting(false); this.isExecuting(false);
} }

View File

@@ -6,7 +6,6 @@ import { ContextualPaneBase } from "./ContextualPaneBase";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import * as ko from "knockout"; import * as ko from "knockout";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export class SetupNotebooksPane extends ContextualPaneBase { export class SetupNotebooksPane extends ContextualPaneBase {
private description: ko.Observable<string>; private description: ko.Observable<string>;
@@ -86,7 +85,7 @@ export class SetupNotebooksPane extends ContextualPaneBase {
"Successfully created a default notebook workspace for the account" "Successfully created a default notebook workspace for the account"
); );
} catch (error) { } catch (error) {
const errorMessage = getErrorMessage(error); const errorMessage = typeof error == "string" ? error : error.message;
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.CreateNotebookWorkspace, Action.CreateNotebookWorkspace,
{ {
@@ -94,8 +93,7 @@ export class SetupNotebooksPane extends ContextualPaneBase {
defaultExperience: this.container && this.container.defaultExperience(), defaultExperience: this.container && this.container.defaultExperience(),
dataExplorerArea: Areas.ContextualPane, dataExplorerArea: Areas.ContextualPane,
paneTitle: this.title(), paneTitle: this.title(),
error: errorMessage, error: errorMessage
errorStack: getErrorStack(error)
}, },
startKey startKey
); );

View File

@@ -4,8 +4,8 @@ import * as ViewModels from "../../Contracts/ViewModels";
import { ContextualPaneBase } from "./ContextualPaneBase"; import { ContextualPaneBase } from "./ContextualPaneBase";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent"; import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import { UploadDetailsRecord, UploadDetails } from "../../workers/upload/definitions"; import { UploadDetailsRecord, UploadDetails } from "../../workers/upload/definitions";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
const UPLOAD_FILE_SIZE_LIMIT = 2097152; const UPLOAD_FILE_SIZE_LIMIT = 2097152;
@@ -61,9 +61,9 @@ export class UploadItemsPane extends ContextualPaneBase {
this._resetFileInput(); this._resetFileInput();
}, },
(error: any) => { (error: any) => {
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(error);
this.formErrors(errorMessage); this.formErrors(message[0].message);
this.formErrorsDetails(errorMessage); this.formErrorsDetails(message[0].message);
} }
) )
.finally(() => { .finally(() => {

View File

@@ -1,3 +1,4 @@
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import * as ko from "knockout"; import * as ko from "knockout";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as React from "react"; import * as React from "react";
@@ -8,7 +9,6 @@ import { ReactAdapter } from "../../Bindings/ReactBindingHandler";
import { UploadDetailsRecord, UploadDetails } from "../../workers/upload/definitions"; import { UploadDetailsRecord, UploadDetails } from "../../workers/upload/definitions";
import { UploadItemsPaneComponent, UploadItemsPaneProps } from "./UploadItemsPaneComponent"; import { UploadItemsPaneComponent, UploadItemsPaneProps } from "./UploadItemsPaneComponent";
import Explorer from "../Explorer"; import Explorer from "../Explorer";
import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
const UPLOAD_FILE_SIZE_LIMIT = 2097152; const UPLOAD_FILE_SIZE_LIMIT = 2097152;
@@ -107,9 +107,9 @@ export class UploadItemsPaneAdapter implements ReactAdapter {
this.selectedFilesTitle = ""; this.selectedFilesTitle = "";
}, },
error => { error => {
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(error);
this.formError = errorMessage; this.formError = message[0].message;
this.formErrorDetail = errorMessage; this.formErrorDetail = message[0].message;
} }
) )
.finally(() => { .finally(() => {

View File

@@ -16,9 +16,9 @@ import * as Entities from "../Entities";
import QueryTablesTab from "../../Tabs/QueryTablesTab"; import QueryTablesTab from "../../Tabs/QueryTablesTab";
import * as TableEntityProcessor from "../TableEntityProcessor"; import * as TableEntityProcessor from "../TableEntityProcessor";
import * as TelemetryProcessor from "../../../Shared/Telemetry/TelemetryProcessor"; import * as TelemetryProcessor from "../../../Shared/Telemetry/TelemetryProcessor";
import * as ErrorParserUtility from "../../../Common/ErrorParserUtility";
import * as DataModels from "../../../Contracts/DataModels"; import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels"; import * as ViewModels from "../../../Contracts/ViewModels";
import { getErrorMessage, getErrorStack } from "../../../Common/ErrorHandlingUtils";
interface IListTableEntitiesSegmentedResult extends Entities.IListTableEntitiesResult { interface IListTableEntitiesSegmentedResult extends Entities.IListTableEntitiesResult {
ExceedMaximumRetries?: boolean; ExceedMaximumRetries?: boolean;
@@ -387,8 +387,17 @@ export default class TableEntityListViewModel extends DataTableViewModel {
} }
}) })
.catch((error: any) => { .catch((error: any) => {
const errorMessage = getErrorMessage(error); const parsedErrors = ErrorParserUtility.parse(error);
this.queryErrorMessage(errorMessage); var errors = parsedErrors.map((error: DataModels.ErrorDataModel) => {
return <ViewModels.QueryError>{
message: error.message,
start: error.location ? error.location.start : undefined,
end: error.location ? error.location.end : undefined,
code: error.code,
severity: error.severity
};
});
this.queryErrorMessage(errors[0].message);
if (this.queryTablesTab.onLoadStartKey != null && this.queryTablesTab.onLoadStartKey != undefined) { if (this.queryTablesTab.onLoadStartKey != null && this.queryTablesTab.onLoadStartKey != undefined) {
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.Tab, Action.Tab,
@@ -399,8 +408,7 @@ export default class TableEntityListViewModel extends DataTableViewModel {
defaultExperience: this.queryTablesTab.collection.container.defaultExperience(), defaultExperience: this.queryTablesTab.collection.container.defaultExperience(),
dataExplorerArea: Areas.Tab, dataExplorerArea: Areas.Tab,
tabTitle: this.queryTablesTab.tabTitle(), tabTitle: this.queryTablesTab.tabTitle(),
error: errorMessage, error: error
errorStack: getErrorStack(error)
}, },
this.queryTablesTab.onLoadStartKey this.queryTablesTab.onLoadStartKey
); );

View File

@@ -7,14 +7,16 @@ import { ConsoleDataType } from "../../Explorer/Menus/NotificationConsole/Notifi
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import * as Entities from "./Entities"; import * as Entities from "./Entities";
import * as HeadersUtility from "../../Common/HeadersUtility"; import * as HeadersUtility from "../../Common/HeadersUtility";
import * as Logger from "../../Common/Logger";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import * as TableConstants from "./Constants"; import * as TableConstants from "./Constants";
import * as TableEntityProcessor from "./TableEntityProcessor"; import * as TableEntityProcessor from "./TableEntityProcessor";
import * as ViewModels from "../../Contracts/ViewModels"; import * as ViewModels from "../../Contracts/ViewModels";
import { MessageTypes } from "../../Contracts/ExplorerContracts";
import { sendMessage } from "../../Common/MessageHandler";
import Explorer from "../Explorer"; import Explorer from "../Explorer";
import { queryDocuments, deleteDocument, updateDocument, createDocument } from "../../Common/DocumentClientUtilityBase"; import { queryDocuments, deleteDocument, updateDocument, createDocument } from "../../Common/DocumentClientUtilityBase";
import { configContext } from "../../ConfigContext"; import { configContext } from "../../ConfigContext";
import { handleError } from "../../Common/ErrorHandlingUtils";
export interface CassandraTableKeys { export interface CassandraTableKeys {
partitionKeys: CassandraTableKey[]; partitionKeys: CassandraTableKey[];
@@ -186,9 +188,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(entity); deferred.resolve(entity);
}, },
error => { reason => {
handleError(error, "AddRowCassandra", `Error while adding new row to table ${collection.id()}`); NotificationConsoleUtils.logConsoleMessage(
deferred.reject(error); ConsoleDataType.Error,
`Error while adding new row to table ${collection.id()}:\n ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "AddRowCassandra", reason.code);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -260,9 +267,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(newEntity); deferred.resolve(newEntity);
}, },
error => { reason => {
handleError(error, "UpdateRowCassandra", `Failed to update row ${newEntity.RowKey._}`); NotificationConsoleUtils.logConsoleMessage(
deferred.reject(error); ConsoleDataType.Error,
`Failed to update row ${newEntity.RowKey._}: ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "UpdateRowCassandra", reason.code);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -320,11 +332,16 @@ export class CassandraAPIDataClient extends TableDataClient {
ContinuationToken: data.paginationToken ContinuationToken: data.paginationToken
}); });
}, },
(error: any) => { reason => {
if (shouldNotify) { if (shouldNotify) {
handleError(error, "QueryDocumentsCassandra", `Failed to query rows for table ${collection.id()}`); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Failed to query rows for table ${collection.id()}: ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "QueryDocumentsCassandra", reason.status);
this._checkForbiddenError(reason);
} }
deferred.reject(error); deferred.reject(reason);
} }
) )
.done(() => { .done(() => {
@@ -362,8 +379,13 @@ export class CassandraAPIDataClient extends TableDataClient {
`Successfully deleted row ${currEntityToDelete.RowKey._}` `Successfully deleted row ${currEntityToDelete.RowKey._}`
); );
}, },
error => { reason => {
handleError(error, "DeleteRowCassandra", `Error while deleting row ${currEntityToDelete.RowKey._}`); NotificationConsoleUtils.logConsoleMessage(
ConsoleDataType.Error,
`Error while deleting row ${currEntityToDelete.RowKey._}:\n ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "DeleteRowCassandra", reason.code);
this._checkForbiddenError(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -398,13 +420,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(); deferred.resolve();
}, },
error => { reason => {
handleError( NotificationConsoleUtils.logConsoleMessage(
error, ConsoleDataType.Error,
"CreateKeyspaceCassandra", `Error while creating a keyspace with query ${createKeyspaceQuery}:\n ${JSON.stringify(reason)}`
`Error while creating a keyspace with query ${createKeyspaceQuery}`
); );
deferred.reject(error); Logger.logError(JSON.stringify(reason), "CreateKeyspaceCassandra", reason.code);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -444,9 +467,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(); deferred.resolve();
}, },
error => { reason => {
handleError(error, "CreateTableCassandra", `Error while creating a table with query ${createTableQuery}`); NotificationConsoleUtils.logConsoleMessage(
deferred.reject(error); ConsoleDataType.Error,
`Error while creating a table with query ${createTableQuery}:\n ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "CreateTableCassandra", reason.code);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -480,13 +508,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(); deferred.resolve();
}, },
error => { reason => {
handleError( NotificationConsoleUtils.logConsoleMessage(
error, ConsoleDataType.Error,
"DeleteKeyspaceOrTableCassandra", `Error while deleting resource with query ${deleteQuery}:\n ${JSON.stringify(reason)}`
`Error while deleting resource with query ${deleteQuery}`
); );
deferred.reject(error); Logger.logError(JSON.stringify(reason), "DeleteKeyspaceOrTableCassandra", reason.code);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.finally(() => { .finally(() => {
@@ -534,9 +563,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(data); deferred.resolve(data);
}, },
(error: any) => { reason => {
handleError(error, "FetchKeysCassandra", `Error fetching keys for table ${collection.id()}`); NotificationConsoleUtils.logConsoleMessage(
deferred.reject(error); ConsoleDataType.Error,
`Error fetching keys for table ${collection.id()}:\n ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "FetchKeysCassandra", reason.status);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.done(() => { .done(() => {
@@ -584,9 +618,14 @@ export class CassandraAPIDataClient extends TableDataClient {
); );
deferred.resolve(data.columns); deferred.resolve(data.columns);
}, },
(error: any) => { reason => {
handleError(error, "FetchSchemaCassandra", `Error fetching schema for table ${collection.id()}`); NotificationConsoleUtils.logConsoleMessage(
deferred.reject(error); ConsoleDataType.Error,
`Error fetching schema for table ${collection.id()}:\n ${JSON.stringify(reason)}`
);
Logger.logError(JSON.stringify(reason), "FetchSchemaCassandra", reason.status);
this._checkForbiddenError(reason);
deferred.reject(reason);
} }
) )
.done(() => { .done(() => {
@@ -673,4 +712,13 @@ export class CassandraAPIDataClient extends TableDataClient {
displayTokenRenewalPromptForStatus(xhrObj.status); displayTokenRenewalPromptForStatus(xhrObj.status);
}; };
private _checkForbiddenError(reason: any) {
if (reason && reason.code === Constants.HttpStatusCodes.Forbidden) {
sendMessage({
type: MessageTypes.ForbiddenError,
reason: typeof reason === "string" ? "reason" : JSON.stringify(reason)
});
}
}
} }

View File

@@ -6,6 +6,7 @@ import * as ViewModels from "../../Contracts/ViewModels";
import { Action } from "../../Shared/Telemetry/TelemetryConstants"; import { Action } from "../../Shared/Telemetry/TelemetryConstants";
import { AccessibleVerticalList } from "../Tree/AccessibleVerticalList"; import { AccessibleVerticalList } from "../Tree/AccessibleVerticalList";
import { KeyCodes } from "../../Common/Constants"; import { KeyCodes } from "../../Common/Constants";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import ConflictId from "../Tree/ConflictId"; import ConflictId from "../Tree/ConflictId";
import editable from "../../Common/EditableUtility"; import editable from "../../Common/EditableUtility";
import * as HeadersUtility from "../../Common/HeadersUtility"; import * as HeadersUtility from "../../Common/HeadersUtility";
@@ -27,7 +28,6 @@ import {
updateDocument updateDocument
} from "../../Common/DocumentClientUtilityBase"; } from "../../Common/DocumentClientUtilityBase";
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent"; import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
export default class ConflictsTab extends TabsBase { export default class ConflictsTab extends TabsBase {
public selectedConflictId: ko.Observable<ConflictId>; public selectedConflictId: ko.Observable<ConflictId>;
@@ -241,8 +241,9 @@ export default class ConflictsTab extends TabsBase {
return this.loadNextPage(); return this.loadNextPage();
} }
) )
.catch(error => { .catch(reason => {
window.alert(getErrorMessage(error)); const message = ErrorParserUtility.parse(reason)[0].message;
window.alert(message);
}); });
} }
@@ -335,10 +336,10 @@ export default class ConflictsTab extends TabsBase {
); );
}); });
}, },
error => { reason => {
this.isExecutionError(true); this.isExecutionError(true);
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(reason)[0].message;
window.alert(errorMessage); window.alert(message);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.ResolveConflict, Action.ResolveConflict,
{ {
@@ -348,9 +349,7 @@ export default class ConflictsTab extends TabsBase {
tabTitle: this.tabTitle(), tabTitle: this.tabTitle(),
conflictResourceType: selectedConflict.resourceType, conflictResourceType: selectedConflict.resourceType,
conflictOperationType: selectedConflict.operationType, conflictOperationType: selectedConflict.operationType,
conflictResourceId: selectedConflict.resourceId, conflictResourceId: selectedConflict.resourceId
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -397,10 +396,10 @@ export default class ConflictsTab extends TabsBase {
startKey startKey
); );
}, },
error => { reason => {
this.isExecutionError(true); this.isExecutionError(true);
const errorMessage = getErrorMessage(error); const message = ErrorParserUtility.parse(reason)[0].message;
window.alert(errorMessage); window.alert(message);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.DeleteConflict, Action.DeleteConflict,
{ {
@@ -410,9 +409,7 @@ export default class ConflictsTab extends TabsBase {
tabTitle: this.tabTitle(), tabTitle: this.tabTitle(),
conflictResourceType: selectedConflict.resourceType, conflictResourceType: selectedConflict.resourceType,
conflictOperationType: selectedConflict.operationType, conflictOperationType: selectedConflict.operationType,
conflictResourceId: selectedConflict.resourceId, conflictResourceId: selectedConflict.resourceId
error: errorMessage,
errorStack: getErrorStack(error)
}, },
startKey startKey
); );
@@ -473,8 +470,7 @@ export default class ConflictsTab extends TabsBase {
defaultExperience: this.collection.container.defaultExperience(), defaultExperience: this.collection.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab, dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.tabTitle(), tabTitle: this.tabTitle(),
error: getErrorMessage(error), error: error
errorStack: getErrorStack(error)
}, },
this.onLoadStartKey this.onLoadStartKey
); );
@@ -549,8 +545,7 @@ export default class ConflictsTab extends TabsBase {
defaultExperience: this.collection.container.defaultExperience(), defaultExperience: this.collection.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab, dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.tabTitle(), tabTitle: this.tabTitle(),
error: getErrorMessage(error), error: error
errorStack: getErrorStack(error)
}, },
this.onLoadStartKey this.onLoadStartKey
); );

View File

@@ -1,6 +1,7 @@
import * as AutoPilotUtils from "../../Utils/AutoPilotUtils"; import * as AutoPilotUtils from "../../Utils/AutoPilotUtils";
import * as Constants from "../../Common/Constants"; import * as Constants from "../../Common/Constants";
import * as DataModels from "../../Contracts/DataModels"; import * as DataModels from "../../Contracts/DataModels";
import * as ErrorParserUtility from "../../Common/ErrorParserUtility";
import * as ko from "knockout"; import * as ko from "knockout";
import * as PricingUtils from "../../Utils/PricingUtils"; import * as PricingUtils from "../../Utils/PricingUtils";
import * as SharedConstants from "../../Shared/Constants"; import * as SharedConstants from "../../Shared/Constants";
@@ -19,7 +20,6 @@ import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandBu
import { userContext } from "../../UserContext"; import { userContext } from "../../UserContext";
import { updateOfferThroughputBeyondLimit } from "../../Common/dataAccess/updateOfferThroughputBeyondLimit"; import { updateOfferThroughputBeyondLimit } from "../../Common/dataAccess/updateOfferThroughputBeyondLimit";
import { configContext, Platform } from "../../ConfigContext"; import { configContext, Platform } from "../../ConfigContext";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
const updateThroughputBeyondLimitWarningMessage: string = ` const updateThroughputBeyondLimitWarningMessage: string = `
You are about to request an increase in throughput beyond the pre-allocated capacity. You are about to request an increase in throughput beyond the pre-allocated capacity.
@@ -163,8 +163,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
this.overrideWithAutoPilotSettings() ? this.autoPilotThroughput() : this.throughput(), this.overrideWithAutoPilotSettings() ? this.autoPilotThroughput() : this.throughput(),
serverId, serverId,
regions, regions,
multimaster, multimaster
false /*rupmEnabled*/
); );
} else { } else {
estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml( estimatedSpend = PricingUtils.getEstimatedAutoscaleSpendHtml(
@@ -460,8 +459,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
databaseAccountName: userContext.databaseAccount.name, databaseAccountName: userContext.databaseAccount.name,
resourceGroup: userContext.resourceGroup, resourceGroup: userContext.resourceGroup,
databaseName: this.database.id(), databaseName: this.database.id(),
throughput: newThroughput, throughput: newThroughput
offerIsRUPerMinuteThroughputEnabled: false
}; };
await updateOfferThroughputBeyondLimit(requestPayload); await updateOfferThroughputBeyondLimit(requestPayload);
this.database.offer().content.offerThroughput = originalThroughputValue; this.database.offer().content.offerThroughput = originalThroughputValue;
@@ -490,8 +488,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
this.container.isRefreshingExplorer(false); this.container.isRefreshingExplorer(false);
this.isExecutionError(true); this.isExecutionError(true);
console.error(error); console.error(error);
const errorMessage = getErrorMessage(error); this.displayedError(ErrorParserUtility.parse(error)[0].message);
this.displayedError(errorMessage);
TelemetryProcessor.traceFailure( TelemetryProcessor.traceFailure(
Action.UpdateSettings, Action.UpdateSettings,
{ {
@@ -500,8 +497,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
defaultExperience: this.container.defaultExperience(), defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab, dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.tabTitle(), tabTitle: this.tabTitle(),
error: errorMessage, error: error
errorStack: getErrorStack(error)
}, },
startKey startKey
); );

Some files were not shown because too many files have changed in this diff Show More