Skip to content

Commit

Permalink
Refactor caching to cache sanitized endpoints
Browse files Browse the repository at this point in the history
Improves implementation speed drastically.
  • Loading branch information
yashasvi-ranawat committed May 5, 2024
1 parent 3ee9bee commit 2cbbf30
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 18 deletions.
28 changes: 11 additions & 17 deletions bitcash/network/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
# Default API call total time timeout
DEFAULT_TIMEOUT = 5

# Default blockheigt cache timeout
DEFAULT_BLOCKHEIGHT_CACHE_TIME = 300
# Default sanitized endpoint, based on blockheigt, cache timeout
DEFAULT_SANITIZED_ENDPOINTS_CACHE_TIME = 300

BCH_TO_SAT_MULTIPLIER = 100000000

Expand Down Expand Up @@ -110,8 +110,15 @@ def get_endpoints_for(network):
return tuple(endpoints)


@time_cache(max_age=DEFAULT_BLOCKHEIGHT_CACHE_TIME, cache_size=1)
def _get_endpoints_blockheight(endpoints):
@time_cache(max_age=DEFAULT_SANITIZED_ENDPOINTS_CACHE_TIME, cache_size=len(NETWORKS))
def get_sanitized_endpoints_for(network="mainnet"):
"""Gets endpoints sanitized by their blockheights.
Solves the problem when an endpoint is stuck on an older block.
:param network: network in ["mainnet", "testnet", "regtest"].
"""
endpoints = get_endpoints_for(network)

endpoints_blockheight = [0 for _ in range(len(endpoints))]

for i, endpoint in enumerate(endpoints):
Expand All @@ -123,19 +130,6 @@ def _get_endpoints_blockheight(endpoints):
if sum(endpoints_blockheight) == 0:
raise ConnectionError("All APIs are unreachable.") # pragma: no cover

return tuple(endpoints_blockheight)


def get_sanitized_endpoints_for(network="mainnet"):
"""Gets endpoints sanitized by their blockheights.
Solves the problem when an endpoint is stuck on an older block.
:param network: network in ["mainnet", "testnet", "regtest"].
"""
endpoints = get_endpoints_for(network)

endpoints_blockheight = _get_endpoints_blockheight(endpoints)

# remove unreachable or un-synced endpoints
highest_blockheight = max(endpoints_blockheight)
pop_indices = []
Expand Down
2 changes: 1 addition & 1 deletion tests/network/test_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def mock_get_endpoints_for(network):
def test_get_ordered_endpoints_for():
monkeypatch = MonkeyPatch()
monkeypatch.setattr(_services, "get_endpoints_for", mock_get_endpoints_for)
endpoints = get_sanitized_endpoints_for("mainnet")
endpoints = get_sanitized_endpoints_for("mock_mainnet")
assert len(endpoints) == 4
for endpoint in endpoints:
assert endpoint.get_blockheight() == 4
Expand Down

0 comments on commit 2cbbf30

Please sign in to comment.