Skip to content

Commit d229046

Browse files
committed
add update limiter to help database
1 parent f829b50 commit d229046

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

pkg/common/nodes.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ func (n *NodeJSON) ID() []byte {
7474
return n.N.ID().Bytes()
7575
}
7676

77+
func (n *NodeJSON) IDString() string {
78+
return n.N.ID().String()
79+
}
80+
7781
func (n *NodeJSON) TerminalString() string {
7882
return n.N.ID().TerminalString()
7983
}

pkg/database/execution_crawler.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,58 @@ func (db *DB) InsertBlocks(
399399
return nil
400400
}
401401

402+
type UpdateLimiter struct {
403+
m map[string]time.Time
404+
ttl time.Duration
405+
lock sync.Mutex
406+
}
407+
408+
func NewUpdateLimiter(ttl time.Duration) *UpdateLimiter {
409+
limiter := &UpdateLimiter{
410+
m: map[string]time.Time{},
411+
ttl: ttl,
412+
lock: sync.Mutex{},
413+
}
414+
415+
go limiter.runCleaner()
416+
417+
return limiter
418+
}
419+
420+
func (l *UpdateLimiter) runCleaner() {
421+
for {
422+
time.Sleep(time.Minute)
423+
424+
l.lock.Lock()
425+
426+
for key, ts := range l.m {
427+
if time.Since(ts) > l.ttl {
428+
delete(l.m, key)
429+
}
430+
}
431+
432+
l.lock.Unlock()
433+
}
434+
}
435+
436+
func (l *UpdateLimiter) IsLimited(node common.NodeJSON) bool {
437+
l.lock.Lock()
438+
defer l.lock.Unlock()
439+
440+
id := node.IDString()
441+
442+
t, found := l.m[id]
443+
if found && time.Since(t) < l.ttl {
444+
return true
445+
}
446+
447+
l.m[id] = time.Now()
448+
449+
return false
450+
}
451+
452+
var limiter = NewUpdateLimiter(3 * time.Hour)
453+
402454
func (db *DB) UpsertCrawledNode(ctx context.Context, tx pgx.Tx, node common.NodeJSON) error {
403455
defer metrics.NodeUpdateInc(node.Direction.String(), node.Error)
404456

@@ -407,6 +459,10 @@ func (db *DB) UpsertCrawledNode(ctx context.Context, tx pgx.Tx, node common.Node
407459
return nil
408460
}
409461

462+
if limiter.IsLimited(node) {
463+
return nil
464+
}
465+
410466
if !node.EthNode {
411467
err := db.UpdateNotEthNode(ctx, tx, node)
412468
if err != nil {

0 commit comments

Comments
 (0)