Waits a given time, if the given deferred hasn't called back
    by then we cancel it. If the deferred was cancelled by the timeout,
    a `TimeoutError` error is produced.
    
    Returns `deferred`.

def timeout_deferred(deferred, timeout, error_message="Timeout occured"):
    """
    Waits a given time, if the given deferred hasn't called back
    by then we cancel it. If the deferred was cancelled by the timeout,
    a `TimeoutError` error is produced.
    
    Returns `deferred`.
    """
    
    timeout_occured = [False]
    
    def got_result(result):
        if not timeout_occured[0]:
            # Deferred called back before the timeout.
            delayedCall.cancel()
            return result
        else:
            if isinstance(result, failure.Failure) and result.check(defer.CancelledError):
                # Got a `CancelledError` after we called  `cancel()`.
                # Replace it with a `TimeoutError`.
                raise TimeoutError(error_message)
            else:
                # Apparently the given deferred has something else to tell us.
                # It might be that it completed before the `cancel()` had an effect
                # (or as a result thereof). It might also be that it triggered an
                # error. In either case, we want this to be visible down-stream.
                return result
    
    def time_is_up():
        timeout_occured[0] = True
        deferred.cancel()
    delayedCall = reactor.callLater(timeout, time_is_up)

    deferred.addBoth(got_result)
    return deferred