Skip to content

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

Cleanup how we pass context.Context object around

天舟7a73a28b55aa
diff --git a/bin/bb/cmd/dump.go b/bin/bb/cmd/dump.go
index 9d3ad839ae..7b1aaba901 100644
--- a/bin/bb/cmd/dump.go
+++ b/bin/bb/cmd/dump.go
@@ -39,14 +39,14 @@ var (
SslCert: sslCert,
SslKey: sslKey,
}
- return dumpDatabase(databaseType, username, password, hostname, port, database, file, tlsCfg, schemaOnly)
+ return dumpDatabase(context.Background(), databaseType, username, password, hostname, port, database, file, tlsCfg, schemaOnly)
},
}
)
// dumpDatabase exports the schema of a database instance.
// When file isn't specified, the schema will be exported to stdout.
-func dumpDatabase(databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig, schemaOnly bool) error {
+func dumpDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig, schemaOnly bool) error {
var dbType db.Type
switch databaseType {
case "mysql":
@@ -61,6 +61,7 @@ func dumpDatabase(databaseType, username, password, hostname, port, database, fi
}
db, err := db.Open(
+ ctx,
dbType,
db.DriverConfig{Logger: logger},
db.ConnectionConfig{
@@ -76,7 +77,7 @@ func dumpDatabase(databaseType, username, password, hostname, port, database, fi
if err != nil {
return err
}
- defer db.Close(context.Background())
+ defer db.Close()
out := os.Stdout
if file != "" {
@@ -85,9 +86,9 @@ func dumpDatabase(databaseType, username, password, hostname, port, database, fi
return fmt.Errorf("failed to create dump file %s, got error: %w", file, err)
}
}
- defer out.Close()
+ defer out.Close(ctx)
- if err := db.Dump(context.Background(), database, out, schemaOnly); err != nil {
+ if err := db.Dump(ctx, database, out, schemaOnly); err != nil {
return fmt.Errorf("failed to create dump %s, got error: %w", file, err)
}
return nil
diff --git a/bin/bb/cmd/restore.go b/bin/bb/cmd/restore.go
index e19e9ee3a9..262855d65e 100644
--- a/bin/bb/cmd/restore.go
+++ b/bin/bb/cmd/restore.go
@@ -40,13 +40,13 @@ var (
SslCert: sslCert,
SslKey: sslKey,
}
- return restoreDatabase(databaseType, username, password, hostname, port, database, file, tlsCfg)
+ return restoreDatabase(context.Background(), databaseType, username, password, hostname, port, database, file, tlsCfg)
},
}
)
// restoreDatabase restores the schema of a database instance.
-func restoreDatabase(databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig) error {
+func restoreDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig) error {
f, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("os.OpenFile(%q) error: %v", file, err)
@@ -67,6 +67,7 @@ func restoreDatabase(databaseType, username, password, hostname, port, database,
return fmt.Errorf("database type %q not supported; supported types: mysql, pg", databaseType)
}
db, err := db.Open(
+ ctx,
dbType,
db.DriverConfig{Logger: logger},
db.ConnectionConfig{
@@ -82,9 +83,9 @@ func restoreDatabase(databaseType, username, password, hostname, port, database,
if err != nil {
return err
}
- defer db.Close(context.Background())
+ defer db.Close(ctx)
- if err := db.Restore(context.Background(), sc); err != nil {
+ if err := db.Restore(ctx, sc); err != nil {
return fmt.Errorf("failed to restore from database dump %s got error: %w", file, err)
}
return nil
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 31e6e97df1..a63a9f31a3 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -199,7 +199,7 @@ func start() {
}()
// Execute program.
- if err := m.Run(); err != nil {
+ if err := m.Run(ctx); err != nil {
if err != http.ErrServerClosed {
m.l.Error(err.Error())
m.Close()
@@ -231,7 +231,7 @@ func newMain() *main {
}
}
-func initSetting(settingService api.SettingService) (*config, error) {
+func initSetting(ctx context.Context, settingService api.SettingService) (*config, error) {
result := &config{}
{
configCreate := &api.SettingCreate{
@@ -240,7 +240,7 @@ func initSetting(settingService api.SettingService) (*config, error) {
Value: common.RandomString(SECRET_LENGTH),
Description: "Random string used to sign the JWT auth token.",
}
- config, err := settingService.CreateSettingIfNotExist(context.Background(), configCreate)
+ config, err := settingService.CreateSettingIfNotExist(ctx, configCreate)
if err != nil {
return nil, err
}
@@ -254,7 +254,7 @@ func initSetting(settingService api.SettingService) (*config, error) {
Value: "",
Description: "URL for the external console (e.g. phpMyAdmin).",
}
- _, err := settingService.CreateSettingIfNotExist(context.Background(), configCreate)
+ _, err := settingService.CreateSettingIfNotExist(ctx, configCreate)
if err != nil {
return nil, err
}
@@ -263,14 +263,14 @@ func initSetting(settingService api.SettingService) (*config, error) {
return result, nil
}
-func (m *main) Run() error {
+func (m *main) Run(ctx context.Context) error {
db := store.NewDB(m.l, m.profile.dsn, m.profile.seedDir, m.profile.forceResetSeed, readonly)
if err := db.Open(); err != nil {
return fmt.Errorf("cannot open db: %w", err)
}
settingService := store.NewSettingService(m.l, db)
- config, err := initSetting(settingService)
+ config, err := initSetting(ctx, settingService)
if err != nil {
return fmt.Errorf("failed to init config: %w", err)
}
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 2b4c5d4d13..06fe02957b 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -303,7 +303,7 @@ type ConnectionContext struct {
type Driver interface {
// A driver might support multiple engines (e.g. MySQL driver can support both MySQL and TiDB),
// So we pass the dbType to tell the exact engine.
- Open(dbType Type, config ConnectionConfig, ctx ConnectionContext) (Driver, error)
+ Open(ctx context.Context, dbType Type, config ConnectionConfig, connCtx ConnectionContext) (Driver, error)
// Remember to call Close to avoid connection leak
Close(ctx context.Context) error
Ping(ctx context.Context) error
@@ -346,7 +346,7 @@ func Register(dbType Type, f DriverFunc) {
}
// Open opens a database specified by its database driver type and connection config
-func Open(dbType Type, driverConfig DriverConfig, connectionConfig ConnectionConfig, ctx ConnectionContext) (Driver, error) {
+func Open(ctx context.Context, dbType Type, driverConfig DriverConfig, connectionConfig ConnectionConfig, connCtx ConnectionContext) (Driver, error) {
driversMu.RLock()
f, ok := drivers[dbType]
driversMu.RUnlock()
@@ -354,13 +354,13 @@ func Open(dbType Type, driverConfig DriverConfig, connectionConfig ConnectionCon
return nil, fmt.Errorf("db: unknown driver %v", dbType)
}
- driver, err := f(driverConfig).Open(dbType, connectionConfig, ctx)
+ driver, err := f(driverConfig).Open(ctx, dbType, connectionConfig, connCtx)
if err != nil {
return nil, err
}
- if err := driver.Ping(context.Background()); err != nil {
- driver.Close(context.Background())
+ if err := driver.Ping(ctx); err != nil {
+ driver.Close(ctx)
return nil, err
}
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index a1edd0d91b..7995aa0e3c 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -51,7 +51,7 @@ func newDriver(config db.DriverConfig) db.Driver {
}
}
-func (driver *Driver) Open(dbType db.Type, config db.ConnectionConfig, ctx db.ConnectionContext) (db.Driver, error) {
+func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {
protocol := "tcp"
if strings.HasPrefix(config.Host, "/") {
protocol = "unix"
@@ -86,8 +86,8 @@ func (driver *Driver) Open(dbType db.Type, config db.ConnectionConfig, ctx db.Co
}
driver.l.Debug("Opening MySQL driver",
zap.String("dsn", loggedDSN),
- zap.String("environment", ctx.EnvironmentName),
- zap.String("database", ctx.InstanceName),
+ zap.String("environment", connCtx.EnvironmentName),
+ zap.String("database", connCtx.InstanceName),
)
db, err := sql.Open("mysql", dsn)
if err != nil {
@@ -95,7 +95,7 @@ func (driver *Driver) Open(dbType db.Type, config db.ConnectionConfig, ctx db.Co
}
driver.dbType = dbType
driver.db = db
- driver.connectionCtx = ctx
+ driver.connectionCtx = connCtx
return driver, nil
}
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index 0ea4bd1a40..f9705efff2 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -203,7 +203,7 @@ func newDriver(config db.DriverConfig) db.Driver {
}
}
-func (driver *Driver) Open(dbType db.Type, config db.ConnectionConfig, ctx db.ConnectionContext) (db.Driver, error) {
+func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {
if (config.TlsConfig.SslCert == "" && config.TlsConfig.SslKey != "") ||
(config.TlsConfig.SslCert != "" && config.TlsConfig.SslKey == "") {
return nil, fmt.Errorf("ssl-cert and ssl-key must be both set or unset")
@@ -230,7 +230,7 @@ func (driver *Driver) Open(dbType db.Type, config db.ConnectionConfig, ctx db.Co
}
driver.db = db
driver.baseDSN = dsn
- driver.connectionCtx = ctx
+ driver.connectionCtx = connCtx
return driver, nil
}
diff --git a/server/acl.go b/server/acl.go
index af402fe72d..cce0c538dc 100644
--- a/server/acl.go
+++ b/server/acl.go
@@ -25,6 +25,7 @@ func GetRoleContextKey() string {
func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readonly bool) echo.HandlerFunc {
return func(c echo.Context) error {
+ ctx := context.Background()
// Skips auth, actuator, plan
if strings.HasPrefix(c.Path(), "/api/auth") || strings.HasPrefix(c.Path(), "/api/actuator") || strings.HasPrefix(c.Path(), "/api/plan") {
return next(c)
@@ -41,7 +42,7 @@ func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
memberFind := &api.MemberFind{
PrincipalId: &principalId,
}
- member, err := s.MemberService.FindMember(context.Background(), memberFind)
+ member, err := s.MemberService.FindMember(ctx, memberFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User ID is not a member: %d", principalId))
@@ -69,7 +70,7 @@ func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
activityFind := &api.ActivityFind{
ID: &activityId,
}
- activity, err := s.ActivityService.FindActivity(context.Background(), activityFind)
+ activity, err := s.ActivityService.FindActivity(ctx, activityFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Activity ID not found: %d", activityId))
@@ -90,7 +91,7 @@ func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
bookmarkFind := &api.BookmarkFind{
ID: &bookmarkId,
}
- bookmark, err := s.BookmarkService.FindBookmark(context.Background(), bookmarkFind)
+ bookmark, err := s.BookmarkService.FindBookmark(ctx, bookmarkFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Bookmark ID not found: %d", bookmarkId))
@@ -111,7 +112,7 @@ func ACLMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
inboxFind := &api.InboxFind{
ID: &inboxId,
}
- inbox, err := s.InboxService.FindInbox(context.Background(), inboxFind)
+ inbox, err := s.InboxService.FindInbox(ctx, inboxFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Inbox ID not found: %d", inboxId))
diff --git a/server/activity.go b/server/activity.go
index 7b8ccc50e9..2a7ac6a068 100644
--- a/server/activity.go
+++ b/server/activity.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerActivityRoutes(g *echo.Group) {
g.POST("/activity", func(c echo.Context) error {
+ ctx := context.Background()
activityCreate := &api.ActivityCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, activityCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create activity request").SetInternal(err)
@@ -27,7 +28,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
issueFind := &api.IssueFind{
ID: &activityCreate.ContainerId,
}
- issue, err := s.IssueService.FindIssue(context.Background(), issueFind)
+ issue, err := s.IssueService.FindIssue(ctx, issueFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unable to find issue ID for creating the comment: %d", activityCreate.ContainerId))
@@ -45,14 +46,14 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
foundIssue = issue
}
- activity, err := s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{
+ activity, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{
issue: foundIssue,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
}
- if err := s.ComposeActivityRelationship(context.Background(), activity); err != nil {
+ if err := s.ComposeActivityRelationship(ctx, activity); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created activity relationship").SetInternal(err)
}
@@ -64,6 +65,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
})
g.GET("/activity", func(c echo.Context) error {
+ ctx := context.Background()
activityFind := &api.ActivityFind{}
if containerIdStr := c.QueryParams().Get("container"); containerIdStr != "" {
containerId, err := strconv.Atoi(containerIdStr)
@@ -79,13 +81,13 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
}
activityFind.Limit = &limit
}
- list, err := s.ActivityService.FindActivityList(context.Background(), activityFind)
+ list, err := s.ActivityService.FindActivityList(ctx, activityFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch activity list").SetInternal(err)
}
for _, activity := range list {
- if err := s.ComposeActivityRelationship(context.Background(), activity); err != nil {
+ if err := s.ComposeActivityRelationship(ctx, activity); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch activity relationship: %v", activity.ID)).SetInternal(err)
}
}
@@ -98,6 +100,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
})
g.PATCH("/activity/:activityId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("activityId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("activityId"))).SetInternal(err)
@@ -111,7 +114,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch activity request").SetInternal(err)
}
- activity, err := s.ActivityService.PatchActivity(context.Background(), activityPatch)
+ activity, err := s.ActivityService.PatchActivity(ctx, activityPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Activity ID not found: %d", id))
@@ -119,7 +122,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch activity ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeActivityRelationship(context.Background(), activity); err != nil {
+ if err := s.ComposeActivityRelationship(ctx, activity); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated activity relationship: %v", activity.ID)).SetInternal(err)
}
@@ -131,6 +134,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
})
g.DELETE("/activity/:activityId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("activityId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("activityId"))).SetInternal(err)
@@ -140,7 +144,7 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
ID: id,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- err = s.ActivityService.DeleteActivity(context.Background(), activityDelete)
+ err = s.ActivityService.DeleteActivity(ctx, activityDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Activity ID not found: %d", id))
@@ -157,12 +161,12 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
func (s *Server) ComposeActivityRelationship(ctx context.Context, activity *api.Activity) error {
var err error
- activity.Creator, err = s.ComposePrincipalById(context.Background(), activity.CreatorId)
+ activity.Creator, err = s.ComposePrincipalById(ctx, activity.CreatorId)
if err != nil {
return err
}
- activity.Updater, err = s.ComposePrincipalById(context.Background(), activity.UpdaterId)
+ activity.Updater, err = s.ComposePrincipalById(ctx, activity.UpdaterId)
if err != nil {
return err
}
diff --git a/server/activity_manager.go b/server/activity_manager.go
index 71ec5e149e..6c43888fee 100644
--- a/server/activity_manager.go
+++ b/server/activity_manager.go
@@ -57,7 +57,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
}
if postInbox {
- if err := m.s.PostInboxIssueActivity(context.Background(), meta.issue, activity.ID); err != nil {
+ if err := m.s.PostInboxIssueActivity(ctx, meta.issue, activity.ID); err != nil {
return nil, err
}
}
@@ -66,7 +66,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
ProjectId: &meta.issue.ProjectId,
ActivityType: &create.Type,
}
- hookList, err := m.s.ProjectWebhookService.FindProjectWebhookList(context.Background(), hookFind)
+ hookList, err := m.s.ProjectWebhookService.FindProjectWebhookList(ctx, hookFind)
if err != nil {
return nil, fmt.Errorf("failed to find project webhook after changing the issue status: %v, error: %w", meta.issue.Name, err)
}
@@ -87,7 +87,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
principalFind := &api.PrincipalFind{
ID: &create.CreatorId,
}
- updater, err := m.s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ updater, err := m.s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
return nil, fmt.Errorf("failed to find updater for posting webhook event after changing the issue status: %v, error: %w", meta.issue.Name, err)
}
@@ -139,7 +139,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
principalFind := &api.PrincipalFind{
ID: &oldId,
}
- oldAssignee, err = m.s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ oldAssignee, err = m.s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
m.s.l.Warn("Failed to post webhook event after changing the issue assignee, failed to find old assignee",
zap.String("issue_name", meta.issue.Name),
@@ -161,7 +161,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
principalFind := &api.PrincipalFind{
ID: &newId,
}
- newAssignee, err = m.s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ newAssignee, err = m.s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
m.s.l.Warn("Failed to post webhook event after changing the issue assignee, failed to find new assignee",
zap.String("issue_name", meta.issue.Name),
@@ -198,7 +198,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
taskFind := &api.TaskFind{
ID: &update.TaskId,
}
- task, err := m.s.TaskService.FindTask(context.Background(), taskFind)
+ task, err := m.s.TaskService.FindTask(ctx, taskFind)
if err != nil {
m.s.l.Warn("Failed to post webhook event after changing the issue task status, failed to find task",
zap.String("issue_name", meta.issue.Name),
diff --git a/server/actuator.go b/server/actuator.go
index e0116714cd..988381cf53 100644
--- a/server/actuator.go
+++ b/server/actuator.go
@@ -11,6 +11,7 @@ import (
func (s *Server) registerActuatorRoutes(g *echo.Group) {
g.GET("/actuator/info", func(c echo.Context) error {
+ ctx := context.Background()
serverInfo := api.ServerInfo{
Version: s.version,
Readonly: s.readonly,
@@ -24,7 +25,7 @@ func (s *Server) registerActuatorRoutes(g *echo.Group) {
find := &api.MemberFind{
Role: &findRole,
}
- list, err := s.MemberService.FindMemberList(context.Background(), find)
+ list, err := s.MemberService.FindMemberList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch admin setup status").SetInternal(err)
}
diff --git a/server/anomaly_scanner.go b/server/anomaly_scanner.go
index 8ab0d08937..253fcbb837 100644
--- a/server/anomaly_scanner.go
+++ b/server/anomaly_scanner.go
@@ -49,8 +49,10 @@ func (s *AnomalyScanner) Run() error {
}
}()
+ ctx := context.Background()
+
environmentFind := &api.EnvironmentFind{}
- environmentList, err := s.server.EnvironmentService.FindEnvironmentList(context.Background(), environmentFind)
+ environmentList, err := s.server.EnvironmentService.FindEnvironmentList(ctx, environmentFind)
if err != nil {
s.l.Error("Failed to retrieve instance list", zap.Error(err))
return
@@ -58,7 +60,7 @@ func (s *AnomalyScanner) Run() error {
backupPlanPolicyMap := make(map[int]*api.BackupPlanPolicy)
for _, env := range environmentList {
- policy, err := s.server.PolicyService.GetBackupPlanPolicy(context.Background(), env.ID)
+ policy, err := s.server.PolicyService.GetBackupPlanPolicy(ctx, env.ID)
if err != nil {
s.l.Error("Failed to retrieve backup policy",
zap.String("environment", env.Name),
@@ -72,7 +74,7 @@ func (s *AnomalyScanner) Run() error {
instanceFind := &api.InstanceFind{
RowStatus: &rowStatus,
}
- instanceList, err := s.server.InstanceService.FindInstanceList(context.Background(), instanceFind)
+ instanceList, err := s.server.InstanceService.FindInstanceList(ctx, instanceFind)
if err != nil {
s.l.Error("Failed to retrieve instance list", zap.Error(err))
return
@@ -88,7 +90,7 @@ func (s *AnomalyScanner) Run() error {
}
}
- if err := s.server.ComposeInstanceAdminDataSource(context.Background(), instance); err != nil {
+ if err := s.server.ComposeInstanceAdminDataSource(ctx, instance); err != nil {
s.l.Error("Failed to retrieve instance admin connection info",
zap.String("instance", instance.Name),
zap.Error(err))
@@ -116,12 +118,12 @@ func (s *AnomalyScanner) Run() error {
mu.Unlock()
}()
- s.checkInstanceAnomaly(context.Background(), instance)
+ s.checkInstanceAnomaly(ctx, instance)
databaseFind := &api.DatabaseFind{
InstanceId: &instance.ID,
}
- dbList, err := s.server.DatabaseService.FindDatabaseList(context.Background(), databaseFind)
+ dbList, err := s.server.DatabaseService.FindDatabaseList(ctx, databaseFind)
if err != nil {
s.l.Error("Failed to retrieve database list",
zap.String("instance", instance.Name),
@@ -129,8 +131,8 @@ func (s *AnomalyScanner) Run() error {
return
}
for _, database := range dbList {
- s.checkDatabaseAnomaly(context.Background(), instance, database)
- s.checkBackupAnomaly(context.Background(), instance, database, backupPlanPolicyMap)
+ s.checkDatabaseAnomaly(ctx, instance, database)
+ s.checkBackupAnomaly(ctx, instance, database, backupPlanPolicyMap)
}
}(instance)
@@ -147,7 +149,7 @@ func (s *AnomalyScanner) Run() error {
}
func (s *AnomalyScanner) checkInstanceAnomaly(ctx context.Context, instance *api.Instance) {
- driver, err := GetDatabaseDriver(instance, "", s.l)
+ driver, err := GetDatabaseDriver(ctx, instance, "", s.l)
// Check connection
if err != nil {
@@ -227,7 +229,7 @@ func (s *AnomalyScanner) checkInstanceAnomaly(ctx context.Context, instance *api
}
func (s *AnomalyScanner) checkDatabaseAnomaly(ctx context.Context, instance *api.Instance, database *api.Database) {
- driver, err := GetDatabaseDriver(instance, database.Name, s.l)
+ driver, err := GetDatabaseDriver(ctx, instance, database.Name, s.l)
// Check connection
if err != nil {
diff --git a/server/auth.go b/server/auth.go
index c5ab0a35c3..240d78db55 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerAuthRoutes(g *echo.Group) {
g.POST("/auth/login", func(c echo.Context) error {
+ ctx := context.Background()
login := &api.Login{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, login); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request").SetInternal(err)
@@ -23,7 +24,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
principalFind := &api.PrincipalFind{
Email: &login.Email,
}
- user, err := s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User not found: %s", login.Email))
@@ -34,7 +35,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
memberFind := &api.MemberFind{
PrincipalId: &user.ID,
}
- member, err := s.MemberService.FindMember(context.Background(), memberFind)
+ member, err := s.MemberService.FindMember(ctx, memberFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Member not found: %s", login.Email))
@@ -74,6 +75,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
})
g.POST("/auth/signup", func(c echo.Context) error {
+ ctx := context.Background()
signup := &api.Signup{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, signup); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signup request").SetInternal(err)
@@ -92,7 +94,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
PasswordHash: string(passwordHash),
}
- user, err := s.PrincipalService.CreatePrincipal(context.Background(), principalCreate)
+ user, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Email already exists: %s", signup.Email))
@@ -104,7 +106,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
find := &api.MemberFind{
Role: &findRole,
}
- list, err := s.MemberService.FindMemberList(context.Background(), find)
+ list, err := s.MemberService.FindMemberList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
}
@@ -121,7 +123,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
PrincipalId: user.ID,
}
- member, err := s.MemberService.CreateMember(context.Background(), memberCreate)
+ member, err := s.MemberService.CreateMember(ctx, memberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member already exists: %s", signup.Email))
@@ -147,7 +149,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
Level: api.ACTIVITY_INFO,
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after create member: %d", member.ID)).SetInternal(err)
}
diff --git a/server/backup_runner.go b/server/backup_runner.go
index 34ee519dd0..3c71322759 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -46,14 +46,16 @@ func (s *BackupRunner) Run() error {
s.l.Error("Auto backup runner PANIC RECOVER", zap.Error(err))
}
}()
+
+ ctx := context.Background()
+
// Find all databases that need a backup in this hour.
t := time.Now().UTC().Truncate(time.Hour)
-
match := &api.BackupSettingsMatch{
Hour: t.Hour(),
DayOfWeek: int(t.Weekday()),
}
- list, err := s.server.BackupService.FindBackupSettingsMatch(context.Background(), match)
+ list, err := s.server.BackupService.FindBackupSettingsMatch(ctx, match)
if err != nil {
s.l.Error("Failed to retrieve backup settings match", zap.Error(err))
return
@@ -71,7 +73,7 @@ func (s *BackupRunner) Run() error {
databaseFind := &api.DatabaseFind{
ID: &backupSetting.DatabaseId,
}
- database, err := s.server.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.server.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
s.l.Error("Failed to get database for backup setting",
zap.Int("id", backupSetting.ID),
@@ -92,7 +94,7 @@ func (s *BackupRunner) Run() error {
delete(runningTasks, backupSettingId)
mu.Unlock()
}()
- if err := s.scheduleBackupTask(database, backupName); err != nil {
+ if err := s.scheduleBackupTask(ctx, database, backupName); err != nil {
s.l.Error("Failed to create automatic backup for database",
zap.Int("databaseID", database.ID),
zap.String("error", err.Error()))
@@ -108,14 +110,14 @@ func (s *BackupRunner) Run() error {
return nil
}
-func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName string) error {
+func (s *BackupRunner) scheduleBackupTask(ctx context.Context, database *api.Database, backupName string) error {
path, err := getAndCreateBackupPath(s.server.dataDir, database, backupName)
if err != nil {
return err
}
// Store the migration history version if exists.
- migrationHistoryVersion, err := getMigrationVersion(database, s.l)
+ migrationHistoryVersion, err := getMigrationVersion(ctx, database, s.l)
if err != nil {
return fmt.Errorf("failed to get migration history for database %q: %w", database.Name, err)
}
@@ -130,7 +132,7 @@ func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName str
StorageBackend: api.BackupStorageBackendLocal,
Path: path,
}
- backup, err := s.server.BackupService.CreateBackup(context.Background(), backupCreate)
+ backup, err := s.server.BackupService.CreateBackup(ctx, backupCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
// Automatic backup already exists.
@@ -147,7 +149,7 @@ func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName str
return fmt.Errorf("failed to create task payload: %w", err)
}
- createdPipeline, err := s.server.PipelineService.CreatePipeline(context.Background(), &api.PipelineCreate{
+ createdPipeline, err := s.server.PipelineService.CreatePipeline(ctx, &api.PipelineCreate{
Name: backupName,
CreatorId: backupCreate.CreatorId,
})
@@ -155,7 +157,7 @@ func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName str
return fmt.Errorf("failed to create pipeline: %w", err)
}
- createdStage, err := s.server.StageService.CreateStage(context.Background(), &api.StageCreate{
+ createdStage, err := s.server.StageService.CreateStage(ctx, &api.StageCreate{
Name: backupName,
EnvironmentId: database.Instance.EnvironmentId,
PipelineId: createdPipeline.ID,
@@ -165,7 +167,7 @@ func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName str
return fmt.Errorf("failed to create stage: %w", err)
}
- _, err = s.server.TaskService.CreateTask(context.Background(), &api.TaskCreate{
+ _, err = s.server.TaskService.CreateTask(ctx, &api.TaskCreate{
Name: backupName,
PipelineId: createdPipeline.ID,
StageId: createdStage.ID,
diff --git a/server/bookmark.go b/server/bookmark.go
index 6d71e861e2..b17e0f8937 100644
--- a/server/bookmark.go
+++ b/server/bookmark.go
@@ -14,6 +14,7 @@ import (
func (s *Server) registerBookmarkRoutes(g *echo.Group) {
g.POST("/bookmark", func(c echo.Context) error {
+ ctx := context.Background()
bookmarkCreate := &api.BookmarkCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, bookmarkCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create bookmark request").SetInternal(err)
@@ -21,7 +22,7 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
bookmarkCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
- bookmark, err := s.BookmarkService.CreateBookmark(context.Background(), bookmarkCreate)
+ bookmark, err := s.BookmarkService.CreateBookmark(ctx, bookmarkCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Bookmark already exists: %s", bookmarkCreate.Link))
@@ -29,7 +30,7 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create bookmark").SetInternal(err)
}
- if err := s.ComposeBookmarkRelationship(context.Background(), bookmark); err != nil {
+ if err := s.ComposeBookmarkRelationship(ctx, bookmark); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created bookmark relationship").SetInternal(err)
}
@@ -41,17 +42,18 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
})
g.GET("/bookmark", func(c echo.Context) error {
+ ctx := context.Background()
creatorId := c.Get(GetPrincipalIdContextKey()).(int)
bookmarkFind := &api.BookmarkFind{
CreatorId: &creatorId,
}
- list, err := s.BookmarkService.FindBookmarkList(context.Background(), bookmarkFind)
+ list, err := s.BookmarkService.FindBookmarkList(ctx, bookmarkFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch bookmark list").SetInternal(err)
}
for _, bookmark := range list {
- if err := s.ComposeBookmarkRelationship(context.Background(), bookmark); err != nil {
+ if err := s.ComposeBookmarkRelationship(ctx, bookmark); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch bookmark relationship: %v", bookmark.Name)).SetInternal(err)
}
}
@@ -64,6 +66,7 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
})
g.DELETE("/bookmark/:bookmarkId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("bookmarkId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("bookmarkId"))).SetInternal(err)
@@ -73,7 +76,7 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
ID: id,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- err = s.BookmarkService.DeleteBookmark(context.Background(), bookmarkDelete)
+ err = s.BookmarkService.DeleteBookmark(ctx, bookmarkDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Bookmark ID not found: %d", id))
@@ -95,7 +98,7 @@ func (s *Server) ComposeBookmarkRelationship(ctx context.Context, bookmark *api.
return err
}
- bookmark.Updater, err = s.ComposePrincipalById(context.Background(), bookmark.UpdaterId)
+ bookmark.Updater, err = s.ComposePrincipalById(ctx, bookmark.UpdaterId)
if err != nil {
return err
}
diff --git a/server/database.go b/server/database.go
index ea77c4f9e4..d5d3f88ad0 100644
--- a/server/database.go
+++ b/server/database.go
@@ -18,6 +18,7 @@ import (
func (s *Server) registerDatabaseRoutes(g *echo.Group) {
g.POST("/database", func(c echo.Context) error {
+ ctx := context.Background()
databaseCreate := &api.DatabaseCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, databaseCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create database request").SetInternal(err)
@@ -27,13 +28,13 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
databaseCreate.TimezoneName = z
databaseCreate.TimezoneOffset = offset
- instance, err := s.InstanceService.FindInstance(context.Background(), &api.InstanceFind{ID: &databaseCreate.InstanceId})
+ instance, err := s.InstanceService.FindInstance(ctx, &api.InstanceFind{ID: &databaseCreate.InstanceId})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find instance").SetInternal(err)
}
databaseCreate.EnvironmentId = instance.EnvironmentId
- database, err := s.DatabaseService.CreateDatabase(context.Background(), databaseCreate)
+ database, err := s.DatabaseService.CreateDatabase(ctx, databaseCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Database name already exists: %s", databaseCreate.Name))
@@ -41,7 +42,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create database").SetInternal(err)
}
- if err := s.ComposeDatabaseRelationship(context.Background(), database); err != nil {
+ if err := s.ComposeDatabaseRelationship(ctx, database); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created database relationship").SetInternal(err)
}
@@ -53,6 +54,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database", func(c echo.Context) error {
+ ctx := context.Background()
databaseFind := &api.DatabaseFind{}
if instanceIdStr := c.QueryParam("instance"); instanceIdStr != "" {
instanceId, err := strconv.Atoi(instanceIdStr)
@@ -69,7 +71,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
databaseFind.ProjectId = &projectId
}
- list, err := s.ComposeDatabaseListByFind(context.Background(), databaseFind)
+ list, err := s.ComposeDatabaseListByFind(ctx, databaseFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch database list").SetInternal(err)
}
@@ -105,6 +107,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database/:id", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -113,7 +116,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -129,6 +132,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.PATCH("/database/:id", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Database ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -146,7 +150,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
// the old project and new project.
var existingDatabase *api.Database
if databasePatch.ProjectId != nil {
- existingDatabase, err = s.DatabaseService.FindDatabase(context.Background(), &api.DatabaseFind{
+ existingDatabase, err = s.DatabaseService.FindDatabase(ctx, &api.DatabaseFind{
ID: &databasePatch.ID,
})
if err != nil {
@@ -157,7 +161,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
}
- database, err := s.DatabaseService.PatchDatabase(context.Background(), databasePatch)
+ database, err := s.DatabaseService.PatchDatabase(ctx, databasePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -165,7 +169,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch database ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeDatabaseRelationship(context.Background(), database); err != nil {
+ if err := s.ComposeDatabaseRelationship(ctx, database); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated database relationship: %v", database.Name)).SetInternal(err)
}
@@ -176,7 +180,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseName: database.Name,
})
if err == nil {
- existingDatabase.Project, err = s.ComposeProjectlById(context.Background(), existingDatabase.ProjectId)
+ existingDatabase.Project, err = s.ComposeProjectlById(ctx, existingDatabase.ProjectId)
if err == nil {
activityCreate := &api.ActivityCreate{
CreatorId: c.Get(GetPrincipalIdContextKey()).(int),
@@ -187,7 +191,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
database.Name, database.Project.Name),
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
}
if err != nil {
@@ -209,7 +213,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
existingDatabase.Name, existingDatabase.Project.Name),
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
s.l.Warn("Failed to create project activity after transferring database",
zap.Int("database_id", database.ID),
@@ -230,6 +234,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database/:id/table", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -238,7 +243,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -249,7 +254,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
tableFind := &api.TableFind{
DatabaseId: &id,
}
- tableList, err := s.TableService.FindTableList(context.Background(), tableFind)
+ tableList, err := s.TableService.FindTableList(ctx, tableFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch table list for database id: %d", id)).SetInternal(err)
}
@@ -260,7 +265,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseId: &id,
TableId: &table.ID,
}
- table.ColumnList, err = s.ColumnService.FindColumnList(context.Background(), columnFind)
+ table.ColumnList, err = s.ColumnService.FindColumnList(ctx, columnFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch colmun list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
}
@@ -269,7 +274,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseId: &id,
TableId: &table.ID,
}
- table.IndexList, err = s.IndexService.FindIndexList(context.Background(), indexFind)
+ table.IndexList, err = s.IndexService.FindIndexList(ctx, indexFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch index list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
}
@@ -283,6 +288,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database/:id/table/:tableName", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -291,7 +297,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -304,7 +310,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseId: &id,
Name: &tableName,
}
- table, err := s.TableService.FindTable(context.Background(), tableFind)
+ table, err := s.TableService.FindTable(ctx, tableFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch table for database id: %d, table name: %s", id, tableName)).SetInternal(err)
}
@@ -315,7 +321,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseId: &id,
TableId: &table.ID,
}
- table.ColumnList, err = s.ColumnService.FindColumnList(context.Background(), columnFind)
+ table.ColumnList, err = s.ColumnService.FindColumnList(ctx, columnFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch colmun list for database id: %d, table name: %s", id, tableName)).SetInternal(err)
}
@@ -324,7 +330,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
DatabaseId: &id,
TableId: &table.ID,
}
- table.IndexList, err = s.IndexService.FindIndexList(context.Background(), indexFind)
+ table.IndexList, err = s.IndexService.FindIndexList(ctx, indexFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch index list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
}
@@ -337,6 +343,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.POST("/database/:id/backup", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -351,7 +358,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -364,20 +371,20 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create backup directory for database ID: %v", id)).SetInternal(err)
}
- version, err := getMigrationVersion(database, s.l)
+ version, err := getMigrationVersion(ctx, database, s.l)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get migration history for database %q", database.Name)).SetInternal(err)
}
backupCreate.MigrationHistoryVersion = version
- backup, err := s.BackupService.CreateBackup(context.Background(), backupCreate)
+ backup, err := s.BackupService.CreateBackup(ctx, backupCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Backup name already exists: %s", backupCreate.Name))
}
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup").SetInternal(err)
}
- if err := s.ComposeBackupRelationship(context.Background(), backup); err != nil {
+ if err := s.ComposeBackupRelationship(ctx, backup); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose backup relationship").SetInternal(err)
}
@@ -389,7 +396,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup task payload").SetInternal(err)
}
- createdPipeline, err := s.PipelineService.CreatePipeline(context.Background(), &api.PipelineCreate{
+ createdPipeline, err := s.PipelineService.CreatePipeline(ctx, &api.PipelineCreate{
Name: fmt.Sprintf("backup-pipeline-%s", backup.Name),
CreatorId: backupCreate.CreatorId,
})
@@ -397,7 +404,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup pipeline").SetInternal(err)
}
- createdStage, err := s.StageService.CreateStage(context.Background(), &api.StageCreate{
+ createdStage, err := s.StageService.CreateStage(ctx, &api.StageCreate{
Name: fmt.Sprintf("backup-stage-%s", backup.Name),
EnvironmentId: database.Instance.EnvironmentId,
PipelineId: createdPipeline.ID,
@@ -407,7 +414,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup stage").SetInternal(err)
}
- _, err = s.TaskService.CreateTask(context.Background(), &api.TaskCreate{
+ _, err = s.TaskService.CreateTask(ctx, &api.TaskCreate{
Name: fmt.Sprintf("backup-task-%s", backup.Name),
PipelineId: createdPipeline.ID,
StageId: createdStage.ID,
@@ -430,6 +437,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database/:id/backup", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -438,7 +446,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- _, err = s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ _, err = s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -449,13 +457,13 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
backupFind := &api.BackupFind{
DatabaseId: &id,
}
- backupList, err := s.BackupService.FindBackupList(context.Background(), backupFind)
+ backupList, err := s.BackupService.FindBackupList(ctx, backupFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to backup list for database id: %d", id)).SetInternal(err)
}
for _, backup := range backupList {
- if err := s.ComposeBackupRelationship(context.Background(), backup); err != nil {
+ if err := s.ComposeBackupRelationship(ctx, backup); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose backup relationship").SetInternal(err)
}
}
@@ -468,6 +476,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.PATCH("/database/:id/backupsetting", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -482,7 +491,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- db, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ db, err := s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -491,7 +500,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
backupSettingUpsert.EnvironmentId = db.Instance.Environment.ID
- backupSetting, err := s.BackupService.UpsertBackupSetting(context.Background(), backupSettingUpsert)
+ backupSetting, err := s.BackupService.UpsertBackupSetting(ctx, backupSettingUpsert)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to set backup setting").SetInternal(err)
}
@@ -504,6 +513,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
g.GET("/database/:id/backupsetting", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -512,7 +522,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
databaseFind := &api.DatabaseFind{
ID: &id,
}
- _, err = s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ _, err = s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -523,7 +533,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
backupSettingFind := &api.BackupSettingFind{
DatabaseId: &id,
}
- backupSetting, err := s.BackupService.FindBackupSetting(context.Background(), backupSettingFind)
+ backupSetting, err := s.BackupService.FindBackupSetting(ctx, backupSettingFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
// Returns the backup setting with UNKNOWN_ID to indicate the database has no backup
@@ -544,7 +554,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
func (s *Server) ComposeDatabaseByFind(ctx context.Context, find *api.DatabaseFind) (*api.Database, error) {
- database, err := s.DatabaseService.FindDatabase(context.Background(), find)
+ database, err := s.DatabaseService.FindDatabase(ctx, find)
if err != nil {
return nil, err
}
@@ -557,13 +567,13 @@ func (s *Server) ComposeDatabaseByFind(ctx context.Context, find *api.DatabaseFi
}
func (s *Server) ComposeDatabaseListByFind(ctx context.Context, find *api.DatabaseFind) ([]*api.Database, error) {
- list, err := s.DatabaseService.FindDatabaseList(context.Background(), find)
+ list, err := s.DatabaseService.FindDatabaseList(ctx, find)
if err != nil {
return nil, err
}
for _, database := range list {
- if err := s.ComposeDatabaseRelationship(context.Background(), database); err != nil {
+ if err := s.ComposeDatabaseRelationship(ctx, database); err != nil {
return nil, err
}
}
@@ -574,28 +584,28 @@ func (s *Server) ComposeDatabaseListByFind(ctx context.Context, find *api.Databa
func (s *Server) ComposeDatabaseRelationship(ctx context.Context, database *api.Database) error {
var err error
- database.Creator, err = s.ComposePrincipalById(context.Background(), database.CreatorId)
+ database.Creator, err = s.ComposePrincipalById(ctx, database.CreatorId)
if err != nil {
return err
}
- database.Updater, err = s.ComposePrincipalById(context.Background(), database.UpdaterId)
+ database.Updater, err = s.ComposePrincipalById(ctx, database.UpdaterId)
if err != nil {
return err
}
- database.Project, err = s.ComposeProjectlById(context.Background(), database.ProjectId)
+ database.Project, err = s.ComposeProjectlById(ctx, database.ProjectId)
if err != nil {
return err
}
- database.Instance, err = s.ComposeInstanceById(context.Background(), database.InstanceId)
+ database.Instance, err = s.ComposeInstanceById(ctx, database.InstanceId)
if err != nil {
return err
}
if database.SourceBackupId != 0 {
- database.SourceBackup, err = s.ComposeBackupByID(context.Background(), database.SourceBackupId)
+ database.SourceBackup, err = s.ComposeBackupByID(ctx, database.SourceBackupId)
if err != nil {
return err
}
@@ -604,7 +614,7 @@ func (s *Server) ComposeDatabaseRelationship(ctx context.Context, database *api.
database.DataSourceList = []*api.DataSource{}
rowStatus := api.Normal
- database.AnomalyList, err = s.AnomalyService.FindAnomalyList(context.Background(), &api.AnomalyFind{
+ database.AnomalyList, err = s.AnomalyService.FindAnomalyList(ctx, &api.AnomalyFind{
RowStatus: &rowStatus,
DatabaseId: &database.ID,
})
@@ -612,11 +622,11 @@ func (s *Server) ComposeDatabaseRelationship(ctx context.Context, database *api.
return err
}
for _, anomaly := range database.AnomalyList {
- anomaly.Creator, err = s.ComposePrincipalById(context.Background(), anomaly.CreatorId)
+ anomaly.Creator, err = s.ComposePrincipalById(ctx, anomaly.CreatorId)
if err != nil {
return err
}
- anomaly.Updater, err = s.ComposePrincipalById(context.Background(), anomaly.UpdaterId)
+ anomaly.Updater, err = s.ComposePrincipalById(ctx, anomaly.UpdaterId)
if err != nil {
return err
}
@@ -658,8 +668,9 @@ func (s *Server) ComposeBackupRelationship(ctx context.Context, backup *api.Back
// Retrieve db.Driver connection.
// Upon successful return, caller MUST call driver.Close, otherwise, it will leak the database connection.
-func GetDatabaseDriver(instance *api.Instance, databaseName string, logger *zap.Logger) (db.Driver, error) {
+func GetDatabaseDriver(ctx context.Context, instance *api.Instance, databaseName string, logger *zap.Logger) (db.Driver, error) {
driver, err := db.Open(
+ ctx,
instance.Engine,
db.DriverConfig{Logger: logger},
db.ConnectionConfig{
diff --git a/server/environment.go b/server/environment.go
index 35950090d2..afe39b6ff8 100644
--- a/server/environment.go
+++ b/server/environment.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
g.POST("/environment", func(c echo.Context) error {
+ ctx := context.Background()
environmentCreate := &api.EnvironmentCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, environmentCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create environment request").SetInternal(err)
@@ -22,7 +23,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
environmentCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
- environment, err := s.EnvironmentService.CreateEnvironment(context.Background(), environmentCreate)
+ environment, err := s.EnvironmentService.CreateEnvironment(ctx, environmentCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Environment name already exists: %s", environmentCreate.Name))
@@ -30,7 +31,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create environment").SetInternal(err)
}
- if err := s.ComposeEnvironmentRelationship(context.Background(), environment); err != nil {
+ if err := s.ComposeEnvironmentRelationship(ctx, environment); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created environment relationship").SetInternal(err)
}
@@ -42,18 +43,19 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
})
g.GET("/environment", func(c echo.Context) error {
+ ctx := context.Background()
environmentFind := &api.EnvironmentFind{}
if rowStatusStr := c.QueryParam("rowstatus"); rowStatusStr != "" {
rowStatus := api.RowStatus(rowStatusStr)
environmentFind.RowStatus = &rowStatus
}
- list, err := s.EnvironmentService.FindEnvironmentList(context.Background(), environmentFind)
+ list, err := s.EnvironmentService.FindEnvironmentList(ctx, environmentFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch environment list").SetInternal(err)
}
for _, environment := range list {
- if err := s.ComposeEnvironmentRelationship(context.Background(), environment); err != nil {
+ if err := s.ComposeEnvironmentRelationship(ctx, environment); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment relationship: %v", environment.Name)).SetInternal(err)
}
}
@@ -66,6 +68,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
})
g.PATCH("/environment/:id", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -79,7 +82,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch environment request").SetInternal(err)
}
- environment, err := s.EnvironmentService.PatchEnvironment(context.Background(), environmentPatch)
+ environment, err := s.EnvironmentService.PatchEnvironment(ctx, environmentPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", id))
@@ -87,7 +90,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch environment ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeEnvironmentRelationship(context.Background(), environment); err != nil {
+ if err := s.ComposeEnvironmentRelationship(ctx, environment); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated environment relationship: %v", environment.Name)).SetInternal(err)
}
@@ -99,6 +102,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
})
g.PATCH("/environment/reorder", func(c echo.Context) error {
+ ctx := context.Background()
patchList, err := jsonapi.UnmarshalManyPayload(c.Request().Body, reflect.TypeOf(new(api.EnvironmentPatch)))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted environment reorder request").SetInternal(err)
@@ -107,7 +111,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
for _, item := range patchList {
environmentPatch, _ := item.(*api.EnvironmentPatch)
environmentPatch.UpdaterId = c.Get(GetPrincipalIdContextKey()).(int)
- _, err = s.EnvironmentService.PatchEnvironment(context.Background(), environmentPatch)
+ _, err = s.EnvironmentService.PatchEnvironment(ctx, environmentPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", environmentPatch.ID))
@@ -117,13 +121,13 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
}
environmentFind := &api.EnvironmentFind{}
- list, err := s.EnvironmentService.FindEnvironmentList(context.Background(), environmentFind)
+ list, err := s.EnvironmentService.FindEnvironmentList(ctx, environmentFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch environment list for reorder").SetInternal(err)
}
for _, environment := range list {
- if err := s.ComposeEnvironmentRelationship(context.Background(), environment); err != nil {
+ if err := s.ComposeEnvironmentRelationship(ctx, environment); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch reordered environment relationship: %v", environment.Name)).SetInternal(err)
}
}
@@ -140,7 +144,7 @@ func (s *Server) ComposeEnvironmentById(ctx context.Context, id int) (*api.Envir
environmentFind := &api.EnvironmentFind{
ID: &id,
}
- environment, err := s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ environment, err := s.EnvironmentService.FindEnvironment(ctx, environmentFind)
if err != nil {
return nil, err
}
@@ -155,12 +159,12 @@ func (s *Server) ComposeEnvironmentById(ctx context.Context, id int) (*api.Envir
func (s *Server) ComposeEnvironmentRelationship(ctx context.Context, environment *api.Environment) error {
var err error
- environment.Creator, err = s.ComposePrincipalById(context.Background(), environment.CreatorId)
+ environment.Creator, err = s.ComposePrincipalById(ctx, environment.CreatorId)
if err != nil {
return err
}
- environment.Updater, err = s.ComposePrincipalById(context.Background(), environment.UpdaterId)
+ environment.Updater, err = s.ComposePrincipalById(ctx, environment.UpdaterId)
if err != nil {
return err
}
diff --git a/server/inbox.go b/server/inbox.go
index dcf60e6886..ea971af1b4 100644
--- a/server/inbox.go
+++ b/server/inbox.go
@@ -14,6 +14,7 @@ import (
func (s *Server) registerInboxRoutes(g *echo.Group) {
g.GET("/inbox", func(c echo.Context) error {
+ ctx := context.Background()
inboxFind := &api.InboxFind{}
userIdStr := c.QueryParams().Get("user")
if userIdStr != "" {
@@ -31,13 +32,13 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
}
inboxFind.ReadCreatedAfterTs = &createdTs
}
- list, err := s.InboxService.FindInboxList(context.Background(), inboxFind)
+ list, err := s.InboxService.FindInboxList(ctx, 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 {
+ if err := s.ComposeActivityRelationship(ctx, inbox.Activity); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch inbox activity relationship: %v", inbox.Activity.ID)).SetInternal(err)
}
}
@@ -50,6 +51,7 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
})
g.GET("/inbox/summary", func(c echo.Context) error {
+ ctx := context.Background()
userIdStr := c.QueryParams().Get("user")
if userIdStr == "" {
return echo.NewHTTPError(http.StatusBadRequest, "Missing query parameter user")
@@ -59,7 +61,7 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter user is not a number: %s", userIdStr)).SetInternal(err)
}
- summary, err := s.InboxService.FindInboxSummary(context.Background(), userId)
+ summary, err := s.InboxService.FindInboxSummary(ctx, userId)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch inbox summary for user ID: %d", userId)).SetInternal(err)
}
@@ -68,6 +70,7 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
})
g.PATCH("/inbox/:inboxId", func(c echo.Context) error {
+ ctx := context.Background()
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)
@@ -80,7 +83,7 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch inbox request").SetInternal(err)
}
- inbox, err := s.InboxService.PatchInbox(context.Background(), inboxPatch)
+ inbox, err := s.InboxService.PatchInbox(ctx, inboxPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Inbox ID not found: %d", id))
@@ -88,7 +91,7 @@ func (s *Server) registerInboxRoutes(g *echo.Group) {
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 {
+ if err := s.ComposeActivityRelationship(ctx, inbox.Activity); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated inbox activity relationship: %v", inbox.ID)).SetInternal(err)
}
diff --git a/server/instance.go b/server/instance.go
index deec6320bb..a50a0c6699 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -16,6 +16,7 @@ import (
func (s *Server) registerInstanceRoutes(g *echo.Group) {
// Besides adding the instance to Bytebase, it will also try to create a "bytebase" db in the newly added instance.
g.POST("/instance", func(c echo.Context) error {
+ ctx := context.Background()
instanceCreate := &api.InstanceCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, instanceCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create instance request").SetInternal(err)
@@ -23,7 +24,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
instanceCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
- instance, err := s.InstanceService.CreateInstance(context.Background(), instanceCreate)
+ instance, err := s.InstanceService.CreateInstance(ctx, instanceCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Instance name already exists: %s", instanceCreate.Name))
@@ -31,19 +32,19 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)
}
- if err := s.ComposeInstanceRelationship(context.Background(), instance); err != nil {
+ if err := s.ComposeInstanceRelationship(ctx, instance); err != nil {
return err
}
// Try creating the "bytebase" db in the added instance if needed.
// Since we allow user to add new instance upfront even providing the incorrect username/password,
// thus it's OK if it fails. Frontend will surface relavant info suggesting the "bytebase" db hasn't created yet.
- db, err := GetDatabaseDriver(instance, "", s.l)
+ db, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err == nil {
- defer db.Close(context.Background())
- db.SetupMigrationIfNeeded(context.Background())
+ defer db.Close(ctx)
+ db.SetupMigrationIfNeeded(ctx)
// Try immediately sync the engine version and schema after instance creation.
- s.SyncEngineVersionAndSchema(instance)
+ s.SyncEngineVersionAndSchema(ctx, instance)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -54,18 +55,19 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance", func(c echo.Context) error {
+ ctx := context.Background()
instanceFind := &api.InstanceFind{}
if rowStatusStr := c.QueryParam("rowstatus"); rowStatusStr != "" {
rowStatus := api.RowStatus(rowStatusStr)
instanceFind.RowStatus = &rowStatus
}
- list, err := s.InstanceService.FindInstanceList(context.Background(), instanceFind)
+ list, err := s.InstanceService.FindInstanceList(ctx, instanceFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch instance list").SetInternal(err)
}
for _, instance := range list {
- if err := s.ComposeInstanceRelationship(context.Background(), instance); err != nil {
+ if err := s.ComposeInstanceRelationship(ctx, instance); err != nil {
return err
}
}
@@ -78,12 +80,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance/:instanceId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), id)
+ instance, err := s.ComposeInstanceById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -99,6 +102,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.PATCH("/instance/:instanceId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
@@ -114,7 +118,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
var instance *api.Instance
if instancePatch.RowStatus != nil || instancePatch.Name != nil || instancePatch.ExternalLink != nil || instancePatch.Host != nil || instancePatch.Port != nil {
- instance, err = s.InstanceService.PatchInstance(context.Background(), instancePatch)
+ instance, err = s.InstanceService.PatchInstance(ctx, instancePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -127,7 +131,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
instanceFind := &api.InstanceFind{
ID: &id,
}
- instance, err = s.InstanceService.FindInstance(context.Background(), instanceFind)
+ instance, err = s.InstanceService.FindInstance(ctx, instanceFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -140,7 +144,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
InstanceId: &instance.ID,
Type: &dataSourceType,
}
- adminDataSource, err := s.DataSourceService.FindDataSource(context.Background(), dataSourceFind)
+ adminDataSource, err := s.DataSourceService.FindDataSource(ctx, dataSourceFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch data source for instance: %v", instance.Name)).SetInternal(err)
}
@@ -151,23 +155,23 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
Username: instancePatch.Username,
Password: instancePatch.Password,
}
- _, err = s.DataSourceService.PatchDataSource(context.Background(), dataSourcePatch)
+ _, err = s.DataSourceService.PatchDataSource(ctx, dataSourcePatch)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch data source for instance: %v", instance.Name)).SetInternal(err)
}
}
- if err := s.ComposeInstanceRelationship(context.Background(), instance); err != nil {
+ if err := s.ComposeInstanceRelationship(ctx, instance); err != nil {
return err
}
// Try immediately setup the migration schema, sync the engine version and schema after updating any connection related info.
if instancePatch.Host != nil || instancePatch.Port != nil || instancePatch.Username != nil || instancePatch.Password != nil {
- db, err := GetDatabaseDriver(instance, "", s.l)
+ db, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err == nil {
- defer db.Close(context.Background())
- db.SetupMigrationIfNeeded(context.Background())
- s.SyncEngineVersionAndSchema(instance)
+ defer db.Close(ctx)
+ db.SetupMigrationIfNeeded(ctx)
+ s.SyncEngineVersionAndSchema(ctx, instance)
}
}
@@ -179,6 +183,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance/:instanceId/user", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
@@ -187,7 +192,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
instanceUserFind := &api.InstanceUserFind{
InstanceId: id,
}
- list, err := s.InstanceUserService.FindInstanceUserList(context.Background(), instanceUserFind)
+ list, err := s.InstanceUserService.FindInstanceUserList(ctx, instanceUserFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch user list for instance: %v", id)).SetInternal(err)
}
@@ -200,12 +205,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.POST("/instance/:instanceId/migration", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), id)
+ instance, err := s.ComposeInstanceById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -215,6 +221,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
resultSet := &api.SqlResultSet{}
db, err := db.Open(
+ ctx,
instance.Engine,
db.DriverConfig{Logger: s.l},
db.ConnectionConfig{
@@ -231,8 +238,8 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
if err != nil {
resultSet.Error = err.Error()
} else {
- defer db.Close(context.Background())
- if err := db.SetupMigrationIfNeeded(context.Background()); err != nil {
+ defer db.Close(ctx)
+ if err := db.SetupMigrationIfNeeded(ctx); err != nil {
resultSet.Error = err.Error()
}
}
@@ -245,12 +252,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance/:instanceId/migration/status", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), id)
+ instance, err := s.ComposeInstanceById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -259,13 +267,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
}
instanceMigration := &api.InstanceMigration{}
- db, err := GetDatabaseDriver(instance, "", s.l)
+ db, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err != nil {
instanceMigration.Status = api.InstanceMigrationSchemaUnknown
instanceMigration.Error = err.Error()
} else {
- defer db.Close(context.Background())
- setup, err := db.NeedsSetupMigration(context.Background())
+ defer db.Close(ctx)
+ setup, err := db.NeedsSetupMigration(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to check migration setup status for host:port: %v:%v", instance.Host, instance.Port)).SetInternal(err)
}
@@ -284,6 +292,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance/:instanceId/migration/history/:historyId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Intance ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
@@ -294,7 +303,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("History ID is not a number: %s", c.Param("historyId"))).SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), id)
+ instance, err := s.ComposeInstanceById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -303,12 +312,12 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
}
find := &db.MigrationHistoryFind{ID: &historyId}
- driver, err := GetDatabaseDriver(instance, "", s.l)
+ driver, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history ID %d for instance %q", id, instance.Name)).SetInternal(err)
}
- defer driver.Close(context.Background())
- list, err := driver.FindMigrationHistoryList(context.Background(), find)
+ defer driver.Close(ctx)
+ list, err := driver.FindMigrationHistoryList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
}
@@ -344,12 +353,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
g.GET("/instance/:instanceId/migration/history", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("instanceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), id)
+ instance, err := s.ComposeInstanceById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -375,12 +385,12 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
}
historyList := []*api.MigrationHistory{}
- driver, err := GetDatabaseDriver(instance, "", s.l)
+ driver, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history for instance %q", instance.Name)).SetInternal(err)
}
- defer driver.Close(context.Background())
- list, err := driver.FindMigrationHistoryList(context.Background(), find)
+ defer driver.Close(ctx)
+ list, err := driver.FindMigrationHistoryList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
}
@@ -420,7 +430,7 @@ func (s *Server) ComposeInstanceById(ctx context.Context, id int) (*api.Instance
instanceFind := &api.InstanceFind{
ID: &id,
}
- instance, err := s.InstanceService.FindInstance(context.Background(), instanceFind)
+ instance, err := s.InstanceService.FindInstance(ctx, instanceFind)
if err != nil {
return nil, err
}
@@ -435,23 +445,23 @@ func (s *Server) ComposeInstanceById(ctx context.Context, id int) (*api.Instance
func (s *Server) ComposeInstanceRelationship(ctx context.Context, instance *api.Instance) error {
var err error
- instance.Creator, err = s.ComposePrincipalById(context.Background(), instance.CreatorId)
+ instance.Creator, err = s.ComposePrincipalById(ctx, instance.CreatorId)
if err != nil {
return err
}
- instance.Updater, err = s.ComposePrincipalById(context.Background(), instance.UpdaterId)
+ instance.Updater, err = s.ComposePrincipalById(ctx, instance.UpdaterId)
if err != nil {
return err
}
- instance.Environment, err = s.ComposeEnvironmentById(context.Background(), instance.EnvironmentId)
+ instance.Environment, err = s.ComposeEnvironmentById(ctx, instance.EnvironmentId)
if err != nil {
return err
}
rowStatus := api.Normal
- instance.AnomalyList, err = s.AnomalyService.FindAnomalyList(context.Background(), &api.AnomalyFind{
+ instance.AnomalyList, err = s.AnomalyService.FindAnomalyList(ctx, &api.AnomalyFind{
RowStatus: &rowStatus,
InstanceId: &instance.ID,
InstanceOnly: true,
@@ -460,24 +470,24 @@ func (s *Server) ComposeInstanceRelationship(ctx context.Context, instance *api.
return err
}
for _, anomaly := range instance.AnomalyList {
- anomaly.Creator, err = s.ComposePrincipalById(context.Background(), anomaly.CreatorId)
+ anomaly.Creator, err = s.ComposePrincipalById(ctx, anomaly.CreatorId)
if err != nil {
return err
}
- anomaly.Updater, err = s.ComposePrincipalById(context.Background(), anomaly.UpdaterId)
+ anomaly.Updater, err = s.ComposePrincipalById(ctx, anomaly.UpdaterId)
if err != nil {
return err
}
}
- return s.ComposeInstanceAdminDataSource(context.Background(), instance)
+ return s.ComposeInstanceAdminDataSource(ctx, instance)
}
func (s *Server) ComposeInstanceAdminDataSource(ctx context.Context, instance *api.Instance) error {
dataSourceFind := &api.DataSourceFind{
InstanceId: &instance.ID,
}
- dataSourceList, err := s.DataSourceService.FindDataSourceList(context.Background(), dataSourceFind)
+ dataSourceList, err := s.DataSourceService.FindDataSourceList(ctx, dataSourceFind)
if err != nil {
return err
}
@@ -495,7 +505,7 @@ func (s *Server) FindInstanceAdminPasswordById(ctx context.Context, instanceId i
dataSourceFind := &api.DataSourceFind{
InstanceId: &instanceId,
}
- dataSourceList, err := s.DataSourceService.FindDataSourceList(context.Background(), dataSourceFind)
+ dataSourceList, err := s.DataSourceService.FindDataSourceList(ctx, dataSourceFind)
if err != nil {
return "", err
}
diff --git a/server/issue.go b/server/issue.go
index fa79915a12..4590bf7a6e 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -16,6 +16,7 @@ import (
func (s *Server) registerIssueRoutes(g *echo.Group) {
g.POST("/issue", func(c echo.Context) error {
+ ctx := context.Background()
issueCreate := &api.IssueCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, issueCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create issue request").SetInternal(err)
@@ -59,7 +60,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
}
}
- issue, err := s.CreateIssue(context.Background(), issueCreate, c.Get(GetPrincipalIdContextKey()).(int))
+ issue, err := s.CreateIssue(ctx, issueCreate, c.Get(GetPrincipalIdContextKey()).(int))
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create issue").SetInternal(err)
}
@@ -69,7 +70,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
IssueId: issue.ID,
SubscriberId: subscriberId,
}
- _, err := s.IssueSubscriberService.CreateIssueSubscriber(context.Background(), subscriberCreate)
+ _, err := s.IssueSubscriberService.CreateIssueSubscriber(ctx, subscriberCreate)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to add subscriber %d after creating issue %d", subscriberId, issue.ID)).SetInternal(err)
}
@@ -83,6 +84,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
})
g.GET("/issue", func(c echo.Context) error {
+ ctx := context.Background()
issueFind := &api.IssueFind{}
projectIdStr := c.QueryParams().Get("project")
if projectIdStr != "" {
@@ -114,13 +116,13 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
}
issueFind.PrincipalId = &userId
}
- list, err := s.IssueService.FindIssueList(context.Background(), issueFind)
+ list, err := s.IssueService.FindIssueList(ctx, issueFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch issue list").SetInternal(err)
}
for _, issue := range list {
- if err := s.ComposeIssueRelationship(context.Background(), issue); err != nil {
+ if err := s.ComposeIssueRelationship(ctx, issue); err != nil {
return err
}
}
@@ -133,12 +135,13 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
})
g.GET("/issue/:issueId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
}
- issue, err := s.ComposeIssueById(context.Background(), id)
+ issue, err := s.ComposeIssueById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue ID not found: %d", id))
@@ -154,6 +157,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
})
g.PATCH("/issue/:issueId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
@@ -170,7 +174,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
issueFind := &api.IssueFind{
ID: &id,
}
- issue, err := s.IssueService.FindIssue(context.Background(), issueFind)
+ issue, err := s.IssueService.FindIssue(ctx, issueFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Unable to find issue ID to update: %d", id))
@@ -178,7 +182,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue ID when updating issue: %v", id)).SetInternal(err)
}
- updatedIssue, err := s.IssueService.PatchIssue(context.Background(), issuePatch)
+ updatedIssue, err := s.IssueService.PatchIssue(ctx, issuePatch)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update issue ID: %v", id)).SetInternal(err)
}
@@ -229,7 +233,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
Level: api.ACTIVITY_INFO,
Payload: string(payload),
}
- _, err := s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{
+ _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{
issue: issue,
})
if err != nil {
@@ -237,7 +241,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
}
}
- if err := s.ComposeIssueRelationship(context.Background(), updatedIssue); err != nil {
+ if err := s.ComposeIssueRelationship(ctx, updatedIssue); err != nil {
return err
}
@@ -249,6 +253,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
})
g.PATCH("/issue/:issueId/status", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
@@ -262,7 +267,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update issue status request").SetInternal(err)
}
- issue, err := s.ComposeIssueById(context.Background(), id)
+ issue, err := s.ComposeIssueById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue ID not found: %d", id))
@@ -270,7 +275,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue ID: %v", id)).SetInternal(err)
}
- updatedIssue, err := s.ChangeIssueStatus(context.Background(), issue, issueStatusPatch.Status, issueStatusPatch.UpdaterId, issueStatusPatch.Comment)
+ updatedIssue, err := s.ChangeIssueStatus(ctx, issue, issueStatusPatch.Status, issueStatusPatch.UpdaterId, issueStatusPatch.Comment)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound).SetInternal(err)
@@ -280,7 +285,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
}
- if err := s.ComposeIssueRelationship(context.Background(), updatedIssue); err != nil {
+ if err := s.ComposeIssueRelationship(ctx, updatedIssue); err != nil {
return err
}
@@ -296,7 +301,7 @@ func (s *Server) ComposeIssueById(ctx context.Context, id int) (*api.Issue, erro
issueFind := &api.IssueFind{
ID: &id,
}
- issue, err := s.IssueService.FindIssue(context.Background(), issueFind)
+ issue, err := s.IssueService.FindIssue(ctx, issueFind)
if err != nil {
return nil, err
}
@@ -311,17 +316,17 @@ func (s *Server) ComposeIssueById(ctx context.Context, id int) (*api.Issue, erro
func (s *Server) ComposeIssueRelationship(ctx context.Context, issue *api.Issue) error {
var err error
- issue.Creator, err = s.ComposePrincipalById(context.Background(), issue.CreatorId)
+ issue.Creator, err = s.ComposePrincipalById(ctx, issue.CreatorId)
if err != nil {
return err
}
- issue.Updater, err = s.ComposePrincipalById(context.Background(), issue.UpdaterId)
+ issue.Updater, err = s.ComposePrincipalById(ctx, issue.UpdaterId)
if err != nil {
return err
}
- issue.Assignee, err = s.ComposePrincipalById(context.Background(), issue.AssigneeId)
+ issue.Assignee, err = s.ComposePrincipalById(ctx, issue.AssigneeId)
if err != nil {
return err
}
@@ -329,7 +334,7 @@ func (s *Server) ComposeIssueRelationship(ctx context.Context, issue *api.Issue)
issueSubscriberFind := &api.IssueSubscriberFind{
IssueId: &issue.ID,
}
- list, err := s.IssueSubscriberService.FindIssueSubscriberList(context.Background(), issueSubscriberFind)
+ list, err := s.IssueSubscriberService.FindIssueSubscriberList(ctx, issueSubscriberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch subscriber list for issue %d", issue.ID)).SetInternal(err)
}
@@ -339,12 +344,12 @@ func (s *Server) ComposeIssueRelationship(ctx context.Context, issue *api.Issue)
issue.SubscriberIdList = append(issue.SubscriberIdList, subscriber.SubscriberId)
}
- issue.Project, err = s.ComposeProjectlById(context.Background(), issue.ProjectId)
+ issue.Project, err = s.ComposeProjectlById(ctx, issue.ProjectId)
if err != nil {
return err
}
- issue.Pipeline, err = s.ComposePipelineById(context.Background(), issue.PipelineId)
+ issue.Pipeline, err = s.ComposePipelineById(ctx, issue.PipelineId)
if err != nil {
return err
}
@@ -362,7 +367,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
for _, stageCreate := range issueCreate.Pipeline.StageList {
stageCreate.CreatorId = creatorId
stageCreate.PipelineId = createdPipeline.ID
- createdStage, err := s.StageService.CreateStage(context.Background(), &stageCreate)
+ createdStage, err := s.StageService.CreateStage(ctx, &stageCreate)
if err != nil {
return nil, fmt.Errorf("failed to create stage for issue. Error %w", err)
}
@@ -408,7 +413,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
}
taskCreate.Payload = string(bytes)
}
- _, err := s.TaskService.CreateTask(context.Background(), &taskCreate)
+ _, err := s.TaskService.CreateTask(ctx, &taskCreate)
if err != nil {
return nil, fmt.Errorf("failed to create task for issue. Error %w", err)
}
@@ -417,7 +422,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
issueCreate.CreatorId = creatorId
issueCreate.PipelineId = createdPipeline.ID
- issue, err := s.IssueService.CreateIssue(context.Background(), issueCreate)
+ issue, err := s.IssueService.CreateIssue(ctx, issueCreate)
if err != nil {
return nil, fmt.Errorf("failed to create issue. Error %w", err)
}
@@ -440,7 +445,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
Level: api.ACTIVITY_INFO,
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{
issue: issue,
})
if err != nil {
@@ -470,7 +475,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
Comment: fmt.Sprintf("Created rollback issue %q", issue.Name),
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{
issue: rollbackIssue,
})
if err != nil {
@@ -478,11 +483,11 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
}
}
- if err := s.ComposeIssueRelationship(context.Background(), issue); err != nil {
+ if err := s.ComposeIssueRelationship(ctx, issue); err != nil {
return nil, err
}
- if _, err := s.ScheduleNextTaskIfNeeded(context.Background(), issue.Pipeline); err != nil {
+ if _, err := s.ScheduleNextTaskIfNeeded(ctx, issue.Pipeline); err != nil {
return nil, fmt.Errorf("failed to schedule task after creating the issue: %v. Error %w", issue.Name, err)
}
@@ -511,7 +516,7 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
for _, stage := range issue.Pipeline.StageList {
for _, task := range stage.TaskList {
if task.Status == api.TaskRunning {
- if _, err := s.ChangeTaskStatus(context.Background(), task, api.TaskCanceled, updaterId); err != nil {
+ if _, err := s.ChangeTaskStatus(ctx, task, api.TaskCanceled, updaterId); err != nil {
return nil, fmt.Errorf("failed to cancel issue: %v, failed to cancel task: %v, error: %w", issue.Name, task.Name, err)
}
}
@@ -525,7 +530,7 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
UpdaterId: updaterId,
Status: &pipelineStatus,
}
- if _, err := s.PipelineService.PatchPipeline(context.Background(), pipelinePatch); err != nil {
+ if _, err := s.PipelineService.PatchPipeline(ctx, pipelinePatch); err != nil {
return nil, fmt.Errorf("failed to update issue status: %v, failed to update pipeline status: %w", issue.Name, err)
}
@@ -534,7 +539,7 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
UpdaterId: updaterId,
Status: &newStatus,
}
- updatedIssue, err := s.IssueService.PatchIssue(context.Background(), issuePatch)
+ updatedIssue, err := s.IssueService.PatchIssue(ctx, issuePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return nil, fmt.Errorf("failed to update issue status: %v, error: %w", issue.Name, err)
@@ -560,7 +565,7 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
Payload: string(payload),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{
issue: updatedIssue,
})
if err != nil {
@@ -576,7 +581,7 @@ func (s *Server) PostInboxIssueActivity(ctx context.Context, issue *api.Issue, a
ReceiverId: issue.CreatorId,
ActivityId: activity_id,
}
- _, err := s.InboxService.CreateInbox(context.Background(), inboxCreate)
+ _, err := s.InboxService.CreateInbox(ctx, inboxCreate)
if err != nil {
return fmt.Errorf("failed to post activity to creator inbox: %d, error: %w", issue.CreatorId, err)
}
@@ -587,7 +592,7 @@ func (s *Server) PostInboxIssueActivity(ctx context.Context, issue *api.Issue, a
ReceiverId: issue.AssigneeId,
ActivityId: activity_id,
}
- _, err := s.InboxService.CreateInbox(context.Background(), inboxCreate)
+ _, err := s.InboxService.CreateInbox(ctx, inboxCreate)
if err != nil {
return fmt.Errorf("failed to post activity to assignee inbox: %d, error: %w", issue.AssigneeId, err)
}
@@ -599,7 +604,7 @@ func (s *Server) PostInboxIssueActivity(ctx context.Context, issue *api.Issue, a
ReceiverId: subscriberId,
ActivityId: activity_id,
}
- _, err := s.InboxService.CreateInbox(context.Background(), inboxCreate)
+ _, err := s.InboxService.CreateInbox(ctx, inboxCreate)
if err != nil {
return fmt.Errorf("failed to post activity to subscriber inbox: %d, error: %w", subscriberId, err)
}
diff --git a/server/issue_subscriber.go b/server/issue_subscriber.go
index 2ec415f957..0c8e7e502e 100644
--- a/server/issue_subscriber.go
+++ b/server/issue_subscriber.go
@@ -14,6 +14,7 @@ import (
func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
g.POST("/issue/:issueId/subscriber", func(c echo.Context) error {
+ ctx := context.Background()
issueId, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
@@ -26,7 +27,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
issueSubscriberCreate.IssueId = issueId
- issueSubscriber, err := s.IssueSubscriberService.CreateIssueSubscriber(context.Background(), issueSubscriberCreate)
+ issueSubscriber, err := s.IssueSubscriberService.CreateIssueSubscriber(ctx, issueSubscriberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Subscriber %d already exists in issue %d", issueSubscriberCreate.SubscriberId, issueSubscriberCreate.IssueId))
@@ -34,7 +35,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to add subscriber %d to issue %d", issueSubscriberCreate.SubscriberId, issueSubscriberCreate.IssueId)).SetInternal(err)
}
- if err := s.ComposeIssueSubscriberRelationship(context.Background(), issueSubscriber); err != nil {
+ if err := s.ComposeIssueSubscriberRelationship(ctx, issueSubscriber); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch subscriber %d relationship for issue %d", issueSubscriberCreate.SubscriberId, issueSubscriberCreate.IssueId)).SetInternal(err)
}
@@ -46,6 +47,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
})
g.GET("/issue/:issueId/subscriber", func(c echo.Context) error {
+ ctx := context.Background()
issueId, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
@@ -54,13 +56,13 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
issueSubscriberFind := &api.IssueSubscriberFind{
IssueId: &issueId,
}
- list, err := s.IssueSubscriberService.FindIssueSubscriberList(context.Background(), issueSubscriberFind)
+ list, err := s.IssueSubscriberService.FindIssueSubscriberList(ctx, issueSubscriberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch subscriber list for issue %d", issueId)).SetInternal(err)
}
for _, issueSubscriber := range list {
- if err := s.ComposeIssueSubscriberRelationship(context.Background(), issueSubscriber); err != nil {
+ if err := s.ComposeIssueSubscriberRelationship(ctx, issueSubscriber); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch subscriber %d relationship for issue %d", issueSubscriber.SubscriberId, issueSubscriber.IssueId)).SetInternal(err)
}
}
@@ -73,6 +75,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
})
g.DELETE("/issue/:issueId/subscriber/:subscriberId", func(c echo.Context) error {
+ ctx := context.Background()
issueId, err := strconv.Atoi(c.Param("issueId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Issue ID is not a number: %s", c.Param("issueId"))).SetInternal(err)
@@ -87,7 +90,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
IssueId: issueId,
SubscriberId: subscriberId,
}
- err = s.IssueSubscriberService.DeleteIssueSubscriber(context.Background(), issueSubscriberDelete)
+ err = s.IssueSubscriberService.DeleteIssueSubscriber(ctx, issueSubscriberDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Subscriber %d not found in issue %d", subscriberId, issueId))
diff --git a/server/jwt.go b/server/jwt.go
index 57e45aedb7..0a75f0acbc 100644
--- a/server/jwt.go
+++ b/server/jwt.go
@@ -209,6 +209,7 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc,
// We either have a valid access token or we will attempt to generate new access token and refresh token
if err == nil {
+ ctx := context.Background()
principalId, err := strconv.Atoi(claims.Subject)
if err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, "Malformatted ID in the token.")
@@ -218,7 +219,7 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc,
principalFind := &api.PrincipalFind{
ID: &principalId,
}
- user, err := p.FindPrincipal(context.Background(), principalFind)
+ user, err := p.FindPrincipal(ctx, principalFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", principalId))
diff --git a/server/member.go b/server/member.go
index 2a93285f84..57a46d3f67 100644
--- a/server/member.go
+++ b/server/member.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerMemberRoutes(g *echo.Group) {
g.POST("/member", func(c echo.Context) error {
+ ctx := context.Background()
memberCreate := &api.MemberCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, memberCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create member request").SetInternal(err)
@@ -22,7 +23,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
memberCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
- member, err := s.MemberService.CreateMember(context.Background(), memberCreate)
+ member, err := s.MemberService.CreateMember(ctx, memberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member for user ID already exists: %d", memberCreate.PrincipalId))
@@ -35,7 +36,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
principalFind := &api.PrincipalFind{
ID: &member.PrincipalId,
}
- user, err := s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", member.PrincipalId))
@@ -60,13 +61,13 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
Level: api.ACTIVITY_INFO,
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after creating member: %d", member.ID)).SetInternal(err)
}
}
- if err := s.ComposeMemberRelationship(context.Background(), member); err != nil {
+ if err := s.ComposeMemberRelationship(ctx, member); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created member relationship").SetInternal(err)
}
@@ -78,14 +79,15 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
})
g.GET("/member", func(c echo.Context) error {
+ ctx := context.Background()
memberFind := &api.MemberFind{}
- list, err := s.MemberService.FindMemberList(context.Background(), memberFind)
+ list, err := s.MemberService.FindMemberList(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch member list").SetInternal(err)
}
for _, member := range list {
- if err := s.ComposeMemberRelationship(context.Background(), member); err != nil {
+ if err := s.ComposeMemberRelationship(ctx, member); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch member relationship: %v", member.ID)).SetInternal(err)
}
}
@@ -98,6 +100,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
})
g.PATCH("/member/:id", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -106,7 +109,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
memberFind := &api.MemberFind{
ID: &id,
}
- member, err := s.MemberService.FindMember(context.Background(), memberFind)
+ member, err := s.MemberService.FindMember(ctx, memberFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find member ID: %d", id))
@@ -122,7 +125,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch member request").SetInternal(err)
}
- updatedMember, err := s.MemberService.PatchMember(context.Background(), memberPatch)
+ updatedMember, err := s.MemberService.PatchMember(ctx, memberPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Member ID not found: %d", id))
@@ -135,7 +138,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
principalFind := &api.PrincipalFind{
ID: &updatedMember.PrincipalId,
}
- user, err := s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", updatedMember.PrincipalId))
@@ -161,7 +164,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
Level: api.ACTIVITY_INFO,
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after changing member role: %d", updatedMember.ID)).SetInternal(err)
}
@@ -186,14 +189,14 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
Level: api.ACTIVITY_INFO,
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after changing member role: %d", updatedMember.ID)).SetInternal(err)
}
}
}
- if err := s.ComposeMemberRelationship(context.Background(), updatedMember); err != nil {
+ if err := s.ComposeMemberRelationship(ctx, updatedMember); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated member relationship: %v", updatedMember.ID)).SetInternal(err)
}
@@ -213,12 +216,12 @@ func (s *Server) ComposeMemberRelationship(ctx context.Context, member *api.Memb
return err
}
- member.Updater, err = s.ComposePrincipalById(context.Background(), member.UpdaterId)
+ member.Updater, err = s.ComposePrincipalById(ctx, member.UpdaterId)
if err != nil {
return err
}
- member.Principal, err = s.ComposePrincipalById(context.Background(), member.PrincipalId)
+ member.Principal, err = s.ComposePrincipalById(ctx, member.PrincipalId)
if err != nil {
return err
}
diff --git a/server/pipeline.go b/server/pipeline.go
index 319ceaac91..63f5b3c998 100644
--- a/server/pipeline.go
+++ b/server/pipeline.go
@@ -10,7 +10,7 @@ func (s *Server) ComposePipelineById(ctx context.Context, id int) (*api.Pipeline
pipelineFind := &api.PipelineFind{
ID: &id,
}
- pipeline, err := s.PipelineService.FindPipeline(context.Background(), pipelineFind)
+ pipeline, err := s.PipelineService.FindPipeline(ctx, pipelineFind)
if err != nil {
return nil, err
}
@@ -25,17 +25,17 @@ func (s *Server) ComposePipelineById(ctx context.Context, id int) (*api.Pipeline
func (s *Server) ComposePipelineRelationship(ctx context.Context, pipeline *api.Pipeline) error {
var err error
- pipeline.Creator, err = s.ComposePrincipalById(context.Background(), pipeline.CreatorId)
+ pipeline.Creator, err = s.ComposePrincipalById(ctx, pipeline.CreatorId)
if err != nil {
return err
}
- pipeline.Updater, err = s.ComposePrincipalById(context.Background(), pipeline.UpdaterId)
+ pipeline.Updater, err = s.ComposePrincipalById(ctx, pipeline.UpdaterId)
if err != nil {
return err
}
- pipeline.StageList, err = s.ComposeStageListByPipelineId(context.Background(), pipeline.ID)
+ pipeline.StageList, err = s.ComposeStageListByPipelineId(ctx, pipeline.ID)
if err != nil {
return err
}
@@ -62,7 +62,7 @@ func (s *Server) ScheduleNextTaskIfNeeded(ctx context.Context, pipeline *api.Pip
if _, err := s.TaskCheckScheduler.ScheduleCheckIfNeeded(ctx, task, api.SYSTEM_BOT_ID, skipIfAlreadyTerminated); err != nil {
return nil, err
}
- updatedTask, err := s.TaskScheduler.ScheduleIfNeeded(context.Background(), task)
+ updatedTask, err := s.TaskScheduler.ScheduleIfNeeded(ctx, task)
if err != nil {
return nil, err
}
diff --git a/server/policy.go b/server/policy.go
index 33fcd6303e..2e1794bd1e 100644
--- a/server/policy.go
+++ b/server/policy.go
@@ -13,6 +13,7 @@ import (
func (s *Server) registerPolicyRoutes(g *echo.Group) {
g.PATCH("/policy/environment/:environmentId", func(c echo.Context) error {
+ ctx := context.Background()
environmentID, err := strconv.Atoi(c.Param("environmentId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("environmentID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -30,12 +31,12 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
policyUpsert.Type = pType
policyUpsert.UpdaterId = c.Get(GetPrincipalIdContextKey()).(int)
- policy, err := s.PolicyService.UpsertPolicy(context.Background(), policyUpsert)
+ policy, err := s.PolicyService.UpsertPolicy(ctx, policyUpsert)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to set policy for type %q", pType)).SetInternal(err)
}
- if err := s.ComposePolicyRelationship(context.Background(), policy); err != nil {
+ if err := s.ComposePolicyRelationship(ctx, policy); err != nil {
return err
}
@@ -47,6 +48,7 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
})
g.GET("/policy/environment/:environmentId", func(c echo.Context) error {
+ ctx := context.Background()
environmentID, err := strconv.Atoi(c.Param("environmentId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("environmentID is not a number: %s", c.Param("id"))).SetInternal(err)
@@ -59,12 +61,12 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
policyFind.Type = &pType
policyFind.EnvironmentId = &environmentID
- policy, err := s.PolicyService.FindPolicy(context.Background(), policyFind)
+ policy, err := s.PolicyService.FindPolicy(ctx, policyFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get policy for type %q", pType)).SetInternal(err)
}
- if err := s.ComposePolicyRelationship(context.Background(), policy); err != nil {
+ if err := s.ComposePolicyRelationship(ctx, policy); err != nil {
return err
}
@@ -79,17 +81,17 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
func (s *Server) ComposePolicyRelationship(ctx context.Context, policy *api.Policy) error {
var err error
- policy.Creator, err = s.ComposePrincipalById(context.Background(), policy.CreatorId)
+ policy.Creator, err = s.ComposePrincipalById(ctx, policy.CreatorId)
if err != nil {
return err
}
- policy.Updater, err = s.ComposePrincipalById(context.Background(), policy.UpdaterId)
+ policy.Updater, err = s.ComposePrincipalById(ctx, policy.UpdaterId)
if err != nil {
return err
}
- policy.Environment, err = s.ComposeEnvironmentById(context.Background(), policy.EnvironmentId)
+ policy.Environment, err = s.ComposeEnvironmentById(ctx, policy.EnvironmentId)
if err != nil {
return err
}
diff --git a/server/principal.go b/server/principal.go
index 7669e34878..a778751269 100644
--- a/server/principal.go
+++ b/server/principal.go
@@ -16,6 +16,7 @@ import (
func (s *Server) registerPrincipalRoutes(g *echo.Group) {
g.POST("/principal", func(c echo.Context) error {
+ ctx := context.Background()
principalCreate := &api.PrincipalCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, principalCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create principal request").SetInternal(err)
@@ -29,7 +30,7 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
}
principalCreate.PasswordHash = string(passwordHash)
- principal, err := s.PrincipalService.CreatePrincipal(context.Background(), principalCreate)
+ principal, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, "User already exists")
@@ -47,14 +48,15 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
})
g.GET("/principal", func(c echo.Context) error {
- list, err := s.PrincipalService.FindPrincipalList(context.Background())
+ ctx := context.Background()
+ list, err := s.PrincipalService.FindPrincipalList(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal list").SetInternal(err)
}
filteredList := []*api.Principal{}
for _, principal := range list {
- if err := s.ComposePrincipalRole(context.Background(), principal); err != nil {
+ if err := s.ComposePrincipalRole(ctx, principal); err != nil {
// Normally this should not happen since we create the member together with the principal
// and we don't allow deleting the member. Just in case.
if common.ErrorCode(err) == common.NotFound {
@@ -77,12 +79,13 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
})
g.GET("/principal/:principalId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("principalId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("principalId"))).SetInternal(err)
}
- principal, err := s.ComposePrincipalById(context.Background(), id)
+ principal, err := s.ComposePrincipalById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", id))
@@ -98,6 +101,7 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
})
g.PATCH("/principal/:principalId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("principalId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("principalId"))).SetInternal(err)
@@ -119,14 +123,14 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
principalPatch.PasswordHash = &passwordHashStr
}
- principal, err := s.PrincipalService.PatchPrincipal(context.Background(), principalPatch)
+ principal, err := s.PrincipalService.PatchPrincipal(ctx, principalPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", id))
}
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch principal ID: %v", id)).SetInternal(err)
}
- if err := s.ComposePrincipalRole(context.Background(), principal); err != nil {
+ if err := s.ComposePrincipalRole(ctx, principal); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch role for principal: %v", principal.Name)).SetInternal(err)
}
@@ -142,7 +146,7 @@ func (s *Server) ComposePrincipalById(ctx context.Context, id int) (*api.Princip
principalFind := &api.PrincipalFind{
ID: &id,
}
- principal, err := s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ principal, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
if err != nil {
return nil, err
}
@@ -159,7 +163,7 @@ func (s *Server) ComposePrincipalRole(ctx context.Context, principal *api.Princi
memberFind := &api.MemberFind{
PrincipalId: &principal.ID,
}
- member, err := s.MemberService.FindMember(context.Background(), memberFind)
+ member, err := s.MemberService.FindMember(ctx, memberFind)
if err != nil {
return err
}
diff --git a/server/project.go b/server/project.go
index 1962b124f2..fc71d6937a 100644
--- a/server/project.go
+++ b/server/project.go
@@ -20,12 +20,13 @@ import (
func (s *Server) registerProjectRoutes(g *echo.Group) {
g.POST("/project", func(c echo.Context) error {
+ ctx := context.Background()
projectCreate := &api.ProjectCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, projectCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create project request").SetInternal(err)
}
projectCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
- project, err := s.ProjectService.CreateProject(context.Background(), projectCreate)
+ project, err := s.ProjectService.CreateProject(ctx, projectCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project name already exists: %s", projectCreate.Name))
@@ -40,12 +41,12 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
PrincipalId: projectCreate.CreatorId,
}
- _, err = s.ProjectMemberService.CreateProjectMember(context.Background(), projectMember)
+ _, err = s.ProjectMemberService.CreateProjectMember(ctx, projectMember)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to add owner after creating project").SetInternal(err)
}
- if err := s.ComposeProjectRelationship(context.Background(), project); err != nil {
+ if err := s.ComposeProjectRelationship(ctx, project); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch relationship after creating project").SetInternal(err)
}
@@ -57,6 +58,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
})
g.GET("/project", func(c echo.Context) error {
+ ctx := context.Background()
projectFind := &api.ProjectFind{}
if userIdStr := c.QueryParam("user"); userIdStr != "" {
userId, err := strconv.Atoi(userIdStr)
@@ -69,13 +71,13 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
rowStatus := api.RowStatus(rowStatusStr)
projectFind.RowStatus = &rowStatus
}
- list, err := s.ProjectService.FindProjectList(context.Background(), projectFind)
+ list, err := s.ProjectService.FindProjectList(ctx, projectFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch project list").SetInternal(err)
}
for _, project := range list {
- if err := s.ComposeProjectRelationship(context.Background(), project); err != nil {
+ if err := s.ComposeProjectRelationship(ctx, project); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project relationship: %v", project.Name)).SetInternal(err)
}
}
@@ -88,12 +90,13 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
})
g.GET("/project/:projectId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
}
- project, err := s.ComposeProjectlById(context.Background(), id)
+ project, err := s.ComposeProjectlById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", id))
@@ -109,6 +112,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
})
g.PATCH("/project/:projectId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -122,7 +126,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch project request").SetInternal(err)
}
- project, err := s.ProjectService.PatchProject(context.Background(), projectPatch)
+ project, err := s.ProjectService.PatchProject(ctx, projectPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", id))
@@ -130,7 +134,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch project ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeProjectRelationship(context.Background(), project); err != nil {
+ if err := s.ComposeProjectRelationship(ctx, project); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated project relationship: %v", project.Name)).SetInternal(err)
}
@@ -143,6 +147,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// When we link the repository with the project, we will also change the project workflow type to VCS
g.POST("/project/:projectId/repository", func(c echo.Context) error {
+ ctx := context.Background()
repositoryCreate := &api.RepositoryCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create linked repository request").SetInternal(err)
@@ -159,7 +164,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
vcsFind := &api.VCSFind{
ID: &repositoryCreate.VCSId,
}
- vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ vcs, err := s.VCSService.FindVCS(ctx, vcsFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", repositoryCreate.VCSId))
@@ -208,7 +213,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
// Remove enclosing /
repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")
- repository, err := s.RepositoryService.CreateRepository(context.Background(), repositoryCreate)
+ repository, err := s.RepositoryService.CreateRepository(ctx, repositoryCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project %d has already linked repository", repositoryCreate.ProjectId))
@@ -216,7 +221,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)
}
- if err := s.ComposeRepositoryRelationship(context.Background(), repository); err != nil {
+ if err := s.ComposeRepositoryRelationship(ctx, repository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create project").SetInternal(err)
}
@@ -231,6 +236,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// 1. repository also contains project, which would cause circular dependency when composing it.
// 2. repository info is only needed when fetching a particular project by id, thus it's unnecessary to include it in the project list response.
g.GET("/project/:projectId/repository", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -239,7 +245,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
ProjectId: &projectId,
}
- list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
+ list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)
}
@@ -250,7 +256,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
for _, repository := range list {
- if err := s.ComposeRepositoryRelationship(context.Background(), repository); err != nil {
+ if err := s.ComposeRepositoryRelationship(ctx, repository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)
}
}
@@ -264,6 +270,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// When we unlink the repository with the project, we will also change the project workflow type to UI
g.PATCH("/project/:projectId/repository", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -297,7 +304,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
ProjectId: &projectId,
}
- list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
+ list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)
}
@@ -311,7 +318,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repository := list[0]
repositoryPatch.ID = repository.ID
- updatedRepository, err := s.RepositoryService.PatchRepository(context.Background(), repositoryPatch)
+ updatedRepository, err := s.RepositoryService.PatchRepository(ctx, repositoryPatch)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectId)).SetInternal(err)
}
@@ -320,7 +327,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
vcsFind := &api.VCSFind{
ID: &repository.VCSId,
}
- vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ vcs, err := s.VCSService.FindVCS(ctx, vcsFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectId)).SetInternal(err)
}
@@ -358,7 +365,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
}
- if err := s.ComposeRepositoryRelationship(context.Background(), updatedRepository); err != nil {
+ if err := s.ComposeRepositoryRelationship(ctx, updatedRepository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to updating repository for project").SetInternal(err)
}
@@ -371,6 +378,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// When we unlink the repository with the project, we will also change the project workflow type to UI
g.DELETE("/project/:projectId/repository", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -379,7 +387,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
ProjectId: &projectId,
}
- list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
+ list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)
}
@@ -395,7 +403,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
vcsFind := &api.VCSFind{
ID: &repository.VCSId,
}
- vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ vcs, err := s.VCSService.FindVCS(ctx, vcsFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectId)).SetInternal(err)
}
@@ -404,7 +412,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
ProjectId: projectId,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- if err := s.RepositoryService.DeleteRepository(context.Background(), repositoryDelete); err != nil {
+ if err := s.RepositoryService.DeleteRepository(ctx, repositoryDelete); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectId)).SetInternal(err)
}
@@ -455,12 +463,12 @@ func (s *Server) ComposeProjectlById(ctx context.Context, id int) (*api.Project,
func (s *Server) ComposeProjectRelationship(ctx context.Context, project *api.Project) error {
var err error
- project.Creator, err = s.ComposePrincipalById(context.Background(), project.CreatorId)
+ project.Creator, err = s.ComposePrincipalById(ctx, project.CreatorId)
if err != nil {
return err
}
- project.Updater, err = s.ComposePrincipalById(context.Background(), project.UpdaterId)
+ project.Updater, err = s.ComposePrincipalById(ctx, project.UpdaterId)
if err != nil {
return err
}
diff --git a/server/project_member.go b/server/project_member.go
index c5a5106a30..1ec888ed0f 100644
--- a/server/project_member.go
+++ b/server/project_member.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
g.POST("/project/:projectId/member", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -28,7 +29,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create project membership request").SetInternal(err)
}
- projectMember, err := s.ProjectMemberService.CreateProjectMember(context.Background(), projectMemberCreate)
+ projectMember, err := s.ProjectMemberService.CreateProjectMember(ctx, projectMemberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, "User is already a project member")
@@ -36,7 +37,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create project member").SetInternal(err)
}
- if err := s.ComposeProjectMemberRelationship(context.Background(), projectMember); err != nil {
+ if err := s.ComposeProjectMemberRelationship(ctx, projectMember); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created project membership relationship").SetInternal(err)
}
@@ -49,7 +50,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
Comment: fmt.Sprintf("Granted %s to %s (%s).",
projectMember.Principal.Name, projectMember.Principal.Email, projectMember.Role),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
s.l.Warn("Failed to create project activity after creating member",
zap.Int("project_id", projectId),
@@ -68,6 +69,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
})
g.PATCH("/project/:projectId/member/:memberId", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -78,7 +80,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memberId"))).SetInternal(err)
}
- existingProjectMember, err := s.ProjectMemberService.FindProjectMember(context.Background(), &api.ProjectMemberFind{ID: &id})
+ existingProjectMember, err := s.ProjectMemberService.FindProjectMember(ctx, &api.ProjectMemberFind{ID: &id})
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project member ID not found: %d", id))
@@ -94,7 +96,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted change project membership").SetInternal(err)
}
- projectMember, err := s.ProjectMemberService.PatchProjectMember(context.Background(), projectMemberPatch)
+ projectMember, err := s.ProjectMemberService.PatchProjectMember(ctx, projectMemberPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project member ID not found: %d", id))
@@ -102,7 +104,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change project membership ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeProjectMemberRelationship(context.Background(), projectMember); err != nil {
+ if err := s.ComposeProjectMemberRelationship(ctx, projectMember); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch updated project membership relationship").SetInternal(err)
}
@@ -115,7 +117,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
Comment: fmt.Sprintf("Changed %s (%s) from %s to %s.",
projectMember.Principal.Name, projectMember.Principal.Email, existingProjectMember.Role, projectMember.Role),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
s.l.Warn("Failed to create project activity after updating member role",
zap.Int("project_id", projectId),
@@ -135,6 +137,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
})
g.DELETE("/project/:projectId/member/:memberId", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -145,7 +148,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memberId"))).SetInternal(err)
}
- projectMember, err := s.ProjectMemberService.FindProjectMember(context.Background(), &api.ProjectMemberFind{ID: &id})
+ projectMember, err := s.ProjectMemberService.FindProjectMember(ctx, &api.ProjectMemberFind{ID: &id})
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project member ID not found: %d", id))
@@ -157,7 +160,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
ID: id,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- err = s.ProjectMemberService.DeleteProjectMember(context.Background(), projectMemberDelete)
+ err = s.ProjectMemberService.DeleteProjectMember(ctx, projectMemberDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project member ID not found: %d", id))
@@ -166,7 +169,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
}
{
- projectMember.Principal, err = s.ComposePrincipalById(context.Background(), projectMember.PrincipalId)
+ projectMember.Principal, err = s.ComposePrincipalById(ctx, projectMember.PrincipalId)
if err == nil {
activityCreate := &api.ActivityCreate{
CreatorId: c.Get(GetPrincipalIdContextKey()).(int),
@@ -176,7 +179,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
Comment: fmt.Sprintf("Revoked %s from %s (%s).",
projectMember.Role, projectMember.Principal.Name, projectMember.Principal.Email),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
}
if err != nil {
s.l.Warn("Failed to create project activity after deleting member",
@@ -214,17 +217,17 @@ func (s *Server) ComposeProjectMemberListByProjectId(ctx context.Context, projec
func (s *Server) ComposeProjectMemberRelationship(ctx context.Context, projectMember *api.ProjectMember) error {
var err error
- projectMember.Creator, err = s.ComposePrincipalById(context.Background(), projectMember.CreatorId)
+ projectMember.Creator, err = s.ComposePrincipalById(ctx, projectMember.CreatorId)
if err != nil {
return err
}
- projectMember.Updater, err = s.ComposePrincipalById(context.Background(), projectMember.UpdaterId)
+ projectMember.Updater, err = s.ComposePrincipalById(ctx, projectMember.UpdaterId)
if err != nil {
return err
}
- projectMember.Principal, err = s.ComposePrincipalById(context.Background(), projectMember.PrincipalId)
+ projectMember.Principal, err = s.ComposePrincipalById(ctx, projectMember.PrincipalId)
if err != nil {
return err
}
diff --git a/server/project_webhook.go b/server/project_webhook.go
index 433fa65176..12a9e64932 100644
--- a/server/project_webhook.go
+++ b/server/project_webhook.go
@@ -16,6 +16,7 @@ import (
func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
g.GET("/project/:projectId/webhook", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -24,13 +25,13 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
find := &api.ProjectWebhookFind{
ProjectId: &projectId,
}
- list, err := s.ProjectWebhookService.FindProjectWebhookList(context.Background(), find)
+ list, err := s.ProjectWebhookService.FindProjectWebhookList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch webhook list for project ID: %d", projectId)).SetInternal(err)
}
for _, hook := range list {
- if err := s.ComposeProjectWebhookRelationship(context.Background(), hook); err != nil {
+ if err := s.ComposeProjectWebhookRelationship(ctx, hook); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch webhook relationship: %v", hook.Name)).SetInternal(err)
}
}
@@ -43,6 +44,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
})
g.POST("/project/:projectId/webhook", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -56,7 +58,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create project webhook request").SetInternal(err)
}
- hook, err := s.ProjectWebhookService.CreateProjectWebhook(context.Background(), hookCreate)
+ hook, err := s.ProjectWebhookService.CreateProjectWebhook(ctx, hookCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Webhook url already exists in the project: %s", hookCreate.URL))
@@ -64,7 +66,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create project webhook").SetInternal(err)
}
- if err := s.ComposeProjectWebhookRelationship(context.Background(), hook); err != nil {
+ if err := s.ComposeProjectWebhookRelationship(ctx, hook); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch webhook relationship").SetInternal(err)
}
@@ -76,6 +78,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
})
g.GET("/project/:projectId/webhook/:webhookId", func(c echo.Context) error {
+ ctx := context.Background()
_, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -89,7 +92,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
find := &api.ProjectWebhookFind{
ID: &id,
}
- hook, err := s.ProjectWebhookService.FindProjectWebhook(context.Background(), find)
+ hook, err := s.ProjectWebhookService.FindProjectWebhook(ctx, find)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
@@ -97,7 +100,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project webhook ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeProjectWebhookRelationship(context.Background(), hook); err != nil {
+ if err := s.ComposeProjectWebhookRelationship(ctx, hook); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch webhook relationship").SetInternal(err)
}
@@ -109,6 +112,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
})
g.PATCH("/project/:projectId/webhook/:webhookId", func(c echo.Context) error {
+ ctx := context.Background()
_, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -127,7 +131,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted change project webhook").SetInternal(err)
}
- hook, err := s.ProjectWebhookService.PatchProjectWebhook(context.Background(), hookPatch)
+ hook, err := s.ProjectWebhookService.PatchProjectWebhook(ctx, hookPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
@@ -138,7 +142,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change project webhook ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeProjectWebhookRelationship(context.Background(), hook); err != nil {
+ if err := s.ComposeProjectWebhookRelationship(ctx, hook); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch updated project webhook relationship").SetInternal(err)
}
@@ -150,6 +154,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
})
g.DELETE("/project/:projectId/webhook/:webhookId", func(c echo.Context) error {
+ ctx := context.Background()
_, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -164,7 +169,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
ID: id,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- err = s.ProjectWebhookService.DeleteProjectWebhook(context.Background(), hookDelete)
+ err = s.ProjectWebhookService.DeleteProjectWebhook(ctx, hookDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
@@ -178,6 +183,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
})
g.GET("/project/:projectId/webhook/:webhookId/test", func(c echo.Context) error {
+ ctx := context.Background()
projectId, err := strconv.Atoi(c.Param("projectId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
@@ -186,7 +192,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
projectFind := &api.ProjectFind{
ID: &projectId,
}
- project, err := s.ProjectService.FindProject(context.Background(), projectFind)
+ project, err := s.ProjectService.FindProject(ctx, projectFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", projectId))
@@ -202,7 +208,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
find := &api.ProjectWebhookFind{
ID: &id,
}
- hook, err := s.ProjectWebhookService.FindProjectWebhook(context.Background(), find)
+ hook, err := s.ProjectWebhookService.FindProjectWebhook(ctx, find)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
@@ -246,12 +252,12 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
func (s *Server) ComposeProjectWebhookRelationship(ctx context.Context, hook *api.ProjectWebhook) error {
var err error
- hook.Creator, err = s.ComposePrincipalById(context.Background(), hook.CreatorId)
+ hook.Creator, err = s.ComposePrincipalById(ctx, hook.CreatorId)
if err != nil {
return err
}
- hook.Updater, err = s.ComposePrincipalById(context.Background(), hook.UpdaterId)
+ hook.Updater, err = s.ComposePrincipalById(ctx, hook.UpdaterId)
if err != nil {
return err
}
diff --git a/server/repository.go b/server/repository.go
index c82c507043..4001db1dc9 100644
--- a/server/repository.go
+++ b/server/repository.go
@@ -9,22 +9,22 @@ import (
func (s *Server) ComposeRepositoryRelationship(ctx context.Context, repository *api.Repository) error {
var err error
- repository.Creator, err = s.ComposePrincipalById(context.Background(), repository.CreatorId)
+ repository.Creator, err = s.ComposePrincipalById(ctx, repository.CreatorId)
if err != nil {
return err
}
- repository.Updater, err = s.ComposePrincipalById(context.Background(), repository.UpdaterId)
+ repository.Updater, err = s.ComposePrincipalById(ctx, repository.UpdaterId)
if err != nil {
return err
}
- repository.VCS, err = s.ComposeVCSById(context.Background(), repository.VCSId)
+ repository.VCS, err = s.ComposeVCSById(ctx, repository.VCSId)
if err != nil {
return err
}
- repository.Project, err = s.ComposeProjectlById(context.Background(), repository.ProjectId)
+ repository.Project, err = s.ComposeProjectlById(ctx, repository.ProjectId)
if err != nil {
return err
}
diff --git a/server/schema_syncer.go b/server/schema_syncer.go
index 1e79ed5dd1..460389a6c8 100644
--- a/server/schema_syncer.go
+++ b/server/schema_syncer.go
@@ -44,11 +44,13 @@ func (s *SchemaSyncer) Run() error {
}
}()
+ ctx := context.Background()
+
rowStatus := api.Normal
instanceFind := &api.InstanceFind{
RowStatus: &rowStatus,
}
- list, err := s.server.InstanceService.FindInstanceList(context.Background(), instanceFind)
+ list, err := s.server.InstanceService.FindInstanceList(ctx, instanceFind)
if err != nil {
s.l.Error("Failed to retrieve instances", zap.Error(err))
return
@@ -63,7 +65,7 @@ func (s *SchemaSyncer) Run() error {
runningTasks[instance.ID] = true
mu.Unlock()
- if err := s.server.ComposeInstanceRelationship(context.Background(), instance); err != nil {
+ if err := s.server.ComposeInstanceRelationship(ctx, instance); err != nil {
s.l.Error("Failed to sync instance",
zap.Int("id", instance.ID),
zap.String("name", instance.Name),
@@ -77,7 +79,7 @@ func (s *SchemaSyncer) Run() error {
delete(runningTasks, instance.ID)
mu.Unlock()
}()
- resultSet := s.server.SyncEngineVersionAndSchema(instance)
+ resultSet := s.server.SyncEngineVersionAndSchema(ctx, instance)
if resultSet.Error != "" {
s.l.Debug("Failed to sync instance",
zap.Int("id", instance.ID),
diff --git a/server/setting.go b/server/setting.go
index ac0632bc22..af5477efe3 100644
--- a/server/setting.go
+++ b/server/setting.go
@@ -18,8 +18,9 @@ var (
func (s *Server) registerSettingRoutes(g *echo.Group) {
g.GET("/setting", func(c echo.Context) error {
+ ctx := context.Background()
find := &api.SettingFind{}
- list, err := s.SettingService.FindSettingList(context.Background(), find)
+ list, err := s.SettingService.FindSettingList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch setting list").SetInternal(err)
}
@@ -35,7 +36,7 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {
}
for _, setting := range filteredList {
- if err := s.ComposeSettingRelationship(context.Background(), setting); err != nil {
+ if err := s.ComposeSettingRelationship(ctx, setting); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch setting relationship: %v", setting.Name)).SetInternal(err)
}
}
@@ -48,6 +49,7 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {
})
g.PATCH("/setting/:name", func(c echo.Context) error {
+ ctx := context.Background()
settingPatch := &api.SettingPatch{
Name: api.SettingName(c.Param("name")),
UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
@@ -56,7 +58,7 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update setting request").SetInternal(err)
}
- setting, err := s.SettingService.PatchSetting(context.Background(), settingPatch)
+ setting, err := s.SettingService.PatchSetting(ctx, settingPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Setting name not found: %s", settingPatch.Name))
@@ -80,7 +82,7 @@ func (s *Server) ComposeSettingRelationship(ctx context.Context, setting *api.Se
return err
}
- setting.Updater, err = s.ComposePrincipalById(context.Background(), setting.UpdaterId)
+ setting.Updater, err = s.ComposePrincipalById(ctx, setting.UpdaterId)
if err != nil {
return err
}
diff --git a/server/sql.go b/server/sql.go
index dddbeaf15c..43e96134f1 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -15,6 +15,7 @@ import (
func (s *Server) registerSqlRoutes(g *echo.Group) {
g.POST("/sql/ping", func(c echo.Context) error {
+ ctx := context.Background()
connectionInfo := &api.ConnectionInfo{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql ping request").SetInternal(err)
@@ -26,7 +27,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
// not transfer the password back to client, thus the client will pass the instanceId to
// let server retrieve the password.
if password == "" && connectionInfo.InstanceId != nil {
- adminPassword, err := s.FindInstanceAdminPasswordById(context.Background(), *connectionInfo.InstanceId)
+ adminPassword, err := s.FindInstanceAdminPasswordById(ctx, *connectionInfo.InstanceId)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to retrieve admin password for instance: %d", connectionInfo.InstanceId)).SetInternal(err)
}
@@ -34,6 +35,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
}
db, err := db.Open(
+ ctx,
connectionInfo.Engine,
db.DriverConfig{Logger: s.l},
db.ConnectionConfig{
@@ -57,8 +59,8 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
}
resultSet.Error = fmt.Errorf("failed to connect %q for user %q (using password: %s), %w", hostPort, connectionInfo.Username, usePassword, err).Error()
} else {
- defer db.Close(context.Background())
- if err := db.Ping(context.Background()); err != nil {
+ defer db.Close(ctx)
+ if err := db.Ping(ctx); err != nil {
resultSet.Error = err.Error()
}
}
@@ -71,12 +73,13 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
})
g.POST("/sql/syncschema", func(c echo.Context) error {
+ ctx := context.Background()
sync := &api.SqlSyncSchema{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, sync); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql sync schema request").SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), sync.InstanceId)
+ instance, err := s.ComposeInstanceById(ctx, sync.InstanceId)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", sync.InstanceId))
@@ -84,7 +87,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", sync.InstanceId)).SetInternal(err)
}
- resultSet := s.SyncEngineVersionAndSchema(instance)
+ resultSet := s.SyncEngineVersionAndSchema(ctx, instance)
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {
@@ -94,24 +97,24 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
})
}
-func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.SqlResultSet) {
+func (s *Server) SyncEngineVersionAndSchema(ctx context.Context, instance *api.Instance) (rs *api.SqlResultSet) {
resultSet := &api.SqlResultSet{}
err := func() error {
- driver, err := GetDatabaseDriver(instance, "", s.l)
+ driver, err := GetDatabaseDriver(ctx, instance, "", s.l)
if err != nil {
return err
}
- defer driver.Close(context.Background())
+ defer driver.Close(ctx)
// Sync engine version
- version, err := driver.GetVersion(context.Background())
+ version, err := driver.GetVersion(ctx)
if err != nil {
return err
}
// Underlying version may change due to upgrade, however it's a rare event, so we only update if it actually differs
// to avoid changing the updated_ts
if version != instance.EngineVersion {
- _, err := s.InstanceService.PatchInstance(context.Background(), &api.InstancePatch{
+ _, err := s.InstanceService.PatchInstance(ctx, &api.InstancePatch{
ID: instance.ID,
UpdaterId: api.SYSTEM_BOT_ID,
EngineVersion: &version,
@@ -123,12 +126,12 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
}
// Sync schema
- userList, schemaList, err := driver.SyncSchema(context.Background())
+ userList, schemaList, err := driver.SyncSchema(ctx)
if err != nil {
resultSet.Error = err.Error()
} else {
var createTable = func(database *api.Database, tableCreate *api.TableCreate) (*api.Table, error) {
- createTable, err := s.TableService.CreateTable(context.Background(), tableCreate)
+ createTable, err := s.TableService.CreateTable(ctx, tableCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return nil, fmt.Errorf("failed to sync table for instance: %s, database: %s. Table name already exists: %s", instance.Name, database.Name, tableCreate.Name)
@@ -139,7 +142,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
}
var createColumn = func(database *api.Database, table *api.Table, columnCreate *api.ColumnCreate) error {
- _, err := s.ColumnService.CreateColumn(context.Background(), columnCreate)
+ _, err := s.ColumnService.CreateColumn(ctx, columnCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return fmt.Errorf("failed to sync column for instance: %s, database: %s, table: %s. Column name already exists: %s", instance.Name, database.Name, table.Name, columnCreate.Name)
@@ -150,7 +153,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
}
var createIndex = func(database *api.Database, table *api.Table, indexCreate *api.IndexCreate) error {
- _, err := s.IndexService.CreateIndex(context.Background(), indexCreate)
+ _, err := s.IndexService.CreateIndex(ctx, indexCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. index and expression already exists: %s(%s)", instance.Name, database.Name, table.Name, indexCreate.Name, indexCreate.Expression)
@@ -188,7 +191,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
TableId: &upsertedTable.ID,
Name: &column.Name,
}
- _, err := s.ColumnService.FindColumn(context.Background(), columnFind)
+ _, err := s.ColumnService.FindColumn(ctx, columnFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
columnCreate := &api.ColumnCreate{
@@ -221,7 +224,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
Name: &index.Name,
Expression: &index.Expression,
}
- _, err := s.IndexService.FindIndex(context.Background(), indexFind)
+ _, err := s.IndexService.FindIndex(ctx, indexFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
indexCreate := &api.IndexCreate{
@@ -250,7 +253,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
instanceUserFind := &api.InstanceUserFind{
InstanceId: instance.ID,
}
- instanceUserList, err := s.InstanceUserService.FindInstanceUserList(context.Background(), instanceUserFind)
+ instanceUserList, err := s.InstanceUserService.FindInstanceUserList(ctx, instanceUserFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch user list for instance: %v", instance.ID)).SetInternal(err)
}
@@ -263,7 +266,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
Name: user.Name,
Grant: user.Grant,
}
- _, err := s.InstanceUserService.UpsertInstanceUser(context.Background(), userUpsert)
+ _, err := s.InstanceUserService.UpsertInstanceUser(ctx, userUpsert)
if err != nil {
return fmt.Errorf("failed to sync user for instance: %s. Failed to upsert user. Error %w", instance.Name, err)
}
@@ -283,7 +286,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
userDelete := &api.InstanceUserDelete{
ID: user.ID,
}
- err := s.InstanceUserService.DeleteInstanceUser(context.Background(), userDelete)
+ err := s.InstanceUserService.DeleteInstanceUser(ctx, userDelete)
if err != nil {
return fmt.Errorf("failed to sync user for instance: %s. Failed to delete user: %s. Error %w", instance.Name, user.Name, err)
}
@@ -304,7 +307,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
databaseFind := &api.DatabaseFind{
InstanceId: &instance.ID,
}
- dbList, err := s.DatabaseService.FindDatabaseList(context.Background(), databaseFind)
+ dbList, err := s.DatabaseService.FindDatabaseList(ctx, databaseFind)
if err != nil {
return fmt.Errorf("failed to sync database for instance: %s. Failed to find database list. Error %w", instance.Name, err)
}
@@ -327,7 +330,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
SyncStatus: &syncStatus,
LastSuccessfulSyncTs: &ts,
}
- database, err := s.DatabaseService.PatchDatabase(context.Background(), databasePatch)
+ database, err := s.DatabaseService.PatchDatabase(ctx, databasePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return fmt.Errorf("failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name)
@@ -338,7 +341,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
tableDelete := &api.TableDelete{
DatabaseId: database.ID,
}
- err = s.TableService.DeleteTable(context.Background(), tableDelete)
+ err = s.TableService.DeleteTable(ctx, tableDelete)
if err != nil {
return fmt.Errorf("failed to sync database for instance: %s. Failed to reset table info for database: %s. Error %w", instance.Name, database.Name, err)
}
@@ -363,7 +366,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
TimezoneName: z,
TimezoneOffset: offset,
}
- database, err := s.DatabaseService.CreateDatabase(context.Background(), databaseCreate)
+ database, err := s.DatabaseService.CreateDatabase(ctx, databaseCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return fmt.Errorf("failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name)
@@ -398,7 +401,7 @@ func (s *Server) SyncEngineVersionAndSchema(instance *api.Instance) (rs *api.Sql
SyncStatus: &syncStatus,
LastSuccessfulSyncTs: &ts,
}
- database, err := s.DatabaseService.PatchDatabase(context.Background(), databasePatch)
+ database, err := s.DatabaseService.PatchDatabase(ctx, databasePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return fmt.Errorf("failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name)
diff --git a/server/stage.go b/server/stage.go
index 8c1ecaf95c..099a74ad43 100644
--- a/server/stage.go
+++ b/server/stage.go
@@ -10,7 +10,7 @@ func (s *Server) ComposeStageListByPipelineId(ctx context.Context, pipelineId in
stageFind := &api.StageFind{
PipelineId: &pipelineId,
}
- stageList, err := s.StageService.FindStageList(context.Background(), stageFind)
+ stageList, err := s.StageService.FindStageList(ctx, stageFind)
if err != nil {
return nil, err
}
@@ -26,22 +26,22 @@ func (s *Server) ComposeStageListByPipelineId(ctx context.Context, pipelineId in
func (s *Server) ComposeStageRelationship(ctx context.Context, stage *api.Stage) error {
var err error
- stage.Creator, err = s.ComposePrincipalById(context.Background(), stage.CreatorId)
+ stage.Creator, err = s.ComposePrincipalById(ctx, stage.CreatorId)
if err != nil {
return err
}
- stage.Updater, err = s.ComposePrincipalById(context.Background(), stage.UpdaterId)
+ stage.Updater, err = s.ComposePrincipalById(ctx, stage.UpdaterId)
if err != nil {
return err
}
- stage.Environment, err = s.ComposeEnvironmentById(context.Background(), stage.EnvironmentId)
+ stage.Environment, err = s.ComposeEnvironmentById(ctx, stage.EnvironmentId)
if err != nil {
return err
}
- stage.TaskList, err = s.ComposeTaskListByPipelineAndStageId(context.Background(), stage.PipelineId, stage.ID)
+ stage.TaskList, err = s.ComposeTaskListByPipelineAndStageId(ctx, stage.PipelineId, stage.ID)
if err != nil {
return err
}
diff --git a/server/task.go b/server/task.go
index ed862d8c04..1ae7213cfe 100644
--- a/server/task.go
+++ b/server/task.go
@@ -29,6 +29,7 @@ var (
func (s *Server) registerTaskRoutes(g *echo.Group) {
g.PATCH("/pipeline/:pipelineId/task/:taskId", func(c echo.Context) error {
+ ctx := context.Background()
taskId, err := strconv.Atoi(c.Param("taskId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskId"))).SetInternal(err)
@@ -45,7 +46,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
taskFind := &api.TaskFind{
ID: &taskId,
}
- task, err := s.TaskService.FindTask(context.Background(), taskFind)
+ task, err := s.TaskService.FindTask(ctx, taskFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Task ID not found: %d", taskId))
@@ -73,7 +74,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
}
}
- updatedTask, err := s.TaskService.PatchTask(context.Background(), taskPatch)
+ updatedTask, err := s.TaskService.PatchTask(ctx, taskPatch)
if err != nil {
if common.ErrorCode(err) == common.Invalid {
return echo.NewHTTPError(http.StatusBadRequest, common.ErrorMessage(err))
@@ -81,7 +82,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\"", task.Name)).SetInternal(err)
}
- if err := s.ComposeTaskRelationship(context.Background(), updatedTask); err != nil {
+ if err := s.ComposeTaskRelationship(ctx, updatedTask); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated task \"%v\" relationship", updatedTask.Name)).SetInternal(err)
}
@@ -98,7 +99,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("failed to marshal statement advise payload: %v, err: %w", task.Name, err))
}
- _, err = s.TaskCheckRunService.CreateTaskCheckRunIfNeeded(context.Background(), &api.TaskCheckRunCreate{
+ _, err = s.TaskCheckRunService.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{
CreatorId: api.SYSTEM_BOT_ID,
TaskId: task.ID,
Type: api.TaskCheckDatabaseStatementSyntax,
@@ -114,7 +115,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
)
}
- _, err = s.TaskCheckRunService.CreateTaskCheckRunIfNeeded(context.Background(), &api.TaskCheckRunCreate{
+ _, err = s.TaskCheckRunService.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{
CreatorId: api.SYSTEM_BOT_ID,
TaskId: task.ID,
Type: api.TaskCheckDatabaseStatementCompatibility,
@@ -140,6 +141,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
})
g.PATCH("/pipeline/:pipelineId/task/:taskId/status", func(c echo.Context) error {
+ ctx := context.Background()
taskId, err := strconv.Atoi(c.Param("taskId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskId"))).SetInternal(err)
@@ -156,7 +158,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
taskFind := &api.TaskFind{
ID: &taskId,
}
- task, err := s.TaskService.FindTask(context.Background(), taskFind)
+ task, err := s.TaskService.FindTask(ctx, taskFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Task ID not found: %d", taskId))
@@ -164,7 +166,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update task status").SetInternal(err)
}
- updatedTask, err := s.ChangeTaskStatusWithPatch(context.Background(), task, taskStatusPatch)
+ updatedTask, err := s.ChangeTaskStatusWithPatch(ctx, task, taskStatusPatch)
if err != nil {
if common.ErrorCode(err) == common.Invalid {
return echo.NewHTTPError(http.StatusBadRequest, common.ErrorMessage(err))
@@ -172,7 +174,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\" status", task.Name)).SetInternal(err)
}
- if err := s.ComposeTaskRelationship(context.Background(), updatedTask); err != nil {
+ if err := s.ComposeTaskRelationship(ctx, updatedTask); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated task \"%v\" relationship", updatedTask.Name)).SetInternal(err)
}
@@ -184,6 +186,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
})
g.POST("/pipeline/:pipelineId/task/:taskId/check", func(c echo.Context) error {
+ ctx := context.Background()
taskId, err := strconv.Atoi(c.Param("taskId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskId"))).SetInternal(err)
@@ -192,7 +195,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
taskFind := &api.TaskFind{
ID: &taskId,
}
- task, err := s.TaskService.FindTask(context.Background(), taskFind)
+ task, err := s.TaskService.FindTask(ctx, taskFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Task ID not found: %d", taskId))
@@ -201,13 +204,13 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
}
skipIfAlreadyTerminated := false
- updatedTask, err := s.TaskCheckScheduler.ScheduleCheckIfNeeded(context.Background(), task, c.Get(GetPrincipalIdContextKey()).(int), skipIfAlreadyTerminated)
+ updatedTask, err := s.TaskCheckScheduler.ScheduleCheckIfNeeded(ctx, task, c.Get(GetPrincipalIdContextKey()).(int), skipIfAlreadyTerminated)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to run task check \"%v\"", task.Name)).SetInternal(err)
}
- if err := s.ComposeTaskRelationship(context.Background(), updatedTask); err != nil {
+ if err := s.ComposeTaskRelationship(ctx, updatedTask); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated task \"%v\" relationship", updatedTask.Name)).SetInternal(err)
}
@@ -224,7 +227,7 @@ func (s *Server) ComposeTaskListByPipelineAndStageId(ctx context.Context, pipeli
PipelineId: &pipelineId,
StageId: &stageId,
}
- taskList, err := s.TaskService.FindTaskList(context.Background(), taskFind)
+ taskList, err := s.TaskService.FindTaskList(ctx, taskFind)
if err != nil {
return nil, err
}
@@ -242,7 +245,7 @@ func (s *Server) ComposeTaskById(ctx context.Context, id int) (*api.Task, error)
taskFind := &api.TaskFind{
ID: &id,
}
- task, err := s.TaskService.FindTask(context.Background(), taskFind)
+ task, err := s.TaskService.FindTask(ctx, taskFind)
if err != nil {
return nil, err
}
@@ -257,41 +260,41 @@ func (s *Server) ComposeTaskById(ctx context.Context, id int) (*api.Task, error)
func (s *Server) ComposeTaskRelationship(ctx context.Context, task *api.Task) error {
var err error
- task.Creator, err = s.ComposePrincipalById(context.Background(), task.CreatorId)
+ task.Creator, err = s.ComposePrincipalById(ctx, task.CreatorId)
if err != nil {
return err
}
- task.Updater, err = s.ComposePrincipalById(context.Background(), task.UpdaterId)
+ task.Updater, err = s.ComposePrincipalById(ctx, task.UpdaterId)
if err != nil {
return err
}
for _, taskRun := range task.TaskRunList {
- taskRun.Creator, err = s.ComposePrincipalById(context.Background(), taskRun.CreatorId)
+ taskRun.Creator, err = s.ComposePrincipalById(ctx, taskRun.CreatorId)
if err != nil {
return err
}
- taskRun.Updater, err = s.ComposePrincipalById(context.Background(), taskRun.UpdaterId)
+ taskRun.Updater, err = s.ComposePrincipalById(ctx, taskRun.UpdaterId)
if err != nil {
return err
}
}
for _, taskCheckRun := range task.TaskCheckRunList {
- taskCheckRun.Creator, err = s.ComposePrincipalById(context.Background(), taskCheckRun.CreatorId)
+ taskCheckRun.Creator, err = s.ComposePrincipalById(ctx, taskCheckRun.CreatorId)
if err != nil {
return err
}
- taskCheckRun.Updater, err = s.ComposePrincipalById(context.Background(), taskCheckRun.UpdaterId)
+ taskCheckRun.Updater, err = s.ComposePrincipalById(ctx, taskCheckRun.UpdaterId)
if err != nil {
return err
}
}
- task.Instance, err = s.ComposeInstanceById(context.Background(), task.InstanceId)
+ task.Instance, err = s.ComposeInstanceById(ctx, task.InstanceId)
if err != nil {
return err
}
@@ -300,7 +303,7 @@ func (s *Server) ComposeTaskRelationship(ctx context.Context, task *api.Task) er
databaseFind := &api.DatabaseFind{
ID: task.DatabaseId,
}
- task.Database, err = s.ComposeDatabaseByFind(context.Background(), databaseFind)
+ task.Database, err = s.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
return err
}
@@ -401,7 +404,7 @@ func (s *Server) ChangeTaskStatusWithPatch(ctx context.Context, task *api.Task,
if issue != nil {
activityMeta.issue = issue
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &activityMeta)
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &activityMeta)
if err != nil {
return nil, err
}
@@ -432,7 +435,7 @@ func (s *Server) ChangeTaskStatusWithPatch(ctx context.Context, task *api.Task,
return nil, fmt.Errorf("invalid create database task payload: %w", err)
}
- instance, err := s.InstanceService.FindInstance(context.Background(), &api.InstanceFind{
+ instance, err := s.InstanceService.FindInstance(ctx, &api.InstanceFind{
ID: &task.InstanceId,
})
if err != nil {
@@ -466,11 +469,11 @@ func (s *Server) ChangeTaskStatusWithPatch(ctx context.Context, task *api.Task,
// If create database or schema update task completes, we sync the corresponding instance schema immediately.
if (updatedTask.Type == api.TaskDatabaseCreate || updatedTask.Type == api.TaskDatabaseSchemaUpdate) &&
updatedTask.Status == api.TaskDone {
- instance, err := s.ComposeInstanceById(context.Background(), task.InstanceId)
+ instance, err := s.ComposeInstanceById(ctx, task.InstanceId)
if err != nil {
return nil, fmt.Errorf("failed to sync instance schema after completing task: %w", err)
}
- s.SyncEngineVersionAndSchema(instance)
+ s.SyncEngineVersionAndSchema(ctx, instance)
}
// If this is the last task in the pipeline and just completed, and the assignee is system bot:
@@ -490,7 +493,7 @@ func (s *Server) ChangeTaskStatusWithPatch(ctx context.Context, task *api.Task,
UpdaterId: taskStatusPatch.UpdaterId,
Status: &status,
}
- if _, err := s.PipelineService.PatchPipeline(context.Background(), pipelinePatch); err != nil {
+ if _, err := s.PipelineService.PatchPipeline(ctx, pipelinePatch); err != nil {
return nil, fmt.Errorf("failed to mark pipeline %v as DONE after completing task %v: %w", pipeline.Name, updatedTask.Name, err)
}
} else {
diff --git a/server/task_check_executor_database_connect.go b/server/task_check_executor_database_connect.go
index 131e7dd1a8..254f5b94f4 100644
--- a/server/task_check_executor_database_connect.go
+++ b/server/task_check_executor_database_connect.go
@@ -36,7 +36,7 @@ func (exec *TaskCheckDatabaseConnectExecutor) Run(ctx context.Context, server *S
return []api.TaskCheckResult{}, common.Errorf(common.Internal, err)
}
- driver, err := GetDatabaseDriver(database.Instance, database.Name, exec.l)
+ driver, err := GetDatabaseDriver(ctx, database.Instance, database.Name, exec.l)
if err != nil {
return []api.TaskCheckResult{
{
diff --git a/server/task_check_executor_migration_schema.go b/server/task_check_executor_migration_schema.go
index 9445b35066..1331c8d295 100644
--- a/server/task_check_executor_migration_schema.go
+++ b/server/task_check_executor_migration_schema.go
@@ -28,12 +28,12 @@ func (exec *TaskCheckMigrationSchemaExecutor) Run(ctx context.Context, server *S
return []api.TaskCheckResult{}, common.Errorf(common.Internal, err)
}
- instance, err := server.ComposeInstanceById(context.Background(), task.InstanceId)
+ instance, err := server.ComposeInstanceById(ctx, task.InstanceId)
if err != nil {
return []api.TaskCheckResult{}, err
}
- driver, err := GetDatabaseDriver(instance, "", exec.l)
+ driver, err := GetDatabaseDriver(ctx, instance, "", exec.l)
if err != nil {
return []api.TaskCheckResult{}, err
}
diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.go
index ee439ec239..811d0c35e3 100644
--- a/server/task_check_scheduler.go
+++ b/server/task_check_scheduler.go
@@ -49,12 +49,14 @@ func (s *TaskCheckScheduler) Run() error {
}
}()
+ ctx := context.Background()
+
// Inspect all running task checks
taskCheckRunStatusList := []api.TaskCheckRunStatus{api.TaskCheckRunRunning}
taskCheckRunFind := &api.TaskCheckRunFind{
StatusList: &taskCheckRunStatusList,
}
- taskCheckRunList, err := s.server.TaskCheckRunService.FindTaskCheckRunList(context.Background(), taskCheckRunFind)
+ taskCheckRunList, err := s.server.TaskCheckRunService.FindTaskCheckRunList(ctx, taskCheckRunFind)
if err != nil {
s.l.Error("Failed to retrieve running tasks", zap.Error(err))
return
@@ -85,7 +87,7 @@ func (s *TaskCheckScheduler) Run() error {
delete(runningTaskChecks, taskCheckRun.ID)
mu.Unlock()
}()
- checkResultList, err := executor.Run(context.Background(), s.server, taskCheckRun)
+ checkResultList, err := executor.Run(ctx, s.server, taskCheckRun)
if err == nil {
bytes, err := json.Marshal(api.TaskCheckRunResultPayload{
@@ -108,7 +110,7 @@ func (s *TaskCheckScheduler) Run() error {
Code: common.Ok,
Result: string(bytes),
}
- _, err = s.server.TaskCheckRunService.PatchTaskCheckRunStatus(context.Background(), taskCheckRunStatusPatch)
+ _, err = s.server.TaskCheckRunService.PatchTaskCheckRunStatus(ctx, taskCheckRunStatusPatch)
if err != nil {
s.l.Error("Failed to mark task check run as DONE",
zap.Int("id", taskCheckRun.ID),
@@ -144,7 +146,7 @@ func (s *TaskCheckScheduler) Run() error {
Code: common.ErrorCode(err),
Result: string(bytes),
}
- _, err = s.server.TaskCheckRunService.PatchTaskCheckRunStatus(context.Background(), taskCheckRunStatusPatch)
+ _, err = s.server.TaskCheckRunService.PatchTaskCheckRunStatus(ctx, taskCheckRunStatusPatch)
if err != nil {
s.l.Error("Failed to mark task check run as FAILED",
zap.Int("id", taskCheckRun.ID),
@@ -185,7 +187,7 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *ap
databaseFind := &api.DatabaseFind{
ID: task.DatabaseId,
}
- database, err := s.server.ComposeDatabaseByFind(context.Background(), databaseFind)
+ database, err := s.server.ComposeDatabaseByFind(ctx, databaseFind)
if err != nil {
return nil, err
}
diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.go
index 625b0b61b9..aaaaf6363f 100644
--- a/server/task_executor_database_backup.go
+++ b/server/task_executor_database_backup.go
@@ -85,7 +85,7 @@ func (exec *DatabaseBackupTaskExecutor) RunOnce(ctx context.Context, server *Ser
// backupDatabase will take a backup of a database.
func (exec *DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, instance *api.Instance, databaseName string, backup *api.Backup, dataDir string) error {
- driver, err := GetDatabaseDriver(instance, databaseName, exec.l)
+ driver, err := GetDatabaseDriver(ctx, instance, databaseName, exec.l)
if err != nil {
return err
}
@@ -124,19 +124,19 @@ func getAndCreateBackupPath(dataDir string, database *api.Database, name string)
return filepath.Join(dir, fmt.Sprintf("%s.sql", name)), nil
}
-func getMigrationVersion(database *api.Database, logger *zap.Logger) (string, error) {
- driver, err := GetDatabaseDriver(database.Instance, database.Name, logger)
+func getMigrationVersion(ctx context.Context, database *api.Database, logger *zap.Logger) (string, error) {
+ driver, err := GetDatabaseDriver(ctx, database.Instance, database.Name, logger)
if err != nil {
return "", err
}
- defer driver.Close(context.Background())
+ defer driver.Close(ctx)
limit := 1
find := &db.MigrationHistoryFind{
Database: &database.Name,
Limit: &limit,
}
- list, err := driver.FindMigrationHistoryList(context.Background(), find)
+ list, err := driver.FindMigrationHistoryList(ctx, find)
if err != nil {
return "", fmt.Errorf("failed to fetch migration history list: %w", err)
}
diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.go
index 2d29b32f3f..90d9edb64d 100644
--- a/server/task_executor_database_create.go
+++ b/server/task_executor_database_create.go
@@ -44,11 +44,11 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser
}
instance := task.Instance
- driver, err := GetDatabaseDriver(task.Instance, "", exec.l)
+ driver, err := GetDatabaseDriver(ctx, task.Instance, "", exec.l)
if err != nil {
return true, nil, err
}
- defer driver.Close(context.Background())
+ defer driver.Close(ctx)
var statement string
switch instance.Engine {
@@ -77,7 +77,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser
Description: "Create database",
CreateDatabase: true,
}
- creator, err := server.ComposePrincipalById(context.Background(), task.CreatorId)
+ creator, err := server.ComposePrincipalById(ctx, task.CreatorId)
if err != nil {
// If somehow we unable to find the principal, we just emit the error since it's not
// critical enough to fail the entire operation.
diff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.go
index f63539a270..6290a48ff5 100644
--- a/server/task_executor_database_restore.go
+++ b/server/task_executor_database_restore.go
@@ -58,7 +58,7 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Se
sourceDatabaseFind := &api.DatabaseFind{
ID: &backup.DatabaseId,
}
- sourceDatabase, err := server.ComposeDatabaseByFind(context.Background(), sourceDatabaseFind)
+ sourceDatabase, err := server.ComposeDatabaseByFind(ctx, sourceDatabaseFind)
if err != nil {
return true, nil, fmt.Errorf("failed to find database for the backup: %w", err)
}
@@ -67,7 +67,7 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Se
InstanceId: &task.InstanceId,
Name: &payload.DatabaseName,
}
- targetDatabase, err := server.ComposeDatabaseByFind(context.Background(), targetDatabaseFind)
+ targetDatabase, err := server.ComposeDatabaseByFind(ctx, targetDatabaseFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return true, nil, fmt.Errorf("target database %q not found in instance %q: %w", payload.DatabaseName, task.Instance.Name, err)
@@ -104,12 +104,12 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Se
UpdaterId: api.SYSTEM_BOT_ID,
SourceBackupId: &backup.ID,
}
- if _, err = server.DatabaseService.PatchDatabase(context.Background(), databasePatch); err != nil {
+ if _, err = server.DatabaseService.PatchDatabase(ctx, databasePatch); err != nil {
return true, nil, fmt.Errorf("failed to patch database source backup ID after restore: %w", err)
}
// Sync database schema after restore is completed.
- server.SyncEngineVersionAndSchema(targetDatabase.Instance)
+ server.SyncEngineVersionAndSchema(ctx, targetDatabase.Instance)
return true, &api.TaskRunResultPayload{
Detail: fmt.Sprintf("Restored database %q from backup %q", targetDatabase.Name, backup.Name),
@@ -120,7 +120,7 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Se
// restoreDatabase will restore the database from a backup
func (exec *DatabaseRestoreTaskExecutor) restoreDatabase(ctx context.Context, instance *api.Instance, databaseName string, backup *api.Backup, dataDir string) error {
- driver, err := GetDatabaseDriver(instance, databaseName, exec.l)
+ driver, err := GetDatabaseDriver(ctx, instance, databaseName, exec.l)
if err != nil {
return err
}
@@ -149,7 +149,7 @@ func (exec *DatabaseRestoreTaskExecutor) restoreDatabase(ctx context.Context, in
// create many ephemeral databases from backup for testing purpose)
// Returns migration history id and the version on success
func createBranchMigrationHistory(ctx context.Context, server *Server, sourceDatabase, targetDatabase *api.Database, backup *api.Backup, task *api.Task, logger *zap.Logger) (int64, string, error) {
- targetDriver, err := GetDatabaseDriver(targetDatabase.Instance, targetDatabase.Name, logger)
+ targetDriver, err := GetDatabaseDriver(ctx, targetDatabase.Instance, targetDatabase.Name, logger)
if err != nil {
return -1, "", err
}
diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.go
index 5017be9d27..e4d2821117 100644
--- a/server/task_executor_schema_update.go
+++ b/server/task_executor_schema_update.go
@@ -57,7 +57,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
}
if payload.VCSPushEvent == nil {
mi.Engine = db.UI
- creator, err := server.ComposePrincipalById(context.Background(), task.CreatorId)
+ creator, err := server.ComposePrincipalById(ctx, task.CreatorId)
if err != nil {
// If somehow we unable to find the principal, we just emit the error since it's not
// critical enough to fail the entire operation.
@@ -76,7 +76,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
repositoryFind := &api.RepositoryFind{
ProjectId: &task.Database.ProjectId,
}
- repository, err = server.RepositoryService.FindRepository(context.Background(), repositoryFind)
+ repository, err = server.RepositoryService.FindRepository(ctx, repositoryFind)
if err != nil {
return true, nil, fmt.Errorf("failed to find linked repository for database %q", databaseName)
}
@@ -126,11 +126,11 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
return true, nil, err
}
- driver, err := GetDatabaseDriver(task.Instance, databaseName, exec.l)
+ driver, err := GetDatabaseDriver(ctx, task.Instance, databaseName, exec.l)
if err != nil {
return true, nil, err
}
- defer driver.Close(context.Background())
+ defer driver.Close(ctx)
exec.l.Debug("Start sql migration...",
zap.String("instance", task.Instance.Name),
@@ -159,7 +159,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", mi.Database)
- repository.VCS, err = server.ComposeVCSById(context.Background(), repository.VCSId)
+ repository.VCS, err = server.ComposeVCSById(ctx, repository.VCSId)
if err != nil {
return true, nil, fmt.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, databaseName)
}
@@ -214,7 +214,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
Payload: string(payload),
}
- _, err = server.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = server.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
exec.l.Error("Failed to create file commit activity after writing back the latest schema",
zap.Int("task_id", task.ID),
diff --git a/server/task_scheduler.go b/server/task_scheduler.go
index 055f2c9163..4b66301443 100644
--- a/server/task_scheduler.go
+++ b/server/task_scheduler.go
@@ -49,12 +49,14 @@ func (s *TaskScheduler) Run() error {
}
}()
+ ctx := context.Background()
+
// Inspect all open pipelines and schedule the next PENDING task if applicable
pipelineStatus := api.Pipeline_Open
pipelineFind := &api.PipelineFind{
Status: &pipelineStatus,
}
- pipelineList, err := s.server.PipelineService.FindPipelineList(context.Background(), pipelineFind)
+ pipelineList, err := s.server.PipelineService.FindPipelineList(ctx, pipelineFind)
if err != nil {
s.l.Error("Failed to retrieve open pipelines", zap.Error(err))
return
@@ -63,7 +65,7 @@ func (s *TaskScheduler) Run() error {
if pipeline.ID == api.ONBOARDING_PIPELINE_ID {
continue
}
- if err := s.server.ComposePipelineRelationship(context.Background(), pipeline); err != nil {
+ if err := s.server.ComposePipelineRelationship(ctx, pipeline); err != nil {
s.l.Error("Failed to fetch pipeline relationship",
zap.Int("id", pipeline.ID),
zap.String("name", pipeline.Name),
@@ -72,7 +74,7 @@ func (s *TaskScheduler) Run() error {
continue
}
- if _, err := s.server.ScheduleNextTaskIfNeeded(context.Background(), pipeline); err != nil {
+ if _, err := s.server.ScheduleNextTaskIfNeeded(ctx, pipeline); err != nil {
s.l.Error("Failed to schedule next running task",
zap.Int("pipeline_id", pipeline.ID),
zap.Error(err),
@@ -85,7 +87,7 @@ func (s *TaskScheduler) Run() error {
taskFind := &api.TaskFind{
StatusList: &taskStatusList,
}
- taskList, err := s.server.TaskService.FindTaskList(context.Background(), taskFind)
+ taskList, err := s.server.TaskService.FindTaskList(ctx, taskFind)
if err != nil {
s.l.Error("Failed to retrieve running tasks", zap.Error(err))
return
@@ -108,7 +110,7 @@ func (s *TaskScheduler) Run() error {
// This fetches quite a bit info and may cause performance issue if we have many ongoing tasks
// We may optimize this in the future since only some relationship info is needed by the executor
- if err := s.server.ComposeTaskRelationship(context.Background(), task); err != nil {
+ if err := s.server.ComposeTaskRelationship(ctx, task); err != nil {
s.l.Error("Failed to fetch task relationship",
zap.Int("id", task.ID),
zap.String("name", task.Name),
@@ -131,7 +133,7 @@ func (s *TaskScheduler) Run() error {
delete(runningTasks, task.ID)
mu.Unlock()
}()
- done, result, err := executor.RunOnce(context.Background(), s.server, task)
+ done, result, err := executor.RunOnce(ctx, s.server, task)
if done {
if err == nil {
bytes, err := json.Marshal(*result)
@@ -152,7 +154,7 @@ func (s *TaskScheduler) Run() error {
Code: &code,
Result: &result,
}
- _, err = s.server.ChangeTaskStatusWithPatch(context.Background(), task, taskStatusPatch)
+ _, err = s.server.ChangeTaskStatusWithPatch(ctx, task, taskStatusPatch)
if err != nil {
s.l.Error("Failed to mark task as DONE",
zap.Int("id", task.ID),
@@ -187,7 +189,7 @@ func (s *TaskScheduler) Run() error {
Code: &code,
Result: &result,
}
- _, err = s.server.ChangeTaskStatusWithPatch(context.Background(), task, taskStatusPatch)
+ _, err = s.server.ChangeTaskStatusWithPatch(ctx, task, taskStatusPatch)
if err != nil {
s.l.Error("Failed to mark task as FAILED",
zap.Int("id", task.ID),
@@ -248,7 +250,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*
instanceFind := &api.InstanceFind{
ID: &task.InstanceId,
}
- instance, err := s.server.InstanceService.FindInstance(context.Background(), instanceFind)
+ instance, err := s.server.InstanceService.FindInstance(ctx, instanceFind)
if err != nil {
return nil, err
}
diff --git a/server/vcs.go b/server/vcs.go
index eaaaee13a6..50747a12c7 100644
--- a/server/vcs.go
+++ b/server/vcs.go
@@ -16,6 +16,7 @@ import (
func (s *Server) registerVCSRoutes(g *echo.Group) {
g.POST("/vcs", func(c echo.Context) error {
+ ctx := context.Background()
vcsCreate := &api.VCSCreate{
CreatorId: c.Get(GetPrincipalIdContextKey()).(int),
}
@@ -26,12 +27,12 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
vcsCreate.InstanceURL = strings.TrimRight(vcsCreate.InstanceURL, "/")
vcsCreate.ApiURL = fmt.Sprintf("%s/%s", vcsCreate.InstanceURL, gitlab.ApiPath)
- vcs, err := s.VCSService.CreateVCS(context.Background(), vcsCreate)
+ vcs, err := s.VCSService.CreateVCS(ctx, vcsCreate)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create VCS").SetInternal(err)
}
- if err := s.ComposeVCSRelationship(context.Background(), vcs); err != nil {
+ if err := s.ComposeVCSRelationship(ctx, vcs); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created VCS relationship").SetInternal(err)
}
@@ -43,14 +44,15 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
g.GET("/vcs", func(c echo.Context) error {
+ ctx := context.Background()
vcsFind := &api.VCSFind{}
- list, err := s.VCSService.FindVCSList(context.Background(), vcsFind)
+ list, err := s.VCSService.FindVCSList(ctx, vcsFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch vcs list").SetInternal(err)
}
for _, vcs := range list {
- if err := s.ComposeVCSRelationship(context.Background(), vcs); err != nil {
+ if err := s.ComposeVCSRelationship(ctx, vcs); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch vcs relationship: %v", vcs.ID)).SetInternal(err)
}
}
@@ -63,12 +65,13 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
g.GET("/vcs/:vcsId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("vcsId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsId"))).SetInternal(err)
}
- vcs, err := s.ComposeVCSById(context.Background(), id)
+ vcs, err := s.ComposeVCSById(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))
@@ -84,6 +87,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
g.PATCH("/vcs/:vcsId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("vcsId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("VCS ID is not a number: %s", c.Param("vcsId"))).SetInternal(err)
@@ -97,7 +101,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted change VCS request").SetInternal(err)
}
- vcs, err := s.VCSService.PatchVCS(context.Background(), vcsPatch)
+ vcs, err := s.VCSService.PatchVCS(ctx, vcsPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))
@@ -105,7 +109,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change VCS ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeVCSRelationship(context.Background(), vcs); err != nil {
+ if err := s.ComposeVCSRelationship(ctx, vcs); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch updated VCS relationship").SetInternal(err)
}
@@ -117,6 +121,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
g.DELETE("/vcs/:vcsId", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("vcsId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("VCS is not a number: %s", c.Param("vcsId"))).SetInternal(err)
@@ -126,7 +131,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
ID: id,
DeleterId: c.Get(GetPrincipalIdContextKey()).(int),
}
- err = s.VCSService.DeleteVCS(context.Background(), vcsDelete)
+ err = s.VCSService.DeleteVCS(ctx, vcsDelete)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))
@@ -140,6 +145,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
g.GET("/vcs/:vcsId/repository", func(c echo.Context) error {
+ ctx := context.Background()
id, err := strconv.Atoi(c.Param("vcsId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsId"))).SetInternal(err)
@@ -148,13 +154,13 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
VCSId: &id,
}
- list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
+ list, err := s.RepositoryService.FindRepositoryList(ctx, repositoryFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for vcs ID: %v", id)).SetInternal(err)
}
for _, repository := range list {
- if err := s.ComposeRepositoryRelationship(context.Background(), repository); err != nil {
+ if err := s.ComposeRepositoryRelationship(ctx, repository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.ID)).SetInternal(err)
}
}
@@ -186,12 +192,12 @@ func (s *Server) ComposeVCSById(ctx context.Context, id int) (*api.VCS, error) {
func (s *Server) ComposeVCSRelationship(ctx context.Context, vcs *api.VCS) error {
var err error
- vcs.Creator, err = s.ComposePrincipalById(context.Background(), vcs.CreatorId)
+ vcs.Creator, err = s.ComposePrincipalById(ctx, vcs.CreatorId)
if err != nil {
return err
}
- vcs.Updater, err = s.ComposePrincipalById(context.Background(), vcs.UpdaterId)
+ vcs.Updater, err = s.ComposePrincipalById(ctx, vcs.UpdaterId)
if err != nil {
return err
}
diff --git a/server/webhook.go b/server/webhook.go
index e98e9d9cea..20164d54a5 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -27,6 +27,7 @@ var (
func (s *Server) registerWebhookRoutes(g *echo.Group) {
g.POST("/gitlab/:id", func(c echo.Context) error {
+ ctx := context.Background()
var b []byte
b, err := io.ReadAll(c.Request().Body)
if err != nil {
@@ -47,7 +48,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
repositoryFind := &api.RepositoryFind{
WebhookEndpointId: &webhookEndpointId,
}
- repository, err := s.RepositoryService.FindRepository(context.Background(), repositoryFind)
+ repository, err := s.RepositoryService.FindRepository(ctx, repositoryFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Endpoint not found: %v", webhookEndpointId))
@@ -55,7 +56,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointId)).SetInternal(err)
}
- if err := s.ComposeRepositoryRelationship(context.Background(), repository); err != nil {
+ if err := s.ComposeRepositoryRelationship(ctx, repository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)
}
@@ -140,7 +141,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
Comment: fmt.Sprintf("Ignored committed file %q, %s.", added, err.Error()),
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
s.l.Warn("Failed to create project activity to record ignored repository committed file", zap.Error(err))
}
@@ -175,7 +176,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
ProjectId: &repository.ProjectId,
Name: &mi.Database,
}
- databaseList, err := s.ComposeDatabaseListByFind(context.Background(), databaseFind)
+ databaseList, err := s.ComposeDatabaseListByFind(ctx, databaseFind)
if err != nil {
createIgnoredFileActivity(fmt.Errorf("failed to find database matching database %q referenced by the committed file", mi.Database))
continue
@@ -228,7 +229,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
// Load pipeline approval policy per environment.
if _, ok := pipelineApprovalByEnv[database.Instance.EnvironmentId]; !ok {
- p, err := s.PolicyService.GetPipelineApprovalPolicy(context.Background(), database.Instance.EnvironmentId)
+ p, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, database.Instance.EnvironmentId)
if err != nil {
createIgnoredFileActivity(fmt.Errorf("failed to find pipeline approval policy for environment %v", database.Instance.EnvironmentId))
continue
@@ -291,7 +292,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
AssigneeId: api.SYSTEM_BOT_ID,
}
- issue, err := s.CreateIssue(context.Background(), issueCreate, api.SYSTEM_BOT_ID)
+ issue, err := s.CreateIssue(ctx, issueCreate, api.SYSTEM_BOT_ID)
if err != nil {
s.l.Warn("Failed to create update schema task for added repository file", zap.Error(err),
zap.String("file", added))
@@ -319,7 +320,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
Comment: fmt.Sprintf("Created issue %q.", issue.Name),
Payload: string(bytes),
}
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
}
diff --git a/store/inbox.go b/store/inbox.go
index 3ecee7ed66..23bfebf4d2 100644
--- a/store/inbox.go
+++ b/store/inbox.go
@@ -193,7 +193,7 @@ func (s *InboxService) createInbox(ctx context.Context, tx *Tx, create *api.Inbo
activityFind := &api.ActivityFind{
ID: &activityId,
}
- inbox.Activity, err = s.activityService.FindActivity(context.Background(), activityFind)
+ inbox.Activity, err = s.activityService.FindActivity(ctx, activityFind)
if err != nil {
return nil, FormatError(err)
}
@@ -307,7 +307,7 @@ func (s *InboxService) patchInbox(ctx context.Context, tx *Tx, patch *api.InboxP
activityFind := &api.ActivityFind{
ID: &activityId,
}
- inbox.Activity, err = s.activityService.FindActivity(context.Background(), activityFind)
+ inbox.Activity, err = s.activityService.FindActivity(ctx, activityFind)
if err != nil {
return nil, FormatError(err)
}