Skip to content

Sourcery refactored main branch - #1

Open
sourcery-ai[bot] wants to merge 1 commit into
mainfrom
sourcery/main
Open

Sourcery refactored main branch#1
sourcery-ai[bot] wants to merge 1 commit into
mainfrom
sourcery/main

Conversation

@sourcery-ai

@sourcery-ai sourcery-ai Bot commented Dec 30, 2023

Copy link
Copy Markdown

Branch main refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch origin sourcery/main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai
sourcery-ai Bot requested a review from chandan0000 December 30, 2023 07:43

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

'--wsgi-file app.py --callable app')
else:
print('Unknown async_mode: ' + sio.async_mode)
print(f'Unknown async_mode: {sio.async_mode}')

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 128-128 refactored with the following changes:

'--wsgi-file latency.py --callable app')
else:
print('Unknown async_mode: ' + sio.async_mode)
print(f'Unknown async_mode: {sio.async_mode}')

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 57-57 refactored with the following changes:

'--wsgi-file latency.py --callable app')
else:
print('Unknown async_mode: ' + sio.async_mode)
print(f'Unknown async_mode: {sio.async_mode}')

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 51-51 refactored with the following changes:

Comment thread src/socketio/admin.py
def push(self, type, count=1):
timestamp = int(time.time()) * 1000
key = '{};{}'.format(timestamp, type)
key = f'{timestamp};{type}'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EventBuffer.push refactored with the following changes:

Comment thread src/socketio/admin.py
buffer = self.buffer
self.buffer = {}
return [value for value in buffer.values()]
return list(buffer.values())

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EventBuffer.get_and_clear refactored with the following changes:

