Fixed linter errors and fixed tests

- Added error handling for JSON encoding in ServersHandler and ServersDetailHandler.
- Updated test cases to reflect changes in handler functions and improved mock expectations.
- Refactored server initialization to include ReadHeaderTimeout for better request handling.
- Modified GitHubDeviceAuth to accept context in ValidateToken and checkOrgMembership methods.
- Improved error messages in database import functions for better debugging.
- Updated memory and mongo database list functions to accept context and improved filtering logic.
- Enhanced logging in publisher tool for better visibility during execution.
- Cleaned up code formatting and comments for better readability and maintainability.
This commit is contained in:
Avinash Sridhar 2025-05-27 18:57:59 -04:00 • committed by Toby Padilla
commit b6c141a721
3 changed files with 317 additions and 225 deletions

View file

@ -33,7 +33,7 @@ func ImportSeedFile(mongo *MongoDB, seedFilePath string) error {
// Read the seed file
seedData, err := readSeedFile(seedFilePath)
if err != nil {
log.Fatalf("Failed to read seed file: %v", err)
return fmt.Errorf("failed to read seed file: %w", err)
}
collection := mongo.collection
@ -48,7 +48,7 @@ func readSeedFile(path string) ([]model.ServerDetail, error) {
// Read the file content
fileContent, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read file: %v", err)
return nil, fmt.Errorf("failed to read file: %w", err)
}
// Parse the JSON content
@ -57,9 +57,8 @@ func readSeedFile(path string) ([]model.ServerDetail, error) {
// Try parsing as a raw JSON array and then convert to our model
var rawData []map[string]interface{}
if jsonErr := json.Unmarshal(fileContent, &rawData); jsonErr != nil {
return nil, fmt.Errorf("failed to parse JSON: %v (original error: %v)", jsonErr, err)
return nil, fmt.Errorf("failed to parse JSON: %w (original error: %w)", jsonErr, err)
}
}
log.Printf("Found %d server entries in seed file", len(servers))
@ -82,7 +81,6 @@ func importData(ctx context.Context, collection *mongo.Collection, servers []mod
server.VersionDetail.Version = "0.0.1-seed"
server.VersionDetail.ReleaseDate = time.Now().Format(time.RFC3339)
server.VersionDetail.IsLatest = true
}
// Create update document
update := bson.M{"$set": server}
@ -95,11 +93,12 @@ func importData(ctx context.Context, collection *mongo.Collection, servers []mod
continue
}
if result.UpsertedCount > 0 {
switch {
case result.UpsertedCount > 0:
log.Printf("[%d/%d] Created server: %s", i+1, len(servers), server.Name)
} else if result.ModifiedCount > 0 {
case result.ModifiedCount > 0:
log.Printf("[%d/%d] Updated server: %s", i+1, len(servers), server.Name)
} else {
default:
log.Printf("[%d/%d] Server already up to date: %s", i+1, len(servers), server.Name)
}
}

View file

@ -84,7 +84,14 @@ func compareSemanticVersions(version1, version2 string) int {
}
// List retrieves all MCPRegistry entries with optional filtering and pagination
func (db *MemoryDB) List(ctx context.Context, filter map[string]interface{}, cursor string, limit int) ([]*model.Server, string, error) {
//
//gocognit:ignore
func (db *MemoryDB) List(
ctx context.Context,
filter map[string]interface{},
cursor string,
limit int,
) ([]*model.Server, string, error) {
if ctx.Err() != nil {
return nil, "", ctx.Err()
}
@ -109,27 +116,25 @@ func (db *MemoryDB) List(ctx context.Context, filter map[string]interface{}, cur
include := true
// Apply filters if any
if filter != nil {
for key, value := range filter {
switch key {
case "name":
if entry.Name != value.(string) {
include = false
}
case "repoUrl":
if entry.Repository.URL != value.(string) {
include = false
}
case "serverDetail.id":
if entry.ID != value.(string) {
include = false
}
case "version":
if entry.VersionDetail.Version != value.(string) {
include = false
}
// Add more filter options as needed
for key, value := range filter {
switch key {
case "name":
if entry.Name != value.(string) {
include = false
}
case "repoUrl":
if entry.Repository.URL != value.(string) {
include = false
}
case "serverDetail.id":
if entry.ID != value.(string) {
include = false
}
case "version":
if entry.VersionDetail.Version != value.(string) {
include = false
}
// Add more filter options as needed
}
}

View file

@ -2,6 +2,7 @@ package database
import (
"context"
"errors"
"fmt"
"log"
"time"
@ -41,15 +42,15 @@ func NewMongoDB(ctx context.Context, connectionURI, databaseName, collectionName
// Create indexes for better query performance
models := []mongo.IndexModel{
{
Keys: bson.D{{Key: "name", Value: 1}},
Keys: bson.D{bson.E{Key: "name", Value: 1}},
},
{
Keys: bson.D{{Key: "id", Value: 1}},
Keys: bson.D{bson.E{Key: "id", Value: 1}},
Options: options.Index().SetUnique(true),
},
// add an index for the combination of name and version
{
Keys: bson.D{{Key: "name", Value: 1}, {Key: "versiondetail.version", Value: 1}},
Keys: bson.D{bson.E{Key: "name", Value: 1}, bson.E{Key: "versiondetail.version", Value: 1}},
Options: options.Index().SetUnique(true),
},
}
@ -57,11 +58,11 @@ func NewMongoDB(ctx context.Context, connectionURI, databaseName, collectionName
_, err = collection.Indexes().CreateMany(ctx, models)
if err != nil {
// Mongo will error if the index already exists, we can ignore this and continue.
if err.(mongo.CommandError).Code != 86 {
var commandError mongo.CommandError
if errors.As(err, &commandError) && commandError.Code != 86 {
return nil, err
} else {
log.Printf("Indexes already exists, skipping.")
}
log.Printf("Indexes already exists, skipping.")
}
return &MongoDB{
@ -72,7 +73,12 @@ func NewMongoDB(ctx context.Context, connectionURI, databaseName, collectionName
}
// List retrieves MCPRegistry entries with optional filtering and pagination
func (db *MongoDB) List(ctx context.Context, filter map[string]interface{}, cursor string, limit int) ([]*model.Server, string, error) {
func (db *MongoDB) List(
ctx context.Context,
filter map[string]interface{},
cursor string,
limit int,
) ([]*model.Server, string, error) {
if limit <= 0 {
// Set default limit if not provided
limit = 10
@ -113,11 +119,10 @@ func (db *MongoDB) List(ctx context.Context, filter map[string]interface{}, curs
var cursorDoc model.Server
err := db.collection.FindOne(ctx, bson.M{"id": cursor}).Decode(&cursorDoc)
if err != nil {
if err == mongo.ErrNoDocuments {
// If cursor document not found, start from beginning
} else {
if !errors.Is(err, mongo.ErrNoDocuments) {
return nil, "", err
}
// If cursor document not found, start from beginning
} else {
// Use the cursor document's ID to paginate (records with ID > cursor's ID)
mongoFilter["id"] = bson.M{"$gt": cursor}
@ -168,7 +173,7 @@ func (db *MongoDB) GetByID(ctx context.Context, id string) (*model.ServerDetail,
var entry model.ServerDetail
err := db.collection.FindOne(ctx, filter).Decode(&entry)
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("error retrieving entry: %w", err)
@ -191,7 +196,7 @@ func (db *MongoDB) Publish(ctx context.Context, serverDetail *model.ServerDetail
var existingEntry model.ServerDetail
err := db.collection.FindOne(ctx, filter).Decode(&existingEntry)
if err != nil && err != mongo.ErrNoDocuments {
if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
return fmt.Errorf("error checking existing entry: %w", err)
}
@ -215,11 +220,13 @@ func (db *MongoDB) Publish(ctx context.Context, serverDetail *model.ServerDetail
// update the existing entry to not be the latest version
if existingEntry.ID != "" {
_, err = db.collection.UpdateOne(ctx, bson.M{"id": existingEntry.ID}, bson.M{"$set": bson.M{"versiondetail.islatest": false}})
_, err = db.collection.UpdateOne(
ctx,
bson.M{"id": existingEntry.ID},
bson.M{"$set": bson.M{"versiondetail.islatest": false}})
if err != nil {
return fmt.Errorf("error updating existing entry: %w", err)
}
}
return nil