Compare commits

..

20 Commits

Author SHA1 Message Date
MokireddySampath
a516d9ec45 Update AddTableEntityPanel.test.tsx.snap 2023-06-06 22:13:02 +05:30
MokireddySampath
61a0433c40 Update QuickstartCarousel.tsx 2023-06-06 22:11:22 +05:30
MokireddySampath
0fd7129d2f Update AddTableEntityPanel.tsx 2023-05-31 14:54:26 +05:30
MokireddySampath
b4c0e29c04 Update RightPaneForm.tsx 2023-05-31 14:53:33 +05:30
MokireddySampath
8e723df3fb Update NewVertexComponent.tsx 2023-05-31 14:51:35 +05:30
MokireddySampath
9e2ab607f7 Update ThroughputInput.test.tsx.snap 2023-05-31 14:49:04 +05:30
MokireddySampath
7108c9b1ba Update ThroughputInput.tsx 2023-05-31 14:46:54 +05:30
MokireddySampath
e3632b734c Update ThroughputInput.less 2023-05-31 14:46:27 +05:30
MokireddySampath
881efd965c Update TableEntity.tsx 2023-05-31 14:46:03 +05:30
MokireddySampath
84b73d5bb6 Update queryBuilder.less 2023-05-31 14:45:33 +05:30
MokireddySampath
9e7beff184 Update fulldatatables.less 2023-05-31 14:45:01 +05:30
MokireddySampath
a0b6d71507 Update SplashScreen.tsx 2023-05-31 14:44:21 +05:30
Sampath
e267b5c1cc screenreader content changed to announce the entire alert 2023-05-31 14:41:19 +05:30
Sampath
85bd63f1a4 arialabel added to the add property button 2023-05-31 13:04:48 +05:30
Sampath
ccd817e432 add property is readout twice while using screenreader 2023-05-30 22:01:36 +05:30
Sampath
34611bdbdf capacity calculator link has been added with underline on focus 2023-05-23 16:48:02 +05:30
Sampath
15388fb03e header text color changed to meet luminosity ratio requirement 2023-05-23 15:38:16 +05:30
Sampath
c8310021bc outline has been restored to choose columns link in entities page 2023-05-22 18:05:39 +05:30
Sampath
93392c8795 heading role has been addedd and tag has been changed to h1 2023-05-22 17:04:36 +05:30
Sampath
f98cdf39d6 arialabel has been added to close button of invitational youtube video 2023-05-17 18:57:51 +05:30
75 changed files with 1963 additions and 16051 deletions

View File

@@ -1,41 +0,0 @@
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->

View File

@@ -1,35 +0,0 @@
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="40" height="40" fill="white"/>
<path d="M17 3.73926L20 4.04436V12.6862L15.2 13.8013L13.6 15.9967V19.4479C13.6 21.7669 14.8545 23.9045 16.879 25.0353L21.4036 27.5626L13.6 31.69L10.3559 32.1523L7.27902 30.4337C5.25445 29.3028 4 27.1652 4 24.8462V14.7591C4 12.4395 5.25512 10.3015 7.28055 9.17085L16.3174 4.12639L16.3121 4.13012L17 3.73926Z" fill="url(#paint0_radial_420_101763)"/>
<path d="M17 3.73926L20 4.04436V12.6862L15.2 13.8013L13.6 15.9967V19.4479C13.6 21.7669 14.8545 23.9045 16.879 25.0353L21.4036 27.5626L13.6 31.69L10.3559 32.1523L7.27902 30.4337C5.25445 29.3028 4 27.1652 4 24.8462V14.7591C4 12.4395 5.25512 10.3015 7.28055 9.17085L16.3174 4.12639L16.3121 4.13012L17 3.73926Z" fill="url(#paint1_linear_420_101763)"/>
<path d="M26.399 15.001L34.399 19.801L35.999 21.401V24.8452C35.999 27.1642 34.7446 29.3018 32.72 30.4327L23.12 35.7949C21.1804 36.8784 18.8177 36.8784 16.878 35.7949L7.27804 30.4327C7.09146 30.3284 6.91141 30.2157 6.73828 30.095L7.278 30.3965C9.21762 31.4799 11.5803 31.4799 13.52 30.3965L23.12 25.0342C25.1445 23.9033 26.399 21.7657 26.399 19.4467V15.001Z" fill="url(#paint2_radial_420_101763)"/>
<path d="M26.399 15.001L34.399 19.801L35.999 21.401V24.8452C35.999 27.1642 34.7446 29.3018 32.72 30.4327L23.12 35.7949C21.1804 36.8784 18.8177 36.8784 16.878 35.7949L7.27804 30.4327C7.09146 30.3284 6.91141 30.2157 6.73828 30.095L7.278 30.3965C9.21762 31.4799 11.5803 31.4799 13.52 30.3965L23.12 25.0342C25.1445 23.9033 26.399 21.7657 26.399 19.4467V15.001Z" fill="url(#paint3_linear_420_101763)"/>
<path d="M32.7191 9.17053L23.119 3.8117C21.1802 2.72943 18.819 2.72943 16.8802 3.8117L16.3151 4.1271C14.6239 5.31737 13.5996 7.26472 13.5996 9.36025V16.0461L16.8802 14.2149C18.819 13.1326 21.1802 13.1326 23.119 14.2149L32.7191 19.5737C34.6984 20.6786 35.9421 22.7456 35.9977 25.0039C35.999 24.9514 35.9996 24.8987 35.9996 24.8459V14.7588C35.9996 12.4392 34.7445 10.3011 32.7191 9.17053Z" fill="url(#paint4_radial_420_101763)"/>
<path d="M32.7191 9.17053L23.119 3.8117C21.1802 2.72943 18.819 2.72943 16.8802 3.8117L16.3151 4.1271C14.6239 5.31737 13.5996 7.26472 13.5996 9.36025V16.0461L16.8802 14.2149C18.819 13.1326 21.1802 13.1326 23.119 14.2149L32.7191 19.5737C34.6984 20.6786 35.9421 22.7456 35.9977 25.0039C35.999 24.9514 35.9996 24.8987 35.9996 24.8459V14.7588C35.9996 12.4392 34.7445 10.3011 32.7191 9.17053Z" fill="url(#paint5_linear_420_101763)"/>
<defs>
<radialGradient id="paint0_radial_420_101763" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(17.5054 12.8837) rotate(112.544) scale(23.4519 19.3067)">
<stop offset="0.206732" stop-color="#45D586"/>
<stop offset="0.875628" stop-color="#128245"/>
</radialGradient>
<linearGradient id="paint1_linear_420_101763" x1="15.0625" y1="29.6174" x2="13.787" y2="27.2436" gradientUnits="userSpaceOnUse">
<stop offset="0.9999" stop-color="#0F773F"/>
<stop offset="1" stop-color="#0078D4" stop-opacity="0"/>
</linearGradient>
<radialGradient id="paint2_radial_420_101763" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(10.899 27.5214) rotate(-3.9995) scale(24.6197 15.4594)">
<stop offset="0.140029" stop-color="#FBFF47"/>
<stop offset="0.952721" stop-color="#54B228"/>
</radialGradient>
<linearGradient id="paint3_linear_420_101763" x1="30.8932" y1="18.5508" x2="29.5491" y2="20.8921" gradientUnits="userSpaceOnUse">
<stop offset="0.9999" stop-color="#27770B"/>
<stop offset="1" stop-color="#8C66BA" stop-opacity="0"/>
</linearGradient>
<radialGradient id="paint4_radial_420_101763" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(30.632 19.3878) rotate(-138.33) scale(22.8015 13.0047)">
<stop stop-color="#95FEA0"/>
<stop offset="0.839255" stop-color="#10B7B7"/>
</radialGradient>
<linearGradient id="paint5_linear_420_101763" x1="13.5996" y1="11.7134" x2="16.2131" y2="11.7134" gradientUnits="userSpaceOnUse">
<stop offset="0.9999" stop-color="#0A7B7B"/>
<stop offset="1" stop-color="#436DCD" stop-opacity="0"/>
</linearGradient>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -1,3 +0,0 @@
<svg width="334" height="154" viewBox="0 0 334 154" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="0.5" y="0.5" width="333" height="153" fill="#F3F2F1" stroke="#E1DFDD"/>
</svg>

Before

Width:  |  Height:  |  Size: 188 B

View File

