Skip to content

Commit 6c8f1a7

Browse files
authored
Keep the server error when the connection closes mid-operation (MagicStack#1369)
Co-authored-by: Riti Grover <[email protected]>
1 parent 4cf0220 commit 6c8f1a7

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

‎asyncpg/protocol/protocol.pyx‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -674,9 +674,19 @@ cdef class BaseProtocol(CoreProtocol):
674674

675675
cdef _handle_waiter_on_connection_lost(self, cause):
676676
if self.waiter is not None and not self.waiter.done():
677-
exc = apg_exc.ConnectionDoesNotExistError(
678-
'connection was closed in the middle of '
679-
'operation')
677+
msg = 'connection was closed in the middle of operation'
678+
if (self.result_type == RESULT_FAILED and
679+
isinstance(self.result, dict)):
680+
# The server sent an ErrorResponse and then closed the
681+
# connection without a ReadyForQuery (a FATAL error, or
682+
# pgbouncer's query_wait_timeout). Do not lose it.
683+
server_exc = apg_exc_base.PostgresError.new(
684+
self.result, query=self.last_query)
685+
if cause is not None:
686+
server_exc.__cause__ = cause
687+
cause = server_exc
688+
msg = '{}: {}'.format(msg, server_exc.args[0])
689+
exc = apg_exc.ConnectionDoesNotExistError(msg)
680690
if cause is not None:
681691
exc.__cause__ = cause
682692
self.waiter.set_exception(exc)

‎tests/test_execute.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,32 @@ async def test_execute_script_interrupted_terminate(self):
9898

9999
self.con.terminate()
100100

101+
async def test_execute_script_interrupted_by_server(self):
102+
# The server reports why it is closing the connection with an
103+
# ErrorResponse and then closes it without a ReadyForQuery (this
104+
# is also what pgbouncer does on query_wait_timeout). The reported
105+
# error must not be lost.
106+
pid = await self.con.fetchval('SELECT pg_backend_pid()')
107+
fut = self.loop.create_task(
108+
self.con.execute('''SELECT pg_sleep(10)'''))
109+
110+
await asyncio.sleep(0.2)
111+
112+
other = await self.connect()
113+
try:
114+
await other.execute('SELECT pg_terminate_backend($1)', pid)
115+
finally:
116+
await other.close()
117+
118+
with self.assertRaisesRegex(
119+
asyncpg.ConnectionDoesNotExistError,
120+
'closed in the middle of operation: '
121+
'terminating connection'):
122+
await fut
123+
124+
exc = fut.exception()
125+
self.assertIsInstance(exc.__cause__, exceptions.AdminShutdownError)
126+
101127

102128
class TestExecuteMany(tb.ConnectedTestCase):
103129
def setUp(self):

0 commit comments

Comments
 (0)