fix:auto format

This commit is contained in:
Archie Agarwal 2025-07-07 15:41:10 +05:30
parent f2044f2054
commit 3949a0ecce
7 changed files with 290 additions and 282 deletions

View File

@ -334,4 +334,4 @@ describe("SettingsComponent - indexing policy subscription", () => {
// @ts-expect-error: rawDataModel is intentionally accessed for test validation
expect(instance.collection.rawDataModel.indexingPolicy).toEqual(mockIndexingPolicy);
});
});
});

View File

@ -303,15 +303,18 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
if (this.props.settingsTab.isActive()) {
useCommandBar.getState().setContextButtons(this.getTabsButtons());
}
this.unsubscribe = useIndexingPolicyStore.subscribe(() => {
this.refreshCollectionData();
},
(state) => state.indexingPolicies[this.collection.id()]
this.unsubscribe = useIndexingPolicyStore.subscribe(
() => {
this.refreshCollectionData();
},
(state) => state.indexingPolicies[this.collection.id()],
);
this.refreshCollectionData();
}
componentWillUnmount(): void {
if (this.unsubscribe) { this.unsubscribe(); }
if (this.unsubscribe) {
this.unsubscribe();
}
}
componentDidUpdate(): void {
if (this.props.settingsTab.isActive()) {
@ -859,8 +862,9 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
const numberOfRegions = userContext.databaseAccount?.properties.locations?.length || 1;
const throughputDelta = (newThroughput - this.offer.autoscaleMaxThroughput) * numberOfRegions;
if (throughputCap && throughputCap !== -1 && throughputCap - this.totalThroughputUsed < throughputDelta) {
throughputError = `Your account is currently configured with a total throughput limit of ${throughputCap} RU/s. This update isn't possible because it would increase the total throughput to ${this.totalThroughputUsed + throughputDelta
} RU/s. Change total throughput limit in cost management.`;
throughputError = `Your account is currently configured with a total throughput limit of ${throughputCap} RU/s. This update isn't possible because it would increase the total throughput to ${
this.totalThroughputUsed + throughputDelta
} RU/s. Change total throughput limit in cost management.`;
}
this.setState({ autoPilotThroughput: newThroughput, throughputError });
};
@ -871,8 +875,9 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
const numberOfRegions = userContext.databaseAccount?.properties.locations?.length || 1;
const throughputDelta = (newThroughput - this.offer.manualThroughput) * numberOfRegions;
if (throughputCap && throughputCap !== -1 && throughputCap - this.totalThroughputUsed < throughputDelta) {
throughputError = `Your account is currently configured with a total throughput limit of ${throughputCap} RU/s. This update isn't possible because it would increase the total throughput to ${this.totalThroughputUsed + throughputDelta
} RU/s. Change total throughput limit in cost management.`;
throughputError = `Your account is currently configured with a total throughput limit of ${throughputCap} RU/s. This update isn't possible because it would increase the total throughput to ${
this.totalThroughputUsed + throughputDelta
} RU/s. Change total throughput limit in cost management.`;
}
this.setState({ throughput: newThroughput, throughputError });
};
@ -992,8 +997,8 @@ export class SettingsComponent extends React.Component<SettingsComponentProps, S
newCollection.changeFeedPolicy =
this.changeFeedPolicyVisible && this.state.changeFeedPolicy === ChangeFeedPolicyState.On
? {
retentionDuration: Constants.BackendDefaults.maxChangeFeedRetentionDuration,
}
retentionDuration: Constants.BackendDefaults.maxChangeFeedRetentionDuration,
}
: undefined;
newCollection.analyticalStorageTtl = this.getAnalyticalStorageTtl();

View File

