Skip to content

Commit

Permalink
feat(mongodb.go): add sanitization functions for field names and docu…
Browse files Browse the repository at this point in the history
…ments to prevent issues with MongoDB

refactor(mongodb.go): update SaveTraces method to sanitize trace documents before saving to MongoDB
  • Loading branch information
HyunSu1768 committed Sep 11, 2024
1 parent 6578eff commit 79aa0c9
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion internal/repository/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"fmt"
"log"
"otel-trace-reciever/internal/models"
"strings"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
Expand Down Expand Up @@ -34,14 +36,57 @@ func NewMongoRepository(uri string) (*MongoRepository, error) {
}, nil
}

func sanitizeFieldName(name string) string {
return strings.ReplaceAll(name, ".", "_")
}

func sanitizeDocument(doc bson.M) bson.M {
result := make(bson.M)
for k, v := range doc {
newKey := sanitizeFieldName(k)
switch val := v.(type) {
case bson.M:
result[newKey] = sanitizeDocument(val)
case []interface{}:
result[newKey] = sanitizeArray(val)
default:
result[newKey] = val
}
}
return result
}

func sanitizeArray(arr []interface{}) []interface{} {
result := make([]interface{}, len(arr))
for i, v := range arr {
if doc, ok := v.(bson.M); ok {
result[i] = sanitizeDocument(doc)
} else {
result[i] = v
}
}
return result
}

func (r *MongoRepository) SaveTraces(ctx context.Context, traces []*models.Trace) error {
if len(traces) == 0 {
return nil
}

documents := make([]interface{}, len(traces))
for i, trace := range traces {
documents[i] = trace
// Convert trace to BSON and sanitize field names
bsonDoc, err := bson.Marshal(trace)
if err != nil {
return fmt.Errorf("failed to marshal trace: %v", err)
}
var doc bson.M
err = bson.Unmarshal(bsonDoc, &doc)
if err != nil {
return fmt.Errorf("failed to unmarshal trace: %v", err)
}
sanitizedDoc := sanitizeDocument(doc)
documents[i] = sanitizedDoc
}

result, err := r.traceCollection.InsertMany(ctx, documents)
Expand Down

0 comments on commit 79aa0c9

Please sign in to comment.