Skip to content

Commit d9a41f8

Browse files
committed
feat: add index and TTL
1 parent 972c686 commit d9a41f8

1 file changed

Lines changed: 30 additions & 1 deletion

File tree

internal/services/usage.go

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,38 @@ type UsageService struct {
2121

2222
func NewUsageService(db *db.DB, cfg *cfg.Cfg, logger *logger.Logger) *UsageService {
2323
base := NewBaseService(db, cfg, logger)
24+
collection := base.db.Collection((models.Usage{}).CollectionName())
25+
26+
indexModels := []mongo.IndexModel{
27+
{
28+
Keys: bson.D{
29+
{Key: "user_id", Value: 1},
30+
{Key: "project_id", Value: 1},
31+
{Key: "model_slug", Value: 1},
32+
{Key: "hour_bucket", Value: 1},
33+
},
34+
Options: options.Index().SetUnique(true),
35+
},
36+
{
37+
Keys: bson.D{
38+
{Key: "project_id", Value: 1},
39+
},
40+
},
41+
{
42+
Keys: bson.D{
43+
{Key: "hour_bucket", Value: 1},
44+
},
45+
Options: options.Index().SetExpireAfterSeconds(14 * 24 * 60 * 60), // 2 weeks TTL
46+
},
47+
}
48+
_, err := collection.Indexes().CreateMany(context.Background(), indexModels)
49+
if err != nil {
50+
logger.Error("Failed to create indexes for usages collection", err)
51+
}
52+
2453
return &UsageService{
2554
BaseService: base,
26-
usageCollection: base.db.Collection((models.Usage{}).CollectionName()),
55+
usageCollection: collection,
2756
}
2857
}
2958

0 commit comments

Comments
 (0)