summary refs log tree commit diff
path: root/synapse/util
diff options
context:
space:
mode:
authorErik Johnston <erik@matrix.org>2015-02-11 17:10:33 +0000
committerErik Johnston <erik@matrix.org>2015-02-11 17:10:33 +0000
commitc52e8d395be2e6bc7bd2e768cd3fdc18df448603 (patch)
tree76a07d178fcbe350bc6f2046b05a045e00bdaaf2 /synapse/util
parentMerge pull request #62 from matrix-org/state-chache (diff)
parentFix so timing out connections to actually work. (diff)
downloadsynapse-c52e8d395be2e6bc7bd2e768cd3fdc18df448603.tar.xz
Merge pull request #61 from matrix-org/timeout-federation-requests
Timeout federation requests
Diffstat (limited to 'synapse/util')
-rw-r--r--synapse/util/__init__.py55
1 files changed, 54 insertions, 1 deletions
diff --git a/synapse/util/__init__.py b/synapse/util/__init__.py
index fee76b0a9b..e77eba90ad 100644
--- a/synapse/util/__init__.py
+++ b/synapse/util/__init__.py
@@ -15,9 +15,12 @@
 
 from synapse.util.logcontext import LoggingContext
 
-from twisted.internet import reactor, task
+from twisted.internet import defer, reactor, task
 
 import time
+import logging
+
+logger = logging.getLogger(__name__)
 
 
 class Clock(object):
@@ -53,3 +56,53 @@ class Clock(object):
 
     def cancel_call_later(self, timer):
         timer.cancel()
+
+    def time_bound_deferred(self, given_deferred, time_out):
+        if given_deferred.called:
+            return given_deferred
+
+        ret_deferred = defer.Deferred()
+
+        def timed_out_fn():
+            try:
+                ret_deferred.errback(RuntimeError("Timed out"))
+            except:
+                pass
+
+            try:
+                given_deferred.cancel()
+            except:
+                pass
+
+        timer = None
+
+        def cancel(res):
+            try:
+                self.cancel_call_later(timer)
+            except:
+                pass
+            return res
+
+        ret_deferred.addBoth(cancel)
+
+        def sucess(res):
+            try:
+                ret_deferred.callback(res)
+            except:
+                pass
+
+            return res
+
+        def err(res):
+            try:
+                ret_deferred.errback(res)
+            except:
+                pass
+
+            return res
+
+        given_deferred.addCallbacks(callback=sucess, errback=err)
+
+        timer = self.call_later(time_out, timed_out_fn)
+
+        return ret_deferred