@ -1,85 +1,88 @@
import type { IIndexMetric } from "Explorer/Tabs/QueryTab/ResultsView";
interface IndexObject {
index: string;
impact: string;
section: "Included" | "Not Included" | "Header";
composite?: {
path: string;
order: "ascending" | "descending";
}[];
path?: string;
index: string;
impact: string;
section: "Included" | "Not Included" | "Header";
composite?: {
path: string;
order: "ascending" | "descending";
}[];
path?: string;
}
export interface IndexMetricsJson {
included?: IIndexMetric[];
notIncluded?: IIndexMetric[];
included?: IIndexMetric[];
notIncluded?: IIndexMetric[];
}
export function parseIndexMetrics(indexMetrics: string | IndexMetricsJson): {
included: IIndexMetric[];
notIncluded: IIndexMetric[];
included: IIndexMetric[];
notIncluded: IIndexMetric[];
} {
// If already JSON, just extract arrays
if (typeof indexMetrics === "object" && indexMetrics !== null) {
return {
included: Array.isArray(indexMetrics.included) ? indexMetrics.included : [],
notIncluded: Array.isArray(indexMetrics.notIncluded) ? indexMetrics.notIncluded : [],
};
}
// If already JSON, just extract arrays
if (typeof indexMetrics === "object" && indexMetrics !== null) {
return {
included: Array.isArray(indexMetrics.included) ? indexMetrics.included : [],
notIncluded: Array.isArray(indexMetrics.notIncluded) ? indexMetrics.notIncluded : [],
};
}
// Otherwise, parse as string (current SDK)
const included: IIndexMetric[] = [];
const notIncluded: IIndexMetric[] = [];
const lines = (indexMetrics as string).split("\n").map((line) => line.trim()).filter(Boolean);
let currentSection = "";
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith("Utilized Single Indexes") || line.startsWith("Utilized Composite Indexes")) {
currentSection = "included";
} else if (line.startsWith("Potential Single Indexes") || line.startsWith("Potential Composite Indexes")) {
currentSection = "notIncluded";
} else if (line.startsWith("Index Spec:")) {
const index = line.replace("Index Spec:", "").trim();
const impactLine = lines[i + 1];
const impact = impactLine?.includes("Index Impact Score:") ? impactLine.split(":")[1].trim() : "Unknown";
// Otherwise, parse as string (current SDK)
const included: IIndexMetric[] = [];
const notIncluded: IIndexMetric[] = [];
const lines = (indexMetrics as string)
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
let currentSection = "";
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith("Utilized Single Indexes") || line.startsWith("Utilized Composite Indexes")) {
currentSection = "included";
} else if (line.startsWith("Potential Single Indexes") || line.startsWith("Potential Composite Indexes")) {
currentSection = "notIncluded";
} else if (line.startsWith("Index Spec:")) {
const index = line.replace("Index Spec:", "").trim();
const impactLine = lines[i + 1];
const impact = impactLine?.includes("Index Impact Score:") ? impactLine.split(":")[1].trim() : "Unknown";
const isComposite = index.includes(",");
const isComposite = index.includes(",");
const sectionMap: Record<string, "Included" | "Not Included"> = {
included: "Included",
notIncluded: "Not Included",
};
const sectionMap: Record<string, "Included" | "Not Included"> = {
included: "Included",
notIncluded: "Not Included",
};
const indexObj: IndexObject = { index, impact, section: sectionMap[currentSection] ?? "Header", };
if (isComposite) {
indexObj.composite = index.split(",").map((part: string) => {
const [path, order] = part.trim().split(/\s+/);
return {
path: path.trim(),
order: order?.toLowerCase() === "desc" ? "descending" : "ascending",
};
});
} else {
let path = "/unknown/*";
const pathRegex = /\/[^/\s*?]+(?:\/[^/\s*?]+)*(\/\*|\?)/;
const match = index.match(pathRegex);
if (match) {
path = match[0];
} else {
const simplePathRegex = /\/[^/\s]+/;
const simpleMatch = index.match(simplePathRegex);
if (simpleMatch) {
path = simpleMatch[0] + "/*";
}
}
indexObj.path = path;
}
if (currentSection === "included") {
included.push(indexObj);
} else if (currentSection === "notIncluded") {
notIncluded.push(indexObj);
}
const indexObj: IndexObject = { index, impact, section: sectionMap[currentSection] ?? "Header" };
if (isComposite) {
indexObj.composite = index.split(",").map((part: string) => {
const [path, order] = part.trim().split(/\s+/);
return {
path: path.trim(),
order: order?.toLowerCase() === "desc" ? "descending" : "ascending",
};
});
} else {
let path = "/unknown/*";
const pathRegex = /\/[^/\s*?]+(?:\/[^/\s*?]+)*(\/\*|\?)/;
const match = index.match(pathRegex);
if (match) {
path = match[0];
} else {
const simplePathRegex = /\/[^/\s]+/;
const simpleMatch = index.match(simplePathRegex);
if (simpleMatch) {
path = simpleMatch[0] + "/*";
}
}
indexObj.path = path;
}
if (currentSection === "included") {
included.push(indexObj);
} else if (currentSection === "notIncluded") {
notIncluded.push(indexObj);
}
}
return { included, notIncluded };
}
}
return { included, notIncluded };
}

