Skip to content

Commit dd1e1ff

Browse files
committed
feat: plugin call context for cursor execute arguments
Plugins see the arguments of Cursor.execute and Cursor.executemany but cannot replace what the target driver receives. Add a call context for synchronous plugins, read through PluginService.current_call_context. A plugin assigns new arguments to it before calling execute_func: the plugins after it and the driver get the new arguments, and the plugins before it and the caller keep their own. A replacement is undone when the plugin that made it returns. The driver's arguments are bound when the call reaches DefaultPlugin, so a driver call that starts late on a socket_timeout worker still sends them. Each thread has its own context, and the context's arguments are cleared when the call ends, so a copy of the thread's context taken during the call keeps none of them. Also route cursor loops through the plugins once per loop (as Cursor.__next__), and return the wrapper cursor from execute when the driver returns its own, so a fetch chained onto psycopg's execute goes through the plugins too. Document the call context in the developer guide and add CHANGELOG entries.
1 parent 7e31ed8 commit dd1e1ff

9 files changed

Lines changed: 682 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,13 @@ 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).
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, 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`.
14+
* Loops over a cursor (`for row in cursor`) skipped every plugin. A loop now calls the plugins subscribed to `Cursor.__next__`, and those subscribed to every method, such as `execute_time`, once per loop, not once per row. Like `fetchone`, a loop over a cursor whose connection is no longer the current one now raises `AwsWrapperError`.
15+
1116
## [3.1.0] - 2026-08-24
1217
### :magic_wand: Added
1318
* Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252))

‎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 change the arguments of `Cursor.execute` or `Cursor.executemany` for those, assign new ones to the
99+
`args` and `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: 102 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,34 @@ 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+
def __init__(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]):
856+
self.args = args
857+
self.kwargs = kwargs
858+
859+
860+
# The methods whose call gets a PluginCallContext. Their target driver functions (in AwsWrapperCursor) take the
861+
# context's arguments.
862+
_CALL_CONTEXT_METHODS: FrozenSet[DbApiMethod] = frozenset({DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY})
863+
864+
# The current call's context belongs to the calling thread, not to a plugin service, so it is a ContextVar. Resetting
865+
# its token in PluginManager.execute makes the enclosing call's context current again after a nested call.
866+
_CURRENT_CALL_CONTEXT: ContextVar[Optional[PluginCallContext]] = ContextVar(
867+
"aws_advanced_python_wrapper_plugin_call_context", default=None)
868+
869+
819870
class PluginChainCallableInfo:
820871
"""Container for plugin chain callable and subscription information."""
821872
def __init__(self, func: Callable, is_subscribed: bool):
@@ -1022,13 +1073,18 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla
10221073
if context is not None:
10231074
context.set_attribute("python_call", method.method_name)
10241075

1076+
call_context = PluginCallContext(args, kwargs) if method in _CALL_CONTEXT_METHODS else None
1077+
token = None if call_context is None else _CURRENT_CALL_CONTEXT.set(call_context)
10251078
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)
1079+
if call_context is None:
1080+
result = self._execute_with_subscribed_plugins(
1081+
method,
1082+
# next_plugin_func is defined later in make_pipeline
1083+
lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs),
1084+
target_driver_func,
1085+
None)
1086+
else:
1087+
result = self._execute_with_call_context(target, method, target_driver_func, call_context)
10321088
if context is not None:
10331089
context.set_success(True)
10341090

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

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

‎aws_advanced_python_wrapper/wrapper.py‎

Lines changed: 14 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,12 @@ 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.__next__ 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_NEXT,
443+
lambda: iter(self.target_cursor))
434444

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

‎docs/development-guide/LoadablePlugins.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ 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.__next__` once per loop, not once per row. 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. 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. The asynchronous cursor sends each row of a loop through the plugins as `Cursor.fetchone` instead.
63+
64+
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.
65+
6266
### Tips on Creating a Custom Plugin
6367

6468
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 +126,9 @@ When creating custom plugins, it is important to **avoid** the following bad pra
122126
- the plugin should always call the pipeline lambdas (i.e. `connect_func: Callable` or `force_connect_func: Callable`)
123127
4. Running long tasks synchronously:
124128
- 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
129+
5. Modifying the arguments a method is called with:
130+
- the objects passed to a plugin's `execute` belong to the caller (its query parameters, for example) and must not be changed
131+
- 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)
125132

126133
See the following examples for more details:
127134

‎docs/development-guide/PluginService.md‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,63 @@ It also keeps track of the host list provider in use, and notifies it to update
99
It is expected that the plugins do not establish a connection themselves, but rather call `PluginService.connect()`
1010
to establish connections.
1111

12+
## The Call Context
13+
14+
A plugin may need to change the arguments that `Cursor.execute` or
15+
`Cursor.executemany` passes to the target driver, for example to replace a
16+
parameter value or to rewrite the statement. The call context covers these
17+
two methods only.
18+
19+
While one of them runs through the plugins,
20+
`PluginService.current_call_context` holds the call's arguments as a
21+
`PluginCallContext` with two attributes, `args` (a tuple) and `kwargs` (a
22+
mapping). A plugin that changes them **assigns** a new tuple to `args` and a
23+
new mapping to `kwargs` before it calls `execute_func`:
24+
25+
```python
26+
def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any:
27+
context = self._plugin_service.current_call_context
28+
if context is not None:
29+
context.args, context.kwargs = self._rewrite(args, kwargs) # a new tuple and a new dict
30+
return execute_func()
31+
```
32+
33+
The plugins after it in the chain, and the target driver, receive exactly the
34+
new arguments, even when they are empty; the plugins before it keep
35+
theirs. Changing `args` or `kwargs` in place is not allowed, and the
36+
caller's own objects must never be modified.
37+
38+
`current_call_context` is set whenever a plugin handles one of these two
39+
methods through the wrapper. A plugin that must change the arguments, rather
40+
than one that may, should raise when it finds `None` instead of calling
41+
`execute_func` with the arguments unchanged.
42+
43+
A replacement lasts until the plugin that made it returns. A plugin before it
44+
that calls `execute_func` again starts again from the arguments it saw, so the
45+
replacement is made once per run. The arguments the target driver receives
46+
are fixed when the call reaches `DefaultPlugin`, the last plugin in the chain,
47+
so a driver call that `socket_timeout` runs on a worker thread sends them even
48+
if it starts late. That covers `DefaultPlugin` only: a plugin that runs
49+
`execute_func` on a thread of its own must wait for that call before it returns,
50+
since a call that reaches `DefaultPlugin` after the plugin that made a
51+
replacement has returned sends the arguments without it.
52+
53+
Each `Cursor.execute` and `Cursor.executemany` call has its own context, a
54+
call made from inside a plugin included, and the enclosing call's context is
55+
current again when it returns. Other methods get no context of their own:
56+
during a `Cursor.fetchone` called from inside an `execute`, for example,
57+
`current_call_context` still returns the enclosing call's context. So read it
58+
only while handling `Cursor.execute` or `Cursor.executemany`. It is `None`
59+
when no such call is running on the thread.
60+
61+
The context belongs to the calling thread, not to the connection's plugin
62+
service. Another thread sees it only through a copy of the thread's context
63+
taken during the call (`contextvars.copy_context()`, or a thread that inherits
64+
its creator's context), and such a copy holds no arguments once the call has
65+
returned.
66+
67+
The call context is available to synchronous plugins only.
68+
1269
## Host List Providers
1370

1471
The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database.

0 commit comments

Comments
 (0)