Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support load more in expr selector (#18570)
ecmadao6e486d354703
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts b/frontend/src/components/CustomApproval/Settings/components/common/utils.tsindex 5777a13b91..5243e9f95b 100644--- a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts+++ b/frontend/src/components/CustomApproval/Settings/components/common/utils.ts@@ -1,32 +1,17 @@-import { CheckIcon } from "lucide-vue-next";-import type { SelectOption } from "naive-ui";-import type { VNode } from "vue";-import { h } from "vue";import { type OptionConfig } from "@/components/ExprEditor/context";-import { getInstanceIdOptions } from "@/components/SensitiveData/components/utils";-import { EnvironmentV1Name, RichDatabaseName } from "@/components/v2";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import { type Factor, SQLTypeList } from "@/plugins/cel";import { t } from "@/plugins/i18n";-import {- useEnvironmentV1Store,- useInstanceV1Store,- useProjectV1Store,- useRoleStore,-} from "@/store";-import {- type ComposedDatabase,- DEFAULT_PROJECT_NAME,- PRESET_WORKSPACE_ROLES,- PresetRiskLevelList,-} from "@/types";+import { useRoleStore } from "@/store";+import { PRESET_WORKSPACE_ROLES, PresetRiskLevelList } from "@/types";import { Engine, RiskLevel } from "@/types/proto-es/v1/common_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";import {displayRoleTitle,engineNameV1,- extractProjectResourceName,- getDefaultPagination,+ getEnvironmentIdOptions,+ getInstanceIdOptionConfig,+ getProjectIdOptionConfig,supportedEngineV1List,} from "@/utils";import {@@ -82,116 +67,20 @@ const migrationFactorList: Factor[] = [CEL_ATTRIBUTE_STATEMENT_TEXT,] as const;-export const getRenderOptionFunc = (resource: {- title: string | (() => VNode);- name: string;-}): ((info: { node: VNode; selected: boolean }) => VNode) => {- return (info: { node: VNode; selected: boolean }) => {- return h(- info.node,- { class: "flex items-center justify-between gap-x-4" },- [- h("div", { class: "flex flex-col px-1 py-1 z-10" }, [- typeof resource.title === "string"- ? h(- "div",- { class: `textlabel ${info.selected ? "text-accent!" : ""}` },- resource.title- )- : resource.title(),- h("div", { class: "opacity-60 textinfolabel" }, resource.name),- ]),- info.selected ? h(CheckIcon, { class: "w-4 z-10" }) : undefined,- ]- );- };-};--export const getEnvironmentIdOptions = () => {- const environmentList = useEnvironmentV1Store().getEnvironmentList();- return environmentList.map<SelectOption>((env) => {- const environmentId = env.id;- return {- label: `${env.title} (${environmentId})`,- value: environmentId,- render: getRenderOptionFunc({- name: env.name,- title: () =>- h(EnvironmentV1Name, {- environment: env,- link: false,- showColor: true,- }),- }),- };- });-};--export const getProjectIdOptions = (projects: Project[]) => {- return projects- .filter((proj) => proj.name != DEFAULT_PROJECT_NAME)- .map<SelectOption>((proj) => {- const projectId = extractProjectResourceName(proj.name);- return {- label: `${proj.title} (${projectId})`,- value: projectId,- render: getRenderOptionFunc(proj),- };- });-};--export const getDatabasFullNameOptions = (databases: ComposedDatabase[]) => {- return databases.map<SelectOption>((database) => {- return {- label: database.name,- value: database.name,- render: getRenderOptionFunc({- name: database.name,- title: () =>- h(RichDatabaseName, {- database,- showEngineIcon: true,- showInstance: true,- showProject: false,- showArrow: true,- }),- }),- };- });-};--export const getDatabaseIdOptions = (databases: ComposedDatabase[]) => {- return databases.map<SelectOption>((database) => {- return {- label: database.databaseName,- value: database.databaseName,- render: getRenderOptionFunc({- name: database.name,- title: () =>- h(RichDatabaseName, {- database,- showEngineIcon: true,- showInstance: false,- showProject: false,- showArrow: false,- }),- }),- };- });-};-const getDBEndingOptions = () => {- return supportedEngineV1List().map<SelectOption>((type) => ({+ return supportedEngineV1List().map<ResourceSelectOption<unknown>>((type) => ({label: engineNameV1(type),value: Engine[type],}));};const getLevelOptions = () => {- return PresetRiskLevelList.map<SelectOption>(({ level }) => ({- label: levelText(level),- value: level,- }));+ return PresetRiskLevelList.map<ResourceSelectOption<unknown>>(+ ({ level }) => ({+ label: levelText(level),+ value: RiskLevel[level],+ })+ );};const getRiskLevelOptions = () => {@@ -207,7 +96,7 @@ const getRiskLevelOptions = () => {value: "HIGH",},];- return levels.map<SelectOption>(({ label, value }) => ({+ return levels.map<ResourceSelectOption<unknown>>(({ label, value }) => ({label,value,}));@@ -215,7 +104,7 @@ const getRiskLevelOptions = () => {const getSQLTypeOptions = (source: WorkspaceApprovalSetting_Rule_Source) => {const mapOptions = (values: readonly string[]) => {- return values.map<SelectOption>((v) => ({+ return values.map<ResourceSelectOption<unknown>>((v) => ({label: v,value: v,}));@@ -305,44 +194,16 @@ export const getApprovalOptionConfigMap = () => {const factorList = getApprovalFactorList(source);return factorList.reduce((map, factor) => {- let options: SelectOption[] = [];+ let options: ResourceSelectOption<unknown>[] = [];switch (factor) {case CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID:options = getEnvironmentIdOptions();break;case CEL_ATTRIBUTE_RESOURCE_PROJECT_ID:- const projectStore = useProjectV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return projectStore- .fetchProjectList({- pageSize: getDefaultPagination(),- filter: {- query: keyword,- },- })- .then((resp) => getProjectIdOptions(resp.projects));- },- });+ map.set(factor, getProjectIdOptionConfig());return map;case CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID:- const store = useInstanceV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return store- .fetchInstanceList({- pageSize: getDefaultPagination(),- filter: {- query: keyword,- },- })- .then((resp) => getInstanceIdOptions(resp.instances));- },- });+ map.set(factor, getInstanceIdOptionConfig());return map;case CEL_ATTRIBUTE_RESOURCE_DB_ENGINE:options = getDBEndingOptions();@@ -363,7 +224,7 @@ export const getApprovalOptionConfigMap = (break;}- map.set(factor, { options, remote: false });+ map.set(factor, { options });return map;}, new Map<Factor, OptionConfig>());diff --git a/frontend/src/components/DatabaseGroup/utils.ts b/frontend/src/components/DatabaseGroup/utils.tsindex 47b55c79ee..8d6abe9508 100644--- a/frontend/src/components/DatabaseGroup/utils.ts+++ b/frontend/src/components/DatabaseGroup/utils.ts@@ -1,13 +1,11 @@-import type { SelectOption } from "naive-ui";-import {- getDatabaseIdOptions,- getEnvironmentIdOptions,-} from "@/components/CustomApproval/Settings/components/common";import { type OptionConfig } from "@/components/ExprEditor/context";-import { getInstanceIdOptions } from "@/components/SensitiveData/components/utils";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import type { Factor } from "@/plugins/cel";-import { useDatabaseV1Store, useInstanceV1Store } from "@/store";-import { getDefaultPagination } from "@/utils";+import {+ getDatabaseIdOptionConfig,+ getEnvironmentIdOptions,+ getInstanceIdOptionConfig,+} from "@/utils";import {CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,@@ -22,49 +20,19 @@ export const FactorList: Factor[] = [export const getDatabaseGroupOptionConfigMap = (project: string) => {return FactorList.reduce((map, factor) => {- let options: SelectOption[] = [];+ let options: ResourceSelectOption<unknown>[] = [];switch (factor) {case CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID:options = getEnvironmentIdOptions();break;case CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID:- const store = useInstanceV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return store- .fetchInstanceList({- pageSize: getDefaultPagination(),- filter: {- query: keyword,- },- })- .then((resp) => getInstanceIdOptions(resp.instances));- },- });+ map.set(factor, getInstanceIdOptionConfig());return map;case CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME:- const dbStore = useDatabaseV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return dbStore- .fetchDatabases({- pageSize: getDefaultPagination(),- parent: project,- filter: {- query: keyword,- },- })- .then((resp) => getDatabaseIdOptions(resp.databases));- },- });+ map.set(factor, getDatabaseIdOptionConfig(project));return map;}map.set(factor, {- remote: false,options,});return map;diff --git a/frontend/src/components/ExprEditor/components/MultiSelect.vue b/frontend/src/components/ExprEditor/components/MultiSelect.vueindex 26c63e1f29..93d4d048dc 100644--- a/frontend/src/components/ExprEditor/components/MultiSelect.vue+++ b/frontend/src/components/ExprEditor/components/MultiSelect.vue@@ -1,9 +1,23 @@<template>+ <RemoteResourceSelector+ v-if="optionConfig.search"+ size="small"+ max-tag-count="responsive"+ style="min-width: 12rem; width: auto; max-width: 20rem; overflow-x: hidden"+ :multiple="true"+ :disabled="readonly"+ :value="value"+ :search="optionConfig.search"+ :additional-options="additionalOptions"+ :consistent-menu-width="false"+ :fallback-option="optionConfig.fallback"+ @update:value="$emit('update:value', $event as string[])"+ @open="initial"+ /><NSelect+ v-else:value="value"- :remote="optionConfig.remote"- :options="state.rawOptionList"- :loading="state.loading"+ :options="optionConfig.options":multiple="true":filterable="true":consistent-menu-width="false"@@ -13,7 +27,6 @@max-tag-count="responsive"size="small"style="min-width: 12rem; width: auto; max-width: 20rem; overflow-x: hidden"- @search="handleSearch"@update:value="$emit('update:value', $event)"><template #action>@@ -27,43 +40,50 @@</template><script lang="ts" setup>-import { useDebounceFn } from "@vueuse/core";-import type { SelectOption } from "naive-ui";import { NCheckbox, NSelect } from "naive-ui";-import { computed, reactive, toRef, watch } from "vue";+import { computed, onMounted, ref, toRef } from "vue";+import RemoteResourceSelector from "@/components/v2/Select/RemoteResourceSelector/index.vue";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import { type ConditionExpr } from "@/plugins/cel";-import { DEBOUNCE_SEARCH_DELAY } from "@/types";import { useExprEditorContext } from "../context";-import { useSelectOptionConfig } from "./common";--interface LocalState {- loading: boolean;- rawOptionList: SelectOption[];-}+import { initOptions, useSelectOptionConfig } from "./common";const props = defineProps<{- value: string[] | number[];+ value: string[];expr: ConditionExpr;}>();const emit = defineEmits<{- (event: "update:value", value: string[] | number[]): void;+ (event: "update:value", value: string[]): void;}>();const context = useExprEditorContext();const { readonly } = context;-const state = reactive<LocalState>({- loading: false,- rawOptionList: [],-});+const { optionConfig } = useSelectOptionConfig(toRef(props, "expr"));+const additionalOptions = ref<ResourceSelectOption<unknown>[]>([]);++const initial = async () => {+ if (props.value.length === 0) {+ return;+ }+ const options = await initOptions(+ props.value.filter(+ (v) => !additionalOptions.value.find((option) => option.value === v)+ ),+ optionConfig.value+ );+ additionalOptions.value = options;+};-const { optionConfig, factor } = useSelectOptionConfig(toRef(props, "expr"));+onMounted(async () => {+ await initial();+});const checkAllState = computed(() => {- const selected = new Set<any>(props.value);+ const selected = new Set<string>(props.value);const checked =selected.size > 0 &&- state.rawOptionList.every((opt) => {+ optionConfig.value.options.every((opt) => {return selected.has(opt.value);});const indeterminate = props.value.length > 0 && !checked;@@ -77,55 +97,10 @@ const toggleCheckAll = (on: boolean) => {if (on) {emit("update:value",- state.rawOptionList.map((opt) => opt.value as string)+ optionConfig.value.options.map((opt) => opt.value as string));} else {emit("update:value", []);}};--// Non-debounced function for initial load-const loadOptions = async (search: string) => {- if (!optionConfig.value.search) {- state.rawOptionList = [...optionConfig.value.options];- return;- }-- state.loading = true;- try {- const options = await optionConfig.value.search(search);- state.rawOptionList = [...options];- } finally {- state.loading = false;- }-};--// Debounced version for user-typed searches-const handleSearch = useDebounceFn(loadOptions, DEBOUNCE_SEARCH_DELAY);--watch(- () => factor.value,- async () => {- // Use non-debounced loadOptions for initial load to ensure options- // are available immediately when the component renders- await loadOptions("");- // valid initial value.- const search = optionConfig.value.search;- if (!search) {- return;- }- const existed = new Set(state.rawOptionList.map((opt) => opt.value));- const pendingInit = props.value.filter((val) => !existed.has(val));- for (const pending of pendingInit) {- const options = await search(pending as string);- for (const option of options) {- if (!existed.has(option.value)) {- state.rawOptionList.push(option);- existed.add(option.value);- }- }- }- },- { immediate: true }-);</script>diff --git a/frontend/src/components/ExprEditor/components/SingleSelect.vue b/frontend/src/components/ExprEditor/components/SingleSelect.vueindex ce2f203e7c..6b9a6105c4 100644--- a/frontend/src/components/ExprEditor/components/SingleSelect.vue+++ b/frontend/src/components/ExprEditor/components/SingleSelect.vue@@ -1,97 +1,65 @@<template>+ <RemoteResourceSelector+ v-if="optionConfig.search"+ size="small"+ style="min-width: 7rem; width: auto; overflow-x: hidden"+ :multiple="false"+ :disabled="readonly"+ :value="value"+ :search="optionConfig.search"+ :consistent-menu-width="false"+ :additional-options="additionalOptions"+ :fallback-option="optionConfig.fallback"+ @update:value="$emit('update:value', $event as string)"+ @open="initial"+ /><NSelect+ v-else+ size="small"+ style="min-width: 7rem; width: auto; overflow-x: hidden":value="value"- :remote="optionConfig.remote"- :options="state.rawOptionList"- :loading="state.loading"+ :options="optionConfig.options":consistent-menu-width="false":filterable="true":placeholder="$t('cel.condition.select-value')":disabled="readonly"- size="small"- style="min-width: 7rem; width: auto; overflow-x: hidden"- @search="handleSearch"@update:value="$emit('update:value', $event)"/></template><script lang="ts" setup>-import { useDebounceFn } from "@vueuse/core";-import type { SelectOption } from "naive-ui";import { NSelect } from "naive-ui";-import { reactive, toRef, watch } from "vue";+import { onMounted, ref, toRef } from "vue";+import RemoteResourceSelector from "@/components/v2/Select/RemoteResourceSelector/index.vue";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import { type ConditionExpr } from "@/plugins/cel";-import { DEBOUNCE_SEARCH_DELAY } from "@/types";import { useExprEditorContext } from "../context";-import { useSelectOptionConfig } from "./common";--interface LocalState {- loading: boolean;- rawOptionList: SelectOption[];-}+import { initOptions, useSelectOptionConfig } from "./common";const props = defineProps<{- value: string | number;+ value: string;expr: ConditionExpr;}>();defineEmits<{- (event: "update:value", value: string | number): void;+ (event: "update:value", value: string): void;}>();const context = useExprEditorContext();const { readonly } = context;-const state = reactive<LocalState>({- loading: false,- rawOptionList: [],-});-const { optionConfig, factor } = useSelectOptionConfig(toRef(props, "expr"));+const { optionConfig } = useSelectOptionConfig(toRef(props, "expr"));+const additionalOptions = ref<ResourceSelectOption<unknown>[]>([]);-// Non-debounced function for initial load-const loadOptions = async (search: string) => {- if (!optionConfig.value.search) {- state.rawOptionList = [...optionConfig.value.options];+const initial = async () => {+ if (!props.value || additionalOptions.value[0]?.value === props.value) {return;}-- state.loading = true;- try {- const options = await optionConfig.value.search(search);- state.rawOptionList = [...options];- } finally {- state.loading = false;- }+ const options = await initOptions([props.value], optionConfig.value);+ additionalOptions.value = options;};-// Debounced version for user-typed searches-const handleSearch = useDebounceFn(loadOptions, DEBOUNCE_SEARCH_DELAY);--watch(- () => factor.value,- async () => {- // Use non-debounced loadOptions for initial load to ensure options- // are available immediately when the component renders- await loadOptions("");- const search = optionConfig.value.search;- if (!search) {- return;- }-- if (- props.value &&- !state.rawOptionList.find((opt) => opt.value === props.value)- ) {- const existed = new Set(state.rawOptionList.map((opt) => opt.value));- const options = await search(props.value as string);- for (const option of options) {- if (!existed.has(option.value)) {- state.rawOptionList.push(option);- existed.add(option.value);- }- }- }- },- { immediate: true }-);+onMounted(async () => {+ await initial();+});</script>diff --git a/frontend/src/components/ExprEditor/components/ValueInput.vue b/frontend/src/components/ExprEditor/components/ValueInput.vueindex 2c4785a0d6..ce6ee0e5e3 100644--- a/frontend/src/components/ExprEditor/components/ValueInput.vue+++ b/frontend/src/components/ExprEditor/components/ValueInput.vue@@ -14,9 +14,9 @@<template v-if="inputType === 'SINGLE-SELECT'"><SingleSelectv-if="isNumberValue"- :value="getNumberValue()"+ :value="`${getNumberValue()}`":expr="expr"- @update:value="setNumberValue($event as number)"+ @update:value="setNumberValue(Number($event))"/><SingleSelectv-if="isStringValue"@@ -27,7 +27,7 @@</template><template v-if="inputType === 'MULTI-SELECT'"><MultiSelect- :value="getArrayValue()"+ :value="getStringArrayValue()":expr="expr"@update:value="setArrayValue($event)"/>@@ -97,7 +97,7 @@ const isArrayValue = computed(() => {const inputType = computed((): InputType => {const optionConfig = optionConfigMap.value.get(factor.value);const hasOption =- (optionConfig?.options.length ?? 0 > 0) || optionConfig?.remote;+ (optionConfig?.options.length ?? 0 > 0) || optionConfig?.search;if (isArrayValue.value) {return hasOption ? "MULTI-SELECT" : "MULTI-INPUT";diff --git a/frontend/src/components/ExprEditor/components/common.ts b/frontend/src/components/ExprEditor/components/common.tsindex 81538a3d63..6e0983ca64 100644--- a/frontend/src/components/ExprEditor/components/common.ts+++ b/frontend/src/components/ExprEditor/components/common.ts@@ -1,5 +1,6 @@import type { ComputedRef, Ref } from "vue";import { computed } from "vue";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import type { ConditionExpr } from "@/plugins/cel";import {type Factor,@@ -7,8 +8,38 @@ import {type Operator,} from "@/plugins/cel";import { t, te } from "@/plugins/i18n";+import { getDefaultPagination } from "@/utils";import { type OptionConfig, useExprEditorContext } from "../context";+export const initOptions = async (+ values: string[],+ optionConfig: OptionConfig+): Promise<ResourceSelectOption<unknown>[]> => {+ if (optionConfig.fetch) {+ return await optionConfig.fetch(values);+ }++ if (optionConfig.search && !optionConfig.fallback) {+ // only use the batch search when not provide the fallback+ const search = optionConfig.search;+ const response = await Promise.all(+ values.map((value) =>+ search({+ search: value,+ pageToken: "",+ pageSize: getDefaultPagination(),+ })+ )+ );+ return response.reduce<ResourceSelectOption<unknown>[]>((list, resp) => {+ list.push(...resp.options);+ return list;+ }, []);+ }++ return [];+};+export const useSelectOptionConfig = (expr: Ref<ConditionExpr>): {@@ -21,9 +52,7 @@ export const useSelectOptionConfig = (const factor = computed(() => expr.value.args[0]);const optionConfig = computed(() => {- return (- optionConfigMap.value.get(factor.value) || { remote: false, options: [] }- );+ return optionConfigMap.value.get(factor.value) || { options: [] };});return { optionConfig, factor };diff --git a/frontend/src/components/ExprEditor/context.ts b/frontend/src/components/ExprEditor/context.tsindex ce7a5e0038..05e11a84a1 100644--- a/frontend/src/components/ExprEditor/context.ts+++ b/frontend/src/components/ExprEditor/context.ts@@ -1,11 +1,19 @@-import type { SelectOption } from "naive-ui";import { type InjectionKey, inject, provide, type Ref } from "vue";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import type { Factor, Operator } from "@/plugins/cel";export type OptionConfig = {- remote: boolean;- search?: (keyword: string) => Promise<SelectOption[]>;- options: SelectOption[];+ search?: (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => Promise<{+ nextPageToken: string;+ options: ResourceSelectOption<unknown>[];+ }>;+ fetch?: (names: string[]) => Promise<ResourceSelectOption<unknown>[]>;+ fallback?: (value: string) => ResourceSelectOption<unknown>;+ options: ResourceSelectOption<unknown>[];};export type ExprEditorContext = {diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vueindex 0084c4bd6d..49a74e9b7b 100644--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue@@ -59,7 +59,6 @@import { cloneDeep, head } from "lodash-es";import { NRadio, NRadioGroup, NTooltip } from "naive-ui";import { computed, reactive, watch } from "vue";-import { getDatabasFullNameOptions } from "@/components/CustomApproval/Settings/components/common";import ExprEditor from "@/components/ExprEditor";import { type OptionConfig } from "@/components/ExprEditor/context";import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";@@ -71,12 +70,12 @@ import {validateSimpleExpr,wrapAsGroup,} from "@/plugins/cel";-import { hasFeature, useDatabaseV1Store, useProjectByName } from "@/store";-import type { DatabaseResource } from "@/types";+import { hasFeature, useProjectByName } from "@/store";+import { type DatabaseResource } from "@/types";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {batchConvertCELStringToParsedExpr,- getDefaultPagination,+ getDatabaseNameOptionConfig,} from "@/utils";import {CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,@@ -205,7 +204,6 @@ watch(const { project } = useProjectByName(computed(() => props.projectName));const hasRequiredFeature = computed(() => hasFeature(props.requiredFeature));-const dbStore = useDatabaseV1Store();const factorList = computed((): Factor[] => {const list: Factor[] = [@@ -230,25 +228,10 @@ const factorOptionConfigMap = computed((): Map<Factor, OptionConfig> => {return factorList.value.reduce((map, factor) => {if (factor !== CEL_ATTRIBUTE_RESOURCE_DATABASE) {map.set(factor, {- remote: false,options: [],});} else {- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return dbStore- .fetchDatabases({- pageSize: getDefaultPagination(),- parent: props.projectName,- filter: {- query: keyword,- },- })- .then((resp) => getDatabasFullNameOptions(resp.databases));- },- });+ map.set(factor, getDatabaseNameOptionConfig(props.projectName));}return map;}, new Map<Factor, OptionConfig>());diff --git a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vueindex b8d95c8f41..32fe961cc0 100644--- a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue+++ b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue@@ -120,26 +120,15 @@ import {PencilIcon,PlusIcon,} from "lucide-vue-next";-import { NButton, NEmpty, type SelectOption } from "naive-ui";+import { NButton, NEmpty } from "naive-ui";import { v4 as uuidv4 } from "uuid";import { computed, nextTick, onMounted, reactive, ref } from "vue";import { useI18n } from "vue-i18n";-import {- getEnvironmentIdOptions,- getProjectIdOptions,-} from "@/components/CustomApproval/Settings/components/common";-import { getDatabaseIdOptions } from "@/components/CustomApproval/Settings/components/common/utils";import { type OptionConfig } from "@/components/ExprEditor/context";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import { useBodyLayoutContext } from "@/layouts/common";import type { Factor } from "@/plugins/cel";-import {- featureToRef,- pushNotification,- useDatabaseV1Store,- useInstanceV1Store,- usePolicyV1Store,- useProjectV1Store,-} from "@/store";+import { featureToRef, pushNotification, usePolicyV1Store } from "@/store";import type {MaskingRulePolicy_MaskingRule,Policy,@@ -153,7 +142,10 @@ import {import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {arraySwap,- getDefaultPagination,+ getDatabaseIdOptionConfig,+ getEnvironmentIdOptions,+ getInstanceIdOptionConfig,+ getProjectIdOptionConfig,hasWorkspacePermissionV2,} from "@/utils";import {@@ -168,10 +160,7 @@ import {import LearnMoreLink from "../LearnMoreLink.vue";import { MiniActionButton } from "../v2";import MaskingRuleConfig from "./components/MaskingRuleConfig.vue";-import {- getClassificationLevelOptions,- getInstanceIdOptions,-} from "./components/utils";+import { getClassificationLevelOptions } from "./components/utils";type MaskingRuleMode = "NORMAL" | "EDIT" | "CREATE";@@ -361,70 +350,26 @@ const factorList = computed((): Factor[] => {const factorOptionsMap = computed((): Map<Factor, OptionConfig> => {return factorList.value.reduce((map, factor) => {- let options: SelectOption[] = [];+ let options: ResourceSelectOption<unknown>[] = [];switch (factor) {case CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID:options = getEnvironmentIdOptions();break;case CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID:- const store = useInstanceV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return store- .fetchInstanceList({- pageSize: getDefaultPagination(),- filter: {- query: keyword,- },- })- .then((resp) => getInstanceIdOptions(resp.instances));- },- });+ map.set(factor, getInstanceIdOptionConfig());return map;case CEL_ATTRIBUTE_RESOURCE_PROJECT_ID:- const projectStore = useProjectV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return projectStore- .fetchProjectList({- pageSize: getDefaultPagination(),- filter: {- query: keyword,- },- })- .then((resp) => getProjectIdOptions(resp.projects));- },- });+ map.set(factor, getProjectIdOptionConfig());return map;case CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL:options = getClassificationLevelOptions();break;case CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME: {- const dbStore = useDatabaseV1Store();- map.set(factor, {- remote: true,- options: [],- search: async (keyword: string) => {- return dbStore- .fetchDatabases({- pageSize: getDefaultPagination(),- parent: "workspaces/-",- filter: {- query: keyword,- },- })- .then((resp) => getDatabaseIdOptions(resp.databases));- },- });+ map.set(factor, getDatabaseIdOptionConfig("workspaces/-"));return map;}}map.set(factor, {- remote: false,options,});return map;diff --git a/frontend/src/components/SensitiveData/components/utils.ts b/frontend/src/components/SensitiveData/components/utils.tsindex 77b715270d..69265706e5 100644--- a/frontend/src/components/SensitiveData/components/utils.ts+++ b/frontend/src/components/SensitiveData/components/utils.ts@@ -1,19 +1,14 @@import { create } from "@bufbuild/protobuf";import { uniq } from "lodash-es";-import type { SelectOption } from "naive-ui";-import { h } from "vue";-import { getRenderOptionFunc } from "@/components/CustomApproval/Settings/components/common";-import { InstanceV1Name } from "@/components/v2";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";import type { Factor, Operator } from "@/plugins/cel";import { CollectionOperatorList, EqualityOperatorList } from "@/plugins/cel";import { useSettingV1Store } from "@/store";-import type { Instance } from "@/types/proto-es/v1/instance_service_pb";import type { Algorithm } from "@/types/proto-es/v1/setting_service_pb";import {AlgorithmSchema,Setting_SettingName,} from "@/types/proto-es/v1/setting_service_pb";-import { extractInstanceResourceName } from "@/utils";import { CEL_ATTRIBUTE_RESOURCE_PROJECT_ID } from "@/utils/cel-attributes";export const getClassificationLevelOptions = () => {@@ -33,30 +28,12 @@ export const getClassificationLevelOptions = () => {return [];}- return config[0].levels.map<SelectOption>((level) => ({+ return config[0].levels.map<ResourceSelectOption<unknown>>((level) => ({label: level.title,value: level.id,}));};-export const getInstanceIdOptions = (instanceList: Instance[]) => {- return instanceList.map<SelectOption>((ins) => {- const instanceId = extractInstanceResourceName(ins.name);- return {- label: `${ins.title} (${instanceId})`,- value: instanceId,- render: getRenderOptionFunc({- name: ins.name,- title: () =>- h(InstanceV1Name, {- instance: ins,- link: false,- }),- }),- };- });-};-export const factorOperatorOverrideMap = new Map<Factor, Operator[]>([[CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,diff --git a/frontend/src/utils/expr.ts b/frontend/src/utils/expr.tsnew file mode 100644index 0000000000..49f8dff210--- /dev/null+++ b/frontend/src/utils/expr.ts@@ -0,0 +1,271 @@+import { CheckIcon } from "lucide-vue-next";+import type { VNode } from "vue";+import { h } from "vue";+import { type OptionConfig } from "@/components/ExprEditor/context";+import {+ EnvironmentV1Name,+ InstanceV1Name,+ RichDatabaseName,+} from "@/components/v2";+import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";+import {+ instanceNamePrefix,+ projectNamePrefix,+ useDatabaseV1Store,+ useEnvironmentV1Store,+ useInstanceV1Store,+ useProjectV1Store,+} from "@/store";+import { type ComposedDatabase, isValidInstanceName } from "@/types";+import type { Instance } from "@/types/proto-es/v1/instance_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import {+ extractInstanceResourceName,+ extractProjectResourceName,+} from "@/utils";++const getRenderOptionFunc = (resource: {+ title: string | (() => VNode);+ name: string;+}): ((info: { node: VNode; selected: boolean }) => VNode) => {+ return (info: { node: VNode; selected: boolean }) => {+ return h(+ info.node,+ { class: "flex items-center justify-between gap-x-4" },+ [+ h("div", { class: "flex flex-col px-1 py-1 z-10" }, [+ typeof resource.title === "string"+ ? h(+ "div",+ { class: `textlabel ${info.selected ? "text-accent!" : ""}` },+ resource.title+ )+ : resource.title(),+ h("div", { class: "opacity-60 textinfolabel" }, resource.name),+ ]),+ info.selected ? h(CheckIcon, { class: "w-4 z-10" }) : undefined,+ ]+ );+ };+};++export const getEnvironmentIdOptions = () => {+ const environmentList = useEnvironmentV1Store().getEnvironmentList();+ return environmentList.map<ResourceSelectOption<unknown>>((env) => {+ const environmentId = env.id;+ return {+ label: `${env.title} (${environmentId})`,+ value: environmentId,+ render: getRenderOptionFunc({+ name: env.name,+ title: () =>+ h(EnvironmentV1Name, {+ environment: env,+ link: false,+ showColor: true,+ }),+ }),+ };+ });+};++const getProjectIdOption = (proj: Project) => {+ const projectId = extractProjectResourceName(proj.name);+ return {+ label: `${proj.title} (${projectId})`,+ value: projectId,+ render: getRenderOptionFunc(proj),+ };+};++const getDatabasFullNameOption = (database: ComposedDatabase) => {+ return {+ label: database.name,+ value: database.name,+ render: getRenderOptionFunc({+ name: database.name,+ title: () =>+ h(RichDatabaseName, {+ database,+ showEngineIcon: true,+ showInstance: true,+ showProject: false,+ showArrow: true,+ }),+ }),+ };+};++const getInstanceIdOption = (ins: Instance) => {+ const instanceId = extractInstanceResourceName(ins.name);+ return {+ label: `${ins.title} (${instanceId})`,+ value: instanceId,+ render: getRenderOptionFunc({+ name: ins.name,+ title: () =>+ h(InstanceV1Name, {+ instance: ins,+ link: false,+ }),+ }),+ };+};++const getDatabaseIdOptions = (databases: ComposedDatabase[]) => {+ return databases.map<ResourceSelectOption<unknown>>((database) => {+ return {+ label: database.databaseName,+ value: database.databaseName,+ render: getRenderOptionFunc({+ name: database.name,+ title: () =>+ h(RichDatabaseName, {+ database,+ showEngineIcon: true,+ showInstance: false,+ showProject: false,+ showArrow: false,+ }),+ }),+ };+ });+};++export const getProjectIdOptionConfig = (): OptionConfig => {+ const projectStore = useProjectV1Store();+ return {+ options: [],+ fetch: async (projectIds: string[]) => {+ const projects = await projectStore.batchGetProjects(+ projectIds.map((projectId) => `${projectNamePrefix}${projectId}`)+ );+ return projects.map(getProjectIdOption);+ },+ search: async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => {+ return projectStore+ .fetchProjectList({+ pageSize: params.pageSize,+ pageToken: params.pageToken,+ filter: {+ query: params.search,+ excludeDefault: true,+ },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken ?? "",+ options: resp.projects.map(getProjectIdOption),+ }));+ },+ };+};++export const getInstanceIdOptionConfig = (): OptionConfig => {+ const store = useInstanceV1Store();+ return {+ options: [],+ fetch: async (instanceIds: string[]) => {+ // TODO(ed): batch fetch instances+ const instances = await Promise.all(+ instanceIds.map((instanceId) =>+ store.getOrFetchInstanceByName(`${instanceNamePrefix}${instanceId}`)+ )+ );+ const options: ResourceSelectOption<unknown>[] = [];+ for (const instance of instances) {+ if (!isValidInstanceName(instance.name)) {+ continue;+ }+ options.push(getInstanceIdOption(instance));+ }+ return options;+ },+ search: async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => {+ return store+ .fetchInstanceList({+ pageSize: params.pageSize,+ pageToken: params.pageToken,+ filter: {+ query: params.search,+ },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: resp.instances.map(getInstanceIdOption),+ }));+ },+ };+};++export const getDatabaseIdOptionConfig = (parent: string): OptionConfig => {+ const dbStore = useDatabaseV1Store();+ return {+ options: [],+ // Since we use the database name (not the fullname) as the value, we cannot fetch the resource because we don't know the instance id.+ // While searching via query is possible, but the performance cost could be significant if there're multiple values.+ // So provide the fallback to show the selected database name instead of the entire database entity.+ fallback: (value: string) => {+ return {+ label: value,+ value: value,+ };+ },+ search: async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => {+ return dbStore+ .fetchDatabases({+ pageSize: params.pageSize,+ pageToken: params.pageToken,+ parent: parent,+ filter: {+ query: params.search,+ },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: getDatabaseIdOptions(resp.databases),+ }));+ },+ };+};++export const getDatabaseNameOptionConfig = (parent: string): OptionConfig => {+ const dbStore = useDatabaseV1Store();+ return {+ options: [],+ fetch: async (names: string[]) => {+ const databases = await dbStore.batchGetDatabases(names);+ return databases.map(getDatabasFullNameOption);+ },+ search: async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => {+ return dbStore+ .fetchDatabases({+ pageSize: params.pageSize,+ pageToken: params.pageToken,+ parent,+ filter: {+ query: params.search,+ },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: resp.databases.map(getDatabasFullNameOption),+ }));+ },+ };+};diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex ce6c432f9e..fba8db2159 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -25,3 +25,4 @@ export * from "./v1";export * from "./iam";export * from "./auto-route";export * from "./pagination";+export * from "./expr";