選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

57 行
2.3 KiB

  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Callable, TypeVar
  15. F = TypeVar("F", bound=Callable[..., Any])
  16. def cancellable(function: F) -> F:
  17. """Marks a function as cancellable.
  18. Servlet methods with this decorator will be cancelled if the client disconnects before we
  19. finish processing the request.
  20. Although this annotation is particularly useful for servlet methods, it's also
  21. useful for intermediate functions, where it documents the fact that the function has
  22. been audited for cancellation safety and needs to preserve that.
  23. This then simplifies auditing new functions that call those same intermediate
  24. functions.
  25. During cancellation, `Deferred.cancel()` will be invoked on the `Deferred` wrapping
  26. the method. The `cancel()` call will propagate down to the `Deferred` that is
  27. currently being waited on. That `Deferred` will raise a `CancelledError`, which will
  28. propagate up, as per normal exception handling.
  29. Before applying this decorator to a new function, you MUST recursively check
  30. that all `await`s in the function are on `async` functions or `Deferred`s that
  31. handle cancellation cleanly, otherwise a variety of bugs may occur, ranging from
  32. premature logging context closure, to stuck requests, to database corruption.
  33. See the documentation page on Cancellation for more information.
  34. Usage:
  35. class SomeServlet(RestServlet):
  36. @cancellable
  37. async def on_GET(self, request: SynapseRequest) -> ...:
  38. ...
  39. """
  40. function.cancellable = True # type: ignore[attr-defined]
  41. return function
  42. def is_function_cancellable(function: Callable[..., Any]) -> bool:
  43. """Checks whether a servlet method has the `@cancellable` flag."""
  44. return getattr(function, "cancellable", False)