diff --git a/validate/common.go b/validate/common.go new file mode 100644 index 0000000..e8ce5ff --- /dev/null +++ b/validate/common.go @@ -0,0 +1,104 @@ +package validate + +import ( + "context" + "fmt" + "gitea.pena/PenaSide/common/mongo" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "regexp" + "time" +) + +type t struct { + ID string `bson:"_id,omitempty"` + I int `bson:"i"` +} + +// todo в будущем в монге будут запрещены некоторые операции, надо будет обновлять +func ValidateMongo(cfg mongo.Configuration) error { + if cfg.URL == "" { + return fmt.Errorf("mongo URL is empty") + } + if cfg.DatabaseName == "" { + return fmt.Errorf("mongo database name is empty") + } + + cfg.DatabaseName = "testDBName" + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + database, err := mongo.Connect(ctx, &mongo.ConnectDeps{ + Configuration: &cfg, + Timeout: 10 * time.Second, + }) + if err != nil { + return err + } + + defer database.Drop(ctx) + + testCollection := database.Collection(cfg.DatabaseName) + + receivedChannel := make(chan string, 10) + errorChannel := make(chan error, 1) + + go func() { + defer close(receivedChannel) + defer close(errorChannel) + for i := 0; i <= 100; i++ { + d := t{ + ID: primitive.NewObjectID().Hex(), + I: i, + } + + _, err = testCollection.InsertOne(ctx, d) + if err != nil { + errorChannel <- err + } + + receivedChannel <- d.ID + } + }() + timeout := time.After(30 * time.Second) + for { + select { + case err = <-errorChannel: + if err != nil { + return fmt.Errorf("error document insert: %w", err) + } + case id := <-receivedChannel: + result := t{} + err := testCollection.FindOne(ctx, bson.M{"_id": id}).Decode(&result) + if err != nil { + return fmt.Errorf("mongo error finding document: %v", err) + } + if id != result.ID { + return fmt.Errorf("invalid id received") + } + if result.I == 100 { + return nil + } + case <-timeout: + return fmt.Errorf("timeout") + } + } +} + +func ValidateTgToken(token string) error { + if token == "" { + return fmt.Errorf("tg token is empty") + } + + // todo обдумать еще регулярку + pattern := `^\d+:.+$` + ok, err := regexp.MatchString(pattern, token) + if err != nil { + return fmt.Errorf("error validating tg token - %s: %w", token, err) + } + if !ok { + return fmt.Errorf("invalid tg token format: %s", token) + } + + return nil +}