Skip to content

Commit 6f3c031

Browse files
committed
refactor: resolve a potential infinite loop with a custom Exception
1 parent 09b2e8d commit 6f3c031

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

postgresql_watcher/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from .watcher import PostgresqlWatcher
1+
from .watcher import PostgresqlWatcher, PostgresqlWatcherChannelSubscriptionTimeoutError

postgresql_watcher/watcher.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,11 +111,15 @@ def start(self):
111111
self.subscription_proces.start()
112112
# And wait for the Process to be ready to listen for updates
113113
# from PostgreSQL
114+
timeout = 20 # seconds
115+
timeout_time = time() + timeout
114116
while True:
115117
if self.parent_conn.poll():
116118
message = int(self.parent_conn.recv())
117119
if message == _ChannelSubscriptionMessage.IS_READY:
118120
break
121+
if time() > timeout_time:
122+
raise PostgresqlWatcherChannelSubscriptionTimeoutError(timeout)
119123
sleep(1 / 1000) # wait for 1 ms
120124

121125
def _cleanup_connections_and_processes(self) -> None:
@@ -175,3 +179,13 @@ def should_reload(self) -> bool:
175179
self._create_subscription_process(delay=10)
176180

177181
return False
182+
183+
184+
class PostgresqlWatcherChannelSubscriptionTimeoutError(RuntimeError):
185+
"""
186+
Raised if the channel subscription could not be established within a given timeout.
187+
"""
188+
189+
def __init__(self, timeout_in_seconds: float) -> None:
190+
msg = f"The channel subscription could not be established within {timeout_in_seconds:.0f} seconds."
191+
super().__init__(msg)

0 commit comments

Comments
 (0)