Skip to content

Commit 49bf412

Browse files
committed
fix: add stricter lint checks and fix the defects they found
Checks added: - mypy: strict_equality, warn_unused_ignores, ignore-without-code and unused-awaitable. - ruff, run alongside flake8: B, ASYNC, RUF006, and TID251 to ban psycopg, mysql and aiomysql imports outside the driver dialects. - import-linter: only the aio tree and the async SQLAlchemy dialects import aio, and the plugin service and wrapper modules do not import the Django or SQLAlchemy integrations. CI runs ruff check . and lint-imports after isort. ruff and import-linter are new dev dependencies; import-linter is pinned to 2.15, the last release that supports Python 3.10. Fixes: - The sync is_static_host_list_provider() compared the provider instance with a class, so it always returned False and the two branches that called it never ran. The method and both branches are removed, so stale DNS and read/write splitting behave as they do on main. - The blue/green status provider bound green_host late in a loop, so every IAM success handler registered the last green host. - The aio topology monitor dropped the tasks it scheduled, so they could be garbage-collected before they finished. - HostResponseTimeMonitor kept its closed connection after stopping, and its tests compared values without asserting them. Also removes 79 type: ignore comments that no longer hid anything, and fixes smaller issues the checks flagged, mostly in tests.
1 parent f4cb4cf commit 49bf412

58 files changed

Lines changed: 674 additions & 162 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/main.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,9 @@ jobs:
6666
run: poetry run flake8 .
6767
- name: Run isort - dependency import sorting check
6868
run: poetry run isort --check-only .
69+
- name: Run ruff - bug patterns
70+
run: poetry run ruff check .
71+
- name: Run import-linter - layer contracts
72+
run: poetry run lint-imports
6973
- name: Run unit tests
7074
run: poetry run pytest ./tests/unit -Werror

‎.importlinter‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
[importlinter]
2+
root_package = aws_advanced_python_wrapper
3+
4+
[importlinter:contract:aio-is-protected]
5+
name = Only the aio tree and the async SQLAlchemy dialects import aio
6+
type = protected
7+
protected_modules =
8+
aws_advanced_python_wrapper.aio
9+
allowed_importers =
10+
aws_advanced_python_wrapper.aio
11+
aws_advanced_python_wrapper.sqlalchemy_dialects
12+
ignore_imports =
13+
aws_advanced_python_wrapper.database_dialect -> aws_advanced_python_wrapper.aio.host_list_provider
14+
aws_advanced_python_wrapper.dialect_verifier -> aws_advanced_python_wrapper.aio.dialect_utils
15+
16+
[importlinter:contract:core-not-integrations]
17+
name = Core does not import the Django or SQLAlchemy integrations
18+
type = forbidden
19+
source_modules =
20+
aws_advanced_python_wrapper.plugin_service
21+
aws_advanced_python_wrapper.wrapper
22+
aws_advanced_python_wrapper.aio.plugin_service
23+
aws_advanced_python_wrapper.aio.wrapper
24+
forbidden_modules =
25+
aws_advanced_python_wrapper.django
26+
aws_advanced_python_wrapper.sqlalchemy_dialects
27+
aws_advanced_python_wrapper.sqlalchemy

‎aws_advanced_python_wrapper/aio/cluster_topology_monitor.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,16 @@
4848
import weakref
4949
from time import perf_counter_ns
5050
from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional,
51-
Set, Tuple)
51+
Set, Tuple, Union)
5252

5353
from aws_advanced_python_wrapper.aio import topology_store
5454
from aws_advanced_python_wrapper.hostinfo import HostRole
5555
from aws_advanced_python_wrapper.utils.log import Logger
5656
from aws_advanced_python_wrapper.utils.messages import Messages
5757

