Skip to content

Commit

Permalink
Add heartbeat jitter (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
nsaje authored Jul 16, 2024
1 parent d77aa39 commit a9efbfe
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
6 changes: 5 additions & 1 deletion socketshark/subscription.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import random
import time
from typing import Any, Dict, Optional

Expand Down Expand Up @@ -184,8 +185,10 @@ async def periodic_heartbeat(self):
subscription=self.name,
period=period,
)
# Add some randomness to the first heartbeat period to avoid all
# subscriptions sending heartbeats at the same time upon redeploy.
await asyncio.sleep(period * random.random())
while True:
await asyncio.sleep(period)
try:
self.session.log.debug(
'sending heartbeat', subscription=self.name
Expand All @@ -202,6 +205,7 @@ async def periodic_heartbeat(self):
subscription=self.name,
error=e.error,
)
await asyncio.sleep(period)

async def before_subscribe(self):
return await self.perform_service_request('before_subscribe')
Expand Down
8 changes: 5 additions & 3 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import os
import random
import time
from unittest.mock import patch

Expand Down Expand Up @@ -1097,6 +1098,7 @@ async def test_subscription_periodic_heartbeat(self):
},
)

random.seed(1) # due to a random sleep at the beginning
await session.on_client_event(
{
'event': 'subscribe',
Expand All @@ -1105,10 +1107,10 @@ async def test_subscription_periodic_heartbeat(self):
)

mock.assert_not_called()

await asyncio.sleep(0.4)

await asyncio.sleep(0.2)
mock.assert_called_once()
await asyncio.sleep(0.2)
assert len(list(mock.requests.values())[0]) == 2

await shark.shutdown()

Expand Down

0 comments on commit a9efbfe

Please sign in to comment.