From e026a34b81b570e64a45fc3ecc56ffdec1946815 Mon Sep 17 00:00:00 2001 From: syntaxsdev Date: Thu, 2 Jan 2025 15:03:31 -0500 Subject: [PATCH] refactor: mongo update --- .air.toml | 52 ++++++++++++++++++++ internal/services/mongo.go | 15 ++++++ internal/services/monitoring/health_check.go | 15 ++++-- internal/services/strategy.go | 20 ++++++++ 4 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 .air.toml diff --git a/.air.toml b/.air.toml new file mode 100644 index 0000000..498951f --- /dev/null +++ b/.air.toml @@ -0,0 +1,52 @@ +root = "." +testdata_dir = "testdata" +tmp_dir = "tmp" + +[build] + args_bin = [] + bin = "./tmp/main" + cmd = "go build -o ./tmp/main ." + delay = 1000 + exclude_dir = ["assets", "tmp", "vendor", "testdata"] + exclude_file = [] + exclude_regex = ["_test.go"] + exclude_unchanged = false + follow_symlink = false + full_bin = "" + include_dir = [] + include_ext = ["go", "tpl", "tmpl", "html"] + include_file = [] + kill_delay = "0s" + log = "build-errors.log" + poll = false + poll_interval = 0 + post_cmd = [] + pre_cmd = [] + rerun = false + rerun_delay = 500 + send_interrupt = false + stop_on_error = false + +[color] + app = "" + build = "yellow" + main = "magenta" + runner = "green" + watcher = "cyan" + +[log] + main_only = false + silent = false + time = false + +[misc] + clean_on_exit = false + +[proxy] + app_port = 0 + enabled = false + proxy_port = 0 + +[screen] + clear_on_rebuild = false + keep_scroll = true diff --git a/internal/services/mongo.go b/internal/services/mongo.go index be4691c..6916582 100644 --- a/internal/services/mongo.go +++ b/internal/services/mongo.go @@ -4,6 +4,7 @@ import ( "context" "time" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/mongo" ) @@ -25,6 +26,20 @@ func (s *MongoService) Insert(collection string, item interface{}) (interface{}, } +func (s *MongoService) Update(collection string, filter map[string]any, item map[string]interface{}) (interface{}, error) { + coll := s.Client.Database(s.DatabaseName).Collection(collection) + bsonFilter := bson.M(filter) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + result, err := coll.UpdateOne(ctx, bsonFilter, item) + if err != nil { + return nil, err + } + return result.UpsertedID, nil + +} + func (s *MongoService) First(collection string, filter interface{}, result interface{}) error { coll := s.Client.Database(s.DatabaseName).Collection(collection) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/internal/services/monitoring/health_check.go b/internal/services/monitoring/health_check.go index 06a3141..1dbe072 100644 --- a/internal/services/monitoring/health_check.go +++ b/internal/services/monitoring/health_check.go @@ -52,16 +52,19 @@ func NewHealthChecker(client *http.Client) *HealthChecker { func (h *HealthChecker) Check(data *HealthData, s *models.Strategy) { if s.Options.Active && s.HasHealthCheck() { url, _ := s.HealthCheckUrl() - resp, err := h.client.Get(url) - if err != nil || (resp.StatusCode < 200 || resp.StatusCode > 203) { + resp, _ := h.client.Get(url) + if resp == nil || (resp.StatusCode < 200 || resp.StatusCode > 203) { data.Update(false) + log.Printf("WARN: Health check error. Error count: %v", data.FailureCount) } else { data.Update(true) } } + // Max 5 unhealthy checks if data.FailureCount == 5 { s.Options.Active = false + log.Printf("INFO: %s has been switched off due to failed healthchecks.\n", s.Name) } } @@ -88,7 +91,13 @@ func (h *HealthChecker) BackgroundProcess(s *services.StrategyService) { } h.mu.Unlock() val := h.healthData[strat.Name] - go h.Check(val, &strat) + // Only launch on active strategies + h.Check(val, &strat) + + if !strat.Options.Active { + s.UpdateStrategy(&strat) + + } } time.Sleep(time.Duration(defaultWait) * time.Second) } diff --git a/internal/services/strategy.go b/internal/services/strategy.go index cad86de..5d115ce 100644 --- a/internal/services/strategy.go +++ b/internal/services/strategy.go @@ -1,6 +1,9 @@ package services import ( + "fmt" + "log" + "github.com/syntaxsdev/mercury/models" "go.mongodb.org/mongo-driver/bson" ) @@ -24,6 +27,23 @@ func (s *StrategyService) GetAllStrategies() ([]models.Strategy, error) { return results, nil } +// Update Strategy +func (s *StrategyService) UpdateStrategy(strat *models.Strategy) error { + if strat.Name == "" { + log.Println("ERROR: `Name` field does not exist.") + return fmt.Errorf("`Name` does not exist.") + } + + filter := bson.M{"name": strat.Name} + update := map[string]interface{}{"$set": strat} + _, err := s.db.Update("strategies", filter, update) + + if err != nil { + return fmt.Errorf("ERROR: Failed to update strategy %s: %w", strat.Name, err) + } + return nil +} + // // Create A Strategy // func CreateStrategy(m *MongoService) (*models.Strategy, error) { // var newStrategy models.Strategy