forked from dfuse-io/dfuse-eosio
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[BLOCK-2245] prevent duplicated transaction (#47)
- Loading branch information
1 parent
48dd273
commit 4da9cc9
Showing
3 changed files
with
152 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
//Implement Least Recently Used cache to check for duplication transaction ID | ||
|
||
package resolvers | ||
|
||
import ( | ||
"container/list" | ||
) | ||
|
||
type TrxCache struct { | ||
capacity int | ||
data map[string]*list.Element | ||
order list.List | ||
} | ||
|
||
func NewTrxCache(capacity int) *TrxCache { | ||
return &TrxCache{ | ||
capacity: capacity, | ||
data: make(map[string]*list.Element), | ||
order: *list.New(), | ||
} | ||
} | ||
|
||
func (c *TrxCache) Put(key string) { | ||
if ele, exists := c.data[key]; exists { | ||
// If key already exists, move it to the front | ||
c.order.MoveToFront(ele) | ||
return | ||
} | ||
|
||
// If at capacity, remove the oldest entry | ||
if c.order.Len() == c.capacity { | ||
c.evictOldest() | ||
} | ||
|
||
// Add new entry to the front of the list and to the map | ||
ele := c.order.PushFront(key) | ||
c.data[key] = ele | ||
} | ||
|
||
func (c *TrxCache) Exists(key string) bool { | ||
_, exists := c.data[key] | ||
return exists | ||
} | ||
|
||
func (c *TrxCache) evictOldest() { | ||
// Remove the oldest entry (tail of the list) | ||
oldest := c.order.Back() | ||
if oldest != nil { | ||
c.order.Remove(oldest) | ||
delete(c.data, oldest.Value.(string)) | ||
} | ||
} |