Skip to content

Commit 39a1382

Browse files
committed
Fix memory retained by error responses
Pyramid keeps an error response's exception on the request. Its traceback reached the frame holding the pipeline result, so each failed request kept the selected metadata tree alive until a full garbage collection. Run the plumbings in their own function, re-raise HTTP errors without their traceback, and raise 409/500 outside the except clauses. HTTP errors such as 406 from content negotiation are no longer turned into 500. Closes #283.
1 parent 3180ea6 commit 39a1382

2 files changed

Lines changed: 150 additions & 40 deletions

File tree

‎src/pyff/api.py‎

Lines changed: 59 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import importlib
22
import threading
3+
import traceback
34
from collections.abc import Generator, Iterable, Mapping
45
from datetime import datetime, timedelta
56
from json import dumps
@@ -265,54 +266,72 @@ def _d(x: Optional[str], do_split: bool = True) -> tuple[Optional[str], Optional
265266
else:
266267
q = new_path
267268

269+
# The pipeline result - often the whole selected metadata tree - only lives in _run_plumbings' frame. Pyramid keeps
270+
# an error response's exception on the request, so an error must not reference that frame through its traceback:
271+
# request, exception and frame would form a reference cycle, freed only by a full garbage collection (issue #283).
268272
try:
269-
accepter = MediaAccept(accept)
270-
for p in request.registry.plumbings:
271-
state = {
272-
entry: True,
273-
'headers': {'Content-Type': None},
274-
'accept': accepter,
275-
'url': request.current_route_url(),
276-
'select': q,
277-
'match': match.lower() if match else match,
278-
'path': new_path,
279-
'stats': {},
280-
}
281-
282-
r = p.process(request.registry.md, state=state, raise_exceptions=True, scheduler=request.registry.scheduler)
283-
log.debug(f'Plumbing process result: {r}')
284-
if r is None:
285-
r = []
286-
287-
response = Response()
288-
_headers = state.get('headers', {})
289-
response.headers.update(_headers)
290-
ctype = _headers.get('Content-Type', None)
291-
if not ctype:
292-
r, t = _fmt(r, accepter)
293-
ctype = t
294-
295-
response.text = b2u(r)
296-
response.size = len(r)
297-
response.content_type = ctype
298-
cache_ttl = int(state.get('cache', 0))
299-
response.expires = datetime.now() + timedelta(seconds=cache_ttl)
300-
return response
273+
response = _run_plumbings(request, entry, accept, q, match, new_path)
274+
except exc.HTTPException as ex:
275+
# An HTTP error from processing, eg 406 from content negotiation, is the response as is.
276+
raise ex.with_traceback(None)
301277
except ResourceException as ex:
302-
import traceback
303-
304278
log.debug(traceback.format_exc())
305279
log.warning(f'Exception from processing pipeline: {ex}')
306-
raise exc.exception_response(409)
280+
status = 409
307281
except BaseException as ex:
308-
import traceback
309-
310282
log.debug(traceback.format_exc())
311283
log.error(f'Exception from processing pipeline: {ex}')
312-
raise exc.exception_response(500)
284+
status = 500
285+
else:
286+
if response is None and request.method == 'GET':
287+
raise exc.exception_response(404)
288+
return response
313289

314-
if request.method == 'GET':
315-
raise exc.exception_response(404)
290+
# Raised outside the except clauses, so that it does not chain the original exception and its traceback.
291+
raise exc.exception_response(status)
292+
293+
294+
def _run_plumbings(
295+
request: Request, entry: str, accept: str, q: Optional[str], match: Optional[str], new_path: Optional[str]
296+
) -> Optional[Response]:
297+
"""
298+
Run the request through the plumbings and format the result for the accepted content type.
299+
300+
:return: the response, or None if there are no plumbings
301+
"""
302+
accepter = MediaAccept(accept)
303+
for p in request.registry.plumbings:
304+
state = {
305+
entry: True,
306+
'headers': {'Content-Type': None},
307+
'accept': accepter,
308+
'url': request.current_route_url(),
309+
'select': q,
310+
'match': match.lower() if match else match,
311+
'path': new_path,
312+
'stats': {},
313+
}
314+
315+
r = p.process(request.registry.md, state=state, raise_exceptions=True, scheduler=request.registry.scheduler)
316+
log.debug(f'Plumbing process result: {r}')
317+
if r is None:
318+
r = []
319+
320+
response = Response()
321+
_headers = state.get('headers', {})
322+
response.headers.update(_headers)
323+
ctype = _headers.get('Content-Type', None)
324+
if not ctype:
325+
r, t = _fmt(r, accepter)
326+
ctype = t
327+
328+
response.text = b2u(r)
329+
response.size = len(r)
330+
response.content_type = ctype
331+
cache_ttl = int(state.get('cache', 0))
332+
response.expires = datetime.now() + timedelta(seconds=cache_ttl)
333+
return response
334+
return None
316335

317336

318337
def webfinger_handler(request: Request) -> Response:

‎src/pyff/test/test_md_api.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import gc
12
import json
23
import os
34
import shutil
45
import tempfile
56
import unittest
7+
import weakref
68
from datetime import datetime, timezone
79
from types import SimpleNamespace
10+
from unittest import mock
811
from urllib.parse import quote as urlescape
912

1013
import pytest
@@ -356,3 +359,91 @@ def test_entity_id_without_trailing_slash_is_not_found(self):
356359
with RequestsInterceptor(self.app, host='127.0.0.1', port=80) as url:
357360
assert requests.post(f'{url}/api/call/update').status_code == 200
358361
assert self._entity_ids(url, '/entities/https:/sp.example.com/saml2/metadata') == set()
362+
363+
364+
class _PipelineResult(list):
365+
"""A pipeline result that can be weakly referenced, to observe when it is freed"""
366+
367+
368+
class PyFFAPITestErrorResponses(PipeLineTest):
369+
"""
370+
Errors while processing a request must have the right status, and must not keep the pipeline result - often
371+
the whole selected metadata tree - alive after the request: cf. issue #283.
372+
"""
373+
374+
mdx = None
375+
app = None
376+
377+
@classmethod
378+
def setUpClass(cls):
379+
SignerTestCase.setUpClass()
380+
config.local_copy_dir = tempfile.mkdtemp()
381+
cls.mdx = tempfile.NamedTemporaryFile('w').name
382+
with open(cls.mdx, "w") as fd:
383+
fd.write(
384+
f"""
385+
- when update:
386+
- load:
387+
- {os.path.join(cls.datadir, 'metadata', 'test01.xml')}
388+
- when request:
389+
- select
390+
- pipe:
391+
- when accept application/xml:
392+
- emit application/xml
393+
- break
394+
"""
395+
)
396+
cls._app = mkapp(cls.mdx)
397+
cls.app = lambda *args, **kwargs: cls._app
398+
399+
@classmethod
400+
def tearDownClass(cls):
401+
SignerTestCase.tearDownClass()
402+
if os.path.exists(cls.mdx):
403+
os.unlink(cls.mdx)
404+
if os.path.exists(config.local_copy_dir):
405+
shutil.rmtree(config.local_copy_dir)
406+
407+
def _request_with_pipeline_result(self, url, fail):
408+
"""
409+
GET /entities as text/plain with the pipeline replaced by one producing a weakly referenceable result,
410+
then failing if ``fail``. The garbage collector is off, so only reference counting can free the result.
411+
412+
:return: the HTTP status and whether the result was freed once the request was done
413+
"""
414+
refs = []
415+
416+
def process(*args, **kwargs):
417+
result = _PipelineResult(['<md:EntitiesDescriptor/>'])
418+
refs.append(weakref.ref(result))
419+
if fail:
420+
raise RuntimeError("pipeline failed")
421+
return result
422+
423+
gc.collect()
424+
gc.disable()
425+
try:
426+
with mock.patch.object(self._app.registry.plumbings[0], 'process', process):
427+
status = requests.get(f'{url}/entities', headers={'Accept': 'text/plain'}).status_code
428+
return status, refs[0]() is None
429+
finally:
430+
gc.enable()
431+
432+
def test_unacceptable_type_is_406(self):
433+
"""No pipeline branch and no format matches text/plain: that is 406 Not Acceptable, not a server error"""
434+
with RequestsInterceptor(self.app, host='127.0.0.1', port=80) as url:
435+
assert requests.post(f'{url}/api/call/update').status_code == 200
436+
r = requests.get(f'{url}/entities', headers={'Accept': 'text/plain'})
437+
assert r.status_code == 406
438+
439+
def test_406_frees_the_pipeline_result(self):
440+
with RequestsInterceptor(self.app, host='127.0.0.1', port=80) as url:
441+
status, freed = self._request_with_pipeline_result(url, fail=False)
442+
assert status == 406
443+
assert freed, "the pipeline result outlived a 406 response"
444+
445+
def test_500_frees_the_pipeline_result(self):
446+
with RequestsInterceptor(self.app, host='127.0.0.1', port=80) as url:
447+
status, freed = self._request_with_pipeline_result(url, fail=True)
448+
assert status == 500
449+
assert freed, "the pipeline result outlived a 500 response"

0 commit comments

Comments
 (0)