Skip to content

Commit 10a023f

Browse files
committed
feat: plugin call context for cursor execute arguments
1 parent 7e31ed8 commit 10a023f

12 files changed

Lines changed: 969 additions & 28 deletions

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
## [Unreleased]
77

88
### :magic_wand: Added
9+
* Synchronous plugins can replace the arguments that `Cursor.execute` and `Cursor.executemany` pass to the plugins after them and to the target driver, without modifying the caller's objects, by assigning new `args` and `kwargs` to the plugin service's `current_call_context`. See [The Call Context](./docs/development-guide/PluginService.md#the-call-context). ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
910
* The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275))
1011

12+
### :bug: Fixed
13+
* With psycopg's synchronous cursor, a fetch chained onto `cursor.execute()` (`cursor.execute(query).fetchone()`) skipped every plugin, the failover and host monitoring plugins included, because `execute()` returned the driver's cursor. It now returns the wrapper's cursor, so `isinstance(cursor.execute(query), psycopg.Cursor)` is now `False`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
14+
* `next(cursor)` on a synchronous cursor raised `TypeError`. It now returns the next row through the plugins subscribed to `Cursor.fetchone`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
15+
* Loops over a synchronous cursor (`for row in cursor`) skipped every plugin. A loop now calls the plugins subscribed to `Cursor.__iter__`, and those subscribed to every method, such as `execute_time`, once per loop, not once per row. A loop over a cursor whose connection is no longer the current one now raises `AwsWrapperError` where `fetchone` does. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
16+
1117
## [3.1.0] - 2026-08-24
1218
### :magic_wand: Added
1319
* Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252))

‎aws_advanced_python_wrapper/driver_dialect.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,9 @@ def execute(
131131
exec_timeout: Optional[float] = None,
132132
conn: Optional[Connection] = None,
133133
**kwargs: Any) -> Cursor:
134-
if DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods:
134+
# Cursor.__iter__ only creates the driver's iterator; the rows are fetched outside this call.
135+
if method_name == DbApiMethod.CURSOR_ITER.method_name or (
136+
DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods):
135137
return exec_func()
136138

137139
if exec_timeout is None:

‎aws_advanced_python_wrapper/pep249_methods.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,19 +61,20 @@ class DbApiMethod(Enum):
6161
CURSOR_CONNECTION = (28, "Cursor.connection", False)
6262
CURSOR_ROWNUMBER = (29, "Cursor.rownumber", False)
6363
CURSOR_NEXT = (30, "Cursor.__next__", False)
64-
CURSOR_LASTROWID = (31, "Cursor.lastrowid", False)
64+
CURSOR_ITER = (31, "Cursor.__iter__", False)
65+
CURSOR_LASTROWID = (32, "Cursor.lastrowid", False)
6566

6667
# AWS Advanced Python Wrapper Methods for the execution pipelines.
67-
CONNECT = (32, "connect", True)
68-
FORCE_CONNECT = (33, "force_connect", True)
69-
INIT_HOST_PROVIDER = (34, "init_host_provider", True)
70-
NOTIFY_CONNECTION_CHANGED = (35, "notify_connection_changed", True)
71-
NOTIFY_HOST_LIST_CHANGED = (36, "notify_host_list_changed", True)
72-
GET_HOST_INFO_BY_STRATEGY = (37, "get_host_info_by_strategy", True)
73-
ACCEPTS_STRATEGY = (38, "accepts_strategy", True)
68+
CONNECT = (33, "connect", True)
69+
FORCE_CONNECT = (34, "force_connect", True)
70+
INIT_HOST_PROVIDER = (35, "init_host_provider", True)
71+
NOTIFY_CONNECTION_CHANGED = (36, "notify_connection_changed", True)
72+
NOTIFY_HOST_LIST_CHANGED = (37, "notify_host_list_changed", True)
73+
GET_HOST_INFO_BY_STRATEGY = (38, "get_host_info_by_strategy", True)
74+
ACCEPTS_STRATEGY = (39, "accepts_strategy", True)
7475

7576
# Special marker for all methods
76-
ALL = (39, "*", False)
77+
ALL = (40, "*", False)
7778

7879
def __init__(self, id: int, method_name: str, always_use_pipeline: bool):
7980
self.id = id