Comment on lines -209 to +214
await self.sio.emit('socket_disconnected', (
namespace,
sid,
'N/A',
datetime.utcnow().isoformat() + 'Z',
), namespace=self.admin_namespace)
await self.sio.emit(
'socket_disconnected',
(namespace, sid, 'N/A', f'{datetime.utcnow().isoformat()}Z'),
namespace=self.admin_namespace,
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._disconnect refactored with the following changes:

Comment on lines -236 to +241
self.admin_queue.append(('room_joined', (
namespace,
room,
sid,
datetime.utcnow().isoformat() + 'Z',
)))
self.admin_queue.append(
(
'room_joined',
(namespace, room, sid, f'{datetime.utcnow().isoformat()}Z'),
)
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._basic_enter_room refactored with the following changes:

Comment on lines -246 to +251
self.admin_queue.append(('room_left', (
namespace,
room,
sid,
datetime.utcnow().isoformat() + 'Z',
)))
self.admin_queue.append(
(
'room_left',
(namespace, room, sid, f'{datetime.utcnow().isoformat()}Z'),
)
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._basic_leave_room refactored with the following changes:

Comment on lines -261 to +275
else [data]
else [data]
if not isinstance(skip_sid, list): # pragma: no branch
skip_sid = [skip_sid]
for sid, _ in self.sio.manager.get_participants(namespace, room):
if sid not in skip_sid:
await self.sio.emit('event_sent', (
namespace,
sid,
event_data,
datetime.utcnow().isoformat() + 'Z',
), namespace=self.admin_namespace)
await self.sio.emit(
'event_sent',
(
namespace,
sid,
event_data,
f'{datetime.utcnow().isoformat()}Z',
),
namespace=self.admin_namespace,
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._emit refactored with the following changes:

Comment on lines -278 to +286
await self.sio.emit('event_received', (
namespace,
sid,
data,
datetime.utcnow().isoformat() + 'Z',
), namespace=self.admin_namespace)
await self.sio.emit(
'event_received',
(namespace, sid, data, f'{datetime.utcnow().isoformat()}Z'),
namespace=self.admin_namespace,
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._handle_event_internal refactored with the following changes:

Comment on lines -335 to +348
sid = self.sio.manager.sid_from_eio_sid(eio_sid, namespace)
if sid:
if sid := self.sio.manager.sid_from_eio_sid(eio_sid, namespace):
serialized_socket = self.serialize_socket(sid, namespace,
eio_sid)
await self.sio.emit('socket_connected', (
serialized_socket,
datetime.utcfromtimestamp(t).isoformat() + 'Z',
), namespace=self.admin_namespace)
await self.sio.emit(
'socket_connected',
(
serialized_socket,
f'{datetime.utcfromtimestamp(t).isoformat()}Z',
),
namespace=self.admin_namespace,
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._eio_send_ping refactored with the following changes:

Comment on lines -347 to +353
namespaces = list(self.sio.handlers.keys())
namespaces.sort()
namespaces = sorted(self.sio.handlers.keys())

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer._emit_server_stats refactored with the following changes:

Comment on lines -378 to +383
self.sio.manager._timestamps else 0
self.sio.manager._timestamps else 0

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InstrumentedAsyncServer.serialize_socket refactored with the following changes:

Comment on lines -120 to +121
'Cannot receive from rabbitmq... '
'retrying in {} secs'.format(retry_sleep))
f'Cannot receive from rabbitmq... retrying in {retry_sleep} secs'
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncAioPikaManager._listen refactored with the following changes:

namespaces = list(set(self.handlers.keys()).union(
set(self.namespace_handlers.keys())))
if len(namespaces) == 0:
if not namespaces:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncClient.connect refactored with the following changes:

Comment on lines -98 to +100
else:
message = {'method': 'enter_room', 'sid': sid, 'room': room,
'namespace': namespace or '/', 'host_id': self.host_id}
await self._publish(message) # notify other hosts
message = {'method': 'enter_room', 'sid': sid, 'room': room,
'namespace': namespace or '/', 'host_id': self.host_id}
await self._publish(message) # notify other hosts

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncPubSubManager.enter_room refactored with the following changes:

Comment on lines -107 to +108
else:
message = {'method': 'leave_room', 'sid': sid, 'room': room,
'namespace': namespace or '/', 'host_id': self.host_id}
await self._publish(message) # notify other hosts
message = {'method': 'leave_room', 'sid': sid, 'room': room,
'namespace': namespace or '/', 'host_id': self.host_id}
await self._publish(message) # notify other hosts

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncPubSubManager.leave_room refactored with the following changes:

Comment on lines -215 to +213
self._get_logger().debug('pubsub message: {}'.format(
data['method']))
self._get_logger().debug(f"pubsub message: {data['method']}")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncPubSubManager._thread refactored with the following changes:

Comment on lines -91 to +97
self._get_logger().error('Cannot receive from redis... '
'retrying in '
'{} secs'.format(retry_sleep))
self._get_logger().error(
f'Cannot receive from redis... retrying in {retry_sleep} secs'
)
connect = True
await asyncio.sleep(retry_sleep)
retry_sleep *= 2
if retry_sleep > 60:
retry_sleep = 60
retry_sleep = min(retry_sleep, 60)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncRedisManager._redis_listen_with_retries refactored with the following changes:

sid = None
if namespace in self.handlers or namespace in self.namespace_handlers \
or self.namespaces == '*' or namespace in self.namespaces:
or self.namespaces == '*' or namespace in self.namespaces:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncServer._handle_connect refactored with the following changes:

Comment on lines -625 to +638
'*' in self.handlers[namespace]:
'*' in self.handlers[namespace]:
handler = self.handlers[namespace]['*']
args = (event, *args)
if handler:
if asyncio.iscoroutinefunction(handler):
try:
ret = await handler(*args)
except asyncio.CancelledError: # pragma: no cover
ret = None
else:
ret = handler(*args)
return ret
else:
if not handler:
return self.not_handled

# or else, forward the event to a namepsace handler if one exists
if asyncio.iscoroutinefunction(handler):
try:
ret = await handler(*args)
except asyncio.CancelledError: # pragma: no cover
ret = None
else:
ret = handler(*args)
return ret

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncServer._trigger_event refactored with the following changes:

This removes the following comments ( why? ):

# or else, forward the event to a namepsace handler if one exists

Comment on lines -676 to +674
elif pkt.packet_type == packet.BINARY_EVENT or \
pkt.packet_type == packet.BINARY_ACK:
elif pkt.packet_type in [packet.BINARY_EVENT, packet.BINARY_ACK]:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AsyncServer._handle_eio_message refactored with the following changes:

Comment on lines -173 to +181
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
if len(args) == 1 and not kwargs and callable(args[0]):
# the decorator was invoked without arguments
# args[0] is the decorated function
return self.on(args[0].__name__)(args[0])
else:
# the decorator was invoked with arguments
def set_handler(handler):
return self.on(handler.__name__, *args, **kwargs)(handler)
# the decorator was invoked with arguments
def set_handler(handler):
return self.on(handler.__name__, *args, **kwargs)(handler)

return set_handler
return set_handler

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseClient.event refactored with the following changes:

participants = ns[room]._fwdm.copy() if room in ns else {}
for sid, eio_sid in participants.items():
yield sid, eio_sid
yield from participants.items()

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseManager.get_participants refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)

Comment on lines -90 to +99
rooms = []
for room_name, room in self.rooms[namespace].copy().items():
if sid in room:
rooms.append(room_name)
rooms = [
room_name
for room_name, room in self.rooms[namespace].copy().items()
if sid in room
]
for room in rooms:
self.basic_leave_room(sid, namespace, room)
if sid in self.callbacks:
del self.callbacks[sid]
if namespace in self.pending_disconnect and \
sid in self.pending_disconnect[namespace]:
sid in self.pending_disconnect[namespace]:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseManager.basic_disconnect refactored with the following changes:

Comment on lines -17 to +25
if len(args) == 0:
if not args:
self.error_args = {'message': 'Connection rejected by server'}
elif len(args) == 1:
self.error_args = {'message': str(args[0])}
else:
self.error_args = {'message': str(args[0])}
if len(args) == 2:
self.error_args['data'] = args[1]
else:
self.error_args['data'] = args[1:]
self.error_args = {
'message': str(args[0]),
'data': args[1] if len(args) == 2 else args[1:],
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConnectionRefusedError.__init__ refactored with the following changes:

def _kafka_listen(self):
for message in self.consumer:
yield message
yield from self.consumer

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KafkaManager._kafka_listen refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)


def _queue(self):
queue_name = 'flask-socketio.' + str(uuid.uuid4())
queue_name = f'flask-socketio.{str(uuid.uuid4())}'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KombuManager._queue refactored with the following changes:

Comment on lines +124 to +132
retry_sleep = 1
while True:
message = queue.get(block=True)
message.ack()
yield message.payload
retry_sleep = 1
except (OSError, kombu.exceptions.KombuError):
self._get_logger().error(
'Cannot receive from rabbitmq... '
'retrying in {} secs'.format(retry_sleep))
f'Cannot receive from rabbitmq... retrying in {retry_sleep} secs'
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KombuManager._listen refactored with the following changes:

Comment thread src/socketio/namespace.py
having a single method that catches all events is desired.
"""
handler_name = 'on_' + event
handler_name = f'on_{event}'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Namespace.trigger_event refactored with the following changes:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants