2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2023-01-20 14:47:40 +00:00
|
|
|
# Copyright (c) 2023 Status Research & Development GmbH
|
2022-07-01 18:19:57 +00:00
|
|
|
# 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.
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2021-03-09 12:22:52 +00:00
|
|
|
|
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
|
2022-07-27 11:47:50 +00:00
|
|
|
mid*: MessageId
|
2024-03-25 11:06:34 +00:00
|
|
|
topic*: string
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-04 06:10:32 +00:00
|
|
|
MCache* = object of RootObj
|
2022-07-27 11:47:50 +00:00
|
|
|
msgs*: Table[MessageId, Message]
|
2019-12-06 02:16:18 +00:00
|
|
|
history*: seq[seq[CacheEntry]]
|
|
|
|
windowSize*: Natural
|
|
|
|
|
2022-07-27 11:47:50 +00:00
|
|
|
func get*(c: MCache, mid: MessageId): Option[Message] =
|
2020-06-19 17:29:25 +00:00
|
|
|
if mid in c.msgs:
|
2021-03-09 12:22:52 +00:00
|
|
|
try: some(c.msgs[mid])
|
|
|
|
except KeyError: raiseAssert "checked"
|
2020-12-03 19:53:16 +00:00
|
|
|
else:
|
|
|
|
none(Message)
|
2020-06-19 17:29:25 +00:00
|
|
|
|
2022-07-27 11:47:50 +00:00
|
|
|
func contains*(c: MCache, mid: MessageId): bool =
|
2021-03-09 12:22:52 +00:00
|
|
|
mid in c.msgs
|
2020-06-19 17:29:25 +00:00
|
|
|
|
2022-07-27 11:47:50 +00:00
|
|
|
func put*(c: var MCache, msgId: MessageId, msg: Message) =
|
2020-12-03 19:53:16 +00:00
|
|
|
if not c.msgs.hasKeyOrPut(msgId, msg):
|
|
|
|
# Only add cache entry if the message was not already in the cache
|
2024-03-25 11:06:34 +00:00
|
|
|
c.history[0].add(CacheEntry(mid: msgId, topic: msg.topic))
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2022-07-27 11:47:50 +00:00
|
|
|
func window*(c: MCache, topic: string): HashSet[MessageId] =
|
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]:
|
2024-03-25 11:06:34 +00:00
|
|
|
if entry.topic == topic:
|
|
|
|
result.incl(entry.mid)
|
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),
|
|
|
|
windowSize: window
|
|
|
|
)
|