‎aws_advanced_python_wrapper/plugin.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,18 @@ def force_connect(
9393
return force_connect_func()
9494

9595
def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any:
96+
"""
97+
Handles a call to a method this plugin subscribes to, such as `Cursor.execute`. Calling `execute_func` runs the plugins after this one,
98+
then the target driver method. To send different `Cursor.execute` or `Cursor.executemany` arguments to them, assign a new tuple to the
99+
`args` and a new mapping to the `kwargs` of :py:attr:`PluginService.current_call_context` before calling `execute_func`.
100+
101+
:param target: the target driver object the method is called on, such as the driver's cursor or connection.
102+
:param method_name: the name of the method, such as `Cursor.execute`.
103+
:param execute_func: the function to call to continue the call down the pipeline.
104+
:param args: the method's positional arguments, as they are when this plugin's turn comes.
105+
:param kwargs: the method's keyword arguments, as they are when this plugin's turn comes.
106+
:return: the result of the call, usually the value `execute_func` returns.
107+
"""
96108
return execute_func()
97109

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

‎aws_advanced_python_wrapper/plugin_service.py‎

Lines changed: 104 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@
4646
from abc import abstractmethod
4747
from concurrent.futures import TimeoutError
4848
from contextlib import closing
49-
from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, Set,
50-
Tuple)
49+
from contextvars import ContextVar
50+
from functools import partial
51+
from typing import (Any, Callable, Dict, FrozenSet, Mapping, Optional,
52+
Protocol, Set, Tuple)
5153

5254
from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \
5355
AllowedAndBlockedHosts
@@ -215,6 +217,23 @@ def network_bound_methods(self) -> Set[str]:
215217
def props(self) -> Properties:
216218
...
217219

220+
@property
221+
@abstractmethod
222+
def current_call_context(self) -> Optional[PluginCallContext]:
223+
"""
224+
The context of the ``Cursor.execute`` or ``Cursor.executemany`` call this thread is running through the plugins.
225+
226+
Read it only while handling one of those two methods. Each of those calls has its own context, a call made
227+
from inside a plugin included, and the enclosing one is current again once it returns. Other methods get no
228+
context of their own, so while one of them runs inside such a call, this still returns the enclosing call's
229+
context. ``None`` when no such call is running on this thread.
230+
231+
The value belongs to the calling thread, not to this connection's plugin service. Another thread sees it only
232+
through a copy of this thread's context taken during the call (``contextvars.copy_context()``, or a thread
233+
that inherits its creator's context), and such a copy holds no arguments once the call has returned.
234+
"""
235+
...
236+
218237
def is_network_bound_method(self, method_name: str) -> bool:
219238
...
220239

@@ -521,6 +540,10 @@ def network_bound_methods(self) -> Set[str]:
521540
def props(self) -> Properties:
522541
return self._props
523542

543+
@property
544+
def current_call_context(self) -> Optional[PluginCallContext]:
545+
return _CURRENT_CALL_CONTEXT.get()
546+
524547
def update_in_transaction(self, is_in_transaction: Optional[bool] = None):
525548
if is_in_transaction is not None:
526549
self._is_in_transaction = is_in_transaction
@@ -816,6 +839,36 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]:
816839
return status
817840

818841

842+
class PluginCallContext:
843+
"""The arguments of the ``Cursor.execute`` or ``Cursor.executemany`` call the plugins are handling.
844+
845+
Each plugin's ``execute`` receives the arguments as they are when its turn comes. A plugin that needs to hand
846+
different ones to the plugins after it and to the target driver method assigns a new tuple to ``args`` and a new
847+
mapping to ``kwargs`` before it calls its ``execute_func``. Changing either object in place is not allowed, and
848+
the caller's own objects must never be modified. The target driver method receives exactly what is assigned, even
849+
when it is empty. A replacement lasts until the plugin that made it returns, so a plugin before it that calls its
850+
``execute_func`` again starts from the arguments it saw.
851+
852+
Reached through :py:attr:`PluginService.current_call_context`.
853+
"""
854+
855+
__slots__ = ("args", "kwargs")
856+
857+
def __init__(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]):
858+
self.args = args
859+
self.kwargs = kwargs
860+
861+
862+
# The methods whose call gets a PluginCallContext. Their target driver functions (in AwsWrapperCursor) take the
863+
# context's arguments.
864+
_CALL_CONTEXT_METHODS: FrozenSet[DbApiMethod] = frozenset({DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY})
865+
866+
# The current call's context belongs to the calling thread, not to a plugin service, so it is a ContextVar. Resetting
867+
# its token in PluginManager.execute makes the enclosing call's context current again after a nested call.
868+
_CURRENT_CALL_CONTEXT: ContextVar[Optional[PluginCallContext]] = ContextVar(
869+
"aws_advanced_python_wrapper_plugin_call_context", default=None)
870+
871+
819872
class PluginChainCallableInfo:
820873
"""Container for plugin chain callable and subscription information."""
821874
def __init__(self, func: Callable, is_subscribed: bool):
@@ -1022,13 +1075,18 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla
10221075
if context is not None:
10231076
context.set_attribute("python_call", method.method_name)
10241077

