Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Implement /inbox API
天舟c1b629b56fb4
diff --git a/api/inbox.go b/api/inbox.gonew file mode 100644index 0000000000..1d2dcb2791--- /dev/null+++ b/api/inbox.go@@ -0,0 +1,70 @@+package api++import (+ "context"+ "encoding/json"+)++type InboxStatus string++const (+ UNREAD InboxStatus = "UNREAD"+ READ InboxStatus = "READ"+ PINNED InboxStatus = "PINNED"+)++func (e InboxStatus) String() string {+ switch e {+ case UNREAD:+ return "UNREAD"+ case READ:+ return "READ"+ case PINNED:+ return "PINNED"+ }+ return "UNKNOWN"+}++type Inbox struct {+ ID int `jsonapi:"primary,inbox"`++ // Domain specific fields+ ReceiverId int `jsonapi:"attr,receiverId"`+ Activity *Activity `jsonapi:"relation,activity"`+ Status InboxStatus `jsonapi:"attr,status"`+}++type InboxCreate struct {+ // Domain specific fields+ ReceiverId int+ ActivityId int+}++type InboxFind struct {+ ID *int++ // Domain specific fields+ ReceiverId *int+}++func (find *InboxFind) String() string {+ str, err := json.Marshal(*find)+ if err != nil {+ return err.Error()+ }+ return string(str)+}++type InboxPatch struct {+ ID int++ // Domain specific fields+ Status InboxStatus `jsonapi:"attr,status"`+}++type InboxService interface {+ CreateInbox(ctx context.Context, create *InboxCreate) (*Inbox, error)+ FindInboxList(ctx context.Context, find *InboxFind) ([]*Inbox, error)+ FindInbox(ctx context.Context, find *InboxFind) (*Inbox, error)+ PatchInbox(ctx context.Context, patch *InboxPatch) (*Inbox, error)+}diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex 993289e354..ed0eac8be7 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -285,6 +285,7 @@ func (m *main) Run() error {server.StageService = store.NewStageService(m.l, db)server.TaskService = store.NewTaskService(m.l, db, store.NewTaskRunService(m.l, db))server.ActivityService = store.NewActivityService(m.l, db)+ server.InboxService = store.NewInboxService(m.l, db, server.ActivityService)server.BookmarkService = store.NewBookmarkService(m.l, db)server.VCSService = store.NewVCSService(m.l, db)server.RepositoryService = store.NewRepositoryService(m.l, db, server.ProjectService)diff --git a/server/acl.go b/server/acl.goindex 1a3131ce9f..d8b1e48b18 100644--- a/server/acl.go+++ b/server/acl.go@@ -101,6 +101,27 @@ func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Handmethod = method + "_SELF"}}+ } else if strings.HasPrefix(c.Path(), "/api/inbox") {+ inboxIdStr := c.Param("inboxId")+ if inboxIdStr != "" {+ inboxId, err := strconv.Atoi(inboxIdStr)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Inbox ID is not a number: %s", inboxIdStr))+ }+ inboxFind := &api.InboxFind{+ ID: &inboxId,+ }+ inbox, err := s.InboxService.FindInbox(context.Background(), inboxFind)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Inbox ID not found: %d", inboxId))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process authorize request.").SetInternal(err)+ }+ if inbox.ReceiverId == principalId {+ method = method + "_SELF"+ }+ }}}diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex 608565dc43..55aa30d342 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -43,6 +43,8 @@ p, DBA, /activity, POSTp, DBA, /activity, GETp, DBA, /activity/{id}, PATCH_SELFp, DBA, /activity/{id}, DELETE_SELF+p, DBA, /inbox, GET+p, DBA, /inbox/{id}, PATCH_SELFp, DBA, /bookmark, POSTp, DBA, /bookmark, GETp, DBA, /bookmark/{id}, DELETE_SELFdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex 0fb266a6a9..f518313e5f 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -39,6 +39,8 @@ p, DEVELOPER, /activity, POSTp, DEVELOPER, /activity, GETp, DEVELOPER, /activity/{id}, PATCH_SELFp, DEVELOPER, /activity/{id}, DELETE_SELF+p, DEVELOPER, /inbox, GET+p, DEVELOPER, /inbox/{id}, PATCH_SELFp, DEVELOPER, /bookmark, POSTp, DEVELOPER, /bookmark, GETp, DEVELOPER, /bookmark/{id}, DELETE_SELFdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 05f3db5752..54172019c8 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -47,6 +47,8 @@ p, OWNER, /activity, POSTp, OWNER, /activity, GETp, OWNER, /activity/{id}, PATCH_SELFp, OWNER, /activity/{id}, DELETE_SELF+p, OWNER, /inbox, GET+p, OWNER, /inbox/{id}, PATCH_SELFp, OWNER, /bookmark, POSTp, OWNER, /bookmark, GETp, OWNER, /bookmark/{id}, DELETE_SELFdiff --git a/server/inbox.go b/server/inbox.gonew file mode 100644index 0000000000..34b207dffe--- /dev/null+++ b/server/inbox.go@@ -0,0 +1,75 @@+package server++import (+ "context"+ "fmt"+ "net/http"+ "strconv"++ "github.com/bytebase/bytebase"+ "github.com/bytebase/bytebase/api"+ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"+)++func (s *Server) registerInboxRoutes(g *echo.Group) {+ g.GET("/inbox", func(c echo.Context) error {+ inboxFind := &api.InboxFind{}+ userIdStr := c.QueryParams().Get("user")+ if userIdStr != "" {+ userId, err := strconv.Atoi(userIdStr)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter user is not a number: %s", userIdStr)).SetInternal(err)+ }+ inboxFind.ReceiverId = &userId+ }+ list, err := s.InboxService.FindInboxList(context.Background(), inboxFind)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch inbox list").SetInternal(err)+ }++ for _, inbox := range list {+ if err := s.ComposeActivityRelationship(context.Background(), inbox.Activity); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch inbox activity relationship: %v", inbox.Activity.ID)).SetInternal(err)+ }+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal inbox list response").SetInternal(err)+ }+ return nil+ })++ g.PATCH("/inbox/:inboxId", func(c echo.Context) error {+ id, err := strconv.Atoi(c.Param("inboxId"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("inboxId"))).SetInternal(err)+ }++ inboxPatch := &api.InboxPatch{+ ID: id,+ }+ if err := jsonapi.UnmarshalPayload(c.Request().Body, inboxPatch); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch inbox request").SetInternal(err)+ }++ inbox, err := s.InboxService.PatchInbox(context.Background(), inboxPatch)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Inbox ID not found: %d", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch inbox ID: %v", id)).SetInternal(err)+ }++ if err := s.ComposeActivityRelationship(context.Background(), inbox.Activity); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated inbox activity relationship: %v", inbox.ID)).SetInternal(err)+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, inbox); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal inbox ID response: %v", id)).SetInternal(err)+ }+ return nil+ })+}diff --git a/server/server.go b/server/server.goindex f8d3f7bb75..af4eb0b98e 100644--- a/server/server.go+++ b/server/server.go@@ -43,6 +43,7 @@ type Server struct {StageService api.StageServiceTaskService api.TaskServiceActivityService api.ActivityService+ InboxService api.InboxServiceBookmarkService api.BookmarkServiceVCSService api.VCSServiceRepositoryService api.RepositoryService@@ -159,6 +160,7 @@ func NewServer(logger *zap.Logger, version string, host string, port int, mode ss.registerIssueSubscriberRoutes(apiGroup)s.registerTaskRoutes(apiGroup)s.registerActivityRoutes(apiGroup)+ s.registerInboxRoutes(apiGroup)s.registerBookmarkRoutes(apiGroup)s.registerSqlRoutes(apiGroup)s.registerVCSRoutes(apiGroup)diff --git a/store/inbox.go b/store/inbox.gonew file mode 100644index 0000000000..7eb4f5d2a9--- /dev/null+++ b/store/inbox.go@@ -0,0 +1,261 @@+package store++import (+ "context"+ "fmt"+ "strings"++ "github.com/bytebase/bytebase"+ "github.com/bytebase/bytebase/api"+ "go.uber.org/zap"+)++var (+ _ api.InboxService = (*InboxService)(nil)+)++// InboxService represents a service for managing inbox.+type InboxService struct {+ l *zap.Logger+ db *DB++ activityService api.ActivityService+}++// NewInboxService returns a new instance of InboxService.+func NewInboxService(logger *zap.Logger, db *DB, activityService api.ActivityService) *InboxService {+ return &InboxService{l: logger, db: db, activityService: activityService}+}++// CreateInbox creates a new inbox.+func (s *InboxService) CreateInbox(ctx context.Context, create *api.InboxCreate) (*api.Inbox, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ inbox, err := s.createInbox(ctx, tx, create)+ if err != nil {+ return nil, err+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ return inbox, nil+}++// FindInboxList retrieves a list of inboxs based on find.+func (s *InboxService) FindInboxList(ctx context.Context, find *api.InboxFind) ([]*api.Inbox, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ list, err := findInboxList(ctx, tx, find)+ if err != nil {+ return []*api.Inbox{}, err+ }++ return list, nil+}++// FindInbox retrieves a single inbox based on find.+// Returns ENOTFOUND if no matching record.+// Returns ECONFLICT if finding more than 1 matching records.+func (s *InboxService) FindInbox(ctx context.Context, find *api.InboxFind) (*api.Inbox, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ list, err := findInboxList(ctx, tx, find)+ if err != nil {+ return nil, err+ } else if len(list) == 0 {+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("inbox not found: %+v", find)}+ } else if len(list) > 1 {+ return nil, &bytebase.Error{Code: bytebase.ECONFLICT, Message: fmt.Sprintf("found %d inboxes with filter %+v, expect 1", len(list), find)}+ }+ return list[0], nil+}++// PatchInbox updates an existing inbox by ID.+// Returns ENOTFOUND if inbox does not exist.+func (s *InboxService) PatchInbox(ctx context.Context, patch *api.InboxPatch) (*api.Inbox, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ inbox, err := s.patchInbox(ctx, tx, patch)+ if err != nil {+ return nil, FormatError(err)+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ return inbox, nil+}++// createInbox creates a new inbox.+func (s *InboxService) createInbox(ctx context.Context, tx *Tx, create *api.InboxCreate) (*api.Inbox, error) {+ // Insert row into database.+ row, err := tx.QueryContext(ctx, `+ INSERT INTO inbox (+ receiver_id,+ activity_id,+ `+"`status`"+`+ )+ VALUES (?, ?, 'UNREAD')+ RETURNING id, receiver_id, activity_id, `+"`status`"+`+ `,+ create.ReceiverId,+ create.ActivityId,+ )++ if err != nil {+ return nil, FormatError(err)+ }+ defer row.Close()++ row.Next()+ var inbox api.Inbox+ var activityId int+ if err := row.Scan(+ &inbox.ID,+ &inbox.ReceiverId,+ &activityId,+ &inbox.Status,+ ); err != nil {+ return nil, FormatError(err)+ }++ activityFind := &api.ActivityFind{+ ID: &activityId,+ }+ inbox.Activity, err = s.activityService.FindActivity(context.Background(), activityFind)+ if err != nil {+ return nil, FormatError(err)+ }++ return &inbox, nil+}++func findInboxList(ctx context.Context, tx *Tx, find *api.InboxFind) (_ []*api.Inbox, err error) {+ // Build WHERE clause.+ where, args := []string{"1 = 1"}, []interface{}{}+ where = append(where, "inbox.activity_id = activity.id")+ if v := find.ID; v != nil {+ where, args = append(where, "inbox.id = ?"), append(args, *v)+ }+ if v := find.ReceiverId; v != nil {+ where, args = append(where, "receiver_id = ?"), append(args, *v)+ }++ rows, err := tx.QueryContext(ctx, `+ SELECT+ inbox.id,+ receiver_id,+ `+"`status`,"+`+ activity.id,+ activity.creator_id,+ activity.created_ts,+ activity.updater_id,+ activity.updated_ts,+ activity.container_id,+ activity.type,+ activity.comment,+ activity.payload+ FROM inbox, activity+ WHERE `+strings.Join(where, " AND "),+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ // Iterate over result set and deserialize rows into list.+ list := make([]*api.Inbox, 0)+ for rows.Next() {+ var inbox api.Inbox+ inbox.Activity = &api.Activity{}+ if err := rows.Scan(+ &inbox.ID,+ &inbox.ReceiverId,+ &inbox.Status,+ &inbox.Activity.ID,+ &inbox.Activity.CreatorId,+ &inbox.Activity.CreatedTs,+ &inbox.Activity.UpdaterId,+ &inbox.Activity.UpdatedTs,+ &inbox.Activity.ContainerId,+ &inbox.Activity.Type,+ &inbox.Activity.Comment,+ &inbox.Activity.Payload,+ ); err != nil {+ return nil, FormatError(err)+ }++ list = append(list, &inbox)+ }+ if err := rows.Err(); err != nil {+ return nil, FormatError(err)+ }++ return list, nil+}++// patchInbox updates a inbox by ID. Returns the new state of the inbox after update.+func (s *InboxService) patchInbox(ctx context.Context, tx *Tx, patch *api.InboxPatch) (*api.Inbox, error) {+ // Build UPDATE clause.+ set, args := []string{"`status` = ?"}, []interface{}{patch.Status}+ args = append(args, patch.ID)++ // Execute update query with RETURNING.+ row, err := tx.QueryContext(ctx, `+ UPDATE inbox+ SET `+strings.Join(set, ", ")+`+ WHERE id = ?+ RETURNING id, receiver_id, activity_id, `+"`status`"+`+ `,+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer row.Close()++ if row.Next() {+ var inbox api.Inbox+ var activityId int+ if err := row.Scan(+ &inbox.ID,+ &inbox.ReceiverId,+ &activityId,+ &inbox.Status,+ ); err != nil {+ return nil, FormatError(err)+ }++ activityFind := &api.ActivityFind{+ ID: &activityId,+ }+ inbox.Activity, err = s.activityService.FindActivity(context.Background(), activityFind)+ if err != nil {+ return nil, FormatError(err)+ }++ return &inbox, nil+ }++ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("inbox ID not found: %d", patch.ID)}+}