diff --git a/src/practical/account_pool.py b/src/practical/account_pool.py new file mode 100644 index 0000000..6bead2a --- /dev/null +++ b/src/practical/account_pool.py @@ -0,0 +1,57 @@ +import queue +import time + + +class AccountPool: + """Thread-safe pool of account identifiers, handed out oldest-idle-first. + + Callers check an account out with `get_account()` and must return it with `release_account()` + when done. If none are available, `get_account()` blocks (up to `timeout` seconds) until one is + released, so this is safe to share across threads that each need exclusive use of an account. + """ + + class AccountPoolTimeoutError(Exception): + """Raised when no account becomes available within the pool's timeout.""" + + def __init__(self, timeout: float): + super().__init__(f"No accounts available after {timeout} seconds") + + def __init__(self, accounts, timeout: float = 30): + self.timeout = timeout + self.account_queue = queue.PriorityQueue[tuple[int, str]]() + self.accounts = accounts + self.outstanding_accounts: set[str] = set() + + for account in accounts: + self.account_queue.put((time.monotonic_ns(), account)) + + def add_account(self, account: str): + """Add a new account to the pool, immediately available for checkout.""" + self.accounts.append(account) + self.account_queue.put((time.monotonic_ns(), account)) + + def get_account(self) -> str: + """Check out and return the account that's been idle longest, blocking until one is free. + + Raises `AccountPoolTimeoutError` if none becomes available within `self.timeout` seconds. + """ + try: + _, account = self.account_queue.get(block=True, timeout=self.timeout) + except queue.Empty: + raise self.AccountPoolTimeoutError(timeout=self.timeout) + + self.outstanding_accounts.add(account) + return account + + def release_account(self, account): + """Return a checked-out account to the pool.""" + self.outstanding_accounts.remove(account) + self.account_queue.put((time.monotonic_ns(), account)) + + def size(self): + """Return the total number of accounts in the pool, checked out or not.""" + return len(self.accounts) + + def used_accounts(self): + """Return the accounts currently checked out.""" + return list(self.outstanding_accounts) diff --git a/src/singly_linked_lists/intersection_two_linked_lists.py b/src/singly_linked_lists/intersection_two_linked_lists.py index 2d27a55..bc50451 100644 --- a/src/singly_linked_lists/intersection_two_linked_lists.py +++ b/src/singly_linked_lists/intersection_two_linked_lists.py @@ -15,8 +15,8 @@ def get_intersection_node( cover equal total distance and meet at the intersection (or both reach None if there is none). Time: O(N), Space: O(1). """ - node_a: SinglyLinkedListNode = head_a - node_b: SinglyLinkedListNode = head_b + node_a = head_a + node_b = head_b while node_a != node_b: node_a = node_a.next diff --git a/tests/practical/test_account_pool.py b/tests/practical/test_account_pool.py new file mode 100644 index 0000000..1954856 --- /dev/null +++ b/tests/practical/test_account_pool.py @@ -0,0 +1,92 @@ +import threading + +import pytest + +from src.practical.account_pool import AccountPool + + +def test_account_pool_init(): + accounts = ["account1", "account2", "account3"] + pool = AccountPool(accounts) + + assert pool.size() == 3 + assert pool.used_accounts() == [] + + +def test_get_account(): + accounts = ["account1", "account2", "account3"] + pool = AccountPool(accounts) + + account = pool.get_account() + assert account == "account1" # PriorityQueue returns items in the order they were added + assert account in pool.used_accounts() + + +def test_release_account(): + accounts = ["account1", "account2", "account3"] + pool = AccountPool(accounts) + + account = pool.get_account() + assert account in pool.used_accounts() + + pool.release_account(account) + assert account not in pool.used_accounts() + + +def test_accounts_ordered_by_priority(): + accounts = ["account1", "account2", "account3"] + pool = AccountPool(accounts) + + account1 = pool.get_account() + assert account1 == "account1" + + account2 = pool.get_account() + assert account2 == "account2" + + pool.release_account(account1) + account3 = pool.get_account() + assert account3 == "account3" + + account4 = pool.get_account() + assert account4 == "account1" + + +def test_block_until_account_available(): + accounts = ["account1"] + pool = AccountPool(accounts, timeout=1) + + account = pool.get_account() + assert account == "account1" + assert account in pool.used_accounts() + + result = [] + thread = threading.Thread(target=lambda: result.append(pool.get_account()), daemon=True) + thread.start() + thread.join(timeout=0.01) + assert thread.is_alive() # Priority Queue should be blocking call + assert result == [] + + pool.release_account("account1") + thread.join(timeout=0.1) + assert not thread.is_alive() + assert result == ["account1"] + assert account in pool.used_accounts() + + +def test_timeout(): + accounts = ["account1"] + pool = AccountPool(accounts, timeout=0.01) + + account = pool.get_account() + assert account in accounts + + with pytest.raises(AccountPool.AccountPoolTimeoutError): + pool.get_account() + + +def test_size(): + pool = AccountPool([]) + assert pool.size() == 0 + + pool.add_account("account1") + assert pool.size() == 1 diff --git a/tests/strings/test_anagram.py b/tests/strings/test_anagram.py index 40324b7..d09e424 100644 --- a/tests/strings/test_anagram.py +++ b/tests/strings/test_anagram.py @@ -6,4 +6,3 @@ def test_valid_anagram(): assert not valid_anagram("test", "tests") assert not valid_anagram("test", "tezt") assert not valid_anagram("test", "tsst") -