2019-12-06 02:16:18 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
import std/[sets, tables, options]
|
|
|
|
import rpc/[messages]
|
|
|
|
|
|
|
|
export sets, tables, messages, options
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
CacheEntry* = object
|
|
|
|
mid*: string
|
2020-09-04 06:10:32 +00:00
|
|
|
topicIDs*: seq[string]
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
MCache* = object of RootObj
|
|
|
|
msgs*: Table[string, Message]
|
2019-12-06 02:16:18 +00:00
|
|
|
history*: seq[seq[CacheEntry]]
|
|
|
|
historySize*: Natural
|
|
|
|
windowSize*: Natural
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func get*(c: MCache, mid: string): Option[Message] =
|
2020-06-19 17:29:25 +00:00
|
|
|
result = none(Message)
|
|
|
|
if mid in c.msgs:
|
|
|
|
result = some(c.msgs[mid])
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func contains*(c: MCache, mid: string): bool =
|
2020-06-19 17:29:25 +00:00
|
|
|
c.get(mid).isSome
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func put*(c: var MCache, msgId: string, msg: Message) =
|
2020-06-28 15:56:38 +00:00
|
|
|
if msgId notin c.msgs:
|
2020-09-04 06:10:32 +00:00
|
|
|
c.msgs[msgId] = msg
|
|
|
|
c.history[0].add(CacheEntry(mid: msgId, topicIDs: msg.topicIDs))
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func window*(c: MCache, topic: string): HashSet[string] =
|
2019-12-06 02:16:18 +00:00
|
|
|
result = initHashSet[string]()
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
let
|
|
|
|
len = min(c.windowSize, c.history.len)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
for i in 0..<len:
|
|
|
|
for entry in c.history[i]:
|
|
|
|
for t in entry.topicIDs:
|
|
|
|
if t == topic:
|
|
|
|
result.incl(entry.mid)
|
|
|
|
break
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func shift*(c: var MCache) =
|
|
|
|
for entry in c.history.pop():
|
|
|
|
c.msgs.del(entry.mid)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
c.history.insert(@[])
|
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
func init*(T: type MCache, window, history: Natural): T =
|
|
|
|
T(
|
|
|
|
history: newSeq[seq[CacheEntry]](history),
|
|
|
|
historySize: history,
|
|
|
|
windowSize: window
|
|
|
|
)
|