Skip to content

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

feat: pagination support for activity list (#3941)

ZhengXc957c8b2f35b
diff --git a/api/activity.go b/api/activity.go
index 62d1c8057f..e1dc3db616 100644
--- a/api/activity.go
+++ b/api/activity.go
@@ -232,6 +232,12 @@ type Activity struct {
Payload string `jsonapi:"attr,payload"`
}
+// ActivityResponse is the API message for an activity response.
+type ActivityResponse struct {
+ ActivityList []*Activity `jsonapi:"relation,activityList"`
+ NextToken string `jsonapi:"attr,nextToken"`
+}
+
// ActivityCreate is the API message for creating an activity.
type ActivityCreate struct {
// Standard fields
@@ -256,6 +262,8 @@ type ActivityFind struct {
LevelList []ActivityLevel
ContainerID *int
Limit *int
+ // If specified, only find activities whose ID is smaller than SinceID.
+ SinceID *int
// If specified, sorts the returned list by created_ts in <<ORDER>>
// Different use cases want different orders.
// e.g. Issue activity list wants ASC, while view recent activity list wants DESC.
diff --git a/frontend/src/store/modules/activity.ts b/frontend/src/store/modules/activity.ts
index 674fde3350..ae46f1bbdc 100644
--- a/frontend/src/store/modules/activity.ts
+++ b/frontend/src/store/modules/activity.ts
@@ -13,7 +13,11 @@ import {
ProjectId,
ResourceObject,
UNKNOWN_ID,
+ isPagedResponse,
+ ResourceIdentifier,
+ empty,
} from "@/types";
+import { convertEntityList } from "./utils";
import { useAuthStore } from "./auth";
import { getPrincipalFromIncludedList } from "./principal";
import { useIssueStore } from "./issue";
@@ -40,6 +44,27 @@ function convert(
};
}
+function getActivityFromIncludedList(
+ data:
+ | ResourceIdentifier<ResourceObject>
+ | ResourceIdentifier<ResourceObject>[]
+ | undefined,
+ includedList: ResourceObject[]
+): Activity {
+ if (data == null) {
+ return empty("ACTIVITY");
+ }
+ for (const item of includedList || []) {
+ if (item.type !== "activity") {
+ continue;
+ }
+ if (item.id == (data as ResourceIdentifier).id) {
+ return convert(item, includedList);
+ }
+ }
+ return empty("ACTIVITY");
+}
+
export const useActivityStore = defineStore("activity", {
state: (): ActivityState => ({
activityListByUser: new Map(),
@@ -87,24 +112,44 @@ export const useActivityStore = defineStore("activity", {
this.setActivityListForUser({ userId, activityList });
return activityList;
},
- async fetchActivityList(params: {
+ async fetchPagedActivityList(params: {
typePrefix: string | string[];
container?: number | string;
order: "ASC" | "DESC";
user?: number;
limit?: number;
level?: string | string[];
+ token?: string;
}) {
const url = `/api/activity?${stringify(params, {
arrayFormat: "repeat",
})}`;
- const response = (await axios.get(url)).data;
- const activityList: Activity[] = response.data.map(
- (activity: ResourceObject) => {
- return convert(activity, response.included);
- }
+ const responseData = (await axios.get(url)).data;
+ const activityList = convertEntityList(
+ responseData,
+ "activityList",
+ convert,
+ getActivityFromIncludedList
);
- return activityList;
+ const nextToken = isPagedResponse(responseData, "activityList")
+ ? responseData.data.attributes.nextToken
+ : "";
+ return {
+ nextToken,
+ activityList,
+ };
+ },
+ async fetchActivityList(params: {
+ typePrefix: string | string[];
+ container?: number | string;
+ order: "ASC" | "DESC";
+ user?: number;
+ limit?: number;
+ level?: string | string[];
+ token?: string;
+ }) {
+ const result = await this.fetchPagedActivityList(params);
+ return result.activityList;
},
async fetchActivityListForIssue(issue: Issue) {
const activityList = await this.fetchActivityList({
diff --git a/frontend/src/store/modules/auditLog.ts b/frontend/src/store/modules/auditLog.ts
index 9ca3cf25a8..b3bb1d465c 100644
--- a/frontend/src/store/modules/auditLog.ts
+++ b/frontend/src/store/modules/auditLog.ts
@@ -1,36 +1,50 @@
import { watchEffect } from "vue";
import { defineStore, storeToRefs } from "pinia";
import axios from "axios";
-import type { AuditLogState, ResponseWithData, ResourceObjects } from "@/types";
-import { AuditActivityType } from "@/types";
+import type {
+ AuditLogState,
+ ResourceObject,
+ ResourceIdentifier,
+} from "@/types";
+import { AuditActivityType, empty, isPagedResponse } from "@/types";
import type { AuditLog } from "@/types/auditLog";
+import { getPrincipalFromIncludedList } from "./principal";
+import { convertEntityList } from "./utils";
-const convertAuditLogList = (res: ResponseWithData): AuditLog[] => {
- const activityList = res.data as ResourceObjects;
- const auditLogList: AuditLog[] = activityList.map(
- (activity) =>
- ({
- createdTs: activity.attributes.createdTs as number,
- creator: res.included!.find(
- (item) =>
- item.id ===
- (
- activity.relationships!.creator.data as {
- id: string;
- type: string;
- }
- ).id
- )?.attributes.email as string,
- type: activity.attributes.type as string,
- level: activity.attributes.level as string,
- comment: activity.attributes.comment as string,
- payload: activity.attributes.payload as string,
- } as AuditLog)
- );
-
- return auditLogList;
+const convert = (
+ auditLog: ResourceObject,
+ includedList: ResourceObject[]
+): AuditLog => {
+ return {
+ ...(auditLog.attributes as Omit<AuditLog, "creator">),
+ creator: getPrincipalFromIncludedList(
+ auditLog.relationships!.creator.data,
+ includedList
+ )?.email as string,
+ };
};
+function getAuditLogFromIncludedList(
+ data:
+ | ResourceIdentifier<ResourceObject>
+ | ResourceIdentifier<ResourceObject>[]
+ | undefined,
+ includedList: ResourceObject[]
+): AuditLog {
+ if (data == null) {
+ return empty("AUDIT_LOG");
+ }
+ for (const item of includedList || []) {
+ if (item.type !== "activity") {
+ continue;
+ }
+ if (item.id == (data as ResourceIdentifier).id) {
+ return convert(item, includedList);
+ }
+ }
+ return empty("AUDIT_LOG");
+}
+
const typePrefixQuery = `${(
Object.keys(AuditActivityType) as Array<keyof typeof AuditActivityType>
)
@@ -45,11 +59,27 @@ export const useAuditLogStore = defineStore("auditLog", {
setAuditLogList(auditLogList: AuditLog[]) {
this.auditLogList = auditLogList;
},
+ async fetchPagedAuditLogList() {
+ const url = `/api/activity?${typePrefixQuery}`;
+ const responseData = (await axios.get(url)).data;
+ const auditLogList = convertEntityList(
+ responseData,
+ "activityList",
+ convert,
+ getAuditLogFromIncludedList
+ );
+ const nextToken = isPagedResponse(responseData, "activityList")
+ ? responseData.data.attributes.nextToken
+ : "";
+ return {
+ nextToken,
+ auditLogList,
+ };
+ },
async fetchAuditLogList() {
- const res = (await axios.get(`/api/activity?${typePrefixQuery}`)).data;
- const list = convertAuditLogList(res);
- this.setAuditLogList(list);
- return list;
+ const res = await this.fetchPagedAuditLogList();
+ this.setAuditLogList(res.auditLogList);
+ return res.auditLogList;
},
},
});
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index 4ab926d591..929ddce839 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -26,6 +26,7 @@ import { DeploymentConfig } from "./deployment";
import { Policy, DefaultApprovalPolicy } from "./policy";
import { Sheet } from "./sheet";
import { SQLReviewPolicy } from "./sqlReview";
+import { AuditLog, AuditActivityType, AuditActivityLevel } from "./auditLog";
// System bot id
export const SYSTEM_BOT_ID = 1;
@@ -129,7 +130,8 @@ export type ResourceType =
| "ANOMALY"
| "DEPLOYMENT_CONFIG"
| "SHEET"
- | "SQL_REVIEW";
+ | "SQL_REVIEW"
+ | "AUDIT_LOG";
interface ResourceMaker {
(type: "PRINCIPAL"): Principal;
@@ -157,6 +159,7 @@ interface ResourceMaker {
(type: "DEPLOYMENT_CONFIG"): DeploymentConfig;
(type: "SHEET"): Sheet;
(type: "SQL_REVIEW"): SQLReviewPolicy;
+ (type: "AUDIT_LOG"): AuditLog;
}
const makeUnknown = (type: ResourceType) => {
@@ -927,6 +930,15 @@ const makeEmpty = (type: ResourceType) => {
ruleList: [],
};
+ const EMPTY_AUDIT_LOG: AuditLog = {
+ createdTs: 0,
+ creator: EMPTY_PRINCIPAL.email,
+ type: AuditActivityType.MemberCreate,
+ level: AuditActivityLevel.INFO,
+ comment: "",
+ payload: "",
+ };
+
switch (type) {
case "PRINCIPAL":
return EMPTY_PRINCIPAL;
@@ -978,6 +990,8 @@ const makeEmpty = (type: ResourceType) => {
return EMPTY_SHEET;
case "SQL_REVIEW":
return EMPTY_SQL_REVIEW_POLICY;
+ case "AUDIT_LOG":
+ return EMPTY_AUDIT_LOG;
}
};
export const empty = makeEmpty as ResourceMaker;
diff --git a/server/activity.go b/server/activity.go
index 1462808fb3..bac83446e4 100644
--- a/server/activity.go
+++ b/server/activity.go
@@ -58,6 +58,15 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
g.GET("/activity", func(c echo.Context) error {
ctx := c.Request().Context()
activityFind := &api.ActivityFind{}
+
+ pageToken := c.QueryParams().Get("token")
+ // We use descending order by default for activities.
+ sinceID, err := unmarshalPageToken(pageToken, api.DESC)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed page token").SetInternal(err)
+ }
+ activityFind.SinceID = &sinceID
+
if creatorIDStr := c.QueryParams().Get("user"); creatorIDStr != "" {
creatorID, err := strconv.Atoi(creatorIDStr)
if err != nil {
@@ -88,6 +97,9 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter limit is not a number: %s", limitStr)).SetInternal(err)
}
activityFind.Limit = &limit
+ } else {
+ limit := api.DefaultPageSize
+ activityFind.Limit = &limit
}
if orderStr := c.QueryParams().Get("order"); orderStr != "" {
order, err := api.StringToSortOrder(orderStr)
@@ -101,8 +113,20 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch activity list").SetInternal(err)
}
+ activityResponse := &api.ActivityResponse{}
+ activityResponse.ActivityList = activityList
+
+ nextSinceID := sinceID
+ if len(activityList) > 0 {
+ // Decrement the ID as we use decreasing order by default.
+ nextSinceID = activityList[len(activityList)-1].ID - 1
+ }
+ if activityResponse.NextToken, err = marshalPageToken(nextSinceID); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal page token").SetInternal(err)
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, activityList); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, activityResponse); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal activity list response").SetInternal(err)
}
return nil
diff --git a/store/activity.go b/store/activity.go
index addb358897..b23bc4a4ba 100644
--- a/store/activity.go
+++ b/store/activity.go
@@ -359,6 +359,9 @@ func findActivityImpl(ctx context.Context, tx *Tx, find *api.ActivityFind) ([]*a
}
where = append(where, fmt.Sprintf("(%s)", strings.Join(queryValues, " OR ")))
}
+ if v := find.SinceID; v != nil {
+ where, args = append(where, fmt.Sprintf("id <= $%d", len(args)+1)), append(args, *v)
+ }
var query = `
SELECT
@@ -375,7 +378,7 @@ func findActivityImpl(ctx context.Context, tx *Tx, find *api.ActivityFind) ([]*a
FROM activity
WHERE ` + strings.Join(where, " AND ")
if v := find.Order; v != nil {
- query += fmt.Sprintf(" ORDER BY created_ts %s", *v)
+ query += fmt.Sprintf(" ORDER BY id %s", *v)
}
if v := find.Limit; v != nil {
query += fmt.Sprintf(" LIMIT %d", *v)