1078+
call_context = PluginCallContext(args, kwargs) if method in _CALL_CONTEXT_METHODS else None
1079+
token = None if call_context is None else _CURRENT_CALL_CONTEXT.set(call_context)
10251080
try:
1026-
result = self._execute_with_subscribed_plugins(
1027-
method,
1028-
# next_plugin_func is defined later in make_pipeline
1029-
lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs),
1030-
target_driver_func,
1031-
None)
1081+
if call_context is None:
1082+
result = self._execute_with_subscribed_plugins(
1083+
method,
1084+
# next_plugin_func is defined later in make_pipeline
1085+
lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs),
1086+
target_driver_func,
1087+
None)
1088+
else:
1089+
result = self._execute_with_call_context(target, method, target_driver_func, call_context)
10321090
if context is not None:
10331091
context.set_success(True)
10341092

@@ -1038,9 +1096,47 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla
10381096
context.set_success(False)
10391097
raise e
10401098
finally:
1099+
if token is not None:
1100+
_CURRENT_CALL_CONTEXT.reset(token)
1101+
if call_context is not None:
1102+
# A copy of this thread's context taken during the call (one a plugin passes to a thread it starts, say)
1103+
# still holds this object, so it must not keep the call's arguments once the call has returned.
1104+
call_context.args, call_context.kwargs = (), {}
10411105
if context is not None:
10421106
context.close_context()
10431107

1108+
def _execute_with_call_context(
1109+
self, target: Any, method: DbApiMethod, target_driver_func: Callable, call_context: PluginCallContext) -> Any:
1110+
# The target driver function is always called with the context's arguments, so a replacement reaches the
1111+
# driver as written: an empty one fails there instead of running the caller's arguments.
1112+
return self._execute_with_subscribed_plugins(
1113+
method,
1114+
lambda plugin, next_plugin_func: PluginManager._execute_plugin(
1115+
plugin, target, method, next_plugin_func, call_context, target_driver_func),
1116+
lambda: target_driver_func(*call_context.args, **call_context.kwargs),
1117+
None)
1118+
1119+
@staticmethod
1120+
def _execute_plugin(
1121+
plugin: Plugin,
1122+
target: Any,
1123+
method: DbApiMethod,
1124+
next_plugin_func: Callable,
1125+
call_context: PluginCallContext,
1126+
target_driver_func: Callable) -> Any:
1127+
# Each plugin gets the arguments as they are when its turn comes, so a replacement made before it is honoured.
1128+
# A replacement lasts until the plugin that made it returns: a plugin before it that calls its execute_func
1129+
# again starts from the arguments it saw, so nothing is replaced twice.
1130+
args, kwargs = call_context.args, call_context.kwargs
1131+
if isinstance(plugin, DefaultPlugin):
1132+
# DefaultPlugin may run the driver call on a socket_timeout worker that starts only after this call has
1133+
# timed out and every replacement has been undone, so the driver function gets these arguments bound now.
1134+
next_plugin_func = partial(target_driver_func, *args, **kwargs)
1135+
try:
1136+
return plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs)
1137+
finally:
1138+
call_context.args, call_context.kwargs = args, kwargs
1139+
10441140
def _execute_with_telemetry(self, plugin_name: str, func: Callable):
10451141
context = self._telemetry_factory.open_telemetry_context(plugin_name, TelemetryTraceLevel.NESTED)
10461142
try:

‎aws_advanced_python_wrapper/wrapper.py‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -401,16 +401,21 @@ def execute(
401401
*args: Any,
402402
**kwargs: Any
403403
) -> AwsWrapperCursor:
404-
return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE,
405-
lambda: self.target_cursor.execute(*args, **kwargs), *args, **kwargs)
404+
# The plugin manager calls the driver with the statement's arguments,
405+
# which a plugin may have replaced.
406+
result = self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE,
407+
lambda *a, **kw: self.target_cursor.execute(*a, **kw), *args, **kwargs)
408+
# psycopg returns the driver cursor itself; return this cursor instead,
409+
# so a chained fetch goes through the plugins.
410+
return self if result is self.target_cursor else result
406411

