mirror of
https://github.com/varun-r-mallya/py-libp2p.git
synced 2025-12-31 20:36:24 +00:00
Add ttl for peer data expiration (#655)
* Add ttl and last_identified to peerdata * Add test for ttl Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * Fix lint and add newsfragments Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * Fix failing ci Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * fix ttl time from 600 to 120 Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * fix test ttl timeout and lint errors Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * Fix docstrings Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> * rebase main * remove print statement --------- Signed-off-by: sukhman <sukhmansinghsaluja@gmail.com> Co-authored-by: pacrob <5199899+pacrob@users.noreply.github.com>
This commit is contained in:
@ -1,7 +1,10 @@
|
||||
from collections.abc import (
|
||||
Sequence,
|
||||
)
|
||||
from typing import Any
|
||||
import time
|
||||
from typing import (
|
||||
Any,
|
||||
)
|
||||
|
||||
from multiaddr import (
|
||||
Multiaddr,
|
||||
@ -22,6 +25,8 @@ class PeerData(IPeerData):
|
||||
metadata: dict[Any, Any]
|
||||
protocols: list[str]
|
||||
addrs: list[Multiaddr]
|
||||
last_identified: int
|
||||
ttl: int # Keep ttl=0 by default for always valid
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.pubkey = None
|
||||
@ -29,6 +34,8 @@ class PeerData(IPeerData):
|
||||
self.metadata = {}
|
||||
self.protocols = []
|
||||
self.addrs = []
|
||||
self.last_identified = int(time.time())
|
||||
self.ttl = 0
|
||||
|
||||
def get_protocols(self) -> list[str]:
|
||||
"""
|
||||
@ -113,6 +120,36 @@ class PeerData(IPeerData):
|
||||
raise PeerDataError("private key not found")
|
||||
return self.privkey
|
||||
|
||||
def update_last_identified(self) -> None:
|
||||
self.last_identified = int(time.time())
|
||||
|
||||
def get_last_identified(self) -> int:
|
||||
"""
|
||||
:return: last identified timestamp
|
||||
"""
|
||||
return self.last_identified
|
||||
|
||||
def get_ttl(self) -> int:
|
||||
"""
|
||||
:return: ttl for current peer
|
||||
"""
|
||||
return self.ttl
|
||||
|
||||
def set_ttl(self, ttl: int) -> None:
|
||||
"""
|
||||
:param ttl: ttl to set
|
||||
"""
|
||||
self.ttl = ttl
|
||||
|
||||
def is_expired(self) -> bool:
|
||||
"""
|
||||
:return: true, if last_identified+ttl > current_time
|
||||
"""
|
||||
# for ttl = 0; peer_data is always valid
|
||||
if self.ttl > 0 and self.last_identified + self.ttl < int(time.time()):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class PeerDataError(KeyError):
|
||||
"""Raised when a key is not found in peer metadata."""
|
||||
|
||||
Reference in New Issue
Block a user