2
2
3
3
/** A CompositeDatasource delegates queries to an consecutive list of datasources. */
4
4
5
- var Datasource = require ( './Datasource' ) ;
5
+ var Datasource = require ( './Datasource' ) ,
6
+ LRU = require ( 'lru-cache' ) ;
6
7
7
8
// Creates a new CompositeDatasource
8
9
function CompositeDatasource ( options ) {
@@ -28,6 +29,7 @@ function CompositeDatasource(options) {
28
29
this . _datasourceNames . push ( datasourceName ) ;
29
30
}
30
31
}
32
+ this . _countCache = LRU ( { max : 1000 , maxAge : 1000 * 60 * 60 * 3 } ) ;
31
33
}
32
34
Datasource . extend ( CompositeDatasource ) ;
33
35
@@ -53,12 +55,21 @@ CompositeDatasource.prototype._getDatasourceById = function(datasourceIndex) {
53
55
54
56
// Count the amount of triple in the query result to get an exact count.
55
57
CompositeDatasource . prototype . _getExactCount = function ( datasource , query , cb ) {
58
+ // Try to find a cache match
59
+ var cacheKey = query . subject + "|" + query . predicate + "|" + query . object ;
60
+ var cache = this . _countCache , count = cache . get ( cacheKey ) ;
61
+ if ( count ) return setImmediate ( cb , count ) ;
62
+
63
+ // Otherwise, count all the triples manually
56
64
var emptyQuery = { offset : 0 , subject : query . subject , predicate : query . predicate , object : query . object } ;
57
65
var exactCount = 0 ;
58
66
var countingTripleStream = { push : function ( triple ) {
59
67
if ( triple ) {
60
68
exactCount ++ ;
61
69
} else {
70
+ // Cache large values; small ones are calculated fast anyway
71
+ if ( exactCount > 1000 )
72
+ cache . set ( cacheKey , exactCount ) ;
62
73
cb ( exactCount ) ;
63
74
}
64
75
} } ;
0 commit comments