407412
def executemany(
408413
self,
409414
*args: Any,
410415
**kwargs: Any
411416
) -> None:
412417
self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTEMANY,
413-
lambda: self.target_cursor.executemany(*args, **kwargs),
418+
lambda *a, **kw: self.target_cursor.executemany(*a, **kw),
414419
*args, **kwargs)
415420

416421
def nextset(self) -> bool:
@@ -430,7 +435,44 @@ def fetchall(self) -> List[Any]:
430435
lambda: self.target_cursor.fetchall())
431436

432437
def __iter__(self) -> Iterator[Any]:
433-
return self.target_cursor.__iter__()
438+
# The plugins subscribed to Cursor.__iter__ run once per loop, not once
439+
# per row: such a plugin returns an iterator over the driver's (one that
440+
# changes each row, say). The driver's iterator still fetches the rows,
441+
# so a server-side cursor keeps fetching a page at a time.
442+
return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_ITER,
443+
lambda: iter(self.target_cursor))
444+
445+
def __next__(self) -> Any:
446+
# A loop doesn't call this method: __iter__ returns the driver's iterator.
447+
# The plugins subscribed to Cursor.fetchone run for each row. A driver cursor
448+
# that is its own iterator (psycopg 3.3 and later) gives the row with its own
449+
# next(), so a server-side cursor continues the page a loop read ahead; any
450+
# other driver cursor gives it with fetchone.
451+
target = self.target_cursor
452+
rows = iter(target)
453+
if rows is not target:
454+
row = self.fetchone()
455+
if row is None:
456+
raise StopIteration
457+
return row
458+
# A row can itself be None (psycopg's scalar_row on a NULL), so the rows end
459+
# only when the driver's next() ends them or a plugin returns None without
460+
# reading a row. The plugins see the end as None, as from fetchone.
461+
read = False
462+
463+
def next_row() -> Any:
464+
nonlocal read
465+
try:
466+
row = next(rows)
467+
except StopIteration:
468+
return None
469+
read = True
470+
return row
471+
472+
row = self._plugin_manager.execute(target, DbApiMethod.CURSOR_FETCHONE, next_row)
473+
if row is None and not read:
474+
raise StopIteration
475+
return row
434476

435477
def setinputsizes(self, sizes: Any) -> None:
436478
return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_SETINPUTSIZES,

‎docs/development-guide/LoadablePlugins.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ Plugins can also subscribe to specific [pipelines](./Pipelines.md) by including
5959
| [Connection changed notification pipeline](./Pipelines.md#connection-changed-notification-pipeline) | notify_connection_changed |
6060
| [Host list changed notification pipeline](./Pipelines.md#host-list-changed-notification-pipeline) | notify_host_list_changed |
6161

62+
A loop over a cursor (`for row in cursor`) calls the plugins subscribed to `Cursor.__iter__` once per loop, not once per row.
63+
Such a plugin calls `execute_func()` to get the target driver's iterator and returns an iterator over it, for example a generator that changes each row.
64+
The driver's iterator fetches the rows after the plugins have returned, so a server-side cursor still fetches a page at a time, and an error raised while fetching a row does not pass through the plugins' `execute` methods.
65+
The asynchronous cursor sends each row of a loop through the plugins as `Cursor.fetchone` instead.
66+
67+
With psycopg, `cursor.execute()` returns the wrapper's cursor, so a fetch chained onto it, such as `cursor.execute(query).fetchone()`, goes through the plugins as well.
68+
`next(cursor)` returns the next row through the plugins subscribed to `Cursor.fetchone`.
69+
6270
### Tips on Creating a Custom Plugin
6371

6472
A custom plugin can subscribe to all Python methods being executed by setting the Plugin's `subscribed_methods` attribute to `{"*"}`. In this case, the plugin will be active in every workflow. We recommend that you be aware of the performance impact of subscribing to all Python methods, especially if your plugin regularly performs demanding tasks for common Python method calls.
@@ -122,6 +130,9 @@ When creating custom plugins, it is important to **avoid** the following bad pra
122130
- the plugin should always call the pipeline lambdas (i.e. `connect_func: Callable` or `force_connect_func: Callable`)
123131
4. Running long tasks synchronously:
124132
- the Python method calls are executed by all subscribed plugins synchronously; if one plugin runs a long task during the execution it blocks the execution for the other plugins
133+
5. Modifying the arguments a method is called with:
134+
- the objects passed to a plugin's `execute` belong to the caller (its query parameters, for example) and must not be changed
135+
- to send different arguments to the plugins after it and to the target driver, a plugin assigns new ones to the [call context](./PluginService.md#the-call-context)
125136

126137
See the following examples for more details:
127138

0 commit comments

Comments
 (0)