Use endpoint instead of region name to track selected region. Prevents having to do endpoint lookups.

This commit is contained in:
Craig Boger (from Dev Box) 2025-02-12 14:49:02 -08:00
parent a6e023ecdf
commit cf5609ef0c
6 changed files with 62 additions and 40 deletions

View File

@ -239,10 +239,6 @@ export class SavedQueries {
public static readonly PartitionKeyProperty: string = "id"; public static readonly PartitionKeyProperty: string = "id";
} }
export class RegionSelectionOptions {
public static readonly Global: string = "Global";
}
export class DocumentsGridMetrics { export class DocumentsGridMetrics {
public static DocumentsPerPage: number = 100; public static DocumentsPerPage: number = 100;
public static IndividualRowHeight: number = 34; public static IndividualRowHeight: number = 34;

View File

@ -110,13 +110,21 @@ export const requestPlugin: Cosmos.Plugin<any> = async (requestContext, diagnost
console.log(`REQUEST CONTEXT ENDPOINT: ${JSON.stringify(requestContext.endpoint)}`); console.log(`REQUEST CONTEXT ENDPOINT: ${JSON.stringify(requestContext.endpoint)}`);
requestContext.headers["x-ms-proxy-target"] = endpoint(); requestContext.headers["x-ms-proxy-target"] = endpoint();
console.log(`REQUEST CONTEXT PROXY: ${JSON.stringify(requestContext.headers["x-ms-proxy-target"])}`); console.log(`REQUEST CONTEXT PROXY: ${JSON.stringify(requestContext.headers["x-ms-proxy-target"])}`);
// return await next(requestContext);
// try {
// return await next(requestContext);
// } catch (error) {
// throw {
// code: error?.code || undefined,
// message: error.message,
// };
// }
try { try {
return await next(requestContext); return await next(requestContext);
} catch (error) { } catch (error) {
throw { console.log(error.code);
code: error?.code || undefined,
message: error.message,
};
} }
}; };
@ -236,6 +244,7 @@ export function client(): Cosmos.CosmosClient {
const options: Cosmos.CosmosClientOptions = { const options: Cosmos.CosmosClientOptions = {
endpoint: endpoint() || "https://cosmos.azure.com", // CosmosClient gets upset if we pass a bad URL. This should never actually get called endpoint: endpoint() || "https://cosmos.azure.com", // CosmosClient gets upset if we pass a bad URL. This should never actually get called
key: userContext.dataPlaneRbacEnabled ? "" : userContext.masterKey, key: userContext.dataPlaneRbacEnabled ? "" : userContext.masterKey,
diagnosticLevel: Cosmos.CosmosDbDiagnosticLevel.debugUnsafe,
tokenProvider, tokenProvider,
userAgentSuffix: "Azure Portal", userAgentSuffix: "Azure Portal",
defaultHeaders: _defaultHeaders, defaultHeaders: _defaultHeaders,

View File

@ -29,9 +29,14 @@ export const updateDocument = async (
.item(documentId.id(), getPartitionKeyValue(documentId)) .item(documentId.id(), getPartitionKeyValue(documentId))
.replace(newDocument, options); .replace(newDocument, options);
console.log(response.diagnostics);
logConsoleInfo(`Successfully updated ${entityName} ${documentId.id()}`); logConsoleInfo(`Successfully updated ${entityName} ${documentId.id()}`);
return response?.resource; return response?.resource;
} catch (error) { } catch (error) {
// If error has diagnostic information, log it.
if (error && error.diagnostics) {
console.error("Diagnostics:", error.diagnostics);
}
handleError(error, "UpdateDocument", `Failed to update ${entityName} ${documentId.id()}`); handleError(error, "UpdateDocument", `Failed to update ${entityName} ${documentId.id()}`);
throw error; throw error;
} finally { } finally {

View File

@ -145,10 +145,10 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
? LocalStorageUtility.getEntryString(StorageKey.IsGraphAutoVizDisabled) ? LocalStorageUtility.getEntryString(StorageKey.IsGraphAutoVizDisabled)
: "false", : "false",
); );
const [selectedRegion, setSelectedRegion] = useState<string>( const [selectedRegionalEndpoint, setSelectedRegionalEndpoint] = useState<string>(
LocalStorageUtility.hasItem(StorageKey.SelectedRegion) LocalStorageUtility.hasItem(StorageKey.SelectedRegionalEndpoint)
? LocalStorageUtility.getEntryString(StorageKey.SelectedRegion) ? LocalStorageUtility.getEntryString(StorageKey.SelectedRegionalEndpoint)
: Constants.RegionSelectionOptions.Global, : "",
); );
const [retryAttempts, setRetryAttempts] = useState<number>( const [retryAttempts, setRetryAttempts] = useState<number>(
LocalStorageUtility.hasItem(StorageKey.RetryAttempts) LocalStorageUtility.hasItem(StorageKey.RetryAttempts)
@ -192,10 +192,10 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
const uniqueAccountRegions = new Set<string>(); const uniqueAccountRegions = new Set<string>();
const regionOptions: IDropdownOption[] = []; const regionOptions: IDropdownOption[] = [];
regionOptions.push({ regionOptions.push({
key: Constants.RegionSelectionOptions.Global, key: userContext?.databaseAccount?.properties?.documentEndpoint,
text: `${Constants.RegionSelectionOptions.Global} (Default)`, text: `Global (Default)`,
data: { data: {
endpoint: userContext?.databaseAccount?.properties?.documentEndpoint, isGlobal: true,
writeEnabled: true, writeEnabled: true,
}, },
}); });
@ -203,10 +203,10 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
if (!uniqueAccountRegions.has(loc.locationName)) { if (!uniqueAccountRegions.has(loc.locationName)) {
uniqueAccountRegions.add(loc.locationName); uniqueAccountRegions.add(loc.locationName);
regionOptions.push({ regionOptions.push({
key: loc.locationName, key: loc.documentEndpoint,
text: `${loc.locationName} (Read/Write)`, text: `${loc.locationName} (Read/Write)`,
data: { data: {
endpoint: loc.documentEndpoint, isGlobal: false,
writeEnabled: true, writeEnabled: true,
}, },
}); });
@ -216,10 +216,10 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
if (!uniqueAccountRegions.has(loc.locationName)) { if (!uniqueAccountRegions.has(loc.locationName)) {
uniqueAccountRegions.add(loc.locationName); uniqueAccountRegions.add(loc.locationName);
regionOptions.push({ regionOptions.push({
key: loc.locationName, key: loc.documentEndpoint,
text: `${loc.locationName} (Read)`, text: `${loc.locationName} (Read)`,
data: { data: {
endpoint: loc.documentEndpoint, isGlobal: false,
writeEnabled: false, writeEnabled: false,
}, },
}); });
@ -311,18 +311,23 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
} }
} }
const storedRegion = LocalStorageUtility.getEntryString(StorageKey.SelectedRegion); const storedRegionalEndpoint = LocalStorageUtility.getEntryString(StorageKey.SelectedRegionalEndpoint);
const selectedRegionIsGlobal = selectedRegion === Constants.RegionSelectionOptions.Global; const selectedRegionIsGlobal =
if (selectedRegionIsGlobal && storedRegion) { selectedRegionalEndpoint === userContext?.databaseAccount?.properties?.documentEndpoint;
LocalStorageUtility.removeEntry(StorageKey.SelectedRegion); if (selectedRegionIsGlobal && storedRegionalEndpoint) {
LocalStorageUtility.removeEntry(StorageKey.SelectedRegionalEndpoint);
updateUserContext({ updateUserContext({
selectedRegionalEndpoint: undefined, selectedRegionalEndpoint: undefined,
refreshCosmosClient: true, refreshCosmosClient: true,
}); });
} else if (!selectedRegionIsGlobal && selectedRegion !== storedRegion) { } else if (
LocalStorageUtility.setEntryString(StorageKey.SelectedRegion, selectedRegion); selectedRegionalEndpoint &&
!selectedRegionIsGlobal &&
selectedRegionalEndpoint !== storedRegionalEndpoint
) {
LocalStorageUtility.setEntryString(StorageKey.SelectedRegionalEndpoint, selectedRegionalEndpoint);
updateUserContext({ updateUserContext({
selectedRegionalEndpoint: regionOptions.find((option) => option.key === selectedRegion)?.data?.endpoint, selectedRegionalEndpoint: selectedRegionalEndpoint,
refreshCosmosClient: true, refreshCosmosClient: true,
}); });
} }
@ -477,7 +482,7 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
}; };
const handleOnSelectedRegionOptionChange = (ev: React.FormEvent<HTMLInputElement>, option: IDropdownOption): void => { const handleOnSelectedRegionOptionChange = (ev: React.FormEvent<HTMLInputElement>, option: IDropdownOption): void => {
setSelectedRegion(option.key as string); setSelectedRegionalEndpoint(option.key as string);
}; };
const handleOnQueryRetryAttemptsSpinButtonChange = (ev: React.MouseEvent<HTMLElement>, newValue?: string): void => { const handleOnQueryRetryAttemptsSpinButtonChange = (ev: React.MouseEvent<HTMLElement>, newValue?: string): void => {
@ -649,7 +654,11 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
</InfoTooltip> </InfoTooltip>
</div> </div>
<Dropdown <Dropdown
placeholder={regionOptions.find((option) => option.key === selectedRegion)?.text} placeholder={
selectedRegionalEndpoint
? regionOptions.find((option) => option.key === selectedRegionalEndpoint)?.text
: regionOptions[0]?.text
}
onChange={handleOnSelectedRegionOptionChange} onChange={handleOnSelectedRegionOptionChange}
options={regionOptions} options={regionOptions}
styles={{ root: { marginBottom: "10px" } }} styles={{ root: { marginBottom: "10px" } }}

View File

@ -11,7 +11,7 @@ export enum StorageKey {
RUThreshold, RUThreshold,
QueryTimeoutEnabled, QueryTimeoutEnabled,
QueryTimeout, QueryTimeout,
SelectedRegion, SelectedRegionalEndpoint,
RetryAttempts, RetryAttempts,
RetryInterval, RetryInterval,
MaxWaitTimeInSeconds, MaxWaitTimeInSeconds,

View File

@ -298,7 +298,7 @@ async function configureHostedWithAAD(config: AAD): Promise<Explorer> {
`Configuring Data Explorer for ${userContext.apiType} account ${account.name}`, `Configuring Data Explorer for ${userContext.apiType} account ${account.name}`,
"Explorer/configureHostedWithAAD", "Explorer/configureHostedWithAAD",
); );
if (userContext.apiType === "SQL") { if (userContext.apiType === "SQL" && userContext.authType === AuthType.AAD) {
checkAndUpdateSelectedRegionalEndpoint(); checkAndUpdateSelectedRegionalEndpoint();
} }
if (!userContext.features.enableAadDataPlane) { if (!userContext.features.enableAadDataPlane) {
@ -555,7 +555,7 @@ async function configurePortal(): Promise<Explorer> {
const { databaseAccount: account, subscriptionId, resourceGroup } = userContext; const { databaseAccount: account, subscriptionId, resourceGroup } = userContext;
if (userContext.apiType === "SQL") { if (userContext.apiType === "SQL" && userContext.authType === AuthType.AAD) {
checkAndUpdateSelectedRegionalEndpoint(); checkAndUpdateSelectedRegionalEndpoint();
} }
@ -678,16 +678,19 @@ function updateAADEndpoints(portalEnv: PortalEnv) {
} }
function checkAndUpdateSelectedRegionalEndpoint() { function checkAndUpdateSelectedRegionalEndpoint() {
//TODO: Possibly refactor userContext to store selected regional endpoint instead of selected region. if (LocalStorageUtility.hasItem(StorageKey.SelectedRegionalEndpoint)) {
if (LocalStorageUtility.hasItem(StorageKey.SelectedRegion)) { const storedRegionalEndpoint = LocalStorageUtility.getEntryString(StorageKey.SelectedRegionalEndpoint);
const storedRegion = LocalStorageUtility.getEntryString(StorageKey.SelectedRegion); const validLocation = userContext.databaseAccount?.properties?.readLocations?.find(
const location = userContext.databaseAccount?.properties?.readLocations?.find( (loc) => loc.documentEndpoint === storedRegionalEndpoint,
(loc) => loc.locationName === storedRegion,
); );
updateUserContext({ if (validLocation) {
selectedRegionalEndpoint: location?.documentEndpoint, updateUserContext({
refreshCosmosClient: true, selectedRegionalEndpoint: storedRegionalEndpoint,
}); refreshCosmosClient: true,
});
} else {
LocalStorageUtility.removeEntry(StorageKey.SelectedRegionalEndpoint);
}
} }
} }