47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/mrhid6/go-mongoose/mongoose"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type Server struct {
|
|
mc *mongoose.MongooseClient
|
|
col *mongo.Collection
|
|
}
|
|
|
|
// ---------- Indexes ----------
|
|
func (s *Server) ensureIndexes(ctx context.Context) error {
|
|
idxs := s.col.Indexes()
|
|
models := []mongo.IndexModel{
|
|
// frequently query by status + availableAt + priority
|
|
{
|
|
Keys: bson.D{
|
|
{"status", 1},
|
|
{"availableAt", 1},
|
|
{"priority", -1},
|
|
},
|
|
Options: options.Index().SetName("status_available_priority"),
|
|
},
|
|
// lease expiration useful for queries
|
|
{
|
|
Keys: bson.D{
|
|
{"leasedUntil", 1},
|
|
},
|
|
Options: options.Index().SetName("leased_until_idx"),
|
|
},
|
|
// TTL index on done tasks if you want automatic removal after X seconds.
|
|
// Uncomment or adjust the seconds as you need. Here we do not create by default.
|
|
// {
|
|
// Keys: bson.D{{"updatedAt", 1}},
|
|
// Options: options.Index().SetExpireAfterSeconds(60 * 60 * 24), // e.g. 24h
|
|
// },
|
|
}
|
|
_, err := idxs.CreateMany(ctx, models)
|
|
return err
|
|
}
|