Skip to content

Commit

Permalink
refactor: mongo update
Browse files Browse the repository at this point in the history
  • Loading branch information
syntaxsdev committed Jan 2, 2025
1 parent f0eb735 commit e026a34
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 3 deletions.
52 changes: 52 additions & 0 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions internal/services/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
)

Expand All @@ -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)
Expand Down
15 changes: 12 additions & 3 deletions internal/services/monitoring/health_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand All @@ -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)
}
Expand Down
20 changes: 20 additions & 0 deletions internal/services/strategy.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package services

import (
"fmt"
"log"

"github.com/syntaxsdev/mercury/models"
"go.mongodb.org/mongo-driver/bson"
)
Expand All @@ -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
Expand Down

0 comments on commit e026a34

Please sign in to comment.