-
Notifications
You must be signed in to change notification settings - Fork 516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[multi-tenancy] add profile resource management #928
Closed
TimoGlastra
wants to merge
2
commits into
openwallet-foundation:main
from
TimoGlastra:multitenancy/profile-cache
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,94 @@ | ||
"""Cache for multitenancy profiles.""" | ||
|
||
import logging | ||
import sys | ||
from collections import OrderedDict | ||
from typing import Optional | ||
|
||
from ..core.profile import Profile | ||
|
||
LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
class ProfileCache: | ||
"""Profile cache that caches based on LRU strategy.""" | ||
|
||
def __init__(self, capacity: int): | ||
"""Initialize ProfileCache. | ||
|
||
Args: | ||
capacity: The capacity of the cache. If capacity is exceeded | ||
profiles are closed. | ||
""" | ||
|
||
self.profiles: OrderedDict[str, Profile] = OrderedDict() | ||
self.capacity = capacity | ||
|
||
async def _cleanup(self): | ||
for (key, profile) in self.profiles.items(): | ||
# When ref count is 4 we can assume the profile is not referenced | ||
# 1 = profiles dict | ||
# 2 = self.profiles.items() | ||
# 3 = profile above | ||
# 4 = sys.getrefcount | ||
if sys.getrefcount(profile) <= 4: | ||
LOGGER.debug(f"closing profile with id {key}") | ||
del self.profiles[key] | ||
await profile.close() | ||
|
||
if len(self.profiles) <= self.capacity: | ||
break | ||
|
||
def get(self, key: str) -> Optional[Profile]: | ||
"""Get profile with associated key from cache. | ||
|
||
Args: | ||
key (str): the key to get the profile for. | ||
|
||
Returns: | ||
Optional[Profile]: Profile if found in cache. | ||
|
||
""" | ||
if key not in self.profiles: | ||
return None | ||
else: | ||
self.profiles.move_to_end(key) | ||
return self.profiles[key] | ||
|
||
def has(self, key: str) -> bool: | ||
"""Check whether there is a profile with associated key in the cache. | ||
|
||
Args: | ||
key (str): the key to check for a profile | ||
|
||
Returns: | ||
bool: Whether the key exists in the cache | ||
|
||
""" | ||
return key in self.profiles | ||
|
||
async def put(self, key: str, value: Profile) -> None: | ||
"""Add profile with associated key to the cache. | ||
|
||
If new profile exceeds the cache capacity least recently used profiles | ||
that are not used will be removed from the cache. | ||
|
||
Args: | ||
key (str): the key to set | ||
value (Profile): the profile to set | ||
""" | ||
self.profiles[key] = value | ||
self.profiles.move_to_end(key) | ||
LOGGER.debug(f"setting profile with id {key} in profile cache") | ||
|
||
if len(self.profiles) > self.capacity: | ||
LOGGER.debug(f"profile limit of {self.capacity} reached. cleaning...") | ||
await self._cleanup() | ||
|
||
def remove(self, key: str): | ||
"""Remove profile with associated key from the cache. | ||
|
||
Args: | ||
key (str): The key to remove from the cache. | ||
""" | ||
del self.profiles[key] |
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,100 @@ | ||
import sys | ||
from asynctest import TestCase as AsyncTestCase | ||
from asynctest import mock as async_mock | ||
|
||
from ..cache import ProfileCache | ||
|
||
|
||
class TestProfileCache(AsyncTestCase): | ||
async def setUp(self): | ||
pass | ||
|
||
async def test_cache_cleanup_capacity_reached(self): | ||
with async_mock.patch.object(ProfileCache, "_cleanup") as _cleanup: | ||
cache = ProfileCache(1) | ||
|
||
await cache.put("1", async_mock.MagicMock()) | ||
_cleanup.assert_not_called() | ||
|
||
await cache.put("2", async_mock.MagicMock()) | ||
_cleanup.assert_called_once() | ||
|
||
async def test_get_not_in_cache(self): | ||
cache = ProfileCache(1) | ||
|
||
assert cache.get("1") is None | ||
|
||
async def test_put_get_in_cache(self): | ||
cache = ProfileCache(1) | ||
|
||
profile = async_mock.MagicMock() | ||
await cache.put("1", profile) | ||
|
||
assert cache.get("1") is profile | ||
|
||
async def test_remove(self): | ||
cache = ProfileCache(1) | ||
|
||
profile = async_mock.MagicMock() | ||
await cache.put("1", profile) | ||
|
||
assert cache.get("1") is profile | ||
|
||
cache.remove("1") | ||
|
||
assert cache.get("1") is None | ||
|
||
async def test_has_true(self): | ||
cache = ProfileCache(1) | ||
|
||
profile = async_mock.MagicMock() | ||
|
||
assert cache.has("1") is False | ||
await cache.put("1", profile) | ||
assert cache.has("1") is True | ||
|
||
async def test_cleanup(self): | ||
cache = ProfileCache(1) | ||
|
||
with async_mock.patch.object(sys, "getrefcount") as getrefcount: | ||
getrefcount.return_value = 4 | ||
|
||
profile1 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
profile2 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
|
||
await cache.put("1", profile1) | ||
|
||
assert len(cache.profiles) == 1 | ||
|
||
await cache.put("2", profile2) | ||
|
||
assert len(cache.profiles) == 1 | ||
assert cache.get("1") == None | ||
profile1.close.assert_called_once() | ||
|
||
async def test_cleanup_reference(self): | ||
cache = ProfileCache(3) | ||
|
||
with async_mock.patch.object(sys, "getrefcount") as getrefcount: | ||
getrefcount.side_effect = [6, 4] | ||
|
||
profile1 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
profile2 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
profile3 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
profile4 = async_mock.MagicMock(close=async_mock.CoroutineMock()) | ||
|
||
await cache.put("1", profile1) | ||
await cache.put("2", profile2) | ||
await cache.put("3", profile3) | ||
|
||
assert len(cache.profiles) == 3 | ||
|
||
await cache.put("4", profile4) | ||
|
||
assert len(cache.profiles) == 3 | ||
assert cache.get("1") == profile1 | ||
assert cache.get("2") == None | ||
assert cache.get("3") == profile3 | ||
assert cache.get("4") == profile4 | ||
|
||
profile2.close.assert_called_once() |
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems a bit odd that this will always iterate through the profiles, short-circuiting if there is one to be cleaned up and we are now below max capacity. Also
self.profiles.items()
will increase the refcount of the dict itself but not the entries it contains, as I understand it (and according to my test just now).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not that happy with this approach myself. I'll see if I can rework it a bit.
Do you have a suggestion on how to approach this? Do you think the way ledger handles refcounting will also work for here?