Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,9 @@ jobs:
run: poetry run flake8 .
- name: Run isort - dependency import sorting check
run: poetry run isort --check-only .
- name: Run ruff - bug patterns
run: poetry run ruff check .
- name: Run import-linter - layer contracts
run: poetry run lint-imports
- name: Run unit tests
run: poetry run pytest ./tests/unit -Werror
27 changes: 27 additions & 0 deletions .importlinter
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[importlinter]
root_package = aws_advanced_python_wrapper

[importlinter:contract:aio-is-protected]
name = Only the aio tree and the async SQLAlchemy dialects import aio
type = protected
protected_modules =
aws_advanced_python_wrapper.aio
allowed_importers =
aws_advanced_python_wrapper.aio
aws_advanced_python_wrapper.sqlalchemy_dialects
ignore_imports =
aws_advanced_python_wrapper.database_dialect -> aws_advanced_python_wrapper.aio.host_list_provider
aws_advanced_python_wrapper.dialect_verifier -> aws_advanced_python_wrapper.aio.dialect_utils

[importlinter:contract:core-not-integrations]
name = Core does not import the Django or SQLAlchemy integrations
type = forbidden
source_modules =
aws_advanced_python_wrapper.plugin_service
aws_advanced_python_wrapper.wrapper
aws_advanced_python_wrapper.aio.plugin_service
aws_advanced_python_wrapper.aio.wrapper
forbidden_modules =
aws_advanced_python_wrapper.django
aws_advanced_python_wrapper.sqlalchemy_dialects
aws_advanced_python_wrapper.sqlalchemy
13 changes: 10 additions & 3 deletions aws_advanced_python_wrapper/aio/cluster_topology_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,16 @@
import weakref
from time import perf_counter_ns
from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional,
Set, Tuple)
Set, Tuple, Union)

from aws_advanced_python_wrapper.aio import topology_store
from aws_advanced_python_wrapper.hostinfo import HostRole
from aws_advanced_python_wrapper.utils.log import Logger
from aws_advanced_python_wrapper.utils.messages import Messages

if TYPE_CHECKING:
from concurrent.futures import Future

