From 1dbd5dbd940999b29ba254ae81a24e8841f74faf Mon Sep 17 00:00:00 2001 From: ycdesu Date: Fri, 10 Jun 2022 12:16:58 +0800 Subject: [PATCH 1/2] sync: only sync when previous operation is done --- pkg/server/routes.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pkg/server/routes.go b/pkg/server/routes.go index 94e8f5fd1..4849ea54e 100644 --- a/pkg/server/routes.go +++ b/pkg/server/routes.go @@ -77,11 +77,13 @@ func (s *Server) newEngine() *gin.Engine { }) r.POST("/api/environment/sync", func(c *gin.Context) { - go func() { - if err := s.Environ.Sync(context.Background()); err != nil { - logrus.WithError(err).Error("sync error") - } - }() + if s.Environ.IsSyncing() == bbgo.SyncDone { + go func() { + if err := s.Environ.Sync(context.Background()); err != nil { + logrus.WithError(err).Error("sync error") + } + }() + } c.JSON(http.StatusOK, gin.H{ "success": true, From 9a71c9a5eb469050712f2fa07aa26c042f3e44c8 Mon Sep 17 00:00:00 2001 From: ycdesu Date: Fri, 10 Jun 2022 12:19:38 +0800 Subject: [PATCH 2/2] web: pass root ctx into setup func --- pkg/server/routes.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pkg/server/routes.go b/pkg/server/routes.go index 4849ea54e..30cae8232 100644 --- a/pkg/server/routes.go +++ b/pkg/server/routes.go @@ -48,7 +48,7 @@ type Server struct { srv *http.Server } -func (s *Server) newEngine() *gin.Engine { +func (s *Server) newEngine(ctx context.Context) *gin.Engine { r := gin.Default() r.Use(cors.New(cors.Config{ AllowOrigins: []string{"*"}, @@ -79,7 +79,9 @@ func (s *Server) newEngine() *gin.Engine { r.POST("/api/environment/sync", func(c *gin.Context) { if s.Environ.IsSyncing() == bbgo.SyncDone { go func() { - if err := s.Environ.Sync(context.Background()); err != nil { + // We use the root context here because the syncing operation is a background goroutine. + // It should not be terminated if the request is disconnected. + if err := s.Environ.Sync(ctx); err != nil { logrus.WithError(err).Error("sync error") } }() @@ -251,7 +253,7 @@ func (s *Server) newEngine() *gin.Engine { } func (s *Server) RunWithListener(ctx context.Context, l net.Listener) error { - r := s.newEngine() + r := s.newEngine(ctx) bind := l.Addr().String() if s.OpenInBrowser { @@ -263,7 +265,7 @@ func (s *Server) RunWithListener(ctx context.Context, l net.Listener) error { } func (s *Server) Run(ctx context.Context, bindArgs ...string) error { - r := s.newEngine() + r := s.newEngine(ctx) bind := resolveBind(bindArgs) if s.OpenInBrowser { openBrowser(ctx, bind)