Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(frontend): workspace slow query settings (#5419)

Liu Ji351e4f5ffd3f
diff --git a/backend/legacyapi/plan.go b/backend/legacyapi/plan.go
index 17aee12092..799ccff78c 100644
--- a/backend/legacyapi/plan.go
+++ b/backend/legacyapi/plan.go
@@ -156,6 +156,8 @@ const (
// FeatureCustomApproval enables custom risk level definition and custom
// approval chain definition.
FeatureCustomApproval FeatureType = "bb.feature.custom-approval"
+ // FeatureSlowQuery enables slow query logging and analyzing.
+ FeatureSlowQuery FeatureType = "bb.feature.slow-query"
// FeaturePluginOpenAI enables AI features powered by OpenAI.
FeaturePluginOpenAI FeatureType = "bb.feature.plugin.openai"
@@ -222,6 +224,8 @@ func (e FeatureType) Name() string {
return "Access Control"
case FeatureCustomApproval:
return "Custom Approval"
+ case FeatureSlowQuery:
+ return "Slow Query"
// Plugins
case FeaturePluginOpenAI:
return "OpenAI"
@@ -281,6 +285,7 @@ var FeatureMatrix = map[FeatureType][3]bool{
FeatureSensitiveData: {false, false, true},
FeatureAccessControl: {false, false, true},
FeatureCustomApproval: {false, false, true},
+ FeatureSlowQuery: {false, false, true},
// Plugins
FeaturePluginOpenAI: {false, false, true},
}
diff --git a/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue
new file mode 100644
index 0000000000..2996c5b162
--- /dev/null
+++ b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue
@@ -0,0 +1,136 @@
+<template>
+ <div class="space-y-4 pb-4">
+ <div>
+ <EnvironmentTabFilter
+ :environment="state.filter.environment?.id ?? UNKNOWN_ID"
+ :include-all="true"
+ @update:environment="changeEnvironment"
+ />
+ </div>
+ <div class="w-[48rem] max-w-full">
+ <SlowQueryPolicyTable
+ :instance-list="state.ready ? filteredInstanceList : []"
+ :policy-list="policyList"
+ :toggle-active="toggleActive"
+ :show-placeholder="state.ready"
+ />
+ <div
+ v-if="!state.ready"
+ class="relative flex flex-col h-[8rem] items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, onMounted, reactive } from "vue";
+
+import {
+ featureToRef,
+ useEnvironmentList,
+ useInstanceStore,
+ useSlowQueryPolicyStore,
+} from "@/store";
+import {
+ Environment,
+ EnvironmentId,
+ Instance,
+ SlowQueryPolicyPayload,
+ UNKNOWN_ID,
+} from "@/types";
+import { EnvironmentTabFilter } from "@/components/v2";
+import { SlowQueryPolicyTable } from "./components";
+import { instanceSupportSlowQuery } from "@/utils";
+
+const emit = defineEmits<{
+ (event: "show-feature-modal"): void;
+}>();
+
+type LocalState = {
+ ready: boolean;
+ instanceList: Instance[];
+ filter: {
+ environment: Environment | undefined;
+ };
+};
+
+const state = reactive<LocalState>({
+ ready: false,
+ instanceList: [],
+ filter: {
+ environment: undefined,
+ },
+});
+
+const policyStore = useSlowQueryPolicyStore();
+const instanceStore = useInstanceStore();
+const environmentList = useEnvironmentList(["NORMAL"]);
+const hasSlowQueryFeature = featureToRef("bb.feature.slow-query");
+
+const policyList = computed(() => {
+ return policyStore.getPolicyListByResourceTypeAndPolicyType(
+ "instance",
+ "bb.policy.slow-query"
+ );
+});
+
+const filteredInstanceList = computed(() => {
+ const list = state.instanceList;
+ const { environment } = state.filter;
+ if (environment && environment.id !== UNKNOWN_ID) {
+ return list.filter(
+ (instance) => instance.environment.id === environment.id
+ );
+ }
+ return list;
+});
+
+const prepare = async () => {
+ try {
+ const prepareInstanceList = async () => {
+ const list = await instanceStore.fetchInstanceList(["NORMAL"]);
+ state.instanceList = list.filter(instanceSupportSlowQuery);
+ };
+ const preparePolicyList = async () => {
+ await policyStore.fetchPolicyListByResourceTypeAndPolicyType(
+ "instance",
+ "bb.policy.slow-query"
+ );
+ };
+ await Promise.all([prepareInstanceList(), preparePolicyList()]);
+ } finally {
+ state.ready = true;
+ }
+};
+
+const changeEnvironment = (id: EnvironmentId | undefined) => {
+ state.filter.environment = environmentList.value.find((env) => env.id === id);
+};
+
+const toggleActive = async (instance: Instance, active: boolean) => {
+ if (!hasSlowQueryFeature.value) {
+ emit("show-feature-modal");
+ return;
+ }
+
+ try {
+ const payload: SlowQueryPolicyPayload = {
+ active,
+ };
+ await policyStore.upsertPolicyByResourceTypeAndPolicyType(
+ "instance",
+ instance.id,
+ "bb.policy.slow-query",
+ {
+ payload,
+ }
+ );
+ } catch {
+ // nothing
+ }
+};
+
+onMounted(prepare);
+</script>
diff --git a/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue b/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue
new file mode 100644
index 0000000000..f2518b6e67
--- /dev/null
+++ b/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue
@@ -0,0 +1,79 @@
+<template>
+ <BBGrid
+ :column-list="COLUMNS"
+ :data-source="instanceList"
+ :row-clickable="false"
+ row-key="id"
+ class="border"
+ >
+ <template #item="{ item: instance }: { item: Instance }">
+ <div class="bb-grid-cell">
+ <InstanceName :instance="instance" />
+ </div>
+
+ <div class="bb-grid-cell">
+ <EnvironmentName :environment="instance.environment" />
+ </div>
+ <div class="bb-grid-cell">
+ <SpinnerSwitch
+ :value="isActive(instance)"
+ :disabled="!allowAdmin"
+ :on-toggle="(active) => toggleActive(instance, active)"
+ />
+ </div>
+ </template>
+ </BBGrid>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { type BBGridColumn, BBGrid } from "@/bbkit";
+import type { Instance, Policy, SlowQueryPolicyPayload } from "@/types";
+import { InstanceName, EnvironmentName, SpinnerSwitch } from "@/components/v2/";
+import { useCurrentUser } from "@/store";
+import { hasWorkspacePermission } from "@/utils";
+
+const props = defineProps<{
+ instanceList: Instance[];
+ policyList: Policy[];
+ toggleActive: (instance: Instance, active: boolean) => Promise<void>;
+}>();
+
+const { t } = useI18n();
+const currentUser = useCurrentUser();
+
+const COLUMNS = computed((): BBGridColumn[] => {
+ return [
+ {
+ title: t("common.instance"),
+ width: "2fr",
+ },
+ {
+ title: t("common.environment"),
+ width: "minmax(auto, 1fr)",
+ },
+ {
+ title: t("common.active"),
+ width: "minmax(auto, 6rem)",
+ },
+ ];
+});
+
+const allowAdmin = computed(() => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-slow-query",
+ currentUser.value.role
+ );
+});
+
+const isActive = (instance: Instance) => {
+ const policy = props.policyList.find((policy) => {
+ return policy.resourceId === instance.id;
+ });
+ if (!policy) return false;
+ const payload = policy.payload as SlowQueryPolicyPayload;
+ return payload.active;
+};
+</script>
diff --git a/frontend/src/components/SlowQuery/Settings/components/index.ts b/frontend/src/components/SlowQuery/Settings/components/index.ts
new file mode 100644
index 0000000000..c501e35400
--- /dev/null
+++ b/frontend/src/components/SlowQuery/Settings/components/index.ts
@@ -0,0 +1,3 @@
+import SlowQueryPolicyTable from "./SlowQueryPolicyTable.vue";
+
+export { SlowQueryPolicyTable };
diff --git a/frontend/src/components/SlowQuery/Settings/index.ts b/frontend/src/components/SlowQuery/Settings/index.ts
new file mode 100644
index 0000000000..9cb796ae50
--- /dev/null
+++ b/frontend/src/components/SlowQuery/Settings/index.ts
@@ -0,0 +1,3 @@
+import SlowQuerySettings from "./SlowQuerySettings.vue";
+
+export { SlowQuerySettings };
diff --git a/frontend/src/components/SlowQuery/index.ts b/frontend/src/components/SlowQuery/index.ts
new file mode 100644
index 0000000000..abda3bc7b5
--- /dev/null
+++ b/frontend/src/components/SlowQuery/index.ts
@@ -0,0 +1 @@
+export * from "./Settings";
diff --git a/frontend/src/components/v2/Form/SpinnerSwitch.vue b/frontend/src/components/v2/Form/SpinnerSwitch.vue
new file mode 100644
index 0000000000..deb6479e5e
--- /dev/null
+++ b/frontend/src/components/v2/Form/SpinnerSwitch.vue
@@ -0,0 +1,25 @@
+<template>
+ <NSwitch :loading="loading" @update:value="handleToggle" />
+</template>
+
+<script lang="ts" setup>
+import { ref } from "vue";
+import { NSwitch } from "naive-ui";
+
+const props = defineProps<{
+ onToggle: (on: boolean) => Promise<any>;
+}>();
+
+const loading = ref(false);
+
+const handleToggle = async (on: boolean) => {
+ if (loading.value) return;
+
+ loading.value = true;
+ try {
+ await props.onToggle(on);
+ } finally {
+ loading.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/v2/Form/index.ts b/frontend/src/components/v2/Form/index.ts
new file mode 100644
index 0000000000..6b9951c199
--- /dev/null
+++ b/frontend/src/components/v2/Form/index.ts
@@ -0,0 +1,3 @@
+import SpinnerSwitch from "./SpinnerSwitch.vue";
+
+export { SpinnerSwitch };
diff --git a/frontend/src/components/v2/Model/EnvironmentName.vue b/frontend/src/components/v2/Model/EnvironmentName.vue
new file mode 100644
index 0000000000..fe0b35152e
--- /dev/null
+++ b/frontend/src/components/v2/Model/EnvironmentName.vue
@@ -0,0 +1,44 @@
+<template>
+ <component
+ :is="link ? 'router-link' : tag"
+ v-bind="bindings"
+ class="inline-flex items-center gap-x-1"
+ >
+ <span>{{ environmentName(environment) }}</span>
+ <ProductionEnvironmentIcon
+ :environment="environment"
+ class="!text-current"
+ />
+ </component>
+</template>
+
+<script lang="ts" setup>
+import type { Environment } from "@/types";
+import { environmentName, environmentSlug } from "@/utils";
+import ProductionEnvironmentIcon from "@/components/Environment/ProductionEnvironmentIcon.vue";
+import { computed } from "vue";
+
+const props = withDefaults(
+ defineProps<{
+ environment: Environment;
+ tag?: string;
+ link?: boolean;
+ }>(),
+ {
+ tag: "span",
+ link: true,
+ }
+);
+
+const bindings = computed(() => {
+ if (props.link) {
+ return {
+ to: `/environment/${environmentSlug(props.environment)}`,
+ onClick: (e: MouseEvent) => {
+ e.stopPropagation();
+ },
+ };
+ }
+ return {};
+});
+</script>
diff --git a/frontend/src/components/v2/Model/InstanceName.vue b/frontend/src/components/v2/Model/InstanceName.vue
new file mode 100644
index 0000000000..febdc478ef
--- /dev/null
+++ b/frontend/src/components/v2/Model/InstanceName.vue
@@ -0,0 +1,42 @@
+<template>
+ <component
+ :is="link ? 'router-link' : tag"
+ :to="link && `/instance/${instance.id}`"
+ class="inline-flex items-center gap-x-1"
+ @click.stop=""
+ >
+ <InstanceEngineIcon
+ v-if="icon && iconPosition === 'prefix'"
+ :instance="instance"
+ />
+
+ <span>{{ instanceName(instance) }}</span>
+
+ <InstanceEngineIcon
+ v-if="icon && iconPosition === 'suffix'"
+ :instance="instance"
+ />
+ </component>
+</template>
+
+<script lang="ts" setup>
+import type { Instance } from "@/types";
+import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";
+import { instanceName } from "@/utils";
+
+withDefaults(
+ defineProps<{
+ instance: Instance;
+ tag?: string;
+ link?: boolean;
+ icon?: boolean;
+ iconPosition?: "prefix" | "suffix";
+ }>(),
+ {
+ tag: "span",
+ link: true,
+ icon: true,
+ iconPosition: "prefix",
+ }
+);
+</script>
diff --git a/frontend/src/components/v2/Model/index.ts b/frontend/src/components/v2/Model/index.ts
new file mode 100644
index 0000000000..e7ed32b35f
--- /dev/null
+++ b/frontend/src/components/v2/Model/index.ts
@@ -0,0 +1,4 @@
+import InstanceName from "./InstanceName.vue";
+import EnvironmentName from "./EnvironmentName.vue";
+
+export { InstanceName, EnvironmentName };
diff --git a/frontend/src/components/v2/TabFilter/EnvironmentTabFilter.vue b/frontend/src/components/v2/TabFilter/EnvironmentTabFilter.vue
new file mode 100644
index 0000000000..386ccd34e0
--- /dev/null
+++ b/frontend/src/components/v2/TabFilter/EnvironmentTabFilter.vue
@@ -0,0 +1,61 @@
+<template>
+ <TabFilter
+ :value="environment"
+ :items="items"
+ @update:value="$emit('update:environment', $event)"
+ >
+ <template #label="{ item }">
+ <template v-if="item.value === UNKNOWN_ID">{{ item.label }}</template>
+ <EnvironmentName v-else :environment="item.environment" :link="false" />
+ </template>
+ </TabFilter>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { useEnvironmentList } from "@/store";
+import { Environment, EnvironmentId, UNKNOWN_ID, unknown } from "@/types";
+import { TabFilterItem } from "./types";
+import { EnvironmentName } from "../Model";
+
+interface EnvironmentTabFilterItem extends TabFilterItem<EnvironmentId> {
+ environment: Environment;
+}
+
+const props = withDefaults(
+ defineProps<{
+ environment: EnvironmentId; // UNKNOWN_ID(-1) to "ALL"
+ includeAll?: boolean;
+ }>(),
+ {
+ includeAll: false,
+ }
+);
+
+defineEmits<{
+ (event: "update:environment", id: EnvironmentId): void;
+}>();
+
+const { t } = useI18n();
+const environmentList = useEnvironmentList(["NORMAL"]);
+
+const items = computed(() => {
+ const environmentItems = environmentList.value.map<EnvironmentTabFilterItem>(
+ (env) => ({
+ value: env.id,
+ label: env.name,
+ environment: env,
+ })
+ );
+ if (props.environment === UNKNOWN_ID || props.includeAll) {
+ environmentItems.unshift({
+ value: UNKNOWN_ID,
+ label: t("common.all"),
+ environment: unknown("ENVIRONMENT"),
+ });
+ }
+ return environmentItems;
+});
+</script>
diff --git a/frontend/src/components/v2/TabFilter/TabFilter.vue b/frontend/src/components/v2/TabFilter/TabFilter.vue
new file mode 100644
index 0000000000..7ac1961e9a
--- /dev/null
+++ b/frontend/src/components/v2/TabFilter/TabFilter.vue
@@ -0,0 +1,69 @@
+<template>
+ <div>
+ <div v-if="responsive" class="block sm:hidden">
+ <label for="tabs" class="sr-only">Select a tab</label>
+ <NSelect
+ :disabled="disabled"
+ :options="items"
+ :value="value"
+ @update:value="$emit('update:value', $event)"
+ />
+ </div>
+ <div
+ class="gap-x-4 w-full overflow-x-auto hide-scrollbar whitespace-nowrap py-[3px]"
+ aria-label="Tabs"
+ :class="responsive ? 'hidden sm:flex' : 'flex'"
+ >
+ <button
+ v-for="item in items"
+ :key="item.value"
+ :disabled="disabled"
+ class="rounded-md text-sm px-3 py-1 flex items-center disabled:cursor-not-allowed disabled:pointer-events-none transition-colors duration-150"
+ :class="[
+ value === item.value
+ ? 'bg-gray-200 text-gray-800 disabled:bg-gray-100'
+ : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100',
+ ]"
+ @click.prevent="update(item.value)"
+ >
+ <slot name="label" :item="item">
+ {{ item.label }}
+ </slot>
+ </button>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NSelect } from "naive-ui";
+import { TabFilterItem } from "./types";
+
+type ValueType = string | number; // Use generic typed component in the future
+
+const props = withDefaults(
+ defineProps<{
+ value: ValueType;
+ items: TabFilterItem<ValueType>[];
+ disabled?: boolean;
+ responsive?: boolean;
+ }>(),
+ {
+ disabled: false,
+ responsive: true,
+ }
+);
+
+const emit = defineEmits<{
+ (
+ event: "update:value",
+ value: ValueType,
+ item: TabFilterItem<ValueType>
+ ): void;
+}>();
+
+const update = (value: ValueType) => {
+ const item = props.items.find((item) => item.value === value);
+ if (!item) return;
+ emit("update:value", value, item);
+};
+</script>
diff --git a/frontend/src/components/v2/TabFilter/index.ts b/frontend/src/components/v2/TabFilter/index.ts
new file mode 100644
index 0000000000..3466837f47
--- /dev/null
+++ b/frontend/src/components/v2/TabFilter/index.ts
@@ -0,0 +1,5 @@
+import TabFilter from "./TabFilter.vue";
+import EnvironmentTabFilter from "./EnvironmentTabFilter.vue";
+
+export * from "./types";
+export { TabFilter, EnvironmentTabFilter };
diff --git a/frontend/src/components/v2/TabFilter/types.ts b/frontend/src/components/v2/TabFilter/types.ts
new file mode 100644
index 0000000000..58c3cde307
--- /dev/null
+++ b/frontend/src/components/v2/TabFilter/types.ts
@@ -0,0 +1,4 @@
+export type TabFilterItem<T extends string | number> = {
+ label: string;
+ value: T;
+};
diff --git a/frontend/src/components/v2/index.ts b/frontend/src/components/v2/index.ts
new file mode 100644
index 0000000000..66209c1fff
--- /dev/null
+++ b/frontend/src/components/v2/index.ts
@@ -0,0 +1,3 @@
+export * from "./TabFilter";
+export * from "./Model";
+export * from "./Form";
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index e79c85a363..19066f0cbe 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -234,7 +234,8 @@
"deleted": "Deleted",
"will-override-current-data": "Will override current data.",
"rollout": "Roll out",
- "uploading": "Uploading"
+ "uploading": "Uploading",
+ "active": "Active"
},
"error-page": {
"go-back-home": "Go back home"
@@ -1764,6 +1765,10 @@
"title": "Custom approval",
"desc": "Configure security risk level and approval flow for different tasks."
},
+ "bb-feature-slow-query": {
+ "title": "Slow query",
+ "desc": "Logging and analyzing slow SQL queries."
+ },
"bb-feature-vcs-schema-write-back": {
"title": "Schema write-back",
"desc": "After a successful schema change, schema write-back enables Bytebase to write back the latest full schema snapshot to your VCS repository."
@@ -2229,5 +2234,24 @@
"generating-approval-flow": "Generating approval flow",
"approved-issue": "approved issue"
}
+ },
+ "slow-query": {
+ "self": "Slow query",
+ "slow-queries": "Slow queries",
+ "last-query-time": "Last query time",
+ "database-name": "Database name",
+ "sql-statement": "SQL statement",
+ "total-query-count": "Total query count",
+ "query-time-95-percent": "Query time (95%)",
+ "query-time-avg": "Query time avg.",
+ "rows-examined-95-percent": "Rows examined (95%)",
+ "rows-sent-95-percent": "Rows sent (95%)",
+ "rows-examined-avg": "Rows examined avg.",
+ "rows-sent-avg": "Rows sent avg.",
+ "query-start-time": "Query start time",
+ "rows-examined": "Rows examined",
+ "rows-sent": "Rows sent",
+ "lock-time": "Lock time",
+ "query-time": "Query time"
}
}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 42169008fd..8ef7b6dcbf 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -232,7 +232,8 @@
"deleted": "已删除",
"will-override-current-data": "将会覆盖当前数据。",
"rollout": "发布",
- "uploading": "上传中"
+ "uploading": "上传中",
+ "active": "开启"
},
"error-page": {
"go-back-home": "回到主页"
@@ -1763,6 +1764,10 @@
"title": "自定义审批",
"desc": "为不同的任务配置安全风险等级和自定义审批流。"
},
+ "bb-feature-slow-query": {
+ "title": "慢查询",
+ "desc": "记录与分析慢速的 SQL 查询。"
+ },
"bb-feature-vcs-schema-write-back": {
"title": "Schema 回写",
"desc": "当一个 Schema 变更完成后,可以将最新的 Schema 快照回写到 VCS。"
@@ -2226,5 +2231,24 @@
"generating-approval-flow": "正在生成审批流",
"approved-issue": "批准工单"
}
+ },
+ "slow-query": {
+ "self": "慢查询",
+ "slow-queries": "慢查询",
+ "last-query-time": "最近执行时间",
+ "database-name": "数据库名",
+ "sql-statement": "SQL 语句",
+ "total-query-count": "总执行次数",
+ "query-time-95-percent": "执行时长(95%)",
+ "query-time-avg": "平均执行时长",
+ "rows-examined-95-percent": "扫描行数(95%)",
+ "rows-sent-95-percent": "返回行数(95%)",
+ "rows-examined-avg": "平均扫描行数",
+ "rows-sent-avg": "平均返回行数",
+ "query-start-time": "执行开始时间",
+ "rows-examined": "解析行数",
+ "rows-sent": "返回行数",
+ "lock-time": "持有锁时长",
+ "query-time": "执行时长"
}
}
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 7c90fd0765..2e891259ef 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -6,6 +6,7 @@ import {
RouteRecordRaw,
} from "vue-router";
import { useTitle } from "@vueuse/core";
+import { startCase } from "lodash-es";
import BodyLayout from "../layouts/BodyLayout.vue";
import DashboardLayout from "../layouts/DashboardLayout.vue";
@@ -426,6 +427,14 @@ const routes: Array<RouteRecordRaw> = [
import("../views/SettingWorkspaceCustomApproval.vue"),
props: true,
},
+ {
+ path: "slow-query",
+ name: "setting.workspace.slow-query",
+ meta: { title: () => startCase(t("slow-query.self")) },
+ component: () =>
+ import("../views/SettingWorkspaceSlowQuery.vue"),
+ props: true,
+ },
{
path: "gitops",
name: "setting.workspace.gitops",
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index 4bfa2408ba..c926bc1abe 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -22,6 +22,7 @@ export * from "./notification";
export * from "./oauth";
export * from "./pipeline";
export * from "./policy";
+export * from "./slowQueryPolicy";
export * from "./principal";
export * from "./project";
export * from "./projectWebhook";
diff --git a/frontend/src/store/modules/slowQueryPolicy.ts b/frontend/src/store/modules/slowQueryPolicy.ts
new file mode 100644
index 0000000000..6957d43219
--- /dev/null
+++ b/frontend/src/store/modules/slowQueryPolicy.ts
@@ -0,0 +1,172 @@
+import { defineStore } from "pinia";
+import { ref } from "vue";
+import axios from "axios";
+import { IdType, ResourceObject, unknown } from "@/types";
+import {
+ PipelineApprovalPolicyPayload,
+ Policy,
+ PolicyResourceType,
+ PolicyType,
+ PolicyUpsert,
+ SensitiveDataPolicyPayload,
+} from "@/types/policy";
+
+function convert(
+ resourceType: PolicyResourceType,
+ policy: ResourceObject,
+ includedList: ResourceObject[]
+): Policy {
+ const result: Policy = {
+ ...(policy.attributes as Omit<Policy, "id" | "environment" | "payload">),
+ id: parseInt(policy.id),
+ resourceType,
+ environment: unknown("ENVIRONMENT"),
+ payload: JSON.parse((policy.attributes.payload as string) || "{}"),
+ };
+
+ if (result.type === "bb.policy.pipeline-approval") {
+ const payload = result.payload as PipelineApprovalPolicyPayload;
+ if (!payload.assigneeGroupList) {
+ // Assign an empty array as fallback
+ payload.assigneeGroupList = [];
+ }
+ }
+ if (result.type === "bb.policy.sensitive-data") {
+ const payload = result.payload as SensitiveDataPolicyPayload;
+ if (!payload.sensitiveDataList) {
+ // The array might be null, fill it with empty array to fallback.
+ payload.sensitiveDataList = [];
+ }
+ }
+
+ return result;
+}
+
+export const useSlowQueryPolicyStore = defineStore("slow-query-policy", () => {
+ const policyMapByResourceType = ref(
+ new Map<PolicyResourceType, Map<PolicyType, Policy[]>>()
+ );
+
+ const getPolicyListByResourceTypeAndPolicyType = (
+ resourceType: PolicyResourceType,
+ policyType: PolicyType
+ ) => {
+ return (
+ policyMapByResourceType.value.get(resourceType)?.get(policyType) ?? []
+ );
+ };
+ const setPolicyListByResourceTypeAndPolicyType = (
+ resourceType: PolicyResourceType,
+ policyType: PolicyType,
+ policyList: Policy[]
+ ) => {
+ const map = policyMapByResourceType.value.get(resourceType);
+ if (map) {
+ map.set(policyType, policyList);
+ } else {
+ policyMapByResourceType.value.set(
+ resourceType,
+ new Map([[policyType, policyList]])
+ );
+ }
+ };
+ const updatePolicy = (policy: Policy) => {
+ const { resourceType, type } = policy;
+ const policyList = getPolicyListByResourceTypeAndPolicyType(
+ resourceType,
+ type
+ );
+ const index = policyList.findIndex(
+ (p) => p.resourceId === policy.resourceId
+ );
+ if (index >= 0) {
+ policyList[index] = policy;
+ } else {
+ policyList.push(policy);
+ }
+ setPolicyListByResourceTypeAndPolicyType(resourceType, type, policyList);
+ };
+ const removePolicy = (
+ resourceType: PolicyResourceType,
+ resourceId: IdType,
+ policyType: PolicyType
+ ) => {
+ const policyList = getPolicyListByResourceTypeAndPolicyType(
+ resourceType,
+ policyType
+ );
+ const index = policyList.findIndex((p) => p.resourceId === resourceId);
+ if (index >= 0) {
+ policyList.splice(index, 1);
+ setPolicyListByResourceTypeAndPolicyType(
+ resourceType,
+ policyType,
+ policyList
+ );
+ }
+ };
+
+ const fetchPolicyListByResourceTypeAndPolicyType = async (
+ resourceType: PolicyResourceType,
+ policyType: PolicyType
+ ) => {
+ const url = `/api/policy?resourceType=${resourceType}&type=${policyType}`;
+ const data: { data: ResourceObject[]; included: ResourceObject[] } = (
+ await axios.get(url)
+ ).data;
+ const policyList = data.data.map((d) =>
+ convert(resourceType, d, data.included)
+ );
+ setPolicyListByResourceTypeAndPolicyType(
+ resourceType,
+ policyType,
+ policyList
+ );
+ return policyList;
+ };
+ const upsertPolicyByResourceTypeAndPolicyType = async (
+ resourceType: PolicyResourceType,
+ resourceId: IdType,
+ policyType: PolicyType,
+ policyUpsert: PolicyUpsert
+ ) => {
+ const data = (
+ await axios.patch(
+ `/api/policy/${resourceType}/${resourceId}?type=${policyType}`,
+ {
+ data: {
+ type: "policyUpsert",
+ attributes: {
+ rowStatus: policyUpsert.rowStatus,
+ payload: policyUpsert.payload
+ ? JSON.stringify(policyUpsert.payload)
+ : undefined,
+ },
+ },
+ }
+ )
+ ).data;
+ const policy = convert(resourceType, data.data, data.included);
+
+ updatePolicy(policy);
+
+ return policy;
+ };
+ const deletePolicyByResourceTypeAndPolicyType = async (
+ resourceType: PolicyResourceType,
+ resourceId: IdType,
+ policyType: PolicyType
+ ) => {
+ await axios.delete(
+ `/api/policy/${resourceType}/${resourceId}?type=${policyType}`
+ );
+ removePolicy(resourceType, resourceId, policyType);
+ };
+
+ return {
+ getPolicyListByResourceTypeAndPolicyType,
+ fetchPolicyListByResourceTypeAndPolicyType,
+ upsertPolicyByResourceTypeAndPolicyType,
+ deletePolicyByResourceTypeAndPolicyType,
+ };
+});
diff --git a/frontend/src/types/plan.ts b/frontend/src/types/plan.ts
index df6b970cde..2b5d4d6903 100644
--- a/frontend/src/types/plan.ts
+++ b/frontend/src/types/plan.ts
@@ -37,6 +37,7 @@ export type FeatureType =
| "bb.feature.sensitive-data"
| "bb.feature.access-control"
| "bb.feature.custom-approval"
+ | "bb.feature.slow-query"
// Plugins
| "bb.feature.plugin.openai";
diff --git a/frontend/src/types/policy.ts b/frontend/src/types/policy.ts
index a971f2e332..31b2d3b2d9 100644
--- a/frontend/src/types/policy.ts
+++ b/frontend/src/types/policy.ts
@@ -14,7 +14,8 @@ export type PolicyType =
| "bb.policy.sql-review"
| "bb.policy.environment-tier"
| "bb.policy.sensitive-data"
- | "bb.policy.access-control";
+ | "bb.policy.access-control"
+ | "bb.policy.slow-query";
export type PipelineApprovalPolicyValue =
| "MANUAL_APPROVAL_NEVER"
@@ -92,13 +93,18 @@ export type AccessControlPolicyPayload = {
disallowRuleList: AccessControlRule[];
};
+export type SlowQueryPolicyPayload = {
+ active: boolean;
+};
+
export type PolicyPayload =
| PipelineApprovalPolicyPayload
| BackupPlanPolicyPayload
| SQLReviewPolicyPayload
| EnvironmentTierPolicyPayload
| SensitiveDataPolicyPayload
- | AccessControlPolicyPayload;
+ | AccessControlPolicyPayload
+ | SlowQueryPolicyPayload;
export type PolicyResourceType =
| ""
diff --git a/frontend/src/utils/instance.ts b/frontend/src/utils/instance.ts
index 4f8f2d5b51..dea39dd2da 100644
--- a/frontend/src/utils/instance.ts
+++ b/frontend/src/utils/instance.ts
@@ -7,7 +7,7 @@ import {
languageOfEngine,
MaybeRef,
} from "../types";
-import { isDev } from "./util";
+import { isDev, semverCompare } from "./util";
export const supportedEngineList = () => {
const engines: EngineType[] = [
@@ -132,3 +132,11 @@ export const instanceHasSSL = (
"MARIADB",
].includes(engine);
};
+
+export const instanceSupportSlowQuery = (instance: Instance) => {
+ const { engine } = instance;
+ if (engine === "MYSQL") {
+ return semverCompare(instance.engineVersion, "5.7", "gte");
+ }
+ return false;
+};
diff --git a/frontend/src/utils/role.ts b/frontend/src/utils/role.ts
index de3c1456bc..2dc9f7a9f1 100644
--- a/frontend/src/utils/role.ts
+++ b/frontend/src/utils/role.ts
@@ -21,6 +21,7 @@ export type WorkspacePermissionType =
| "bb.permission.workspace.manage-sensitive-data"
| "bb.permission.workspace.manage-access-control"
| "bb.permission.workspace.manage-custom-approval"
+ | "bb.permission.workspace.manage-slow-query"
| "bb.permission.workspace.manage-subscription"
// Can execute admininstrive queries such as "SHOW PROCESSLIST"
| "bb.permission.workspace.admin-sql-editor"
@@ -50,6 +51,7 @@ export const WORKSPACE_PERMISSION_MATRIX: Map<
["bb.permission.workspace.manage-sensitive-data", [false, true, true]],
["bb.permission.workspace.manage-access-control", [false, true, true]],
["bb.permission.workspace.manage-custom-approval", [false, true, true]],
+ ["bb.permission.workspace.manage-slow-query", [false, true, true]],
["bb.permission.workspace.manage-subscription", [false, false, true]],
["bb.permission.workspace.admin-sql-editor", [false, true, true]],
["bb.permission.workspace.audit-log", [false, true, true]],
diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vue
index 3757653bfc..0ac69262e0 100644
--- a/frontend/src/views/SettingSidebar.vue
+++ b/frontend/src/views/SettingSidebar.vue
@@ -83,6 +83,11 @@
class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
>{{ $t("sql-review.title") }}</router-link
>
+ <router-link
+ to="/setting/slow-query"
+ class="outline-item group w-full flex items-center pl-11 pr-2 py-2 capitalize"
+ >{{ $t("slow-query.self") }}</router-link
+ >
<router-link
to="/setting/risk-center"
class="outline-item group w-full flex items-center truncate pl-11 pr-2 py-2"
diff --git a/frontend/src/views/SettingWorkspaceSlowQuery.vue b/frontend/src/views/SettingWorkspaceSlowQuery.vue
new file mode 100644
index 0000000000..796fb6618d
--- /dev/null
+++ b/frontend/src/views/SettingWorkspaceSlowQuery.vue
@@ -0,0 +1,28 @@
+<template>
+ <div class="w-full mt-4 space-y-4 text-sm">
+ <FeatureAttention
+ v-if="!hasSlowQueryFeature"
+ feature="bb.feature.slow-query"
+ :description="$t('subscription.features.bb-feature-slow-query.desc')"
+ />
+
+ <SlowQuerySettings @show-feature-modal="showFeatureModal = true" />
+ </div>
+
+ <FeatureModal
+ v-if="showFeatureModal"
+ feature="bb.feature.slow-query"
+ @cancel="showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { ref } from "vue";
+
+import { featureToRef } from "@/store";
+import { SlowQuerySettings } from "@/components/SlowQuery";
+
+const showFeatureModal = ref(false);
+
+const hasSlowQueryFeature = featureToRef("bb.feature.slow-query");
+</script>