Skip to content

Commit db70317

Browse files
author
Jiri Malek
committed
Limit document count query runtime and fallback to estimation on expire.
1 parent aad6009 commit db70317

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

internal/repository/db/bridge.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ type MongoDbBridge struct {
3333
initEpochs *sync.Once
3434
}
3535

36+
// docListCountAggregationTimeout represents a max duration of DB query executed to calculate
37+
// exact document count in filtered collection. If this duration is exceeded, the query fails
38+
// ad we fall back to full collection documents count estimation.
39+
const docListCountAggregationTimeout = 500 * time.Millisecond
40+
3641
// intZero represents an empty big value.
3742
var intZero = new(big.Int)
3843

@@ -216,3 +221,24 @@ func (db *MongoDbBridge) EstimateCount(col *mongo.Collection) (uint64, error) {
216221
}
217222
return uint64(val), nil
218223
}
224+
225+
// listDocumentsCount tries to calculate precise documents count and if it's not counted in limited
226+
// time, use general estimation to speed up the loader.
227+
func (db *MongoDbBridge) listDocumentsCount(col *mongo.Collection, filter *bson.D) (int64, error) {
228+
// try to count the proper way
229+
total, err := col.CountDocuments(context.Background(), filter, options.Count().SetMaxTime(docListCountAggregationTimeout))
230+
if err == nil {
231+
return total, nil
232+
}
233+
234+
// it failed in the limited time we gave it
235+
db.log.Errorf("can not count documents properly; %s", err.Error())
236+
237+
// just estimate the whole collection size
238+
total, err = col.EstimatedDocumentCount(context.Background())
239+
if err != nil {
240+
db.log.Errorf("can not count documents")
241+
return 0, err
242+
}
243+
return total, nil
244+
}

internal/repository/db/transaction.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ func (db *MongoDbBridge) initTrxList(col *mongo.Collection, cursor *string, coun
178178
}
179179

180180
// find how many transactions do we have in the database
181-
total, err := col.CountDocuments(context.Background(), *filter)
181+
total, err := db.listDocumentsCount(col, filter)
182182
if err != nil {
183183
db.log.Errorf("can not count transactions")
184184
return nil, err

0 commit comments

Comments
 (0)