file_consumer.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # Copyright 2018 New Vector Ltd
  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. import queue
  15. from typing import BinaryIO, Optional, Union, cast
  16. from twisted.internet import threads
  17. from twisted.internet.defer import Deferred
  18. from twisted.internet.interfaces import IPullProducer, IPushProducer
  19. from synapse.logging.context import make_deferred_yieldable, run_in_background
  20. from synapse.types import ISynapseReactor
  21. class BackgroundFileConsumer:
  22. """A consumer that writes to a file like object. Supports both push
  23. and pull producers
  24. Args:
  25. file_obj: The file like object to write to. Closed when
  26. finished.
  27. reactor: the Twisted reactor to use
  28. """
  29. # For PushProducers pause if we have this many unwritten slices
  30. _PAUSE_ON_QUEUE_SIZE = 5
  31. # And resume once the size of the queue is less than this
  32. _RESUME_ON_QUEUE_SIZE = 2
  33. def __init__(self, file_obj: BinaryIO, reactor: ISynapseReactor) -> None:
  34. self._file_obj: BinaryIO = file_obj
  35. self._reactor: ISynapseReactor = reactor
  36. # Producer we're registered with
  37. self._producer: Optional[Union[IPushProducer, IPullProducer]] = None
  38. # True if PushProducer, false if PullProducer
  39. self.streaming = False
  40. # For PushProducers, indicates whether we've paused the producer and
  41. # need to call resumeProducing before we get more data.
  42. self._paused_producer = False
  43. # Queue of slices of bytes to be written. When producer calls
  44. # unregister a final None is sent.
  45. self._bytes_queue: queue.Queue[Optional[bytes]] = queue.Queue()
  46. # Deferred that is resolved when finished writing
  47. self._finished_deferred: Optional[Deferred[None]] = None
  48. # If the _writer thread throws an exception it gets stored here.
  49. self._write_exception: Optional[Exception] = None
  50. def registerProducer(
  51. self, producer: Union[IPushProducer, IPullProducer], streaming: bool
  52. ) -> None:
  53. """Part of IConsumer interface
  54. Args:
  55. producer
  56. streaming: True if push based producer, False if pull
  57. based.
  58. """
  59. if self._producer:
  60. raise Exception("registerProducer called twice")
  61. self._producer = producer
  62. self.streaming = streaming
  63. self._finished_deferred = run_in_background(
  64. threads.deferToThreadPool,
  65. self._reactor,
  66. self._reactor.getThreadPool(),
  67. self._writer,
  68. )
  69. if not streaming:
  70. self._producer.resumeProducing()
  71. def unregisterProducer(self) -> None:
  72. """Part of IProducer interface"""
  73. self._producer = None
  74. assert self._finished_deferred is not None
  75. if not self._finished_deferred.called:
  76. self._bytes_queue.put_nowait(None)
  77. def write(self, write_bytes: bytes) -> None:
  78. """Part of IProducer interface"""
  79. if self._write_exception:
  80. raise self._write_exception
  81. assert self._finished_deferred is not None
  82. if self._finished_deferred.called:
  83. raise Exception("consumer has closed")
  84. self._bytes_queue.put_nowait(write_bytes)
  85. # If this is a PushProducer and the queue is getting behind
  86. # then we pause the producer.
  87. if self.streaming and self._bytes_queue.qsize() >= self._PAUSE_ON_QUEUE_SIZE:
  88. self._paused_producer = True
  89. assert self._producer is not None
  90. # cast safe because `streaming` means this is an IPushProducer
  91. cast(IPushProducer, self._producer).pauseProducing()
  92. def _writer(self) -> None:
  93. """This is run in a background thread to write to the file."""
  94. try:
  95. while self._producer or not self._bytes_queue.empty():
  96. # If we've paused the producer check if we should resume the
  97. # producer.
  98. if self._producer and self._paused_producer:
  99. if self._bytes_queue.qsize() <= self._RESUME_ON_QUEUE_SIZE:
  100. self._reactor.callFromThread(self._resume_paused_producer)
  101. bytes = self._bytes_queue.get()
  102. # If we get a None (or empty list) then that's a signal used
  103. # to indicate we should check if we should stop.
  104. if bytes:
  105. self._file_obj.write(bytes)
  106. # If its a pull producer then we need to explicitly ask for
  107. # more stuff.
  108. if not self.streaming and self._producer:
  109. self._reactor.callFromThread(self._producer.resumeProducing)
  110. except Exception as e:
  111. self._write_exception = e
  112. raise
  113. finally:
  114. self._file_obj.close()
  115. def wait(self) -> "Deferred[None]":
  116. """Returns a deferred that resolves when finished writing to file"""
  117. return make_deferred_yieldable(self._finished_deferred)
  118. def _resume_paused_producer(self) -> None:
  119. """Gets called if we should resume producing after being paused"""
  120. if self._paused_producer and self._producer:
  121. self._paused_producer = False
  122. self._producer.resumeProducing()