View File

@ -21,185 +21,182 @@ Index Spec: /baz/? DESC, /qux/? ASC
Index Impact Score: Low
`;
mockRead.mockResolvedValue({
resource: {
indexingPolicy: {
automatic: true,
indexingMode: "consistent",
includedPaths: [{ path: "/*" }, { path: "/foo/?" }],
excludedPaths: [],
},
partitionKey: "pk",
resource: {
indexingPolicy: {
automatic: true,
indexingMode: "consistent",
includedPaths: [{ path: "/*" }, { path: "/foo/?" }],
excludedPaths: [],
},
partitionKey: "pk",
},
});
mockReplace.mockResolvedValue({
resource: {
indexingPolicy: {
automatic: true,
indexingMode: "consistent",
includedPaths: [{ path: "/*" }],
excludedPaths: [],
},
resource: {
indexingPolicy: {
automatic: true,
indexingMode: "consistent",
includedPaths: [{ path: "/*" }],
excludedPaths: [],
},
},
});
jest.mock("./QueryTabComponent", () => ({
useQueryMetadataStore: () => ({
userQuery: "SELECT * FROM c",
databaseId: "db1",
containerId: "col1",
}),
useQueryMetadataStore: () => ({
userQuery: "SELECT * FROM c",
databaseId: "db1",
containerId: "col1",
}),
}));
jest.mock("Common/CosmosClient", () => ({
client: () => ({
database: () => ({
container: () => ({
items: {
query: () => ({
fetchAll: mockFetchAll.mockResolvedValueOnce({ indexMetrics: indexMetricsString })
,
}),
},
read: mockRead,
replace: mockReplace,
}),
}),
client: () => ({
database: () => ({
container: () => ({
items: {
query: () => ({
fetchAll: mockFetchAll.mockResolvedValueOnce({ indexMetrics: indexMetricsString }),
}),
},
read: mockRead,
replace: mockReplace,
}),
}),
}),
}));
jest.mock("./Indexadvisor", () => ({
useIndexAdvisorStyles: () => ({}),
useIndexAdvisorStyles: () => ({}),
}));
jest.mock("../../../Utils/NotificationConsoleUtils", () => ({
logConsoleProgress: (...args: unknown[]) => {
mockLogConsoleProgress(...args);
return () => { };
},
logConsoleProgress: (...args: unknown[]) => {
mockLogConsoleProgress(...args);
return () => {};
},
}));
jest.mock("../../../Common/ErrorHandlingUtils", () => {
return {
handleError: (...args: unknown[]) => mockHandleError(...args),
};
return {
handleError: (...args: unknown[]) => mockHandleError(...args),
};
});
test("logs progress message when fetching index metrics", async () => {
render(<IndexAdvisorTab />);
await waitFor(() =>
expect(mockLogConsoleProgress).toHaveBeenCalledWith(expect.stringContaining("IndexMetrics"))
);
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockLogConsoleProgress).toHaveBeenCalledWith(expect.stringContaining("IndexMetrics")));
});
test("renders both Included and Not Included sections after loading", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("Included in Current Policy")).toBeInTheDocument());
expect(screen.getByText("Not Included in Current Policy")).toBeInTheDocument();
expect(screen.getByText("/foo/?")).toBeInTheDocument();
expect(screen.getByText("/bar/?")).toBeInTheDocument();
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("Included in Current Policy")).toBeInTheDocument());
expect(screen.getByText("Not Included in Current Policy")).toBeInTheDocument();
expect(screen.getByText("/foo/?")).toBeInTheDocument();
expect(screen.getByText("/bar/?")).toBeInTheDocument();
});
test("shows update button only when an index is selected", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
expect(checkboxes.length).toBeGreaterThan(1);
fireEvent.click(checkboxes[1]);
expect(screen.getByText(/Update Indexing Policy/)).toBeInTheDocument();
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
expect(checkboxes.length).toBeGreaterThan(1);
fireEvent.click(checkboxes[1]);
expect(screen.getByText(/Update Indexing Policy/)).toBeInTheDocument();
fireEvent.click(checkboxes[1]);
expect(screen.queryByText(/Update Indexing Policy/)).not.toBeInTheDocument();
fireEvent.click(checkboxes[1]);
expect(screen.queryByText(/Update Indexing Policy/)).not.toBeInTheDocument();
});
test("calls replace when update policy is confirmed", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]);
const updateButton = screen.getByText(/Update Indexing Policy/);
fireEvent.click(updateButton);
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]);
const updateButton = screen.getByText(/Update Indexing Policy/);
fireEvent.click(updateButton);
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
});
test("calls replace when update button is clicked", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]); // Select /bar/?
fireEvent.click(screen.getByText(/Update Indexing Policy/));
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]); // Select /bar/?
fireEvent.click(screen.getByText(/Update Indexing Policy/));
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
});
test("fetches indexing policy via read", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => {
expect(mockRead).toHaveBeenCalled();
});
render(<IndexAdvisorTab />);
await waitFor(() => {
expect(mockRead).toHaveBeenCalled();
});
});
test("selects all indexes when select-all is clicked", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[0]);
checkboxes.forEach((cb) => {
expect(cb).toBeChecked();
});
fireEvent.click(checkboxes[0]);
checkboxes.forEach((cb) => {
expect(cb).toBeChecked();
});
});
test("shows spinner while loading and hides after fetchIndexMetrics resolves", async () => {
render(<IndexAdvisorTab />);
expect(screen.getByRole("progressbar")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("progressbar")).not.toBeInTheDocument());
render(<IndexAdvisorTab />);
expect(screen.getByRole("progressbar")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("progressbar")).not.toBeInTheDocument());
});
test("calls fetchAll with correct query and options", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockFetchAll).toHaveBeenCalled());
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockFetchAll).toHaveBeenCalled());
});
test("renders IndexAdvisorTab when clicked from ResultsView", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("Included in Current Policy")).toBeInTheDocument());
expect(screen.getByText("/foo/?")).toBeInTheDocument();
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("Included in Current Policy")).toBeInTheDocument());
expect(screen.getByText("/foo/?")).toBeInTheDocument();
});
test("renders index metrics from SDK response", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/foo/?")).toBeInTheDocument());
expect(screen.getByText("/bar/?")).toBeInTheDocument();
expect(screen.getByText("/baz/? DESC, /qux/? ASC")).toBeInTheDocument();
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/foo/?")).toBeInTheDocument());
expect(screen.getByText("/bar/?")).toBeInTheDocument();
expect(screen.getByText("/baz/? DESC, /qux/? ASC")).toBeInTheDocument();
});
test("calls handleError if fetchIndexMetrics throws", async () => {
mockFetchAll.mockRejectedValueOnce(new Error("fail"));
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockHandleError).toHaveBeenCalled());
mockFetchAll.mockRejectedValueOnce(new Error("fail"));
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockHandleError).toHaveBeenCalled());
});
test("calls handleError if fetchIndexMetrics throws2nd", async () => {
mockFetchAll.mockRejectedValueOnce(new Error("fail"));
mockFetchAll.mockRejectedValueOnce(new Error("fail"));
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockHandleError).toHaveBeenCalled());
expect(screen.queryByRole("status")).not.toBeInTheDocument();
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockHandleError).toHaveBeenCalled());
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});
test("IndexingPolicyStore stores updated policy on componentDidMount", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockRead).toHaveBeenCalled());
render(<IndexAdvisorTab />);
await waitFor(() => expect(mockRead).toHaveBeenCalled());
const readResult = await mockRead.mock.results[0].value;
const policy = readResult.resource.indexingPolicy;
const readResult = await mockRead.mock.results[0].value;
const policy = readResult.resource.indexingPolicy;
expect(policy).toBeDefined();
expect(policy.automatic).toBe(true);
expect(policy.indexingMode).toBe("consistent");
expect(policy.includedPaths).toEqual(expect.arrayContaining([{ path: "/*" }, { path: "/foo/?" }]));
expect(policy).toBeDefined();
expect(policy.automatic).toBe(true);
expect(policy.indexingMode).toBe("consistent");
expect(policy.includedPaths).toEqual(expect.arrayContaining([{ path: "/*" }, { path: "/foo/?" }]));
});
test("refreshCollectionData updates observable and re-renders", async () => {
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
render(<IndexAdvisorTab />);
await waitFor(() => expect(screen.getByText("/bar/?")).toBeInTheDocument());
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]); // Select /bar/?
fireEvent.click(screen.getByText(/Update Indexing Policy/));
const checkboxes = screen.getAllByRole("checkbox");
fireEvent.click(checkboxes[1]); // Select /bar/?
fireEvent.click(screen.getByText(/Update Indexing Policy/));
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
expect(screen.getByText("/bar/?")).toBeInTheDocument();
await waitFor(() => expect(mockReplace).toHaveBeenCalled());
expect(screen.getByText("/bar/?")).toBeInTheDocument();
});

View File

@ -71,7 +71,6 @@ export const useQueryMetadataStore = create<QueryMetadataStore>((set) => ({
setMetadata: (query1, db, container) => set({ userQuery: query1, databaseId: db, containerId: container }),
}));
enum ToggleState {
Result,
QueryMetrics,
@ -376,9 +375,9 @@ class QueryTabComponentImpl extends React.Component<QueryTabComponentImplProps,
this._iterator = this.props.isPreferredApiMongoDB
? queryIterator(this.props.collection.databaseId, this.props.viewModelcollection, query)
: queryDocuments(this.props.collection.databaseId, this.props.collection.id(), query, {
enableCrossPartitionQuery: HeadersUtility.shouldEnableCrossPartitionKey(),
abortSignal: this.queryAbortController.signal,
} as unknown as FeedOptions);
enableCrossPartitionQuery: HeadersUtility.shouldEnableCrossPartitionKey(),
abortSignal: this.queryAbortController.signal,
} as unknown as FeedOptions);
}
await this._queryDocumentsPage(firstItemIndex);

View File

@ -20,9 +20,15 @@ import {
TableColumnDefinition,
TableHeader,
TableRow,
createTableColumn
createTableColumn,
} from "@fluentui/react-components";
import { ArrowDownloadRegular, ChevronDown20Regular, ChevronRight20Regular, CircleFilled, CopyRegular } from "@fluentui/react-icons";
import {
ArrowDownloadRegular,
ChevronDown20Regular,
ChevronRight20Regular,
CircleFilled,
CopyRegular,
} from "@fluentui/react-icons";
import copy from "clipboard-copy";
import { HttpHeaders } from "Common/Constants";
import MongoUtility from "Common/MongoUtility";
@ -394,8 +400,9 @@ const QueryStatsTab: React.FC<Pick<ResultsViewProps, "queryResults">> = ({ query
},
{
metric: "User defined function execution time",
value: `${aggregatedQueryMetrics.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.toString() || 0
} ms`,
value: `${
aggregatedQueryMetrics.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.toString() || 0
} ms`,
toolTip: "Total time spent executing user-defined functions",
},
{
@ -578,14 +585,16 @@ export const IndexAdvisorTab: React.FC = () => {
clearMessage();
setLoading(false);
}
}
};
if (userQuery && databaseId && containerId) {
fetchIndexMetrics();
}
}, [userQuery, databaseId, containerId]);
useEffect(() => {
if (!indexMetrics) { return }
if (!indexMetrics) {
return;
}
const { included, notIncluded } = parseIndexMetrics(indexMetrics);
setIncludedIndexes(included);
@ -598,7 +607,8 @@ export const IndexAdvisorTab: React.FC = () => {
}, [indexMetrics]);
useEffect(() => {
const allSelected = notIncluded.length > 0 && notIncluded.every((item) => selectedIndexes.some((s) => s.index === item.index));
const allSelected =
notIncluded.length > 0 && notIncluded.every((item) => selectedIndexes.some((s) => s.index === item.index));
setSelectAll(allSelected);
}, [selectedIndexes, notIncluded]);
@ -606,9 +616,7 @@ export const IndexAdvisorTab: React.FC = () => {
if (checked) {
setSelectedIndexes((prev) => [...prev, indexObj]);
} else {
setSelectedIndexes((prev) =>
prev.filter((item) => item.index !== indexObj.index)
);
setSelectedIndexes((prev) => prev.filter((item) => item.index !== indexObj.index));
}
};
@ -624,32 +632,27 @@ export const IndexAdvisorTab: React.FC = () => {
const { resource: containerDef } = await containerRef.read();
const newIncludedPaths = selectedIndexes
.filter(index => !index.composite)
.map(index => {
.filter((index) => !index.composite)
.map((index) => {
return {
path: index.path,
};
});
const newCompositeIndexes: CompositePath[][] = selectedIndexes
.filter(index => Array.isArray(index.composite))
.map(index =>
(index.composite as { path: string; order: string }[]).map(comp => ({
path: comp.path,
order: comp.order === "descending" ? "descending" : "ascending",
})) as CompositePath[]
.filter((index) => Array.isArray(index.composite))
.map(
(index) =>
(index.composite as { path: string; order: string }[]).map((comp) => ({
path: comp.path,
order: comp.order === "descending" ? "descending" : "ascending",
})) as CompositePath[],
);
const updatedPolicy: IndexingPolicy = {
...containerDef.indexingPolicy,
includedPaths: [
...(containerDef.indexingPolicy?.includedPaths || []),
...newIncludedPaths,
],
compositeIndexes: [
...(containerDef.indexingPolicy?.compositeIndexes || []),
...newCompositeIndexes,
],
includedPaths: [...(containerDef.indexingPolicy?.includedPaths || []), ...newIncludedPaths],
compositeIndexes: [...(containerDef.indexingPolicy?.compositeIndexes || []), ...newCompositeIndexes],
automatic: containerDef.indexingPolicy?.automatic ?? true,
indexingMode: containerDef.indexingPolicy?.indexingMode ?? "consistent",
excludedPaths: containerDef.indexingPolicy?.excludedPaths ?? [],
@ -660,7 +663,7 @@ export const IndexAdvisorTab: React.FC = () => {
indexingPolicy: updatedPolicy,
});
useIndexingPolicyStore.getState().setIndexingPolicyFor(containerId, updatedPolicy);
const selectedIndexSet = new Set(selectedIndexes.map(s => s.index));
const selectedIndexSet = new Set(selectedIndexes.map((s) => s.index));
const updatedNotIncluded: typeof notIncluded = [];
const newlyIncluded: typeof included = [];
for (const item of notIncluded) {
@ -686,16 +689,17 @@ export const IndexAdvisorTab: React.FC = () => {
};
const renderImpactDots = (impact: string) => {
let count = 0;
if (impact === "High") { count = 3; }
else if (impact === "Medium") { count = 2; }
else if (impact === "Low") { count = 1; }
if (impact === "High") {
count = 3;
} else if (impact === "Medium") {
count = 2;
} else if (impact === "Low") {
count = 1;
}
return (
<div className={style.indexAdvisorImpactDots}>
{Array.from({ length: count }).map((_, i) => (
<CircleFilled
key={i}
className={style.indexAdvisorImpactDot}
/>
<CircleFilled key={i} className={style.indexAdvisorImpactDot} />
))}
</div>
);
@ -712,11 +716,10 @@ export const IndexAdvisorTab: React.FC = () => {
{isNotIncluded ? (
<Checkbox
checked={selectedIndexes.some((selected) => selected.index === item.index)}
onChange={(_, data) => handleCheckboxChange(item, data.checked === true)} />
onChange={(_, data) => handleCheckboxChange(item, data.checked === true)}
/>
) : isHeader && item.index === "Not Included in Current Policy" && notIncluded.length > 0 ? (
<Checkbox
checked={selectAll}
onChange={(_, data) => handleSelectAll(data.checked === true)} />
<Checkbox checked={selectAll} onChange={(_, data) => handleSelectAll(data.checked === true)} />
) : (
<div className={style.indexAdvisorCheckboxSpacer}></div>
)}
@ -729,24 +732,28 @@ export const IndexAdvisorTab: React.FC = () => {
} else if (item.index === "Not Included in Current Policy") {
setShowNotIncluded(!showNotIncluded);
}
}}>
{item.index === "Included in Current Policy"
? showIncluded ? <ChevronDown20Regular /> : <ChevronRight20Regular />
: showNotIncluded ? <ChevronDown20Regular /> : <ChevronRight20Regular />
}
}}
>
{item.index === "Included in Current Policy" ? (
showIncluded ? (
<ChevronDown20Regular />
) : (
<ChevronRight20Regular />
)
) : showNotIncluded ? (
<ChevronDown20Regular />
) : (
<ChevronRight20Regular />
)}
</span>
) : (
<div className={style.indexAdvisorChevronSpacer}></div>
)}
<div className={isHeader ? style.indexAdvisorRowBold : style.indexAdvisorRowNormal}>
{item.index}
</div>
<div className={isHeader ? style.indexAdvisorRowBold : style.indexAdvisorRowNormal}>{item.index}</div>
<div className={isHeader ? style.indexAdvisorRowImpactHeader : style.indexAdvisorRowImpact}>
{!isHeader && item.impact}
</div>
<div>
{!isHeader && renderImpactDots(item.impact)}
</div>
<div>{!isHeader && renderImpactDots(item.impact)}</div>
</div>
</TableCell>
</TableRow>
@ -756,29 +763,30 @@ export const IndexAdvisorTab: React.FC = () => {
const items: IIndexMetric[] = [];
items.push({ index: "Not Included in Current Policy", impact: "", section: "Header" });
if (showNotIncluded) {
notIncluded.forEach((item) =>
items.push({ ...item, section: "Not Included" })
);
notIncluded.forEach((item) => items.push({ ...item, section: "Not Included" }));
}
items.push({ index: "Included in Current Policy", impact: "", section: "Header" });
if (showIncluded) {
included.forEach((item) =>
items.push({ ...item, section: "Included" })
);
included.forEach((item) => items.push({ ...item, section: "Included" }));
}
return items;
}, [included, notIncluded, showIncluded, showNotIncluded]);
if (loading) {
return <div>
<Spinner
size="small"
style={{
'--spinner-size': '16px',
'--spinner-thickness': '2px',
'--spinner-color': '#0078D4',
} as React.CSSProperties} />
</div>;
return (
<div>
<Spinner
size="small"
style={
{
"--spinner-size": "16px",
"--spinner-thickness": "2px",
"--spinner-color": "#0078D4",
} as React.CSSProperties
}
/>
</div>
);
}
return (
@ -786,12 +794,12 @@ export const IndexAdvisorTab: React.FC = () => {
<div className={style.indexAdvisorMessage}>
{updateMessageShown ? (
<>
<span
className={style.indexAdvisorSuccessIcon}>
<span className={style.indexAdvisorSuccessIcon}>
<FontIcon iconName="CheckMark" style={{ color: "white", fontSize: 12 }} />
</span>
<span>
Your indexing policy has been updated with the new included paths. You may review the changes in Scale & Settings.
Your indexing policy has been updated with the new included paths. You may review the changes in Scale &
Settings.
</span>
</>
) : (
@ -807,25 +815,23 @@ export const IndexAdvisorTab: React.FC = () => {
<div className={style.indexAdvisorCheckboxSpacer}></div>
<div className={style.indexAdvisorChevronSpacer}></div>
<div>Index</div>
<div><span style={{ whiteSpace: "nowrap" }}>Estimated Impact</span></div>
<div>
<span style={{ whiteSpace: "nowrap" }}>Estimated Impact</span>
</div>
</div>
</TableCell>
</TableRow>
</TableHeader>
<TableBody>
{indexMetricItems.map(renderRow)}
</TableBody>
<TableBody>{indexMetricItems.map(renderRow)}</TableBody>
</Table>
{selectedIndexes.length > 0 && (
<div className={style.indexAdvisorButtonBar}>
{isUpdating ? (
<div className={style.indexAdvisorButtonSpinner}>
<Spinner size="tiny" /> </div>
<Spinner size="tiny" />{" "}
</div>
) : (
<button
onClick={handleUpdatePolicy}
className={style.indexAdvisorButton}
>
<button onClick={handleUpdatePolicy} className={style.indexAdvisorButton}>
Update Indexing Policy with selected index(es)
</button>
)}
@ -895,4 +901,3 @@ export const useIndexingPolicyStore = create<IndexingPolicyStore>((set) => ({
},
})),
}));

View File

@ -11,6 +11,5 @@ export const useQueryMetadataStore = create<QueryMetadataStore>((set) => ({
userQuery: "",
databaseId: "",
containerId: "",
setMetadata: (query1, db, container) =>
set({ userQuery: query1, databaseId: db, containerId: container }),
setMetadata: (query1, db, container) => set({ userQuery: query1, databaseId: db, containerId: container }),
}));