-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolling_utils.py
More file actions
60 lines (48 loc) · 1.86 KB
/
polling_utils.py
File metadata and controls
60 lines (48 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import time
from typing import Callable, TypeVar
from core.global_settings import global_settings
from gql.types import MemberAddress
T = TypeVar("T")
AddressesResult = tuple[int, list[MemberAddress]]
def poll_until(
fetch: Callable[[], T | None],
predicate: Callable[[T], bool],
attempts: int,
interval: int,
) -> T | None:
"""Poll *fetch* up to *attempts* times, sleeping *interval* seconds between tries.
Returns the first result for which *predicate* is ``True``,
or ``None`` if all attempts are exhausted or *fetch* keeps returning ``None``.
"""
for _ in range(attempts):
result = fetch()
if result is not None and predicate(result):
return result
time.sleep(interval)
return None
def wait_addresses_visible(
fetch: Callable[[], AddressesResult],
seeded_descriptions: set[str],
) -> AddressesResult:
"""Poll *fetch* until every description in *seeded_descriptions* is present.
The xAPI ``currentCustomerAddresses`` / ``currentOrganizationAddresses``
queries are backed by an index that updates asynchronously after
``updateMemberAddresses``; without polling, freshly seeded addresses may
not be visible yet. Mirrors the pattern documented in
``project_personalization_search_async.md``.
If the polling budget is exhausted, returns the last fetched result so
the caller's assertions surface a meaningful diff rather than ``None``.
"""
def has_all(result: AddressesResult) -> bool:
_, items = result
present = {a.description for a in items if a.description}
return seeded_descriptions.issubset(present)
result = poll_until(
fetch=fetch,
predicate=has_all,
attempts=global_settings.poll_attempts,
interval=global_settings.poll_interval,
)
if result is None:
return fetch()
return result