Skip to content

Commit 9398c40

Browse files
committed
Apply ruff format . again.
1 parent d6e4c61 commit 9398c40

18 files changed

Lines changed: 1355 additions & 1355 deletions

example_config.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,70 +3,70 @@
33

44
# Host and port to bind WebSockets.
55

6-
WS_HOST = '127.0.0.1'
7-
WS_PORT = '9000'
6+
WS_HOST = "127.0.0.1"
7+
WS_PORT = "9000"
88

99
# Redis options
1010
REDIS = {
11-
'host': 'localhost',
12-
'port': 6379,
11+
"host": "localhost",
12+
"port": 6379,
1313
}
1414

1515
# Optional metrics reporting with Prometheus
1616
METRICS = {
17-
'prometheus': {
18-
'port': 9090,
17+
"prometheus": {
18+
"port": 9090,
1919
}
2020
}
2121

2222
# Authentication (currently only "ticket" authentication is supported)
2323
AUTHENTICATION = {
24-
'ticket': {
24+
"ticket": {
2525
# API endpoint to validate the ticket and exchange it for auth info.
26-
'validation_url': 'http://auth-service/auth/ticket/',
26+
"validation_url": "http://auth-service/auth/ticket/",
2727
# Fields that the validation endpoint returns.
28-
'auth_fields': ['session_id', 'user_id'],
28+
"auth_fields": ["session_id", "user_id"],
2929
}
3030
}
3131

3232
# List of services
3333
SERVICES = {
34-
'my_service': {
34+
"my_service": {
3535
# Whether to always require authentication. When False, anonymous
3636
# sessions are supported even if an authorizer is configured.
37-
'require_authentication': True,
37+
"require_authentication": True,
3838
# URL to the authorizer which receives auth information (from the
3939
# authentication endpoint), extra fields (configured below), and
4040
# subscription information.
41-
'authorizer': 'http://auth-service/auth/authorizer/',
41+
"authorizer": "http://auth-service/auth/authorizer/",
4242
# Fields returned by the authorizer callback that are passed to all
4343
# subsequent service callbacks.
44-
'authorizer_fields': ['capabilities'],
44+
"authorizer_fields": ["capabilities"],
4545
# Periodically reauthorize subscriptions and add some jitter to avoid
4646
# thundering herds.
47-
'authorization_renewal_period': 300,
48-
'authorization_renewal_jitter': 30,
47+
"authorization_renewal_period": 300,
48+
"authorization_renewal_jitter": 30,
4949
# If this service requires extra fields to fulfill a subscription,
5050
# you may provide them here. They are passed to all URL callbacks.
51-
'extra_fields': ['organization_id'],
51+
"extra_fields": ["organization_id"],
5252
# If filter fields are specified, messages can be published only to
5353
# sessions that match the given fields (either from extra_fields or
5454
# from authorizer_fields).
55-
'filter_fields': ['user_id'],
55+
"filter_fields": ["user_id"],
5656
# Optional URL which is called before subscribing to or unsubscribing
5757
# from this service. When an error is returned, the subscription or
5858
# unsubscription command fails.
59-
"before_subscribe": 'http://my-service/subscribe/',
60-
"before_unsubscribe": 'http://my-service/unsubscribe/',
59+
"before_subscribe": "http://my-service/subscribe/",
60+
"before_unsubscribe": "http://my-service/unsubscribe/",
6161
# Optional URL which is called after subscribing to or unsubscribing
6262
# from this service.
63-
"on_subscribe": 'http://my-service/on_subscribe/',
64-
"on_unsubscribe": 'http://my-service/on_unsubscribe/',
63+
"on_subscribe": "http://my-service/on_subscribe/",
64+
"on_unsubscribe": "http://my-service/on_unsubscribe/",
6565
# URL which is called when a message is passed to this service.
66-
"on_message": 'http://my-service/on_message/',
66+
"on_message": "http://my-service/on_message/",
6767
# If set, the service will send a heartbeat message to the URL defined
6868
# in 'on_heartbeat' every 'heartbeat_period' seconds.
6969
"heartbeat_period": 30,
70-
"on_heartbeat": 'http://my-service/on_heartbeat/',
70+
"on_heartbeat": "http://my-service/on_heartbeat/",
7171
},
7272
}

setup.py

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,58 @@
11
from setuptools import setup
22

3-
with open('README.rst', encoding='utf-8') as file:
3+
with open("README.rst", encoding="utf-8") as file:
44
long_description = file.read()
55

66

77
install_requires = [
8-
'aiohttp',
9-
'aioredis',
10-
'click',
11-
'structlog',
12-
'websockets',
8+
"aiohttp",
9+
"aioredis",
10+
"click",
11+
"structlog",
12+
"websockets",
1313
]
1414

1515
tests_require = install_requires + [
16-
'aioresponses',
17-
'pytest',
18-
'pytest-asyncio',
19-
'ruff',
16+
"aioresponses",
17+
"pytest",
18+
"pytest-asyncio",
19+
"ruff",
2020
]
2121

2222
setup(
23-
name='socketshark',
24-
version='0.5.0',
25-
url='http://github.com/closeio/socketshark',
26-
license='MIT',
27-
description='WebSocket message router',
23+
name="socketshark",
24+
version="0.5.0",
25+
url="http://github.com/closeio/socketshark",
26+
license="MIT",
27+
description="WebSocket message router",
2828
long_description=long_description,
29-
test_suite='tests',
29+
test_suite="tests",
3030
tests_require=tests_require,
31-
platforms='any',
31+
platforms="any",
3232
install_requires=install_requires,
3333
extras_require={
34-
'prometheus': 'prometheus-async',
34+
"prometheus": "prometheus-async",
3535
},
3636
classifiers=[
37-
'Intended Audience :: Developers',
38-
'License :: OSI Approved :: MIT License',
39-
'Operating System :: OS Independent',
40-
'Topic :: Software Development :: Libraries :: Python Modules',
41-
'Programming Language :: Python',
42-
'Programming Language :: Python :: 3',
43-
'Programming Language :: Python :: 3.9',
44-
'Programming Language :: Python :: 3.10',
45-
'Programming Language :: Python :: 3.11',
46-
'Programming Language :: Python :: 3.12',
37+
"Intended Audience :: Developers",
38+
"License :: OSI Approved :: MIT License",
39+
"Operating System :: OS Independent",
40+
"Topic :: Software Development :: Libraries :: Python Modules",
41+
"Programming Language :: Python",
42+
"Programming Language :: Python :: 3",
43+
"Programming Language :: Python :: 3.9",
44+
"Programming Language :: Python :: 3.10",
45+
"Programming Language :: Python :: 3.11",
46+
"Programming Language :: Python :: 3.12",
4747
],
4848
packages=[
49-
'socketshark',
50-
'socketshark.backend',
51-
'socketshark.metrics',
49+
"socketshark",
50+
"socketshark.backend",
51+
"socketshark.metrics",
5252
],
5353
entry_points={
54-
'console_scripts': [
55-
'socketshark = socketshark.__main__:run',
54+
"console_scripts": [
55+
"socketshark = socketshark.__main__:run",
5656
],
5757
},
5858
)

socketshark/__init__.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,21 @@
2121

2222
def setup_logging(log_config: LogConfig) -> None:
2323
# Configure root logger if logging level is specified in config
24-
if log_config['level']:
25-
level = getattr(logging, log_config['level'])
26-
formatter = logging.Formatter(log_config['format'])
24+
if log_config["level"]:
25+
level = getattr(logging, log_config["level"])
26+
formatter = logging.Formatter(log_config["format"])
2727
sh: logging.StreamHandler[Any] = logging.StreamHandler()
2828
sh.setFormatter(formatter)
2929

3030
logger = logging.getLogger()
3131
logger.setLevel(level)
3232
logger.addHandler(sh)
3333

34-
trace_level = getattr(logging, log_config['trace_level'])
35-
trace_logger = logging.getLogger(log_config['trace_logger_prefix'])
34+
trace_level = getattr(logging, log_config["trace_level"])
35+
trace_logger = logging.getLogger(log_config["trace_logger_prefix"])
3636
trace_logger.setLevel(trace_level)
3737

38-
if log_config['setup_structlog']:
38+
if log_config["setup_structlog"]:
3939
setup_structlog(sys.stdout.isatty())
4040

4141

@@ -44,7 +44,7 @@ def setup_structlog(tty: bool = False) -> None:
4444
structlog.stdlib.filter_by_level,
4545
structlog.stdlib.add_log_level,
4646
structlog.stdlib.add_logger_name,
47-
structlog.processors.TimeStamper(fmt='iso', utc=True),
47+
structlog.processors.TimeStamper(fmt="iso", utc=True),
4848
structlog.processors.StackInfoRenderer(),
4949
structlog.processors.format_exc_info,
5050
]
@@ -66,8 +66,8 @@ def load_backend(config: Config) -> Any:
6666
"""
6767
Return the backend module from the given SocketShark configuration.
6868
"""
69-
backend_name = config.get('BACKEND', 'websockets')
70-
backend_module = f'socketshark.backend.{backend_name}'
69+
backend_name = config.get("BACKEND", "websockets")
70+
backend_module = f"socketshark.backend.{backend_name}"
7171
return importlib.import_module(backend_module)
7272

7373

@@ -87,35 +87,35 @@ def __init__(self, config: Config) -> None:
8787
self.redis_connections: list[RedisConnection] = []
8888

8989
def _init_logging(self) -> None:
90-
logger_name = self.config['LOG']['logger_name']
91-
trace_logger_prefix = self.config['LOG']['trace_logger_prefix']
92-
trace_logger_name = f'{trace_logger_prefix}.{logger_name}'
90+
logger_name = self.config["LOG"]["logger_name"]
91+
trace_logger_prefix = self.config["LOG"]["trace_logger_prefix"]
92+
trace_logger_name = f"{trace_logger_prefix}.{logger_name}"
9393
pid = os.getpid()
9494
self.log: structlog.stdlib.BoundLogger = structlog.get_logger(
9595
logger_name
9696
).bind(pid=pid)
9797
self.trace_log: structlog.stdlib.BoundLogger = structlog.get_logger(
9898
trace_logger_name
9999
).bind(pid=pid)
100-
self.trace_log.debug('trace')
100+
self.trace_log.debug("trace")
101101

102102
def signal_ready(self) -> None:
103103
"""
104104
Notify that the backend is ready.
105105
"""
106106
self.log.info(
107-
'🦈 ready',
108-
host=self.config['WS_HOST'],
109-
port=self.config['WS_PORT'],
110-
secure=bool(self.config.get('WS_SSL')),
107+
"🦈 ready",
108+
host=self.config["WS_HOST"],
109+
port=self.config["WS_PORT"],
110+
secure=bool(self.config.get("WS_SSL")),
111111
)
112112
self.metrics.set_ready(True)
113113

114114
def signal_shutdown(self) -> None:
115115
"""
116116
Notify that the backend shut down.
117117
"""
118-
self.log.info('done')
118+
self.log.info("done")
119119
self.metrics.set_ready(False)
120120

121121
async def _redis_connection_handler(self) -> None:
@@ -132,7 +132,7 @@ async def _redis_connection_handler(self) -> None:
132132
]
133133
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
134134

135-
self.log.error('redis unexpectedly closed')
135+
self.log.error("redis unexpectedly closed")
136136
self.metrics.set_ready(False)
137137

138138
# Since we rely on PUBSUB channels, we disconnect all clients when
@@ -145,15 +145,15 @@ async def prepare(self) -> None:
145145
146146
Initialize Redis connection and the receiver class.
147147
"""
148-
redis_settings = [self.config['REDIS']]
149-
if self.config.get('REDIS_ALT'):
150-
redis_settings.append(self.config['REDIS_ALT'])
148+
redis_settings = [self.config["REDIS"]]
149+
if self.config.get("REDIS_ALT"):
150+
redis_settings.append(self.config["REDIS_ALT"])
151151
try:
152152
self.redis_connections = await asyncio.gather(
153153
*[RedisConnection.create(s) for s in redis_settings]
154154
)
155155
except (OSError, aioredis.RedisError):
156-
self.log.exception('could not connect to redis')
156+
self.log.exception("could not connect to redis")
157157
raise
158158

159159
self._redis_connection_handler_task = asyncio.ensure_future(
@@ -174,7 +174,7 @@ async def shutdown(self) -> None:
174174
if self._shutdown:
175175
return
176176

177-
self.log.info('shutting down')
177+
self.log.info("shutting down")
178178

179179
self._shutdown = True
180180

@@ -192,7 +192,7 @@ async def shutdown(self) -> None:
192192
# Wait for all sessions to close
193193
while self.sessions:
194194
self.log.info(
195-
'waiting for sessions to close', n_sessions=len(self.sessions)
195+
"waiting for sessions to close", n_sessions=len(self.sessions)
196196
)
197197
await asyncio.sleep(1)
198198

@@ -238,7 +238,7 @@ def _install_signal_handlers(self) -> None:
238238
"""
239239

240240
def request_stop() -> None:
241-
self.log.info('stop requested')
241+
self.log.info("stop requested")
242242
asyncio.ensure_future(self.shutdown())
243243

244244
loop = asyncio.get_event_loop()
@@ -254,11 +254,11 @@ def _uninstall_signal_handlers(self) -> None:
254254
loop.remove_signal_handler(signal.SIGTERM)
255255

256256
def get_ssl_context(self) -> ssl.SSLContext | None:
257-
ssl_settings = self.config.get('WS_SSL')
257+
ssl_settings = self.config.get("WS_SSL")
258258
if ssl_settings:
259259
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
260260
ssl_context.load_cert_chain(
261-
certfile=ssl_settings['cert'], keyfile=ssl_settings['key']
261+
certfile=ssl_settings["cert"], keyfile=ssl_settings["key"]
262262
)
263263
return ssl_context
264264
return None
@@ -286,16 +286,16 @@ def load_config(config_name: str) -> Config:
286286

287287

288288
@click.command()
289-
@click.option('-c', '--config', required=True, help='dotted path to config')
289+
@click.option("-c", "--config", required=True, help="dotted path to config")
290290
@click.pass_context
291291
def run(context: click.Context, config: str) -> None:
292292
config_obj = load_config(config)
293293

294-
setup_logging(config_obj['LOG'])
294+
setup_logging(config_obj["LOG"])
295295

296296
shark = SocketShark(config_obj)
297297
try:
298298
shark.start()
299299
except Exception:
300-
shark.log.exception('unhandled exception')
300+
shark.log.exception("unhandled exception")
301301
raise

0 commit comments

Comments
 (0)