Refactored Settings Tab (#161)

* added  SettingsV2 Tab

* lint changes

* foxed failing test

* Addressed PR comments

- removed dangerouslySetInnerHtml
- removed underscore dependency
- added AccessibleElement
- removed unnecesary exceptions to linting

* split render into separate functions

- removed sinon in test
- Added some enums to replace constant strings
- removed dangerously set inner html
- made autopilot input as StatefulValue

* add settingscomponent snapshot

* fixed linting errors

* fixed errors

* addressed PR comments

- Moved StatefulValue to new class
- Split render to more functions for throughputInputComponents

* Added sub components

- Added tests for SettingsRenderUtls
- Added empty test files for adding tests later

* Moved all inputs to fluent UI

- removed rupm
- added reusable styles

* Added Tabs

- Added ToolTipLabel component
- Removed toggleables for individual components
- Removed accessible elements
- Added IndexingPolicyComponent

* Added more tests

* Addressed PR comments

* Moved Label radio buttons to choicegroup

* fixed lint errors

* Removed StatefulValue

- Moved conflict res tab to the end
- Added styling for autpilot radiobuttons

* fixed linting errors

* fix bugs from merge to master

* fixed formatting issue

* Addressed PR comments

- Added unit tests for smaller methods within each component

* fixed linting errors

* removed redundant snapshots

* removed empty line

* made separate props objects for subcomponents

* Moved dirty checks to sub components

* Made indesing policy component height = 80% of view port

- modified auto pilot v3 messages
- Added Fluent UI tolltip
-

* Moved warning messages inline

* moved conflict res helpers out

* fixed bugs

* added stack style for message

* fixed tests

* Added tests

* fixed linting and format errors

* undid changes

* more edits

* fixed compile errors

* fixed compile errors

* fixed errors

* fixed bug with save and discard buttons

* fixed compile errors

* addressed PR comments
This commit is contained in:
Srinath Narayanan 2020-09-30 12:34:39 -07:00 committed by GitHub
parent 4ecdfe60eb
commit fc722e87be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 11504 additions and 59 deletions

View File

@ -35,6 +35,7 @@
@NotificationLow: #FFF4CE;
@NotificationHigh: #F9E9B0;
@Purple1: #8A2DA5;
@Dirty: #9b4f96;
@BaseLow: #F2F2F2;
@BaseMediumLow: #E6E6E6;

78
package-lock.json generated
View File

@ -3294,10 +3294,9 @@
}
},
"@babel/runtime-corejs3": {
"version": "7.10.2",
"resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.10.2.tgz",
"integrity": "sha512-+a2M/u7r15o3dV1NEizr9bRi+KUVnrs/qYxF0Z06DAPx/4VCWaz1WA7EcbE+uqGgt39lp5akWGmHsTseIkHkHg==",
"dev": true,
"version": "7.11.2",
"resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.11.2.tgz",
"integrity": "sha512-qh5IR+8VgFz83VBa6OkaET6uN/mJOhHONuy3m1sgF0CV6mXdPSEBdA7e1eUbVvyNtANjMbg22JUv71BaDXLY6A==",
"requires": {
"core-js-pure": "^3.0.0",
"regenerator-runtime": "^0.13.4"
@ -9232,7 +9231,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz",
"integrity": "sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0",
@ -10991,8 +10989,7 @@
"core-js-pure": {
"version": "3.6.5",
"resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.6.5.tgz",
"integrity": "sha512-lacdXOimsiD0QyNf9BC/mxivNJ/ybBGJXQFKzRekp1WTHoVUWsUHEn+2T8GJAzzIhyOuXA+gOxCVN3l+5PLPUA==",
"dev": true
"integrity": "sha512-lacdXOimsiD0QyNf9BC/mxivNJ/ybBGJXQFKzRekp1WTHoVUWsUHEn+2T8GJAzzIhyOuXA+gOxCVN3l+5PLPUA=="
},
"core-util-is": {
"version": "1.0.2",
@ -13018,7 +13015,6 @@
"version": "7.20.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.20.0.tgz",
"integrity": "sha512-rqe1abd0vxMjmbPngo4NaYxTcR3Y4Hrmc/jg4T+sYz63yqlmJRknpEQfmWY+eDWPuMmix6iUIK+mv0zExjeLgA==",
"dev": true,
"requires": {
"array-includes": "^3.1.1",
"doctrine": "^2.1.0",
@ -13037,7 +13033,6 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",
"integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",
"dev": true,
"requires": {
"esutils": "^2.0.2"
}
@ -13046,7 +13041,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.2.tgz",
"integrity": "sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.5",
@ -16158,7 +16152,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.2.tgz",
"integrity": "sha512-2cQNfwhAfJIkU4KZPkDI+Gj5yNNnbqi40W9Gge6dfnk4TocEVm00B3bdiL+JINrbGJil2TeHvM4rETGzk/f/0g==",
"dev": true,
"requires": {
"es-abstract": "^1.17.0-next.1",
"has": "^1.0.3",
@ -16376,6 +16369,11 @@
"resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz",
"integrity": "sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw=="
},
"is-negative-zero": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz",
"integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE="
},
"is-number": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
@ -16461,8 +16459,7 @@
"is-string": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz",
"integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==",
"dev": true
"integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ=="
},
"is-subset": {
"version": "0.1.1",
@ -20556,7 +20553,6 @@
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz",
"integrity": "sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w==",
"dev": true,
"requires": {
"array-includes": "^3.1.1",
"object.assign": "^4.1.0"
@ -22222,7 +22218,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.2.tgz",
"integrity": "sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0-next.1",
@ -22260,7 +22255,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz",
"integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0-next.1",
@ -24837,13 +24831,51 @@
"integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw=="
},
"side-channel": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.2.tgz",
"integrity": "sha512-7rL9YlPHg7Ancea1S96Pa8/QWb4BtXL/TZvS6B8XFetGBeuhAsfmUspK6DokBeZ64+Kj9TCNRD/30pVz1BvQNA==",
"dev": true,
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.3.tgz",
"integrity": "sha512-A6+ByhlLkksFoUepsGxfj5x1gTSrs+OydsRptUxeNCabQpCFUvcwIczgOigI8vhY/OJCnPnyE9rGiwgvr9cS1g==",
"requires": {
"es-abstract": "^1.17.0-next.1",
"object-inspect": "^1.7.0"
"es-abstract": "^1.18.0-next.0",
"object-inspect": "^1.8.0"
},
"dependencies": {
"es-abstract": {
"version": "1.18.0-next.0",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.0.tgz",
"integrity": "sha512-elZXTZXKn51hUBdJjSZGYRujuzilgXo8vSPQzjGYXLvSlGiCo8VO8ZGV3kjo9a0WNJJ57hENagwbtlRuHuzkcQ==",
"requires": {
"es-to-primitive": "^1.2.1",
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1",
"is-callable": "^1.2.0",
"is-negative-zero": "^2.0.0",
"is-regex": "^1.1.1",
"object-inspect": "^1.8.0",
"object-keys": "^1.1.1",
"object.assign": "^4.1.0",
"string.prototype.trimend": "^1.0.1",
"string.prototype.trimstart": "^1.0.1"
}
},
"is-callable": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.0.tgz",
"integrity": "sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw=="
},
"is-regex": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz",
"integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==",
"requires": {
"has-symbols": "^1.0.1"
}
},
"object-inspect": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz",
"integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA=="
}
}
},
"signal-exit": {
@ -25475,7 +25507,6 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.2.tgz",
"integrity": "sha512-N/jp6O5fMf9os0JU3E72Qhf590RSRZU/ungsL/qJUYVTNv7hTG0P/dbPjxINVN9jpscu3nzYwKESU3P3RY5tOg==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0",
@ -28049,7 +28080,6 @@
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/xregexp/-/xregexp-4.3.0.tgz",
"integrity": "sha512-7jXDIFXh5yJ/orPn4SXjuVrWWoi4Cr8jfV1eHv9CixKSbU+jY4mxfrBwAuDvupPNKpMUY+FeIqsVw/JLT9+B8g==",
"dev": true,
"requires": {
"@babel/runtime-corejs3": "^7.8.3"
}

View File

@ -55,6 +55,7 @@
"es6-object-assign": "1.1.0",
"es6-symbol": "3.1.3",
"eslint-plugin-jest": "23.13.2",
"eslint-plugin-react": "7.20.0",
"hasher": "1.2.0",
"html2canvas": "1.0.0-rc.5",
"immutable": "4.0.0-rc.12",
@ -139,7 +140,6 @@
"eslint-cli": "1.1.1",
"eslint-plugin-no-null": "1.0.2",
"eslint-plugin-prefer-arrow": "1.2.2",
"eslint-plugin-react": "7.20.0",
"expose-loader": "0.7.5",
"file-loader": "2.0.0",
"fs-extra": "7.0.0",

View File

@ -124,6 +124,7 @@ export class Features {
public static readonly enableGalleryPublish = "enablegallerypublish";
public static readonly enableCodeOfConduct = "enablecodeofconduct";
public static readonly enableLinkInjection = "enablelinkinjection";
public static readonly enableSettingsV2 = "enablesettingsv2";
public static readonly enableSpark = "enablespark";
public static readonly livyEndpoint = "livyendpoint";
public static readonly notebookServerUrl = "notebookserverurl";

View File

@ -309,10 +309,6 @@ export interface ScriptTabOption extends TabOptions {
partitionKey?: DataModels.PartitionKey;
}
export interface WaitsForTemplate {
isTemplateReady: ko.Observable<boolean>;
}
export interface EditorPosition {
line: number;
column: number;
@ -359,7 +355,8 @@ export enum CollectionTabKind {
NotebookV2 = 15,
SparkMasterTab = 16,
Gallery = 17,
NotebookViewer = 18
NotebookViewer = 18,
SettingsV2 = 19
}
export enum TerminalKind {

View File

@ -48,6 +48,10 @@ describe("Component Registerer", () => {
expect(ko.components.isRegistered("settings-tab")).toBe(true);
});
it("should register settings-tab-v2 component", () => {
expect(ko.components.isRegistered("settings-tab-v2")).toBe(true);
});
it("should register query-tab component", () => {
expect(ko.components.isRegistered("query-tab")).toBe(true);
});

View File

@ -34,6 +34,7 @@ ko.components.register("stored-procedure-tab", new TabComponents.StoredProcedure
ko.components.register("trigger-tab", new TabComponents.TriggerTab());
ko.components.register("user-defined-function-tab", new TabComponents.UserDefinedFunctionTab());
ko.components.register("settings-tab", new TabComponents.SettingsTab());
ko.components.register("settings-tab-v2", new TabComponents.SettingsTabV2());
ko.components.register("query-tab", new TabComponents.QueryTab());
ko.components.register("tables-query-tab", new TabComponents.QueryTablesTab());
ko.components.register("graph-tab", new TabComponents.GraphTab());

View File

@ -55,6 +55,7 @@ export const FeaturePanelComponent: React.FunctionComponent = () => {
label: "Enable Injecting Notebook Viewer Link into the first cell",
value: "true"
},
{ key: "feature.enablesettingsv2", label: "Enable SettingsV2 Tab", value: "true" },
{ key: "feature.canexceedmaximumvalue", label: "Can exceed max value", value: "true" },
{
key: "feature.enablefixedcollectionwithsharedthroughput",

View File

@ -178,6 +178,12 @@ exports[`Feature panel renders all flags 1`] = `
className="checkboxRow"
horizontalAlign="space-between"
>
<StyledCheckboxBase
checked={false}
key="feature.enablesettingsv2"
label="Enable SettingsV2 Tab"
onChange={[Function]}
/>
<StyledCheckboxBase
checked={false}
key="feature.canexceedmaximumvalue"

View File

@ -0,0 +1,31 @@
@import "../../../../less/Common/Constants";
.settingsV2MainContainer {
height: 100%;
overflow-y: auto;
width: 100%;
}
.settingsV2ToolTip {
padding: 10px;
font: 12px @DataExplorerFont;
max-width: 300px;
}
.autoPilotSelector span {
height: 25px;
font: 14px @DataExplorerFont;
}
.settingsV2TabsContainer {
padding: @LargeSpace @LargeSpace 30px @LargeSpace;
height: 100%;
overflow-y: auto;
width: 100%;
font-family: @DataExplorerFont;
}
.settingsV2IndexingPolicyEditor {
width: 100%;
height: 60vh;
}

View File

@ -0,0 +1,269 @@
import { shallow } from "enzyme";
import React from "react";
import { SettingsComponentProps, SettingsComponent, SettingsComponentState } from "./SettingsComponent";
import * as ViewModels from "../../../Contracts/ViewModels";
import SettingsTabV2 from "../../Tabs/SettingsTabV2";
import { collection } from "./TestUtils";
import * as DataModels from "../../../Contracts/DataModels";
import ko from "knockout";
import { TtlType, isDirty, TtlOnNoDefault, TtlOn, TtlOff } from "./SettingsUtils";
import Explorer from "../../Explorer";
import { updateCollection } from "../../../Common/dataAccess/updateCollection";
jest.mock("../../../Common/dataAccess/updateCollection", () => ({
updateCollection: jest.fn().mockReturnValue({
id: undefined,
defaultTtl: undefined,
indexingPolicy: undefined,
conflictResolutionPolicy: undefined,
changeFeedPolicy: undefined,
analyticalStorageTtl: undefined,
geospatialConfig: undefined
} as DataModels.Collection)
}));
import { updateOffer } from "../../../Common/DocumentClientUtilityBase";
jest.mock("../../../Common/DocumentClientUtilityBase", () => ({
updateOffer: jest.fn().mockReturnValue({} as DataModels.Offer)
}));
describe("SettingsComponent", () => {
const baseProps: SettingsComponentProps = {
settingsTab: new SettingsTabV2({
collection: collection,
tabKind: ViewModels.CollectionTabKind.SettingsV2,
title: "Scale & Settings",
tabPath: "",
node: undefined,
selfLink: undefined,
hashLocation: "settings",
isActive: ko.observable(false),
onUpdateTabsButtons: undefined
})
};
it("renders", () => {
const wrapper = shallow(<SettingsComponent {...baseProps} />);
expect(wrapper).toMatchSnapshot();
});
it("dirty value enables save button and discard button", () => {
const wrapper = shallow(<SettingsComponent {...baseProps} />);
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
expect(settingsComponentInstance.isSaveSettingsButtonEnabled()).toEqual(false);
expect(settingsComponentInstance.isDiscardSettingsButtonEnabled()).toEqual(false);
wrapper.setState({ isScaleSaveable: true, isScaleDiscardable: true });
wrapper.update();
expect(settingsComponentInstance.isSaveSettingsButtonEnabled()).toEqual(true);
expect(settingsComponentInstance.isDiscardSettingsButtonEnabled()).toEqual(true);
wrapper.setState({
isScaleSaveable: false,
isScaleDiscardable: false,
isSubSettingsSaveable: true,
isSubSettingsDiscardable: true
});
wrapper.update();
expect(settingsComponentInstance.isSaveSettingsButtonEnabled()).toEqual(true);
expect(settingsComponentInstance.isDiscardSettingsButtonEnabled()).toEqual(true);
wrapper.setState({ isSubSettingsSaveable: false, isSubSettingsDiscardable: false, isIndexingPolicyDirty: true });
wrapper.update();
expect(settingsComponentInstance.isSaveSettingsButtonEnabled()).toEqual(true);
expect(settingsComponentInstance.isDiscardSettingsButtonEnabled()).toEqual(true);
wrapper.setState({ isIndexingPolicyDirty: false, isConflictResolutionDirty: true });
wrapper.update();
expect(settingsComponentInstance.isSaveSettingsButtonEnabled()).toEqual(true);
expect(settingsComponentInstance.isDiscardSettingsButtonEnabled()).toEqual(true);
});
it("auto pilot helper functions pass on correct value", () => {
const newCollection = { ...collection };
newCollection.offer = ko.observable<DataModels.Offer>({
content: {
offerAutopilotSettings: {
maxThroughput: 10000
}
}
} as DataModels.Offer);
const props = { ...baseProps };
props.settingsTab.collection = newCollection;
const wrapper = shallow(<SettingsComponent {...props} />);
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
expect(settingsComponentInstance.hasProvisioningTypeChanged()).toEqual(false);
wrapper.setState({
userCanChangeProvisioningTypes: true,
isAutoPilotSelected: true,
wasAutopilotOriginallySet: false,
autoPilotThroughput: 1000
});
wrapper.update();
expect(settingsComponentInstance.hasProvisioningTypeChanged()).toEqual(true);
});
it("shouldShowKeyspaceSharedThroughputMessage", () => {
let settingsComponentInstance = new SettingsComponent(baseProps);
expect(settingsComponentInstance.shouldShowKeyspaceSharedThroughputMessage()).toEqual(false);
const newContainer = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
newContainer.isPreferredApiCassandra = ko.computed(() => true);
const newCollection = { ...collection };
newCollection.container = newContainer;
const newDatabase = {
nodeKind: undefined,
rid: undefined,
container: newContainer,
self: undefined,
id: undefined,
collections: undefined,
offer: undefined,
isDatabaseExpanded: undefined,
isDatabaseShared: ko.computed(() => true),
selectedSubnodeKind: undefined,
selectDatabase: undefined,
expandDatabase: undefined,
collapseDatabase: undefined,
loadCollections: undefined,
findCollectionWithId: undefined,
openAddCollection: undefined,
onDeleteDatabaseContextMenuClick: undefined,
readSettings: undefined,
onSettingsClick: undefined,
loadOffer: undefined
} as ViewModels.Database;
newCollection.getDatabase = () => newDatabase;
newCollection.offer = ko.observable(undefined);
const props = { ...baseProps };
props.settingsTab.collection = newCollection;
settingsComponentInstance = new SettingsComponent(props);
expect(settingsComponentInstance.shouldShowKeyspaceSharedThroughputMessage()).toEqual(true);
});
it("hasConflictResolution", () => {
let settingsComponentInstance = new SettingsComponent(baseProps);
expect(settingsComponentInstance.hasConflictResolution()).toEqual(undefined);
const newContainer = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
newContainer.databaseAccount = ko.observable({
id: undefined,
name: undefined,
location: undefined,
type: undefined,
kind: undefined,
tags: undefined,
properties: {
documentEndpoint: undefined,
tableEndpoint: undefined,
gremlinEndpoint: undefined,
cassandraEndpoint: undefined,
enableMultipleWriteLocations: true
}
});
const newCollection = { ...collection };
newCollection.container = newContainer;
newCollection.conflictResolutionPolicy = ko.observable({
mode: DataModels.ConflictResolutionMode.Custom,
conflictResolutionProcedure: undefined
} as DataModels.ConflictResolutionPolicy);
const props = { ...baseProps };
props.settingsTab.collection = newCollection;
settingsComponentInstance = new SettingsComponent(props);
expect(settingsComponentInstance.hasConflictResolution()).toEqual(true);
});
it("isOfferReplacePending", () => {
let settingsComponentInstance = new SettingsComponent(baseProps);
expect(settingsComponentInstance.isOfferReplacePending()).toEqual(undefined);
const newCollection = { ...collection };
newCollection.offer = ko.observable({
headers: { "x-ms-offer-replace-pending": true }
} as DataModels.OfferWithHeaders);
const props = { ...baseProps };
props.settingsTab.collection = newCollection;
settingsComponentInstance = new SettingsComponent(props);
expect(settingsComponentInstance.isOfferReplacePending()).toEqual(true);
});
it("save calls updateCollection and updateOffer", async () => {
const wrapper = shallow(<SettingsComponent {...baseProps} />);
wrapper.setState({ isSubSettingsSaveable: true, isScaleSaveable: true });
wrapper.update();
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
await settingsComponentInstance.onSaveClick();
expect(updateCollection).toBeCalled();
expect(updateOffer).toBeCalled();
});
it("revert resets state values", async () => {
const wrapper = shallow(<SettingsComponent {...baseProps} />);
wrapper.setState({ timeToLive: TtlType.OnNoDefault, throughput: 10 });
wrapper.update();
let state = wrapper.state() as SettingsComponentState;
expect(isDirty(state.timeToLive, state.timeToLiveBaseline)).toEqual(true);
expect(isDirty(state.throughput, state.throughputBaseline)).toEqual(true);
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
settingsComponentInstance.onRevertClick();
state = wrapper.state() as SettingsComponentState;
expect(isDirty(state.timeToLive, state.timeToLiveBaseline)).toEqual(false);
expect(isDirty(state.throughput, state.throughputBaseline)).toEqual(false);
});
it("getTtlValue", async () => {
const settingsComponentInstance = new SettingsComponent(baseProps);
expect(settingsComponentInstance.getTtlValue(TtlType.OnNoDefault)).toEqual(TtlOnNoDefault);
expect(settingsComponentInstance.getTtlValue(TtlType.On)).toEqual(TtlOn);
expect(settingsComponentInstance.getTtlValue(TtlType.Off)).toEqual(TtlOff);
});
it("getAnalyticalStorageTtl", () => {
const newCollection = { ...collection };
newCollection.analyticalStorageTtl = ko.observable(10);
const props = { ...baseProps };
props.settingsTab.collection = newCollection;
const wrapper = shallow(<SettingsComponent {...props} />);
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
expect(settingsComponentInstance.getAnalyticalStorageTtl()).toEqual(10);
wrapper.setState({ analyticalStorageTtlSelection: TtlType.Off });
wrapper.update();
expect(settingsComponentInstance.getAnalyticalStorageTtl()).toEqual(-1);
});
it("getUpdatedConflictResolutionPolicy", () => {
const wrapper = shallow(<SettingsComponent {...baseProps} />);
const conflictResolutionPolicyPath = "_ts";
const conflictResolutionPolicyProcedure = "sample_sproc";
const expectSprocPath =
"/dbs/" + collection.databaseId + "/colls/" + collection.id() + "/sprocs/" + conflictResolutionPolicyProcedure;
wrapper.setState({
conflictResolutionPolicyMode: DataModels.ConflictResolutionMode.LastWriterWins,
conflictResolutionPolicyPath: conflictResolutionPolicyPath
});
wrapper.update();
const settingsComponentInstance = wrapper.instance() as SettingsComponent;
let conflictResolutionPolicy = settingsComponentInstance.getUpdatedConflictResolutionPolicy();
expect(conflictResolutionPolicy.mode).toEqual(DataModels.ConflictResolutionMode.LastWriterWins);
expect(conflictResolutionPolicy.conflictResolutionPath).toEqual(conflictResolutionPolicyPath);
wrapper.setState({
conflictResolutionPolicyMode: DataModels.ConflictResolutionMode.Custom,
conflictResolutionPolicyProcedure: conflictResolutionPolicyProcedure
});
wrapper.update();
conflictResolutionPolicy = settingsComponentInstance.getUpdatedConflictResolutionPolicy();
expect(conflictResolutionPolicy.mode).toEqual(DataModels.ConflictResolutionMode.Custom);
expect(conflictResolutionPolicy.conflictResolutionProcedure).toEqual(expectSprocPath);
});
});

View File

@ -0,0 +1,912 @@
import * as React from "react";
import * as AutoPilotUtils from "../../../Utils/AutoPilotUtils";
import * as Constants from "../../../Common/Constants";
import * as DataModels from "../../../Contracts/DataModels";
import * as SharedConstants from "../../../Shared/Constants";
import * as ViewModels from "../../../Contracts/ViewModels";
import DiscardIcon from "../../../../images/discard.svg";
import SaveIcon from "../../../../images/save-cosmos.svg";
import { traceStart, traceFailure, traceSuccess } from "../../../Shared/Telemetry/TelemetryProcessor";
import { Action } from "../../../Shared/Telemetry/TelemetryConstants";
import { RequestOptions } from "@azure/cosmos/dist-esm";
import Explorer from "../../Explorer";
import { updateOffer } from "../../../Common/DocumentClientUtilityBase";
import { updateCollection } from "../../../Common/dataAccess/updateCollection";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
import { userContext } from "../../../UserContext";
import { updateOfferThroughputBeyondLimit } from "../../../Common/dataAccess/updateOfferThroughputBeyondLimit";
import SettingsTab from "../../Tabs/SettingsTabV2";
import { throughputUnit } from "./SettingsRenderUtils";
import { ScaleComponent, ScaleComponentProps } from "./SettingsSubComponents/ScaleComponent";
import {
getMaxRUs,
hasDatabaseSharedThroughput,
GeospatialConfigType,
TtlType,
ChangeFeedPolicyState,
SettingsV2TabTypes,
getTabTitle,
isDirty,
TtlOff,
TtlOn,
TtlOnNoDefault,
parseConflictResolutionMode,
parseConflictResolutionProcedure
} from "./SettingsUtils";
import {
ConflictResolutionComponent,
ConflictResolutionComponentProps
} from "./SettingsSubComponents/ConflictResolutionComponent";
import { SubSettingsComponent, SubSettingsComponentProps } from "./SettingsSubComponents/SubSettingsComponent";
import { Pivot, PivotItem, IPivotProps, IPivotItemProps, IChoiceGroupOption } from "office-ui-fabric-react";
import "./SettingsComponent.less";
import { IndexingPolicyComponent, IndexingPolicyComponentProps } from "./SettingsSubComponents/IndexingPolicyComponent";
interface SettingsV2TabInfo {
tab: SettingsV2TabTypes;
content: JSX.Element;
}
interface ButtonV2 {
isVisible: () => boolean;
isEnabled: () => boolean;
isSelected?: () => boolean;
}
export interface SettingsComponentProps {
settingsTab: SettingsTab;
}
export interface SettingsComponentState {
throughput: number;
throughputBaseline: number;
autoPilotThroughput: number;
autoPilotThroughputBaseline: number;
isAutoPilotSelected: boolean;
wasAutopilotOriginallySet: boolean;
isScaleSaveable: boolean;
isScaleDiscardable: boolean;
timeToLive: TtlType;
timeToLiveBaseline: TtlType;
timeToLiveSeconds: number;
timeToLiveSecondsBaseline: number;
geospatialConfigType: GeospatialConfigType;
geospatialConfigTypeBaseline: GeospatialConfigType;
analyticalStorageTtlSelection: TtlType;
analyticalStorageTtlSelectionBaseline: TtlType;
analyticalStorageTtlSeconds: number;
analyticalStorageTtlSecondsBaseline: number;
changeFeedPolicy: ChangeFeedPolicyState;
changeFeedPolicyBaseline: ChangeFeedPolicyState;
isSubSettingsSaveable: boolean;
isSubSettingsDiscardable: boolean;
indexingPolicyContent: DataModels.IndexingPolicy;
indexingPolicyContentBaseline: DataModels.IndexingPolicy;
shouldDiscardIndexingPolicy: boolean;
indexingPolicyElementFocussed: boolean;
isIndexingPolicyDirty: boolean;
conflictResolutionPolicyMode: DataModels.ConflictResolutionMode;
conflictResolutionPolicyModeBaseline: DataModels.ConflictResolutionMode;
conflictResolutionPolicyPath: string;
conflictResolutionPolicyPathBaseline: string;
conflictResolutionPolicyProcedure: string;
conflictResolutionPolicyProcedureBaseline: string;
isConflictResolutionDirty: boolean;
initialNotification: DataModels.Notification;
selectedTab: SettingsV2TabTypes;
}
export class SettingsComponent extends React.Component<SettingsComponentProps, SettingsComponentState> {
private static readonly sixMonthsInSeconds = 15768000;
private static readonly zeroSeconds = 0;
public saveSettingsButton: ButtonV2;
public discardSettingsChangesButton: ButtonV2;
public isAnalyticalStorageEnabled: boolean;
private collection: ViewModels.Collection;
private container: Explorer;
private changeFeedPolicyVisible: boolean;
private isFixedContainer: boolean;
private autoPilotTiersList: ViewModels.DropdownOption<DataModels.AutopilotTier>[];
private shouldShowIndexingPolicyEditor: boolean;
constructor(props: SettingsComponentProps) {
super(props);
this.collection = this.props.settingsTab.collection as ViewModels.Collection;
this.container = this.collection?.container;
this.isAnalyticalStorageEnabled = !!this.collection?.analyticalStorageTtl();
this.shouldShowIndexingPolicyEditor =
this.container && !this.container.isPreferredApiCassandra() && !this.container.isPreferredApiMongoDB();
this.changeFeedPolicyVisible = this.collection?.container.isFeatureEnabled(
Constants.Features.enableChangeFeedPolicy
);
// Mongo container with system partition key still treat as "Fixed"
this.isFixedContainer =
!this.collection.partitionKey ||
(this.container.isPreferredApiMongoDB() && this.collection.partitionKey.systemKey);
this.state = {
throughput: undefined,
throughputBaseline: undefined,
autoPilotThroughput: undefined,
autoPilotThroughputBaseline: undefined,
isAutoPilotSelected: false,
wasAutopilotOriginallySet: false,
isScaleSaveable: false,
isScaleDiscardable: false,
timeToLive: undefined,
timeToLiveBaseline: undefined,
timeToLiveSeconds: undefined,
timeToLiveSecondsBaseline: undefined,
geospatialConfigType: undefined,
geospatialConfigTypeBaseline: undefined,
analyticalStorageTtlSelection: undefined,
analyticalStorageTtlSelectionBaseline: undefined,
analyticalStorageTtlSeconds: undefined,
analyticalStorageTtlSecondsBaseline: undefined,
changeFeedPolicy: undefined,
changeFeedPolicyBaseline: undefined,
isSubSettingsSaveable: false,
isSubSettingsDiscardable: false,
indexingPolicyContent: undefined,
indexingPolicyContentBaseline: undefined,
indexingPolicyElementFocussed: false,
shouldDiscardIndexingPolicy: false,
isIndexingPolicyDirty: false,
conflictResolutionPolicyMode: undefined,
conflictResolutionPolicyModeBaseline: undefined,
conflictResolutionPolicyPath: undefined,
conflictResolutionPolicyPathBaseline: undefined,
conflictResolutionPolicyProcedure: undefined,
conflictResolutionPolicyProcedureBaseline: undefined,
isConflictResolutionDirty: false,
initialNotification: undefined,
selectedTab: SettingsV2TabTypes.ScaleTab
};
this.saveSettingsButton = {
isEnabled: this.isSaveSettingsButtonEnabled,
isVisible: () => {
return true;
}
};
this.discardSettingsChangesButton = {
isEnabled: this.isDiscardSettingsButtonEnabled,
isVisible: () => {
return true;
}
};
}
componentDidMount(): void {
this.setAutoPilotStates();
this.setBaseline();
if (this.props.settingsTab.isActive()) {
this.props.settingsTab.getSettingsTabContainer().onUpdateTabsButtons(this.getTabsButtons());
}
}
componentDidUpdate(): void {
if (this.props.settingsTab.isActive()) {
this.props.settingsTab.getSettingsTabContainer().onUpdateTabsButtons(this.getTabsButtons());
}
}
public isSaveSettingsButtonEnabled = (): boolean => {
if (this.isOfferReplacePending()) {
return false;
}
return (
this.state.isScaleSaveable ||
this.state.isSubSettingsSaveable ||
this.state.isIndexingPolicyDirty ||
this.state.isConflictResolutionDirty
);
};
public isDiscardSettingsButtonEnabled = (): boolean => {
return (
this.state.isScaleDiscardable ||
this.state.isSubSettingsDiscardable ||
this.state.isIndexingPolicyDirty ||
this.state.isConflictResolutionDirty
);
};
private setAutoPilotStates = (): void => {
const offer = this.collection?.offer && this.collection.offer();
const offerAutopilotSettings = offer?.content?.offerAutopilotSettings;
if (
offerAutopilotSettings &&
offerAutopilotSettings.maxThroughput &&
AutoPilotUtils.isValidAutoPilotThroughput(offerAutopilotSettings.maxThroughput)
) {
this.setState({
isAutoPilotSelected: true,
wasAutopilotOriginallySet: true,
autoPilotThroughput: offerAutopilotSettings.maxThroughput,
autoPilotThroughputBaseline: offerAutopilotSettings.maxThroughput
});
}
};
public hasProvisioningTypeChanged = (): boolean =>
this.state.wasAutopilotOriginallySet !== this.state.isAutoPilotSelected;
public shouldShowKeyspaceSharedThroughputMessage = (): boolean =>
this.container && this.container.isPreferredApiCassandra() && hasDatabaseSharedThroughput(this.collection);
public hasConflictResolution = (): boolean =>
this.container?.databaseAccount &&
this.container.databaseAccount()?.properties?.enableMultipleWriteLocations &&
this.collection.conflictResolutionPolicy &&
!!this.collection.conflictResolutionPolicy();
public isOfferReplacePending = (): boolean => {
const offer = this.collection?.offer && this.collection.offer();
return (
offer &&
Object.keys(offer).find(value => value === "headers") &&
!!(offer as DataModels.OfferWithHeaders).headers[Constants.HttpHeaders.offerReplacePending]
);
};
public onSaveClick = async (): Promise<void> => {
this.props.settingsTab.isExecutionError(false);
this.props.settingsTab.isExecuting(true);
const startKey: number = traceStart(Action.UpdateSettings, {
databaseAccountName: this.container.databaseAccount()?.name,
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle()
});
const newCollection: DataModels.Collection = { ...this.collection.rawDataModel };
try {
if (
this.state.isSubSettingsSaveable ||
this.state.isIndexingPolicyDirty ||
this.state.isConflictResolutionDirty
) {
let defaultTtl: number;
switch (this.state.timeToLive) {
case TtlType.On:
defaultTtl = Number(this.state.timeToLiveSeconds);
break;
case TtlType.OnNoDefault:
defaultTtl = -1;
break;
case TtlType.Off:
default:
defaultTtl = undefined;
break;
}
newCollection.defaultTtl = defaultTtl;
newCollection.indexingPolicy = this.state.indexingPolicyContent;
newCollection.changeFeedPolicy =
this.changeFeedPolicyVisible && this.state.changeFeedPolicy === ChangeFeedPolicyState.On
? {
retentionDuration: Constants.BackendDefaults.maxChangeFeedRetentionDuration
}
: undefined;
newCollection.analyticalStorageTtl = this.getAnalyticalStorageTtl();
newCollection.geospatialConfig = {
type: this.state.geospatialConfigType
};
const conflictResolutionChanges: DataModels.ConflictResolutionPolicy = this.getUpdatedConflictResolutionPolicy();
if (conflictResolutionChanges) {
newCollection.conflictResolutionPolicy = conflictResolutionChanges;
}
const updatedCollection: DataModels.Collection = await updateCollection(
this.collection.databaseId,
this.collection.id(),
newCollection
);
this.collection.rawDataModel = updatedCollection;
this.collection.defaultTtl(updatedCollection.defaultTtl);
this.collection.analyticalStorageTtl(updatedCollection.analyticalStorageTtl);
this.collection.id(updatedCollection.id);
this.collection.indexingPolicy(updatedCollection.indexingPolicy);
this.collection.conflictResolutionPolicy(updatedCollection.conflictResolutionPolicy);
this.collection.changeFeedPolicy(updatedCollection.changeFeedPolicy);
this.collection.geospatialConfig(updatedCollection.geospatialConfig);
this.setState({
isSubSettingsSaveable: false,
isSubSettingsDiscardable: false,
isIndexingPolicyDirty: false,
isConflictResolutionDirty: false
});
}
if (this.state.isScaleSaveable) {
const newThroughput = this.state.throughput;
const newOffer: DataModels.Offer = { ...this.collection.offer() };
const originalThroughputValue: number = this.state.throughput;
if (newOffer.content) {
newOffer.content.offerThroughput = newThroughput;
} else {
newOffer.content = {
offerThroughput: newThroughput,
offerIsRUPerMinuteThroughputEnabled: false
};
}
const headerOptions: RequestOptions = { initialHeaders: {} };
if (this.state.isAutoPilotSelected) {
newOffer.content.offerAutopilotSettings = {
maxThroughput: this.state.autoPilotThroughput
};
// user has changed from provisioned --> autoscale
if (this.hasProvisioningTypeChanged()) {
headerOptions.initialHeaders[Constants.HttpHeaders.migrateOfferToAutopilot] = "true";
delete newOffer.content.offerAutopilotSettings;
} else {
delete newOffer.content.offerThroughput;
}
} else {
this.setState({
isAutoPilotSelected: false
});
// user has changed from autoscale --> provisioned
if (this.hasProvisioningTypeChanged()) {
headerOptions.initialHeaders[Constants.HttpHeaders.migrateOfferToManualThroughput] = "true";
} else {
delete newOffer.content.offerAutopilotSettings;
}
}
if (
getMaxRUs(this.collection, this.container) <=
SharedConstants.CollectionCreation.DefaultCollectionRUs1Million &&
newThroughput > SharedConstants.CollectionCreation.DefaultCollectionRUs1Million &&
this.container
) {
const requestPayload = {
subscriptionId: userContext.subscriptionId,
databaseAccountName: userContext.databaseAccount.name,
resourceGroup: userContext.resourceGroup,
databaseName: this.collection.databaseId,
collectionName: this.collection.id(),
throughput: newThroughput,
offerIsRUPerMinuteThroughputEnabled: false
};
try {
await updateOfferThroughputBeyondLimit(requestPayload);
this.collection.offer().content.offerThroughput = originalThroughputValue;
this.setState({
throughput: originalThroughputValue,
throughputBaseline: originalThroughputValue,
initialNotification: {
description: `Throughput update for ${newThroughput} ${throughputUnit}`
} as DataModels.Notification
});
this.setState({ isScaleSaveable: false, isScaleDiscardable: false });
} catch (error) {
traceFailure(
Action.UpdateSettings,
{
databaseAccountName: this.container.databaseAccount().name,
databaseName: this.collection && this.collection.databaseId,
collectionName: this.collection && this.collection.id(),
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle(),
error: error
},
startKey
);
throw error;
}
} else {
const updatedOffer: DataModels.Offer = await updateOffer(this.collection.offer(), newOffer, headerOptions);
this.collection.offer(updatedOffer);
this.setState({ isScaleSaveable: false, isScaleDiscardable: false });
if (this.state.isAutoPilotSelected) {
this.setState({
autoPilotThroughput: updatedOffer.content.offerAutopilotSettings.maxThroughput,
autoPilotThroughputBaseline: updatedOffer.content.offerAutopilotSettings.maxThroughput
});
} else {
this.setState({
throughput: updatedOffer.content.offerThroughput,
throughputBaseline: updatedOffer.content.offerThroughput
});
}
}
}
this.container.isRefreshingExplorer(false);
this.setBaseline();
this.setState({ wasAutopilotOriginallySet: this.state.isAutoPilotSelected });
traceSuccess(
Action.UpdateSettings,
{
databaseAccountName: this.container.databaseAccount()?.name,
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle()
},
startKey
);
} catch (reason) {
this.container.isRefreshingExplorer(false);
this.props.settingsTab.isExecutionError(true);
console.error(reason);
traceFailure(
Action.UpdateSettings,
{
databaseAccountName: this.container.databaseAccount()?.name,
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle()
},
startKey
);
}
this.props.settingsTab.isExecuting(false);
};
public onRevertClick = (): void => {
this.setState({
throughput: this.state.throughputBaseline,
timeToLive: this.state.timeToLiveBaseline,
timeToLiveSeconds: this.state.timeToLiveSecondsBaseline,
geospatialConfigType: this.state.geospatialConfigTypeBaseline,
indexingPolicyContent: this.state.indexingPolicyContentBaseline,
conflictResolutionPolicyMode: this.state.conflictResolutionPolicyModeBaseline,
conflictResolutionPolicyPath: this.state.conflictResolutionPolicyPathBaseline,
conflictResolutionPolicyProcedure: this.state.conflictResolutionPolicyProcedureBaseline,
analyticalStorageTtlSelection: this.state.analyticalStorageTtlSelectionBaseline,
analyticalStorageTtlSeconds: this.state.analyticalStorageTtlSecondsBaseline,
changeFeedPolicy: this.state.changeFeedPolicyBaseline,
autoPilotThroughput: this.state.autoPilotThroughputBaseline,
isAutoPilotSelected: this.state.wasAutopilotOriginallySet,
shouldDiscardIndexingPolicy: true,
isScaleSaveable: false,
isScaleDiscardable: false,
isSubSettingsSaveable: false,
isSubSettingsDiscardable: false,
isIndexingPolicyDirty: false,
isConflictResolutionDirty: false
});
};
private onScaleSaveableChange = (isScaleSaveable: boolean): void =>
this.setState({ isScaleSaveable: isScaleSaveable });
private onScaleDiscardableChange = (isScaleDiscardable: boolean): void =>
this.setState({ isScaleDiscardable: isScaleDiscardable });
private onIndexingPolicyElementFocusChange = (indexingPolicyElementFocussed: boolean): void =>
this.setState({ indexingPolicyElementFocussed: indexingPolicyElementFocussed });
private onIndexingPolicyContentChange = (newIndexingPolicy: DataModels.IndexingPolicy): void =>
this.setState({ indexingPolicyContent: newIndexingPolicy });
private resetShouldDiscardIndexingPolicy = (): void => this.setState({ shouldDiscardIndexingPolicy: false });
private logIndexingPolicySuccessMessage = (): void => {
if (this.props.settingsTab.onLoadStartKey) {
traceSuccess(
Action.Tab,
{
databaseAccountName: this.container.databaseAccount().name,
databaseName: this.collection.databaseId,
collectionName: this.collection.id(),
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: this.props.settingsTab.tabTitle()
},
this.props.settingsTab.onLoadStartKey
);
this.props.settingsTab.onLoadStartKey = undefined;
}
};
private onConflictResolutionPolicyModeChange = (
event?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
): void =>
this.setState({
conflictResolutionPolicyMode:
DataModels.ConflictResolutionMode[option.key as keyof typeof DataModels.ConflictResolutionMode]
});
private onConflictResolutionPolicyPathChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => this.setState({ conflictResolutionPolicyPath: newValue });
private onConflictResolutionPolicyProcedureChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => this.setState({ conflictResolutionPolicyProcedure: newValue });
private onConflictResolutionDirtyChange = (isConflictResolutionDirty: boolean): void =>
this.setState({ isConflictResolutionDirty: isConflictResolutionDirty });
public getTtlValue = (value: string): TtlType => {
switch (value) {
case TtlOn:
return TtlType.On;
case TtlOff:
return TtlType.Off;
case TtlOnNoDefault:
return TtlType.OnNoDefault;
}
return undefined;
};
private onTtlChange = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption): void =>
this.setState({ timeToLive: this.getTtlValue(option.key) });
private onTimeToLiveSecondsChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => {
let newTimeToLiveSeconds = parseInt(newValue);
newTimeToLiveSeconds = isNaN(newTimeToLiveSeconds) ? SettingsComponent.zeroSeconds : newTimeToLiveSeconds;
this.setState({ timeToLiveSeconds: newTimeToLiveSeconds });
};
private onGeoSpatialConfigTypeChange = (
ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
): void =>
this.setState({ geospatialConfigType: GeospatialConfigType[option.key as keyof typeof GeospatialConfigType] });
private onAnalyticalStorageTtlSelectionChange = (
ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
): void => this.setState({ analyticalStorageTtlSelection: this.getTtlValue(option.key) });
private onAnalyticalStorageTtlSecondsChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => {
let newAnalyticalStorageTtlSeconds = parseInt(newValue);
newAnalyticalStorageTtlSeconds = isNaN(newAnalyticalStorageTtlSeconds)
? SettingsComponent.zeroSeconds
: newAnalyticalStorageTtlSeconds;
this.setState({ analyticalStorageTtlSeconds: newAnalyticalStorageTtlSeconds });
};
private onChangeFeedPolicyChange = (
ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
): void =>
this.setState({ changeFeedPolicy: ChangeFeedPolicyState[option.key as keyof typeof ChangeFeedPolicyState] });
private onSubSettingsSaveableChange = (isSubSettingsSaveable: boolean): void =>
this.setState({ isSubSettingsSaveable: isSubSettingsSaveable });
private onSubSettingsDiscardableChange = (isSubSettingsDiscardable: boolean): void =>
this.setState({ isSubSettingsDiscardable: isSubSettingsDiscardable });
private onIndexingPolicyDirtyChange = (isIndexingPolicyDirty: boolean): void =>
this.setState({ isIndexingPolicyDirty: isIndexingPolicyDirty });
public getAnalyticalStorageTtl = (): number => {
if (this.isAnalyticalStorageEnabled) {
if (this.state.analyticalStorageTtlSelection === TtlType.On) {
return Number(this.state.analyticalStorageTtlSeconds);
} else {
return Constants.AnalyticalStorageTtl.Infinite;
}
}
return undefined;
};
public getUpdatedConflictResolutionPolicy = (): DataModels.ConflictResolutionPolicy => {
if (
!isDirty(this.state.conflictResolutionPolicyMode, this.state.conflictResolutionPolicyModeBaseline) &&
!isDirty(this.state.conflictResolutionPolicyPath, this.state.conflictResolutionPolicyPathBaseline) &&
!isDirty(this.state.conflictResolutionPolicyProcedure, this.state.conflictResolutionPolicyProcedureBaseline)
) {
return undefined;
}
const policy: DataModels.ConflictResolutionPolicy = {
mode: parseConflictResolutionMode(this.state.conflictResolutionPolicyMode)
};
if (
policy.mode === DataModels.ConflictResolutionMode.Custom &&
this.state.conflictResolutionPolicyProcedure?.length > 0
) {
policy.conflictResolutionProcedure = Constants.HashRoutePrefixes.sprocWithIds(
this.collection.databaseId,
this.collection.id(),
this.state.conflictResolutionPolicyProcedure,
false
);
}
if (policy.mode === DataModels.ConflictResolutionMode.LastWriterWins) {
policy.conflictResolutionPath = this.state.conflictResolutionPolicyPath;
if (policy.conflictResolutionPath?.startsWith("/")) {
policy.conflictResolutionPath = "/" + policy.conflictResolutionPath;
}
}
return policy;
};
public setBaseline = (): void => {
const defaultTtl = this.collection.defaultTtl();
let timeToLive: TtlType = this.state.timeToLive;
let timeToLiveSeconds = this.state.timeToLiveSeconds;
switch (defaultTtl) {
case undefined:
case 0:
timeToLive = TtlType.Off;
timeToLiveSeconds = SettingsComponent.sixMonthsInSeconds;
break;
case -1:
timeToLive = TtlType.OnNoDefault;
timeToLiveSeconds = SettingsComponent.sixMonthsInSeconds;
break;
default:
timeToLive = TtlType.On;
timeToLiveSeconds = defaultTtl;
break;
}
let analyticalStorageTtlSelection: TtlType;
let analyticalStorageTtlSeconds: number;
if (this.isAnalyticalStorageEnabled) {
const analyticalStorageTtl: number = this.collection.analyticalStorageTtl();
if (analyticalStorageTtl === Constants.AnalyticalStorageTtl.Infinite) {
analyticalStorageTtlSelection = TtlType.OnNoDefault;
} else {
analyticalStorageTtlSelection = TtlType.On;
analyticalStorageTtlSeconds = analyticalStorageTtl;
}
}
const offerThroughput = this.collection?.offer && this.collection.offer()?.content?.offerThroughput;
const changeFeedPolicy = this.collection.rawDataModel?.changeFeedPolicy
? ChangeFeedPolicyState.On
: ChangeFeedPolicyState.Off;
const indexingPolicyContent = this.collection.indexingPolicy();
const conflictResolutionPolicy: DataModels.ConflictResolutionPolicy =
this.collection.conflictResolutionPolicy && this.collection.conflictResolutionPolicy();
const conflictResolutionPolicyMode = parseConflictResolutionMode(conflictResolutionPolicy?.mode);
const conflictResolutionPolicyPath = conflictResolutionPolicy?.conflictResolutionPath;
const conflictResolutionPolicyProcedure = parseConflictResolutionProcedure(
conflictResolutionPolicy?.conflictResolutionProcedure
);
const geospatialConfigTypeString: string =
(this.collection.geospatialConfig && this.collection.geospatialConfig()?.type) || GeospatialConfigType.Geometry;
const geoSpatialConfigType = GeospatialConfigType[geospatialConfigTypeString as keyof typeof GeospatialConfigType];
this.setState({
throughput: offerThroughput,
throughputBaseline: offerThroughput,
changeFeedPolicy: changeFeedPolicy,
changeFeedPolicyBaseline: changeFeedPolicy,
timeToLive: timeToLive,
timeToLiveBaseline: timeToLive,
timeToLiveSeconds: timeToLiveSeconds,
timeToLiveSecondsBaseline: timeToLiveSeconds,
analyticalStorageTtlSelection: analyticalStorageTtlSelection,
analyticalStorageTtlSelectionBaseline: analyticalStorageTtlSelection,
analyticalStorageTtlSeconds: analyticalStorageTtlSeconds,
analyticalStorageTtlSecondsBaseline: analyticalStorageTtlSeconds,
indexingPolicyContent: indexingPolicyContent,
indexingPolicyContentBaseline: indexingPolicyContent,
conflictResolutionPolicyMode: conflictResolutionPolicyMode,
conflictResolutionPolicyModeBaseline: conflictResolutionPolicyMode,
conflictResolutionPolicyPath: conflictResolutionPolicyPath,
conflictResolutionPolicyPathBaseline: conflictResolutionPolicyPath,
conflictResolutionPolicyProcedure: conflictResolutionPolicyProcedure,
conflictResolutionPolicyProcedureBaseline: conflictResolutionPolicyProcedure,
geospatialConfigType: geoSpatialConfigType,
geospatialConfigTypeBaseline: geoSpatialConfigType
});
};
private getTabsButtons = (): CommandButtonComponentProps[] => {
const buttons: CommandButtonComponentProps[] = [];
if (this.saveSettingsButton.isVisible()) {
const label = "Save";
buttons.push({
iconSrc: SaveIcon,
iconAlt: label,
onCommandClick: async () => await this.onSaveClick(),
commandButtonLabel: label,
ariaLabel: label,
hasPopup: false,
disabled: !this.saveSettingsButton.isEnabled()
});
}
if (this.discardSettingsChangesButton.isVisible()) {
const label = "Discard";
buttons.push({
iconSrc: DiscardIcon,
iconAlt: label,
onCommandClick: this.onRevertClick,
commandButtonLabel: label,
ariaLabel: label,
hasPopup: false,
disabled: !this.discardSettingsChangesButton.isEnabled()
});
}
return buttons;
};
private onMaxAutoPilotThroughputChange = (newThroughput: number): void =>
this.setState({ autoPilotThroughput: newThroughput });
private onThroughputChange = (newThroughput: number): void => this.setState({ throughput: newThroughput });
private onAutoPilotSelected = (isAutoPilotSelected: boolean): void =>
this.setState({ isAutoPilotSelected: isAutoPilotSelected });
private onPivotChange = (item: PivotItem): void => {
const selectedTab = SettingsV2TabTypes[item.props.itemKey as keyof typeof SettingsV2TabTypes];
this.setState({ selectedTab: selectedTab });
};
public render(): JSX.Element {
const scaleComponentProps: ScaleComponentProps = {
collection: this.collection,
container: this.container,
isFixedContainer: this.isFixedContainer,
autoPilotTiersList: this.autoPilotTiersList,
onThroughputChange: this.onThroughputChange,
throughput: this.state.throughput,
throughputBaseline: this.state.throughputBaseline,
autoPilotThroughput: this.state.autoPilotThroughput,
autoPilotThroughputBaseline: this.state.autoPilotThroughputBaseline,
isAutoPilotSelected: this.state.isAutoPilotSelected,
wasAutopilotOriginallySet: this.state.wasAutopilotOriginallySet,
onAutoPilotSelected: this.onAutoPilotSelected,
onMaxAutoPilotThroughputChange: this.onMaxAutoPilotThroughputChange,
onScaleSaveableChange: this.onScaleSaveableChange,
onScaleDiscardableChange: this.onScaleDiscardableChange,
initialNotification: this.props.settingsTab.pendingNotification()
};
const subSettingsComponentProps: SubSettingsComponentProps = {
collection: this.collection,
container: this.container,
isAnalyticalStorageEnabled: this.isAnalyticalStorageEnabled,
changeFeedPolicyVisible: this.changeFeedPolicyVisible,
timeToLive: this.state.timeToLive,
timeToLiveBaseline: this.state.timeToLiveBaseline,
onTtlChange: this.onTtlChange,
timeToLiveSeconds: this.state.timeToLiveSeconds,
timeToLiveSecondsBaseline: this.state.timeToLiveSecondsBaseline,
onTimeToLiveSecondsChange: this.onTimeToLiveSecondsChange,
geospatialConfigType: this.state.geospatialConfigType,
geospatialConfigTypeBaseline: this.state.geospatialConfigTypeBaseline,
onGeoSpatialConfigTypeChange: this.onGeoSpatialConfigTypeChange,
analyticalStorageTtlSelection: this.state.analyticalStorageTtlSelection,
analyticalStorageTtlSelectionBaseline: this.state.analyticalStorageTtlSelectionBaseline,
onAnalyticalStorageTtlSelectionChange: this.onAnalyticalStorageTtlSelectionChange,
analyticalStorageTtlSeconds: this.state.analyticalStorageTtlSeconds,
analyticalStorageTtlSecondsBaseline: this.state.analyticalStorageTtlSecondsBaseline,
onAnalyticalStorageTtlSecondsChange: this.onAnalyticalStorageTtlSecondsChange,
changeFeedPolicy: this.state.changeFeedPolicy,
changeFeedPolicyBaseline: this.state.changeFeedPolicyBaseline,
onChangeFeedPolicyChange: this.onChangeFeedPolicyChange,
onSubSettingsSaveableChange: this.onSubSettingsSaveableChange,
onSubSettingsDiscardableChange: this.onSubSettingsDiscardableChange
};
const indexingPolicyComponentProps: IndexingPolicyComponentProps = {
shouldDiscardIndexingPolicy: this.state.shouldDiscardIndexingPolicy,
resetShouldDiscardIndexingPolicy: this.resetShouldDiscardIndexingPolicy,
indexingPolicyContent: this.state.indexingPolicyContent,
indexingPolicyContentBaseline: this.state.indexingPolicyContentBaseline,
onIndexingPolicyElementFocusChange: this.onIndexingPolicyElementFocusChange,
onIndexingPolicyContentChange: this.onIndexingPolicyContentChange,
logIndexingPolicySuccessMessage: this.logIndexingPolicySuccessMessage,
onIndexingPolicyDirtyChange: this.onIndexingPolicyDirtyChange
};
const conflictResolutionPolicyComponentProps: ConflictResolutionComponentProps = {
collection: this.collection,
container: this.container,
conflictResolutionPolicyMode: this.state.conflictResolutionPolicyMode,
conflictResolutionPolicyModeBaseline: this.state.conflictResolutionPolicyModeBaseline,
onConflictResolutionPolicyModeChange: this.onConflictResolutionPolicyModeChange,
conflictResolutionPolicyPath: this.state.conflictResolutionPolicyPath,
conflictResolutionPolicyPathBaseline: this.state.conflictResolutionPolicyPathBaseline,
onConflictResolutionPolicyPathChange: this.onConflictResolutionPolicyPathChange,
conflictResolutionPolicyProcedure: this.state.conflictResolutionPolicyProcedure,
conflictResolutionPolicyProcedureBaseline: this.state.conflictResolutionPolicyProcedureBaseline,
onConflictResolutionPolicyProcedureChange: this.onConflictResolutionPolicyProcedureChange,
onConflictResolutionDirtyChange: this.onConflictResolutionDirtyChange
};
const tabs: SettingsV2TabInfo[] = [];
if (!hasDatabaseSharedThroughput(this.collection)) {
tabs.push({
tab: SettingsV2TabTypes.ScaleTab,
content: <ScaleComponent {...scaleComponentProps} />
});
}
tabs.push({
tab: SettingsV2TabTypes.SubSettingsTab,
content: <SubSettingsComponent {...subSettingsComponentProps} />
});
if (this.shouldShowIndexingPolicyEditor) {
tabs.push({
tab: SettingsV2TabTypes.IndexingPolicyTab,
content: <IndexingPolicyComponent {...indexingPolicyComponentProps} />
});
}
if (this.hasConflictResolution()) {
tabs.push({
tab: SettingsV2TabTypes.ConflictResolutionTab,
content: <ConflictResolutionComponent {...conflictResolutionPolicyComponentProps} />
});
}
const pivotProps: IPivotProps = {
onLinkClick: this.onPivotChange,
selectedKey: SettingsV2TabTypes[this.state.selectedTab]
};
const pivotItems = tabs.map(tab => {
const pivotItemProps: IPivotItemProps = {
itemKey: SettingsV2TabTypes[tab.tab],
style: { marginTop: 20 },
headerText: getTabTitle(tab.tab)
};
return (
<PivotItem key={pivotItemProps.itemKey} {...pivotItemProps}>
{tab.content}
</PivotItem>
);
});
return (
<div className="settingsV2MainContainer">
{this.shouldShowKeyspaceSharedThroughputMessage() && (
<div>This table shared throughput is configured at the keyspace</div>
)}
<div className="settingsV2TabsContainer">
<Pivot {...pivotProps}>{pivotItems}</Pivot>
</div>
</div>
);
}
}

View File

@ -0,0 +1,20 @@
import ko from "knockout";
import * as React from "react";
import { ReactAdapter } from "../../../Bindings/ReactBindingHandler";
import { SettingsComponent, SettingsComponentProps } from "./SettingsComponent";
export class SettingsComponentAdapter implements ReactAdapter {
public parameters: ko.Observable<number>;
constructor(private props: SettingsComponentProps) {
this.parameters = ko.observable<number>(Date.now());
}
public renderComponent(): JSX.Element {
return <SettingsComponent {...this.props} />;
}
public triggerRender(): void {
window.requestAnimationFrame(() => this.parameters(Date.now()));
}
}

View File

@ -0,0 +1,58 @@
import { shallow } from "enzyme";
import React from "react";
import {
getAutoPilotV3SpendElement,
getEstimatedSpendElement,
getEstimatedAutoscaleSpendElement,
manualToAutoscaleDisclaimerElement,
ttlWarning,
indexingPolicyTTLWarningMessage,
updateThroughputBeyondLimitWarningMessage,
updateThroughputDelayedApplyWarningMessage,
getThroughputApplyDelayedMessage,
getThroughputApplyShortDelayMessage,
getThroughputApplyLongDelayMessage,
getToolTipContainer,
conflictResolutionCustomToolTip,
changeFeedPolicyToolTip,
conflictResolutionLwwTooltip
} from "./SettingsRenderUtils";
class SettingsRenderUtilsTestComponent extends React.Component {
public render(): JSX.Element {
return (
<>
{getAutoPilotV3SpendElement(1000, false)}
{getAutoPilotV3SpendElement(undefined, false)}
{getAutoPilotV3SpendElement(1000, true)}
{getAutoPilotV3SpendElement(undefined, true)}
{getEstimatedSpendElement(1000, "mooncake", 2, false, true)}
{getEstimatedAutoscaleSpendElement(1000, "mooncake", 2, false)}
{manualToAutoscaleDisclaimerElement}
{ttlWarning}
{indexingPolicyTTLWarningMessage}
{updateThroughputBeyondLimitWarningMessage}
{updateThroughputDelayedApplyWarningMessage}
{getThroughputApplyDelayedMessage(false, 1000, "RU/s", "sampleDb", "sampleCollection", 2000)}
{getThroughputApplyShortDelayMessage(false, 1000, "RU/s", "sampleDb", "sampleCollection", 2000)}
{getThroughputApplyLongDelayMessage(false, 1000, "RU/s", "sampleDb", "sampleCollection", 2000)}
{getToolTipContainer(<span>Sample Text</span>)}
{conflictResolutionLwwTooltip}
{conflictResolutionCustomToolTip}
{changeFeedPolicyToolTip}
</>
);
}
}
describe("SettingsUtils functions", () => {
it("render", () => {
const wrapper = shallow(<SettingsRenderUtilsTestComponent />);
expect(wrapper).toMatchSnapshot();
});
});

View File

@ -0,0 +1,349 @@
import * as React from "react";
import * as AutoPilotUtils from "../../../Utils/AutoPilotUtils";
import { AutopilotDocumentation, hoursInAMonth } from "../../../Shared/Constants";
import { Urls, StyleConstants } from "../../../Common/Constants";
import {
computeAutoscaleUsagePriceHourly,
getPriceCurrency,
getCurrencySign,
getAutoscalePricePerRu,
getMultimasterMultiplier,
computeRUUsagePriceHourly,
getPricePerRu,
calculateEstimateNumber
} from "../../../Utils/PricingUtils";
import {
ITextFieldStyles,
ICheckboxStyles,
IStackProps,
IStackTokens,
IChoiceGroupStyles,
Link,
Text,
IMessageBarStyles,
ITextStyles
} from "office-ui-fabric-react";
import { isDirtyTypes, isDirty } from "./SettingsUtils";
const infoAndToolTipTextStyle: ITextStyles = { root: { fontSize: 12 } };
export const spendAckCheckBoxStyle: ICheckboxStyles = {
label: {
margin: 0,
padding: "2 0 2 0"
},
text: {
fontSize: 12
}
};
export const subComponentStackProps: Partial<IStackProps> = {
tokens: { childrenGap: 20 }
};
export const titleAndInputStackProps: Partial<IStackProps> = {
tokens: { childrenGap: 5 }
};
export const checkBoxAndInputStackProps: Partial<IStackProps> = {
tokens: { childrenGap: 10 }
};
export const toolTipLabelStackTokens: IStackTokens = {
childrenGap: 6
};
export const messageBarStyles: Partial<IMessageBarStyles> = { root: { marginTop: "5px" } };
export const throughputUnit = "RU/s";
export const getAutoPilotV3SpendElement = (
maxAutoPilotThroughputSet: number,
isDatabaseThroughput: boolean,
requestUnitsUsageCostElement?: JSX.Element
): JSX.Element => {
if (!maxAutoPilotThroughputSet) {
return <></>;
}
const resource: string = isDatabaseThroughput ? "database" : "container";
return (
<>
<Text>
Your {resource} throughput will automatically scale from{" "}
<b>
{AutoPilotUtils.getMinRUsBasedOnUserInput(maxAutoPilotThroughputSet)} RU/s (10% of max RU/s) -{" "}
{maxAutoPilotThroughputSet} RU/s
</b>{" "}
based on usage.
<br />
</Text>
{requestUnitsUsageCostElement}
<Text>
After the first {AutoPilotUtils.getStorageBasedOnUserInput(maxAutoPilotThroughputSet)} GB of data stored, the
max RU/s will be automatically upgraded based on the new storage value.
<Link href={AutopilotDocumentation.Url} target="_blank">
{" "}
Learn more
</Link>
.
</Text>
</>
);
};
export const getEstimatedAutoscaleSpendElement = (
throughput: number,
serverId: string,
regions: number,
multimaster: boolean
): JSX.Element => {
const hourlyPrice: number = computeAutoscaleUsagePriceHourly(serverId, throughput, regions, multimaster);
const monthlyPrice: number = hourlyPrice * hoursInAMonth;
const currency: string = getPriceCurrency(serverId);
const currencySign: string = getCurrencySign(serverId);
const pricePerRu =
getAutoscalePricePerRu(serverId, getMultimasterMultiplier(regions, multimaster)) *
getMultimasterMultiplier(regions, multimaster);
return (
<Text id="autoscaleSpendElement">
Estimated monthly cost ({currency}) is{" "}
<b>
{currencySign}
{calculateEstimateNumber(monthlyPrice / 10)}
{` - `}
{currencySign}
{calculateEstimateNumber(monthlyPrice)}{" "}
</b>
({"regions: "} {regions}, {throughput / 10} - {throughput} RU/s, {currencySign}
{pricePerRu}/RU)
</Text>
);
};
export const getEstimatedSpendElement = (
throughput: number,
serverId: string,
regions: number,
multimaster: boolean,
rupmEnabled: boolean
): JSX.Element => {
const hourlyPrice: number = computeRUUsagePriceHourly(serverId, rupmEnabled, throughput, regions, multimaster);
const dailyPrice: number = hourlyPrice * 24;
const monthlyPrice: number = hourlyPrice * hoursInAMonth;
const currency: string = getPriceCurrency(serverId);
const currencySign: string = getCurrencySign(serverId);
const pricePerRu = getPricePerRu(serverId) * getMultimasterMultiplier(regions, multimaster);
return (
<Text id="throughputSpendElement">
Estimated cost ({currency}):{" "}
<b>
{currencySign}
{calculateEstimateNumber(hourlyPrice)} hourly {` / `}
{currencySign}
{calculateEstimateNumber(dailyPrice)} daily {` / `}
{currencySign}
{calculateEstimateNumber(monthlyPrice)} monthly{" "}
</b>
({"regions: "} {regions}, {throughput}RU/s, {currencySign}
{pricePerRu}/RU)
</Text>
);
};
export const manualToAutoscaleDisclaimerElement: JSX.Element = (
<Text styles={infoAndToolTipTextStyle} id="manualToAutoscaleDisclaimerElement">
The starting autoscale max RU/s will be determined by the system, based on the current manual throughput settings
and storage of your resource. After autoscale has been enabled, you can change the max RU/s.{" "}
<a href={Urls.autoscaleMigration}>Learn more</a>
</Text>
);
export const ttlWarning: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
The system will automatically delete items based on the TTL value (in seconds) you provide, without needing a delete
operation explicitly issued by a client application. For more information see,{" "}
<Link target="_blank" href="https://aka.ms/cosmos-db-ttl">
Time to Live (TTL) in Azure Cosmos DB
</Link>
.
</Text>
);
export const indexingPolicyTTLWarningMessage: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
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>
);
export const updateThroughputBeyondLimitWarningMessage: JSX.Element = (
<Text styles={infoAndToolTipTextStyle} id="updateThroughputBeyondLimitWarningMessage">
You are about to request an increase in throughput beyond the pre-allocated capacity. The service will scale out and
increase throughput for the selected container. This operation will take 1-3 business days to complete. You can
track the status of this request in Notifications.
</Text>
);
export const updateThroughputDelayedApplyWarningMessage: JSX.Element = (
<Text styles={infoAndToolTipTextStyle} id="updateThroughputDelayedApplyWarningMessage">
You are about to request an increase in throughput beyond the pre-allocated capacity. This operation will take some
time to complete.
</Text>
);
const getCurrentThroughput = (
isAutoscale: boolean,
throughput: number,
throughputUnit: string,
targetThroughput?: number
): string => {
if (targetThroughput) {
if (throughput) {
return isAutoscale
? `, Current autoscale throughput: ${Math.round(
throughput / 10
)} - ${throughput} ${throughputUnit}, Target autoscale throughput: ${Math.round(
targetThroughput / 10
)} - ${targetThroughput} ${throughputUnit}`
: `, Current manual throughput: ${throughput} ${throughputUnit}, Target manual throughput: ${targetThroughput}`;
} else {
return isAutoscale
? `, Target autoscale throughput: ${Math.round(targetThroughput / 10)} - ${targetThroughput} ${throughputUnit}`
: `, Target manual throughput: ${targetThroughput} ${throughputUnit}`;
}
}
if (!targetThroughput && throughput) {
return isAutoscale
? `, Current autoscale throughput: ${Math.round(throughput / 10)} - ${throughput} ${throughputUnit}`
: `, Current manual throughput: ${throughput} ${throughputUnit}`;
}
return "";
};
export const getThroughputApplyDelayedMessage = (
isAutoscale: boolean,
throughput: number,
throughputUnit: string,
databaseName: string,
collectionName: string,
requestedThroughput: number
): JSX.Element => (
<Text styles={infoAndToolTipTextStyle}>
The request to increase the throughput has successfully been submitted. This operation will take 1-3 business days
to complete. View the latest status in Notifications.
<br />
Database: {databaseName}, Container: {collectionName}{" "}
{getCurrentThroughput(isAutoscale, throughput, throughputUnit, requestedThroughput)}
</Text>
);
export const getThroughputApplyShortDelayMessage = (
isAutoscale: boolean,
throughput: number,
throughputUnit: string,
databaseName: string,
collectionName: string,
targetThroughput: number
): JSX.Element => (
<Text styles={infoAndToolTipTextStyle} id="throughputApplyShortDelayMessage">
A request to increase the throughput is currently in progress. This operation will take some time to complete.
<br />
Database: {databaseName}, Container: {collectionName}{" "}
{getCurrentThroughput(isAutoscale, throughput, throughputUnit, targetThroughput)}
</Text>
);
export const getThroughputApplyLongDelayMessage = (
isAutoscale: boolean,
throughput: number,
throughputUnit: string,
databaseName: string,
collectionName: string,
requestedThroughput: number
): JSX.Element => (
<Text styles={infoAndToolTipTextStyle} id="throughputApplyLongDelayMessage">
A request to increase the throughput is currently in progress. This operation will take 1-3 business days to
complete. View the latest status in Notifications.
<br />
Database: {databaseName}, Container: {collectionName}{" "}
{getCurrentThroughput(isAutoscale, throughput, throughputUnit, requestedThroughput)}
</Text>
);
export const getToolTipContainer = (content: string | JSX.Element): JSX.Element =>
content ? <Text styles={infoAndToolTipTextStyle}>{content}</Text> : undefined;
export const conflictResolutionLwwTooltip: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
Gets or sets the name of a integer property in your documents which is used for the Last Write Wins (LWW) based
conflict resolution scheme. By default, the system uses the system defined timestamp property, _ts to decide the
winner for the conflicting versions of the document. Specify your own integer property if you want to override the
default timestamp based conflict resolution.
</Text>
);
export const conflictResolutionCustomToolTip: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
Gets or sets the name of a stored procedure (aka merge procedure) for resolving the conflicts. You can write
application defined logic to determine the winner of the conflicting versions of a document. The stored procedure
will get executed transactionally, exactly once, on the server side. If you do not provide a stored procedure, the
conflicts will be populated in the
<Link className="linkDarkBackground" href="https://aka.ms/dataexplorerconflics" target="_blank">
{` conflicts feed`}
</Link>
. You can update/re-register the stored procedure at any time.
</Text>
);
export const changeFeedPolicyToolTip: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
Enable change feed log retention policy to retain last 10 minutes of history for items in the container by default.
To support this, the request unit (RU) charge for this container will be multiplied by a factor of two for writes.
Reads are unaffected.
</Text>
);
export const getTextFieldStyles = (current: isDirtyTypes, baseline: isDirtyTypes): Partial<ITextFieldStyles> => ({
fieldGroup: {
height: 25,
width: 300,
borderColor: isDirty(current, baseline) ? StyleConstants.Dirty : "",
selectors: {
":disabled": {
backgroundColor: StyleConstants.BaseMedium,
borderColor: StyleConstants.BaseMediumHigh
}
}
}
});
export const getChoiceGroupStyles = (current: isDirtyTypes, baseline: isDirtyTypes): Partial<IChoiceGroupStyles> => ({
flexContainer: [
{
selectors: {
".ms-ChoiceField-field.is-checked::before": {
borderColor: isDirty(current, baseline) ? StyleConstants.Dirty : ""
},
".ms-ChoiceField-field.is-checked::after": {
borderColor: isDirty(current, baseline) ? StyleConstants.Dirty : ""
},
".ms-ChoiceField-wrapper label": {
whiteSpace: "nowrap",
fontSize: 14,
fontFamily: StyleConstants.DataExplorerFont,
padding: "2px 5px"
}
}
}
]
});

View File

@ -0,0 +1,54 @@
import { shallow } from "enzyme";
import React from "react";
import { ConflictResolutionComponentProps, ConflictResolutionComponent } from "./ConflictResolutionComponent";
import { container, collection } from "../TestUtils";
import * as DataModels from "../../../../Contracts/DataModels";
describe("ConflictResolutionComponent", () => {
const baseProps: ConflictResolutionComponentProps = {
collection: collection,
container: container,
conflictResolutionPolicyMode: DataModels.ConflictResolutionMode.Custom,
conflictResolutionPolicyModeBaseline: DataModels.ConflictResolutionMode.Custom,
onConflictResolutionPolicyModeChange: () => {
return;
},
conflictResolutionPolicyPath: "",
conflictResolutionPolicyPathBaseline: "",
onConflictResolutionPolicyPathChange: () => {
return;
},
conflictResolutionPolicyProcedure: "",
conflictResolutionPolicyProcedureBaseline: "",
onConflictResolutionPolicyProcedureChange: () => {
return;
},
onConflictResolutionDirtyChange: () => {
return;
}
};
it("Sproc text field displayed", () => {
const wrapper = shallow(<ConflictResolutionComponent {...baseProps} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#conflictResolutionCustomTextField")).toEqual(true);
expect(wrapper.exists("#conflictResolutionLwwTextField")).toEqual(false);
});
it("Path text field displayed", () => {
const props = { ...baseProps, conflictResolutionPolicyMode: DataModels.ConflictResolutionMode.LastWriterWins };
const wrapper = shallow(<ConflictResolutionComponent {...props} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#conflictResolutionCustomTextField")).toEqual(false);
expect(wrapper.exists("#conflictResolutionLwwTextField")).toEqual(true);
});
it("conflict resolution policy dirty is set", () => {
let conflictRsolutionComponent = new ConflictResolutionComponent(baseProps);
expect(conflictRsolutionComponent.IsComponentDirty()).toEqual(false);
const newProps = { ...baseProps, conflictResolutionPolicyMode: DataModels.ConflictResolutionMode.LastWriterWins };
conflictRsolutionComponent = new ConflictResolutionComponent(newProps);
expect(conflictRsolutionComponent.IsComponentDirty()).toEqual(true);
});
});

View File

@ -0,0 +1,142 @@
import * as React from "react";
import * as ViewModels from "../../../../Contracts/ViewModels";
import * as DataModels from "../../../../Contracts/DataModels";
import Explorer from "../../../Explorer";
import {
getTextFieldStyles,
conflictResolutionLwwTooltip,
conflictResolutionCustomToolTip,
subComponentStackProps,
getChoiceGroupStyles
} from "../SettingsRenderUtils";
import { TextField, ITextFieldProps, Stack, IChoiceGroupOption, ChoiceGroup } from "office-ui-fabric-react";
import { ToolTipLabelComponent } from "./ToolTipLabelComponent";
import { isDirty } from "../SettingsUtils";
export interface ConflictResolutionComponentProps {
collection: ViewModels.Collection;
container: Explorer;
conflictResolutionPolicyMode: DataModels.ConflictResolutionMode;
conflictResolutionPolicyModeBaseline: DataModels.ConflictResolutionMode;
onConflictResolutionPolicyModeChange: (
event?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
) => void;
conflictResolutionPolicyPath: string;
conflictResolutionPolicyPathBaseline: string;
onConflictResolutionPolicyPathChange: (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
) => void;
conflictResolutionPolicyProcedure: string;
conflictResolutionPolicyProcedureBaseline: string;
onConflictResolutionPolicyProcedureChange: (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
) => void;
onConflictResolutionDirtyChange: (isConflictResolutionDirty: boolean) => void;
}
export class ConflictResolutionComponent extends React.Component<ConflictResolutionComponentProps> {
private shouldCheckComponentIsDirty = true;
private conflictResolutionChoiceGroupOptions: IChoiceGroupOption[] = [
{
key: DataModels.ConflictResolutionMode.LastWriterWins,
text: "Last Write Wins (default)"
},
{ key: DataModels.ConflictResolutionMode.Custom, text: "Merge Procedure (custom)" }
];
componentDidMount(): void {
this.onComponentUpdate();
}
componentDidUpdate(): void {
this.onComponentUpdate();
}
private onComponentUpdate = (): void => {
if (!this.shouldCheckComponentIsDirty) {
this.shouldCheckComponentIsDirty = true;
return;
}
this.props.onConflictResolutionDirtyChange(this.IsComponentDirty());
this.shouldCheckComponentIsDirty = false;
};
public IsComponentDirty = (): boolean => {
if (
isDirty(this.props.conflictResolutionPolicyMode, this.props.conflictResolutionPolicyModeBaseline) ||
isDirty(this.props.conflictResolutionPolicyPath, this.props.conflictResolutionPolicyPathBaseline) ||
isDirty(this.props.conflictResolutionPolicyProcedure, this.props.conflictResolutionPolicyProcedureBaseline)
) {
return true;
}
return false;
};
private getConflictResolutionModeComponent = (): JSX.Element => (
<ChoiceGroup
label="Mode"
selectedKey={this.props.conflictResolutionPolicyMode}
options={this.conflictResolutionChoiceGroupOptions}
onChange={this.props.onConflictResolutionPolicyModeChange}
styles={getChoiceGroupStyles(
this.props.conflictResolutionPolicyMode,
this.props.conflictResolutionPolicyModeBaseline
)}
/>
);
private onRenderLwwComponentTextField = (props: ITextFieldProps) => (
<ToolTipLabelComponent label={props.label} toolTipElement={conflictResolutionLwwTooltip} />
);
private getConflictResolutionLWWComponent = (): JSX.Element => (
<TextField
id="conflictResolutionLwwTextField"
label={"Conflict Resolver Property"}
onRenderLabel={this.onRenderLwwComponentTextField}
styles={getTextFieldStyles(
this.props.conflictResolutionPolicyPath,
this.props.conflictResolutionPolicyPathBaseline
)}
value={this.props.conflictResolutionPolicyPath}
onChange={this.props.onConflictResolutionPolicyPathChange}
/>
);
private onRenderCustomComponentTextField = (props: ITextFieldProps) => (
<ToolTipLabelComponent label={props.label} toolTipElement={conflictResolutionCustomToolTip} />
);
private getConflictResolutionCustomComponent = (): JSX.Element => (
<TextField
id="conflictResolutionCustomTextField"
label="Stored procedure"
onRenderLabel={this.onRenderCustomComponentTextField}
styles={getTextFieldStyles(
this.props.conflictResolutionPolicyProcedure,
this.props.conflictResolutionPolicyProcedureBaseline
)}
value={this.props.conflictResolutionPolicyProcedure}
onChange={this.props.onConflictResolutionPolicyProcedureChange}
/>
);
public render(): JSX.Element {
return (
<Stack {...subComponentStackProps}>
{this.getConflictResolutionModeComponent()}
{this.props.conflictResolutionPolicyMode === DataModels.ConflictResolutionMode.LastWriterWins &&
this.getConflictResolutionLWWComponent()}
{this.props.conflictResolutionPolicyMode === DataModels.ConflictResolutionMode.Custom &&
this.getConflictResolutionCustomComponent()}
</Stack>
);
}
}

View File

@ -0,0 +1,59 @@
import { shallow } from "enzyme";
import React from "react";
import { IndexingPolicyComponent, IndexingPolicyComponentProps } from "./IndexingPolicyComponent";
import * as DataModels from "../../../../Contracts/DataModels";
describe("IndexingPolicyComponent", () => {
const initialIndexingPolicyContent: DataModels.IndexingPolicy = {
automatic: false,
indexingMode: "",
includedPaths: [],
excludedPaths: []
};
const baseProps: IndexingPolicyComponentProps = {
shouldDiscardIndexingPolicy: false,
resetShouldDiscardIndexingPolicy: () => {
return;
},
indexingPolicyContent: initialIndexingPolicyContent,
indexingPolicyContentBaseline: initialIndexingPolicyContent,
onIndexingPolicyElementFocusChange: () => {
return;
},
onIndexingPolicyContentChange: () => {
return;
},
logIndexingPolicySuccessMessage: () => {
return;
},
onIndexingPolicyDirtyChange: () => {
return;
}
};
it("renders", () => {
const wrapper = shallow(<IndexingPolicyComponent {...baseProps} />);
expect(wrapper).toMatchSnapshot();
});
it("indexing policy is reset", () => {
const wrapper = shallow(<IndexingPolicyComponent {...baseProps} />);
const indexingPolicyComponentInstance = wrapper.instance() as IndexingPolicyComponent;
const resetIndexingPolicyEditorMockFn = jest.fn();
indexingPolicyComponentInstance.resetIndexingPolicyEditor = resetIndexingPolicyEditorMockFn;
wrapper.setProps({ shouldDiscardIndexingPolicy: true });
wrapper.update();
expect(resetIndexingPolicyEditorMockFn.mock.calls.length).toEqual(1);
});
it("conflict resolution policy dirty is set", () => {
let indexingPolicyComponent = new IndexingPolicyComponent(baseProps);
expect(indexingPolicyComponent.IsComponentDirty()).toEqual(false);
const newProps = { ...baseProps, indexingPolicyContent: undefined as DataModels.IndexingPolicy };
indexingPolicyComponent = new IndexingPolicyComponent(newProps);
expect(indexingPolicyComponent.IsComponentDirty()).toEqual(true);
});
});

View File

@ -0,0 +1,121 @@
import * as React from "react";
import * as DataModels from "../../../../Contracts/DataModels";
import * as monaco from "monaco-editor";
import { isDirty } from "../SettingsUtils";
import { MessageBar, MessageBarType, Stack } from "office-ui-fabric-react";
import { indexingPolicyTTLWarningMessage, titleAndInputStackProps } from "../SettingsRenderUtils";
export interface IndexingPolicyComponentProps {
shouldDiscardIndexingPolicy: boolean;
resetShouldDiscardIndexingPolicy: () => void;
indexingPolicyContent: DataModels.IndexingPolicy;
indexingPolicyContentBaseline: DataModels.IndexingPolicy;
onIndexingPolicyElementFocusChange: (indexingPolicyContentFocussed: boolean) => void;
onIndexingPolicyContentChange: (newIndexingPolicy: DataModels.IndexingPolicy) => void;
logIndexingPolicySuccessMessage: () => void;
onIndexingPolicyDirtyChange: (isIndexingPolicyDirty: boolean) => void;
}
interface IndexingPolicyComponentState {
indexingPolicyContentIsValid: boolean;
}
export class IndexingPolicyComponent extends React.Component<
IndexingPolicyComponentProps,
IndexingPolicyComponentState
> {
private shouldCheckComponentIsDirty = true;
private indexingPolicyDiv = React.createRef<HTMLDivElement>();
private indexingPolicyEditor: monaco.editor.IStandaloneCodeEditor;
constructor(props: IndexingPolicyComponentProps) {
super(props);
this.state = {
indexingPolicyContentIsValid: true
};
}
componentDidUpdate(): void {
if (this.props.shouldDiscardIndexingPolicy) {
this.resetIndexingPolicyEditor();
this.props.resetShouldDiscardIndexingPolicy();
}
this.onComponentUpdate();
}
componentDidMount(): void {
this.resetIndexingPolicyEditor();
this.onComponentUpdate();
}
public resetIndexingPolicyEditor = (): void => {
if (!this.indexingPolicyEditor) {
this.createIndexingPolicyEditor();
} else {
const indexingPolicyEditorModel = this.indexingPolicyEditor.getModel();
const value: string = JSON.stringify(this.props.indexingPolicyContent, undefined, 4);
indexingPolicyEditorModel.setValue(value);
}
this.onComponentUpdate();
};
private onComponentUpdate = (): void => {
if (!this.shouldCheckComponentIsDirty) {
this.shouldCheckComponentIsDirty = true;
return;
}
this.props.onIndexingPolicyDirtyChange(this.IsComponentDirty());
this.shouldCheckComponentIsDirty = false;
};
public IsComponentDirty = (): boolean => {
if (
isDirty(this.props.indexingPolicyContent, this.props.indexingPolicyContentBaseline) &&
this.state.indexingPolicyContentIsValid
) {
return true;
}
return false;
};
private createIndexingPolicyEditor = (): void => {
const value: string = JSON.stringify(this.props.indexingPolicyContent, undefined, 4);
this.indexingPolicyEditor = monaco.editor.create(this.indexingPolicyDiv.current, {
value: value,
language: "json",
readOnly: false,
ariaLabel: "Indexing Policy"
});
if (this.indexingPolicyEditor) {
this.indexingPolicyEditor.onDidFocusEditorText(() => this.props.onIndexingPolicyElementFocusChange(true));
this.indexingPolicyEditor.onDidBlurEditorText(() => this.props.onIndexingPolicyElementFocusChange(false));
const indexingPolicyEditorModel = this.indexingPolicyEditor.getModel();
indexingPolicyEditorModel.onDidChangeContent(this.onEditorContentChange.bind(this));
this.props.logIndexingPolicySuccessMessage();
}
};
private onEditorContentChange = (): void => {
const indexingPolicyEditorModel = this.indexingPolicyEditor.getModel();
try {
const newIndexingPolicyContent = JSON.parse(indexingPolicyEditorModel.getValue()) as DataModels.IndexingPolicy;
this.props.onIndexingPolicyContentChange(newIndexingPolicyContent);
this.setState({ indexingPolicyContentIsValid: true });
} catch (e) {
this.setState({ indexingPolicyContentIsValid: false });
}
};
public render(): JSX.Element {
return (
<Stack {...titleAndInputStackProps}>
{isDirty(this.props.indexingPolicyContent, this.props.indexingPolicyContentBaseline) && (
<MessageBar messageBarType={MessageBarType.warning}>{indexingPolicyTTLWarningMessage}</MessageBar>
)}
<div className="settingsV2IndexingPolicyEditor" tabIndex={0} ref={this.indexingPolicyDiv}></div>
</Stack>
);
}
}

View File

@ -0,0 +1,160 @@
import { shallow } from "enzyme";
import React from "react";
import { ScaleComponent, ScaleComponentProps } from "./ScaleComponent";
import { container, collection } from "../TestUtils";
import { ThroughputInputAutoPilotV3Component } from "./ThroughputInputComponents/ThroughputInputAutoPilotV3Component";
import Explorer from "../../../Explorer";
import * as Constants from "../../../../Common/Constants";
import { PlatformType } from "../../../../PlatformType";
import * as DataModels from "../../../../Contracts/DataModels";
import { throughputUnit } from "../SettingsRenderUtils";
import * as SharedConstants from "../../../../Shared/Constants";
import ko from "knockout";
describe("ScaleComponent", () => {
const nonNationalCloudContainer = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
nonNationalCloudContainer.getPlatformType = () => PlatformType.Portal;
nonNationalCloudContainer.isRunningOnNationalCloud = () => false;
const targetThroughput = 6000;
const baseProps: ScaleComponentProps = {
collection: collection,
container: container,
isFixedContainer: false,
autoPilotTiersList: [],
onThroughputChange: () => {
return;
},
throughput: 1000,
throughputBaseline: 1000,
autoPilotThroughput: 4000,
autoPilotThroughputBaseline: 4000,
isAutoPilotSelected: false,
wasAutopilotOriginallySet: true,
onAutoPilotSelected: () => false,
onMaxAutoPilotThroughputChange: () => {
return;
},
onScaleSaveableChange: () => {
return;
},
onScaleDiscardableChange: () => {
return;
},
initialNotification: {
description: `Throughput update for ${targetThroughput} ${throughputUnit}`
} as DataModels.Notification
};
it("renders with correct intiial notification", () => {
let wrapper = shallow(<ScaleComponent {...baseProps} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists(ThroughputInputAutoPilotV3Component)).toEqual(true);
expect(wrapper.exists("#throughputApplyLongDelayMessage")).toEqual(true);
expect(wrapper.exists("#throughputApplyShortDelayMessage")).toEqual(false);
expect(wrapper.find("#throughputApplyLongDelayMessage").html()).toContain(targetThroughput);
const newCollection = { ...collection };
const maxThroughput = 5000;
const targetMaxThroughput = 50000;
newCollection.offer = ko.observable({
content: {
offerAutopilotSettings: {
maxThroughput: maxThroughput,
targetMaxThroughput: targetMaxThroughput
}
},
headers: { "x-ms-offer-replace-pending": true }
} as DataModels.OfferWithHeaders);
const newProps = {
...baseProps,
initialNotification: undefined as DataModels.Notification,
collection: newCollection
};
wrapper = shallow(<ScaleComponent {...newProps} />);
expect(wrapper.exists("#throughputApplyShortDelayMessage")).toEqual(true);
expect(wrapper.exists("#throughputApplyLongDelayMessage")).toEqual(false);
expect(wrapper.find("#throughputApplyShortDelayMessage").html()).toContain(maxThroughput);
expect(wrapper.find("#throughputApplyShortDelayMessage").html()).toContain(targetMaxThroughput);
});
it("autoScale disabled", () => {
const scaleComponent = new ScaleComponent(baseProps);
expect(scaleComponent.isAutoScaleEnabled()).toEqual(false);
});
it("autoScale enabled", () => {
const newContainer = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
newContainer.databaseAccount({
id: undefined,
name: undefined,
location: undefined,
type: undefined,
kind: "documentdb",
tags: undefined,
properties: {
documentEndpoint: undefined,
tableEndpoint: undefined,
gremlinEndpoint: undefined,
cassandraEndpoint: undefined,
capabilities: [
{
name: Constants.CapabilityNames.EnableAutoScale.toLowerCase(),
description: undefined
}
]
}
});
const props = { ...baseProps, container: newContainer };
const scaleComponent = new ScaleComponent(props);
expect(scaleComponent.isAutoScaleEnabled()).toEqual(true);
});
it("getMaxRUThroughputInputLimit", () => {
const scaleComponent = new ScaleComponent(baseProps);
expect(scaleComponent.getMaxRUThroughputInputLimit()).toEqual(40000);
});
it("getThroughputTitle", () => {
let scaleComponent = new ScaleComponent(baseProps);
expect(scaleComponent.getThroughputTitle()).toEqual("Throughput (6,000 - 40,000 RU/s)");
let newProps = { ...baseProps, container: nonNationalCloudContainer };
scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.getThroughputTitle()).toEqual("Throughput (6,000 - unlimited RU/s)");
newProps = { ...baseProps, isAutoPilotSelected: true };
scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.getThroughputTitle()).toEqual("Throughput (autoscale)");
});
it("canThroughputExceedMaximumValue", () => {
let scaleComponent = new ScaleComponent(baseProps);
expect(scaleComponent.canThroughputExceedMaximumValue()).toEqual(false);
const newProps = { ...baseProps, container: nonNationalCloudContainer };
scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.canThroughputExceedMaximumValue()).toEqual(true);
});
it("getThroughputWarningMessage", () => {
const throughputBeyondLimit = SharedConstants.CollectionCreation.DefaultCollectionRUs1Million + 1000;
const throughputBeyondMaxRus = SharedConstants.CollectionCreation.DefaultCollectionRUs1Million - 1000;
const newProps = { ...baseProps, container: nonNationalCloudContainer, throughput: throughputBeyondLimit };
let scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.getThroughputWarningMessage().props.id).toEqual("updateThroughputBeyondLimitWarningMessage");
newProps.throughput = throughputBeyondMaxRus;
scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.getThroughputWarningMessage().props.id).toEqual("updateThroughputDelayedApplyWarningMessage");
});
});

View File

@ -0,0 +1,235 @@
import * as React from "react";
import * as Constants from "../../../../Common/Constants";
import { ThroughputInputAutoPilotV3Component } from "./ThroughputInputComponents/ThroughputInputAutoPilotV3Component";
import * as ViewModels from "../../../../Contracts/ViewModels";
import * as DataModels from "../../../../Contracts/DataModels";
import * as SharedConstants from "../../../../Shared/Constants";
import Explorer from "../../../Explorer";
import { PlatformType } from "../../../../PlatformType";
import {
getTextFieldStyles,
subComponentStackProps,
titleAndInputStackProps,
throughputUnit,
getThroughputApplyLongDelayMessage,
getThroughputApplyShortDelayMessage,
updateThroughputBeyondLimitWarningMessage,
updateThroughputDelayedApplyWarningMessage
} from "../SettingsRenderUtils";
import { getMaxRUs, getMinRUs, hasDatabaseSharedThroughput } from "../SettingsUtils";
import * as AutoPilotUtils from "../../../../Utils/AutoPilotUtils";
import { Text, TextField, Stack, Label, MessageBar, MessageBarType } from "office-ui-fabric-react";
export interface ScaleComponentProps {
collection: ViewModels.Collection;
container: Explorer;
isFixedContainer: boolean;
autoPilotTiersList: ViewModels.DropdownOption<DataModels.AutopilotTier>[];
onThroughputChange: (newThroughput: number) => void;
throughput: number;
throughputBaseline: number;
autoPilotThroughput: number;
autoPilotThroughputBaseline: number;
isAutoPilotSelected: boolean;
wasAutopilotOriginallySet: boolean;
onAutoPilotSelected: (isAutoPilotSelected: boolean) => void;
onMaxAutoPilotThroughputChange: (newThroughput: number) => void;
onScaleSaveableChange: (isScaleSaveable: boolean) => void;
onScaleDiscardableChange: (isScaleDiscardable: boolean) => void;
initialNotification: DataModels.Notification;
}
export class ScaleComponent extends React.Component<ScaleComponentProps> {
private isEmulator: boolean;
constructor(props: ScaleComponentProps) {
super(props);
this.isEmulator = this.props.container.isEmulator;
}
public isAutoScaleEnabled = (): boolean => {
const accountCapabilities: DataModels.Capability[] = this.props.container?.databaseAccount()?.properties
?.capabilities;
const enableAutoScaleCapability =
accountCapabilities &&
accountCapabilities.find((capability: DataModels.Capability) => {
return (
capability &&
capability.name &&
capability.name.toLowerCase() === Constants.CapabilityNames.EnableAutoScale.toLowerCase()
);
});
return !!enableAutoScaleCapability;
};
private getStorageCapacityTitle = (): JSX.Element => {
// Mongo container with system partition key still treat as "Fixed"
const isFixed =
!this.props.collection.partitionKey ||
(this.props.container.isPreferredApiMongoDB() && this.props.collection.partitionKey.systemKey);
const capacity: string = isFixed ? "Fixed" : "Unlimited";
return (
<Stack {...titleAndInputStackProps}>
<Label>Storage capacity</Label>
<Text>{capacity}</Text>
</Stack>
);
};
public getMaxRUThroughputInputLimit = (): number => {
if (this.props.container?.getPlatformType() === PlatformType.Hosted && this.props.collection.partitionKey) {
return SharedConstants.CollectionCreation.DefaultCollectionRUs1Million;
}
return getMaxRUs(this.props.collection, this.props.container);
};
public getThroughputTitle = (): string => {
if (this.props.isAutoPilotSelected) {
return AutoPilotUtils.getAutoPilotHeaderText(false);
}
const minThroughput: string = getMinRUs(this.props.collection, this.props.container).toLocaleString();
const maxThroughput: string =
this.canThroughputExceedMaximumValue() && !this.props.isFixedContainer
? "unlimited"
: getMaxRUs(this.props.collection, this.props.container).toLocaleString();
return `Throughput (${minThroughput} - ${maxThroughput} RU/s)`;
};
public canThroughputExceedMaximumValue = (): boolean => {
const isPublicAzurePortal: boolean =
this.props.container.getPlatformType() === PlatformType.Portal &&
!this.props.container.isRunningOnNationalCloud();
const hasPartitionKey = !!this.props.collection.partitionKey;
return isPublicAzurePortal && hasPartitionKey;
};
public getInitialNotificationElement = (): JSX.Element => {
if (this.props.initialNotification) {
return this.getLongDelayMessage();
}
const offer = this.props.collection?.offer && this.props.collection.offer();
if (
offer &&
Object.keys(offer).find(value => {
return value === "headers";
}) &&
!!(offer as DataModels.OfferWithHeaders).headers[Constants.HttpHeaders.offerReplacePending]
) {
const throughput = offer?.content?.offerAutopilotSettings?.maxThroughput;
const targetThroughput =
offer.content?.offerAutopilotSettings?.targetMaxThroughput || offer?.content?.offerThroughput;
return getThroughputApplyShortDelayMessage(
this.props.isAutoPilotSelected,
throughput,
throughputUnit,
this.props.collection.databaseId,
this.props.collection.id(),
targetThroughput
);
}
return undefined;
};
public getThroughputWarningMessage = (): JSX.Element => {
const throughputExceedsBackendLimits: boolean =
this.canThroughputExceedMaximumValue() &&
getMaxRUs(this.props.collection, this.props.container) <=
SharedConstants.CollectionCreation.DefaultCollectionRUs1Million &&
this.props.throughput > SharedConstants.CollectionCreation.DefaultCollectionRUs1Million;
if (throughputExceedsBackendLimits && !!this.props.collection.partitionKey && !this.props.isFixedContainer) {
return updateThroughputBeyondLimitWarningMessage;
}
const throughputExceedsMaxValue: boolean =
!this.isEmulator && this.props.throughput > getMaxRUs(this.props.collection, this.props.container);
if (throughputExceedsMaxValue && !!this.props.collection.partitionKey && !this.props.isFixedContainer) {
return updateThroughputDelayedApplyWarningMessage;
}
return undefined;
};
public getLongDelayMessage = (): JSX.Element => {
const matches: string[] = this.props.initialNotification?.description.match(
`Throughput update for (.*) ${throughputUnit}`
);
const throughput = this.props.throughputBaseline;
const targetThroughput: number = matches.length > 1 && Number(matches[1]);
if (targetThroughput) {
return getThroughputApplyLongDelayMessage(
this.props.wasAutopilotOriginallySet,
throughput,
throughputUnit,
this.props.collection.databaseId,
this.props.collection.id(),
targetThroughput
);
}
return <></>;
};
private getThroughputInputComponent = (): JSX.Element => (
<ThroughputInputAutoPilotV3Component
databaseAccount={this.props.container.databaseAccount()}
serverId={this.props.container.serverId()}
throughput={this.props.throughput}
throughputBaseline={this.props.throughputBaseline}
onThroughputChange={this.props.onThroughputChange}
minimum={getMinRUs(this.props.collection, this.props.container)}
maximum={this.getMaxRUThroughputInputLimit()}
isEnabled={!hasDatabaseSharedThroughput(this.props.collection)}
canExceedMaximumValue={this.canThroughputExceedMaximumValue()}
label={this.getThroughputTitle()}
isEmulator={this.isEmulator}
isFixed={this.props.isFixedContainer}
isAutoPilotSelected={this.props.isAutoPilotSelected}
onAutoPilotSelected={this.props.onAutoPilotSelected}
wasAutopilotOriginallySet={this.props.wasAutopilotOriginallySet}
maxAutoPilotThroughput={this.props.autoPilotThroughput}
maxAutoPilotThroughputBaseline={this.props.autoPilotThroughputBaseline}
onMaxAutoPilotThroughputChange={this.props.onMaxAutoPilotThroughputChange}
spendAckChecked={false}
onScaleSaveableChange={this.props.onScaleSaveableChange}
onScaleDiscardableChange={this.props.onScaleDiscardableChange}
getThroughputWarningMessage={this.getThroughputWarningMessage}
/>
);
public render(): JSX.Element {
return (
<Stack {...subComponentStackProps}>
{this.getInitialNotificationElement() && (
<MessageBar messageBarType={MessageBarType.warning}>{this.getInitialNotificationElement()}</MessageBar>
)}
{!this.isAutoScaleEnabled() && (
<Stack {...subComponentStackProps}>
{this.getThroughputInputComponent()}
{this.getStorageCapacityTitle()}
</Stack>
)}
{/* TODO: Replace link with call to the Azure Support blade */}
{this.isAutoScaleEnabled() && (
<Stack {...titleAndInputStackProps}>
<Text>Throughput (RU/s)</Text>
<TextField disabled styles={getTextFieldStyles(undefined, undefined)} />
<Text>
Your account has custom settings that prevents setting throughput at the container level. Please work with
your Cosmos DB engineering team point of contact to make changes.
</Text>
</Stack>
)}
</Stack>
);
}
}

View File

@ -0,0 +1,136 @@
import { shallow } from "enzyme";
import React from "react";
import { SubSettingsComponent, SubSettingsComponentProps } from "./SubSettingsComponent";
import { container, collection } from "../TestUtils";
import { TtlType, GeospatialConfigType, ChangeFeedPolicyState } from "../SettingsUtils";
import ko from "knockout";
import Explorer from "../../../Explorer";
describe("SubSettingsComponent", () => {
container.isPreferredApiDocumentDB = ko.computed(() => true);
const baseProps: SubSettingsComponentProps = {
collection: collection,
container: container,
timeToLive: TtlType.On,
timeToLiveBaseline: TtlType.On,
onTtlChange: () => {
return;
},
timeToLiveSeconds: 1000,
timeToLiveSecondsBaseline: 1000,
onTimeToLiveSecondsChange: () => {
return;
},
geospatialConfigType: GeospatialConfigType.Geography,
geospatialConfigTypeBaseline: GeospatialConfigType.Geography,
onGeoSpatialConfigTypeChange: () => {
return;
},
isAnalyticalStorageEnabled: true,
analyticalStorageTtlSelection: TtlType.On,
analyticalStorageTtlSelectionBaseline: TtlType.On,
onAnalyticalStorageTtlSelectionChange: () => {
return;
},
analyticalStorageTtlSeconds: 2000,
analyticalStorageTtlSecondsBaseline: 2000,
onAnalyticalStorageTtlSecondsChange: () => {
return;
},
changeFeedPolicyVisible: true,
changeFeedPolicy: ChangeFeedPolicyState.On,
changeFeedPolicyBaseline: ChangeFeedPolicyState.On,
onChangeFeedPolicyChange: () => {
return;
},
onSubSettingsSaveableChange: () => {
return;
},
onSubSettingsDiscardableChange: () => {
return;
}
};
it("renders", () => {
const wrapper = shallow(<SubSettingsComponent {...baseProps} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#timeToLive")).toEqual(true);
expect(wrapper.exists("#timeToLiveSeconds")).toEqual(true);
expect(wrapper.exists("#geoSpatialConfig")).toEqual(true);
expect(wrapper.exists("#analyticalStorageTimeToLive")).toEqual(true);
expect(wrapper.exists("#analyticalStorageTimeToLiveSeconds")).toEqual(true);
expect(wrapper.exists("#changeFeedPolicy")).toEqual(true);
});
it("timeToLiveSeconds hidden", () => {
const props = { ...baseProps, timeToLive: TtlType.Off };
const wrapper = shallow(<SubSettingsComponent {...props} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#timeToLive")).toEqual(true);
expect(wrapper.exists("#timeToLiveSeconds")).toEqual(false);
});
it("analyticalTimeToLive hidden", () => {
const props = { ...baseProps, isAnalyticalStorageEnabled: false };
const wrapper = shallow(<SubSettingsComponent {...props} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#analyticalStorageTimeToLive")).toEqual(false);
expect(wrapper.exists("#analyticalStorageTimeToLiveSeconds")).toEqual(false);
});
it("analyticalTimeToLiveSeconds hidden", () => {
const props = { ...baseProps, analyticalStorageTtlSelection: TtlType.OnNoDefault };
const wrapper = shallow(<SubSettingsComponent {...props} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#analyticalStorageTimeToLive")).toEqual(true);
expect(wrapper.exists("#analyticalStorageTimeToLiveSeconds")).toEqual(false);
});
it("changeFeedPolicy hidden", () => {
const props = { ...baseProps, changeFeedPolicyVisible: false };
const wrapper = shallow(<SubSettingsComponent {...props} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#changeFeedPolicy")).toEqual(false);
});
it("partitionKey is visible", () => {
const subSettingsComponent = new SubSettingsComponent(baseProps);
expect(subSettingsComponent.getPartitionKeyVisible()).toEqual(true);
});
it("partitionKey not visible", () => {
const newContainer = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
newContainer.isPreferredApiCassandra = ko.computed(() => true);
const props = { ...baseProps, container: newContainer };
const subSettingsComponent = new SubSettingsComponent(props);
expect(subSettingsComponent.getPartitionKeyVisible()).toEqual(false);
});
it("largePartitionKey is enabled", () => {
const subSettingsComponent = new SubSettingsComponent(baseProps);
expect(subSettingsComponent.isLargePartitionKeyEnabled()).toEqual(true);
});
it("sub settings saveable and discardable are set", () => {
let subSettingsComponent = new SubSettingsComponent(baseProps);
let isComponentDirtyResult = subSettingsComponent.IsComponentDirty();
expect(isComponentDirtyResult.isSaveable).toEqual(false);
expect(isComponentDirtyResult.isDiscardable).toEqual(false);
const newProps = { ...baseProps, timeToLive: TtlType.OnNoDefault };
subSettingsComponent = new SubSettingsComponent(newProps);
isComponentDirtyResult = subSettingsComponent.IsComponentDirty();
expect(isComponentDirtyResult.isSaveable).toEqual(true);
expect(isComponentDirtyResult.isDiscardable).toEqual(true);
});
});

View File

@ -0,0 +1,296 @@
import * as React from "react";
import * as ViewModels from "../../../../Contracts/ViewModels";
import {
GeospatialConfigType,
TtlType,
ChangeFeedPolicyState,
isDirty,
IsComponentDirtyResult
} from "../SettingsUtils";
import Explorer from "../../../Explorer";
import { Int32 } from "../../../Panes/Tables/Validators/EntityPropertyValidationCommon";
import {
Label,
Text,
TextField,
Stack,
IChoiceGroupOption,
ChoiceGroup,
MessageBar,
MessageBarType
} from "office-ui-fabric-react";
import {
getTextFieldStyles,
changeFeedPolicyToolTip,
subComponentStackProps,
titleAndInputStackProps,
getChoiceGroupStyles,
ttlWarning,
messageBarStyles
} from "../SettingsRenderUtils";
import { ToolTipLabelComponent } from "./ToolTipLabelComponent";
export interface SubSettingsComponentProps {
collection: ViewModels.Collection;
container: Explorer;
timeToLive: TtlType;
timeToLiveBaseline: TtlType;
onTtlChange: (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption) => void;
timeToLiveSeconds: number;
timeToLiveSecondsBaseline: number;
onTimeToLiveSecondsChange: (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
) => void;
geospatialConfigType: GeospatialConfigType;
geospatialConfigTypeBaseline: GeospatialConfigType;
onGeoSpatialConfigTypeChange: (
ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
) => void;
isAnalyticalStorageEnabled: boolean;
analyticalStorageTtlSelection: TtlType;
analyticalStorageTtlSelectionBaseline: TtlType;
onAnalyticalStorageTtlSelectionChange: (
ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
) => void;
analyticalStorageTtlSeconds: number;
analyticalStorageTtlSecondsBaseline: number;
onAnalyticalStorageTtlSecondsChange: (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
) => void;
changeFeedPolicyVisible: boolean;
changeFeedPolicy: ChangeFeedPolicyState;
changeFeedPolicyBaseline: ChangeFeedPolicyState;
onChangeFeedPolicyChange: (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption) => void;
onSubSettingsSaveableChange: (isSubSettingsSaveable: boolean) => void;
onSubSettingsDiscardableChange: (isSubSettingsDiscardable: boolean) => void;
}
export class SubSettingsComponent extends React.Component<SubSettingsComponentProps> {
private shouldCheckComponentIsDirty = true;
private ttlVisible: boolean;
private geospatialVisible: boolean;
private partitionKeyValue: string;
private partitionKeyName: string;
constructor(props: SubSettingsComponentProps) {
super(props);
this.ttlVisible = (this.props.container && !this.props.container.isPreferredApiCassandra()) || false;
this.geospatialVisible = this.props.container.isPreferredApiDocumentDB();
this.partitionKeyValue = "/" + this.props.collection.partitionKeyProperty;
this.partitionKeyName = this.props.container.isPreferredApiMongoDB() ? "Shard key" : "Partition key";
}
componentDidMount(): void {
this.onComponentUpdate();
}
componentDidUpdate(): void {
this.onComponentUpdate();
}
private onComponentUpdate = (): void => {
if (!this.shouldCheckComponentIsDirty) {
this.shouldCheckComponentIsDirty = true;
return;
}
const isComponentDirtyResult = this.IsComponentDirty();
this.props.onSubSettingsSaveableChange(isComponentDirtyResult.isSaveable);
this.props.onSubSettingsDiscardableChange(isComponentDirtyResult.isDiscardable);
this.shouldCheckComponentIsDirty = false;
};
public IsComponentDirty = (): IsComponentDirtyResult => {
if (
(this.props.timeToLive === TtlType.On && !this.props.timeToLiveSeconds) ||
(this.props.analyticalStorageTtlSelection === TtlType.On && !this.props.analyticalStorageTtlSeconds)
) {
return { isSaveable: false, isDiscardable: true };
} else if (
isDirty(this.props.timeToLive, this.props.timeToLiveBaseline) ||
(this.props.timeToLive === TtlType.On &&
isDirty(this.props.timeToLiveSeconds, this.props.timeToLiveSecondsBaseline)) ||
isDirty(this.props.analyticalStorageTtlSelection, this.props.analyticalStorageTtlSelectionBaseline) ||
(this.props.analyticalStorageTtlSelection === TtlType.On &&
isDirty(this.props.analyticalStorageTtlSeconds, this.props.analyticalStorageTtlSecondsBaseline)) ||
isDirty(this.props.geospatialConfigType, this.props.geospatialConfigTypeBaseline) ||
isDirty(this.props.changeFeedPolicy, this.props.changeFeedPolicyBaseline)
) {
return { isSaveable: true, isDiscardable: true };
}
return { isSaveable: false, isDiscardable: false };
};
private ttlChoiceGroupOptions: IChoiceGroupOption[] = [
{ key: TtlType.Off, text: "Off" },
{ key: TtlType.OnNoDefault, text: "On (no default)" },
{ key: TtlType.On, text: "On" }
];
private getTtlComponent = (): JSX.Element => (
<Stack {...titleAndInputStackProps}>
<ChoiceGroup
id="timeToLive"
label="Time to Live"
selectedKey={this.props.timeToLive}
options={this.ttlChoiceGroupOptions}
onChange={this.props.onTtlChange}
styles={getChoiceGroupStyles(this.props.timeToLive, this.props.timeToLiveBaseline)}
/>
{isDirty(this.props.timeToLive, this.props.timeToLiveBaseline) && this.props.timeToLive === TtlType.On && (
<MessageBar messageBarType={MessageBarType.warning} styles={messageBarStyles}>
{ttlWarning}
</MessageBar>
)}
{this.props.timeToLive === TtlType.On && (
<TextField
id="timeToLiveSeconds"
styles={getTextFieldStyles(this.props.timeToLiveSeconds, this.props.timeToLiveSecondsBaseline)}
type="number"
required
min={1}
max={Int32.Max}
value={this.props.timeToLiveSeconds?.toString()}
onChange={this.props.onTimeToLiveSecondsChange}
suffix="second(s)"
/>
)}
</Stack>
);
private analyticalTtlChoiceGroupOptions: IChoiceGroupOption[] = [
{ key: TtlType.Off, text: "Off", disabled: true },
{ key: TtlType.OnNoDefault, text: "On (no default)" },
{ key: TtlType.On, text: "On" }
];
private getAnalyticalStorageTtlComponent = (): JSX.Element => (
<Stack {...titleAndInputStackProps}>
<ChoiceGroup
id="analyticalStorageTimeToLive"
label="Analytical Storage Time to Live"
selectedKey={this.props.analyticalStorageTtlSelection}
options={this.analyticalTtlChoiceGroupOptions}
onChange={this.props.onAnalyticalStorageTtlSelectionChange}
styles={getChoiceGroupStyles(
this.props.analyticalStorageTtlSelection,
this.props.analyticalStorageTtlSelectionBaseline
)}
/>
{this.props.analyticalStorageTtlSelection === TtlType.On && (
<TextField
id="analyticalStorageTimeToLiveSeconds"
styles={getTextFieldStyles(
this.props.analyticalStorageTtlSeconds,
this.props.analyticalStorageTtlSecondsBaseline
)}
type="number"
required
min={1}
max={Int32.Max}
value={this.props.analyticalStorageTtlSeconds?.toString()}
suffix="second(s)"
onChange={this.props.onAnalyticalStorageTtlSecondsChange}
/>
)}
</Stack>
);
private geoSpatialConfigTypeChoiceGroupOptions: IChoiceGroupOption[] = [
{ key: GeospatialConfigType.Geography, text: "Geography" },
{ key: GeospatialConfigType.Geometry, text: "Geometry" }
];
private getGeoSpatialComponent = (): JSX.Element => (
<ChoiceGroup
id="geoSpatialConfig"
label="Geospatial Configuration"
selectedKey={this.props.geospatialConfigType}
options={this.geoSpatialConfigTypeChoiceGroupOptions}
onChange={this.props.onGeoSpatialConfigTypeChange}
styles={getChoiceGroupStyles(this.props.geospatialConfigType, this.props.geospatialConfigTypeBaseline)}
/>
);
private changeFeedChoiceGroupOptions: IChoiceGroupOption[] = [
{ key: ChangeFeedPolicyState.Off, text: "Off" },
{ key: ChangeFeedPolicyState.On, text: "On" }
];
private getChangeFeedComponent = (): JSX.Element => {
const labelId = "settingsV2ChangeFeedLabelId";
return (
<Stack>
<Label id={labelId}>
<ToolTipLabelComponent label="Change feed log retention policy" toolTipElement={changeFeedPolicyToolTip} />
</Label>
<ChoiceGroup
id="changeFeedPolicy"
selectedKey={this.props.changeFeedPolicy}
options={this.changeFeedChoiceGroupOptions}
onChange={this.props.onChangeFeedPolicyChange}
styles={getChoiceGroupStyles(this.props.changeFeedPolicy, this.props.changeFeedPolicyBaseline)}
aria-labelledby={labelId}
/>
</Stack>
);
};
private getPartitionKeyComponent = (): JSX.Element => (
<Stack {...titleAndInputStackProps}>
{this.getPartitionKeyVisible() && (
<TextField
label={this.partitionKeyName}
disabled
styles={getTextFieldStyles(undefined, undefined)}
defaultValue={this.partitionKeyValue}
/>
)}
{this.isLargePartitionKeyEnabled() && <Text>Large {this.partitionKeyName.toLowerCase()} has been enabled</Text>}
</Stack>
);
public getPartitionKeyVisible = (): boolean => {
if (
this.props.container.isPreferredApiCassandra() ||
this.props.container.isPreferredApiTable() ||
!this.props.collection.partitionKeyProperty ||
(this.props.container.isPreferredApiMongoDB() && this.props.collection.partitionKey.systemKey)
) {
return false;
}
return true;
};
public isLargePartitionKeyEnabled = (): boolean => this.props.collection.partitionKey?.version >= 2;
public render(): JSX.Element {
return (
<Stack {...subComponentStackProps}>
{this.ttlVisible && this.getTtlComponent()}
{this.geospatialVisible && this.getGeoSpatialComponent()}
{this.props.isAnalyticalStorageEnabled && this.getAnalyticalStorageTtlComponent()}
{this.props.changeFeedPolicyVisible && this.getChangeFeedComponent()}
{this.getPartitionKeyComponent()}
</Stack>
);
}
}

View File

@ -0,0 +1,97 @@
import { shallow } from "enzyme";
import React from "react";
import {
ThroughputInputAutoPilotV3Component,
ThroughputInputAutoPilotV3Props
} from "./ThroughputInputAutoPilotV3Component";
import * as DataModels from "../../../../../Contracts/DataModels";
describe("ThroughputInputAutoPilotV3Component", () => {
const baseProps: ThroughputInputAutoPilotV3Props = {
databaseAccount: {} as DataModels.DatabaseAccount,
serverId: undefined,
wasAutopilotOriginallySet: false,
throughput: 100,
throughputBaseline: 100,
onThroughputChange: undefined,
minimum: 10000,
maximum: 400,
step: 100,
isEnabled: true,
isEmulator: false,
spendAckChecked: false,
spendAckId: "spendAckId",
spendAckText: "spendAckText",
spendAckVisible: false,
showAsMandatory: true,
isFixed: false,
label: "label",
infoBubbleText: "infoBubbleText",
canExceedMaximumValue: true,
onAutoPilotSelected: undefined,
isAutoPilotSelected: false,
maxAutoPilotThroughput: 4000,
maxAutoPilotThroughputBaseline: 4000,
onMaxAutoPilotThroughputChange: undefined,
onScaleSaveableChange: () => {
return;
},
onScaleDiscardableChange: () => {
return;
},
getThroughputWarningMessage: () => undefined
};
it("throughput input visible", () => {
const wrapper = shallow(<ThroughputInputAutoPilotV3Component {...baseProps} />);
const throughputComponent = wrapper.instance() as ThroughputInputAutoPilotV3Component;
expect(throughputComponent.hasProvisioningTypeChanged()).toEqual(false);
expect(throughputComponent.overrideWithProvisionedThroughputSettings()).toEqual(false);
expect(throughputComponent.overrideWithAutoPilotSettings()).toEqual(false);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#throughputInput")).toEqual(true);
expect(wrapper.exists("#autopilotInput")).toEqual(false);
expect(wrapper.exists("#throughputSpendElement")).toEqual(true);
expect(wrapper.exists("#autoscaleSpendElement")).toEqual(false);
});
it("autopilot input visible", () => {
const newProps = { ...baseProps, isAutoPilotSelected: true };
const wrapper = shallow(<ThroughputInputAutoPilotV3Component {...newProps} />);
const throughputComponent = wrapper.instance() as ThroughputInputAutoPilotV3Component;
expect(throughputComponent.hasProvisioningTypeChanged()).toEqual(true);
expect(throughputComponent.overrideWithProvisionedThroughputSettings()).toEqual(true);
expect(throughputComponent.overrideWithAutoPilotSettings()).toEqual(false);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#autopilotInput")).toEqual(true);
expect(wrapper.exists("#throughputInput")).toEqual(false);
expect(wrapper.exists("#manualToAutoscaleDisclaimerElement")).toEqual(true);
wrapper.setProps({ wasAutopilotOriginallySet: true });
wrapper.update();
expect(wrapper.exists("#autoscaleSpendElement")).toEqual(true);
expect(wrapper.exists("#throughputSpendElement")).toEqual(false);
});
it("spendAck checkbox visible", () => {
const newProps = { ...baseProps, spendAckVisible: true };
const wrapper = shallow(<ThroughputInputAutoPilotV3Component {...newProps} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.exists("#spendAckCheckBox")).toEqual(true);
});
it("scale saveable and discardable are set", () => {
let throughputComponent = new ThroughputInputAutoPilotV3Component(baseProps);
let isComponentDirtyResult = throughputComponent.IsComponentDirty();
expect(isComponentDirtyResult.isSaveable).toEqual(false);
expect(isComponentDirtyResult.isDiscardable).toEqual(false);
const newProps = { ...baseProps, throughput: 1000000 };
throughputComponent = new ThroughputInputAutoPilotV3Component(newProps);
isComponentDirtyResult = throughputComponent.IsComponentDirty();
expect(isComponentDirtyResult.isSaveable).toEqual(true);
expect(isComponentDirtyResult.isDiscardable).toEqual(true);
});
});

View File

@ -0,0 +1,342 @@
import React from "react";
import * as AutoPilotUtils from "../../../../../Utils/AutoPilotUtils";
import {
getTextFieldStyles,
getToolTipContainer,
spendAckCheckBoxStyle,
titleAndInputStackProps,
checkBoxAndInputStackProps,
getChoiceGroupStyles,
messageBarStyles,
getEstimatedSpendElement,
getEstimatedAutoscaleSpendElement,
getAutoPilotV3SpendElement,
manualToAutoscaleDisclaimerElement
} from "../../SettingsRenderUtils";
import {
Text,
TextField,
ChoiceGroup,
IChoiceGroupOption,
Checkbox,
Stack,
Label,
Link,
MessageBar,
MessageBarType
} from "office-ui-fabric-react";
import { ToolTipLabelComponent } from "../ToolTipLabelComponent";
import { IsComponentDirtyResult, isDirty } from "../../SettingsUtils";
import * as SharedConstants from "../../../../../Shared/Constants";
import * as DataModels from "../../../../../Contracts/DataModels";
export interface ThroughputInputAutoPilotV3Props {
databaseAccount: DataModels.DatabaseAccount;
serverId: string;
throughput: number;
throughputBaseline: number;
onThroughputChange: (newThroughput: number) => void;
minimum: number;
maximum: number;
step?: number;
isEnabled?: boolean;
spendAckChecked?: boolean;
spendAckId?: string;
spendAckText?: string;
spendAckVisible?: boolean;
showAsMandatory?: boolean;
isFixed: boolean;
isEmulator: boolean;
label: string;
infoBubbleText?: string;
canExceedMaximumValue?: boolean;
onAutoPilotSelected: (isAutoPilotSelected: boolean) => void;
isAutoPilotSelected: boolean;
wasAutopilotOriginallySet: boolean;
maxAutoPilotThroughput: number;
maxAutoPilotThroughputBaseline: number;
onMaxAutoPilotThroughputChange: (newThroughput: number) => void;
onScaleSaveableChange: (isScaleSaveable: boolean) => void;
onScaleDiscardableChange: (isScaleDiscardable: boolean) => void;
getThroughputWarningMessage: () => JSX.Element;
}
interface ThroughputInputAutoPilotV3State {
spendAckChecked: boolean;
}
export class ThroughputInputAutoPilotV3Component extends React.Component<
ThroughputInputAutoPilotV3Props,
ThroughputInputAutoPilotV3State
> {
private shouldCheckComponentIsDirty = true;
private static readonly defaultStep = 100;
private static readonly zeroThroughput = 0;
private step: number;
private choiceGroupFixedStyle = getChoiceGroupStyles(undefined, undefined);
private options: IChoiceGroupOption[] = [
{ key: "true", text: "Autoscale" },
{ key: "false", text: "Manual" }
];
componentDidMount(): void {
this.onComponentUpdate();
}
componentDidUpdate(): void {
this.onComponentUpdate();
}
private onComponentUpdate = (): void => {
if (!this.shouldCheckComponentIsDirty) {
this.shouldCheckComponentIsDirty = true;
return;
}
const isComponentDirtyResult = this.IsComponentDirty();
this.props.onScaleSaveableChange(isComponentDirtyResult.isSaveable);
this.props.onScaleDiscardableChange(isComponentDirtyResult.isDiscardable);
this.shouldCheckComponentIsDirty = false;
};
public IsComponentDirty = (): IsComponentDirtyResult => {
let isSaveable = false;
let isDiscardable = false;
if (this.props.isEnabled) {
if (this.hasProvisioningTypeChanged()) {
isSaveable = true;
isDiscardable = true;
} else if (this.props.isAutoPilotSelected) {
if (isDirty(this.props.maxAutoPilotThroughput, this.props.maxAutoPilotThroughputBaseline)) {
isDiscardable = true;
if (AutoPilotUtils.isValidAutoPilotThroughput(this.props.maxAutoPilotThroughput)) {
isSaveable = true;
}
}
} else {
if (isDirty(this.props.throughput, this.props.throughputBaseline)) {
isDiscardable = true;
isSaveable = true;
if (
!this.props.throughput ||
this.props.throughput < this.props.minimum ||
(this.props.throughput > this.props.maximum && (this.props.isEmulator || this.props.isFixed)) ||
(this.props.throughput > SharedConstants.CollectionCreation.DefaultCollectionRUs1Million &&
!this.props.canExceedMaximumValue)
) {
isSaveable = false;
}
}
}
}
return { isSaveable, isDiscardable };
};
public constructor(props: ThroughputInputAutoPilotV3Props) {
super(props);
this.state = {
spendAckChecked: this.props.spendAckChecked
};
this.step = this.props.step ?? ThroughputInputAutoPilotV3Component.defaultStep;
}
public hasProvisioningTypeChanged = (): boolean =>
this.props.wasAutopilotOriginallySet !== this.props.isAutoPilotSelected;
public overrideWithAutoPilotSettings = (): boolean =>
this.hasProvisioningTypeChanged() && this.props.wasAutopilotOriginallySet;
public overrideWithProvisionedThroughputSettings = (): boolean =>
this.hasProvisioningTypeChanged() && !this.props.wasAutopilotOriginallySet;
private getRequestUnitsUsageCost = (): JSX.Element => {
const account = this.props.databaseAccount;
if (!account) {
return <></>;
}
const serverId: string = this.props.serverId;
const offerThroughput: number = this.props.throughput;
const regions = account?.properties?.readLocations?.length || 1;
const multimaster = account?.properties?.enableMultipleWriteLocations || false;
let estimatedSpend: JSX.Element;
if (!this.props.isAutoPilotSelected) {
estimatedSpend = getEstimatedSpendElement(
// if migrating from autoscale to manual, we use the autoscale RUs value as that is what will be set...
this.overrideWithAutoPilotSettings() ? this.props.maxAutoPilotThroughput : offerThroughput,
serverId,
regions,
multimaster,
false
);
} else {
estimatedSpend = getEstimatedAutoscaleSpendElement(
this.props.maxAutoPilotThroughput,
serverId,
regions,
multimaster
);
}
return estimatedSpend;
};
private getAutoPilotUsageCost = (): JSX.Element => {
if (!this.props.maxAutoPilotThroughput) {
return <></>;
}
return getAutoPilotV3SpendElement(
this.props.maxAutoPilotThroughput,
false /* isDatabaseThroughput */,
!this.props.isEmulator ? this.getRequestUnitsUsageCost() : <></>
);
};
private onAutoPilotThroughputChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => {
let newThroughput = parseInt(newValue);
newThroughput = isNaN(newThroughput) ? ThroughputInputAutoPilotV3Component.zeroThroughput : newThroughput;
this.props.onMaxAutoPilotThroughputChange(newThroughput);
};
private onThroughputChange = (
event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newValue?: string
): void => {
let newThroughput = parseInt(newValue);
newThroughput = isNaN(newThroughput) ? ThroughputInputAutoPilotV3Component.zeroThroughput : newThroughput;
if (this.overrideWithAutoPilotSettings()) {
this.props.onMaxAutoPilotThroughputChange(newThroughput);
} else {
this.props.onThroughputChange(newThroughput);
}
};
private onChoiceGroupChange = (
event?: React.FormEvent<HTMLElement | HTMLInputElement>,
option?: IChoiceGroupOption
): void => this.props.onAutoPilotSelected(option.key === "true");
private renderThroughputModeChoices = (): JSX.Element => {
const labelId = "settingsV2RadioButtonLabelId";
return (
<Stack>
<Label id={labelId}>
<ToolTipLabelComponent
label={this.props.label}
toolTipElement={getToolTipContainer(this.props.infoBubbleText)}
/>
</Label>
{this.overrideWithProvisionedThroughputSettings() && (
<MessageBar messageBarType={MessageBarType.warning} styles={messageBarStyles}>
{manualToAutoscaleDisclaimerElement}
</MessageBar>
)}
<ChoiceGroup
selectedKey={this.props.isAutoPilotSelected.toString()}
options={this.options}
onChange={this.onChoiceGroupChange}
required={this.props.showAsMandatory}
ariaLabelledBy={labelId}
styles={this.choiceGroupFixedStyle}
/>
</Stack>
);
};
private onSpendAckChecked = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean): void =>
this.setState({ spendAckChecked: checked });
private renderAutoPilotInput = (): JSX.Element => (
<>
<Text>
Provision maximum RU/s required by this resource. Estimate your required RU/s with
<Link target="_blank" href="https://cosmos.azure.com/capacitycalculator/">
{` capacity calculator`}
</Link>
</Text>
<TextField
label="Max RU/s"
required
type="number"
id="autopilotInput"
key="auto pilot throughput input"
styles={getTextFieldStyles(this.props.maxAutoPilotThroughput, this.props.maxAutoPilotThroughputBaseline)}
disabled={this.overrideWithProvisionedThroughputSettings()}
step={this.step}
min={AutoPilotUtils.minAutoPilotThroughput}
value={this.overrideWithProvisionedThroughputSettings() ? "" : this.props.maxAutoPilotThroughput?.toString()}
onChange={this.onAutoPilotThroughputChange}
/>
{!this.overrideWithProvisionedThroughputSettings() && this.getAutoPilotUsageCost()}
{this.props.spendAckVisible && (
<Checkbox
id="spendAckCheckBox"
styles={spendAckCheckBoxStyle}
label={this.props.spendAckText}
checked={this.state.spendAckChecked}
onChange={this.onSpendAckChecked}
/>
)}
</>
);
private renderThroughputInput = (): JSX.Element => (
<Stack {...titleAndInputStackProps}>
<TextField
required
type="number"
id="throughputInput"
key="provisioned throughput input"
styles={getTextFieldStyles(this.props.throughput, this.props.throughputBaseline)}
disabled={this.overrideWithAutoPilotSettings()}
step={this.step}
min={this.props.minimum}
max={this.props.canExceedMaximumValue ? undefined : this.props.maximum}
value={
this.overrideWithAutoPilotSettings()
? this.props.maxAutoPilotThroughputBaseline?.toString()
: this.props.throughput?.toString()
}
onChange={this.onThroughputChange}
/>
{this.props.getThroughputWarningMessage() && (
<MessageBar messageBarType={MessageBarType.warning} styles={messageBarStyles}>
{this.props.getThroughputWarningMessage()}
</MessageBar>
)}
{!this.props.isEmulator && this.getRequestUnitsUsageCost()}
{this.props.spendAckVisible && (
<Checkbox
id="spendAckCheckBox"
styles={spendAckCheckBoxStyle}
label={this.props.spendAckText}
checked={this.state.spendAckChecked}
onChange={this.onSpendAckChecked}
/>
)}
{this.props.isFixed && <p>Choose unlimited storage capacity for more than 10,000 RU/s.</p>}
</Stack>
);
public render(): JSX.Element {
return (
<Stack {...checkBoxAndInputStackProps}>
{!this.props.isFixed && this.renderThroughputModeChoices()}
{this.props.isAutoPilotSelected ? this.renderAutoPilotInput() : this.renderThroughputInput()}
</Stack>
);
}
}

View File

@ -0,0 +1,434 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ThroughputInputAutoPilotV3Component autopilot input visible 1`] = `
<Stack
tokens={
Object {
"childrenGap": 10,
}
}
>
<Stack>
<StyledLabelBase
id="settingsV2RadioButtonLabelId"
>
<ToolTipLabelComponent
label="label"
toolTipElement={
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
infoBubbleText
</Text>
}
/>
</StyledLabelBase>
<StyledMessageBarBase
messageBarType={5}
styles={
Object {
"root": Object {
"marginTop": "5px",
},
}
}
>
<Text
id="manualToAutoscaleDisclaimerElement"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
The starting autoscale max RU/s will be determined by the system, based on the current manual throughput settings and storage of your resource. After autoscale has been enabled, you can change the max RU/s.
<a
href="https://aka.ms/cosmos-autoscale-migration"
>
Learn more
</a>
</Text>
</StyledMessageBarBase>
<StyledChoiceGroupBase
ariaLabelledBy="settingsV2RadioButtonLabelId"
onChange={[Function]}
options={
Array [
Object {
"key": "true",
"text": "Autoscale",
},
Object {
"key": "false",
"text": "Manual",
},
]
}
required={true}
selectedKey="true"
styles={
Object {
"flexContainer": Array [
Object {
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
},
".ms-ChoiceField-field.is-checked::before": Object {
"borderColor": "",
},
".ms-ChoiceField-wrapper label": Object {
"fontFamily": undefined,
"fontSize": 14,
"padding": "2px 5px",
"whiteSpace": "nowrap",
},
},
},
],
}
}
/>
</Stack>
<Text>
Provision maximum RU/s required by this resource. Estimate your required RU/s with
<StyledLinkBase
href="https://cosmos.azure.com/capacitycalculator/"
target="_blank"
>
capacity calculator
</StyledLinkBase>
</Text>
<StyledTextFieldBase
disabled={true}
id="autopilotInput"
key="auto pilot throughput input"
label="Max RU/s"
min={4000}
onChange={[Function]}
required={true}
step={100}
styles={
Object {
"fieldGroup": Object {
"borderColor": "",
"height": 25,
"selectors": Object {
":disabled": Object {
"backgroundColor": undefined,
"borderColor": undefined,
},
},
"width": 300,
},
}
}
type="number"
value=""
/>
</Stack>
`;
exports[`ThroughputInputAutoPilotV3Component spendAck checkbox visible 1`] = `
<Stack
tokens={
Object {
"childrenGap": 10,
}
}
>
<Stack>
<StyledLabelBase
id="settingsV2RadioButtonLabelId"
>
<ToolTipLabelComponent
label="label"
toolTipElement={
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
infoBubbleText
</Text>
}
/>
</StyledLabelBase>
<StyledChoiceGroupBase
ariaLabelledBy="settingsV2RadioButtonLabelId"
onChange={[Function]}
options={
Array [
Object {
"key": "true",
"text": "Autoscale",
},
Object {
"key": "false",
"text": "Manual",
},
]
}
required={true}
selectedKey="false"
styles={
Object {
"flexContainer": Array [
Object {
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
},
".ms-ChoiceField-field.is-checked::before": Object {
"borderColor": "",
},
".ms-ChoiceField-wrapper label": Object {
"fontFamily": undefined,
"fontSize": 14,
"padding": "2px 5px",
"whiteSpace": "nowrap",
},
},
},
],
}
}
/>
</Stack>
<Stack
tokens={
Object {
"childrenGap": 5,
}
}
>
<StyledTextFieldBase
disabled={false}
id="throughputInput"
key="provisioned throughput input"
min={10000}
onChange={[Function]}
required={true}
step={100}
styles={
Object {
"fieldGroup": Object {
"borderColor": "",
"height": 25,
"selectors": Object {
":disabled": Object {
"backgroundColor": undefined,
"borderColor": undefined,
},
},
"width": 300,
},
}
}
type="number"
value="100"
/>
<Text
id="throughputSpendElement"
>
Estimated cost (
USD
):
<b>
$
0.0080
hourly
/
$
0.19
daily
/
$
5.84
monthly
</b>
(
regions:
1
,
100
RU/s,
$
0.00008
/RU)
</Text>
<StyledCheckboxBase
checked={false}
id="spendAckCheckBox"
label="spendAckText"
onChange={[Function]}
styles={
Object {
"label": Object {
"margin": 0,
"padding": "2 0 2 0",
},
"text": Object {
"fontSize": 12,
},
}
}
/>
</Stack>
</Stack>
`;
exports[`ThroughputInputAutoPilotV3Component throughput input visible 1`] = `
<Stack
tokens={
Object {
"childrenGap": 10,
}
}
>
<Stack>
<StyledLabelBase
id="settingsV2RadioButtonLabelId"
>
<ToolTipLabelComponent
label="label"
toolTipElement={
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
infoBubbleText
</Text>
}
/>
</StyledLabelBase>
<StyledChoiceGroupBase
ariaLabelledBy="settingsV2RadioButtonLabelId"
onChange={[Function]}
options={
Array [
Object {
"key": "true",
"text": "Autoscale",
},
Object {
"key": "false",
"text": "Manual",
},
]
}
required={true}
selectedKey="false"
styles={
Object {
"flexContainer": Array [
Object {
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
},
".ms-ChoiceField-field.is-checked::before": Object {
"borderColor": "",
},
".ms-ChoiceField-wrapper label": Object {
"fontFamily": undefined,
"fontSize": 14,
"padding": "2px 5px",
"whiteSpace": "nowrap",
},
},
},
],
}
}
/>
</Stack>
<Stack
tokens={
Object {
"childrenGap": 5,
}
}
>
<StyledTextFieldBase
disabled={false}
id="throughputInput"
key="provisioned throughput input"
min={10000}
onChange={[Function]}
required={true}
step={100}
styles={
Object {
"fieldGroup": Object {
"borderColor": "",
"height": 25,
"selectors": Object {
":disabled": Object {
"backgroundColor": undefined,
"borderColor": undefined,
},
},
"width": 300,
},
}
}
type="number"
value="100"
/>
<Text
id="throughputSpendElement"
>
Estimated cost (
USD
):
<b>
$
0.0080
hourly
/
$
0.19
daily
/
$
5.84
monthly
</b>
(
regions:
1
,
100
RU/s,
$
0.00008
/RU)
</Text>
</Stack>
</Stack>
`;

View File

@ -0,0 +1,15 @@
import { shallow } from "enzyme";
import React from "react";
import { ToolTipLabelComponent, ToolTipLabelComponentProps } from "./ToolTipLabelComponent";
describe("ToolTipLabelComponent", () => {
const props: ToolTipLabelComponentProps = {
label: "sample tool tip label",
toolTipElement: <span>sample tool tip text</span>
};
it("renders", () => {
const wrapper = shallow(<ToolTipLabelComponent {...props} />);
expect(wrapper).toMatchSnapshot();
});
});

View File

@ -0,0 +1,32 @@
import * as React from "react";
import { Stack, Text, IIconStyles, Icon, TooltipHost, DirectionalHint } from "office-ui-fabric-react";
import { toolTipLabelStackTokens } from "../SettingsRenderUtils";
export interface ToolTipLabelComponentProps {
label: string;
toolTipElement: JSX.Element;
}
const iconButtonStyles: Partial<IIconStyles> = { root: { marginBottom: -3 } };
export class ToolTipLabelComponent extends React.Component<ToolTipLabelComponentProps> {
public render(): JSX.Element {
return (
<>
<Stack horizontal verticalAlign="center" tokens={toolTipLabelStackTokens}>
{this.props.label && <Text style={{ fontWeight: 600 }}>{this.props.label}</Text>}
{this.props.toolTipElement && (
<TooltipHost
content={this.props.toolTipElement}
directionalHint={DirectionalHint.rightCenter}
calloutProps={{ gapSpace: 0 }}
styles={{ root: { display: "inline-block", float: "right" } }}
>
<Icon iconName="Info" ariaLabel="Info" styles={iconButtonStyles} />
</TooltipHost>
)}
</Stack>
</>
);
}
}

View File

@ -0,0 +1,145 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ConflictResolutionComponent Path text field displayed 1`] = `
<Stack
tokens={
Object {
"childrenGap": 20,
}
}
>
<StyledChoiceGroupBase
label="Mode"
onChange={[Function]}
options={
Array [
Object {
"key": "LastWriterWins",
"text": "Last Write Wins (default)",
},
Object {
"key": "Custom",
"text": "Merge Procedure (custom)",
},
]
}
selectedKey="LastWriterWins"
styles={
Object {
"flexContainer": Array [
Object {
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": undefined,
},
".ms-ChoiceField-field.is-checked::before": Object {
"borderColor": undefined,
},
".ms-ChoiceField-wrapper label": Object {
"fontFamily": undefined,
"fontSize": 14,
"padding": "2px 5px",
"whiteSpace": "nowrap",
},
},
},
],
}
}
/>
<StyledTextFieldBase
id="conflictResolutionLwwTextField"
label="Conflict Resolver Property"
onChange={[Function]}
onRenderLabel={[Function]}
styles={
Object {
"fieldGroup": Object {
"borderColor": "",
"height": 25,
"selectors": Object {
":disabled": Object {
"backgroundColor": undefined,
"borderColor": undefined,
},
},
"width": 300,
},
}
}
value=""
/>
</Stack>
`;
exports[`ConflictResolutionComponent Sproc text field displayed 1`] = `
<Stack
tokens={
Object {
"childrenGap": 20,
}
}
>
<StyledChoiceGroupBase
label="Mode"
onChange={[Function]}
options={
Array [
Object {
"key": "LastWriterWins",
"text": "Last Write Wins (default)",
},
Object {
"key": "Custom",
"text": "Merge Procedure (custom)",
},
]
}
selectedKey="Custom"
styles={
Object {
"flexContainer": Array [
Object {
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
},
".ms-ChoiceField-field.is-checked::before": Object {
"borderColor": "",
},
".ms-ChoiceField-wrapper label": Object {
"fontFamily": undefined,
"fontSize": 14,
"padding": "2px 5px",
"whiteSpace": "nowrap",
},
},
},
],
}
}
/>
<StyledTextFieldBase
id="conflictResolutionCustomTextField"
label="Stored procedure"
onChange={[Function]}
onRenderLabel={[Function]}
styles={
Object {
"fieldGroup": Object {
"borderColor": "",
"height": 25,
"selectors": Object {
":disabled": Object {
"backgroundColor": undefined,
"borderColor": undefined,
},
},
"width": 300,
},
}
}
value=""
/>
</Stack>
`;

View File

@ -0,0 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`IndexingPolicyComponent renders 1`] = `
<Stack
tokens={
Object {
"childrenGap": 5,
}
}
>
<div
className="settingsV2IndexingPolicyEditor"
tabIndex={0}
/>
</Stack>
`;

View File

@ -0,0 +1,79 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ScaleComponent renders with correct intiial notification 1`] = `
<Stack
tokens={
Object {
"childrenGap": 20,
}
}
>
<StyledMessageBarBase
messageBarType={5}
>
<Text
id="throughputApplyLongDelayMessage"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
A request to increase the throughput is currently in progress. This operation will take 1-3 business days to complete. View the latest status in Notifications.
<br />
Database:
test
, Container:
test
, Current autoscale throughput: 100 - 1000 RU/s, Target autoscale throughput: 600 - 6000 RU/s
</Text>
</StyledMessageBarBase>
<Stack
tokens={
Object {
"childrenGap": 20,
}
}
>
<ThroughputInputAutoPilotV3Component
canExceedMaximumValue={false}
getThroughputWarningMessage={[Function]}
isAutoPilotSelected={false}
isEmulator={false}
isEnabled={true}
isFixed={false}
label="Throughput (6,000 - 40,000 RU/s)"
maxAutoPilotThroughput={4000}
maxAutoPilotThroughputBaseline={4000}
maximum={40000}
minimum={6000}
onAutoPilotSelected={[Function]}
onMaxAutoPilotThroughputChange={[Function]}
onScaleDiscardableChange={[Function]}
onScaleSaveableChange={[Function]}
onThroughputChange={[Function]}
spendAckChecked={false}
throughput={1000}
throughputBaseline={1000}
wasAutopilotOriginallySet={true}
/>
<Stack
tokens={
Object {
"childrenGap": 5,
}
}
>
<StyledLabelBase>
Storage capacity
</StyledLabelBase>
<Text>
Unlimited
</Text>
</Stack>
</Stack>
</Stack>
`;

View File

@ -0,0 +1,58 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ToolTipLabelComponent renders 1`] = `
<Fragment>
<Stack
horizontal={true}
tokens={
Object {
"childrenGap": 6,
}
}
verticalAlign="center"
>
<Text
style={
Object {
"fontWeight": 600,
}
}
>
sample tool tip label
</Text>
<StyledTooltipHostBase
calloutProps={
Object {
"gapSpace": 0,
}
}
content={
<span>
sample tool tip text
</span>
}
directionalHint={12}
styles={
Object {
"root": Object {
"display": "inline-block",
"float": "right",
},
}
}
>
<Memo(StyledIconBase)
ariaLabel="Info"
iconName="Info"
styles={
Object {
"root": Object {
"marginBottom": -3,
},
}
}
/>
</StyledTooltipHostBase>
</Stack>
</Fragment>
`;

View File

@ -0,0 +1,89 @@
import { collection, container } from "./TestUtils";
import {
getMaxRUs,
getMinRUs,
hasDatabaseSharedThroughput,
isDirty,
isDirtyTypes,
parseConflictResolutionMode,
parseConflictResolutionProcedure
} from "./SettingsUtils";
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
import ko from "knockout";
describe("SettingsUtils", () => {
it("getMaxRUs", () => {
expect(collection.offer().content.collectionThroughputInfo.numPhysicalPartitions).toEqual(4);
expect(getMaxRUs(collection, container)).toEqual(40000);
});
it("getMinRUs", () => {
expect(collection.offer().content.collectionThroughputInfo.numPhysicalPartitions).toEqual(4);
expect(getMinRUs(collection, container)).toEqual(6000);
});
it("hasDatabaseSharedThroughput", () => {
expect(hasDatabaseSharedThroughput(collection)).toEqual(undefined);
const newCollection = { ...collection };
newCollection.getDatabase = () => {
return {
nodeKind: undefined,
rid: undefined,
container: undefined,
self: "",
id: ko.observable(""),
collections: ko.observableArray(undefined),
offer: ko.observable(undefined),
isDatabaseExpanded: ko.observable(false),
isDatabaseShared: ko.computed(() => true),
selectedSubnodeKind: ko.observable(undefined),
selectDatabase: undefined,
expandDatabase: undefined,
collapseDatabase: undefined,
loadCollections: undefined,
findCollectionWithId: undefined,
openAddCollection: undefined,
onDeleteDatabaseContextMenuClick: undefined,
readSettings: undefined,
onSettingsClick: undefined,
loadOffer: undefined
} as ViewModels.Database;
};
newCollection.offer(undefined);
expect(hasDatabaseSharedThroughput(newCollection)).toEqual(true);
});
it("parseConflictResolutionMode", () => {
expect(parseConflictResolutionMode("custom")).toEqual(DataModels.ConflictResolutionMode.Custom);
expect(parseConflictResolutionMode("lastwriterwins")).toEqual(DataModels.ConflictResolutionMode.LastWriterWins);
});
it("parseConflictResolutionProcedure", () => {
expect(parseConflictResolutionProcedure("/dbs/db/colls/coll/sprocs/conflictResSproc")).toEqual("conflictResSproc");
expect(parseConflictResolutionProcedure("conflictResSproc")).toEqual("conflictResSproc");
});
describe("isDirty", () => {
const indexingPolicy = {
automatic: true,
indexingMode: "consistent",
includedPaths: [],
excludedPaths: []
} as DataModels.IndexingPolicy;
const cases = [
["baseline", "current"],
[0, 1],
[true, false],
[undefined, indexingPolicy],
[indexingPolicy, { ...indexingPolicy, automatic: false }]
];
test.each(cases)("", (baseline: isDirtyTypes, current: isDirtyTypes) => {
expect(isDirty(baseline, baseline)).toEqual(false);
expect(isDirty(baseline, current)).toEqual(true);
});
});
});

View File

@ -0,0 +1,171 @@
import * as ViewModels from "../../../Contracts/ViewModels";
import * as DataModels from "../../../Contracts/DataModels";
import * as Constants from "../../../Common/Constants";
import * as SharedConstants from "../../../Shared/Constants";
import * as PricingUtils from "../../../Utils/PricingUtils";
import Explorer from "../../Explorer";
export type isDirtyTypes = boolean | string | number | DataModels.IndexingPolicy;
export const TtlOff = "off";
export const TtlOn = "on";
export const TtlOnNoDefault = "on-nodefault";
export enum ChangeFeedPolicyState {
Off = "Off",
On = "On"
}
export enum TtlType {
Off = "off",
On = "on",
OnNoDefault = "on-nodefault"
}
export enum GeospatialConfigType {
Geography = "Geography",
Geometry = "Geometry"
}
export enum SettingsV2TabTypes {
ScaleTab,
ConflictResolutionTab,
SubSettingsTab,
IndexingPolicyTab
}
export interface IsComponentDirtyResult {
isSaveable: boolean;
isDiscardable: boolean;
}
export const hasDatabaseSharedThroughput = (collection: ViewModels.Collection): boolean => {
const database: ViewModels.Database = collection.getDatabase();
return database?.isDatabaseShared() && !collection.offer();
};
export const getMaxRUs = (collection: ViewModels.Collection, container: Explorer): number => {
const isTryCosmosDBSubscription = container?.isTryCosmosDBSubscription() || false;
if (isTryCosmosDBSubscription) {
return Constants.TryCosmosExperience.maxRU;
}
const numPartitionsFromOffer: number =
collection?.offer && collection.offer()?.content?.collectionThroughputInfo?.numPhysicalPartitions;
const numPartitionsFromQuotaInfo: number = collection?.quotaInfo().numPartitions;
const numPartitions = numPartitionsFromOffer ?? numPartitionsFromQuotaInfo ?? 1;
return SharedConstants.CollectionCreation.MaxRUPerPartition * numPartitions;
};
export const getMinRUs = (collection: ViewModels.Collection, container: Explorer): number => {
const isTryCosmosDBSubscription = container?.isTryCosmosDBSubscription();
if (isTryCosmosDBSubscription) {
return SharedConstants.CollectionCreation.DefaultCollectionRUs400;
}
const offerContent = collection?.offer && collection.offer()?.content;
if (offerContent?.offerAutopilotSettings) {
return SharedConstants.CollectionCreation.DefaultCollectionRUs400;
}
const collectionThroughputInfo: DataModels.OfferThroughputInfo = offerContent?.collectionThroughputInfo;
if (collectionThroughputInfo?.minimumRUForCollection > 0) {
return collectionThroughputInfo.minimumRUForCollection;
}
const numPartitions = collectionThroughputInfo?.numPhysicalPartitions ?? collection.quotaInfo().numPartitions;
if (!numPartitions || numPartitions === 1) {
return SharedConstants.CollectionCreation.DefaultCollectionRUs400;
}
const baseRU = SharedConstants.CollectionCreation.DefaultCollectionRUs400;
const quotaInKb = collection.quotaInfo().collectionSize;
const quotaInGb = PricingUtils.usageInGB(quotaInKb);
const perPartitionGBQuota: number = Math.max(10, quotaInGb / numPartitions);
const baseRUbyPartitions: number = ((numPartitions * perPartitionGBQuota) / 10) * 100;
return Math.max(baseRU, baseRUbyPartitions);
};
export const parseConflictResolutionMode = (modeFromBackend: string): DataModels.ConflictResolutionMode => {
// Backend can contain different casing as it does case-insensitive comparisson
if (!modeFromBackend) {
return undefined;
}
const modeAsLowerCase: string = modeFromBackend.toLowerCase();
if (modeAsLowerCase === DataModels.ConflictResolutionMode.Custom.toLowerCase()) {
return DataModels.ConflictResolutionMode.Custom;
}
// Default is LWW
return DataModels.ConflictResolutionMode.LastWriterWins;
};
export const parseConflictResolutionProcedure = (procedureFromBackEnd: string): string => {
// Backend data comes in /dbs/xxxx/colls/xxxx/sprocs/{name}, to make it easier for users, we just use the name
if (!procedureFromBackEnd) {
return undefined;
}
if (procedureFromBackEnd.indexOf("/") >= 0) {
const sprocsIndex: number = procedureFromBackEnd.indexOf(Constants.HashRoutePrefixes.sprocHash);
if (sprocsIndex === -1) {
return undefined;
}
return procedureFromBackEnd.substr(sprocsIndex + Constants.HashRoutePrefixes.sprocHash.length);
}
// No path, just a name, in case backend returns just the name
return procedureFromBackEnd;
};
export const isDirty = (current: isDirtyTypes, baseline: isDirtyTypes): boolean => {
const currentType = typeof current;
const baselineType = typeof baseline;
if (currentType !== "undefined" && baselineType !== "undefined" && currentType !== baselineType) {
throw new Error("current and baseline values are not of the same type.");
}
const currentStringValue = getStringValue(current, currentType);
const baselineStringValue = getStringValue(baseline, baselineType);
return currentStringValue !== baselineStringValue;
};
const getStringValue = (value: isDirtyTypes, type: string): string => {
switch (type) {
case "string":
case "undefined":
case "number":
case "boolean":
return value?.toString();
default:
return JSON.stringify(value);
}
};
export const getTabTitle = (tab: SettingsV2TabTypes): string => {
switch (tab) {
case SettingsV2TabTypes.ScaleTab:
return "Scale";
case SettingsV2TabTypes.ConflictResolutionTab:
return "Conflict Resolution";
case SettingsV2TabTypes.SubSettingsTab:
return "Settings";
case SettingsV2TabTypes.IndexingPolicyTab:
return "Indexing Policy";
default:
throw new Error(`Unknown tab ${tab}`);
}
};

View File

@ -0,0 +1,52 @@
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
import Explorer from "../../Explorer";
import ko from "knockout";
export const container = new Explorer({
notificationsClient: undefined,
isEmulator: false
});
export const collection = ({
container: container,
databaseId: "test",
id: ko.observable<string>("test"),
defaultTtl: ko.observable<number>(5),
analyticalStorageTtl: ko.observable<number>(undefined),
indexingPolicy: ko.observable<DataModels.IndexingPolicy>({
automatic: true,
indexingMode: "default",
includedPaths: [],
excludedPaths: []
}),
uniqueKeyPolicy: {} as DataModels.UniqueKeyPolicy,
quotaInfo: ko.observable<DataModels.CollectionQuotaInfo>({} as DataModels.CollectionQuotaInfo),
offer: ko.observable<DataModels.Offer>({
content: {
offerThroughput: 10000,
offerIsRUPerMinuteThroughputEnabled: false,
collectionThroughputInfo: {
minimumRUForCollection: 6000,
numPhysicalPartitions: 4
} as DataModels.OfferThroughputInfo
}
} as DataModels.Offer),
conflictResolutionPolicy: ko.observable<DataModels.ConflictResolutionPolicy>(
{} as DataModels.ConflictResolutionPolicy
),
changeFeedPolicy: ko.observable<DataModels.ChangeFeedPolicy>({} as DataModels.ChangeFeedPolicy),
geospatialConfig: ko.observable<DataModels.GeospatialConfig>({} as DataModels.GeospatialConfig),
getDatabase: () => {
return;
},
partitionKey: {
paths: [],
kind: "hash",
version: 2
},
partitionKeyProperty: "partitionKey",
readSettings: () => {
return;
}
} as unknown) as ViewModels.Collection;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,314 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`SettingsUtils functions render 1`] = `
<Fragment>
<Text>
Your
container
throughput will automatically scale from
<b>
100
RU/s (10% of max RU/s) -
1000
RU/s
</b>
based on usage.
<br />
</Text>
<Text>
After the first
10
GB of data stored, the max RU/s will be automatically upgraded based on the new storage value.
<StyledLinkBase
href="https://aka.ms/cosmos-autoscale-info"
target="_blank"
>
Learn more
</StyledLinkBase>
.
</Text>
<Text>
Your
database
throughput will automatically scale from
<b>
100
RU/s (10% of max RU/s) -
1000
RU/s
</b>
based on usage.
<br />
</Text>
<Text>
After the first
10
GB of data stored, the max RU/s will be automatically upgraded based on the new storage value.
<StyledLinkBase
href="https://aka.ms/cosmos-autoscale-info"
target="_blank"
>
Learn more
</StyledLinkBase>
.
</Text>
<Text
id="throughputSpendElement"
>
Estimated cost (
RMB
):
<b>
¥
1.29
hourly
/
¥
31.06
daily
/
¥
944.60
monthly
</b>
(
regions:
2
,
1000
RU/s,
¥
0.00051
/RU)
</Text>
<Text
id="autoscaleSpendElement"
>
Estimated monthly cost (
RMB
) is
<b>
¥
111.69
-
¥
1116.90
</b>
(
regions:
2
,
100
-
1000
RU/s,
¥
0.000765
/RU)
</Text>
<Text
id="manualToAutoscaleDisclaimerElement"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
The starting autoscale max RU/s will be determined by the system, based on the current manual throughput settings and storage of your resource. After autoscale has been enabled, you can change the max RU/s.
<a
href="https://aka.ms/cosmos-autoscale-migration"
>
Learn more
</a>
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
The system will automatically delete items based on the TTL value (in seconds) you provide, without needing a delete operation explicitly issued by a client application. For more information see,
<StyledLinkBase
href="https://aka.ms/cosmos-db-ttl"
target="_blank"
>
Time to Live (TTL) in Azure Cosmos DB
</StyledLinkBase>
.
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
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
id="updateThroughputBeyondLimitWarningMessage"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
You are about to request an increase in throughput beyond the pre-allocated capacity. The service will scale out and increase throughput for the selected container. This operation will take 1-3 business days to complete. You can track the status of this request in Notifications.
</Text>
<Text
id="updateThroughputDelayedApplyWarningMessage"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
You are about to request an increase in throughput beyond the pre-allocated capacity. This operation will take some time to complete.
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
The request to increase the throughput has successfully been submitted. This operation will take 1-3 business days to complete. View the latest status in Notifications.
<br />
Database:
sampleDb
, Container:
sampleCollection
, Current manual throughput: 1000 RU/s, Target manual throughput: 2000
</Text>
<Text
id="throughputApplyShortDelayMessage"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
A request to increase the throughput is currently in progress. This operation will take some time to complete.
<br />
Database:
sampleDb
, Container:
sampleCollection
, Current manual throughput: 1000 RU/s, Target manual throughput: 2000
</Text>
<Text
id="throughputApplyLongDelayMessage"
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
A request to increase the throughput is currently in progress. This operation will take 1-3 business days to complete. View the latest status in Notifications.
<br />
Database:
sampleDb
, Container:
sampleCollection
, Current manual throughput: 1000 RU/s, Target manual throughput: 2000
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
<span>
Sample Text
</span>
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
Gets or sets the name of a integer property in your documents which is used for the Last Write Wins (LWW) based conflict resolution scheme. By default, the system uses the system defined timestamp property, _ts to decide the winner for the conflicting versions of the document. Specify your own integer property if you want to override the default timestamp based conflict resolution.
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
Gets or sets the name of a stored procedure (aka merge procedure) for resolving the conflicts. You can write application defined logic to determine the winner of the conflicting versions of a document. The stored procedure will get executed transactionally, exactly once, on the server side. If you do not provide a stored procedure, the conflicts will be populated in the
<StyledLinkBase
className="linkDarkBackground"
href="https://aka.ms/dataexplorerconflics"
target="_blank"
>
conflicts feed
</StyledLinkBase>
. You can update/re-register the stored procedure at any time.
</Text>
<Text
styles={
Object {
"root": Object {
"fontSize": 12,
},
}
}
>
Enable change feed log retention policy to retain last 10 minutes of history for items in the container by default. To support this, the request unit (RU) charge for this container will be multiplied by a factor of two for writes. Reads are unaffected.
</Text>
</Fragment>
`;

View File

@ -213,6 +213,7 @@ export default class Explorer {
public isGalleryPublishEnabled: ko.Computed<boolean>;
public isCodeOfConductEnabled: ko.Computed<boolean>;
public isLinkInjectionEnabled: ko.Computed<boolean>;
public isSettingsV2Enabled: ko.Computed<boolean>;
public isGitHubPaneEnabled: ko.Observable<boolean>;
public isPublishNotebookPaneEnabled: ko.Observable<boolean>;
public isCopyNotebookPaneEnabled: ko.Observable<boolean>;
@ -422,6 +423,7 @@ export default class Explorer {
this.isLinkInjectionEnabled = ko.computed<boolean>(() =>
this.isFeatureEnabled(Constants.Features.enableLinkInjection)
);
this.isSettingsV2Enabled = ko.computed<boolean>(() => this.isFeatureEnabled(Constants.Features.enableSettingsV2));
this.isGitHubPaneEnabled = ko.observable<boolean>(false);
this.isPublishNotebookPaneEnabled = ko.observable<boolean>(false);
this.isCopyNotebookPaneEnabled = ko.observable<boolean>(false);

View File

@ -5,7 +5,7 @@ import * as ViewModels from "../../Contracts/ViewModels";
import Collection from "../Tree/Collection";
import Database from "../Tree/Database";
import Explorer from "../Explorer";
import SettingsTab from "../Tabs/SettingsTab";
import SettingsTab from "./SettingsTab";
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
import { IndexingPolicies } from "../../Shared/Constants";

View File

@ -182,7 +182,6 @@ export default class SettingsTab extends TabsBase implements ViewModels.WaitsFor
public partitionKeyVisible: ko.PureComputed<boolean>;
public partitionKeyValue: ko.Observable<string>;
public isLargePartitionKeyEnabled: ko.Computed<boolean>;
public pendingNotification: ko.Observable<DataModels.Notification>;
public requestUnitsUsageCost: ko.Computed<string>;
public rupmOnId: string;
public rupmOffId: string;
@ -859,7 +858,6 @@ export default class SettingsTab extends TabsBase implements ViewModels.WaitsFor
this.ttlOnDefaultFocused = ko.observable<boolean>(false);
this.ttlOnFocused = ko.observable<boolean>(false);
this.indexingPolicyElementFocused = ko.observable<boolean>(false);
this.pendingNotification = ko.observable<DataModels.Notification>(undefined);
this._offerReplacePending = ko.pureComputed<boolean>(() => {
const offer = this.collection && this.collection.offer && this.collection.offer();

View File

@ -0,0 +1 @@
<div style="height: 100%" data-bind="react:settingsComponentAdapter"></div>

View File

@ -0,0 +1,27 @@
import * as ViewModels from "../../Contracts/ViewModels";
import TabsBase from "./TabsBase";
import { SettingsComponentAdapter } from "../Controls/Settings/SettingsComponentAdapter";
import { SettingsComponentProps } from "../Controls/Settings/SettingsComponent";
import Explorer from "../Explorer";
export default class SettingsTabV2 extends TabsBase {
public settingsComponentAdapter: SettingsComponentAdapter;
constructor(options: ViewModels.TabOptions) {
super(options);
const props: SettingsComponentProps = {
settingsTab: this
};
this.settingsComponentAdapter = new SettingsComponentAdapter(props);
}
public onActivate(): Q.Promise<unknown> {
return super.onActivate().then(() => {
this.collection.selectedSubnodeKind(ViewModels.CollectionTabKind.SettingsV2);
});
}
public getSettingsTabContainer(): Explorer {
return this.getContainer();
}
}

View File

@ -10,6 +10,7 @@ import MongoShellTabTemplate from "./MongoShellTab.html";
import QueryTabTemplate from "./QueryTab.html";
import QueryTablesTabTemplate from "./QueryTablesTab.html";
import SettingsTabTemplate from "./SettingsTab.html";
import SettingsTabV2Template from "./SettingsTabV2.html";
import DatabaseSettingsTabTemplate from "./DatabaseSettingsTab.html";
import StoredProcedureTabTemplate from "./StoredProcedureTab.html";
import TriggerTabTemplate from "./TriggerTab.html";
@ -141,6 +142,15 @@ export class SettingsTab {
}
}
export class SettingsTabV2 {
constructor() {
return {
viewModel: TabComponent,
template: SettingsTabV2Template
};
}
}
export class DatabaseSettingsTab {
constructor() {
return {

View File

@ -2,6 +2,7 @@ import * as ko from "knockout";
import Q from "q";
import * as Constants from "../../Common/Constants";
import * as ViewModels from "../../Contracts/ViewModels";
import * as DataModels from "../../Contracts/DataModels";
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
import { RouteHandler } from "../../RouteHandlers/RouteHandler";
import { WaitsForTemplateViewModel } from "../WaitsForTemplateViewModel";
@ -29,6 +30,7 @@ export default class TabsBase extends WaitsForTemplateViewModel {
public hashLocation: ko.Observable<string>;
public isExecutionError: ko.Observable<boolean>;
public isExecuting: ko.Observable<boolean>;
public pendingNotification?: ko.Observable<DataModels.Notification>;
protected _theme: string;
public onLoadStartKey: number;
@ -56,6 +58,7 @@ export default class TabsBase extends WaitsForTemplateViewModel {
this.errorDetailsTabIndex = ko.computed<number>(() => (this.isActive() ? 0 : null));
this.isExecutionError = ko.observable<boolean>(false);
this.isExecuting = ko.observable<boolean>(false);
this.pendingNotification = ko.observable<DataModels.Notification>(undefined);
this.onLoadStartKey = options.onLoadStartKey;
this.hashLocation = ko.observable<string>(options.hashLocation || "");
this.hashLocation.subscribe((newLocation: string) => this.updateGlobalHash(newLocation));

View File

@ -141,6 +141,10 @@
<!-- ko if: $data.tabKind === 18 -->
<notebook-viewer-tab params="{data: $data}"></notebook-viewer-tab>
<!-- /ko -->
<!-- ko if: $data.tabKind === 19 -->
<settings-tab-v2 params="{data: $data}"></settings-tab-v2>
<!-- /ko -->
</div>
<!-- /ko -->
</div>

View File

@ -12,17 +12,13 @@ import { createDocument } from "../../Common/DocumentClientUtilityBase";
import { readCollectionOffer } from "../../Common/dataAccess/readCollectionOffer";
import { readCollectionQuotaInfo } from "../../Common/dataAccess/readCollectionQuotaInfo";
import * as Logger from "../../Common/Logger";
import { configContext } from "../../ConfigContext";
import * as DataModels from "../../Contracts/DataModels";
import * as ViewModels from "../../Contracts/ViewModels";
import { PlatformType } from "../../PlatformType";
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { userContext } from "../../UserContext";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { OfferUtils } from "../../Utils/OfferUtils";
import { StartUploadMessageParams, UploadDetails, UploadDetailsRecord } from "../../workers/upload/definitions";
import Explorer from "../Explorer";
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import { CassandraAPIDataClient, CassandraTableKey, CassandraTableKeys } from "../Tables/TableDataClient";
import ConflictsTab from "../Tabs/ConflictsTab";
@ -33,12 +29,17 @@ import MongoQueryTab from "../Tabs/MongoQueryTab";
import MongoShellTab from "../Tabs/MongoShellTab";
import QueryTab from "../Tabs/QueryTab";
import QueryTablesTab from "../Tabs/QueryTablesTab";
import SettingsTabV2 from "../Tabs/SettingsTabV2";
import SettingsTab from "../Tabs/SettingsTab";
import ConflictId from "./ConflictId";
import DocumentId from "./DocumentId";
import StoredProcedure from "./StoredProcedure";
import Trigger from "./Trigger";
import UserDefinedFunction from "./UserDefinedFunction";
import { configContext } from "../../ConfigContext";
import Explorer from "../Explorer";
import { userContext } from "../../UserContext";
import TabsBase from "../Tabs/TabsBase";
export default class Collection implements ViewModels.Collection {
public nodeKind: string;
@ -562,33 +563,49 @@ export default class Collection implements ViewModels.Collection {
return tab.collection && tab.collection.rid === this.rid;
});
let settingsTab: SettingsTab = matchingTabs && (matchingTabs[0] as SettingsTab);
const traceStartData = {
databaseAccountName: this.container.databaseAccount().name,
databaseName: this.databaseId,
collectionName: this.id(),
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: tabTitle
};
const settingsTabOptions: ViewModels.TabOptions = {
tabKind: undefined,
title: !this.offer() ? "Settings" : "Scale & Settings",
tabPath: "",
collection: this,
node: this,
selfLink: this.self,
hashLocation: `${Constants.HashRoutePrefixes.collectionsWithIds(this.databaseId, this.id())}/settings`,
isActive: ko.observable(false),
onUpdateTabsButtons: this.container.onUpdateTabsButtons
};
const isSettingsV2Enabled = this.container.isSettingsV2Enabled();
var settingsTab: TabsBase;
if (isSettingsV2Enabled) {
settingsTab = matchingTabs && (matchingTabs[0] as SettingsTabV2);
} else {
settingsTab = matchingTabs && (matchingTabs[0] as SettingsTab);
}
if (!settingsTab) {
const startKey: number = TelemetryProcessor.traceStart(Action.Tab, {
databaseAccountName: this.container.databaseAccount().name,
databaseName: this.databaseId,
collectionName: this.id(),
defaultExperience: this.container.defaultExperience(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: tabTitle
});
const startKey: number = TelemetryProcessor.traceStart(Action.Tab, traceStartData);
settingsTabOptions.onLoadStartKey = startKey;
pendingNotificationsPromise.then(
(data: any) => {
const pendingNotification: DataModels.Notification = data && data[0];
settingsTab = new SettingsTab({
tabKind: ViewModels.CollectionTabKind.Settings,
title: tabTitle,
tabPath: "",
collection: this,
node: this,
selfLink: this.self,
hashLocation: `${Constants.HashRoutePrefixes.collectionsWithIds(this.databaseId, this.id())}/settings`,
isActive: ko.observable(false),
onLoadStartKey: startKey,
onUpdateTabsButtons: this.container.onUpdateTabsButtons
});
if (isSettingsV2Enabled) {
settingsTabOptions.tabKind = ViewModels.CollectionTabKind.SettingsV2;
settingsTab = new SettingsTabV2(settingsTabOptions);
} else {
settingsTabOptions.tabKind = ViewModels.CollectionTabKind.Settings;
settingsTab = new SettingsTab(settingsTabOptions);
}
this.container.tabsManager.activateNewTab(settingsTab);
settingsTab.pendingNotification(pendingNotification);
},