5858
if TYPE_CHECKING:
59+
from concurrent.futures import Future
60+
5961
from aws_advanced_python_wrapper.aio.plugin_service import \
6062
AsyncPluginService
6163
from aws_advanced_python_wrapper.aio.topology_store import TopologyKey
@@ -127,6 +129,7 @@ def __init__(
127129
self._probe_host = probe_host
128130

129131
self._task: Optional[asyncio.Task[None]] = None
132+
self._scheduled: Set[Union[asyncio.Task[None], Future[None]]] = set()
130133
self._stop_event = asyncio.Event()
131134
self._last_known_writer: Optional[str] = None
132135
self._high_refresh_until_ns: int = 0
@@ -809,17 +812,21 @@ def _schedule(self, coro: Awaitable[None]) -> bool:
809812
return False
810813
try:
811814
if loop is asyncio.get_running_loop():
812-
loop.create_task(coro) # type: ignore[arg-type]
815+
self._keep_until_done(loop.create_task(coro)) # type: ignore[arg-type]
813816
return True
814817
except RuntimeError:
815818
pass
816819
try:
817-
asyncio.run_coroutine_threadsafe(coro, loop) # type: ignore[arg-type]
820+
self._keep_until_done(asyncio.run_coroutine_threadsafe(coro, loop)) # type: ignore[arg-type]
818821
return True
819822
except RuntimeError:
820823
coro.close() # type: ignore[attr-defined]
821824
return False
822825

826+
def _keep_until_done(self, work: Union[asyncio.Task[None], Future[None]]) -> None:
827+
self._scheduled.add(work)
828+
work.add_done_callback(self._scheduled.discard)
829+
823830
async def _reset(self) -> None:
824831
"""Drop everything tied to the pre-switchover cluster.
825832

‎aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ async def set_read_only(self, conn: Any, read_only: bool) -> None:
259259
"SET SESSION TRANSACTION READ WRITE"
260260
)
261261
# Stash intent on the conn so is_read_only can read it back.
262-
conn._aws_read_only = bool(read_only) # type: ignore[attr-defined]
262+
conn._aws_read_only = bool(read_only)
263263

264264
async def can_execute_query(self, conn: Any) -> bool:
265265
# aiomysql exposes ``closed`` (no ``open`` -- see is_closed).

‎aws_advanced_python_wrapper/aio/failover_plugin.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,7 @@ async def _open_connection(
805805
target, self._plugin_service.props, self)
806806

807807
def _build_target_props(self, target: HostInfo) -> Properties:
808-
props_copy = self._plugin_service.props.copy() # type: ignore[attr-defined]
808+
props_copy = self._plugin_service.props.copy()
809809
props_copy["host"] = target.host
810810
if target.is_port_specified():
811811
props_copy["port"] = str(target.port)

‎aws_advanced_python_wrapper/aio/fastest_response_strategy_plugin.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ async def measure_and_cache(
576576

577577
best: Optional[HostInfo] = None
578578
best_ns: int = _MAX_RESPONSE_NS
579-
for host, r in zip(candidates, results):
579+
for host, r in zip(candidates, results, strict=False):
580580
if isinstance(r, BaseException):
581581
continue
582582
if not isinstance(r, int) or r >= _MAX_RESPONSE_NS:

‎aws_advanced_python_wrapper/aio/plugin_factory.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,7 @@ def sort_factories_by_weight(
381381
last_weight = w
382382

383383
return [f for _, f in sorted(
384-
zip(effective, factories), key=lambda pair: pair[0])]
384+
zip(effective, factories, strict=False), key=lambda pair: pair[0])]
385385

386386

387387
def build_async_plugins(

‎aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ async def _open(
570570
"reader/writer connection.")
571571

572572
from aws_advanced_python_wrapper.utils.properties import Properties
573-
props_copy: Properties = Properties(self._plugin_service.props.copy()) # type: ignore[attr-defined]
573+
props_copy: Properties = Properties(self._plugin_service.props.copy())
574574
props_copy["host"] = target.host
575575
if target.is_port_specified():
576576
props_copy["port"] = str(target.port)

‎aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def _task(connections_list: list):
224224

225225
def _invalidate_connections(self, connections_list: list):
226226
invalidate_connection_thread: Thread = Thread(daemon=True, target=self._task,
227-
args=[connections_list]) # type: ignore[arg-type]
227+
args=[connections_list])
228228
invalidate_connection_thread.start()
229229

230230
def log_opened_connections(self):

‎aws_advanced_python_wrapper/blue_green_plugin.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1759,7 +1759,7 @@ def _get_post_status_connect_routings(self) -> List[ConnectRouting]:
17591759
iam_hosts = (green_host_info,) if blue_host_info is None else (green_host_info, blue_host_info)
17601760

17611761
iam_auth_success_handler = None if is_blue_host_instance \
1762-
else lambda iam_host: self._register_iam_host(green_host, iam_host)
1762+
else self._make_iam_success_handler(green_host)
17631763
host_substitute_routing = SubstituteConnectRouting(
17641764
green_ip_host_info, blue_host, role, iam_hosts, iam_auth_success_handler)
17651765
interim_status = self._interim_statuses[role.value]
@@ -1776,6 +1776,9 @@ def _get_post_status_connect_routings(self) -> List[ConnectRouting]:
17761776

17771777
return routings
17781778

1779+
def _make_iam_success_handler(self, green_host: str) -> Callable[[str], None]:
1780+
return lambda iam_host: self._register_iam_host(green_host, iam_host)
1781+
17791782
def _is_already_successfully_connected(self, connect_host: str, iam_host: str):
17801783
success_hosts = self._iam_auth_success_hosts.compute_if_absent(connect_host, lambda _: ConcurrentSet())
17811784
return success_hosts is not None and iam_host in success_hosts

0 commit comments

Comments
 (0)