William Kurkian | 6f436d0 | 2019-02-06 16:25:01 -0500 | [diff] [blame] | 1 | # Copyright 2017-present Open Networking Foundation |
| 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 twisted.internet import reactor |
| 15 | from twisted.internet.defer import Deferred |
| 16 | from twisted.internet.error import AlreadyCalled |
| 17 | |
| 18 | |
| 19 | class TimeOutError(Exception): pass |
| 20 | |
| 21 | |
| 22 | class DeferredWithTimeout(Deferred): |
| 23 | """ |
| 24 | Deferred with a timeout. If neither the callback nor the errback method |
| 25 | is not called within the given time, the deferred's errback will be called |
| 26 | with a TimeOutError() exception. |
| 27 | |
| 28 | All other uses are the same as of Deferred(). |
| 29 | """ |
| 30 | def __init__(self, timeout=1.0): |
| 31 | Deferred.__init__(self) |
| 32 | self._timeout = timeout |
| 33 | self.timer = reactor.callLater(timeout, self.timed_out) |
| 34 | |
| 35 | def timed_out(self): |
| 36 | self.errback( |
| 37 | TimeOutError('timed out after {} seconds'.format(self._timeout))) |
| 38 | |
| 39 | def callback(self, result): |
| 40 | self._cancel_timer() |
| 41 | return Deferred.callback(self, result) |
| 42 | |
| 43 | def errback(self, fail): |
| 44 | self._cancel_timer() |
| 45 | return Deferred.errback(self, fail) |
| 46 | |
| 47 | def cancel(self): |
| 48 | self._cancel_timer() |
| 49 | return Deferred.cancel(self) |
| 50 | |
| 51 | def _cancel_timer(self): |
| 52 | try: |
| 53 | self.timer.cancel() |
| 54 | except AlreadyCalled: |
| 55 | pass |
| 56 | |