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(frontend): performance optimization (part.2) (#12713)
Liu Ji3b43c4de54a4
diff --git a/frontend/src/components/Branch/BranchCreateView.vue b/frontend/src/components/Branch/BranchCreateView.vueindex ea8205f3cd..8c05183690 100644--- a/frontend/src/components/Branch/BranchCreateView.vue+++ b/frontend/src/components/Branch/BranchCreateView.vue@@ -145,7 +145,7 @@ const isPreparingBranch = ref(false);const EMPTY_BRANCH = Branch.fromPartial({});const allowCreateBranchFromDatabase = computed(() => {- return isOwnerOfProjectV1(props.project.iamPolicy, me.value);+ return isOwnerOfProjectV1(props.project, me.value);});const debouncedDatabaseId = useDebounce(databaseId, DEBOUNCE_RATE);diff --git a/frontend/src/components/Branch/BranchDetailView.vue b/frontend/src/components/Branch/BranchDetailView.vueindex bc7f60f0b1..b561257928 100644--- a/frontend/src/components/Branch/BranchDetailView.vue+++ b/frontend/src/components/Branch/BranchDetailView.vue@@ -273,7 +273,7 @@ const showMergeBranchButton = computed(() => {const showRebaseBranchButton = computed(() => {// For main branches: only project owners are allowedif (!parentBranch.value) {- return isOwnerOfProjectV1(props.project.iamPolicy, currentUser.value);+ return isOwnerOfProjectV1(props.project, currentUser.value);}// For feature branches: project owners and branch creator@@ -284,7 +284,7 @@ const showRebaseBranchButton = computed(() => {const showApplyBranchButton = computed(() => {return (!parentBranch.value &&- isOwnerOfProjectV1(props.project.iamPolicy, currentUser.value)+ isOwnerOfProjectV1(props.project, currentUser.value));});diff --git a/frontend/src/components/Branch/BranchMergeView/BranchMergeView.vue b/frontend/src/components/Branch/BranchMergeView/BranchMergeView.vueindex 4b17648ebd..917a4b2812 100644--- a/frontend/src/components/Branch/BranchMergeView/BranchMergeView.vue+++ b/frontend/src/components/Branch/BranchMergeView/BranchMergeView.vue@@ -145,7 +145,7 @@ const parentBranchOnly = computed(() => {if (!head.parentBranch) {return false; // parent-less (main) branches}- if (isOwnerOfProjectV1(props.project.iamPolicy, me.value)) {+ if (isOwnerOfProjectV1(props.project, me.value)) {return false; // project owners are not limited}return true;diff --git a/frontend/src/components/Branch/BranchRebaseView/BranchRebaseView.vue b/frontend/src/components/Branch/BranchRebaseView/BranchRebaseView.vueindex 57852a29c9..ebe1483d02 100644--- a/frontend/src/components/Branch/BranchRebaseView/BranchRebaseView.vue+++ b/frontend/src/components/Branch/BranchRebaseView/BranchRebaseView.vue@@ -183,7 +183,7 @@ const parentBranchOnly = computed(() => {if (!head.parentBranch) {return false; // parent-less (main) branches}- if (isOwnerOfProjectV1(props.project.iamPolicy, me.value)) {+ if (isOwnerOfProjectV1(props.project, me.value)) {return false; // project owners are not limited}return true;diff --git a/frontend/src/components/KBar/useDatabaseActions.ts b/frontend/src/components/KBar/useDatabaseActions.tsindex 11aede659c..e8bcec11d2 100644--- a/frontend/src/components/KBar/useDatabaseActions.ts+++ b/frontend/src/components/KBar/useDatabaseActions.ts@@ -86,21 +86,25 @@ const useDatabaseActions = (databaseList: MaybeRef<ComposedDatabase[]>) => {};export const useProjectDatabaseActions = (- project: MaybeRef<ComposedProject>+ project: MaybeRef<ComposedProject>,+ limit: number) => {const projectDatabaseList = computed(() => {- return useDatabaseV1Store().databaseListByProject(unref(project).name);+ return useDatabaseV1Store()+ .databaseListByProject(unref(project).name)+ .slice(0, limit); // Don't create too many actions});useDatabaseActions(projectDatabaseList);};-export const useGlobalDatabaseActions = () => {+export const useGlobalDatabaseActions = (limit: number) => {const me = useCurrentUserV1();// Use this to make the list reactive when project is transferred.const databaseList = computed(() => {return useDatabaseV1Store().databaseListByUser(me.value)- .filter((db) => db.project !== DEFAULT_PROJECT_V1_NAME);+ .filter((db) => db.project !== DEFAULT_PROJECT_V1_NAME)+ .slice(0, limit); // Don't create too many actions});useDatabaseActions(databaseList);};diff --git a/frontend/src/components/KBar/useProjectActions.ts b/frontend/src/components/KBar/useProjectActions.tsindex 8290c42d12..6f0157cc96 100644--- a/frontend/src/components/KBar/useProjectActions.ts+++ b/frontend/src/components/KBar/useProjectActions.ts@@ -7,7 +7,7 @@ import { useCurrentUserV1, useProjectV1List } from "@/store";import { DEFAULT_PROJECT_ID } from "@/types";import { hasProjectPermissionV2 } from "@/utils";-export const useProjectActions = () => {+export const useProjectActions = (limit: number) => {const { t } = useI18n();const router = useRouter();const me = useCurrentUserV1();@@ -23,7 +23,7 @@ export const useProjectActions = () => {});const sortedProjectList = computed(() => {- return [...accessibleProjectList.value].sort((a, b) =>+ return [...accessibleProjectList.value.slice(0, limit)].sort((a, b) =>a.title.localeCompare(b.title));});diff --git a/frontend/src/components/Project/ProjectSidebarV1.vue b/frontend/src/components/Project/ProjectSidebarV1.vueindex 5fe515e9a1..acf356391a 100644--- a/frontend/src/components/Project/ProjectSidebarV1.vue+++ b/frontend/src/components/Project/ProjectSidebarV1.vue@@ -86,5 +86,5 @@ const navigationKbarActions = computed(() => {});useRegisterActions(navigationKbarActions);-useProjectDatabaseActions(project);+useProjectDatabaseActions(project, 10);</script>diff --git a/frontend/src/components/ProvideDashboardContext.vue b/frontend/src/components/ProvideDashboardContext.vueindex add68ab4d4..48b84c397e 100644--- a/frontend/src/components/ProvideDashboardContext.vue+++ b/frontend/src/components/ProvideDashboardContext.vue@@ -1,10 +1,18 @@<template>- <slot v-if="!isLoading" />+ <slot v-if="!isInitializing" /><MaskSpinner v-else class="!bg-white" />++ <div+ v-if="!isInitializing && isSwitchingProject"+ class="fixed inset-0 z-[1000000] bg-white/50 flex flex-col items-center justify-center"+ >+ <NSpin />+ </div></template><script lang="ts" setup>-import { ref, onMounted, watch } from "vue";+import { NSpin } from "naive-ui";+import { ref, onMounted } from "vue";import { useRoute, useRouter } from "vue-router";import {useEnvironmentV1Store,@@ -24,7 +32,8 @@ import MaskSpinner from "./misc/MaskSpinner.vue";const route = useRoute();const router = useRouter();-const isLoading = ref<boolean>(true);+const isInitializing = ref<boolean>(true);+const isSwitchingProject = ref(false);const policyStore = usePolicyV1Store();const databaseStore = useDatabaseV1Store();@@ -47,9 +56,13 @@ const fetchDatabases = async (project: string) => {filter: filters.join(" && "),});};++const instanceAndDatabaseInitialized = new Set<string /* project */>();const fetchInstancesAndDatabases = async (project: string) => {+ if (instanceAndDatabaseInitialized.has(project || "")) return;await fetchInstances(project);await fetchDatabases(project);+ instanceAndDatabaseInitialized.add(project || "");};onMounted(async () => {@@ -74,14 +87,25 @@ onMounted(async () => {await Promise.all([useUIStateStore().restoreState()]);await fetchInstancesAndDatabases(route.params.projectId as string);- watch(- () => route.params.projectId,- (project) => {- fetchInstancesAndDatabases(project as string);- },- { immediate: false }- );+ isInitializing.value = false;- isLoading.value = false;+ router.beforeEach((to, from, next) => {+ const fromProject = from.params.projectId as string;+ const toProject = to.params.projectId as string;+ if (fromProject !== toProject) {+ console.debug(+ `[ProvideDashboardContext] project switched ${fromProject} -> ${toProject}`+ );+ isSwitchingProject.value = true;+ fetchInstancesAndDatabases(toProject).finally(() => {+ isSwitchingProject.value = false;++ next();+ });+ return;+ }++ next();+ });});</script>diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vueindex 5158996c90..bee70c1214 100644--- a/frontend/src/components/v2/Select/ProjectSelect.vue+++ b/frontend/src/components/v2/Select/ProjectSelect.vue@@ -22,7 +22,12 @@ import { NSelect } from "naive-ui";import { computed, watchEffect } from "vue";import { useI18n } from "vue-i18n";import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";-import { useCurrentUserV1, useProjectV1Store, useProjectV1List } from "@/store";+import {+ useCurrentUserV1,+ useProjectV1Store,+ useProjectV1List,+ usePermissionStore,+} from "@/store";import type { ComposedProject } from "@/types";import {DEFAULT_PROJECT_ID,@@ -33,7 +38,7 @@ import {import { State } from "@/types/proto/v1/common";import type { Project } from "@/types/proto/v1/project_service";import { Workflow } from "@/types/proto/v1/project_service";-import { hasWorkspacePermissionV2, roleListInProjectV1 } from "@/utils";+import { hasWorkspacePermissionV2 } from "@/utils";interface ProjectSelectOption extends SelectOption {value: string;@@ -77,6 +82,7 @@ const emit = defineEmits<{const { t } = useI18n();const currentUserV1 = useCurrentUserV1();const projectV1Store = useProjectV1Store();+const permissionStore = usePermissionStore();const prepare = () => {projectV1Store.fetchProjectList(true /* showDeleted */);@@ -146,7 +152,10 @@ const combinedProjectList = computed(() => {props.allowedProjectRoleList.length > 0) {list = list.filter((project) => {- const roles = roleListInProjectV1(project.iamPolicy, currentUserV1.value);+ const roles = permissionStore.roleListInProjectV1(+ project,+ currentUserV1.value+ );return intersection(props.allowedProjectRoleList, roles).length > 0;});}diff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vueindex a6e4b989c6..81e583fe40 100644--- a/frontend/src/layouts/BodyLayout.vue+++ b/frontend/src/layouts/BodyLayout.vue@@ -3,99 +3,99 @@<div class="flex-1 flex overflow-hidden"><HideInStandaloneMode><!-- Off-canvas menu for mobile, show/hide based on off-canvas menu state. -->- <div v-if="state.showMobileOverlay" class="md:hidden">- <div class="fixed inset-0 flex z-40">- <div class="fixed inset-0">- <div- class="absolute inset-0 bg-gray-600 opacity-75"+ <div+ v-show="state.showMobileOverlay"+ :class="[sidebarView === 'MOBILE' ? 'block' : 'hidden']"+ class="fixed inset-0 flex z-40"+ >+ <div class="fixed inset-0">+ <div+ class="absolute inset-0 bg-gray-600 opacity-75"+ @click.prevent="state.showMobileOverlay = false"+ ></div>+ </div>+ <div+ tabindex="0"+ class="relative flex-1 flex flex-col max-w-xs w-full bg-white focus:outline-none"+ >+ <div class="absolute top-0 right-0 -mr-12 pt-2">+ <button+ type="button"+ class="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"@click.prevent="state.showMobileOverlay = false"- ></div>+ >+ <span class="sr-only">Close sidebar</span>+ <!-- Heroicon name: x -->+ <heroicons-solid:x class="h-6 w-6 text-white" />+ </button>+ </div>+ <!-- Mobile Sidebar -->+ <div id="sidebar-mobile" class="flex-1 h-0 py-0 overflow-y-auto">+ <!-- Empty as teleport placeholder --></div><div- tabindex="0"- class="relative flex-1 flex flex-col max-w-xs w-full bg-white focus:outline-none"+ class="flex-shrink-0 flex border-t border-block-border px-3 py-1.5">- <div class="absolute top-0 right-0 -mr-12 pt-2">- <button- type="button"- class="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"- @click.prevent="state.showMobileOverlay = false"- >- <span class="sr-only">Close sidebar</span>- <!-- Heroicon name: x -->- <heroicons-solid:x class="h-6 w-6 text-white" />- </button>- </div>- <!-- Mobile Sidebar -->- <div class="flex-1 h-0 py-0 overflow-y-auto">- <router-view- name="leftSidebar"- @click="state.showMobileOverlay = false"+ <div+ v-if="isDemo"+ class="text-sm flex whitespace-nowrap text-accent"+ >+ <heroicons-outline:presentation-chart-bar+ class="w-5 h-5 mr-1"/>+ {{ $t("common.demo-mode") }}</div>+ <router-link+ v-else-if="!isFreePlan || !hasPermission"+ :to="{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }"+ exact-active-class=""+ class="text-sm flex"+ >+ {{ $t(currentPlan) }}+ </router-link><div- class="flex-shrink-0 flex border-t border-block-border px-3 py-1.5"+ v-else+ class="text-sm flex whitespace-nowrap mr-1 text-accent cursor-pointer"+ @click="state.showTrialModal = true">- <div- v-if="isDemo"- class="text-sm flex whitespace-nowrap text-accent"- >- <heroicons-outline:presentation-chart-bar- class="w-5 h-5 mr-1"- />- {{ $t("common.demo-mode") }}- </div>- <router-link- v-else-if="!isFreePlan || !hasPermission"- :to="{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }"- exact-active-class=""- class="text-sm flex"- >- {{ $t(currentPlan) }}- </router-link>- <div- v-else- class="text-sm flex whitespace-nowrap mr-1 text-accent cursor-pointer"- @click="state.showTrialModal = true"- >- <heroicons-solid:sparkles class="w-5 h-5" />- {{ $t(currentPlan) }}- </div>- <div- class="text-sm flex items-center gap-x-1 ml-auto"- :class="- canUpgrade- ? 'text-success cursor-pointer'- : 'text-control-light cursor-default'- "- @click="state.showReleaseModal = canUpgrade"- >- <heroicons-outline:volume-up- v-if="canUpgrade"- class="h-4 w-4"- />- {{ version }}- </div>+ <heroicons-solid:sparkles class="w-5 h-5" />+ {{ $t(currentPlan) }}+ </div>+ <div+ class="text-sm flex items-center gap-x-1 ml-auto"+ :class="+ canUpgrade+ ? 'text-success cursor-pointer'+ : 'text-control-light cursor-default'+ "+ @click="state.showReleaseModal = canUpgrade"+ >+ <heroicons-outline:volume-up+ v-if="canUpgrade"+ class="h-4 w-4"+ />+ {{ version }}</div></div>- <div class="flex-shrink-0 w-14" aria-hidden="true">- <!-- Force sidebar to shrink to fit close icon -->- </div>+ </div>+ <div class="flex-shrink-0 w-14" aria-hidden="true">+ <!-- Force sidebar to shrink to fit close icon --></div></div><!-- Static sidebar for desktop --><aside- class="hidden md:flex md:flex-shrink-0"+ class="flex-shrink-0"data-label="bb-dashboard-static-sidebar"+ :class="[sidebarView === 'DESKTOP' ? 'flex' : 'hidden']"><div class="flex flex-col w-52 bg-control-bg"><!-- Sidebar component, swap this element with another sidebar if you like -->- <div class="flex-1 flex flex-col py-0 overflow-y-auto">- <router-view- name="leftSidebar"- @click="state.showMobileOverlay = false"- />+ <div+ id="sidebar-desktop"+ class="flex-1 flex flex-col py-0 overflow-y-auto"+ >+ <!-- Empty as teleport placeholder --></div><divclass="flex-shrink-0 flex justify-between border-t border-block-border px-3 py-1.5"@@ -156,6 +156,20 @@</div></div></aside>++ <!--+ Do not render two instances of sidebars to desktop and mobile sidebars+ but render one sidebar and teleport it to a correct container when+ screen size varies+ -->+ <teleport+ v-if="mounted"+ :to="+ sidebarView === 'DESKTOP' ? '#sidebar-desktop' : '#sidebar-mobile'+ "+ >+ <router-view name="leftSidebar" />+ </teleport></HideInStandaloneMode><div@@ -239,6 +253,7 @@</template><script lang="ts" setup>+import { useMounted, useWindowSize } from "@vueuse/core";import { storeToRefs } from "pinia";import { computed, reactive, ref } from "vue";import { useRouter } from "vue-router";@@ -267,6 +282,7 @@ interface LocalState {const actuatorStore = useActuatorV1Store();const subscriptionStore = useSubscriptionV1Store();const router = useRouter();+const mounted = useMounted();const state = reactive<LocalState>({showMobileOverlay: false,@@ -276,10 +292,14 @@ const state = reactive<LocalState>({const currentUserV1 = useCurrentUserV1();const mainContainerRef = ref<HTMLDivElement>();+const { width: windowWidth } = useWindowSize();++const sidebarView = computed(() => {+ return windowWidth.value >= 768 ? "DESKTOP" : "MOBILE";+});-const hasPermission = hasWorkspacePermissionV2(- currentUserV1.value,- "bb.settings.set"+const hasPermission = computed(() =>+ hasWorkspacePermissionV2(currentUserV1.value, "bb.settings.set"));const { pageMode, isDemo } = storeToRefs(actuatorStore);@@ -336,7 +356,7 @@ const currentPlan = computed((): string => {case PlanType.ENTERPRISE:return "subscription.plan.enterprise.title";default:- if (hasPermission) {+ if (hasPermission.value) {return "subscription.plan.try";}return "subscription.plan.free.title";diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.tsindex 2954b472a0..455bea467f 100644--- a/frontend/src/store/modules/user.ts+++ b/frontend/src/store/modules/user.ts@@ -14,10 +14,18 @@ import type { UpdateUserRequest, User } from "@/types/proto/v1/auth_service";import { UserType } from "@/types/proto/v1/auth_service";import { State } from "@/types/proto/v1/common";import { userNamePrefix, getUserEmailFromIdentifier } from "./v1/common";+import { usePermissionStore } from "./v1/permission";export const useUserStore = defineStore("user", () => {const userMapByName = ref<Map<string, User>>(new Map());+ const setUser = (user: User) => {+ userMapByName.value.set(user.name, user);++ // invalid permission cache+ usePermissionStore().invalidCacheByUser(user);+ };+const userList = computed(() => {return orderBy(Array.from(userMapByName.value.values()),@@ -59,7 +67,7 @@ export const useUserStore = defineStore("user", () => {showDeleted: true,});for (const user of users) {- userMapByName.value.set(user.name, user);+ setUser(user);}return users;};@@ -72,14 +80,14 @@ export const useUserStore = defineStore("user", () => {silent,});- userMapByName.value.set(user.name, user);+ setUser(user);return user;};const createUser = async (user: User) => {const createdUser = await authServiceClient.createUser({user,});- userMapByName.value.set(createdUser.name, createdUser);+ setUser(createdUser);return createdUser;};const updateUser = async (updateUserRequest: UpdateUserRequest) => {@@ -89,7 +97,7 @@ export const useUserStore = defineStore("user", () => {throw new Error(`user with name ${name} not found`);}const user = await authServiceClient.updateUser(updateUserRequest);- userMapByName.value.set(user.name, user);+ setUser(user);return user;};const getOrFetchUserByName = async (name: string, silent = false) => {@@ -98,7 +106,7 @@ export const useUserStore = defineStore("user", () => {return cachedData;}const user = await fetchUser(name, silent);- userMapByName.value.set(user.name, user);+ setUser(user);return user;};const getUserByName = (name: string) => {@@ -132,7 +140,7 @@ export const useUserStore = defineStore("user", () => {const restoredUser = await authServiceClient.undeleteUser({name: user.name,});- userMapByName.value.set(restoredUser.name, restoredUser);+ setUser(restoredUser);return restoredUser;};diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.tsindex 1fc15f2806..0af6b1090d 100644--- a/frontend/src/store/modules/v1/index.ts+++ b/frontend/src/store/modules/v1/index.ts@@ -25,3 +25,4 @@ export * from "./changelist";export * from "./issueComment";export * from "./auditLog";export * from "./userGroup";+export * from "./permission";diff --git a/frontend/src/store/modules/v1/permission.ts b/frontend/src/store/modules/v1/permission.tsnew file mode 100644index 0000000000..f545b9d3f0--- /dev/null+++ b/frontend/src/store/modules/v1/permission.ts@@ -0,0 +1,154 @@+import { uniq } from "lodash-es";+import { defineStore } from "pinia";+import { shallowReactive } from "vue";+import {+ ALL_USERS_USER_EMAIL,+ getUserEmailInBinding,+ groupBindingPrefix,+ PRESET_WORKSPACE_ROLES,+ type ComposedProject,+ type ProjectPermission,+ type WorkspacePermission,+} from "@/types";+import type { User } from "@/types/proto/v1/auth_service";+import { isBindingPolicyExpired } from "@/utils";+import { useRoleStore } from "../role";+import { userNamePrefix } from "./common";+import { useUserGroupStore } from "./userGroup";++export const usePermissionStore = defineStore("permission", () => {+ const projectRoleListCache = shallowReactive(new Map<string, string[]>());+ const projectPermissionsCache = shallowReactive(+ new Map<string, Set<ProjectPermission>>()+ );+ const workspaceLevelPermissionsMapByUserName = shallowReactive(+ new Map<string, Set<WorkspacePermission | ProjectPermission>>()+ );+ const roleStore = useRoleStore();++ const workspaceLevelPermissionsByUser = (+ user: User+ ): Set<WorkspacePermission | ProjectPermission> => {+ const cached = workspaceLevelPermissionsMapByUserName.get(user.name);+ if (cached) {+ return cached;+ }+ const roleStore = useRoleStore();+ const permissions = new Set(+ user.roles+ .map((role) => roleStore.getRoleByName(role))+ .flatMap(+ (role) =>+ (role ? role.permissions : []) as (+ | WorkspacePermission+ | ProjectPermission+ )[]+ )+ );+ workspaceLevelPermissionsMapByUserName.set(user.name, permissions);+ return permissions;+ };++ const roleListInProjectV1 = (project: ComposedProject, user: User) => {+ const key = `${user.name}@@${project.name}`;+ const cached = projectRoleListCache.get(key);+ if (cached) {+ return cached;+ }++ const groupStore = useUserGroupStore();+ const userInBinding = getUserEmailInBinding(user.email);++ const workspaceLevelProjectRoles = user.roles.filter(+ (role) => !PRESET_WORKSPACE_ROLES.includes(role)+ );++ const { iamPolicy } = project;+ const projectBindingRoles = iamPolicy.bindings+ .filter((binding) => {+ if (isBindingPolicyExpired(binding)) {+ return false;+ }+ for (const member of binding.members) {+ if (member === ALL_USERS_USER_EMAIL) {+ return true;+ }+ if (member === userInBinding) {+ return true;+ }++ if (member.startsWith(groupBindingPrefix)) {+ const group = groupStore.getGroupByIdentifier(member);+ if (!group) {+ continue;+ }++ return group.members.some(+ (m) => m.member === `${userNamePrefix}${user.email}`+ );+ }+ }+ return false;+ })+ .map((binding) => binding.role);++ const result = uniq([+ ...projectBindingRoles,+ ...workspaceLevelProjectRoles,+ ]);+ projectRoleListCache.set(key, result);+ return result;+ };++ const permissionsInProjectV1 = (project: ComposedProject, user: User) => {+ const key = `${user.name}@@${project.name}`;+ const cached = projectPermissionsCache.get(key);+ if (cached) {+ return cached;+ }++ const roles = roleListInProjectV1(project, user);+ const permissions = new Set(+ roles+ .map((role) => roleStore.getRoleByName(role))+ .flatMap(+ (role) => (role ? role.permissions : []) as ProjectPermission[]+ )+ );+ projectPermissionsCache.set(key, permissions);+ return permissions;+ };++ const invalidCacheByProject = (project: string) => {+ const roleListKeys = Array.from(projectRoleListCache.keys()).filter((key) =>+ key.endsWith(`@@${project}`)+ );+ roleListKeys.forEach((key) => projectRoleListCache.delete(key));++ const permissionsKeys = Array.from(projectPermissionsCache.keys()).filter(+ (key) => key.endsWith(`@@${project}`)+ );+ permissionsKeys.forEach((key) => projectPermissionsCache.delete(key));+ };+ const invalidCacheByUser = (user: User) => {+ workspaceLevelPermissionsMapByUserName.delete(user.name);++ const roleListKeys = Array.from(projectRoleListCache.keys()).filter((key) =>+ key.startsWith(`${user.name}@@`)+ );+ roleListKeys.forEach((key) => projectRoleListCache.delete(key));++ const permissionsKeys = Array.from(projectPermissionsCache.keys()).filter(+ (key) => key.startsWith(`${user.name}@@`)+ );+ permissionsKeys.forEach((key) => projectPermissionsCache.delete(key));+ };++ return {+ workspaceLevelPermissionsByUser,+ roleListInProjectV1,+ permissionsInProjectV1,+ invalidCacheByProject,+ invalidCacheByUser,+ };+});diff --git a/frontend/src/store/modules/v1/projectIamPolicy.ts b/frontend/src/store/modules/v1/projectIamPolicy.tsindex e258ac3448..a166025dc4 100644--- a/frontend/src/store/modules/v1/projectIamPolicy.ts+++ b/frontend/src/store/modules/v1/projectIamPolicy.ts@@ -14,6 +14,7 @@ import {import { getUserEmailListInBinding, memberListInProjectV1 } from "@/utils";import { convertFromExpr } from "@/utils/issue/cel";import { useCurrentUserV1 } from "../auth";+import { usePermissionStore } from "./permission";import { useProjectV1Store } from "./project";export const useProjectIamPolicyStore = defineStore(@@ -71,6 +72,8 @@ export const useProjectIamPolicyStore = defineStore(policy,});policyMap.value.set(project, updated);++ usePermissionStore().invalidCacheByProject(project);};const getProjectIamPolicy = (project: string) => {@@ -157,13 +160,17 @@ export const useCurrentUserIamPolicy = () => {return true;}+ const project = projectStore.getProjectByName(projectName);+ if (!project) {+ return false;+ }const policy = iamPolicyStore.policyMap.get(projectName);if (!policy) {return false;}return (- isOwnerOfProjectV1(policy, currentUser.value) ||- isDeveloperOfProjectV1(policy, currentUser.value)+ isOwnerOfProjectV1(project, currentUser.value) ||+ isDeveloperOfProjectV1(project, currentUser.value));};@@ -176,9 +183,13 @@ export const useCurrentUserIamPolicy = () => {if (!policy) {return false;}+ const project = projectStore.getProjectByName(projectName);+ if (!project) {+ return false;+ }return (isProjectOwnerOrDeveloper(projectName) ||- isViewerOfProjectV1(policy, currentUser.value)+ isViewerOfProjectV1(project, currentUser.value));};diff --git a/frontend/src/utils/iam/permission.ts b/frontend/src/utils/iam/permission.tsindex 11d767c002..da16486a33 100644--- a/frontend/src/utils/iam/permission.ts+++ b/frontend/src/utils/iam/permission.ts@@ -1,21 +1,18 @@-import { useProjectV1List, useRoleStore } from "@/store";+import { usePermissionStore, useProjectV1List } from "@/store";import type {ComposedProject,ProjectPermission,WorkspacePermission,} from "@/types";import type { User } from "@/types/proto/v1/auth_service";-import { roleListInProjectV1 } from "../v1/project";export const hasWorkspacePermissionV2 = (user: User,permission: WorkspacePermission): boolean => {- const roleStore = useRoleStore();- const permissions = user.roles- .map((role) => roleStore.getRoleByName(role))- .flatMap((role) => (role ? role.permissions : []));- return permissions.includes(permission);+ const permissions =+ usePermissionStore().workspaceLevelPermissionsByUser(user);+ return permissions.has(permission);};// hasProjectPermissionV2 checks if the user has the given permission on the project.@@ -24,6 +21,8 @@ export const hasProjectPermissionV2 = (user: User,permission: ProjectPermission): boolean => {+ const permissionStore = usePermissionStore();+// If the project is not provided, then check if the user has the given permission on any project in the workspace.if (!project) {const { projectList } = useProjectV1List();@@ -32,23 +31,17 @@ export const hasProjectPermissionV2 = ();}- const roleStore = useRoleStore();-// Check workspace-level permissions first.// For those users who have workspace-level project roles, they should have all project-level permissions.- const workspaceLevelPermissions = user.roles- .map((role) => roleStore.getRoleByName(role))- .flatMap((role) => (role ? role.permissions : []));- if (workspaceLevelPermissions.includes(permission)) {+ const workspaceLevelPermissions =+ permissionStore.workspaceLevelPermissionsByUser(user);+ if (workspaceLevelPermissions.has(permission)) {return true;}// Check project-level permissions.- const roles = roleListInProjectV1(project.iamPolicy, user);- const permissions = roles- .map((role) => roleStore.getRoleByName(role))- .flatMap((role) => (role ? role.permissions : []));- return permissions.includes(permission);+ const permissions = permissionStore.permissionsInProjectV1(project, user);+ return permissions.has(permission);};// hasWorkspaceLevelProjectPermission checks if the user has the given permission on workspace-level-assigned project roles@@ -56,15 +49,9 @@ export const hasWorkspaceLevelProjectPermission = (user: User,permission: ProjectPermission): boolean => {- const roleStore = useRoleStore();- const workspaceLevelRoles = user.roles.map((roleName) =>- roleStore.getRoleByName(roleName)- );- // For those users who have workspace-level project roles, they should have all project-level permissions.- const workspaceLevelPermissions = workspaceLevelRoles.flatMap((role) =>- role ? role.permissions : []- );- return workspaceLevelPermissions.includes(permission);+ const permissions =+ usePermissionStore().workspaceLevelPermissionsByUser(user);+ return permissions.has(permission);};// hasWorkspaceLevelProjectPermission checks if the user has the given permission on ANY project in the workspace.diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.tsindex 0e381303bb..987241704c 100644--- a/frontend/src/utils/v1/database.ts+++ b/frontend/src/utils/v1/database.ts@@ -96,8 +96,8 @@ export const isDatabaseV1Alterable = (// If user is owner or developer of its projects, we will show the database in the UI.if (- isOwnerOfProjectV1(database.projectEntity.iamPolicy, user) ||- isDeveloperOfProjectV1(database.projectEntity.iamPolicy, user)+ isOwnerOfProjectV1(database.projectEntity, user) ||+ isDeveloperOfProjectV1(database.projectEntity, user)) {return true;}diff --git a/frontend/src/utils/v1/project.ts b/frontend/src/utils/v1/project.tsindex 5e8e50a9f5..eea5a2c2c2 100644--- a/frontend/src/utils/v1/project.ts+++ b/frontend/src/utils/v1/project.ts@@ -1,14 +1,14 @@import { orderBy, uniq } from "lodash-es";import { extractUserEmail, useUserStore, useUserGroupStore } from "@/store";-import { userNamePrefix } from "@/store/modules/v1/common";+import { usePermissionStore } from "@/store/modules/v1/permission";import {ALL_USERS_USER_EMAIL,DEFAULT_PROJECT_V1_NAME,UNKNOWN_ID,PresetRoleType,groupBindingPrefix,- getUserEmailInBinding,PRESET_WORKSPACE_ROLES,+ type ComposedProject,} from "@/types";import { User } from "@/types/proto/v1/auth_service";import { State } from "@/types/proto/v1/common";@@ -35,65 +35,29 @@ export const extractProjectResourceName = (name: string) => {return matches?.[1] ?? "";};-export const roleListInProjectV1 = (iamPolicy: IamPolicy, user: User) => {- const groupStore = useUserGroupStore();- const userInBinding = getUserEmailInBinding(user.email);-- const workspaceLevelProjectRoles = user.roles.filter(- (role) => !PRESET_WORKSPACE_ROLES.includes(role)- );-- const projectBindingRoles = iamPolicy.bindings- .filter((binding) => {- if (isBindingPolicyExpired(binding)) {- return false;- }- for (const member of binding.members) {- if (member === ALL_USERS_USER_EMAIL) {- return true;- }- if (member === userInBinding) {- return true;- }-- if (member.startsWith(groupBindingPrefix)) {- const group = groupStore.getGroupByIdentifier(member);- if (!group) {- continue;- }-- return group.members.some(- (m) => m.member === `${userNamePrefix}${user.email}`- );- }- }- return false;- })- .map((binding) => binding.role);-- return uniq([...projectBindingRoles, ...workspaceLevelProjectRoles]);-};--export const isMemberOfProjectV1 = (iamPolicy: IamPolicy, user: User) => {- return roleListInProjectV1(iamPolicy, user).length > 0;+export const isMemberOfProjectV1 = (project: ComposedProject, user: User) => {+ return usePermissionStore().roleListInProjectV1(project, user).length > 0;};-export const isOwnerOfProjectV1 = (iamPolicy: IamPolicy, user: User) => {- return roleListInProjectV1(iamPolicy, user).includes(- PresetRoleType.PROJECT_OWNER- );+export const isOwnerOfProjectV1 = (project: ComposedProject, user: User) => {+ return usePermissionStore()+ .roleListInProjectV1(project, user)+ .includes(PresetRoleType.PROJECT_OWNER);};-export const isDeveloperOfProjectV1 = (iamPolicy: IamPolicy, user: User) => {- return roleListInProjectV1(iamPolicy, user).includes(- PresetRoleType.PROJECT_DEVELOPER- );+export const isDeveloperOfProjectV1 = (+ project: ComposedProject,+ user: User+) => {+ return usePermissionStore()+ .roleListInProjectV1(project, user)+ .includes(PresetRoleType.PROJECT_DEVELOPER);};-export const isViewerOfProjectV1 = (iamPolicy: IamPolicy, user: User) => {- return roleListInProjectV1(iamPolicy, user).includes(- PresetRoleType.PROJECT_VIEWER- );+export const isViewerOfProjectV1 = (project: ComposedProject, user: User) => {+ return usePermissionStore()+ .roleListInProjectV1(project, user)+ .includes(PresetRoleType.PROJECT_VIEWER);};export const getUserEmailListInBinding = (binding: Binding): string[] => {diff --git a/frontend/src/utils/v1/worksheet.ts b/frontend/src/utils/v1/worksheet.tsindex 433e65be2e..f8112ccdb6 100644--- a/frontend/src/utils/v1/worksheet.ts+++ b/frontend/src/utils/v1/worksheet.ts@@ -36,7 +36,7 @@ export const isWorksheetReadableV1 = (sheet: Worksheet) => {case Worksheet_Visibility.VISIBILITY_PROJECT_READ:case Worksheet_Visibility.VISIBILITY_PROJECT_WRITE: {const projectV1 = useProjectV1Store().getProjectByName(sheet.project);- return isMemberOfProjectV1(projectV1.iamPolicy, currentUserV1.value);+ return isMemberOfProjectV1(projectV1, currentUserV1.value);}}return false;@@ -65,9 +65,9 @@ export const isWorksheetWritableV1 = (sheet: Worksheet) => {case Worksheet_Visibility.VISIBILITY_PRIVATE:return false;case Worksheet_Visibility.VISIBILITY_PROJECT_WRITE:- return isMemberOfProjectV1(projectV1.iamPolicy, currentUserV1.value);+ return isMemberOfProjectV1(projectV1, currentUserV1.value);case Worksheet_Visibility.VISIBILITY_PROJECT_READ:- return isOwnerOfProjectV1(projectV1.iamPolicy, currentUserV1.value);+ return isOwnerOfProjectV1(projectV1, currentUserV1.value);}return false;diff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vueindex c7d55c935d..e0a8bd7aba 100644--- a/frontend/src/views/DashboardSidebar.vue+++ b/frontend/src/views/DashboardSidebar.vue@@ -349,6 +349,6 @@ const navigationKbarActions = computed((): Action[] => {});useRegisterActions(navigationKbarActions);-useProjectActions();-useGlobalDatabaseActions();+useProjectActions(10);+useGlobalDatabaseActions(10);</script>