additional_resource.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from synapse.http.server import wrap_request_handler
  16. from twisted.web.resource import Resource
  17. from twisted.web.server import NOT_DONE_YET
  18. class AdditionalResource(Resource):
  19. """Resource wrapper for additional_resources
  20. If the user has configured additional_resources, we need to wrap the
  21. handler class with a Resource so that we can map it into the resource tree.
  22. This class is also where we wrap the request handler with logging, metrics,
  23. and exception handling.
  24. """
  25. def __init__(self, hs, handler):
  26. """Initialise AdditionalResource
  27. The ``handler`` should return a deferred which completes when it has
  28. done handling the request. It should write a response with
  29. ``request.write()``, and call ``request.finish()``.
  30. Args:
  31. hs (synapse.server.HomeServer): homeserver
  32. handler ((twisted.web.server.Request) -> twisted.internet.defer.Deferred):
  33. function to be called to handle the request.
  34. """
  35. Resource.__init__(self)
  36. self._handler = handler
  37. # these are required by the request_handler wrapper
  38. self.version_string = hs.version_string
  39. self.clock = hs.get_clock()
  40. def render(self, request):
  41. self._async_render(request)
  42. return NOT_DONE_YET
  43. @wrap_request_handler
  44. def _async_render(self, request):
  45. return self._handler(request)