@@ -37,7 +37,7 @@ module.exports = {
coverageThreshold: {
global: {
branches: 25,
functions: 24,
functions: 25,
lines: 28,
statements: 28,
},

View File

@@ -650,4 +650,4 @@ tr:hover td.nameColumnText {
.context-menu-item.icon-customize-columns {
background-image: url(../../images/Options.svg);
}
}

View File

@@ -212,7 +212,7 @@
"strict:find": "node ./strict-null-checks/find.js",
"strict:add": "node ./strict-null-checks/auto-add.js",
"compile:fullStrict": "tsc -p ./tsconfig.json --strictNullChecks",
"generateARMClients": "npx ts-node utils/armClientGenerator/generator.ts"
"generateARMClients": "npx ts-node --compiler-options '{\"module\":\"commonjs\"}' utils/armClientGenerator/generator.ts"
},
"repository": {
"type": "git",

File diff suppressed because it is too large Load Diff

View File

@@ -428,91 +428,3 @@ export class JunoEndpoints {
public static readonly Prod = "https://tools.cosmos.azure.com";
public static readonly Stage = "https://tools-staging.cosmos.azure.com";
}
export const QueryCopilotSampleDatabaseId = "CopilotSampleDb";
export const QueryCopilotSampleContainerId = "SampleContainer";
export const QueryCopilotSampleContainerSchema = {
product: {
sampleData: {
id: "de6fadec-0384-43c8-93ea-16c0170b5460",
name: "Premium Phone Mini (Red)",
price: 652.04,
category: "Electronics",
description:
"This Premium Phone Mini (Red) is designed by the company under agreement with the FCC, so we'd give it a pass in either direction, but no one should be using this handset without a compatible handset. All in all, this phone is one of the most affordable Android handsets out there at $100. Check them out.\n\n9. HTC One M9 4",
stock: 74,
countryOfOrigin: "Mexico",
firstAvailable: "2018-07-07 17:42:28",
priceHistory: [592.81],
customerRatings: [
{ username: "dannyhowell", stars: 1, date: "2022-03-12 17:01:23", verifiedUser: true },
{ username: "lindsay26", stars: 1, date: "2022-12-29 07:18:20", verifiedUser: false },
{ username: "smithmiguel", stars: 3, date: "2022-09-08 11:43:27", verifiedUser: false },
{ username: "julie07", stars: 3, date: "2021-03-14 23:54:10", verifiedUser: true },
{ username: "kelly93", stars: 3, date: "2022-11-05 12:45:43", verifiedUser: false },
{ username: "katherinereynolds", stars: 2, date: "2022-09-14 11:49:36", verifiedUser: false },
{ username: "chandlerkenneth", stars: 1, date: "2022-01-14 12:14:43", verifiedUser: true },
],
rareProperty: true,
},
schema: {
properties: {
id: {
type: "string",
},
name: {
type: "string",
},
price: {
type: "number",
},
category: {
type: "string",
},
description: {
type: "string",
},
stock: {
type: "number",
},
countryOfOrigin: {
type: "string",
},
firstAvailable: {
type: "string",
},
priceHistory: {
items: {
type: "number",
},
type: "array",
},
customerRatings: {
items: {
properties: {
username: {
type: "string",
},
stars: {
type: "number",
},
date: {
type: "string",
},
verifiedUser: {
type: "boolean",
},
},
type: "object",
},
type: "array",
},
rareProperty: {
type: "boolean",
},
},
type: "object",
},
},
};

View File

@@ -96,14 +96,6 @@ const readCollectionOfferWithARM = async (databaseId: string, collectionId: stri
? parseInt(resource.minimumThroughput)
: resource.minimumThroughput;
const autoscaleSettings = resource.autoscaleSettings;
const instantMaximumThroughput: number =
typeof resource.instantMaximumThroughput === "string"
? parseInt(resource.instantMaximumThroughput)
: resource.instantMaximumThroughput;
const softAllowedMaximumThroughput: number =
typeof resource.softAllowedMaximumThroughput === "string"
? parseInt(resource.softAllowedMaximumThroughput)
: resource.softAllowedMaximumThroughput;
if (autoscaleSettings) {
return {
@@ -112,8 +104,6 @@ const readCollectionOfferWithARM = async (databaseId: string, collectionId: stri
manualThroughput: undefined,
minimumThroughput,
offerReplacePending: resource.offerReplacePending === "true",
instantMaximumThroughput,
softAllowedMaximumThroughput,
};
}
@@ -123,8 +113,6 @@ const readCollectionOfferWithARM = async (databaseId: string, collectionId: stri
manualThroughput: resource.throughput,
minimumThroughput,
offerReplacePending: resource.offerReplacePending === "true",
instantMaximumThroughput,
softAllowedMaximumThroughput,
};
}

View File

@@ -68,14 +68,6 @@ const readDatabaseOfferWithARM = async (databaseId: string): Promise<Offer> => {
? parseInt(resource.minimumThroughput)
: resource.minimumThroughput;
const autoscaleSettings = resource.autoscaleSettings;
const instantMaximumThroughput: number =
typeof resource.instantMaximumThroughput === "string"
? parseInt(resource.instantMaximumThroughput)
: resource.instantMaximumThroughput;
const softAllowedMaximumThroughput: number =
typeof resource.softAllowedMaximumThroughput === "string"
? parseInt(resource.softAllowedMaximumThroughput)
: resource.softAllowedMaximumThroughput;
if (autoscaleSettings) {
return {
@@ -84,8 +76,6 @@ const readDatabaseOfferWithARM = async (databaseId: string): Promise<Offer> => {
manualThroughput: undefined,
minimumThroughput,
offerReplacePending: resource.offerReplacePending === "true",
instantMaximumThroughput,
softAllowedMaximumThroughput,
};
}
@@ -95,8 +85,6 @@ const readDatabaseOfferWithARM = async (databaseId: string): Promise<Offer> => {
manualThroughput: resource.throughput,
minimumThroughput,
offerReplacePending: resource.offerReplacePending === "true",
instantMaximumThroughput,
softAllowedMaximumThroughput,
};
}

View File

@@ -1,9 +1,8 @@
import { Resource, StoredProcedureDefinition } from "@azure/cosmos";
import { CloudError, SqlStoredProcedureListResult } from "Utils/arm/generatedClients/cosmos/types";
import { AuthType } from "../../AuthType";
import { userContext } from "../../UserContext";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import { listSqlStoredProcedures } from "../../Utils/arm/generatedClients/cosmos/sqlResources";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import { client } from "../CosmosClient";
import { handleError } from "../ErrorHandlingUtils";
@@ -25,13 +24,7 @@ export async function readStoredProcedures(
databaseId,
collectionId
);
const listResult = rpResponse as SqlStoredProcedureListResult;
if (listResult) {
return listResult?.value?.map((sproc) => sproc.properties?.resource as StoredProcedureDefinition & Resource);
}
const cloudError = rpResponse as CloudError;
throw new Error(cloudError?.error?.message);
return rpResponse?.value?.map((sproc) => sproc.properties?.resource as StoredProcedureDefinition & Resource);
}
const response = await client()

View File

@@ -242,8 +242,6 @@ export interface Offer {
minimumThroughput: number | undefined;
offerDefinition?: SDKOfferDefinition;
offerReplacePending: boolean;
instantMaximumThroughput?: number;
softAllowedMaximumThroughput?: number;
}
export interface SDKOfferDefinition extends Resource {

View File

@@ -11,9 +11,9 @@ import DeleteTriggerIcon from "../../images/DeleteTrigger.svg";
import DeleteUDFIcon from "../../images/DeleteUDF.svg";
import HostedTerminalIcon from "../../images/Hosted-Terminal.svg";
import * as ViewModels from "../Contracts/ViewModels";
import { useSidePanel } from "../hooks/useSidePanel";
import { userContext } from "../UserContext";
import { getCollectionName, getDatabaseName } from "../Utils/APITypeUtils";
import { useSidePanel } from "../hooks/useSidePanel";
import { TreeNodeMenuItem } from "./Controls/TreeComponent/TreeComponent";
import Explorer from "./Explorer";
import { useNotebook } from "./Notebook/useNotebook";
@@ -152,7 +152,7 @@ export const createStoreProcedureContextMenuItems = (
{
iconSrc: DeleteSprocIcon,
onClick: () => storedProcedure.delete(),
label: "Delete Stored Procedure",
label: "Delete Store Procedure",
},
];
};

View File

@@ -1,29 +1,46 @@
import { shallow } from "enzyme";
import React from "react";
import { IColumn, Text } from "@fluentui/react";
import {
PriceBreakdown,
changeFeedPolicyToolTip,
conflictResolutionCustomToolTip,
conflictResolutionLwwTooltip,
getAutoPilotV3SpendElement,
getEstimatedSpendingElement,
getRuPriceBreakdown,
getThroughputApplyDelayedMessage,
getThroughputApplyLongDelayMessage,
getThroughputApplyShortDelayMessage,
getToolTipContainer,
indexingPolicynUnsavedWarningMessage,
manualToAutoscaleDisclaimerElement,
mongoIndexTransformationRefreshingMessage,
mongoIndexingPolicyAADError,
mongoIndexingPolicyDisclaimer,
renderMongoIndexTransformationRefreshMessage,
ttlWarning,
indexingPolicynUnsavedWarningMessage,
updateThroughputBeyondLimitWarningMessage,
updateThroughputDelayedApplyWarningMessage,
getThroughputApplyDelayedMessage,
getThroughputApplyShortDelayMessage,
getThroughputApplyLongDelayMessage,
getToolTipContainer,
conflictResolutionCustomToolTip,
changeFeedPolicyToolTip,
conflictResolutionLwwTooltip,
mongoIndexingPolicyDisclaimer,
mongoIndexingPolicyAADError,
mongoIndexTransformationRefreshingMessage,
renderMongoIndexTransformationRefreshMessage,
ManualEstimatedSpendingDisplayProps,
PriceBreakdown,
getRuPriceBreakdown,
} from "./SettingsRenderUtils";
class SettingsRenderUtilsTestComponent extends React.Component {
public render(): JSX.Element {
const costElement: JSX.Element = <></>;
const estimatedSpendingColumns: IColumn[] = [
{ key: "costType", name: "", fieldName: "costType", minWidth: 100, maxWidth: 200, isResizable: true },
{ key: "hourly", name: "Hourly", fieldName: "hourly", minWidth: 100, maxWidth: 200, isResizable: true },
{ key: "daily", name: "Daily", fieldName: "daily", minWidth: 100, maxWidth: 200, isResizable: true },
{ key: "monthly", name: "Monthly", fieldName: "monthly", minWidth: 100, maxWidth: 200, isResizable: true },
];
const estimatedSpendingItems: ManualEstimatedSpendingDisplayProps[] = [
{
costType: <Text>Current Cost</Text>,
hourly: <Text>$ 1.02</Text>,
daily: <Text>$ 24.48</Text>,
monthly: <Text>$ 744.6</Text>,
},
];
const priceBreakdown: PriceBreakdown = {
hourlyPrice: 1.02,
dailyPrice: 24.48,
@@ -35,11 +52,17 @@ class SettingsRenderUtilsTestComponent extends React.Component {
return (
<>
{getEstimatedSpendingElement(costElement, 1000, 2, priceBreakdown, false)}
{getAutoPilotV3SpendElement(1000, false)}
{getAutoPilotV3SpendElement(undefined, false)}
{getAutoPilotV3SpendElement(1000, true)}
{getAutoPilotV3SpendElement(undefined, true)}
{getEstimatedSpendingElement(estimatedSpendingColumns, estimatedSpendingItems, 1000, 2, priceBreakdown, false)}
{manualToAutoscaleDisclaimerElement}
{ttlWarning}
{indexingPolicynUnsavedWarningMessage}
{updateThroughputBeyondLimitWarningMessage}
{updateThroughputDelayedApplyWarningMessage}
{getThroughputApplyDelayedMessage(false, 1000, "RU/s", "sampleDb", "sampleCollection", 2000)}

View File

@@ -1,7 +1,10 @@
import {
DetailsList,
DetailsListLayoutMode,
DetailsRow,
ICheckboxStyles,
IChoiceGroupStyles,
IColumn,
IDetailsColumnStyles,
IDetailsListStyles,
IDetailsRowProps,
@@ -17,6 +20,7 @@ import {
Link,
MessageBar,
MessageBarType,
SelectionMode,
Spinner,
SpinnerSize,
Stack,
@@ -24,7 +28,8 @@ import {
} from "@fluentui/react";
import * as React from "react";
import { StyleConstants, Urls } from "../../../Common/Constants";
import { hoursInAMonth } from "../../../Shared/Constants";
import { AutopilotDocumentation, hoursInAMonth } from "../../../Shared/Constants";
import * as AutoPilotUtils from "../../../Utils/AutoPilotUtils";
import {
computeRUUsagePriceHourly,
estimatedCostDisclaimer,
@@ -98,10 +103,6 @@ export const checkBoxAndInputStackProps: Partial<IStackProps> = {
tokens: { childrenGap: 10 },
};
export const relaxedSpacingStackProps: Partial<IStackProps> = {
tokens: { childrenGap: 20 },
};
export const toolTipLabelStackTokens: IStackTokens = {
childrenGap: 6,
};
@@ -173,6 +174,41 @@ export function onRenderRow(props: IDetailsRowProps): JSX.Element {
return <DetailsRow {...props} styles={transparentDetailsRowStyles} />;
}
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 getRuPriceBreakdown = (
throughput: number,
serverId: string,
@@ -202,7 +238,8 @@ export const getRuPriceBreakdown = (
};
export const getEstimatedSpendingElement = (
costElement: JSX.Element,
estimatedSpendingColumns: IColumn[],
estimatedSpendingItems: EstimatedSpendingDisplayProps[],
throughput: number,
numberOfRegions: number,
priceBreakdown: PriceBreakdown,
@@ -210,25 +247,22 @@ export const getEstimatedSpendingElement = (
): JSX.Element => {
const ruRange: string = isAutoscale ? throughput / 10 + " RU/s - " : "";
return (
<Stack>
<Text style={{ fontWeight: 600 }}>Cost estimate*</Text>
{costElement}
<Text style={{ fontWeight: 600, marginTop: 15 }}>How we calculate this</Text>
<Stack id="throughputSpendElement" style={{ marginTop: 5 }}>
<span>
{numberOfRegions} region{numberOfRegions > 1 && <span>s</span>}
</span>
<span>
{ruRange}
{throughput} RU/s
</span>
<span>
{priceBreakdown.currencySign}
{priceBreakdown.pricePerRu}/RU
</span>
</Stack>
<Text style={{ marginTop: 15 }}>
<em>*{estimatedCostDisclaimer}</em>
<Stack {...addMongoIndexStackProps} styles={mediumWidthStackStyles}>
<DetailsList
disableSelectionZone
items={estimatedSpendingItems}
columns={estimatedSpendingColumns}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
onRenderRow={onRenderRow}
/>
<Text id="throughputSpendElement">
({"regions: "} {numberOfRegions}, {ruRange}
{throughput} RU/s, {priceBreakdown.currencySign}
{priceBreakdown.pricePerRu}/RU)
</Text>
<Text>
<em>{estimatedCostDisclaimer}</em>
</Text>
</Stack>
);
@@ -259,6 +293,14 @@ export const indexingPolicynUnsavedWarningMessage: JSX.Element = (
</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
@@ -266,61 +308,6 @@ export const updateThroughputDelayedApplyWarningMessage: JSX.Element = (
</Text>
);
export const getUpdateThroughputBeyondInstantLimitMessage = (instantMaximumThroughput: number): JSX.Element => {
return (
<Text styles={infoAndToolTipTextStyle} id="updateThroughputDelayedApplyWarningMessage">
Scaling up will take 4-6 hours as it exceeds what Azure Cosmos DB can instantly support currently based on your
number of physical partitions. You can increase your throughput to {instantMaximumThroughput} instantly or proceed
with this value and wait until the scale-up is completed.
</Text>
);
};
export const getUpdateThroughputBeyondSupportLimitMessage = (
instantMaximumThroughput: number,
maximumThroughput: number
): JSX.Element => {
return (
<>
<Text styles={infoAndToolTipTextStyle} id="updateThroughputDelayedApplyWarningMessage">
Your request to increase throughput exceeds the pre-allocated capacity which may take longer than expected.
There are three options you can choose from to proceed:
</Text>
<ol style={{ fontSize: 14, color: "windowtext", marginTop: "5px" }}>
<li>You can instantly scale up to {instantMaximumThroughput} RU/s.</li>
{instantMaximumThroughput < maximumThroughput && (
<li>You can asynchronously scale up to any value under {maximumThroughput} RU/s in 4-6 hours.</li>
)}
<li>
Your current quota max is {maximumThroughput} RU/s. To go over this limit, you must request a quota increase
and the Azure Cosmos DB team will review.
<Link
href="https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/create-support-request-quota-increase"
target="_blank"
>
Learn more
</Link>
</li>
</ol>
</>
);
};
export const getUpdateThroughputBelowMinimumMessage = (minimum: number): JSX.Element => {
return (
<Text styles={infoAndToolTipTextStyle}>
You are not able to lower throughput below your current minimum of {minimum} RU/s. For more information on this
limit, please refer to our service quote documentation.
<Link
href="https://learn.microsoft.com/en-us/azure/cosmos-db/concepts-limits#minimum-throughput-limits"
target="_blank"
>
Learn more
</Link>
</Text>
);
};
export const saveThroughputWarningMessage: JSX.Element = (
<Text styles={infoAndToolTipTextStyle}>
Your bill will be affected as you update your throughput settings. Please review the updated cost estimate below
@@ -512,11 +499,7 @@ export const getTextFieldStyles = (current: isDirtyTypes, baseline: isDirtyTypes
},
});
export const getChoiceGroupStyles = (
current: isDirtyTypes,
baseline: isDirtyTypes,
isHorizontal?: boolean
): Partial<IChoiceGroupStyles> => ({
export const getChoiceGroupStyles = (current: isDirtyTypes, baseline: isDirtyTypes): Partial<IChoiceGroupStyles> => ({
flexContainer: [
{
selectors: {
@@ -533,8 +516,6 @@ export const getChoiceGroupStyles = (
padding: "2px 5px",
},
},
display: isHorizontal ? "inline-flex" : "default",
columnGap: isHorizontal ? "30px" : "default",
},
],
});

View File

@@ -3,6 +3,7 @@ import ko from "knockout";
import React from "react";
import * as Constants from "../../../../Common/Constants";
import * as DataModels from "../../../../Contracts/DataModels";
import * as SharedConstants from "../../../../Shared/Constants";
import { updateUserContext } from "../../../../UserContext";
import Explorer from "../../../Explorer";
import { throughputUnit } from "../SettingsRenderUtils";
@@ -11,6 +12,7 @@ import { ScaleComponent, ScaleComponentProps } from "./ScaleComponent";
import { ThroughputInputAutoPilotV3Component } from "./ThroughputInputComponents/ThroughputInputAutoPilotV3Component";
describe("ScaleComponent", () => {
const nonNationalCloudContainer = new Explorer();
const targetThroughput = 6000;
const baseProps: ScaleComponentProps = {
@@ -123,4 +125,11 @@ describe("ScaleComponent", () => {
scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.canThroughputExceedMaximumValue()).toEqual(true);
});
it("getThroughputWarningMessage", () => {
const throughputBeyondLimit = SharedConstants.CollectionCreation.DefaultCollectionRUs1Million + 1000;
const newProps = { ...baseProps, container: nonNationalCloudContainer, throughput: throughputBeyondLimit };
const scaleComponent = new ScaleComponent(newProps);
expect(scaleComponent.getThroughputWarningMessage().props.id).toEqual("updateThroughputBeyondLimitWarningMessage");
});
});

View File

@@ -1,7 +1,7 @@
import { Link, MessageBar, MessageBarType, Stack, Text, TextField } from "@fluentui/react";
import { Label, Link, MessageBar, MessageBarType, Stack, Text, TextField } from "@fluentui/react";
import * as React from "react";
import * as Constants from "../../../../Common/Constants";
import { Platform, configContext } from "../../../../ConfigContext";
import { configContext, Platform } from "../../../../ConfigContext";
import * as DataModels from "../../../../Contracts/DataModels";
import * as ViewModels from "../../../../Contracts/ViewModels";
import * as SharedConstants from "../../../../Shared/Constants";
@@ -15,6 +15,7 @@ import {
subComponentStackProps,
throughputUnit,
titleAndInputStackProps,
updateThroughputBeyondLimitWarningMessage,
} from "../SettingsRenderUtils";
import { hasDatabaseSharedThroughput } from "../SettingsUtils";
import { ThroughputInputAutoPilotV3Component } from "./ThroughputInputComponents/ThroughputInputAutoPilotV3Component";
@@ -67,6 +68,16 @@ export class ScaleComponent extends React.Component<ScaleComponentProps> {
return !!enableAutoScaleCapability;
};
private getStorageCapacityTitle = (): JSX.Element => {
const capacity: string = this.props.isFixedContainer ? "Fixed" : "Unlimited";
return (
<Stack {...titleAndInputStackProps}>
<Label>Storage capacity</Label>
<Text>{capacity}</Text>
</Stack>
);
};
public getMaxRUs = (): number => {
if (userContext.isTryCosmosDBSubscription) {
return Constants.TryCosmosExperience.maxRU;
@@ -120,6 +131,18 @@ export class ScaleComponent extends React.Component<ScaleComponentProps> {
return undefined;
};
public getThroughputWarningMessage = (): JSX.Element => {
const throughputExceedsBackendLimits: boolean =
this.canThroughputExceedMaximumValue() &&
this.props.throughput > SharedConstants.CollectionCreation.DefaultCollectionRUs1Million;
if (throughputExceedsBackendLimits && !this.props.isFixedContainer) {
return updateThroughputBeyondLimitWarningMessage;
}
return undefined;
};
public getLongDelayMessage = (): JSX.Element => {
const matches: string[] = this.props.initialNotification?.description.match(
`Throughput update for (.*) ${throughputUnit}`
@@ -165,10 +188,9 @@ export class ScaleComponent extends React.Component<ScaleComponentProps> {
spendAckChecked={false}
onScaleSaveableChange={this.props.onScaleSaveableChange}
onScaleDiscardableChange={this.props.onScaleDiscardableChange}
getThroughputWarningMessage={this.getThroughputWarningMessage}
usageSizeInKB={this.props.collection?.usageSizeInKB()}
throughputError={this.props.throughputError}
instantMaximumThroughput={this.offer?.instantMaximumThroughput}
softAllowedMaximumThroughput={this.offer?.softAllowedMaximumThroughput}
/>
);
@@ -207,7 +229,12 @@ export class ScaleComponent extends React.Component<ScaleComponentProps> {
{this.getInitialNotificationElement() && (
<MessageBar messageBarType={MessageBarType.warning}>{this.getInitialNotificationElement()}</MessageBar>
)}
{!this.isAutoScaleEnabled() && <Stack {...subComponentStackProps}>{this.getThroughputInputComponent()}</Stack>}
{!this.isAutoScaleEnabled() && (
<Stack {...subComponentStackProps}>
{this.getThroughputInputComponent()}
{!this.props.database && this.getStorageCapacityTitle()}
</Stack>
)}
{/* TODO: Replace link with call to the Azure Support blade */}
{this.isAutoScaleEnabled() && (

View File

@@ -311,15 +311,8 @@ export class SubSettingsComponent extends React.Component<SubSettingsComponentPr
)}
{userContext.apiType === "SQL" && this.isLargePartitionKeyEnabled() && (
<Text>Large {this.partitionKeyName.toLowerCase()} has been enabled.</Text>
<Text>Large {this.partitionKeyName.toLowerCase()} has been enabled</Text>
)}
{userContext.apiType === "SQL" &&
(this.isHierarchicalPartitionedContainer() ? (
<Text>Hierarchically partitioned container.</Text>
) : (
<Text>Non-hierarchically partitioned container.</Text>
))}
</Stack>
);
@@ -337,7 +330,6 @@ export class SubSettingsComponent extends React.Component<SubSettingsComponentPr
};
public isLargePartitionKeyEnabled = (): boolean => this.props.collection.partitionKey?.version >= 2;
public isHierarchicalPartitionedContainer = (): boolean => this.props.collection.partitionKey?.kind === "MultiHash";
public render(): JSX.Element {
return (

View File

@@ -42,8 +42,7 @@ describe("ThroughputInputAutoPilotV3Component", () => {
onScaleDiscardableChange: () => {
return;
},
instantMaximumThroughput: 5000,
softAllowedMaximumThroughput: 1000000,
getThroughputWarningMessage: () => undefined,
};
it("throughput input visible", () => {

View File

@@ -3,14 +3,10 @@ import {
ChoiceGroup,
FontIcon,
IChoiceGroupOption,
IProgressIndicatorStyles,
ISeparatorStyles,
IColumn,
Label,
Link,
MessageBar,
MessageBarType,
ProgressIndicator,
Separator,
Stack,
Text,
TextField,
@@ -27,24 +23,24 @@ import { autoPilotThroughput1K } from "../../../../../Utils/AutoPilotUtils";
import { calculateEstimateNumber, usageInGB } from "../../../../../Utils/PricingUtils";
import { Int32 } from "../../../../Panes/Tables/Validators/EntityPropertyValidationCommon";
import {
PriceBreakdown,
AutoscaleEstimatedSpendingDisplayProps,
checkBoxAndInputStackProps,
getAutoPilotV3SpendElement,
getChoiceGroupStyles,
getEstimatedSpendingElement,
getRuPriceBreakdown,
getTextFieldStyles,
getToolTipContainer,
getUpdateThroughputBelowMinimumMessage,
getUpdateThroughputBeyondInstantLimitMessage,
getUpdateThroughputBeyondSupportLimitMessage,
ManualEstimatedSpendingDisplayProps,
manualToAutoscaleDisclaimerElement,
messageBarStyles,
noLeftPaddingCheckBoxStyle,
relaxedSpacingStackProps,
PriceBreakdown,
saveThroughputWarningMessage,
titleAndInputStackProps,
transparentDetailsHeaderStyle,
} from "../../SettingsRenderUtils";
import { IsComponentDirtyResult, getSanitizedInputValue, isDirty } from "../../SettingsUtils";
import { getSanitizedInputValue, IsComponentDirtyResult, isDirty } from "../../SettingsUtils";
import { ToolTipLabelComponent } from "../ToolTipLabelComponent";
export interface ThroughputInputAutoPilotV3Props {
@@ -77,10 +73,9 @@ export interface ThroughputInputAutoPilotV3Props {
onMaxAutoPilotThroughputChange: (newThroughput: number) => void;
onScaleSaveableChange: (isScaleSaveable: boolean) => void;
onScaleDiscardableChange: (isScaleDiscardable: boolean) => void;
getThroughputWarningMessage: () => JSX.Element;
usageSizeInKB: number;
throughputError?: string;
instantMaximumThroughput: number;
softAllowedMaximumThroughput: number;
}
interface ThroughputInputAutoPilotV3State {
@@ -132,10 +127,7 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
} else if (this.props.isAutoPilotSelected) {
if (isDirty(this.props.maxAutoPilotThroughput, this.props.maxAutoPilotThroughputBaseline)) {
isDiscardable = true;
if (
this.props.maxAutoPilotThroughput <= this.props.softAllowedMaximumThroughput &&
AutoPilotUtils.isValidAutoPilotThroughput(this.props.maxAutoPilotThroughput)
) {
if (AutoPilotUtils.isValidAutoPilotThroughput(this.props.maxAutoPilotThroughput)) {
isSaveable = true;
}
}
@@ -194,15 +186,7 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
let estimatedSpend: JSX.Element;
if (this.props.isAutoPilotSelected) {
estimatedSpend = this.getEstimatedAutoscaleSpendElement(
this.props.maxAutoPilotThroughputBaseline,
userContext.portalEnv,
regions,
multimaster,
isDirty ? this.props.maxAutoPilotThroughput : undefined
);
} else {
if (!this.props.isAutoPilotSelected) {
estimatedSpend = this.getEstimatedManualSpendElement(
// if migrating from autoscale to manual, we use the autoscale RUs value as that is what will be set...
this.overrideWithAutoPilotSettings() ? this.props.maxAutoPilotThroughput : this.props.throughputBaseline,
@@ -211,6 +195,14 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
multimaster,
isDirty ? this.props.throughput : undefined
);
} else {
estimatedSpend = this.getEstimatedAutoscaleSpendElement(
this.props.maxAutoPilotThroughputBaseline,
userContext.portalEnv,
regions,
multimaster,
isDirty ? this.props.maxAutoPilotThroughput : undefined
);
}
return estimatedSpend;
};
@@ -223,8 +215,52 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
newThroughput?: number
): JSX.Element => {
const prices: PriceBreakdown = getRuPriceBreakdown(throughput, serverId, numberOfRegions, isMultimaster, true);
const estimatedSpendingColumns: IColumn[] = [
{
key: "costType",
name: "",
fieldName: "costType",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
{
key: "minPerMonth",
name: "Min Per Month",
fieldName: "minPerMonth",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
{
key: "maxPerMonth",
name: "Max Per Month",
fieldName: "maxPerMonth",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
];
const estimatedSpendingItems: AutoscaleEstimatedSpendingDisplayProps[] = [
{
costType: <Text>Current Cost</Text>,
minPerMonth: (
<Text>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice / 10)}
</Text>
),
maxPerMonth: (
<Text>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice)}
</Text>
),
},
];
const newThroughputCostElement = (): JSX.Element => {
if (newThroughput) {
const newPrices: PriceBreakdown = getRuPriceBreakdown(
newThroughput,
serverId,
@@ -232,40 +268,37 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
isMultimaster,
true
);
return (
<div>
<Text style={{ fontWeight: 600 }}>Updated cost per month</Text>
<Stack horizontal style={{ marginTop: 5, marginBottom: 10 }}>
<Text style={{ width: "50%" }}>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice / 10)} min
</Text>
<Text style={{ width: "50%" }}>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice)} max
</Text>
</Stack>
</div>
);
};
estimatedSpendingItems.unshift({
costType: (
<Text>
<b>Updated Cost</b>
</Text>
),
minPerMonth: (
<Text>
<b>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice / 10)}
</b>
</Text>
),
maxPerMonth: (
<Text>
<b>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice)}
</b>
</Text>
),
});
}
const costElement = (): JSX.Element => {
const prices: PriceBreakdown = getRuPriceBreakdown(throughput, serverId, numberOfRegions, isMultimaster, true);
return (
<Stack {...checkBoxAndInputStackProps} style={{ marginTop: 15 }}>
{newThroughput && newThroughputCostElement()}
<Text style={{ fontWeight: 600 }}>Current cost per month</Text>
<Stack horizontal style={{ marginTop: 5 }}>
<Text style={{ width: "50%" }}>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice / 10)} min
</Text>
<Text style={{ width: "50%" }}>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice)} max
</Text>
</Stack>
</Stack>
);
};
return getEstimatedSpendingElement(costElement(), newThroughput ?? throughput, numberOfRegions, prices, true);
return getEstimatedSpendingElement(
estimatedSpendingColumns,
estimatedSpendingItems,
newThroughput ?? throughput,
numberOfRegions,
prices,
true
);
};
private getEstimatedManualSpendElement = (
@@ -276,55 +309,122 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
newThroughput?: number
): JSX.Element => {
const prices: PriceBreakdown = getRuPriceBreakdown(throughput, serverId, numberOfRegions, isMultimaster, false);
const estimatedSpendingColumns: IColumn[] = [
{
key: "costType",
name: "",
fieldName: "costType",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
{
key: "hourly",
name: "Hourly",
fieldName: "hourly",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
{
key: "daily",
name: "Daily",
fieldName: "daily",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
{
key: "monthly",
name: "Monthly",
fieldName: "monthly",
minWidth: 100,
maxWidth: 200,
isResizable: true,
styles: transparentDetailsHeaderStyle,
},
];
const estimatedSpendingItems: ManualEstimatedSpendingDisplayProps[] = [
{
costType: <Text>Current Cost</Text>,
hourly: (
<Text>
{prices.currencySign} {calculateEstimateNumber(prices.hourlyPrice)}
</Text>
),
daily: (
<Text>
{prices.currencySign} {calculateEstimateNumber(prices.dailyPrice)}
</Text>
),
monthly: (
<Text>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice)}
</Text>
),
},
];
const newThroughputCostElement = (): JSX.Element => {
if (newThroughput) {
const newPrices: PriceBreakdown = getRuPriceBreakdown(
newThroughput,
serverId,
numberOfRegions,
isMultimaster,
true
false
);
return (
<div>
<Text style={{ fontWeight: 600 }}>Updated cost per month</Text>
<Stack horizontal style={{ marginTop: 5, marginBottom: 10 }}>
<Text style={{ width: "33%" }}>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.hourlyPrice)}/hr
</Text>
<Text style={{ width: "33%" }}>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.dailyPrice)}/day
</Text>
<Text style={{ width: "33%" }}>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice)}/mo
</Text>
</Stack>
</div>
);
};
estimatedSpendingItems.unshift({
costType: (
<Text>
<b>Updated Cost</b>
</Text>
),
hourly: (
<Text>
<b>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.hourlyPrice)}
</b>
</Text>
),
daily: (
<Text>
<b>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.dailyPrice)}
</b>
</Text>
),
monthly: (
<Text>
<b>
{newPrices.currencySign} {calculateEstimateNumber(newPrices.monthlyPrice)}
</b>
</Text>
),
});
}
const costElement = (): JSX.Element => {
const prices: PriceBreakdown = getRuPriceBreakdown(throughput, serverId, numberOfRegions, isMultimaster, true);
return (
<Stack {...checkBoxAndInputStackProps} style={{ marginTop: 15 }}>
{newThroughput && newThroughputCostElement()}
<Text style={{ fontWeight: 600 }}>Current cost per month</Text>
<Stack horizontal style={{ marginTop: 5 }}>
<Text style={{ width: "33%" }}>
{prices.currencySign} {calculateEstimateNumber(prices.hourlyPrice)}/hr
</Text>
<Text style={{ width: "33%" }}>
{prices.currencySign} {calculateEstimateNumber(prices.dailyPrice)}/day
</Text>
<Text style={{ width: "33%" }}>
{prices.currencySign} {calculateEstimateNumber(prices.monthlyPrice)}/mo
</Text>
</Stack>
</Stack>
);
};
return getEstimatedSpendingElement(
estimatedSpendingColumns,
estimatedSpendingItems,
newThroughput ?? throughput,
numberOfRegions,
prices,
false
);
};
return getEstimatedSpendingElement(costElement(), newThroughput ?? throughput, numberOfRegions, prices, false);
private getAutoPilotUsageCost = (): JSX.Element => {
if (!this.props.maxAutoPilotThroughput) {
return <></>;
}
return getAutoPilotV3SpendElement(
this.props.maxAutoPilotThroughput,
false /* isDatabaseThroughput */,
!this.props.isEmulator ? this.getRequestUnitsUsageCost() : <></>
);
};
private onAutoPilotThroughputChange = (
@@ -411,7 +511,7 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
onChange={this.onChoiceGroupChange}
required={this.props.showAsMandatory}
ariaLabelledBy={labelId}
styles={getChoiceGroupStyles(this.props.wasAutopilotOriginallySet, this.props.isAutoPilotSelected, true)}
styles={getChoiceGroupStyles(this.props.wasAutopilotOriginallySet, this.props.isAutoPilotSelected)}
/>
</Stack>
);
@@ -420,266 +520,97 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
private onSpendAckChecked = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean): void =>
this.setState({ spendAckChecked: checked });
private getStorageCapacityTitle = (): JSX.Element => {
const capacity: string = this.props.isFixed ? "Fixed" : "Unlimited";
return (
<Stack {...titleAndInputStackProps}>
<Label>Storage capacity</Label>
<Text>{capacity}</Text>
</Stack>
);
};
private thoughputRangeSeparatorStyles: Partial<ISeparatorStyles> = {
root: [
{
selectors: {
"::before": {
backgroundColor: "rgb(200, 200, 200)",
height: "3px",
marginTop: "-1px",
},
},
},
],
};
private currentThroughputValue = (): number => {
return this.props.isAutoPilotSelected
? this.props.maxAutoPilotThroughput
: this.overrideWithAutoPilotSettings()
? this.props.maxAutoPilotThroughputBaseline
: this.props.throughput;
};
private getCurrentRuRange = (): "below" | "instant" | "delayed" | "requireSupport" => {
if (this.currentThroughputValue() < this.props.minimum) {
return "below";
}
if (
this.currentThroughputValue() >= this.props.minimum &&
this.currentThroughputValue() <= this.props.instantMaximumThroughput
) {
return "instant";
}
if (this.currentThroughputValue() > this.props.softAllowedMaximumThroughput) {
return "requireSupport";
}
return "delayed";
};
private getRuThermometerStyles = (): Partial<IProgressIndicatorStyles> => ({
progressBar: [
{
backgroundColor:
this.getCurrentRuRange() === "instant"
? "rgb(0, 120, 212)"
: this.getCurrentRuRange() === "delayed"
? "rgb(255 216 109)"
: "rgb(251, 217, 203)",
},
],
});
private getRuThermometerPercentValue = (): number => {
let percentValue: number;
const currentRus = this.currentThroughputValue();
switch (this.getCurrentRuRange()) {
case "below":
percentValue = 0;
break;
case "instant": {
const percentOfInstantRange: number = currentRus / this.props.instantMaximumThroughput;
percentValue = percentOfInstantRange * 0.34;
break;
}
case "delayed": {
const adjustedMax = this.props.softAllowedMaximumThroughput - this.props.instantMaximumThroughput;
const adjustedRus = currentRus - this.props.instantMaximumThroughput;
const percentOfDelayedRange = adjustedRus / adjustedMax;
const adjustedPercent = percentOfDelayedRange * 0.66;
percentValue = adjustedPercent + 0.34;
break;
}
default:
// over maximum
percentValue = 1;
}
return percentValue;
};
private getRUThermometer = (): JSX.Element => (
<Stack>
<Stack horizontal>
<Stack.Item style={{ width: "34%" }}>
<span>{this.props.minimum.toLocaleString()}</span>
</Stack.Item>
<Stack.Item style={{ width: "66%" }}>
<span style={{ float: "left", transform: "translateX(-50%)" }}>
{this.props.instantMaximumThroughput.toLocaleString()}
</span>
<span style={{ float: "right" }}>{this.props.softAllowedMaximumThroughput.toLocaleString()}</span>
</Stack.Item>
</Stack>
<ProgressIndicator
barHeight={20}
percentComplete={this.getRuThermometerPercentValue()}
styles={this.getRuThermometerStyles()}
/>
<Stack horizontal>
<Stack.Item style={{ width: "34%", paddingRight: "5px" }}>
<Separator styles={this.thoughputRangeSeparatorStyles}>Instant</Separator>
</Stack.Item>
<Stack.Item style={{ width: "66%", paddingLeft: "5px" }}>
<Separator styles={this.thoughputRangeSeparatorStyles}>4-6 hrs</Separator>
</Stack.Item>
</Stack>
</Stack>
);
private showThroughputWarning = (): boolean => {
return (
this.currentThroughputValue() > this.props.instantMaximumThroughput ||
this.currentThroughputValue() < this.props.minimum
);
};
private getThroughputWarningMessageText = (): JSX.Element => {
switch (this.getCurrentRuRange()) {
case "below":
return getUpdateThroughputBelowMinimumMessage(this.props.minimum);
case "delayed":
return getUpdateThroughputBeyondInstantLimitMessage(this.props.instantMaximumThroughput);
case "requireSupport":
return getUpdateThroughputBeyondSupportLimitMessage(
this.props.instantMaximumThroughput,
this.props.softAllowedMaximumThroughput
);
default:
return <></>;
}
};
private getThroughputWarningMessageBar = (): JSX.Element => {
const isSevereWarning: boolean =
this.currentThroughputValue() > this.props.softAllowedMaximumThroughput ||
this.currentThroughputValue() < this.props.minimum;
return (
<MessageBar messageBarType={isSevereWarning ? MessageBarType.severeWarning : MessageBarType.warning}>
{this.getThroughputWarningMessageText()}
</MessageBar>
);
};
private getThroughputTextField = (): JSX.Element => (
private renderAutoPilotInput = (): JSX.Element => (
<>
{this.props.isAutoPilotSelected ? (
<TextField
label="Maximum RU/s required by this resource"
required
type="number"
id="autopilotInput"
key="auto pilot throughput input"
styles={getTextFieldStyles(this.props.maxAutoPilotThroughput, this.props.maxAutoPilotThroughputBaseline)}
disabled={this.overrideWithProvisionedThroughputSettings()}
step={AutoPilotUtils.autoPilotIncrementStep}
value={this.overrideWithProvisionedThroughputSettings() ? "" : this.props.maxAutoPilotThroughput?.toString()}
onChange={this.onAutoPilotThroughputChange}
min={autoPilotThroughput1K}
onGetErrorMessage={(value: string) => {
const sanitizedValue = getSanitizedInputValue(value);
return sanitizedValue % 1000
? "Throughput value must be in increments of 1000"
: this.props.throughputError;
}}
validateOnLoad={false}
/>
) : (
<TextField
required
type="number"
id="throughputInput"
key="provisioned throughput input"
styles={getTextFieldStyles(this.props.throughput, this.props.throughputBaseline)}
disabled={this.overrideWithAutoPilotSettings()}
step={this.step}
value={
this.overrideWithAutoPilotSettings()
? this.props.maxAutoPilotThroughputBaseline?.toString()
: this.props.throughput?.toString()
}
onChange={this.onThroughputChange}
min={this.props.minimum}
errorMessage={this.props.throughputError}
<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={AutoPilotUtils.autoPilotIncrementStep}
value={this.overrideWithProvisionedThroughputSettings() ? "" : this.props.maxAutoPilotThroughput?.toString()}
onChange={this.onAutoPilotThroughputChange}
min={autoPilotThroughput1K}
errorMessage={this.props.throughputError}
/>
{!this.overrideWithProvisionedThroughputSettings() && this.getAutoPilotUsageCost()}
{this.minRUperGBSurvey()}
{this.props.spendAckVisible && (
<Checkbox
id="spendAckCheckBox"
styles={noLeftPaddingCheckBoxStyle}
label={this.props.spendAckText}
checked={this.state.spendAckChecked}
onChange={this.onSpendAckChecked}
/>
)}
{this.props.isFixed && <p>When using a collection with fixed storage capacity, you can set up to 10,000 RU/s.</p>}
</>
);
private renderThroughputComponent = (): JSX.Element => (
<Stack horizontal>
<Stack.Item style={{ width: "70%", maxWidth: "700px" }}>
<Stack {...relaxedSpacingStackProps} style={{ paddingRight: "50px" }}>
{this.getThroughputTextField()}
{this.props.instantMaximumThroughput && (
<Stack>
{this.getRUThermometer()}
{this.showThroughputWarning() && this.getThroughputWarningMessageBar()}
</Stack>
)}
{this.props.isAutoPilotSelected ? (
<Text style={{ marginTop: "40px" }}>
Based on usage, your {this.props.collectionName ? "container" : "database"} throughput will scale from{" "}
<b>
{AutoPilotUtils.getMinRUsBasedOnUserInput(this.props.maxAutoPilotThroughput)} RU/s (10% of max RU/s) -{" "}
{this.props.maxAutoPilotThroughput} RU/s
</b>
<br />
</Text>
) : (
<>
{this.state.exceedFreeTierThroughput && (
<MessageBar
messageBarIconProps={{ iconName: "WarningSolid", className: "messageBarWarningIcon" }}
styles={messageBarStyles}
style={{ marginTop: "40px" }}
>
{`Billing will apply if you provision more than ${SharedConstants.FreeTierLimits.RU} RU/s of manual throughput, or if the resource scales beyond ${SharedConstants.FreeTierLimits.RU} RU/s with autoscale.`}
</MessageBar>
)}
</>
)}
{!this.overrideWithProvisionedThroughputSettings() && (
<Text>
Estimate your required RU/s with
<Link target="_blank" href="https://cosmos.azure.com/capacitycalculator/">
{` capacity calculator`} <FontIcon iconName="NavigateExternalInline" />
</Link>
</Text>
)}
{this.minRUperGBSurvey()}
{this.props.spendAckVisible && (
<Checkbox
id="spendAckCheckBox"
styles={noLeftPaddingCheckBoxStyle}
label={this.props.spendAckText}
checked={this.state.spendAckChecked}
onChange={this.onSpendAckChecked}
/>
)}
{this.props.isFixed && (
<p>When using a collection with fixed storage capacity, you can set up to 10,000 RU/s.</p>
)}
{this.props.collectionName && (
<Stack.Item style={{ marginTop: "40px" }}>{this.getStorageCapacityTitle()}</Stack.Item>
)}
</Stack>
</Stack.Item>
<Stack.Item style={{ width: "30%", maxWidth: "300px" }}>
{!this.props.isEmulator ? this.getRequestUnitsUsageCost() : <></>}
</Stack.Item>
private renderThroughputInput = (): JSX.Element => (
<Stack {...titleAndInputStackProps}>
<Text>
Estimate your required throughput with
<Link target="_blank" href="https://cosmos.azure.com/capacitycalculator/">
{` capacity calculator`} <FontIcon iconName="NavigateExternalInline" />
</Link>
</Text>
<TextField
required
type="number"
id="throughputInput"
key="provisioned throughput input"
styles={getTextFieldStyles(this.props.throughput, this.props.throughputBaseline)}
disabled={this.overrideWithAutoPilotSettings()}
step={this.step}
value={
this.overrideWithAutoPilotSettings()
? this.props.maxAutoPilotThroughputBaseline?.toString()
: this.props.throughput?.toString()
}
onChange={this.onThroughputChange}
min={this.props.minimum}
errorMessage={this.props.throughputError}
/>
{this.state.exceedFreeTierThroughput && (
<MessageBar
messageBarIconProps={{ iconName: "WarningSolid", className: "messageBarWarningIcon" }}
styles={messageBarStyles}
>
{`Billing will apply if you provision more than ${SharedConstants.FreeTierLimits.RU} RU/s of manual throughput, or if the resource scales beyond ${SharedConstants.FreeTierLimits.RU} RU/s with autoscale.`}
</MessageBar>
)}
{this.props.getThroughputWarningMessage() && (
<MessageBar
messageBarIconProps={{ iconName: "InfoSolid", className: "messageBarInfoIcon" }}
styles={messageBarStyles}
>
{this.props.getThroughputWarningMessage()}
</MessageBar>
)}
{!this.props.isEmulator && this.getRequestUnitsUsageCost()}
{this.minRUperGBSurvey()}
{this.props.spendAckVisible && (
<Checkbox
id="spendAckCheckBox"
styles={noLeftPaddingCheckBoxStyle}
label={this.props.spendAckText}
checked={this.state.spendAckChecked}
onChange={this.onSpendAckChecked}
/>
)}
<br />
{this.props.isFixed && <p>When using a collection with fixed storage capacity, you can set up to 10,000 RU/s.</p>}
</Stack>
);
@@ -709,7 +640,7 @@ export class ThroughputInputAutoPilotV3Component extends React.Component<
{this.renderWarningMessage()}
{this.renderThroughputModeChoices()}
{this.renderThroughputComponent()}
{this.props.isAutoPilotSelected ? this.renderAutoPilotInput() : this.renderThroughputInput()}
</Stack>
);
}

View File

@@ -28,8 +28,6 @@ exports[`ConflictResolutionComponent Path text field displayed 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": undefined,
@@ -102,8 +100,6 @@ exports[`ConflictResolutionComponent Sproc text field displayed 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",

View File

@@ -39,6 +39,7 @@ exports[`ScaleComponent renders with correct initial notification 1`] = `
canExceedMaximumValue={true}
collectionName="test"
databaseName="test"
getThroughputWarningMessage={[Function]}
isAutoPilotSelected={false}
isEmulator={false}
isEnabled={true}
@@ -59,6 +60,20 @@ exports[`ScaleComponent renders with correct initial notification 1`] = `
usageSizeInKB={100}
wasAutopilotOriginallySet={true}
/>
<Stack
tokens={
Object {
"childrenGap": 5,
}
}
>
<StyledLabelBase>
Storage capacity
</StyledLabelBase>
<Text>
Unlimited
</Text>
</Stack>
</Stack>
</Stack>
`;

View File

@@ -40,8 +40,6 @@ exports[`SubSettingsComponent analyticalTimeToLive hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -108,8 +106,6 @@ exports[`SubSettingsComponent analyticalTimeToLive hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -172,8 +168,6 @@ exports[`SubSettingsComponent analyticalTimeToLive hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -224,10 +218,7 @@ exports[`SubSettingsComponent analyticalTimeToLive hidden 1`] = `
<Text>
Large
partition key
has been enabled.
</Text>
<Text>
Non-hierarchically partitioned container.
has been enabled
</Text>
</Stack>
</Stack>
@@ -273,8 +264,6 @@ exports[`SubSettingsComponent analyticalTimeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -341,8 +330,6 @@ exports[`SubSettingsComponent analyticalTimeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -395,8 +382,6 @@ exports[`SubSettingsComponent analyticalTimeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": undefined,
@@ -460,8 +445,6 @@ exports[`SubSettingsComponent analyticalTimeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -512,10 +495,7 @@ exports[`SubSettingsComponent analyticalTimeToLiveSeconds hidden 1`] = `
<Text>
Large
partition key
has been enabled.
</Text>
<Text>
Non-hierarchically partitioned container.
has been enabled
</Text>
</Stack>
</Stack>
@@ -561,8 +541,6 @@ exports[`SubSettingsComponent changeFeedPolicy hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -629,8 +607,6 @@ exports[`SubSettingsComponent changeFeedPolicy hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -683,8 +659,6 @@ exports[`SubSettingsComponent changeFeedPolicy hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -760,10 +734,7 @@ exports[`SubSettingsComponent changeFeedPolicy hidden 1`] = `
<Text>
Large
partition key
has been enabled.
</Text>
<Text>
Non-hierarchically partitioned container.
has been enabled
</Text>
</Stack>
</Stack>
@@ -809,8 +780,6 @@ exports[`SubSettingsComponent renders 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -877,8 +846,6 @@ exports[`SubSettingsComponent renders 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -931,8 +898,6 @@ exports[`SubSettingsComponent renders 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -1021,8 +986,6 @@ exports[`SubSettingsComponent renders 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -1073,10 +1036,7 @@ exports[`SubSettingsComponent renders 1`] = `
<Text>
Large
partition key
has been enabled.
</Text>
<Text>
Non-hierarchically partitioned container.
has been enabled
</Text>
</Stack>
</Stack>
@@ -1122,8 +1082,6 @@ exports[`SubSettingsComponent timeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": undefined,
@@ -1165,8 +1123,6 @@ exports[`SubSettingsComponent timeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -1219,8 +1175,6 @@ exports[`SubSettingsComponent timeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -1309,8 +1263,6 @@ exports[`SubSettingsComponent timeToLiveSeconds hidden 1`] = `
Object {
"flexContainer": Array [
Object {
"columnGap": "default",
"display": "default",
"selectors": Object {
".ms-ChoiceField-field.is-checked::after": Object {
"borderColor": "",
@@ -1361,10 +1313,7 @@ exports[`SubSettingsComponent timeToLiveSeconds hidden 1`] = `
<Text>
Large
partition key
has been enabled.
</Text>
<Text>
Non-hierarchically partitioned container.
has been enabled
</Text>
</Stack>
</Stack>

View File

@@ -2,60 +2,154 @@
exports[`SettingsUtils functions render 1`] = `
<Fragment>
<Stack>
<Text
style={
Object {
"fontWeight": 600,
}
}
<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"
>
Cost estimate*
</Text>
<Text
style={
Object {
"fontWeight": 600,
"marginTop": 15,
}
}
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"
>
How we calculate this
</Text>
<Stack
Learn more
</StyledLinkBase>
.
</Text>
<Stack
styles={
Object {
"root": Object {
"width": 600,
},
}
}
tokens={
Object {
"childrenGap": 10,
}
}
>
<StyledWithViewportComponent
columns={
Array [
Object {
"fieldName": "costType",
"isResizable": true,
"key": "costType",
"maxWidth": 200,
"minWidth": 100,
"name": "",
},
Object {
"fieldName": "hourly",
"isResizable": true,
"key": "hourly",
"maxWidth": 200,
"minWidth": 100,
"name": "Hourly",
},
Object {
"fieldName": "daily",
"isResizable": true,
"key": "daily",
"maxWidth": 200,
"minWidth": 100,
"name": "Daily",
},
Object {
"fieldName": "monthly",
"isResizable": true,
"key": "monthly",
"maxWidth": 200,
"minWidth": 100,
"name": "Monthly",
},
]
}
disableSelectionZone={true}
items={
Array [
Object {
"costType": <Text>
Current Cost
</Text>,
"daily": <Text>
$ 24.48
</Text>,
"hourly": <Text>
$ 1.02
</Text>,
"monthly": <Text>
$ 744.6
</Text>,
},
]
}
layoutMode={1}
onRenderRow={[Function]}
selectionMode={0}
/>
<Text
id="throughputSpendElement"
style={
Object {
"marginTop": 5,
}
}
>
<span>
2
region
<span>
s
</span>
</span>
<span>
1000
RU/s
</span>
<span>
¥
0.00051
/RU
</span>
</Stack>
<Text
style={
Object {
"marginTop": 15,
}
}
>
(
regions:
2
,
1000
RU/s,
¥
0.00051
/RU)
</Text>
<Text>
<em>
*
This cost is an estimate and may vary based on the regions where your account is deployed and potential discounts applied to your account
</em>
</Text>
@@ -111,6 +205,19 @@ exports[`SettingsUtils functions render 1`] = `
>
You have not saved the latest changes made to your indexing policy. Please click save to confirm the changes.
</Text>
<Text
id="updateThroughputBeyondLimitWarningMessage"
styles={
Object {
"root": Object {
"color": "windowtext",
"fontSize": 14,
},
}
}
>
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={

View File

@@ -22,17 +22,10 @@ export class ContainerSampleGenerator {
/**
* Factory function to load the json data file
*/
public static async createSampleGeneratorAsync(
container: Explorer,
isCopilot?: boolean
): Promise<ContainerSampleGenerator> {
public static async createSampleGeneratorAsync(container: Explorer): Promise<ContainerSampleGenerator> {
const generator = new ContainerSampleGenerator(container);
let dataFileContent: any;
if (isCopilot) {
dataFileContent = await import(
/* webpackChunkName: "queryCopilotSampleData" */ "../../../sampleData/queryCopilotSampleData.json"
);
} else if (userContext.apiType === "Gremlin") {
if (userContext.apiType === "Gremlin") {
dataFileContent = await import(
/* webpackChunkName: "gremlinSampleJsonData" */ "../../../sampleData/gremlinSampleData.json"
);

View File

@@ -6,9 +6,9 @@ import * as React from "react";
import LoadGraphIcon from "../../../../images/LoadGraph.png";
import LoadingIndicatorIcon from "../../../../images/LoadingIndicator_3Squares.gif";
import * as Constants from "../../../Common/Constants";
import { getErrorMessage } from "../../../Common/ErrorHandlingUtils";
import { queryDocuments } from "../../../Common/dataAccess/queryDocuments";
import { queryDocumentsPage } from "../../../Common/dataAccess/queryDocumentsPage";
import { getErrorMessage } from "../../../Common/ErrorHandlingUtils";
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
import { InputProperty } from "../../../Contracts/ViewModels";
@@ -182,8 +182,7 @@ export class GraphExplorer extends React.Component<GraphExplorerProps, GraphExpl
public static readonly WITHOUT_STEP_ARGS_MAX_CHARS = 10000; // maximums char size of the without() step parameter
public static readonly ROOT_LIST_PAGE_SIZE = 100;
private static readonly MAX_LATEST_QUERIES = 10;
// TODO This prevents loading too much data in GraphExplorer and d3. A better is to cap the size of the result, rather than the number of items in the array.
private static readonly MAX_RESULT_SIZE = 100_000;
private static readonly MAX_RESULT_SIZE = 10000;
private static readonly TAB_INDEX_JSON = 0;
private static readonly TAB_INDEX_GRAPH = 1;

View File

@@ -31,7 +31,7 @@ export class GremlinClient {
public client: GremlinSimpleClient;
public pendingResults: Map<string, PendingResultData>; // public for testing purposes
private maxResultSize: number;
private static readonly PENDING_REQUEST_TIMEOUT_MS = 1 /* hour */ * 3_600 /* seconds */ * 1_000 /* ms */;
private static readonly PENDING_REQUEST_TIMEOUT_MS = 6 /* minutes */ * 60 /* seconds */ * 1000 /* ms */;
private static readonly TIMEOUT_ERROR_MSG = `Pending request timed out (${GremlinClient.PENDING_REQUEST_TIMEOUT_MS} ms)`;
private static readonly LOG_AREA = "GremlinClient";

View File

@@ -57,7 +57,7 @@ const SharedDatabaseDefault: DataModels.IndexingPolicy = {
],
};
export const AllPropertiesIndexed: DataModels.IndexingPolicy = {
const AllPropertiesIndexed: DataModels.IndexingPolicy = {
indexingMode: "consistent",
automatic: true,
includedPaths: [
@@ -634,18 +634,18 @@ export class AddCollectionPanel extends React.Component<AddCollectionPanelProps,
{userContext.apiType === "SQL" && (
<Stack className="panelGroupSpacing">
<DefaultButton
styles={{ root: { padding: 0, width: 200, height: 30 }, label: { fontSize: 12 } }}
styles={{ root: { padding: 0, width: 250, height: 30 }, label: { fontSize: 12 } }}
hidden={this.state.useHashV1}
disabled={this.state.subPartitionKeys.length >= Constants.BackendDefaults.maxNumMultiHashPartition}
onClick={() => this.setState({ subPartitionKeys: [...this.state.subPartitionKeys, ""] })}
>
Add hierarchical partition key
Add hierarchical partition key (preview)
</DefaultButton>
{this.state.subPartitionKeys.length > 0 && (
<Text variant="small">
<Icon iconName="InfoSolid" className="removeIcon" tabIndex={0} /> This feature allows you to
partition your data with up to three levels of keys for better data distribution. Requires .NET
V3, Java V4 SDK, or preview JavaScript V3 SDK.{" "}
partition your data with up to three levels of keys for better data distribution. Requires preview
version of .NET V3 or Java V4 SDK.{" "}
<Link href="https://aka.ms/cosmos-hierarchical-partitioning" target="_blank">
Learn more
</Link>

View File

@@ -32,14 +32,8 @@ export const PanelInfoErrorComponent: React.FunctionComponent<PanelInfoErrorProp
return (
<Stack className="panelInfoErrorContainer" horizontal verticalAlign="center">
{icon}
<span className="panelWarningErrorDetailsLinkContainer">
<Text
role="alert"
aria-live="assertive"
aria-label={message}
className="panelWarningErrorMessage"
variant="small"
>
<span className="panelWarningErrorDetailsLinkContainer" role="alert" aria-live="assertive">
<Text aria-label={message} className="panelWarningErrorMessage" variant="small">
{message}
{link && linkText && (
<Link target="_blank" href={link}>

View File

@@ -4,11 +4,11 @@ import React, { FunctionComponent, useState } from "react";
import { Areas, SavedQueries } from "../../../Common/Constants";
import { getErrorMessage, getErrorStack } from "../../../Common/ErrorHandlingUtils";
import { Query } from "../../../Contracts/DataModels";
import { useSidePanel } from "../../../hooks/useSidePanel";
import { useTabs } from "../../../hooks/useTabs";
import { Action } from "../../../Shared/Telemetry/TelemetryConstants";
import { traceFailure, traceStart, traceSuccess } from "../../../Shared/Telemetry/TelemetryProcessor";
import { logConsoleError } from "../../../Utils/NotificationConsoleUtils";
import { useSidePanel } from "../../../hooks/useSidePanel";
import { useTabs } from "../../../hooks/useTabs";
import Explorer from "../../Explorer";
import { NewQueryTab } from "../../Tabs/QueryTab/QueryTab";
import { useDatabases } from "../../useDatabases";
@@ -16,13 +16,9 @@ import { RightPaneForm, RightPaneFormProps } from "../RightPaneForm/RightPaneFor
interface SaveQueryPaneProps {
explorer: Explorer;
queryToSave?: string;
}
export const SaveQueryPane: FunctionComponent<SaveQueryPaneProps> = ({
explorer,
queryToSave,
}: SaveQueryPaneProps): JSX.Element => {
export const SaveQueryPane: FunctionComponent<SaveQueryPaneProps> = ({ explorer }: SaveQueryPaneProps): JSX.Element => {
const closeSidePanel = useSidePanel((state) => state.closeSidePanel);
const [isLoading, { setTrue: setLoadingTrue, setFalse: setLoadingFalse }] = useBoolean(false);
const [formError, setFormError] = useState<string>("");
@@ -40,7 +36,7 @@ export const SaveQueryPane: FunctionComponent<SaveQueryPaneProps> = ({
}
const queryTab = useTabs.getState().activeTab as NewQueryTab;
const query: string = queryToSave || queryTab?.iTabAccessor.onSaveClickEvent();
const query: string = queryTab && queryTab.iTabAccessor.onSaveClickEvent();
if (!queryName || queryName.length === 0) {
setFormError("No query name specified");
@@ -66,8 +62,8 @@ export const SaveQueryPane: FunctionComponent<SaveQueryPaneProps> = ({
try {
await explorer.queriesClient.saveQuery(queryParam);
setLoadingFalse();
queryTab?.tabTitle(queryParam.queryName);
queryTab?.tabPath(`${queryTab.collection.databaseId}>${queryTab.collection.id()}>${queryParam.queryName}`);
queryTab.tabTitle(queryParam.queryName);
queryTab.tabPath(`${queryTab.collection.databaseId}>${queryTab.collection.id()}>${queryParam.queryName}`);
traceSuccess(
Action.SaveQuery,
{

View File

@@ -254,12 +254,12 @@ exports[`AddCollectionPanel should render Default properly 1`] = `
"root": Object {
"height": 30,
"padding": 0,
"width": 200,
"width": 250,
},
}
}
>
Add hierarchical partition key
Add hierarchical partition key (preview)
</CustomizedDefaultButton>
</Stack>
</Stack>

View File

@@ -1,11 +0,0 @@
import { shallow } from "enzyme";
import React from "react";
import Explorer from "../Explorer";
import { QueryCopilotCarousel } from "./CopilotCarousel";
describe("Query Copilot Carousel snapshot test", () => {
it("should render when isOpen is true", () => {
const wrapper = shallow(<QueryCopilotCarousel isOpen={true} explorer={new Explorer()} />);
expect(wrapper).toMatchSnapshot();
});
});

View File

@@ -1,277 +0,0 @@
import {
DefaultButton,
ISeparatorStyles,
IconButton,
Image,
Link,
Modal,
PrimaryButton,
Separator,
Spinner,
Stack,
Text,
} from "@fluentui/react";
import { QueryCopilotSampleDatabaseId, StyleConstants } from "Common/Constants";
import { handleError } from "Common/ErrorHandlingUtils";
import { createCollection } from "Common/dataAccess/createCollection";
import * as DataModels from "Contracts/DataModels";
import { ContainerSampleGenerator } from "Explorer/DataSamples/ContainerSampleGenerator";
import Explorer from "Explorer/Explorer";
import { AllPropertiesIndexed } from "Explorer/Panes/AddCollectionPanel";
import { PromptCard } from "Explorer/QueryCopilot/PromptCard";
import { useDatabases } from "Explorer/useDatabases";
import { useCarousel } from "hooks/useCarousel";
import { ReactTabKind, useTabs } from "hooks/useTabs";
import React, { useState } from "react";
import YoutubePlaceholder from "../../../images/YoutubePlaceholder.svg";
interface QueryCopilotCarouselProps {
isOpen: boolean;
explorer: Explorer;
}
const separatorStyles: Partial<ISeparatorStyles> = {
root: {
selectors: {
"::before": {
background: StyleConstants.BaseMedium,
},
},
padding: "16px 0",
height: 1,
},
};
export const QueryCopilotCarousel: React.FC<QueryCopilotCarouselProps> = ({
isOpen,
explorer,
}: QueryCopilotCarouselProps): JSX.Element => {
const [page, setPage] = useState<number>(1);
const [isCreatingDatabase, setIsCreatingDatabase] = useState<boolean>(false);
const [spinnerText, setSpinnerText] = useState<string>("");
const [selectedPrompt, setSelectedPrompt] = useState<number>(1);
const getHeaderText = (): string => {
switch (page) {
case 1:
return "What exactly is copilot?";
case 2:
return "Setting up your Sample database";
case 3:
return "Sample prompts to help you";
default:
return "";
}
};
const getQueryCopilotInitialInput = (): string => {
switch (selectedPrompt) {
case 1:
return "Write a query to return all records in this table";
case 2:
return "Write a query to return all records in this table created in the last thirty days";
case 3:
return 'Write a query to return all records in this table created in the last thirty days which also have the record owner as "Contoso"';
default:
return "";
}
};
const createSampleDatabase = async (): Promise<void> => {
const database = useDatabases.getState().findDatabaseWithId(QueryCopilotSampleDatabaseId);
if (database) {
return;
}
try {
setIsCreatingDatabase(true);
setSpinnerText("Setting up your database...");
const params: DataModels.CreateCollectionParams = {
createNewDatabase: true,
collectionId: "SampleContainer",
databaseId: QueryCopilotSampleDatabaseId,
databaseLevelThroughput: true,
autoPilotMaxThroughput: 1000,
offerThroughput: undefined,
indexingPolicy: AllPropertiesIndexed,
partitionKey: {
paths: ["/categoryId"],
kind: "Hash",
version: 2,
},
};
await createCollection(params);
await explorer.refreshAllDatabases();
const database = useDatabases.getState().findDatabaseWithId(QueryCopilotSampleDatabaseId);
await database.loadCollections();
const collection = database.findCollectionWithId("SampleContainer");
setSpinnerText("Adding sample data set...");
const sampleGenerator = await ContainerSampleGenerator.createSampleGeneratorAsync(explorer, true);
await sampleGenerator.populateContainerAsync(collection);
await database.expandDatabase();
collection.expandCollection();
useDatabases.getState().updateDatabase(database);
} catch (error) {
//TODO: show error in UI
handleError(error, "QueryCopilotCreateSampleDB");
throw error;
} finally {
setIsCreatingDatabase(false);
setSpinnerText("");
}
};
const getContent = (): JSX.Element => {
switch (page) {
case 1:
return (
<Stack style={{ marginTop: 8 }}>
<Text style={{ fontSize: 13 }}>
A couple of lines about copilot and the background about it. The idea is to have some text to give context
to the user.
</Text>
<Text style={{ fontSize: 14, fontWeight: 600, marginTop: 16 }}>How do you use copilot</Text>
<Text style={{ fontSize: 13, marginTop: 8 }}>
To generate queries , just describe the query you want and copilot will generate the query for you.Watch
this video to learn more about how to use copilot.
</Text>
<Image src={YoutubePlaceholder} style={{ margin: "16px auto" }} />
<Text style={{ fontSize: 14, fontWeight: 600 }}>What is copilot good at</Text>
<Text style={{ fontSize: 13, marginTop: 8 }}>
A couple of lines about what copilot can do and its capablites with a link to{" "}
<Link href="" target="_blank">
documentation
</Link>{" "}
if possible.
</Text>
<Text style={{ fontSize: 14, fontWeight: 600, marginTop: 16 }}>What are its limitations</Text>
<Text style={{ fontSize: 13, marginTop: 8 }}>
A couple of lines about what copilot cant do and its limitations.{" "}
<Link href="" target="_blank">
Link to documentation
</Link>
</Text>
<Text style={{ fontSize: 14, fontWeight: 600, marginTop: 16 }}>Disclaimer</Text>
<Text style={{ fontSize: 13, marginTop: 8 }}>
AI-generated content can have mistakes. Make sure it&apos;s accurate and appropriate before using it.{" "}
<Link href="" target="_blank">
Read preview terms
</Link>
</Text>
</Stack>
);
case 2:
return (
<Stack style={{ marginTop: 8 }}>
<Text style={{ fontSize: 13 }}>
Before you get started, we need to configure your sample database for you. Here is a summary of the
database being created for your reference. Configuration values can be updated using the settings icon in
the query builder.
</Text>
<Text style={{ fontSize: 13, fontWeight: 600, marginTop: 24 }}>Database Id</Text>
<Text style={{ fontSize: 13 }}>CopilotSampleDb</Text>
<Text style={{ fontSize: 13, fontWeight: 600, marginTop: 16 }}>Database throughput (autoscale)</Text>
<Text style={{ fontSize: 13 }}>Autoscale</Text>
<Text style={{ fontSize: 13, fontWeight: 600, marginTop: 16 }}>Database Max RU/s</Text>
<Text>1000</Text>
<Text style={{ fontSize: 10, marginTop: 8 }}>
Your database throughput will automatically scale from{" "}
<strong>100 RU/s (10% of max RU/s) - 1000 RU/s</strong> based on usage.
</Text>
<Text style={{ fontSize: 10, marginTop: 8 }}>
Estimated monthly cost (USD): <strong>$8.76 - $87.60</strong> (1 region, 100 - 1000 RU/s, $0.00012/RU)
</Text>
<Text style={{ fontSize: 13, fontWeight: 600, marginTop: 16 }}>Container Id</Text>
<Text style={{ fontSize: 13 }}>SampleContainer</Text>
<Text style={{ fontSize: 13, fontWeight: 600, marginTop: 16 }}>Partition key</Text>
<Text style={{ fontSize: 13 }}>categoryId</Text>
</Stack>
);
case 3:
return (
<Stack>
<Text>To help you get started, here are some sample prompts to get you started</Text>
<Stack tokens={{ childrenGap: 12 }} style={{ marginTop: 16 }}>
<PromptCard
header="Write a query to return all records in this table"
description="This is a basic query which returns all records in the table "
onSelect={() => setSelectedPrompt(1)}
isSelected={selectedPrompt === 1}
/>
<PromptCard
header="Write a query to return all records in this table created in the last thirty days"
description="This builds on the previous query which returns all records in the table which were inserted in the last thirty days. You can also modify this query to return records based upon creation date"
onSelect={() => setSelectedPrompt(2)}
isSelected={selectedPrompt === 2}
/>
<PromptCard
header='Write a query to return all records in this table created in the last thirty days which also have the record owner as "Contoso"'
description='This builds on the previous query which returns all records in the table which were inserted in the last thirty days but which has the record owner as "contoso"'
onSelect={() => setSelectedPrompt(3)}
isSelected={selectedPrompt === 3}
/>
</Stack>
<Text style={{ fontSize: 13, marginTop: 32 }}>
Interested in learning more about how to write effective prompts. Please read this article for more
information.
</Text>
<Text style={{ fontSize: 13, marginTop: 16 }}>
You can also access these prompts by selecting the Samples prompts button in the query builder page.
</Text>
<Text style={{ fontSize: 13, marginTop: 16 }}>
Don&apos;t like any of the prompts? Just click Get Started and write your own prompt.
</Text>
</Stack>
);
default:
return <></>;
}
};
return (
<Modal styles={{ main: { width: 880 } }} isOpen={isOpen && page < 4}>
<Stack style={{ padding: 16 }}>
<Stack horizontal horizontalAlign="space-between">
<Text variant="xLarge">{getHeaderText()}</Text>
<IconButton
iconProps={{ iconName: "Cancel" }}
onClick={() => useCarousel.getState().setShowCopilotCarousel(false)}
/>
</Stack>
{getContent()}
<Separator styles={separatorStyles} />
<Stack horizontal horizontalAlign="start" verticalAlign="center">
{page !== 1 && (
<DefaultButton
text="Previous"
style={{ marginRight: 8 }}
onClick={() => setPage(page - 1)}
disabled={isCreatingDatabase}
/>
)}
<PrimaryButton
text={page === 3 ? "Get started" : "Next"}
onClick={async () => {
if (page === 3) {
useCarousel.getState().setShowCopilotCarousel(false);
useTabs.getState().setQueryCopilotTabInitialInput(getQueryCopilotInitialInput());
useTabs.getState().openAndActivateReactTab(ReactTabKind.QueryCopilot);
return;
}
if (page === 2) {
await createSampleDatabase();
}
setPage(page + 1);
}}
disabled={isCreatingDatabase}
/>
{isCreatingDatabase && <Spinner style={{ marginLeft: 8 }} />}
{isCreatingDatabase && <Text style={{ marginLeft: 8, color: "#0078D4" }}>{spinnerText}</Text>}
</Stack>
</Stack>
</Modal>
);
};

View File

@@ -1,19 +0,0 @@
import { shallow } from "enzyme";
import React from "react";
import { PromptCard } from "./PromptCard";
describe("Prompt card snapshot test", () => {
it("should render properly if isSelected is true", () => {
const wrapper = shallow(
<PromptCard header="TestHeader" description="TestDescription" isSelected={true} onSelect={() => undefined} />
);
expect(wrapper).toMatchSnapshot();
});
it("should render properly if isSelected is false", () => {
const wrapper = shallow(
<PromptCard header="TestHeader" description="TestDescription" isSelected={false} onSelect={() => undefined} />
);
expect(wrapper).toMatchSnapshot();
});
});

View File

@@ -1,48 +0,0 @@
import { ChoiceGroup, Stack, Text } from "@fluentui/react";
import React from "react";
interface PromptCardProps {
header: string;
description: string;
isSelected: boolean;
onSelect: () => void;
}
export const PromptCard: React.FC<PromptCardProps> = ({
header,
description,
isSelected,
onSelect,
}: PromptCardProps): JSX.Element => {
return (
<Stack
horizontal
style={{
padding: "16px 0 16px 16px ",
boxSizing: "border-box",
width: 650,
height: 100,
border: "1px solid #F3F2F1",
boxShadow: "0px 1.6px 3.6px rgba(0, 0, 0, 0.132), 0px 0.3px 0.9px rgba(0, 0, 0, 0.108)",
}}
>
<Stack.Item grow={1}>
<Stack horizontal>
<div>
<Text style={{ fontSize: 13, color: "#00A2AD", background: "#F8FFF0" }}>Prompt</Text>
</div>
<Text style={{ fontSize: 13, marginLeft: 16 }}>{header}</Text>
</Stack>
<Text style={{ fontSize: 10, marginTop: 16 }}>{description}</Text>
</Stack.Item>
<Stack.Item style={{ marginLeft: 16 }}>
<ChoiceGroup
styles={{ flexContainer: { width: 36 } }}
options={[{ key: "selected", text: "" }]}
selectedKey={isSelected ? "selected" : ""}
onChange={onSelect}
/>
</Stack.Item>
</Stack>
);
};

View File

@@ -1,105 +0,0 @@
import {
Checkbox,
ChoiceGroup,
DefaultButton,
IconButton,
Link,
Modal,
PrimaryButton,
Stack,
Text,
TextField,
} from "@fluentui/react";
import { submitFeedback } from "Explorer/QueryCopilot/QueryCopilotUtilities";
import { useQueryCopilot } from "hooks/useQueryCopilot";
import React from "react";
export const QueryCopilotFeedbackModal: React.FC = (): JSX.Element => {
const {
generatedQuery,
userPrompt,
likeQuery,
showFeedbackModal,
closeFeedbackModal,
setHideFeedbackModalForLikedQueries,
} = useQueryCopilot();
const [isContactAllowed, setIsContactAllowed] = React.useState<boolean>(true);
const [description, setDescription] = React.useState<string>("");
const [doNotShowAgainChecked, setDoNotShowAgainChecked] = React.useState<boolean>(false);
return (
<Modal isOpen={showFeedbackModal}>
<Stack style={{ padding: 24 }}>
<Stack horizontal horizontalAlign="space-between">
<Text style={{ fontSize: 20, fontWeight: 600, marginBottom: 20 }}>Send feedback to Microsoft</Text>
<IconButton iconProps={{ iconName: "Cancel" }} onClick={() => closeFeedbackModal()} />
</Stack>
<Text style={{ fontSize: 14, marginBottom: 14 }}>Your feedback will help improve the experience.</Text>
<TextField
styles={{ root: { marginBottom: 14 } }}
label="Description"
required
placeholder="Provide more details"
value={description}
onChange={(_, newValue) => setDescription(newValue)}
multiline
rows={3}
/>
<TextField
styles={{ root: { marginBottom: 14 } }}
label="Query generated"
defaultValue={generatedQuery}
readOnly
/>
<ChoiceGroup
styles={{
root: {
marginBottom: 14,
},
flexContainer: {
selectors: {
".ms-ChoiceField-field::before": { marginTop: 4 },
".ms-ChoiceField-field::after": { marginTop: 4 },
".ms-ChoiceFieldLabel": { paddingLeft: 6 },
},
},
}}
label="May we contact you about your feedback?"
options={[
{ key: "yes", text: "Yes, you may contact me." },
{ key: "no", text: "No, do not contact me." },
]}
selectedKey={isContactAllowed ? "yes" : "no"}
onChange={(_, option) => setIsContactAllowed(option.key === "yes")}
></ChoiceGroup>
<Text style={{ fontSize: 12, marginBottom: 14 }}>
By pressing submit, your feedback will be used to improve Microsoft products and services. IT admins for your
organization will be able to view and manage your feedback data.{" "}
<Link href="" target="_blank">
Privacy statement
</Link>
</Text>
{likeQuery && (
<Checkbox
styles={{ label: { paddingLeft: 0 }, root: { marginBottom: 14 } }}
label="Don't show me this next time"
checked={doNotShowAgainChecked}
onChange={(_, checked) => setDoNotShowAgainChecked(checked)}
/>
)}
<Stack horizontal horizontalAlign="end">
<PrimaryButton
styles={{ root: { marginRight: 8 } }}
onClick={() => {
closeFeedbackModal();
setHideFeedbackModalForLikedQueries(doNotShowAgainChecked);
submitFeedback({ generatedQuery, likeQuery, description, userPrompt });
}}
>
Submit
</PrimaryButton>
<DefaultButton onClick={() => closeFeedbackModal()}>Cancel</DefaultButton>
</Stack>
</Stack>
</Modal>
);
};

View File

@@ -1,13 +0,0 @@
import { shallow } from "enzyme";
import React from "react";
import Explorer from "../Explorer";
import { QueryCopilotTab } from "./QueryCopilotTab";
describe("Query copilot tab snapshot test", () => {
it("should render with initial input", () => {
const wrapper = shallow(
<QueryCopilotTab initialInput="Write a query to return all records in this table" explorer={new Explorer()} />
);
expect(wrapper).toMatchSnapshot();
});
});

View File

@@ -1,275 +0,0 @@
/* eslint-disable no-console */
import { FeedOptions } from "@azure/cosmos";
import {
Callout,
CommandBarButton,
DirectionalHint,
IconButton,
Image,
Link,
Separator,
Spinner,
Stack,
Text,
TextField,
} from "@fluentui/react";
import {
QueryCopilotSampleContainerId,
QueryCopilotSampleContainerSchema,
QueryCopilotSampleDatabaseId,
} from "Common/Constants";
import { getErrorMessage, handleError } from "Common/ErrorHandlingUtils";
import { shouldEnableCrossPartitionKey } from "Common/HeadersUtility";
import { MinimalQueryIterator } from "Common/IteratorUtilities";
import { queryDocuments } from "Common/dataAccess/queryDocuments";
import { queryDocumentsPage } from "Common/dataAccess/queryDocumentsPage";
import { QueryResults } from "Contracts/ViewModels";
import { CommandButtonComponentProps } from "Explorer/Controls/CommandButton/CommandButtonComponent";
import { EditorReact } from "Explorer/Controls/Editor/EditorReact";
import Explorer from "Explorer/Explorer";
import { useCommandBar } from "Explorer/Menus/CommandBar/CommandBarComponentAdapter";
import { SaveQueryPane } from "Explorer/Panes/SaveQueryPane/SaveQueryPane";
import { submitFeedback } from "Explorer/QueryCopilot/QueryCopilotUtilities";
import { QueryResultSection } from "Explorer/Tabs/QueryTab/QueryResultSection";
import { queryPagesUntilContentPresent } from "Utils/QueryUtils";
import { useQueryCopilot } from "hooks/useQueryCopilot";
import { useSidePanel } from "hooks/useSidePanel";
import React, { useState } from "react";
import SplitterLayout from "react-splitter-layout";
import CopilotIcon from "../../../images/Copilot.svg";
import ExecuteQueryIcon from "../../../images/ExecuteQuery.svg";
import SaveQueryIcon from "../../../images/save-cosmos.svg";
interface QueryCopilotTabProps {
initialInput: string;
explorer: Explorer;
}
interface GenerateSQLQueryResponse {
apiVersion: string;
sql: string;
explanation: string;
generateStart: string;
generateEnd: string;
}
export const QueryCopilotTab: React.FC<QueryCopilotTabProps> = ({
initialInput,
explorer,
}: QueryCopilotTabProps): JSX.Element => {
const hideFeedbackModalForLikedQueries = useQueryCopilot((state) => state.hideFeedbackModalForLikedQueries);
const [userInput, setUserInput] = useState<string>(initialInput || "");
const [generatedQuery, setGeneratedQuery] = useState<string>("");
const [query, setQuery] = useState<string>("");
const [selectedQuery, setSelectedQuery] = useState<string>("");
const [isGeneratingQuery, setIsGeneratingQuery] = useState<boolean>(false);
const [isExecuting, setIsExecuting] = useState<boolean>(false);
const [likeQuery, setLikeQuery] = useState<boolean>();
const [showCallout, setShowCallout] = useState<boolean>(false);
const [queryIterator, setQueryIterator] = useState<MinimalQueryIterator>();
const [queryResults, setQueryResults] = useState<QueryResults>();
const [errorMessage, setErrorMessage] = useState<string>("");
const generateSQLQuery = async (): Promise<void> => {
try {
setIsGeneratingQuery(true);
const payload = {
containerSchema: QueryCopilotSampleContainerSchema,
userPrompt: userInput,
};
const response = await fetch("https://copilotorchestrater.azurewebsites.net/generateSQLQuery", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
const generateSQLQueryResponse: GenerateSQLQueryResponse = await response?.json();
if (generateSQLQueryResponse?.sql) {
let query = `-- **Prompt:** ${userInput}\r\n`;
if (generateSQLQueryResponse.explanation) {
query += `-- **Explanation of query:** ${generateSQLQueryResponse.explanation}\r\n`;
}
query += generateSQLQueryResponse.sql;
setQuery(query);
setGeneratedQuery(generateSQLQueryResponse.sql);
}
} catch (error) {
handleError(error, "executeNaturalLanguageQuery");
throw error;
} finally {
setIsGeneratingQuery(false);
}
};
const onExecuteQueryClick = async (): Promise<void> => {
const queryToExecute = selectedQuery || query;
const queryIterator = queryDocuments(QueryCopilotSampleDatabaseId, QueryCopilotSampleContainerId, queryToExecute, {
enableCrossPartitionQuery: shouldEnableCrossPartitionKey(),
} as FeedOptions);
setQueryIterator(queryIterator);
setTimeout(async () => {
await queryDocumentsPerPage(0, queryIterator);
}, 100);
};
const queryDocumentsPerPage = async (firstItemIndex: number, queryIterator: MinimalQueryIterator): Promise<void> => {
try {
setIsExecuting(true);
const queryResults: QueryResults = await queryPagesUntilContentPresent(
firstItemIndex,
async (firstItemIndex: number) =>
queryDocumentsPage(QueryCopilotSampleContainerId, queryIterator, firstItemIndex)
);
setQueryResults(queryResults);
setErrorMessage("");
} catch (error) {
const errorMessage = getErrorMessage(error);
setErrorMessage(errorMessage);
handleError(errorMessage, "executeQueryCopilotTab");
} finally {
setIsExecuting(false);
}
};
const getCommandbarButtons = (): CommandButtonComponentProps[] => {
const executeQueryBtnLabel = selectedQuery ? "Execute Selection" : "Execute Query";
const executeQueryBtn = {
iconSrc: ExecuteQueryIcon,
iconAlt: executeQueryBtnLabel,
onCommandClick: () => onExecuteQueryClick(),
commandButtonLabel: executeQueryBtnLabel,
ariaLabel: executeQueryBtnLabel,
hasPopup: false,
};
const saveQueryBtn = {
iconSrc: SaveQueryIcon,
iconAlt: "Save Query",
onCommandClick: () =>
useSidePanel.getState().openSidePanel("Save Query", <SaveQueryPane explorer={explorer} queryToSave={query} />),
commandButtonLabel: "Save Query",
ariaLabel: "Save Query",
hasPopup: false,
};
return [executeQueryBtn, saveQueryBtn];
};
React.useEffect(() => {
useCommandBar.getState().setContextButtons(getCommandbarButtons());
}, [query, selectedQuery]);
React.useEffect(() => {
if (initialInput) {
generateSQLQuery();
}
}, []);
return (
<Stack className="tab-pane" style={{ padding: 24, width: "100%", height: "100%" }}>
<Stack horizontal verticalAlign="center">
<Image src={CopilotIcon} />
<Text style={{ marginLeft: 8, fontWeight: 600, fontSize: 16 }}>Copilot</Text>
</Stack>
<Stack horizontal verticalAlign="center" style={{ marginTop: 16, width: "100%" }}>
<TextField
value={userInput}
onChange={(_, newValue) => setUserInput(newValue)}
style={{ lineHeight: 30 }}
styles={{ root: { width: "90%" } }}
disabled={isGeneratingQuery}
/>
<IconButton
iconProps={{ iconName: "Send" }}
disabled={isGeneratingQuery}
style={{ marginLeft: 8 }}
onClick={() => generateSQLQuery()}
/>
{isGeneratingQuery && <Spinner style={{ marginLeft: 8 }} />}
</Stack>
<Text style={{ marginTop: 8, marginBottom: 24, fontSize: 12 }}>
AI-generated content can have mistakes. Make sure it&apos;s accurate and appropriate before using it.{" "}
<Link href="" target="_blank">
Read preview terms
</Link>
</Text>
<Stack style={{ backgroundColor: "#FFF8F0", padding: "2px 8px" }} horizontal verticalAlign="center">
<Text style={{ fontWeight: 600, fontSize: 12 }}>Provide feedback on the query generated</Text>
{showCallout && !hideFeedbackModalForLikedQueries && (
<Callout
style={{ padding: 8 }}
target="#likeBtn"
onDismiss={() => {
setShowCallout(false);
submitFeedback({ generatedQuery, likeQuery, description: "", userPrompt: userInput });
}}
directionalHint={DirectionalHint.topCenter}
>
<Text>
Thank you. Need to give{" "}
<Link
onClick={() => {
setShowCallout(false);
useQueryCopilot.getState().openFeedbackModal(generatedQuery, true, userInput);
}}
>
more feedback?
</Link>
</Text>
</Callout>
)}
<IconButton
id="likeBtn"
style={{ marginLeft: 20 }}
iconProps={{ iconName: likeQuery === true ? "LikeSolid" : "Like" }}
onClick={() => {
setLikeQuery(true);
setShowCallout(true);
}}
/>
<IconButton
style={{ margin: "0 10px" }}
iconProps={{ iconName: likeQuery === false ? "DislikeSolid" : "Dislike" }}
onClick={() => {
setLikeQuery(false);
setShowCallout(false);
useQueryCopilot.getState().openFeedbackModal(generatedQuery, false, userInput);
}}
/>
<Separator vertical style={{ color: "#EDEBE9" }} />
<CommandBarButton iconProps={{ iconName: "Copy" }} style={{ margin: "0 10px", backgroundColor: "#FFF8F0" }}>
Copy code
</CommandBarButton>
<CommandBarButton iconProps={{ iconName: "Delete" }} style={{ backgroundColor: "#FFF8F0" }}>
Delete code
</CommandBarButton>
</Stack>
<Stack className="tabPaneContentContainer">
<SplitterLayout vertical={true} primaryIndex={0} primaryMinSize={100} secondaryMinSize={200}>
<EditorReact
language={"sql"}
content={query}
isReadOnly={false}
ariaLabel={"Editing Query"}
lineNumbers={"on"}
onContentChanged={(newQuery: string) => setQuery(newQuery)}
onContentSelected={(selectedQuery: string) => setSelectedQuery(selectedQuery)}
/>
<QueryResultSection
isMongoDB={false}
queryEditorContent={selectedQuery || query}
error={errorMessage}
queryResults={queryResults}
isExecuting={isExecuting}
executeQueryDocumentsPage={(firstItemIndex: number) => queryDocumentsPerPage(firstItemIndex, queryIterator)}
/>
</SplitterLayout>
</Stack>
</Stack>
);
};

View File

@@ -1,36 +0,0 @@
import { QueryCopilotSampleContainerSchema } from "Common/Constants";
import { handleError } from "Common/ErrorHandlingUtils";
interface FeedbackParams {
likeQuery: boolean;
generatedQuery: string;
userPrompt: string;
description?: string;
contact?: string;
}
export const submitFeedback = async (params: FeedbackParams): Promise<void> => {
try {
const { likeQuery, generatedQuery, userPrompt, description, contact } = params;
const payload = {
containerSchema: QueryCopilotSampleContainerSchema,
like: likeQuery ? "like" : "dislike",
generatedSql: generatedQuery,
userPrompt,
description: description || "",
contact: contact || "",
};
const response = await fetch("https://copilotorchestrater.azurewebsites.net/feedback", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
// eslint-disable-next-line no-console
console.log(response);
} catch (error) {
handleError(error, "copilotSubmitFeedback");
}
};

View File

@@ -1,198 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Query Copilot Carousel snapshot test should render when isOpen is true 1`] = `
<Modal
isOpen={true}
styles={
Object {
"main": Object {
"width": 880,
},
}
}
>
<Stack
style={
Object {
"padding": 16,
}
}
>
<Stack
horizontal={true}
horizontalAlign="space-between"
>
<Text
variant="xLarge"
>
What exactly is copilot?
</Text>
<CustomizedIconButton
iconProps={
Object {
"iconName": "Cancel",
}
}
onClick={[Function]}
/>
</Stack>
<Stack
style={
Object {
"marginTop": 8,
}
}
>
<Text
style={
Object {
"fontSize": 13,
}
}
>
A couple of lines about copilot and the background about it. The idea is to have some text to give context to the user.
</Text>
<Text
style={
Object {
"fontSize": 14,
"fontWeight": 600,
"marginTop": 16,
}
}
>
How do you use copilot
</Text>
<Text
style={
Object {
"fontSize": 13,
"marginTop": 8,
}
}
>
To generate queries , just describe the query you want and copilot will generate the query for you.Watch this video to learn more about how to use copilot.
</Text>
<Image
src=""
style={
Object {
"margin": "16px auto",
}
}
/>
<Text
style={
Object {
"fontSize": 14,
"fontWeight": 600,
}
}
>
What is copilot good at
</Text>
<Text
style={
Object {
"fontSize": 13,
"marginTop": 8,
}
}
>
A couple of lines about what copilot can do and its capablites with a link to
<StyledLinkBase
href=""
target="_blank"
>
documentation
</StyledLinkBase>
if possible.
</Text>
<Text
style={
Object {
"fontSize": 14,
"fontWeight": 600,
"marginTop": 16,
}
}
>
What are its limitations
</Text>
<Text
style={
Object {
"fontSize": 13,
"marginTop": 8,
}
}
>
A couple of lines about what copilot cant do and its limitations.
<StyledLinkBase
href=""
target="_blank"
>
Link to documentation
</StyledLinkBase>
</Text>
<Text
style={
Object {
"fontSize": 14,
"fontWeight": 600,
"marginTop": 16,
}
}
>
Disclaimer
</Text>
<Text
style={
Object {
"fontSize": 13,
"marginTop": 8,
}
}
>
AI-generated content can have mistakes. Make sure it's accurate and appropriate before using it.
<StyledLinkBase
href=""
target="_blank"
>
Read preview terms
</StyledLinkBase>
</Text>
</Stack>
<Separator
styles={
Object {
"root": Object {
"height": 1,
"padding": "16px 0",
"selectors": Object {
"::before": Object {
"background": undefined,
},
},
},
}
}
/>
<Stack
horizontal={true}
horizontalAlign="start"
verticalAlign="center"
>
<CustomizedPrimaryButton
disabled={false}
onClick={[Function]}
text="Next"
/>
</Stack>
</Stack>
</Modal>
`;

View File

@@ -1,171 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Prompt card snapshot test should render properly if isSelected is false 1`] = `
<Stack
horizontal={true}
style={
Object {
"border": "1px solid #F3F2F1",
"boxShadow": "0px 1.6px 3.6px rgba(0, 0, 0, 0.132), 0px 0.3px 0.9px rgba(0, 0, 0, 0.108)",
"boxSizing": "border-box",
"height": 100,
"padding": "16px 0 16px 16px ",
"width": 650,
}
}
>
<StackItem
grow={1}
>
<Stack
horizontal={true}
>
<div>
<Text
style={
Object {
"background": "#F8FFF0",
"color": "#00A2AD",
"fontSize": 13,
}
}
>
Prompt
</Text>
</div>
<Text
style={
Object {
"fontSize": 13,
"marginLeft": 16,
}
}
>
TestHeader
</Text>
</Stack>
<Text
style={
Object {
"fontSize": 10,
"marginTop": 16,
}
}
>
TestDescription
</Text>
</StackItem>
<StackItem
style={
Object {
"marginLeft": 16,
}
}
>
<StyledChoiceGroup
onChange={[Function]}
options={
Array [
Object {
"key": "selected",
"text": "",
},
]
}
selectedKey=""
styles={
Object {
"flexContainer": Object {
"width": 36,
},
}
}
/>
</StackItem>
</Stack>
`;
exports[`Prompt card snapshot test should render properly if isSelected is true 1`] = `
<Stack
horizontal={true}
style={
Object {
"border": "1px solid #F3F2F1",
"boxShadow": "0px 1.6px 3.6px rgba(0, 0, 0, 0.132), 0px 0.3px 0.9px rgba(0, 0, 0, 0.108)",
"boxSizing": "border-box",
"height": 100,
"padding": "16px 0 16px 16px ",
"width": 650,
}
}
>
<StackItem
grow={1}
>
<Stack
horizontal={true}
>
<div>
<Text
style={
Object {
"background": "#F8FFF0",
"color": "#00A2AD",
"fontSize": 13,
}
}
>
Prompt
</Text>
</div>
<Text
style={
Object {
"fontSize": 13,
"marginLeft": 16,
}
}
>
TestHeader
</Text>
</Stack>
<Text
style={
Object {
"fontSize": 10,
"marginTop": 16,
}
}
>
TestDescription
</Text>
</StackItem>
<StackItem
style={
Object {
"marginLeft": 16,
}
}
>
<StyledChoiceGroup
onChange={[Function]}
options={
Array [
Object {
"key": "selected",
"text": "",
},
]
}
selectedKey="selected"
styles={
Object {
"flexContainer": Object {
"width": 36,
},
}
}
/>
</StackItem>
</Stack>
`;

View File

@@ -1,211 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Query copilot tab snapshot test should render with initial input 1`] = `
<Stack
className="tab-pane"
style={
Object {
"height": "100%",
"padding": 24,
"width": "100%",
}
}
>
<Stack
horizontal={true}
verticalAlign="center"
>
<Image
src=""
/>
<Text
style={
Object {
"fontSize": 16,
"fontWeight": 600,
"marginLeft": 8,
}
}
>
Copilot
</Text>
</Stack>
<Stack
horizontal={true}
style={
Object {
"marginTop": 16,
"width": "100%",
}
}
verticalAlign="center"
>
<StyledTextFieldBase
disabled={false}
onChange={[Function]}
style={
Object {
"lineHeight": 30,
}
}
styles={
Object {
"root": Object {
"width": "90%",
},
}
}
value="Write a query to return all records in this table"
/>
<CustomizedIconButton
disabled={false}
iconProps={
Object {
"iconName": "Send",
}
}
onClick={[Function]}
style={
Object {
"marginLeft": 8,
}
}
/>
</Stack>
<Text
style={
Object {
"fontSize": 12,
"marginBottom": 24,
"marginTop": 8,
}
}
>
AI-generated content can have mistakes. Make sure it's accurate and appropriate before using it.
<StyledLinkBase
href=""
target="_blank"
>
Read preview terms
</StyledLinkBase>
</Text>
<Stack
horizontal={true}
style={
Object {
"backgroundColor": "#FFF8F0",
"padding": "2px 8px",
}
}
verticalAlign="center"
>
<Text
style={
Object {
"fontSize": 12,
"fontWeight": 600,
}
}
>
Provide feedback on the query generated
</Text>
<CustomizedIconButton
iconProps={
Object {
"iconName": "Like",
}
}
id="likeBtn"
onClick={[Function]}
style={
Object {
"marginLeft": 20,
}
}
/>
<CustomizedIconButton
iconProps={
Object {
"iconName": "Dislike",
}
}
onClick={[Function]}
style={
Object {
"margin": "0 10px",
}
}
/>
<Separator
style={
Object {
"color": "#EDEBE9",
}
}
vertical={true}
/>
<CustomizedCommandBarButton
iconProps={
Object {
"iconName": "Copy",
}
}
style={
Object {
"backgroundColor": "#FFF8F0",
"margin": "0 10px",
}
}
>
Copy code
</CustomizedCommandBarButton>
<CustomizedCommandBarButton
iconProps={
Object {
"iconName": "Delete",
}
}
style={
Object {
"backgroundColor": "#FFF8F0",
}
}
>
Delete code
</CustomizedCommandBarButton>
</Stack>
<Stack
className="tabPaneContentContainer"
>
<t
customClassName=""
onDragEnd={null}
onDragStart={null}
onSecondaryPaneSizeChange={null}
percentage={false}
primaryIndex={0}
primaryMinSize={100}
secondaryMinSize={200}
vertical={true}
>
<EditorReact
ariaLabel="Editing Query"
content=""
isReadOnly={false}
language="sql"
lineNumbers="on"
onContentChanged={[Function]}
onContentSelected={[Function]}
/>
<QueryResultSection
error=""
executeQueryDocumentsPage={[Function]}
isExecuting={false}
isMongoDB={false}
queryEditorContent=""
/>
</t>
</Stack>
</Stack>
`;

View File

@@ -14,21 +14,19 @@ import {
import { sendMessage } from "Common/MessageHandler";
import { MessageTypes } from "Contracts/ExplorerContracts";
import { TerminalKind } from "Contracts/ViewModels";
import { SplashScreenButton } from "Explorer/SplashScreen/SplashScreenButton";
import { Action } from "Shared/Telemetry/TelemetryConstants";
import { traceOpen } from "Shared/Telemetry/TelemetryProcessor";
import { useCarousel } from "hooks/useCarousel";
import { usePostgres } from "hooks/usePostgres";
import { ReactTabKind, useTabs } from "hooks/useTabs";
import * as React from "react";
import { Action } from "Shared/Telemetry/TelemetryConstants";
import { traceOpen } from "Shared/Telemetry/TelemetryProcessor";
import ConnectIcon from "../../../images/Connect_color.svg";
import ContainersIcon from "../../../images/Containers.svg";
import CopilotIcon from "../../../images/Copilot.svg";
import LinkIcon from "../../../images/Link_blue.svg";
import NotebookIcon from "../../../images/notebook/Notebook-resource.svg";
import NotebookColorIcon from "../../../images/Notebooks.svg";
import PowerShellIcon from "../../../images/PowerShell.svg";
import QuickStartIcon from "../../../images/Quickstart_Lightning.svg";
import NotebookIcon from "../../../images/notebook/Notebook-resource.svg";
import CollectionIcon from "../../../images/tree-collection.svg";
import * as Constants from "../../Common/Constants";
import { userContext } from "../../UserContext";
@@ -56,6 +54,10 @@ export interface SplashScreenProps {
}
export class SplashScreen extends React.Component<SplashScreenProps> {
private static readonly dataModelingUrl = "https://docs.microsoft.com/azure/cosmos-db/modeling-data";
private static readonly throughputEstimatorUrl = "https://cosmos.azure.com/capacitycalculator";
private static readonly failoverUrl = "https://docs.microsoft.com/azure/cosmos-db/high-availability";
private readonly container: Explorer;
private subscriptions: Array<{ dispose: () => void }>;
@@ -106,141 +108,9 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
this.setState({});
};
private getSplashScreenButtons = (): JSX.Element => {
if (userContext.features.enableCopilot && userContext.apiType === "SQL") {
return (
<Stack style={{ width: "66%", cursor: "pointer", margin: "40px auto" }} tokens={{ childrenGap: 16 }}>
<Stack horizontal tokens={{ childrenGap: 16 }}>
<SplashScreenButton
imgSrc={QuickStartIcon}
title={"Launch quick start"}
description={"Launch a quick start tutorial to get started with sample data"}
onClick={() => {
this.container.onNewCollectionClicked({ isQuickstart: true });
traceOpen(Action.LaunchQuickstart, { apiType: userContext.apiType });
}}
/>
<SplashScreenButton
imgSrc={ContainersIcon}
title={`New ${getCollectionName()}`}
description={"Create a new container for storage and throughput"}
onClick={() => {
this.container.onNewCollectionClicked();
traceOpen(Action.NewContainerHomepage, { apiType: userContext.apiType });
}}
/>
</Stack>
<Stack horizontal tokens={{ childrenGap: 16 }}>
<SplashScreenButton
imgSrc={CopilotIcon}
title={"Query faster with Copilot"}
description={
"Copilot is your AI buddy that helps you write Azure Cosmos DB queries like a pro. Try it using our sample data set now!"
}
onClick={() => useTabs.getState().openAndActivateReactTab(ReactTabKind.QueryCopilot)}
/>
<SplashScreenButton
imgSrc={ConnectIcon}
title={"Connect"}
description={"Prefer using your own choice of tooling? Find the connection string you need to connect"}
onClick={() => useTabs.getState().openAndActivateReactTab(ReactTabKind.Connect)}
/>
</Stack>
</Stack>
);
}
const mainItems = this.createMainItems();
return (
<div className="mainButtonsContainer">
{userContext.apiType === "Postgres" &&
usePostgres.getState().showPostgreTeachingBubble &&
!usePostgres.getState().showResetPasswordBubble && (
<TeachingBubble
headline="New to Cosmos DB PGSQL?"
target={"#mainButton-quickstartDescription"}
hasCloseButton
onDismiss={() => usePostgres.getState().setShowPostgreTeachingBubble(false)}
calloutProps={{
directionalHint: DirectionalHint.rightCenter,
directionalHintFixed: true,
preventDismissOnLostFocus: true,
preventDismissOnResize: true,
preventDismissOnScroll: true,
}}
primaryButtonProps={{
text: "Get started",
onClick: () => {
useTabs.getState().openAndActivateReactTab(ReactTabKind.Quickstart);
usePostgres.getState().setShowPostgreTeachingBubble(false);
},
}}
>
Welcome! If you are new to Cosmos DB PGSQL and need help with getting started, here is where you can find
sample data, query.
</TeachingBubble>
)}
{mainItems.map((item) => (
<Stack
id={`mainButton-${item.id}`}
horizontal
className="mainButton focusable"
key={`${item.title}`}
onClick={item.onClick}
onKeyPress={(event: React.KeyboardEvent) => this.onSplashScreenItemKeyPress(event, item.onClick)}
tabIndex={0}
role="button"
>
<div>
<img src={item.iconSrc} alt="" />
</div>
<div className="legendContainer">
<Stack horizontal verticalAlign="center" style={{ marginBottom: 8 }}>
<div className="legend">{item.title}</div>
{item.showLinkIcon && <Image style={{ marginLeft: 8, width: 16 }} src={LinkIcon} />}
</Stack>
<div id={item.id} className="newDescription">
{item.description}
</div>
</div>
</Stack>
))}
{userContext.apiType === "Postgres" && usePostgres.getState().showResetPasswordBubble && (
<TeachingBubble
headline="Create your password"
target={"#mainButton-quickstartDescription"}
hasCloseButton
onDismiss={() => {
localStorage.setItem(userContext.databaseAccount.id, "true");
usePostgres.getState().setShowResetPasswordBubble(false);
}}
calloutProps={{
directionalHint: DirectionalHint.bottomRightEdge,
directionalHintFixed: true,
preventDismissOnLostFocus: true,
preventDismissOnResize: true,
preventDismissOnScroll: true,
}}
primaryButtonProps={{
text: "Create",
onClick: () => {
localStorage.setItem(userContext.databaseAccount.id, "true");
sendMessage({
type: MessageTypes.OpenPostgreSQLPasswordReset,
});
usePostgres.getState().setShowResetPasswordBubble(false);
},
}}
>
If you haven&apos;t changed your password yet, change it now.
</TeachingBubble>
)}
</div>
);
};
public render(): JSX.Element {
const mainItems = this.createMainItems();
return (
<div className="connectExplorerContainer">
<form className="connectExplorerFormContainer">
@@ -264,7 +134,91 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
? "Get started with our sample datasets, documentation, and additional tools."
: "Globally distributed, multi-model database service for any scale"}
</div>
{this.getSplashScreenButtons()}
<div className="mainButtonsContainer">
{userContext.apiType === "Postgres" &&
usePostgres.getState().showPostgreTeachingBubble &&
!usePostgres.getState().showResetPasswordBubble && (
<TeachingBubble
headline="New to Cosmos DB PGSQL?"
target={"#mainButton-quickstartDescription"}
hasCloseButton
onDismiss={() => usePostgres.getState().setShowPostgreTeachingBubble(false)}
calloutProps={{
directionalHint: DirectionalHint.rightCenter,
directionalHintFixed: true,
preventDismissOnLostFocus: true,
preventDismissOnResize: true,
preventDismissOnScroll: true,
}}
primaryButtonProps={{
text: "Get started",
onClick: () => {
useTabs.getState().openAndActivateReactTab(ReactTabKind.Quickstart);
usePostgres.getState().setShowPostgreTeachingBubble(false);
},
}}
>
Welcome! If you are new to Cosmos DB PGSQL and need help with getting started, here is where you
can find sample data, query.
</TeachingBubble>
)}
{mainItems.map((item) => (
<Stack
id={`mainButton-${item.id}`}
horizontal
className="mainButton focusable"
key={`${item.title}`}
onClick={item.onClick}
onKeyPress={(event: React.KeyboardEvent) => this.onSplashScreenItemKeyPress(event, item.onClick)}
tabIndex={0}
role="button"
>
<div>
<img src={item.iconSrc} alt="" />
</div>
<div className="legendContainer">
<Stack horizontal verticalAlign="center" style={{ marginBottom: 8 }}>
<div className="legend">{item.title}</div>
{item.showLinkIcon && <Image style={{ marginLeft: 8, width: 16 }} src={LinkIcon} />}
</Stack>
<div id={item.id} className="newDescription">
{item.description}
</div>
</div>
</Stack>
))}
{userContext.apiType === "Postgres" && usePostgres.getState().showResetPasswordBubble && (
<TeachingBubble
headline="Create your password"
target={"#mainButton-quickstartDescription"}
hasCloseButton
onDismiss={() => {
localStorage.setItem(userContext.databaseAccount.id, "true");
usePostgres.getState().setShowResetPasswordBubble(false);
}}
calloutProps={{
directionalHint: DirectionalHint.bottomRightEdge,
directionalHintFixed: true,
preventDismissOnLostFocus: true,
preventDismissOnResize: true,
preventDismissOnScroll: true,
}}
primaryButtonProps={{
text: "Create",
onClick: () => {
localStorage.setItem(userContext.databaseAccount.id, "true");
sendMessage({
type: MessageTypes.OpenPostgreSQLPasswordReset,
});
usePostgres.getState().setShowResetPasswordBubble(false);
},
}}
>
If you haven&apos;t changed your password yet, change it now.
</TeachingBubble>
)}
</div>
{useCarousel.getState().showCoachMark && (
<Coachmark
target="#quickstartDescription"
@@ -294,7 +248,7 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
</Coachmark>
)}
{userContext.apiType === "Postgres" ? (
<Stack horizontal style={{ margin: "0 auto", width: "84%" }} tokens={{ childrenGap: 16 }}>
<Stack horizontal style={{ margin: "0 auto", width: "84%" }} tokens={{ childrenGap: 32 }}>
<Stack style={{ width: "33%" }}>
<Text
variant="large"

View File

@@ -1,50 +0,0 @@
import { Stack, Text } from "@fluentui/react";
import React from "react";
import { KeyCodes } from "../../Common/Constants";
interface SplashScreenButtonProps {
imgSrc: string;
title: string;
description: string;
onClick: () => void;
}
export const SplashScreenButton: React.FC<SplashScreenButtonProps> = ({
imgSrc,
title,
description,
onClick,
}: SplashScreenButtonProps): JSX.Element => {
return (
<Stack
horizontal
style={{
border: "1px solid #949494",
boxSizing: "border-box",
boxShadow: "0 4px 4px rgba(0, 0, 0, 0.25)",
borderRadius: 4,
padding: "32px 16px",
backgroundColor: "#ffffff",
width: "100%",
minHeight: 150,
}}
onClick={onClick}
onKeyPress={(event: React.KeyboardEvent) => {
if (event.charCode === KeyCodes.Space || event.charCode === KeyCodes.Enter) {
onClick();
event.stopPropagation();
}
}}
tabIndex={0}
role="button"
>
<div>
<img src={imgSrc} />
</div>
<Stack style={{ marginLeft: 16 }}>
<Text style={{ fontSize: 18, fontWeight: 600 }}>{title}</Text>
<Text style={{ fontSize: 13 }}>{description}</Text>
</Stack>
</Stack>
);
};

View File

@@ -1,495 +0,0 @@
import {
DetailsList,
DetailsListLayoutMode,
IColumn,
Pivot,
PivotItem,
SelectionMode,
Stack,
Text,
} from "@fluentui/react";
import { HttpHeaders, NormalizedEventKey } from "Common/Constants";
import MongoUtility from "Common/MongoUtility";
import { InfoTooltip } from "Common/Tooltip/InfoTooltip";
import { QueryMetrics } from "Contracts/DataModels";
import { EditorReact } from "Explorer/Controls/Editor/EditorReact";
import { IDocument } from "Explorer/Tabs/QueryTab/QueryTabComponent";
import { userContext } from "UserContext";
import { useNotificationConsole } from "hooks/useNotificationConsole";
import React from "react";
import DownloadQueryMetrics from "../../../../images/DownloadQuery.svg";
import QueryEditorNext from "../../../../images/Query-Editor-Next.svg";
import RunQuery from "../../../../images/RunQuery.png";
import InfoColor from "../../../../images/info_color.svg";
import { QueryResults } from "../../../Contracts/ViewModels";
interface QueryResultProps {
isMongoDB: boolean;
queryEditorContent: string;
error: string;
isExecuting: boolean;
queryResults: QueryResults;
executeQueryDocumentsPage: (firstItemIndex: number) => Promise<void>;
}
export const QueryResultSection: React.FC<QueryResultProps> = ({
isMongoDB,
queryEditorContent,
error,
queryResults,
isExecuting,
executeQueryDocumentsPage,
}: QueryResultProps): JSX.Element => {
const queryMetrics = React.useRef(queryResults?.headers?.[HttpHeaders.queryMetrics]);
React.useEffect(() => {
const latestQueryMetrics = queryResults?.headers?.[HttpHeaders.queryMetrics];
if (latestQueryMetrics && Object.keys(latestQueryMetrics).length > 0) {
queryMetrics.current = latestQueryMetrics;
}
}, [queryResults]);
const onRender = (item: IDocument): JSX.Element => (
<>
<InfoTooltip>{`${item.toolTip}`}</InfoTooltip>
<Text style={{ paddingLeft: 10, margin: 0 }}>{`${item.metric}`}</Text>
</>
);
const columns: IColumn[] = [
{
key: "column2",
name: "METRIC",
minWidth: 200,
data: String,
fieldName: "metric",
onRender,
},
{
key: "column3",
name: "VALUE",
minWidth: 200,
data: String,
fieldName: "value",
},
];
const maybeSubQuery = queryEditorContent && /.*\(.*SELECT.*\)/i.test(queryEditorContent);
const queryResultsString = queryResults
? isMongoDB
? MongoUtility.tojson(queryResults.documents, undefined, false)
: JSON.stringify(queryResults.documents, undefined, 4)
: "";
const onErrorDetailsClick = (): boolean => {
useNotificationConsole.getState().expandConsole();
return false;
};
const onErrorDetailsKeyPress = (event: React.KeyboardEvent<HTMLAnchorElement>): boolean => {
if (event.key === NormalizedEventKey.Space || event.key === NormalizedEventKey.Enter) {
onErrorDetailsClick();
return false;
}
return true;
};
const onDownloadQueryMetricsCsvClick = (): boolean => {
downloadQueryMetricsCsvData();
return false;
};
const onDownloadQueryMetricsCsvKeyPress = (event: React.KeyboardEvent<HTMLAnchorElement>): boolean => {
if (event.key === NormalizedEventKey.Space || NormalizedEventKey.Enter) {
downloadQueryMetricsCsvData();
return false;
}
return true;
};
const downloadQueryMetricsCsvData = (): void => {
const csvData: string = generateQueryMetricsCsvData();
if (!csvData) {
return;
}
if (navigator.msSaveBlob) {
// for IE and Edge
navigator.msSaveBlob(
new Blob([csvData], { type: "data:text/csv;charset=utf-8" }),
"PerPartitionQueryMetrics.csv"
);
} else {
const downloadLink: HTMLAnchorElement = document.createElement("a");
downloadLink.href = "data:text/csv;charset=utf-8," + encodeURI(csvData);
downloadLink.target = "_self";
downloadLink.download = "QueryMetricsPerPartition.csv";
// for some reason, FF displays the download prompt only when
// the link is added to the dom so we add and remove it
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
}
};
const getAggregatedQueryMetrics = (): QueryMetrics => {
const aggregatedQueryMetrics = {
documentLoadTime: 0,
documentWriteTime: 0,
indexHitDocumentCount: 0,
outputDocumentCount: 0,
outputDocumentSize: 0,
indexLookupTime: 0,
retrievedDocumentCount: 0,
retrievedDocumentSize: 0,
vmExecutionTime: 0,
runtimeExecutionTimes: {
queryEngineExecutionTime: 0,
systemFunctionExecutionTime: 0,
userDefinedFunctionExecutionTime: 0,
},
totalQueryExecutionTime: 0,
} as QueryMetrics;
if (queryMetrics.current) {
Object.keys(queryMetrics.current).forEach((partitionKeyRangeId) => {
const queryMetricsPerPartition = queryMetrics.current[partitionKeyRangeId];
if (!queryMetricsPerPartition) {
return;
}
aggregatedQueryMetrics.documentLoadTime += queryMetricsPerPartition.documentLoadTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.documentWriteTime +=
queryMetricsPerPartition.documentWriteTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.indexHitDocumentCount += queryMetricsPerPartition.indexHitDocumentCount || 0;
aggregatedQueryMetrics.outputDocumentCount += queryMetricsPerPartition.outputDocumentCount || 0;
aggregatedQueryMetrics.outputDocumentSize += queryMetricsPerPartition.outputDocumentSize || 0;
aggregatedQueryMetrics.indexLookupTime += queryMetricsPerPartition.indexLookupTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.retrievedDocumentCount += queryMetricsPerPartition.retrievedDocumentCount || 0;
aggregatedQueryMetrics.retrievedDocumentSize += queryMetricsPerPartition.retrievedDocumentSize || 0;
aggregatedQueryMetrics.vmExecutionTime += queryMetricsPerPartition.vmExecutionTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.totalQueryExecutionTime +=
queryMetricsPerPartition.totalQueryExecutionTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.runtimeExecutionTimes.queryEngineExecutionTime +=
queryMetricsPerPartition.runtimeExecutionTimes?.queryEngineExecutionTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.runtimeExecutionTimes.systemFunctionExecutionTime +=
queryMetricsPerPartition.runtimeExecutionTimes?.systemFunctionExecutionTime?.totalMilliseconds() || 0;
aggregatedQueryMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime +=
queryMetricsPerPartition.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.totalMilliseconds() || 0;
});
}
return aggregatedQueryMetrics;
};
const generateQueryMetricsCsvData = (): string => {
if (queryMetrics.current) {
let csvData =
[
"Partition key range id",
"Retrieved document count",
"Retrieved document size (in bytes)",
"Output document count",
"Output document size (in bytes)",
"Index hit document count",
"Index lookup time (ms)",
"Document load time (ms)",
"Query engine execution time (ms)",
"System function execution time (ms)",
"User defined function execution time (ms)",
"Document write time (ms)",
].join(",") + "\n";
Object.keys(queryMetrics.current).forEach((partitionKeyRangeId) => {
const queryMetricsPerPartition = queryMetrics.current[partitionKeyRangeId];
csvData +=
[
partitionKeyRangeId,
queryMetricsPerPartition.retrievedDocumentCount,
queryMetricsPerPartition.retrievedDocumentSize,
queryMetricsPerPartition.outputDocumentCount,
queryMetricsPerPartition.outputDocumentSize,
queryMetricsPerPartition.indexHitDocumentCount,
queryMetricsPerPartition.indexLookupTime?.totalMilliseconds(),
queryMetricsPerPartition.documentLoadTime?.totalMilliseconds(),
queryMetricsPerPartition.runtimeExecutionTimes?.queryEngineExecutionTime?.totalMilliseconds(),
queryMetricsPerPartition.runtimeExecutionTimes?.systemFunctionExecutionTime?.totalMilliseconds(),
queryMetricsPerPartition.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.totalMilliseconds(),
queryMetricsPerPartition.documentWriteTime?.totalMilliseconds(),
].join(",") + "\n";
});
return csvData;
}
return undefined;
};
const onFetchNextPageClick = async (): Promise<void> => {
const { firstItemIndex, itemCount } = queryResults;
await executeQueryDocumentsPage(firstItemIndex + itemCount - 1);
};
const generateQueryStatsItems = (): IDocument[] => {
const items: IDocument[] = [
{
metric: "Request Charge",
value: `${queryResults.requestCharge} RUs`,
toolTip: "Request Charge",
},
{
metric: "Showing Results",
value: queryResults.itemCount > 0 ? `${queryResults.firstItemIndex} - ${queryResults.lastItemIndex}` : `0 - 0`,
toolTip: "Showing Results",
},
];
if (userContext.apiType === "SQL") {
const aggregatedQueryMetrics = getAggregatedQueryMetrics();
items.push(
{
metric: "Retrieved document count",
value: aggregatedQueryMetrics.retrievedDocumentCount?.toString() || "",
toolTip: "Total number of retrieved documents",
},
{
metric: "Retrieved document size",
value: `${aggregatedQueryMetrics.retrievedDocumentSize?.toString() || 0} bytes`,
toolTip: "Total size of retrieved documents in bytes",
},
{
metric: "Output document count",
value: aggregatedQueryMetrics.outputDocumentCount?.toString() || "",
toolTip: "Number of output documents",
},
{
metric: "Output document size",
value: `${aggregatedQueryMetrics.outputDocumentSize?.toString() || 0} bytes`,
toolTip: "Total size of output documents in bytes",
},
{
metric: "Index hit document count",
value: aggregatedQueryMetrics.indexHitDocumentCount?.toString() || "",
toolTip: "Total number of documents matched by the filter",
},
{
metric: "Index lookup time",
value: `${aggregatedQueryMetrics.indexLookupTime?.toString() || 0} ms`,
toolTip: "Time spent in physical index layer",
},
{
metric: "Document load time",
value: `${aggregatedQueryMetrics.documentLoadTime?.toString() || 0} ms`,
toolTip: "Time spent in loading documents",
},
{
metric: "Query engine execution time",
value: `${aggregatedQueryMetrics.runtimeExecutionTimes?.queryEngineExecutionTime?.toString() || 0} ms`,
toolTip:
"Time spent by the query engine to execute the query expression (excludes other execution times like load documents or write results)",
},
{
metric: "System function execution time",
value: `${aggregatedQueryMetrics.runtimeExecutionTimes?.systemFunctionExecutionTime?.toString() || 0} ms`,
toolTip: "Total time spent executing system (built-in) functions",
},
{
metric: "User defined function execution time",
value: `${
aggregatedQueryMetrics.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.toString() || 0
} ms`,
toolTip: "Total time spent executing user-defined functions",
},
{
metric: "Document write time",
value: `${aggregatedQueryMetrics.documentWriteTime.toString() || 0} ms`,
toolTip: "Time spent to write query result set to response buffer",
}
);
}
if (queryResults.roundTrips) {
items.push({
metric: "Round Trips",
value: queryResults.roundTrips?.toString(),
toolTip: "Number of round trips",
});
}
if (queryResults.activityId) {
items.push({
metric: "Activity id",
value: queryResults.activityId,
toolTip: "",
});
}
return items;
};
return (
<Stack style={{ height: "100%" }}>
{isMongoDB && queryEditorContent.length === 0 && (
<div className="mongoQueryHelper">
Start by writing a Mongo query, for example: <strong>{"{'id':'foo'}"}</strong> or{" "}
<strong>
{"{ "}
{" }"}
</strong>{" "}
to get all the documents.
</div>
)}
{maybeSubQuery && (
<div className="warningErrorContainer" aria-live="assertive">
<div className="warningErrorContent">
<span>
<img className="paneErrorIcon" src={InfoColor} alt="Error" />
</span>
<span className="warningErrorDetailsLinkContainer">
We have detected you may be using a subquery. Non-correlated subqueries are not currently supported.
<a href="https://docs.microsoft.com/en-us/azure/cosmos-db/sql-query-subquery">
Please see Cosmos sub query documentation for further information
</a>
</span>
</div>
</div>
)}
{/* <!-- Query Errors Tab - Start--> */}
{error && (
<div className="active queryErrorsHeaderContainer">
<span className="queryErrors" data-toggle="tab">
Errors
</span>
</div>
)}
{/* <!-- Query Errors Tab - End --> */}
{/* <!-- Query Results & Errors Content Container - Start--> */}
<div className="queryResultErrorContentContainer">
{!queryResults && !error && !isExecuting && (
<div className="queryEditorWatermark">
<p>
<img src={RunQuery} alt="Execute Query Watermark" />
</p>
<p className="queryEditorWatermarkText">Execute a query to see the results</p>
</div>
)}
{(queryResults || !!error) && (
<div className="queryResultsErrorsContent">
{!error && (
<Pivot aria-label="Successful execution" style={{ height: "100%" }}>
<PivotItem
headerText="Results"
headerButtonProps={{
"data-order": 1,
"data-title": "Results",
}}
style={{ height: "100%" }}
>
<div className="result-metadata">
<span>
<span>
{queryResults.itemCount > 0
? `${queryResults.firstItemIndex} - ${queryResults.lastItemIndex}`
: `0 - 0`}
</span>
</span>
{queryResults.hasMoreResults && (
<>
<span className="queryResultDivider">|</span>
<span className="queryResultNextEnable">
<a onClick={() => onFetchNextPageClick()}>
<span>Load more</span>
<img className="queryResultnextImg" src={QueryEditorNext} alt="Fetch next page" />
</a>
</span>
</>
)}
</div>
{queryResults && queryResultsString?.length > 0 && !error && (
<div
style={{
paddingBottom: "100px",
height: "100%",
}}
>
<EditorReact
language={"json"}
content={queryResultsString}
isReadOnly={true}
ariaLabel={"Query results"}
/>
</div>
)}
</PivotItem>
<PivotItem
headerText="Query Stats"
headerButtonProps={{
"data-order": 2,
"data-title": "Query Stats",
}}
style={{ height: "100%", overflowY: "scroll" }}
>
{queryResults && !error && (
<div className="queryMetricsSummaryContainer">
<div className="queryMetricsSummary">
<h5>Query Statistics</h5>
<DetailsList
items={generateQueryStatsItems()}
columns={columns}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
compact={true}
/>
</div>
{userContext.apiType === "SQL" && (
<div className="downloadMetricsLinkContainer">
<a
id="downloadMetricsLink"
role="button"
tabIndex={0}
onClick={() => onDownloadQueryMetricsCsvClick()}
onKeyPress={(event: React.KeyboardEvent<HTMLAnchorElement>) =>
onDownloadQueryMetricsCsvKeyPress(event)
}
>
<img
className="downloadCsvImg"
src={DownloadQueryMetrics}
alt="download query metrics csv"
/>
<span>Per-partition query metrics (CSV)</span>
</a>
</div>
)}
</div>
)}
</PivotItem>
</Pivot>
)}
{/* <!-- Query Errors Content - Start--> */}
{!!error && (
<div className="tab-pane active">
<div className="errorContent">
<span className="errorMessage">{error}</span>
<span className="errorDetailsLink">
<a
onClick={() => onErrorDetailsClick()}
onKeyPress={(event: React.KeyboardEvent<HTMLAnchorElement>) => onErrorDetailsKeyPress(event)}
id="error-display"
tabIndex={0}
aria-label="Error details link"
>
More details
</a>
</span>
</div>
</div>
)}
{/* <!-- Query Errors Content - End--> */}
</div>
)}
</div>
</Stack>
);
};

View File

@@ -1,22 +1,30 @@
import { FeedOptions } from "@azure/cosmos";
import { QueryResultSection } from "Explorer/Tabs/QueryTab/QueryResultSection";
import { DetailsList, DetailsListLayoutMode, IColumn, Pivot, PivotItem, SelectionMode, Text } from "@fluentui/react";
import React, { Fragment } from "react";
import SplitterLayout from "react-splitter-layout";
import "react-splitter-layout/lib/index.css";
import DownloadQueryMetrics from "../../../../images/DownloadQuery.svg";
import ExecuteQueryIcon from "../../../../images/ExecuteQuery.svg";
import InfoColor from "../../../../images/info_color.svg";
import QueryEditorNext from "../../../../images/Query-Editor-Next.svg";
import RunQuery from "../../../../images/RunQuery.png";
import SaveQueryIcon from "../../../../images/save-cosmos.svg";
import * as Constants from "../../../Common/Constants";
import { NormalizedEventKey } from "../../../Common/Constants";
import { queryDocuments } from "../../../Common/dataAccess/queryDocuments";
import { queryDocumentsPage } from "../../../Common/dataAccess/queryDocumentsPage";
import { getErrorMessage } from "../../../Common/ErrorHandlingUtils";
import * as HeadersUtility from "../../../Common/HeadersUtility";
import { MinimalQueryIterator } from "../../../Common/IteratorUtilities";
import { queryIterator } from "../../../Common/MongoProxyClient";
import { queryDocuments } from "../../../Common/dataAccess/queryDocuments";
import { queryDocumentsPage } from "../../../Common/dataAccess/queryDocumentsPage";
import MongoUtility from "../../../Common/MongoUtility";
import { Splitter } from "../../../Common/Splitter";
import { InfoTooltip } from "../../../Common/Tooltip/InfoTooltip";
import * as DataModels from "../../../Contracts/DataModels";
import * as ViewModels from "../../../Contracts/ViewModels";
import { useNotificationConsole } from "../../../hooks/useNotificationConsole";
import { useSidePanel } from "../../../hooks/useSidePanel";
import { userContext } from "../../../UserContext";
import * as QueryUtils from "../../../Utils/QueryUtils";
import { useSidePanel } from "../../../hooks/useSidePanel";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
import { EditorReact } from "../../Controls/Editor/EditorReact";
import Explorer from "../../Explorer";
@@ -35,6 +43,7 @@ export interface IDocument {
metric: string;
value: string;
toolTip: string;
isQueryMetricsEnabled: boolean;
}
export interface ITabAccessor {
@@ -65,13 +74,30 @@ export interface IQueryTabComponentProps {
}
interface IQueryTabStates {
queryMetrics: Map<string, DataModels.QueryMetrics>;
aggregatedQueryMetrics: DataModels.QueryMetrics;
activityId: string;
roundTrips: number;
toggleState: ToggleState;
isQueryMetricsEnabled: boolean;
showingDocumentsDisplayText: string;
requestChargeDisplayText: string;
initialEditorContent: string;
sqlQueryEditorContent: string;
selectedContent: string;
queryResults: ViewModels.QueryResults;
_executeQueryButtonTitle: string;
sqlStatementToExecute: string;
queryResults: string;
statusMessge: string;
statusIcon: string;
allResultsMetadata: ViewModels.QueryResultsMetadata[];
error: string;
isTemplateReady: boolean;
_isSaveQueriesEnabled: boolean;
isExecutionError: boolean;
isExecuting: boolean;
columns: IColumn[];
items: IDocument[];
}
export default class QueryTabComponent extends React.Component<IQueryTabComponentProps, IQueryTabStates> {
@@ -79,39 +105,90 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
public executeQueryButton: Button;
public saveQueryButton: Button;
public splitterId: string;
public splitter: Splitter;
public isPreferredApiMongoDB: boolean;
public resultsDisplay: string;
protected monacoSettings: ViewModels.MonacoEditorSettings;
protected _iterator: MinimalQueryIterator;
private _resourceTokenPartitionKey: string;
_partitionKey: DataModels.PartitionKey;
public maybeSubQuery: boolean;
public isCloseClicked: boolean;
private _iterator: MinimalQueryIterator;
public allItems: IDocument[];
public defaultQueryText: string;
constructor(props: IQueryTabComponentProps) {
super(props);
const columns: IColumn[] = [
{
key: "column2",
name: "METRIC",
minWidth: 200,
data: String,
fieldName: "metric",
onRender: this.onRenderColumnItem,
},
{
key: "column3",
name: "VALUE",
minWidth: 200,
data: String,
fieldName: "value",
},
];
if (this.props.isPreferredApiMongoDB) {
this.defaultQueryText = props.queryText;
} else {
this.defaultQueryText = props.queryText !== void 0 ? props.queryText : "SELECT * FROM c";
}
this.state = {
queryMetrics: new Map(),
aggregatedQueryMetrics: undefined,
activityId: "",
roundTrips: undefined,
toggleState: ToggleState.Result,
sqlQueryEditorContent: props.queryText || "SELECT * FROM c",
isQueryMetricsEnabled: userContext.apiType === "SQL" || false,
showingDocumentsDisplayText: this.resultsDisplay,
requestChargeDisplayText: "",
initialEditorContent: this.defaultQueryText,
sqlQueryEditorContent: this.defaultQueryText,
selectedContent: "",
queryResults: undefined,
_executeQueryButtonTitle: "Execute Query",
sqlStatementToExecute: this.defaultQueryText,
queryResults: "",
statusMessge: "",
statusIcon: "",
allResultsMetadata: [],
error: "",
isTemplateReady: false,
_isSaveQueriesEnabled: userContext.apiType === "SQL" || userContext.apiType === "Gremlin",
isExecutionError: this.props.isExecutionError,
isExecuting: false,
columns: columns,
items: [],
};
this.isCloseClicked = false;
this.splitterId = this.props.tabId + "_splitter";
this.queryEditorId = `queryeditor${this.props.tabId}`;
this._partitionKey = props.partitionKey;
this.isPreferredApiMongoDB = this.props.isPreferredApiMongoDB;
this.monacoSettings = new ViewModels.MonacoEditorSettings(this.props.monacoEditorSetting, false);
this.executeQueryButton = {
enabled: !!this.state.sqlQueryEditorContent && this.state.sqlQueryEditorContent.length > 0,
visible: true,
};
const sql = this.state.sqlQueryEditorContent;
this.maybeSubQuery = sql && /.*\(.*SELECT.*\)/i.test(sql);
const isSaveQueryBtnEnabled = userContext.apiType === "SQL" || userContext.apiType === "Gremlin";
this.saveQueryButton = {
enabled: isSaveQueryBtnEnabled,
visible: isSaveQueryBtnEnabled,
enabled: this.state._isSaveQueriesEnabled,
visible: this.state._isSaveQueriesEnabled,
};
this.props.tabsBaseInstance.updateNavbarWithTabsButtons();
this._buildCommandBarOptions();
props.onTabAccessor({
onTabClickEvent: this.onTabClick.bind(this),
onSaveClickEvent: this.getCurrentEditorQuery.bind(this),
@@ -119,6 +196,165 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
});
}
public onRenderColumnItem(item: IDocument): JSX.Element {
if (item.toolTip !== "") {
return (
<>
<InfoTooltip>{`${item.toolTip}`}</InfoTooltip>
<Text style={{ paddingLeft: 10, margin: 0 }}>{`${item.metric}`}</Text>
</>
);
} else {
return undefined;
}
}
public generateDetailsList(): IDocument[] {
const items: IDocument[] = [];
const allItems: IDocument[] = [
{
metric: "Request Charge",
value: this.state.requestChargeDisplayText,
toolTip: "Request Charge",
isQueryMetricsEnabled: true,
},
{
metric: "Showing Results",
value: this.state.showingDocumentsDisplayText,
toolTip: "Showing Results",
isQueryMetricsEnabled: true,
},
{
metric: "Retrieved document count",
value:
this.state.aggregatedQueryMetrics.retrievedDocumentCount !== undefined
? this.state.aggregatedQueryMetrics.retrievedDocumentCount.toString()
: "",
toolTip: "Total number of retrieved documents",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Retrieved document size",
value:
this.state.aggregatedQueryMetrics.retrievedDocumentSize !== undefined
? this.state.aggregatedQueryMetrics.retrievedDocumentSize.toString() + " bytes"
: "",
toolTip: "Total size of retrieved documents in bytes",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Output document count",
value:
this.state.aggregatedQueryMetrics.outputDocumentCount !== undefined
? this.state.aggregatedQueryMetrics.outputDocumentCount.toString()
: "",
toolTip: "Number of output documents",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Output document size",
value:
this.state.aggregatedQueryMetrics.outputDocumentSize !== undefined
? this.state.aggregatedQueryMetrics.outputDocumentSize.toString() + " bytes"
: "",
toolTip: "Total size of output documents in bytes",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Index hit document count",
value:
this.state.aggregatedQueryMetrics.indexHitDocumentCount !== undefined
? this.state.aggregatedQueryMetrics.indexHitDocumentCount.toString()
: "",
toolTip: "Total number of documents matched by the filter",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Index lookup time",
value:
this.state.aggregatedQueryMetrics.indexLookupTime !== undefined
? this.state.aggregatedQueryMetrics.indexLookupTime.toString() + " ms"
: "",
toolTip: "Time spent in physical index layer",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Document load time",
value:
this.state.aggregatedQueryMetrics.documentLoadTime !== undefined
? this.state.aggregatedQueryMetrics.documentLoadTime.toString() + " ms"
: "",
toolTip: "Time spent in loading documents",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Query engine execution time",
value:
this.state.aggregatedQueryMetrics.runtimeExecutionTimes.queryEngineExecutionTime !== undefined
? this.state.aggregatedQueryMetrics.runtimeExecutionTimes.queryEngineExecutionTime.toString() + " ms"
: "",
toolTip:
"Time spent by the query engine to execute the query expression (excludes other execution times like load documents or write results)",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "System function execution time",
value:
this.state.aggregatedQueryMetrics.runtimeExecutionTimes.systemFunctionExecutionTime !== undefined
? this.state.aggregatedQueryMetrics.runtimeExecutionTimes.systemFunctionExecutionTime.toString() + " ms"
: "",
toolTip: "Total time spent executing system (built-in) functions",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "User defined function execution time",
value:
this.state.aggregatedQueryMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime !== undefined
? this.state.aggregatedQueryMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime.toString() +
" ms"
: "",
toolTip: "Total time spent executing user-defined functions",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Document write time",
value:
this.state.aggregatedQueryMetrics.documentWriteTime !== undefined
? this.state.aggregatedQueryMetrics.documentWriteTime.toString() + " ms"
: "",
toolTip: "Time spent to write query result set to response buffer",
isQueryMetricsEnabled: this.state.isQueryMetricsEnabled,
},
{
metric: "Round Trips",
value: this.state.roundTrips ? this.state.roundTrips.toString() : "",
toolTip: "",
isQueryMetricsEnabled: true,
},
{
metric: "Activity id",
value: this.state.activityId ? this.state.activityId : "",
toolTip: "",
isQueryMetricsEnabled: true,
},
];
allItems.forEach((item) => {
if (item.metric === "Round Trips" || item.metric === "Activity id") {
if (item.metric === "Round Trips" && this.state.roundTrips !== undefined) {
items.push(item);
} else if (item.metric === "Activity id" && this.state.activityId !== undefined) {
items.push(item);
}
} else {
if (item.isQueryMetricsEnabled) {
items.push(item);
}
}
});
return items;
}
public onCloseClick(isClicked: boolean): void {
this.isCloseClicked = isClicked;
}
@@ -136,6 +372,14 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
}
public onExecuteQueryClick = async (): Promise<void> => {
const sqlStatement = this.state.selectedContent || this.state.sqlQueryEditorContent;
this.setState({
sqlStatementToExecute: sqlStatement,
allResultsMetadata: [],
queryResults: "",
});
this._iterator = undefined;
setTimeout(async () => {
await this._executeQueryDocumentsPage(0);
@@ -152,6 +396,31 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
.openSidePanel("Open Saved Queries", <BrowseQueriesPane explorer={this.props.collection.container} />);
};
public async onFetchNextPageClick(): Promise<void> {
const allResultsMetadata = (this.state.allResultsMetadata && this.state.allResultsMetadata) || [];
const metadata: ViewModels.QueryResultsMetadata = allResultsMetadata[allResultsMetadata.length - 1];
const firstResultIndex: number = (metadata && Number(metadata.firstItemIndex)) || 1;
const itemCount: number = (metadata && Number(metadata.itemCount)) || 0;
await this._executeQueryDocumentsPage(firstResultIndex + itemCount - 1);
}
//eslint-disable-next-line
public onErrorDetailsClick = (): boolean => {
useNotificationConsole.getState().expandConsole();
return false;
};
public onErrorDetailsKeyPress = (event: React.KeyboardEvent<HTMLAnchorElement>): boolean => {
if (event.key === NormalizedEventKey.Space || event.key === NormalizedEventKey.Enter) {
this.onErrorDetailsClick();
return false;
}
return true;
};
public toggleResult(): void {
this.setState({
toggleState: ToggleState.Result,
@@ -183,30 +452,54 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
focusElement && focusElement.focus();
}
private async _executeQueryDocumentsPage(firstItemIndex: number): Promise<void> {
public isResultToggled(): boolean {
return this.state.toggleState === ToggleState.Result;
}
public isMetricsToggled(): boolean {
return this.state.toggleState === ToggleState.QueryMetrics;
}
public onDownloadQueryMetricsCsvClick = (): boolean => {
this._downloadQueryMetricsCsvData();
return false;
};
public onDownloadQueryMetricsCsvKeyPress = (event: React.KeyboardEvent<HTMLAnchorElement>): boolean => {
if (event.key === NormalizedEventKey.Space || NormalizedEventKey.Enter) {
this._downloadQueryMetricsCsvData();
return false;
}
return true;
};
//eslint-disable-next-line
private async _executeQueryDocumentsPage(firstItemIndex: number): Promise<any> {
this.setState({
error: "",
roundTrips: undefined,
});
if (this._iterator === undefined) {
this._iterator = this.props.isPreferredApiMongoDB
? queryIterator(
this.props.collection.databaseId,
this.props.viewModelcollection,
this.state.selectedContent || this.state.sqlQueryEditorContent
)
: queryDocuments(
this.props.collection.databaseId,
this.props.collection.id(),
this.state.selectedContent || this.state.sqlQueryEditorContent,
{ enableCrossPartitionQuery: HeadersUtility.shouldEnableCrossPartitionKey() } as FeedOptions
);
if (this.isPreferredApiMongoDB) {
this._initIteratorMongo();
} else {
this._initIterator();
}
}
await this._queryDocumentsPage(firstItemIndex);
}
private async _queryDocumentsPage(firstItemIndex: number): Promise<void> {
let results: string;
this.props.tabsBaseInstance.isExecutionError(false);
this.setState({
isExecutionError: false,
});
this._resetAggregateQueryMetrics();
const queryDocuments = async (firstItemIndex: number) =>
await queryDocumentsPage(this.props.collection && this.props.collection.id(), this._iterator, firstItemIndex);
@@ -220,7 +513,44 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
firstItemIndex,
queryDocuments
);
this.setState({ queryResults });
const allResultsMetadata = (this.state.allResultsMetadata && this.state.allResultsMetadata) || [];
const metadata: ViewModels.QueryResultsMetadata = allResultsMetadata[allResultsMetadata.length - 1];
const resultsMetadata: ViewModels.QueryResultsMetadata = {
hasMoreResults: queryResults.hasMoreResults,
itemCount: queryResults.itemCount,
firstItemIndex: queryResults.firstItemIndex,
lastItemIndex: queryResults.lastItemIndex,
};
this.state.allResultsMetadata.push(resultsMetadata);
this.setState({
activityId: queryResults.activityId,
roundTrips: queryResults.roundTrips,
});
const documents = queryResults.documents;
if (this.isPreferredApiMongoDB) {
results = MongoUtility.tojson(documents, undefined, false);
} else {
results = this.props.tabsBaseInstance.renderObjectForEditor(documents, undefined, 4);
}
const resultsDisplay: string =
queryResults.itemCount > 0 ? `${queryResults.firstItemIndex} - ${queryResults.lastItemIndex}` : `0 - 0`;
this.setState({
showingDocumentsDisplayText: resultsDisplay,
requestChargeDisplayText: `${queryResults.requestCharge} RUs`,
queryResults: results,
});
this._updateQueryMetricsMap(queryResults.headers[Constants.HttpHeaders.queryMetrics]);
if (queryResults.itemCount === 0 && metadata !== undefined && metadata.itemCount >= 0) {
// we let users query for the next page because the SDK sometimes specifies there are more elements
// even though there aren't any so we should not update the prior query results.
return;
}
} catch (error) {
this.props.tabsBaseInstance.isExecutionError(true);
this.setState({
@@ -241,10 +571,228 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
}
}
private _updateQueryMetricsMap(metricsMap: { [partitionKeyRange: string]: DataModels.QueryMetrics }): void {
if (!metricsMap) {
this.allItems = this.generateDetailsList();
this.setState({
items: this.allItems,
});
return;
}
Object.keys(metricsMap).forEach((key: string) => {
this.state.queryMetrics.set(key, metricsMap[key]);
});
this._aggregateQueryMetrics(this.state.queryMetrics);
this.allItems = this.generateDetailsList();
this.setState({
items: this.allItems,
});
}
private _aggregateQueryMetrics(metricsMap: Map<string, DataModels.QueryMetrics>): DataModels.QueryMetrics {
if (!metricsMap) {
return undefined;
}
const aggregatedMetrics: DataModels.QueryMetrics = this.state.aggregatedQueryMetrics;
metricsMap.forEach((queryMetrics) => {
if (queryMetrics) {
aggregatedMetrics.documentLoadTime =
this._normalize(queryMetrics.documentLoadTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.documentLoadTime);
aggregatedMetrics.documentWriteTime =
this._normalize(queryMetrics.documentWriteTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.documentWriteTime);
aggregatedMetrics.indexHitDocumentCount =
this._normalize(queryMetrics.indexHitDocumentCount) +
this._normalize(aggregatedMetrics.indexHitDocumentCount);
aggregatedMetrics.outputDocumentCount =
this._normalize(queryMetrics.outputDocumentCount) + this._normalize(aggregatedMetrics.outputDocumentCount);
aggregatedMetrics.outputDocumentSize =
this._normalize(queryMetrics.outputDocumentSize) + this._normalize(aggregatedMetrics.outputDocumentSize);
aggregatedMetrics.indexLookupTime =
this._normalize(queryMetrics.indexLookupTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.indexLookupTime);
aggregatedMetrics.retrievedDocumentCount =
this._normalize(queryMetrics.retrievedDocumentCount) +
this._normalize(aggregatedMetrics.retrievedDocumentCount);
aggregatedMetrics.retrievedDocumentSize =
this._normalize(queryMetrics.retrievedDocumentSize) +
this._normalize(aggregatedMetrics.retrievedDocumentSize);
aggregatedMetrics.vmExecutionTime =
this._normalize(queryMetrics.vmExecutionTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.vmExecutionTime);
aggregatedMetrics.totalQueryExecutionTime =
this._normalize(queryMetrics.totalQueryExecutionTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.totalQueryExecutionTime);
aggregatedMetrics.runtimeExecutionTimes.queryEngineExecutionTime =
this._normalize(queryMetrics.runtimeExecutionTimes.queryEngineExecutionTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.runtimeExecutionTimes.queryEngineExecutionTime);
aggregatedMetrics.runtimeExecutionTimes.systemFunctionExecutionTime =
this._normalize(queryMetrics.runtimeExecutionTimes.systemFunctionExecutionTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.runtimeExecutionTimes.systemFunctionExecutionTime);
aggregatedMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime =
this._normalize(queryMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime.totalMilliseconds()) +
this._normalize(aggregatedMetrics.runtimeExecutionTimes.userDefinedFunctionExecutionTime);
}
});
return aggregatedMetrics;
}
public _downloadQueryMetricsCsvData(): void {
const csvData: string = this._generateQueryMetricsCsvData();
if (!csvData) {
return;
}
if (navigator.msSaveBlob) {
// for IE and Edge
navigator.msSaveBlob(
new Blob([csvData], { type: "data:text/csv;charset=utf-8" }),
"PerPartitionQueryMetrics.csv"
);
} else {
const downloadLink: HTMLAnchorElement = document.createElement("a");
downloadLink.href = "data:text/csv;charset=utf-8," + encodeURI(csvData);
downloadLink.target = "_self";
downloadLink.download = "QueryMetricsPerPartition.csv";
// for some reason, FF displays the download prompt only when
// the link is added to the dom so we add and remove it
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
}
}
protected _initIterator(): void {
const options = QueryTabComponent.getIteratorOptions();
if (this._resourceTokenPartitionKey) {
options.partitionKey = this._resourceTokenPartitionKey;
}
this._iterator = queryDocuments(
this.props.collection.databaseId,
this.props.collection.id(),
this.state.sqlStatementToExecute,
options
);
}
protected _initIteratorMongo(): Promise<MinimalQueryIterator> {
//eslint-disable-next-line
const options: any = {};
options.enableCrossPartitionQuery = HeadersUtility.shouldEnableCrossPartitionKey();
this._iterator = queryIterator(
this.props.collection.databaseId,
this.props.viewModelcollection,
this.state.sqlStatementToExecute
);
const mongoPromise: Promise<MinimalQueryIterator> = new Promise((resolve) => {
resolve(this._iterator);
});
return mongoPromise;
}
//eslint-disable-next-line
public static getIteratorOptions(collection?: ViewModels.Collection): any {
//eslint-disable-next-line
const options: any = {};
options.enableCrossPartitionQuery = HeadersUtility.shouldEnableCrossPartitionKey();
return options;
}
private _normalize(value: number): number {
if (!value) {
return 0;
}
return value;
}
private _resetAggregateQueryMetrics(): void {
this.setState({
aggregatedQueryMetrics: {
clientSideMetrics: {},
documentLoadTime: undefined,
documentWriteTime: undefined,
indexHitDocumentCount: undefined,
outputDocumentCount: undefined,
outputDocumentSize: undefined,
indexLookupTime: undefined,
retrievedDocumentCount: undefined,
retrievedDocumentSize: undefined,
vmExecutionTime: undefined,
queryPreparationTimes: undefined,
runtimeExecutionTimes: {
queryEngineExecutionTime: undefined,
systemFunctionExecutionTime: undefined,
userDefinedFunctionExecutionTime: undefined,
},
totalQueryExecutionTime: undefined,
},
});
}
private _generateQueryMetricsCsvData(): string {
if (!this.state.queryMetrics) {
return undefined;
}
const queryMetrics = this.state.queryMetrics;
let csvData = "";
const columnHeaders: string =
[
"Partition key range id",
"Retrieved document count",
"Retrieved document size (in bytes)",
"Output document count",
"Output document size (in bytes)",
"Index hit document count",
"Index lookup time (ms)",
"Document load time (ms)",
"Query engine execution time (ms)",
"System function execution time (ms)",
"User defined function execution time (ms)",
"Document write time (ms)",
].join(",") + "\n";
csvData = csvData + columnHeaders;
queryMetrics.forEach((queryMetric, partitionKeyRangeId) => {
const partitionKeyRangeData: string =
[
partitionKeyRangeId,
queryMetric.retrievedDocumentCount,
queryMetric.retrievedDocumentSize,
queryMetric.outputDocumentCount,
queryMetric.outputDocumentSize,
queryMetric.indexHitDocumentCount,
queryMetric.indexLookupTime && queryMetric.indexLookupTime.totalMilliseconds(),
queryMetric.documentLoadTime && queryMetric.documentLoadTime.totalMilliseconds(),
queryMetric.runtimeExecutionTimes &&
queryMetric.runtimeExecutionTimes.queryEngineExecutionTime &&
queryMetric.runtimeExecutionTimes.queryEngineExecutionTime.totalMilliseconds(),
queryMetric.runtimeExecutionTimes &&
queryMetric.runtimeExecutionTimes.systemFunctionExecutionTime &&
queryMetric.runtimeExecutionTimes.systemFunctionExecutionTime.totalMilliseconds(),
queryMetric.runtimeExecutionTimes &&
queryMetric.runtimeExecutionTimes.userDefinedFunctionExecutionTime &&
queryMetric.runtimeExecutionTimes.userDefinedFunctionExecutionTime.totalMilliseconds(),
queryMetric.documentWriteTime && queryMetric.documentWriteTime.totalMilliseconds(),
].join(",") + "\n";
csvData = csvData + partitionKeyRangeData;
});
return csvData;
}
protected getTabsButtons(): CommandButtonComponentProps[] {
const buttons: CommandButtonComponentProps[] = [];
if (this.executeQueryButton.visible) {
const label = this.state.selectedContent?.length > 0 ? "Execute Selection" : "Execute Query";
const label = this.state._executeQueryButtonTitle;
buttons.push({
iconSrc: ExecuteQueryIcon,
iconAlt: label,
@@ -272,6 +820,10 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
return buttons;
}
private _buildCommandBarOptions(): void {
this.props.tabsBaseInstance.updateNavbarWithTabsButtons();
}
public onChangeContent(newContent: string): void {
this.setState({
sqlQueryEditorContent: newContent,
@@ -296,11 +848,13 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
public onSelectedContent(selectedContent: string): void {
if (selectedContent.trim().length > 0) {
this.setState({
selectedContent,
selectedContent: selectedContent,
_executeQueryButtonTitle: "Execute Selection",
});
} else {
this.setState({
selectedContent: "",
_executeQueryButtonTitle: "Execute Query",
});
}
useCommandBar.getState().setContextButtons(this.getTabsButtons());
@@ -320,7 +874,7 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
<div className="queryEditor" style={{ height: "100%" }}>
<EditorReact
language={"sql"}
content={this.state.sqlQueryEditorContent}
content={this.state.initialEditorContent}
isReadOnly={false}
ariaLabel={"Editing Query"}
lineNumbers={"on"}
@@ -329,14 +883,174 @@ export default class QueryTabComponent extends React.Component<IQueryTabComponen
/>
</div>
</Fragment>
<QueryResultSection
isMongoDB={this.props.isPreferredApiMongoDB}
queryEditorContent={this.state.sqlQueryEditorContent}
error={this.state.error}
queryResults={this.state.queryResults}
isExecuting={this.state.isExecuting}
executeQueryDocumentsPage={(firstItemIndex: number) => this._executeQueryDocumentsPage(firstItemIndex)}
/>
<Fragment>
{this.isPreferredApiMongoDB && this.state.sqlQueryEditorContent.length === 0 && (
<div className="mongoQueryHelper">
Start by writing a Mongo query, for example: <strong>{"{'id':'foo'}"}</strong> or{" "}
<strong>
{"{ "}
{" }"}
</strong>{" "}
to get all the documents.
</div>
)}
{this.maybeSubQuery && (
<div className="warningErrorContainer" aria-live="assertive">
<div className="warningErrorContent">
<span>
<img className="paneErrorIcon" src={InfoColor} alt="Error" />
</span>
<span className="warningErrorDetailsLinkContainer">
We have detected you may be using a subquery. Non-correlated subqueries are not currently
supported.
<a href="https://docs.microsoft.com/en-us/azure/cosmos-db/sql-query-subquery">
Please see Cosmos sub query documentation for further information
</a>
</span>
</div>
</div>
)}
{/* <!-- Query Errors Tab - Start--> */}
{!!this.state.error && (
<div className="active queryErrorsHeaderContainer">
<span className="queryErrors" data-toggle="tab">
Errors
</span>
</div>
)}
{/* <!-- Query Errors Tab - End --> */}
{/* <!-- Query Results & Errors Content Container - Start--> */}
<div className="queryResultErrorContentContainer">
{this.state.allResultsMetadata.length === 0 &&
!this.state.error &&
!this.state.queryResults &&
!this.props.tabsBaseInstance.isExecuting() && (
<div className="queryEditorWatermark">
<p>
<img src={RunQuery} alt="Execute Query Watermark" />
</p>
<p className="queryEditorWatermarkText">Execute a query to see the results</p>
</div>
)}
{(this.state.allResultsMetadata.length > 0 || !!this.state.error || this.state.queryResults) && (
<div className="queryResultsErrorsContent">
{!this.state.error && (
<Pivot aria-label="Successful execution" style={{ height: "100%" }}>
<PivotItem
headerText="Results"
headerButtonProps={{
"data-order": 1,
"data-title": "Results",
}}
style={{ height: "100%" }}
>
<div className="result-metadata">
<span>
<span>{this.state.showingDocumentsDisplayText}</span>
</span>
{this.state.allResultsMetadata[this.state.allResultsMetadata.length - 1]
.hasMoreResults && (
<>
<span className="queryResultDivider">|</span>
<span className="queryResultNextEnable">
<a onClick={this.onFetchNextPageClick.bind(this)}>
<span>Load more</span>
<img className="queryResultnextImg" src={QueryEditorNext} alt="Fetch next page" />
</a>
</span>
</>
)}
</div>
{this.state.queryResults &&
this.state.queryResults.length > 0 &&
this.state.allResultsMetadata.length > 0 &&
!this.state.error && (
<div
style={{
paddingBottom: "100px",
height: "100%",
}}
>
<EditorReact
language={"json"}
content={this.state.queryResults}
isReadOnly={true}
ariaLabel={"Query results"}
/>
</div>
)}
</PivotItem>
<PivotItem
headerText="Query Stats"
headerButtonProps={{
"data-order": 2,
"data-title": "Query Stats",
}}
style={{ height: "100%", overflowY: "scroll" }}
>
{this.state.allResultsMetadata.length > 0 && !this.state.error && (
<div className="queryMetricsSummaryContainer">
<div className="queryMetricsSummary">
<h5>Query Statistics</h5>
<DetailsList
items={this.state.items}
columns={this.state.columns}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
compact={true}
/>
</div>
{this.state.isQueryMetricsEnabled && (
<div className="downloadMetricsLinkContainer">
<a
id="downloadMetricsLink"
role="button"
tabIndex={0}
onClick={() => this.onDownloadQueryMetricsCsvClick()}
onKeyPress={(event: React.KeyboardEvent<HTMLAnchorElement>) =>
this.onDownloadQueryMetricsCsvKeyPress(event)
}
>
<img
className="downloadCsvImg"
src={DownloadQueryMetrics}
alt="download query metrics csv"
/>
<span>Per-partition query metrics (CSV)</span>
</a>
</div>
)}
</div>
)}
</PivotItem>
</Pivot>
)}
{/* <!-- Query Errors Content - Start--> */}
{!!this.state.error && (
<div className="tab-pane active">
<div className="errorContent">
<span className="errorMessage">{this.state.error}</span>
<span className="errorDetailsLink">
<a
onClick={() => this.onErrorDetailsClick()}
onKeyPress={(event: React.KeyboardEvent<HTMLAnchorElement>) =>
this.onErrorDetailsKeyPress(event)
}
id="error-display"
tabIndex={0}
aria-label="Error details link"
>
More details
</a>
</span>
</div>
</div>
)}
{/* <!-- Query Errors Content - End--> */}
</div>
)}
</div>
</Fragment>
</SplitterLayout>
</div>
</div>

View File

@@ -3,7 +3,6 @@ import { sendMessage } from "Common/MessageHandler";
import { MessageTypes } from "Contracts/ExplorerContracts";
import { CollectionTabKind } from "Contracts/ViewModels";
import Explorer from "Explorer/Explorer";
import { QueryCopilotTab } from "Explorer/QueryCopilot/QueryCopilotTab";
import { SplashScreen } from "Explorer/SplashScreen/SplashScreen";
import { ConnectTab } from "Explorer/Tabs/ConnectTab";
import { PostgresConnectTab } from "Explorer/Tabs/PostgresConnectTab";
@@ -69,13 +68,6 @@ function TabNav({ tab, active, tabKind }: { tab?: Tab; active: boolean; tabKind?
const focusTab = useRef<HTMLLIElement>() as MutableRefObject<HTMLLIElement>;
const tabId = tab ? tab.tabId : "connect";
const getReactTabTitle = (): ko.Observable<string> => {
if (tabKind === ReactTabKind.QueryCopilot) {
return ko.observable("Query");
}
return ko.observable(ReactTabKind[tabKind]);
};
useEffect(() => {
if (active && focusTab.current) {
focusTab.current.focus();
@@ -117,7 +109,7 @@ function TabNav({ tab, active, tabKind }: { tab?: Tab; active: boolean; tabKind?
<img className="loadingIcon" title="Loading" src={loadingIcon} alt="Loading" />
)}
</span>
<span className="tabNavText">{useObservable(tab?.tabTitle || getReactTabTitle())}</span>
<span className="tabNavText">{useObservable(tab?.tabTitle || ko.observable(ReactTabKind[tabKind]))}</span>
{tabKind !== ReactTabKind.Home && (
<span className="tabIconSection">
<CloseButton tab={tab} active={active} hovering={hovering} tabKind={tabKind} />
@@ -219,8 +211,6 @@ const getReactTabContent = (activeReactTab: ReactTabKind, explorer: Explorer): J
return <SplashScreen explorer={explorer} />;
case ReactTabKind.Quickstart:
return <QuickstartTab explorer={explorer} />;
case ReactTabKind.QueryCopilot:
return <QueryCopilotTab initialInput={useTabs.getState().queryCopilotTabInitialInput} explorer={explorer} />;
default:
throw Error(`Unsupported tab kind ${ReactTabKind[activeReactTab]}`);
}

View File

@@ -1,13 +1,13 @@
// CSS Dependencies
import { initializeIcons } from "@fluentui/react";
import "bootstrap/dist/css/bootstrap.css";
import { QuickstartCarousel } from "Explorer/Quickstart/QuickstartCarousel";
import { MongoQuickstartTutorial } from "Explorer/Quickstart/Tutorials/MongoQuickstartTutorial";
import { SQLQuickstartTutorial } from "Explorer/Quickstart/Tutorials/SQLQuickstartTutorial";
import { userContext } from "UserContext";
import "bootstrap/dist/css/bootstrap.css";
import { useCarousel } from "hooks/useCarousel";
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { userContext } from "UserContext";
import "../externals/jquery-ui.min.css";
import "../externals/jquery-ui.min.js";
import "../externals/jquery-ui.structure.min.css";
@@ -16,21 +16,19 @@ import "../externals/jquery.dataTables.min.css";
import "../externals/jquery.typeahead.min.css";
import "../externals/jquery.typeahead.min.js";
// Image Dependencies
import { QueryCopilotCarousel } from "Explorer/QueryCopilot/CopilotCarousel";
import { QueryCopilotFeedbackModal } from "Explorer/QueryCopilot/QueryCopilotFeedbackModal";
import "../images/CosmosDB_rgb_ui_lighttheme.ico";
import hdeConnectImage from "../images/HdeConnectCosmosDB.svg";
import "../images/favicon.ico";
import "../less/TableStyles/CustomizeColumns.less";
import "../less/TableStyles/EntityEditor.less";
import "../less/TableStyles/fulldatatables.less";
import "../less/TableStyles/queryBuilder.less";
import hdeConnectImage from "../images/HdeConnectCosmosDB.svg";
import "../less/documentDB.less";
import "../less/forms.less";
import "../less/infobox.less";
import "../less/menus.less";
import "../less/messagebox.less";
import "../less/resourceTree.less";
import "../less/TableStyles/CustomizeColumns.less";
import "../less/TableStyles/EntityEditor.less";
import "../less/TableStyles/fulldatatables.less";
import "../less/TableStyles/queryBuilder.less";
import "../less/tree.less";
import { CollapsedResourceTree } from "./Common/CollapsedResourceTree";
import { ResourceTreeContainer } from "./Common/ResourceTreeContainer";
@@ -52,17 +50,16 @@ import "./Explorer/Panes/PanelComponent.less";
import { SidePanel } from "./Explorer/Panes/PanelContainerComponent";
import "./Explorer/SplashScreen/SplashScreen.less";
import { Tabs } from "./Explorer/Tabs/Tabs";
import "./Libs/jquery";
import "./Shared/appInsights";
import { useConfig } from "./hooks/useConfig";
import { useKnockoutExplorer } from "./hooks/useKnockoutExplorer";
import "./Libs/jquery";
import "./Shared/appInsights";
initializeIcons();
const App: React.FunctionComponent = () => {
const [isLeftPaneExpanded, setIsLeftPaneExpanded] = useState<boolean>(true);
const isCarouselOpen = useCarousel((state) => state.shouldOpen);
const isCopilotCarouselOpen = useCarousel((state) => state.showCopilotCarousel);
const config = useConfig();
const explorer = useKnockoutExplorer(config?.platform);
@@ -125,8 +122,6 @@ const App: React.FunctionComponent = () => {
{<QuickstartCarousel isOpen={isCarouselOpen} />}
{<SQLQuickstartTutorial />}
{<MongoQuickstartTutorial />}
{<QueryCopilotCarousel isOpen={isCopilotCarouselOpen} explorer={explorer} />}
{<QueryCopilotFeedbackModal />}
</div>
);
};

View File

@@ -35,7 +35,6 @@ export type Features = {
readonly enableLegacyMongoShellV2: boolean;
readonly enableLegacyMongoShellV2Debug: boolean;
readonly loadLegacyMongoShellFromBE: boolean;
readonly enableCopilot: boolean;
// can be set via both flight and feature flag
autoscaleDefault: boolean;
@@ -103,8 +102,6 @@ export function extractFeatures(given = new URLSearchParams(window.location.sear
enableLegacyMongoShellV2: "true" === get("enablelegacymongoshellv2"),
enableLegacyMongoShellV2Debug: "true" === get("enablelegacymongoshellv2debug"),
loadLegacyMongoShellFromBE: "true" === get("loadlegacymongoshellfrombe"),
enableCopilot: true,
// enableCopilot: "true" === get("enablecopilot"),
};
}

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account. */
export async function listCassandraKeyspaces(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given database account and collection. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given collection, split by partition. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given collection and region, split by partition. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given database account, collection and region. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given database account and database. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given database account and region. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the properties of an existing Azure Cosmos DB database account. */
export async function get(
@@ -29,7 +29,13 @@ export async function update(
body: Types.DatabaseAccountUpdateParameters
): Promise<Types.DatabaseAccountGetResults> {
const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PATCH", apiVersion, body });
return armRequest({
host: configContext.ARM_ENDPOINT,
path,
method: "PATCH",
apiVersion,
body,
});
}
/* Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when performing updates on an account. */

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists the Gremlin databases under an existing Azure Cosmos DB database account. */
export async function listGremlinDatabases(

View File

@@ -1,27 +0,0 @@
/*
AUTOGENERATED FILE
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
*/
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
/* List Cosmos DB locations and their properties */
export async function list(subscriptionId: string): Promise<Types.LocationListResult | Types.CloudError> {
const path = `/subscriptions/${subscriptionId}/providers/Microsoft.DocumentDB/locations`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion });
}
/* Get the properties of an existing Cosmos DB location */
export async function get(
subscriptionId: string,
location: string
): Promise<Types.LocationGetResult | Types.CloudError> {
const path = `/subscriptions/${subscriptionId}/providers/Microsoft.DocumentDB/locations/${location}`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion });
}

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists the MongoDB databases under an existing Azure Cosmos DB database account. */
export async function listMongoDBDatabases(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists all of the available Cosmos DB Resource Provider operations. */
export async function list(): Promise<Types.OperationListResult> {

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given partition key range id. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given partition key range id and region. */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given database account. This url is only for PBS and Replication Latency data */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given account, source and target region. This url is only for PBS and Replication Latency data */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Retrieves the metrics determined by the given filter for the given account target region. This url is only for PBS and Replication Latency data */
export async function listMetrics(

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists the SQL databases under an existing Azure Cosmos DB database account. */
export async function listSqlDatabases(
@@ -197,42 +197,6 @@ export async function migrateSqlContainerToManualThroughput(
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "POST", apiVersion });
}
/* Lists the ClientEncryptionKeys under an existing Azure Cosmos DB SQL database. */
export async function listClientEncryptionKeys(
subscriptionId: string,
resourceGroupName: string,
accountName: string,
databaseName: string
): Promise<Types.ClientEncryptionKeysListResult> {
const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/clientEncryptionKeys`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion });
}
/* Gets the ClientEncryptionKey under an existing Azure Cosmos DB SQL database. */
export async function getClientEncryptionKey(
subscriptionId: string,
resourceGroupName: string,
accountName: string,
databaseName: string,
clientEncryptionKeyName: string
): Promise<Types.ClientEncryptionKeyGetResults> {
const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/clientEncryptionKeys/${clientEncryptionKeyName}`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion });
}
/* Create or update a ClientEncryptionKey. This API is meant to be invoked via tools such as the Azure Powershell (instead of directly). */
export async function createUpdateClientEncryptionKey(
subscriptionId: string,
resourceGroupName: string,
accountName: string,
databaseName: string,
clientEncryptionKeyName: string,
body: Types.ClientEncryptionKeyCreateUpdateParameters
): Promise<Types.ClientEncryptionKeyGetResults | void> {
const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/clientEncryptionKeys/${clientEncryptionKeyName}`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body });
}
/* Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. */
export async function listSqlStoredProcedures(
subscriptionId: string,
@@ -240,7 +204,7 @@ export async function listSqlStoredProcedures(
accountName: string,
databaseName: string,
containerName: string
): Promise<Types.SqlStoredProcedureListResult | Types.CloudError> {
): Promise<Types.SqlStoredProcedureListResult> {
const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/storedProcedures`;
return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion });
}

View File

@@ -3,13 +3,13 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
import { configContext } from "../../../../ConfigContext";
import { armRequest } from "../../request";
import * as Types from "./types";
import { configContext } from "../../../../ConfigContext";
const apiVersion = "2023-04-15";
const apiVersion = "2021-04-15";
/* Lists the Tables under an existing Azure Cosmos DB database account. */
export async function listTables(

View File

@@ -3,15 +3,9 @@
Run "npm run generateARMClients" to regenerate
Edting this file directly should be done with extreme caution as not to diverge from ARM REST specs
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2023-04-15/cosmos-db.json
Generated from: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-04-15/cosmos-db.json
*/
/* The List operation response, that contains the client encryption keys and their properties. */
export interface ClientEncryptionKeysListResult {
/* List of client encryption keys and their properties. */
readonly value?: ClientEncryptionKeyGetResults[];
}
/* The List operation response, that contains the database accounts and their properties. */
export interface DatabaseAccountsListResult {
/* List of database account and their properties. */
@@ -167,30 +161,6 @@ export interface ARMProxyResource {
readonly type?: string;
}
/* Parameters to create and update ClientEncryptionKey. */
export interface ClientEncryptionKeyCreateUpdateParameters {
/* Properties to create and update ClientEncryptionKey. */
properties: ClientEncryptionKeyCreateUpdateProperties;
}
/* Properties to create and update ClientEncryptionKey. */
export interface ClientEncryptionKeyCreateUpdateProperties {
/* The standard JSON format of a ClientEncryptionKey */
resource: ClientEncryptionKeyResource;
}
/* Client Encryption Key. */
export type ClientEncryptionKeyGetResults = ARMProxyResource & {
/* The properties of a ClientEncryptionKey */
properties?: ClientEncryptionKeyGetProperties;
};
/* The properties of a ClientEncryptionKey resource */
export interface ClientEncryptionKeyGetProperties {
/* undocumented */
resource?: ClientEncryptionKeyResource & ExtendedResourceProperties;
}
/* An Azure Cosmos DB database account. */
export type DatabaseAccountGetResults = ARMResourceProperties & {
/* Indicates the type of database account. This can only be set at database account creation. */
@@ -201,9 +171,6 @@ export type DatabaseAccountGetResults = ARMResourceProperties & {
/* undocumented */
properties?: DatabaseAccountGetProperties;
/* The system meta data relating to this resource. */
readonly systemData?: unknown;
};
/* The system generated resource properties associated with SQL databases, SQL containers, Gremlin databases and Gremlin graphs. */
@@ -479,17 +446,6 @@ export interface DatabaseAccountGetProperties {
/* Flag to indicate whether to enable storage analytics. */
enableAnalyticalStorage?: boolean;
/* Analytical storage specific properties. */
analyticalStorageConfiguration?: AnalyticalStorageConfiguration;
/* A unique identifier assigned to the database account */
readonly instanceId?: string;
/* Enum to indicate the mode of account creation. */
createMode?: CreateMode;
/* Parameters to indicate the information about the restore. */
restoreParameters?: RestoreParameters;
/* The object representing the policy for taking backups on an account. */
backupPolicy?: BackupPolicy;
@@ -501,19 +457,6 @@ export interface DatabaseAccountGetProperties {
/* An array that contains the Resource Ids for Network Acl Bypass for the Cosmos DB account. */
networkAclBypassResourceIds?: unknown[];
/* Opt-out of local authentication and ensure only MSI and AAD can be used exclusively for authentication. */
disableLocalAuth?: boolean;
/* The object that represents all properties related to capacity enforcement on an account. */
capacity?: Capacity;
/* The object that represents the metadata for the Account Keys of the Cosmos DB account. */
keysMetadata?: DatabaseAccountKeysMetadata;
/* Flag to indicate enabling/disabling of Partition Merge feature on the account */
enablePartitionMerge?: boolean;
/* Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. */
minimalTlsVersion?: MinimalTlsVersion;
}
/* Properties to create and update Azure Cosmos DB database accounts. */
@@ -563,12 +506,6 @@ export interface DatabaseAccountCreateUpdateProperties {
/* Flag to indicate whether to enable storage analytics. */
enableAnalyticalStorage?: boolean;
/* Analytical storage specific properties. */
analyticalStorageConfiguration?: AnalyticalStorageConfiguration;
/* Enum to indicate the mode of account creation. */
createMode?: CreateMode;
/* The object representing the policy for taking backups on an account. */
backupPolicy?: BackupPolicy;
@@ -580,22 +517,6 @@ export interface DatabaseAccountCreateUpdateProperties {
/* An array that contains the Resource Ids for Network Acl Bypass for the Cosmos DB account. */
networkAclBypassResourceIds?: unknown[];
/* Opt-out of local authentication and ensure only MSI and AAD can be used exclusively for authentication. */
disableLocalAuth?: boolean;
/* Parameters to indicate the information about the restore. */
restoreParameters?: RestoreParameters;
/* The object that represents all properties related to capacity enforcement on an account. */
capacity?: Capacity;
/* This property is ignored during the update/create operation, as the metadata is read-only. The object represents the metadata for the Account Keys of the Cosmos DB account. */
keysMetadata?: DatabaseAccountKeysMetadata;
/* Flag to indicate enabling/disabling of Partition Merge feature on the account */
enablePartitionMerge?: boolean;
/* Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. */
minimalTlsVersion?: MinimalTlsVersion;
}
/* Parameters to create and update Cosmos DB database accounts. */
@@ -654,9 +575,6 @@ export interface DatabaseAccountUpdateProperties {
/* Flag to indicate whether to enable storage analytics. */
enableAnalyticalStorage?: boolean;
/* Analytical storage specific properties. */
analyticalStorageConfiguration?: AnalyticalStorageConfiguration;
/* The object representing the policy for taking backups on an account. */
backupPolicy?: BackupPolicy;
@@ -668,19 +586,6 @@ export interface DatabaseAccountUpdateProperties {
/* An array that contains the Resource Ids for Network Acl Bypass for the Cosmos DB account. */
networkAclBypassResourceIds?: unknown[];
/* Opt-out of local authentication and ensure only MSI and AAD can be used exclusively for authentication. */
disableLocalAuth?: boolean;
/* The object that represents all properties related to capacity enforcement on an account. */
capacity?: Capacity;
/* This property is ignored during the update operation, as the metadata is read-only. The object represents the metadata for the Account Keys of the Cosmos DB account. */
keysMetadata?: DatabaseAccountKeysMetadata;
/* Flag to indicate enabling/disabling of Partition Merge feature on the account */
enablePartitionMerge?: boolean;
/* Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. */
minimalTlsVersion?: MinimalTlsVersion;
}
/* Parameters for patching Azure Cosmos DB database account properties. */
@@ -719,20 +624,6 @@ export interface DatabaseAccountConnectionString {
readonly connectionString?: string;
/* Description of the connection string */
readonly description?: string;
/* Kind of the connection string key */
readonly keyKind?: "Primary" | "Secondary" | "PrimaryReadonly" | "SecondaryReadonly";
/* Type of the connection string */
readonly type?:
| "Sql"
| "Table"
| "MongoDB"
| "Cassandra"
| "CassandraConnectorMetadata"
| "Gremlin"
| "SqlDedicatedGateway"
| "GremlinV2"
| "Undefined";
}
/* The connection strings for the given database account. */
@@ -953,10 +844,6 @@ export interface ThroughputSettingsResource {
readonly minimumThroughput?: string;
/* The throughput replace is pending */
readonly offerReplacePending?: string;
/* The offer throughput value to instantly scale up without triggering splits */
readonly instantMaximumThroughput?: string;
/* The maximum throughput value or the maximum maxThroughput value (for autoscale) that can be specified */
readonly softAllowedMaximumThroughput?: string;
}
/* Cosmos DB provisioned throughput settings object */
@@ -992,30 +879,6 @@ export interface OptionsResource {
autoscaleSettings?: AutoscaleSettings;
}
/* Cosmos DB client encryption key resource object. */
export interface ClientEncryptionKeyResource {
/* Name of the ClientEncryptionKey */
id?: string;
/* Encryption algorithm that will be used along with this client encryption key to encrypt/decrypt data. */
encryptionAlgorithm?: string;
/* Wrapped (encrypted) form of the key represented as a byte array. */
wrappedDataEncryptionKey?: string;
/* Metadata for the wrapping provider that can be used to unwrap the wrapped client encryption key. */
keyWrapMetadata?: KeyWrapMetadata;
}
/* Represents key wrap metadata that a key wrapping provider can use to wrap/unwrap a client encryption key. */
export interface KeyWrapMetadata {
/* The name of associated KeyEncryptionKey (aka CustomerManagedKey). */
name?: string;
/* ProviderName of KeyStoreProvider. */
type?: string;
/* Reference / link to the KeyEncryptionKey. */
value?: string;
/* Algorithm used in wrapping and unwrapping of the data encryption key. */
algorithm?: string;
}
/* Cosmos DB SQL database resource object */
export interface SqlDatabaseResource {
/* Name of the Cosmos DB SQL database */
@@ -1040,9 +903,6 @@ export interface SqlContainerResource {
/* The conflict resolution policy for the container. */
conflictResolutionPolicy?: ConflictResolutionPolicy;
/* The client encryption policy for the container. */
clientEncryptionPolicy?: ClientEncryptionPolicy;
/* Analytical TTL. */
analyticalStorageTtl?: number;
}
@@ -1154,27 +1014,6 @@ export interface ConflictResolutionPolicy {
conflictResolutionProcedure?: string;
}
/* Cosmos DB client encryption policy. */
export interface ClientEncryptionPolicy {
/* Paths of the item that need encryption along with path-specific settings. */
includedPaths: ClientEncryptionIncludedPath[];
/* Version of the client encryption policy definition. Supported versions are 1 and 2. Version 2 supports id and partition key path encryption. */
policyFormatVersion: number;
}
/* . */
export interface ClientEncryptionIncludedPath {
/* Path that needs to be encrypted. */
path: string;
/* The identifier of the Client Encryption Key to be used to encrypt the path. */
clientEncryptionKeyId: string;
/* The type of encryption to be performed. Eg - Deterministic, Randomized. */
encryptionType: string;
/* The encryption algorithm which will be used. Eg - AEAD_AES_256_CBC_HMAC_SHA256. */
encryptionAlgorithm: string;
}
/* Cosmos DB SQL storedProcedure resource object */
export interface SqlStoredProcedureResource {
/* Name of the Cosmos DB SQL storedProcedure */
@@ -1196,7 +1035,7 @@ export interface SqlTriggerResource {
/* Name of the Cosmos DB SQL trigger */
id: string;
/* Body of the Trigger */
body?: string;
body: string;
/* Type of the Trigger */
triggerType?: "Pre" | "Post";
@@ -1335,9 +1174,6 @@ export interface GremlinGraphResource {
/* The conflict resolution policy for the graph. */
conflictResolutionPolicy?: ConflictResolutionPolicy;
/* Analytical TTL. */
analyticalStorageTtl?: number;
}
/* CreateUpdateOptions are a list of key-value pairs that describe the resource. Supported keys are "If-Match", "If-None-Match", "Session-Token" and "Throughput" */
@@ -1360,12 +1196,6 @@ export interface Capability {
name?: string;
}
/* The object that represents all properties related to capacity enforcement on an account. */
export interface Capacity {
/* The total throughput limit imposed on the account. A totalThroughputLimit of 2000 imposes a strict limit of max throughput that can be provisioned on that account to be 2000. A totalThroughputLimit of -1 indicates no limits on provisioning of throughput. */
totalThroughputLimit?: number;
}
/* Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". */
export type Tags = { [key: string]: string };
@@ -1405,27 +1235,6 @@ export interface VirtualNetworkRule {
/* Indicates what services are allowed to bypass firewall checks. */
export type NetworkAclBypass = "None" | "AzureServices";
/* The metadata related to an access key for a given database account. */
export interface AccountKeyMetadata {
/* Generation time in UTC of the key in ISO-8601 format. If the value is missing from the object, it means that the last key regeneration was triggered before 2022-06-18. */
readonly generationTime?: string;
}
/* The metadata related to each access key for the given Cosmos DB database account. */
export interface DatabaseAccountKeysMetadata {
/* The metadata related to the Primary Read-Write Key for the given Cosmos DB database account. */
readonly primaryMasterKey?: AccountKeyMetadata;
/* The metadata related to the Secondary Read-Write Key for the given Cosmos DB database account. */
readonly secondaryMasterKey?: AccountKeyMetadata;
/* The metadata related to the Primary Read-Only Key for the given Cosmos DB database account. */
readonly primaryReadonlyMasterKey?: AccountKeyMetadata;
/* The metadata related to the Secondary Read-Only Key for the given Cosmos DB database account. */
readonly secondaryReadonlyMasterKey?: AccountKeyMetadata;
}
/* REST API operation */
export interface Operation {
/* Operation name: {provider}/{resource}/{operation} */
@@ -1621,97 +1430,23 @@ export type UnitType = "Count" | "Bytes" | "Seconds" | "Percent" | "CountPerSeco
export type ConnectorOffer = "Small";
/* Whether requests from Public Network are allowed */
export type PublicNetworkAccess = "Enabled" | "Disabled" | "SecuredByPerimeter";
export type PublicNetworkAccess = "Enabled" | "Disabled";
/* undocumented */
export interface ApiProperties {
/* Describes the ServerVersion of an a MongoDB account. */
serverVersion?: "3.2" | "3.6" | "4.0" | "4.2";
serverVersion?: "3.2" | "3.6" | "4.0";
}
/* Analytical storage specific properties. */
export interface AnalyticalStorageConfiguration {
/* undocumented */
schemaType?: AnalyticalStorageSchemaType;
}
/* Describes the types of schema for analytical storage. */
export type AnalyticalStorageSchemaType = "WellDefined" | "FullFidelity";
/* Enum to indicate the mode of account creation. */
export type CreateMode = "Default" | "Restore";
/* Parameters to indicate the information about the restore. */
export interface RestoreParameters {
/* Describes the mode of the restore. */
restoreMode?: "PointInTime";
/* The id of the restorable database account from which the restore has to be initiated. For example: /subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{restorableDatabaseAccountName} */
restoreSource?: string;
/* Time to which the account has to be restored (ISO-8601 format). */
restoreTimestampInUtc?: string;
/* List of specific databases available for restore. */
databasesToRestore?: DatabaseRestoreResource[];
/* List of specific gremlin databases available for restore. */
gremlinDatabasesToRestore?: GremlinDatabaseRestoreResource[];
/* List of specific tables available for restore. */
tablesToRestore?: TableName[];
}
/* Specific Databases to restore. */
export interface DatabaseRestoreResource {
/* The name of the database available for restore. */
databaseName?: string;
/* The names of the collections available for restore. */
collectionNames?: CollectionName[];
}
/* Specific Gremlin Databases to restore. */
export interface GremlinDatabaseRestoreResource {
/* The name of the gremlin database available for restore. */
databaseName?: string;
/* The names of the graphs available for restore. */
graphNames?: GraphName[];
}
/* The name of the collection. */
export type CollectionName = string;
/* The name of the graph. */
export type GraphName = string;
/* The name of the table. */
export type TableName = string;
/* The object representing the policy for taking backups on an account. */
export interface BackupPolicy {
/* Describes the mode of backups. */
/* undocumented */
type: BackupPolicyType;
/* The object representing the state of the migration between the backup policies. */
migrationState?: BackupPolicyMigrationState;
}
/* Describes the mode of backups. */
export type BackupPolicyType = "Periodic" | "Continuous";
/* The object representing the state of the migration between the backup policies. */
export interface BackupPolicyMigrationState {
/* Describes the status of migration between backup policy types. */
status?: BackupPolicyMigrationStatus;
/* Describes the target backup policy type of the backup policy migration. */
targetType?: BackupPolicyType;
/* Time at which the backup policy migration started (ISO-8601 format). */
startTime?: string;
}
/* Describes the status of migration between backup policy types. */
export type BackupPolicyMigrationStatus = "Invalid" | "InProgress" | "Completed" | "Failed";
/* The object representing periodic mode backup policy. */
export type PeriodicModeBackupPolicy = BackupPolicy & {
/* Configuration values for periodic mode backup */
@@ -1719,10 +1454,7 @@ export type PeriodicModeBackupPolicy = BackupPolicy & {
};
/* The object representing continuous mode backup policy. */
export type ContinuousModeBackupPolicy = BackupPolicy & {
/* Configuration values for continuous mode backup */
continuousModeProperties?: ContinuousModeProperties;
};
export type ContinuousModeBackupPolicy = BackupPolicy;
/* Configuration values for periodic mode backup */
export interface PeriodicModeProperties {
@@ -1730,50 +1462,4 @@ export interface PeriodicModeProperties {
backupIntervalInMinutes?: number;
/* An integer representing the time (in hours) that each backup is retained */
backupRetentionIntervalInHours?: number;
/* Enum to indicate type of backup residency */
backupStorageRedundancy?: BackupStorageRedundancy;
}
/* Configuration values for periodic mode backup */
export interface ContinuousModeProperties {
/* Enum to indicate type of Continuous backup mode */
tier?: ContinuousTier;
}
/* The List operation response, that contains Cosmos DB locations and their properties. */
export interface LocationListResult {
/* List of Cosmos DB locations and their properties. */
readonly value?: LocationGetResult[];
}
/* Cosmos DB location get result */
export type LocationGetResult = ARMProxyResource & {
/* Cosmos DB location metadata */
properties?: LocationProperties;
};
/* Cosmos DB location metadata */
export interface LocationProperties {
/* Flag indicating whether the location supports availability zones or not. */
readonly supportsAvailabilityZone?: boolean;
/* Flag indicating whether the location is residency sensitive. */
readonly isResidencyRestricted?: boolean;
/* The properties of available backup storage redundancies. */
readonly backupStorageRedundancies?: BackupStorageRedundancy[];
/* Flag indicating whether the subscription have access in region for Non-Availability Zones. */
readonly isSubscriptionRegionAccessAllowedForRegular?: boolean;
/* Flag indicating whether the subscription have access in region for Availability Zones(Az). */
readonly isSubscriptionRegionAccessAllowedForAz?: boolean;
/* Enum to indicate current buildout status of the region. */
readonly status?: "Uninitialized" | "Initializing" | "InternallyReady" | "Online" | "Deleting";
}
/* Enum to indicate type of backup storage redundancy. */
export type BackupStorageRedundancy = "Geo" | "Local" | "Zone";
/* Enum to indicate type of Continuous backup tier. */
export type ContinuousTier = "Continuous7Days" | "Continuous30Days";
/* Indicates the minimum allowed Tls version. The default is Tls 1.0, except for Cassandra and Mongo API's, which only work with Tls 1.2. */
export type MinimalTlsVersion = "Tls" | "Tls11" | "Tls12";

View File

@@ -3,17 +3,13 @@ import create, { UseStore } from "zustand";
interface CarouselState {
shouldOpen: boolean;
showCoachMark: boolean;
showCopilotCarousel: boolean;
setShouldOpen: (shouldOpen: boolean) => void;
setShowCoachMark: (showCoachMark: boolean) => void;
setShowCopilotCarousel: (showCopilotCarousel: boolean) => void;
}
export const useCarousel: UseStore<CarouselState> = create((set) => ({
shouldOpen: false,
showCoachMark: false,
showCopilotCarousel: false,
setShouldOpen: (shouldOpen: boolean) => set({ shouldOpen }),
setShowCoachMark: (showCoachMark: boolean) => set({ showCoachMark }),
setShowCopilotCarousel: (showCopilotCarousel: boolean) => set({ showCopilotCarousel }),
}));

View File

@@ -1,25 +0,0 @@
import create, { UseStore } from "zustand";
interface QueryCopilotState {
generatedQuery: string;
likeQuery: boolean;
userPrompt: string;
showFeedbackModal: boolean;
hideFeedbackModalForLikedQueries: boolean;
openFeedbackModal: (generatedQuery: string, likeQuery: boolean, userPrompt: string) => void;
closeFeedbackModal: () => void;
setHideFeedbackModalForLikedQueries: (hideFeedbackModalForLikedQueries: boolean) => void;
}
export const useQueryCopilot: UseStore<QueryCopilotState> = create((set) => ({
generatedQuery: "",
likeQuery: false,
userPrompt: "",
showFeedbackModal: false,
hideFeedbackModalForLikedQueries: false,
openFeedbackModal: (generatedQuery: string, likeQuery: boolean, userPrompt: string) =>
set({ generatedQuery, likeQuery, userPrompt, showFeedbackModal: true }),
closeFeedbackModal: () => set({ generatedQuery: "", likeQuery: false, userPrompt: "", showFeedbackModal: false }),
setHideFeedbackModalForLikedQueries: (hideFeedbackModalForLikedQueries: boolean) =>
set({ hideFeedbackModalForLikedQueries }),
}));

View File

@@ -10,7 +10,6 @@ interface TabsState {
activeTab: TabsBase | undefined;
activeReactTab: ReactTabKind | undefined;
networkSettingsWarning: string;
queryCopilotTabInitialInput: string;
activateTab: (tab: TabsBase) => void;
activateNewTab: (tab: TabsBase) => void;
activateReactTab: (tabkind: ReactTabKind) => void;
@@ -23,14 +22,12 @@ interface TabsState {
openAndActivateReactTab: (tabKind: ReactTabKind) => void;
closeReactTab: (tabKind: ReactTabKind) => void;
setNetworkSettingsWarning: (warningMessage: string) => void;
setQueryCopilotTabInitialInput: (input: string) => void;
}
export enum ReactTabKind {
Connect,
Home,
Quickstart,
QueryCopilot,
}
export const useTabs: UseStore<TabsState> = create((set, get) => ({
@@ -39,7 +36,6 @@ export const useTabs: UseStore<TabsState> = create((set, get) => ({
activeTab: undefined,
activeReactTab: ReactTabKind.Home,
networkSettingsWarning: "",
queryCopilotTabInitialInput: "",
activateTab: (tab: TabsBase): void => {
if (get().openedTabs.some((openedTab) => openedTab.tabId === tab.tabId)) {
set({ activeTab: tab, activeReactTab: undefined });
@@ -150,5 +146,4 @@ export const useTabs: UseStore<TabsState> = create((set, get) => ({
set({ openedReactTabs: updatedOpenedReactTabs });
},
setNetworkSettingsWarning: (warningMessage: string) => set({ networkSettingsWarning: warningMessage }),
setQueryCopilotTabInitialInput: (input: string) => set({ queryCopilotTabInitialInput: input }),
}));

View File

@@ -15,18 +15,12 @@
"target": "es2017",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": [
"es5",
"es6",
"dom"
],
"lib": ["es5", "es6", "dom"],
"jsx": "react",
"moduleResolution": "node",
"resolveJsonModule": true,
"noEmit": true,
"types": [
"jest"
],
"types": ["jest"],
"baseUrl": "src"
},
"typedocOptions": {
@@ -43,17 +37,6 @@
"includes": "./src/SelfServe/Documentation",
"disableSources": true
},
"include": [
"src",
"./src/**/*",
"./utils/**/*"
],
"exclude": [
"./src/**/__mocks__/**/*"
],
"ts-node": {
"compilerOptions": {
"module": "CommonJS"
}
}
}
"include": ["src", "./src/**/*", "./utils/**/*"],
"exclude": ["./src/**/__mocks__/**/*"]
}

View File

@@ -16,15 +16,10 @@ Results of this file should be checked into the repo.
*/
// CHANGE THESE VALUES TO GENERATE NEW CLIENTS
const version = "2023-04-15";
/* The following are legal options for resourceName but you generally will only use cosmos-db:
"cosmos-db" | "managedCassandra" | "mongorbac" | "notebook" | "privateEndpointConnection" | "privateLinkResources" |
"rbac" | "restorable" | "services"
*/
const githubResourceName = "cosmos-db";
const deResourceName = "cosmos";
const schemaURL = `https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/${version}/${githubResourceName}.json`;
const outputDir = path.join(__dirname, `../../src/Utils/arm/generatedClients/${deResourceName}`);
const version = "2021-04-15";
const resourceName = "cosmosNotebooks";
const schemaURL = `https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/${version}/notebook.json`;
const outputDir = path.join(__dirname, `../../src/Utils/arm/generatedClients/${resourceName}/${version}`);
// Array of strings to use for eventual output
const outputTypes: string[] = [""];
@@ -147,7 +142,7 @@ const propertyToType = (property: Property, prop: string, required: boolean) =>
`);
} else {
if (property.type === undefined) {
console.log(`generator.ts - UNHANDLED TYPE: ${prop}. Falling back to unknown`);
console.log(`UHANDLED TYPE: ${prop}. Falling back to unknown`);
property.type = "unknown";
}
outputTypes.push(`
@@ -214,7 +209,7 @@ async function main() {
export type ${definition} = ${type}
`);
} else {
console.log("generator.ts - UNHANDLED MODEL:", def, schema.definitions[def]);
console.log("UNHANDLED MODEL:", def, schema.definitions[def]);
}
}
}
@@ -238,9 +233,9 @@ async function main() {
// Write all grouped fetch functions to objects
for (const clientName in clients) {
const outputClient: string[] = [""];
outputClient.push(`import { armRequest } from "../../request"\n`);
outputClient.push(`import { armRequest } from "../../../request"\n`);
outputClient.push(`import * as Types from "./types"\n`);
outputClient.push(`import { configContext } from "../../../../ConfigContext";\n`);
outputClient.push(`import { configContext } from "../../../../../ConfigContext";\n`);
outputClient.push(`const apiVersion = "${version}"\n\n`);
for (const path of clients[clientName].paths) {
for (const method in schema.paths[path]) {