Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): pagination for project activities and audit logs (#3961)
ZhengX6c4df51c5702
diff --git a/frontend/src/components/AuditLog/PagedAuditLogTable.vue b/frontend/src/components/AuditLog/PagedAuditLogTable.vuenew file mode 100644index 0000000000..b4f27aef96--- /dev/null+++ b/frontend/src/components/AuditLog/PagedAuditLogTable.vue@@ -0,0 +1,183 @@+<template>+ <slot name="table" :list="state.auditLogList" :loading="state.loading" />++ <div+ v-if="state.loading"+ class="flex items-center justify-center py-2 text-gray-400 text-sm"+ >+ <BBSpin />+ </div>++ <slot+ v-if="!state.loading"+ name="more"+ :has-more="state.hasMore"+ :fetch-next-page="fetchNextPage"+ >+ <div+ v-if="!hideLoadMore && pageSize > 0 && state.hasMore"+ class="flex items-center justify-center py-2 text-gray-400 text-sm hover:bg-gray-200 cursor-pointer"+ @click="fetchNextPage"+ >+ {{ $t("common.load-more") }}+ </div>+ </slot>+</template>++<script lang="ts" setup>+import { computed, PropType, reactive, watch } from "vue";++import { useIsLoggedIn, useAuditLogStore } from "@/store";+import { ActivityFind, AuditLog } from "@/types";+import { useSessionStorage } from "@vueuse/core";+import { stringify } from "qs";++type LocalState = {+ loading: boolean;+ auditLogList: AuditLog[];+ paginationToken: string;+ hasMore: boolean;+};++/**+ * It's complex and dangerous to cache the activity list.+ * So we just memorize how many times the user clicks the "load more" button.+ * And load the first N pages in the first fetch.+ * E.g., the user clicked "load more" 4 times, then the first time will set limit+ * to `pageSize * 5`.+ */+type SessionState = {+ // How many times the user clicks the "load more" button.+ page: number;+ // Help us to check if the session is outdated.+ updatedTs: number;+};++const MAX_PAGE_SIZE = 1000;+const SESSION_LIFE = 1 * 60 * 1000; // 1 minute++const props = defineProps({+ // A unique key to identify the session state.+ sessionKey: {+ type: String,+ required: true,+ },+ activityFind: {+ type: Object as PropType<ActivityFind>,+ default: () => ({+ typePrefix: "",+ order: "DESC",+ }),+ },+ pageSize: {+ type: Number,+ default: 10,+ },+ hideLoadMore: {+ type: Boolean,+ default: false,+ },+});++const state = reactive<LocalState>({+ loading: false,+ auditLogList: [],+ paginationToken: "",+ hasMore: true,+});++const sessionState = useSessionStorage<SessionState>(+ `bb.page-audit-log-table.${props.sessionKey}`,+ {+ page: 1,+ updatedTs: 0,+ }+);++const auditLogStore = useAuditLogStore();+const isLoggedIn = useIsLoggedIn();++const limit = computed(() => {+ if (props.pageSize <= 0) return MAX_PAGE_SIZE;+ return props.pageSize;+});++const condition = computed(() => {+ const activityFind = {+ ...props.activityFind,+ limit: limit.value,+ };+ return stringify(activityFind, {+ arrayFormat: "repeat",+ });+});++const fetchData = (refresh = false) => {+ state.loading = true;++ const isFirstFetch = state.paginationToken === "";+ const expectedRowCount = isFirstFetch+ ? // Load one or more page for the first fetch to restore the session+ limit.value * sessionState.value.page+ : // Always load one page if NOT the first fetch+ limit.value;++ auditLogStore+ .fetchPagedAuditLogList({+ ...props.activityFind,+ limit: expectedRowCount,+ token: state.paginationToken,+ })+ .then(({ nextToken, auditLogList }) => {+ if (refresh) {+ state.auditLogList = auditLogList;+ } else {+ state.auditLogList.push(...auditLogList);+ }++ if (auditLogList.length < expectedRowCount) {+ state.hasMore = false;+ } else if (!isFirstFetch) {+ // If we didn't reach the end, memorize we've clicked the "load more" button.+ sessionState.value.page++;+ }++ sessionState.value.updatedTs = Date.now();+ state.paginationToken = nextToken;+ })+ .finally(() => {+ state.loading = false;+ });+};++const resetSession = () => {+ sessionState.value = {+ page: 1,+ updatedTs: 0,+ };+};++const refresh = () => {+ state.paginationToken = "";+ state.hasMore = true;+ resetSession();+ fetchData(true);+};++const fetchNextPage = () => {+ fetchData(false);+};++if (Date.now() - sessionState.value.updatedTs > SESSION_LIFE) {+ // Reset session if it's outdated.+ resetSession();+}+fetchData(true);+watch(condition, refresh);+watch(isLoggedIn, () => {+ // Reset session when logged out.+ if (!isLoggedIn.value) {+ resetSession();+ }+});+</script>diff --git a/frontend/src/components/PagedActivityTable.vue b/frontend/src/components/PagedActivityTable.vuenew file mode 100644index 0000000000..bbf7dd6549--- /dev/null+++ b/frontend/src/components/PagedActivityTable.vue@@ -0,0 +1,187 @@+<template>+ <slot+ name="table"+ :activity-list="state.activityList"+ :loading="state.loading"+ />++ <div+ v-if="state.loading"+ class="flex items-center justify-center py-2 text-gray-400 text-sm"+ >+ <BBSpin />+ </div>++ <slot+ v-if="!state.loading"+ name="more"+ :has-more="state.hasMore"+ :fetch-next-page="fetchNextPage"+ >+ <div+ v-if="!hideLoadMore && pageSize > 0 && state.hasMore"+ class="flex items-center justify-center py-2 text-gray-400 text-sm hover:bg-gray-200 cursor-pointer"+ @click="fetchNextPage"+ >+ {{ $t("common.load-more") }}+ </div>+ </slot>+</template>++<script lang="ts" setup>+import { computed, PropType, reactive, watch } from "vue";++import { useIsLoggedIn, useActivityStore } from "@/store";+import { Activity, ActivityFind } from "@/types";+import { useSessionStorage } from "@vueuse/core";+import { stringify } from "qs";++type LocalState = {+ loading: boolean;+ activityList: Activity[];+ paginationToken: string;+ hasMore: boolean;+};++/**+ * It's complex and dangerous to cache the activity list.+ * So we just memorize how many times the user clicks the "load more" button.+ * And load the first N pages in the first fetch.+ * E.g., the user clicked "load more" 4 times, then the first time will set limit+ * to `pageSize * 5`.+ */+type SessionState = {+ // How many times the user clicks the "load more" button.+ page: number;+ // Help us to check if the session is outdated.+ updatedTs: number;+};++const MAX_PAGE_SIZE = 1000;+const SESSION_LIFE = 1 * 60 * 1000; // 1 minute++const props = defineProps({+ // A unique key to identify the session state.+ sessionKey: {+ type: String,+ required: true,+ },+ activityFind: {+ type: Object as PropType<ActivityFind>,+ default: () => ({+ typePrefix: "",+ order: "DESC",+ }),+ },+ pageSize: {+ type: Number,+ default: 10,+ },+ hideLoadMore: {+ type: Boolean,+ default: false,+ },+});++const state = reactive<LocalState>({+ loading: false,+ activityList: [],+ paginationToken: "",+ hasMore: true,+});++const sessionState = useSessionStorage<SessionState>(+ `bb.page-activity-table.${props.sessionKey}`,+ {+ page: 1,+ updatedTs: 0,+ }+);++const activityStore = useActivityStore();+const isLoggedIn = useIsLoggedIn();++const limit = computed(() => {+ if (props.pageSize <= 0) return MAX_PAGE_SIZE;+ return props.pageSize;+});++const condition = computed(() => {+ const activityFind = {+ ...props.activityFind,+ limit: limit.value,+ };+ return stringify(activityFind, {+ arrayFormat: "repeat",+ });+});++const fetchData = (refresh = false) => {+ state.loading = true;++ const isFirstFetch = state.paginationToken === "";+ const expectedRowCount = isFirstFetch+ ? // Load one or more page for the first fetch to restore the session+ limit.value * sessionState.value.page+ : // Always load one page if NOT the first fetch+ limit.value;++ activityStore+ .fetchPagedActivityList({+ ...props.activityFind,+ limit: expectedRowCount,+ token: state.paginationToken,+ })+ .then(({ nextToken, activityList }) => {+ if (refresh) {+ state.activityList = activityList;+ } else {+ state.activityList.push(...activityList);+ }++ if (activityList.length < expectedRowCount) {+ state.hasMore = false;+ } else if (!isFirstFetch) {+ // If we didn't reach the end, memorize we've clicked the "load more" button.+ sessionState.value.page++;+ }++ sessionState.value.updatedTs = Date.now();+ state.paginationToken = nextToken;+ })+ .finally(() => {+ state.loading = false;+ });+};++const resetSession = () => {+ sessionState.value = {+ page: 1,+ updatedTs: 0,+ };+};++const refresh = () => {+ state.paginationToken = "";+ state.hasMore = true;+ resetSession();+ fetchData(true);+};++const fetchNextPage = () => {+ fetchData(false);+};++if (Date.now() - sessionState.value.updatedTs > SESSION_LIFE) {+ // Reset session if it's outdated.+ resetSession();+}+fetchData(true);+watch(condition, refresh);+watch(isLoggedIn, () => {+ // Reset session when logged out.+ if (!isLoggedIn.value) {+ resetSession();+ }+});+</script>diff --git a/frontend/src/components/ProjectActivityPanel.vue b/frontend/src/components/ProjectActivityPanel.vueindex 8a9c054d17..f96a2174b8 100644--- a/frontend/src/components/ProjectActivityPanel.vue+++ b/frontend/src/components/ProjectActivityPanel.vue@@ -4,51 +4,37 @@<p class="text-lg font-medium leading-7 text-main">{{ $t("common.activity") }}</p>- <ActivityTable :activity-list="state.activityList" />+ <PagedActivityTableVue+ :activity-find="{+ typePrefix: ['bb.project.', 'bb.database.'],+ container: project.id,+ order: 'DESC',+ }"+ session-key="project-activity-panel"+ :page-size="10"+ >+ <template #table="{ activityList }">+ <ActivityTable :activity-list="activityList" />+ </template>+ </PagedActivityTableVue></div></div></template><script lang="ts">-import { defineComponent, onBeforeMount, PropType, reactive } from "vue";-import { Activity, Project } from "../types";+import { defineComponent, PropType } from "vue";+import { Project } from "../types";import ActivityTable from "../components/ActivityTable.vue";-import { useActivityStore } from "@/store";--interface LocalState {- activityList: Activity[];-}+import PagedActivityTableVue from "@/components/PagedActivityTable.vue";export default defineComponent({name: "ProjectActivityPanel",- components: { ActivityTable },+ components: { ActivityTable, PagedActivityTableVue },props: {project: {required: true,type: Object as PropType<Project>,},},- setup(props) {- const state = reactive<LocalState>({- activityList: [],- });- const activityStore = useActivityStore();-- const prepareActivityList = () => {- activityStore- .fetchActivityListForProject({- projectId: props.project.id,- })- .then((list) => {- state.activityList = list;- });- };-- onBeforeMount(prepareActivityList);-- return {- state,- };- },});</script>diff --git a/frontend/src/components/ProjectOverviewPanel.vue b/frontend/src/components/ProjectOverviewPanel.vueindex a25a3eeb0d..f5ae1a1db2 100644--- a/frontend/src/components/ProjectOverviewPanel.vue+++ b/frontend/src/components/ProjectOverviewPanel.vue@@ -5,7 +5,22 @@{{ $t("project.overview.recent-activity") }}</p><div class="relative">- <ActivityTable :activity-list="state.activityList" />+ <!-- show the first 5 activities -->+ <!-- But won't show "Load more", since we have a "View all" link below -->+ <PagedActivityTableVue+ :activity-find="{+ typePrefix: ['bb.project.', 'bb.database.'],+ container: project.id,+ order: 'DESC',+ }"+ session-key="project-activity"+ :page-size="5"+ :hide-load-more="true"+ >+ <template #table="{ activityList }">+ <ActivityTable :activity-list="activityList" />+ </template>+ </PagedActivityTableVue><divv-if="state.isFetchingActivityList"class="absolute inset-0 flex flex-col items-center justify-center bg-white/70"@@ -91,20 +106,18 @@ import {PropType,computed,defineComponent,- watch,} from "vue";import ActivityTable from "../components/ActivityTable.vue";import { IssueTable } from "../components/Issue";-import { Activity, Database, Issue, Project, LabelKeyType } from "../types";+import { Database, Issue, Project, LabelKeyType } from "../types";import { findDefaultGroupByLabel } from "../utils";-import { useActivityStore } from "@/store";import PagedIssueTable from "@/components/Issue/PagedIssueTable.vue";+import PagedActivityTableVue from "./PagedActivityTable.vue";// Show at most 5 activityconst ACTIVITY_LIMIT = 5;interface LocalState {- activityList: Activity[];isFetchingActivityList: boolean;progressIssueList: Issue[];closedIssueList: Issue[];@@ -119,6 +132,7 @@ export default defineComponent({ActivityTable,IssueTable,PagedIssueTable,+ PagedActivityTableVue,},props: {project: {@@ -132,7 +146,6 @@ export default defineComponent({},setup(props) {const state = reactive<LocalState>({- activityList: [],isFetchingActivityList: false,progressIssueList: [],closedIssueList: [],@@ -140,32 +153,11 @@ export default defineComponent({xAxisLabel: "bb.environment",yAxisLabel: undefined,});- const activityStore = useActivityStore();-- const prepareActivityList = () => {- state.isFetchingActivityList = true;- state.activityList = [];- activityStore- .fetchActivityListForProject({- projectId: props.project.id,- limit: ACTIVITY_LIMIT,- })- .then((list) => {- state.activityList = list.slice(0, ACTIVITY_LIMIT);- state.isFetchingActivityList = false;- });- };const isTenantProject = computed((): boolean => {return props.project.tenantMode === "TENANT";});- const prepare = () => {- prepareActivityList();- };-- watch(() => props.project.id, prepare, { immediate: true });-const filteredDatabaseList = computed(() => {const filter = state.databaseNameFilter.toLocaleLowerCase();if (!filter) return props.databaseList;@@ -189,6 +181,7 @@ export default defineComponent({isTenantProject,filteredDatabaseList,excludedKeyList,+ ACTIVITY_LIMIT,};},});diff --git a/frontend/src/store/modules/activity.ts b/frontend/src/store/modules/activity.tsindex ae46f1bbdc..5a7f964c3a 100644--- a/frontend/src/store/modules/activity.ts+++ b/frontend/src/store/modules/activity.ts@@ -10,12 +10,12 @@ import {Issue,IssueId,PrincipalId,- ProjectId,ResourceObject,UNKNOWN_ID,isPagedResponse,ResourceIdentifier,empty,+ ActivityFind,} from "@/types";import { convertEntityList } from "./utils";import { useAuthStore } from "./auth";@@ -112,15 +112,7 @@ export const useActivityStore = defineStore("activity", {this.setActivityListForUser({ userId, activityList });return activityList;},- async fetchPagedActivityList(params: {- typePrefix: string | string[];- container?: number | string;- order: "ASC" | "DESC";- user?: number;- limit?: number;- level?: string | string[];- token?: string;- }) {+ async fetchPagedActivityList(params: ActivityFind) {const url = `/api/activity?${stringify(params, {arrayFormat: "repeat",})}`;@@ -139,15 +131,7 @@ export const useActivityStore = defineStore("activity", {activityList,};},- async fetchActivityList(params: {- typePrefix: string | string[];- container?: number | string;- order: "ASC" | "DESC";- user?: number;- limit?: number;- level?: string | string[];- token?: string;- }) {+ async fetchActivityList(params: ActivityFind) {const result = await this.fetchPagedActivityList(params);return result.activityList;},@@ -171,23 +155,6 @@ export const useActivityStore = defineStore("activity", {}this.fetchActivityListForIssue(issue);},- // We do not store the returned list because the caller will specify different limits.- async fetchActivityListForProject({- projectId,- limit,- }: {- projectId: ProjectId;- limit?: number;- }) {- const activityList = await this.fetchActivityList({- typePrefix: ["bb.project.", "bb.database."],- container: projectId,- order: "DESC",- limit,- });-- return activityList;- },async fetchActivityListForQueryHistory({ limit }: { limit: number }) {const { currentUser } = useAuthStore();const activityList = await this.fetchActivityList({diff --git a/frontend/src/store/modules/auditLog.ts b/frontend/src/store/modules/auditLog.tsindex b3bb1d465c..54aa8571c6 100644--- a/frontend/src/store/modules/auditLog.ts+++ b/frontend/src/store/modules/auditLog.ts@@ -1,12 +1,13 @@-import { watchEffect } from "vue";-import { defineStore, storeToRefs } from "pinia";+import { defineStore } from "pinia";import axios from "axios";+import { stringify } from "qs";import type {AuditLogState,ResourceObject,ResourceIdentifier,+ ActivityFind,} from "@/types";-import { AuditActivityType, empty, isPagedResponse } from "@/types";+import { empty, isPagedResponse } from "@/types";import type { AuditLog } from "@/types/auditLog";import { getPrincipalFromIncludedList } from "./principal";import { convertEntityList } from "./utils";@@ -45,12 +46,6 @@ function getAuditLogFromIncludedList(return empty("AUDIT_LOG");}-const typePrefixQuery = `${(- Object.keys(AuditActivityType) as Array<keyof typeof AuditActivityType>-)- .map((key) => `typePrefix=${AuditActivityType[key]}`)- .join("&")}`;-export const useAuditLogStore = defineStore("auditLog", {state: (): AuditLogState => ({auditLogList: [],@@ -59,8 +54,10 @@ export const useAuditLogStore = defineStore("auditLog", {setAuditLogList(auditLogList: AuditLog[]) {this.auditLogList = auditLogList;},- async fetchPagedAuditLogList() {- const url = `/api/activity?${typePrefixQuery}`;+ async fetchPagedAuditLogList(params: ActivityFind) {+ const url = `/api/activity?${stringify(params, {+ arrayFormat: "repeat",+ })}`;const responseData = (await axios.get(url)).data;const auditLogList = convertEntityList(responseData,@@ -76,17 +73,10 @@ export const useAuditLogStore = defineStore("auditLog", {auditLogList,};},- async fetchAuditLogList() {- const res = await this.fetchPagedAuditLogList();+ async fetchAuditLogList(params: ActivityFind) {+ const res = await this.fetchPagedAuditLogList(params);this.setAuditLogList(res.auditLogList);return res.auditLogList;},},});--export const useAuditLogList = () => {- const store = useAuditLogStore();- watchEffect(async () => await store.fetchAuditLogList());-- return storeToRefs(store).auditLogList;-};diff --git a/frontend/src/types/activity.ts b/frontend/src/types/activity.tsindex d0311d4a98..42047cd10c 100644--- a/frontend/src/types/activity.ts+++ b/frontend/src/types/activity.ts@@ -242,3 +242,13 @@ export type ActivityPatch = {// Domain specific fieldscomment: string;};++export type ActivityFind = {+ typePrefix?: string | string[];+ container?: number | string;+ order?: "ASC" | "DESC";+ user?: number;+ limit?: number;+ level?: string | string[];+ token?: string;+};diff --git a/frontend/src/views/SettingWorkspaceAuditLog.vue b/frontend/src/views/SettingWorkspaceAuditLog.vueindex f34c8f3503..1a021a1540 100644--- a/frontend/src/views/SettingWorkspaceAuditLog.vue+++ b/frontend/src/views/SettingWorkspaceAuditLog.vue@@ -1,52 +1,57 @@<template><div class="space-y-4">- <div v-if="auditLogList.length > 0">- <AuditLogTable- :audit-log-list="auditLogList.sort((a, b) => b.createdTs - a.createdTs)"- @view-detail="handleViewDetail"- />- <BBDialog- ref="dialog"- :title="$t('audit-log.audit-log-detail')"- data-label="bb-audit-log-detail-dialog"- :closable="true"- :show-negative-btn="false"- >- <div class="w-192 font-mono">- <dl>- <dd- v-for="(value, key) in state.modalContent"- :key="key"- class="flex items-start text-sm md:mr-4 mb-1"- >- <NGrid x-gap="20" :cols="20">- <NGi span="3">- <span class="textlabel whitespace-nowrap">{{- logKeyMap[key]- }}</span- ><span class="mr-1">:</span>- </NGi>- <NGi span="17">- <span v-if="value !== ''">- {{- (key as string).includes("Ts")- ? dayjs- .unix(value as number)- .format("YYYY-MM-DD HH:mm:ss Z")- : value- }}- </span>- <span v-else class="italic text-gray-500">- {{ $t("audit-log.table.empty") }}- </span>- </NGi>- </NGrid>- </dd>- </dl>- </div>- </BBDialog>- </div>- <AuditLogEmptyView v-else />+ <PagedAuditLogTable+ :activity-find="{+ typePrefix: typePrefixList,+ order: 'DESC',+ }"+ session-key="settings-audit-log-table"+ :page-size="10"+ >+ <template #table="{ list }">+ <AuditLogTable :audit-log-list="list" @view-detail="handleViewDetail" />+ </template>+ </PagedAuditLogTable>+ <BBDialog+ ref="dialog"+ :title="$t('audit-log.audit-log-detail')"+ data-label="bb-audit-log-detail-dialog"+ :closable="true"+ :show-negative-btn="false"+ >+ <div class="w-192 font-mono">+ <dl>+ <dd+ v-for="(value, key) in state.modalContent"+ :key="key"+ class="flex items-start text-sm md:mr-4 mb-1"+ >+ <NGrid x-gap="20" :cols="20">+ <NGi span="3">+ <span class="textlabel whitespace-nowrap">{{+ logKeyMap[key]+ }}</span+ ><span class="mr-1">:</span>+ </NGi>+ <NGi span="17">+ <span v-if="value !== ''">+ {{+ (key as string).includes("Ts")+ ? dayjs+ .unix(value as number)+ .format("YYYY-MM-DD HH:mm:ss Z")+ : value+ }}+ </span>+ <span v-else class="italic text-gray-500">+ {{ $t("audit-log.table.empty") }}+ </span>+ </NGi>+ </NGrid>+ </dd>+ </dl>+ </div>+ </BBDialog></div></template>@@ -55,7 +60,7 @@ import { reactive, ref } from "vue";import { NGrid, NGi } from "naive-ui";import { useI18n } from "vue-i18n";import { BBDialog } from "@/bbkit";-import { useAuditLogList } from "@/store";+import { AuditActivityType } from "@/types";const dialog = ref<InstanceType<typeof BBDialog> | null>(null);const state = reactive({@@ -64,7 +69,6 @@ const state = reactive({});const { t } = useI18n();-const auditLogList = useAuditLogList();const logKeyMap = {createdTs: t("audit-log.table.created-time"),@@ -76,6 +80,10 @@ const logKeyMap = {payload: t("audit-log.table.payload"),};+const typePrefixList = (+ Object.keys(AuditActivityType) as Array<keyof typeof AuditActivityType>+).map((key) => AuditActivityType[key]);+const handleViewDetail = (log: any) => {state.modalContent = log;state.showModal = true;