Skip to content

Commit 6030e4c

Browse files
authored
Practical account queue (#194)
* Fix typing error * Add basic account queue
1 parent 451aa8d commit 6030e4c

4 files changed

Lines changed: 151 additions & 3 deletions

File tree

‎src/practical/account_pool.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import queue
2+
import time
3+
4+
5+
class AccountPool:
6+
"""Thread-safe pool of account identifiers, handed out oldest-idle-first.
7+
8+
Callers check an account out with `get_account()` and must return it with `release_account()`
9+
when done. If none are available, `get_account()` blocks (up to `timeout` seconds) until one is
10+
released, so this is safe to share across threads that each need exclusive use of an account.
11+
"""
12+
13+
class AccountPoolTimeoutError(Exception):
14+
"""Raised when no account becomes available within the pool's timeout."""
15+
16+
def __init__(self, timeout: float):
17+
super().__init__(f"No accounts available after {timeout} seconds")
18+
19+
def __init__(self, accounts, timeout: float = 30):
20+
self.timeout = timeout
21+
self.account_queue = queue.PriorityQueue[tuple[int, str]]()
22+
self.accounts = accounts
23+
self.outstanding_accounts: set[str] = set()
24+
25+
for account in accounts:
26+
self.account_queue.put((time.monotonic_ns(), account))
27+
28+
def add_account(self, account: str):
29+
"""Add a new account to the pool, immediately available for checkout."""
30+
self.accounts.append(account)
31+
self.account_queue.put((time.monotonic_ns(), account))
32+
33+
def get_account(self) -> str:
34+
"""Check out and return the account that's been idle longest, blocking until one is free.
35+
36+
Raises `AccountPoolTimeoutError` if none becomes available within `self.timeout` seconds.
37+
"""
38+
try:
39+
_, account = self.account_queue.get(block=True, timeout=self.timeout)
40+
except queue.Empty:
41+
raise self.AccountPoolTimeoutError(timeout=self.timeout)
42+
43+
self.outstanding_accounts.add(account)
44+
return account
45+
46+
def release_account(self, account):
47+
"""Return a checked-out account to the pool."""
48+
self.outstanding_accounts.remove(account)
49+
self.account_queue.put((time.monotonic_ns(), account))
50+
51+
def size(self):
52+
"""Return the total number of accounts in the pool, checked out or not."""
53+
return len(self.accounts)
54+
55+
def used_accounts(self):
56+
"""Return the accounts currently checked out."""
57+
return list(self.outstanding_accounts)

‎src/singly_linked_lists/intersection_two_linked_lists.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ def get_intersection_node(
1515
cover equal total distance and meet at the intersection (or both reach None if there is none). Time: O(N),
1616
Space: O(1).
1717
"""
18-
node_a: SinglyLinkedListNode = head_a
19-
node_b: SinglyLinkedListNode = head_b
18+
node_a = head_a
19+
node_b = head_b
2020

2121
while node_a != node_b:
2222
node_a = node_a.next
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import threading
2+
3+
import pytest
4+
5+
from src.practical.account_pool import AccountPool
6+
7+
8+
def test_account_pool_init():
9+
accounts = ["account1", "account2", "account3"]
10+
pool = AccountPool(accounts)
11+
12+
assert pool.size() == 3
13+
assert pool.used_accounts() == []
14+
15+
16+
def test_get_account():
17+
accounts = ["account1", "account2", "account3"]
18+
pool = AccountPool(accounts)
19+
20+
account = pool.get_account()
21+
assert account == "account1" # PriorityQueue returns items in the order they were added
22+
assert account in pool.used_accounts()
23+
24+
25+
def test_release_account():
26+
accounts = ["account1", "account2", "account3"]
27+
pool = AccountPool(accounts)
28+
29+
account = pool.get_account()
30+
assert account in pool.used_accounts()
31+
32+
pool.release_account(account)
33+
assert account not in pool.used_accounts()
34+
35+
36+
def test_accounts_ordered_by_priority():
37+
accounts = ["account1", "account2", "account3"]
38+
pool = AccountPool(accounts)
39+
40+
account1 = pool.get_account()
41+
assert account1 == "account1"
42+
43+
account2 = pool.get_account()
44+
assert account2 == "account2"
45+
46+
pool.release_account(account1)
47+
account3 = pool.get_account()
48+
assert account3 == "account3"
49+
50+
account4 = pool.get_account()
51+
assert account4 == "account1"
52+
53+
54+
def test_block_until_account_available():
55+
accounts = ["account1"]
56+
pool = AccountPool(accounts, timeout=1)
57+
58+
account = pool.get_account()
59+
assert account == "account1"
60+
assert account in pool.used_accounts()
61+
62+
result = []
63+
thread = threading.Thread(target=lambda: result.append(pool.get_account()), daemon=True)
64+
thread.start()
65+
thread.join(timeout=0.01)
66+
assert thread.is_alive() # Priority Queue should be blocking call
67+
assert result == []
68+
69+
pool.release_account("account1")
70+
thread.join(timeout=0.1)
71+
assert not thread.is_alive()
72+
assert result == ["account1"]
73+
assert account in pool.used_accounts()
74+
75+
76+
def test_timeout():
77+
accounts = ["account1"]
78+
pool = AccountPool(accounts, timeout=0.01)
79+
80+
account = pool.get_account()
81+
assert account in accounts
82+
83+
with pytest.raises(AccountPool.AccountPoolTimeoutError):
84+
pool.get_account()
85+
86+
87+
def test_size():
88+
pool = AccountPool([])
89+
assert pool.size() == 0
90+
91+
pool.add_account("account1")
92+
assert pool.size() == 1

‎tests/strings/test_anagram.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,3 @@ def test_valid_anagram():
66
assert not valid_anagram("test", "tests")
77
assert not valid_anagram("test", "tezt")
88
assert not valid_anagram("test", "tsst")
9-

0 commit comments

Comments
 (0)