@@ -2,19 +2,26 @@ package client
2
2
3
3
import (
4
4
"fmt"
5
+ "math/rand"
5
6
"time"
6
7
7
8
"github.com/clems4ever/go-graphkb/internal/knowledge"
8
9
"github.com/sirupsen/logrus"
9
10
)
10
11
12
+ func init () {
13
+ rand .Seed (time .Now ().UnixNano ())
14
+ }
15
+
11
16
// GraphAPI represent the graph API from a data source point of view
12
17
type GraphAPI struct {
13
18
client * GraphClient
14
19
15
20
options GraphAPIOptions
16
21
17
22
currentGraph * knowledge.Graph
23
+ // Stores the date after which the graph will be considered stale
24
+ currentGraphStaleAfter time.Time
18
25
}
19
26
20
27
// GraphAPIOptions options to pass to build graph API
@@ -39,6 +46,11 @@ type GraphAPIOptions struct {
39
46
40
47
// The backoff factor (default is 1.01)
41
48
RetryBackoffFactor float64
49
+
50
+ // The API stores the lastly pushed graph in memory to avoid fetching the entire data at every run which can be heavy on
51
+ // DB if importers run very incrementally. The anti entropy duration is a duration before forcing a synchronization against
52
+ // the server even though the graph is still stored in memory.
53
+ AntiEntropyDuration time.Duration
42
54
}
43
55
44
56
// NewGraphAPI create an emitter of graph
@@ -52,13 +64,17 @@ func NewGraphAPI(options GraphAPIOptions) *GraphAPI {
52
64
// CreateTransaction create a full graph transaction. This kind of transaction will diff the new graph
53
65
// with previous version of it.
54
66
func (gapi * GraphAPI ) CreateTransaction () (* Transaction , error ) {
55
- if gapi .currentGraph == nil {
67
+ if gapi .currentGraph == nil || gapi . currentGraphStaleAfter . Before ( time . Now ()) {
56
68
logrus .Debug ("transaction: fetching remote graph" )
57
69
g , err := gapi .ReadCurrentGraph ()
58
70
if err != nil {
59
71
return nil , fmt .Errorf ("create transaction: %w" , err )
60
72
}
61
73
gapi .currentGraph = g
74
+
75
+ quarter := int64 (gapi .options .AntiEntropyDuration ) / 4
76
+ randDelta := time .Duration (rand .Int63n (quarter * 2 ) - quarter )
77
+ gapi .currentGraphStaleAfter = time .Now ().Add (gapi .options .AntiEntropyDuration ).Add (randDelta )
62
78
}
63
79
64
80
var parallelization = gapi .options .Parallelization
0 commit comments