from aws_advanced_python_wrapper.aio.plugin_service import \
AsyncPluginService
from aws_advanced_python_wrapper.aio.topology_store import TopologyKey
Expand Down Expand Up @@ -127,6 +129,7 @@ def __init__(
self._probe_host = probe_host

self._task: Optional[asyncio.Task[None]] = None
self._scheduled: Set[Union[asyncio.Task[None], Future[None]]] = set()
self._stop_event = asyncio.Event()
self._last_known_writer: Optional[str] = None
self._high_refresh_until_ns: int = 0
Expand Down Expand Up @@ -809,17 +812,21 @@ def _schedule(self, coro: Awaitable[None]) -> bool:
return False
try:
if loop is asyncio.get_running_loop():
loop.create_task(coro) # type: ignore[arg-type]
self._keep_until_done(loop.create_task(coro)) # type: ignore[arg-type]
return True
except RuntimeError:
pass
try:
asyncio.run_coroutine_threadsafe(coro, loop) # type: ignore[arg-type]
self._keep_until_done(asyncio.run_coroutine_threadsafe(coro, loop)) # type: ignore[arg-type]
return True
except RuntimeError:
coro.close() # type: ignore[attr-defined]
return False

def _keep_until_done(self, work: Union[asyncio.Task[None], Future[None]]) -> None:
self._scheduled.add(work)
work.add_done_callback(self._scheduled.discard)

async def _reset(self) -> None:
"""Drop everything tied to the pre-switchover cluster.

Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ async def set_read_only(self, conn: Any, read_only: bool) -> None:
"SET SESSION TRANSACTION READ WRITE"
)
# Stash intent on the conn so is_read_only can read it back.
conn._aws_read_only = bool(read_only) # type: ignore[attr-defined]
conn._aws_read_only = bool(read_only)

async def can_execute_query(self, conn: Any) -> bool:
# aiomysql exposes ``closed`` (no ``open`` -- see is_closed).
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/aio/failover_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ async def _open_connection(
target, self._plugin_service.props, self)

def _build_target_props(self, target: HostInfo) -> Properties:
props_copy = self._plugin_service.props.copy() # type: ignore[attr-defined]
props_copy = self._plugin_service.props.copy()
props_copy["host"] = target.host
if target.is_port_specified():
props_copy["port"] = str(target.port)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ async def measure_and_cache(

best: Optional[HostInfo] = None
best_ns: int = _MAX_RESPONSE_NS
for host, r in zip(candidates, results):
for host, r in zip(candidates, results, strict=False):
if isinstance(r, BaseException):
continue
if not isinstance(r, int) or r >= _MAX_RESPONSE_NS:
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/aio/plugin_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ def sort_factories_by_weight(
last_weight = w

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


def build_async_plugins(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ async def _open(
"reader/writer connection.")

from aws_advanced_python_wrapper.utils.properties import Properties
props_copy: Properties = Properties(self._plugin_service.props.copy()) # type: ignore[attr-defined]
props_copy: Properties = Properties(self._plugin_service.props.copy())
props_copy["host"] = target.host
if target.is_port_specified():
props_copy["port"] = str(target.port)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def _task(connections_list: list):

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

def log_opened_connections(self):
Expand Down
5 changes: 4 additions & 1 deletion aws_advanced_python_wrapper/blue_green_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1759,7 +1759,7 @@ def _get_post_status_connect_routings(self) -> List[ConnectRouting]:
iam_hosts = (green_host_info,) if blue_host_info is None else (green_host_info, blue_host_info)

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

return routings

def _make_iam_success_handler(self, green_host: str) -> Callable[[str], None]:
return lambda iam_host: self._register_iam_host(green_host, iam_host)

def _is_already_successfully_connected(self, connect_host: str, iam_host: str):
success_hosts = self._iam_auth_success_hosts.compute_if_absent(connect_host, lambda _: ConcurrentSet())
return success_hosts is not None and iam_host in success_hosts
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/custom_endpoint_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def from_db_cluster_endpoint(cls, endpoint_response_info: Dict[str, Union[str, L
)

def __eq__(self, other: object):
if self is object:
if self is other:
return True
if not isinstance(other, CustomEndpointInfo):
return False
Expand Down
4 changes: 2 additions & 2 deletions aws_advanced_python_wrapper/failover_v2_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def _get_reader_failover_connection(self) -> ReaderFailoverResult:

remaining_readers.remove(reader_candidate)
self._plugin_service.driver_dialect.execute(
DbApiMethod.CONNECTION_CLOSE.method_name, lambda: candidate_conn.close(), conn=candidate_conn)
DbApiMethod.CONNECTION_CLOSE.method_name, candidate_conn.close, conn=candidate_conn)

if role == HostRole.WRITER:
reader_candidates.remove(reader_candidate)
Expand All @@ -308,7 +308,7 @@ def _get_reader_failover_connection(self) -> ReaderFailoverResult:
return ReaderFailoverResult(candidate_conn, updated_host_info)

self._plugin_service.driver_dialect.execute(
DbApiMethod.CONNECTION_CLOSE.method_name, lambda: candidate_conn.close(), conn=candidate_conn)
DbApiMethod.CONNECTION_CLOSE.method_name, candidate_conn.close, conn=candidate_conn)
if role == HostRole.WRITER:
is_original_writer_still_writer = True
except Exception:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ def run(self):
except Exception:
# Do nothing
pass
self._monitoring_conn = None

if context is not None:
context.close_context()
Expand Down
3 changes: 0 additions & 3 deletions aws_advanced_python_wrapper/host_list_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,6 @@ def initial_connection_host_info(self) -> Optional[HostInfo]:
def initial_connection_host_info(self, value: HostInfo):
...

def is_static_host_list_provider(self) -> bool:
...


class RdsHostListProvider(DynamicHostListProvider, HostListProvider):
_MONITOR_CLEANUP_NANO: ClassVar[int] = 15 * 60 * 1_000_000_000 # 15 minutes
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/hostinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(
self.last_update_time = last_update_time

def __eq__(self, other: object):
if self is object:
if self is other:
return True
if not isinstance(other, HostInfo):
return False
Expand Down
5 changes: 1 addition & 4 deletions aws_advanced_python_wrapper/plugin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
from aws_advanced_python_wrapper.host_availability import HostAvailability
from aws_advanced_python_wrapper.host_list_provider import (
ConnectionStringHostListProvider, HostListProvider,
HostListProviderService, StaticHostListProvider)
HostListProviderService)
from aws_advanced_python_wrapper.host_monitoring_plugin import \
HostMonitoringPluginFactory
from aws_advanced_python_wrapper.host_monitoring_v2_plugin import \
Expand Down Expand Up @@ -750,9 +750,6 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option
except Exception as e:
raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) from e

def is_static_host_list_provider(self) -> bool:
return self._host_list_provider is StaticHostListProvider

def is_network_exception(self, error: Optional[Exception] = None, sql_state: Optional[str] = None) -> bool:
return self._exception_manager.is_network_exception(
dialect=self.database_dialect, error=error, sql_state=sql_state)
Expand Down
5 changes: 1 addition & 4 deletions aws_advanced_python_wrapper/read_write_splitting_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,10 +458,7 @@ def connect(

current_conn = connect_func()

if not is_initial_connection or (
self._host_list_provider_service is not None
and self._host_list_provider_service.is_static_host_list_provider()
):
if not is_initial_connection:
return current_conn

current_role = self._plugin_service.get_host_role(current_conn)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,21 +133,21 @@ def _driver_error_module(self):
"""
return None

def do_execute( # type: ignore[no-untyped-def]
def do_execute(
self, cursor, statement, parameters, context=None):
try:
super().do_execute( # type: ignore[misc]
super().do_execute(
cursor, statement, parameters, context)
except Exception as e:
normalized = _normalize_driver_error(e, self._driver_error_module())
if normalized is not None:
raise normalized from e
raise

def do_executemany( # type: ignore[no-untyped-def]
def do_executemany(
self, cursor, statement, parameters, context=None):
try:
super().do_executemany( # type: ignore[misc]
super().do_executemany(
cursor, statement, parameters, context)
except Exception as e:
normalized = _normalize_driver_error(e, self._driver_error_module())
Expand Down Expand Up @@ -177,21 +177,21 @@ def _driver_error_module(self):
"""See :meth:`_DriverErrorNormalizeMixin._driver_error_module`."""
return None

def do_execute( # type: ignore[no-untyped-def]
def do_execute(
self, cursor, statement, parameters, context=None):
try:
super().do_execute( # type: ignore[misc]
super().do_execute(
cursor, statement, parameters, context)
except Exception as e:
normalized = _normalize_driver_error(e, self._driver_error_module())
if normalized is not None:
raise normalized from e
raise

def do_executemany( # type: ignore[no-untyped-def]
def do_executemany(
self, cursor, statement, parameters, context=None):
try:
super().do_executemany( # type: ignore[misc]
super().do_executemany(
cursor, statement, parameters, context)
except Exception as e:
normalized = _normalize_driver_error(e, self._driver_error_module())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def get_readonly(self, dbapi_conn: Any) -> bool:
return bool(getattr(wrapper, "read_only", False))

@classmethod
def import_dbapi(cls) -> Any: # type: ignore[override]
def import_dbapi(cls) -> Any:
# Parent's return type hint is SA's AsyncAdapt_aiomysql_dbapi class
# specifically; ours is a shim-compatible duck-type. Use Any to
# avoid variance grief with mypy.
Expand Down
3 changes: 0 additions & 3 deletions aws_advanced_python_wrapper/stale_dns_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,6 @@ def init_host_provider(

init_host_provider_func()

if self._host_list_provider_service.is_static_host_list_provider():
raise Exception(Messages.get_formatted("StaleDnsPlugin.RequireDynamicProvider"))

def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]):
self._stale_dns_helper.notify_host_list_changed(changes)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, tracer: Tracer, name: str, trace_level: TelemetryTraceLevel,
self._meter: Meter
self._token: Optional[object] = None

current_span: Span = trace.get_current_span() # type: ignore[assignment]
current_span: trace_api.Span = trace.get_current_span()
is_root = (current_span is None or current_span == trace.INVALID_SPAN)

if is_root and trace_level == TelemetryTraceLevel.NESTED:
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/MySQLSimpleReadWriteSplitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
if TYPE_CHECKING:
from aws_advanced_python_wrapper.pep249 import Connection

import mysql.connector # type: ignore
import mysql.connector

from aws_advanced_python_wrapper import AwsWrapperConnection, release_resources
from aws_advanced_python_wrapper.errors import (
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/PGSimpleReadWriteSplitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
if TYPE_CHECKING:
from aws_advanced_python_wrapper.pep249 import Connection

import psycopg # type: ignore
import psycopg

from aws_advanced_python_wrapper import AwsWrapperConnection, release_resources
from aws_advanced_python_wrapper.errors import (
Expand Down
3 changes: 3 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
[mypy]
strict_equality = True
warn_unused_ignores = True
enable_error_code = ignore-without-code, unused-awaitable
exclude = (?x)(
debug_integration_.*\.py$
| MySQLFailover\.py
Expand Down
Loading