-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
defer.py
2737 lines (2248 loc) · 97.6 KB
/
defer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: twisted.test.test_defer -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Support for results that aren't immediately available.
Maintainer: Glyph Lefkowitz
"""
from __future__ import annotations
import inspect
import traceback
import warnings
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, Future, iscoroutine
from contextvars import Context as _Context, copy_context as _copy_context
from enum import Enum
from functools import wraps
from sys import exc_info, implementation
from types import CoroutineType, GeneratorType, MappingProxyType, TracebackType
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Coroutine,
Generator,
Generic,
Iterable,
List,
Mapping,
NoReturn,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import attr
from incremental import Version
from typing_extensions import Concatenate, Literal, ParamSpec, Self
from twisted.internet.interfaces import IDelayedCall, IReactorTime
from twisted.logger import Logger
from twisted.python import lockfile
from twisted.python.compat import _PYPY, cmp, comparable
from twisted.python.deprecate import deprecated, warnAboutFunction
from twisted.python.failure import Failure, _extraneous
log = Logger()
_T = TypeVar("_T")
_P = ParamSpec("_P")
# See use in _inlineCallbacks for explanation and removal timeline.
_oldPypyStack = _PYPY and implementation.version < (7, 3, 14)
class AlreadyCalledError(Exception):
"""
This error is raised when one of L{Deferred.callback} or L{Deferred.errback}
is called after one of the two had already been called.
"""
class CancelledError(Exception):
"""
This error is raised by default when a L{Deferred} is cancelled.
"""
class TimeoutError(Exception):
"""
This error is raised by default when a L{Deferred} times out.
"""
class NotACoroutineError(TypeError):
"""
This error is raised when a coroutine is expected and something else is
encountered.
"""
def logError(err: Failure) -> Failure:
"""
Log and return failure.
This method can be used as an errback that passes the failure on to the
next errback unmodified. Note that if this is the last errback, and the
deferred gets garbage collected after being this errback has been called,
the clean up code logs it again.
"""
log.failure("", err)
return err
def succeed(result: _T) -> "Deferred[_T]":
"""
Return a L{Deferred} that has already had C{.callback(result)} called.
This is useful when you're writing synchronous code to an
asynchronous interface: i.e., some code is calling you expecting a
L{Deferred} result, but you don't actually need to do anything
asynchronous. Just return C{defer.succeed(theResult)}.
See L{fail} for a version of this function that uses a failing
L{Deferred} rather than a successful one.
@param result: The result to give to the Deferred's 'callback'
method.
"""
d: Deferred[_T] = Deferred()
# This violate abstraction boundaries, so code that is not internal to
# Twisted shouldn't do it, but it's a significant performance optimization:
d.result = result
d.called = True
d._chainedTo = None
return d
def fail(result: Optional[Union[Failure, BaseException]] = None) -> "Deferred[Any]":
"""
Return a L{Deferred} that has already had C{.errback(result)} called.
See L{succeed}'s docstring for rationale.
@param result: The same argument that L{Deferred.errback} takes.
@raise NoCurrentExceptionError: If C{result} is L{None} but there is no
current exception state.
"""
d: Deferred[Any] = Deferred()
d.errback(result)
return d
def execute(
callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
) -> "Deferred[_T]":
"""
Create a L{Deferred} from a callable and arguments.
Call the given function with the given arguments. Return a L{Deferred}
which has been fired with its callback as the result of that invocation
or its C{errback} with a L{Failure} for the exception thrown.
"""
try:
result = callable(*args, **kwargs)
except BaseException:
return fail()
else:
return succeed(result)
@overload
def maybeDeferred(
f: Callable[_P, Deferred[_T]], *args: _P.args, **kwargs: _P.kwargs
) -> "Deferred[_T]":
...
@overload
def maybeDeferred(
f: Callable[_P, Coroutine[Deferred[Any], Any, _T]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> "Deferred[_T]":
...
@overload
def maybeDeferred(
f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
) -> "Deferred[_T]":
...
def maybeDeferred(
f: Callable[_P, Union[Deferred[_T], Coroutine[Deferred[Any], Any, _T], _T]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> "Deferred[_T]":
"""
Invoke a function that may or may not return a L{Deferred} or coroutine.
Call the given function with the given arguments. Then:
- If the returned object is a L{Deferred}, return it.
- If the returned object is a L{Failure}, wrap it with L{fail} and
return it.
- If the returned object is a L{types.CoroutineType}, wrap it with
L{Deferred.fromCoroutine} and return it.
- Otherwise, wrap it in L{succeed} and return it.
- If an exception is raised, convert it to a L{Failure}, wrap it in
L{fail}, and then return it.
@param f: The callable to invoke
@param args: The arguments to pass to C{f}
@param kwargs: The keyword arguments to pass to C{f}
@return: The result of the function call, wrapped in a L{Deferred} if
necessary.
"""
try:
result = f(*args, **kwargs)
except BaseException:
return fail(Failure(captureVars=Deferred.debug))
if type(result) in _DEFERRED_SUBCLASSES:
return result # type: ignore[return-value]
elif isinstance(result, Failure):
return fail(result)
elif type(result) is CoroutineType:
# A note on how we identify this case ...
#
# inspect.iscoroutinefunction(f) should be the simplest and easiest
# way to determine if we want to apply coroutine handling. However,
# the value may be returned by a regular function that calls a
# coroutine function and returns its result. It would be confusing if
# cases like this led to different handling of the coroutine (even
# though it is a mistake to have a regular function call a coroutine
# function to return its result - doing so immediately destroys a
# large part of the value of coroutine functions: that they can only
# have a coroutine result).
#
# There are many ways we could inspect ``result`` to determine if it
# is a "coroutine" but most of these are mistakes. The goal is only
# to determine whether the value came from ``async def`` or not
# because these are the only values we're trying to handle with this
# case. Such values always have exactly one type: CoroutineType.
return Deferred.fromCoroutine(result)
else:
returned: _T = result # type: ignore
return succeed(returned)
@deprecated(
Version("Twisted", 17, 1, 0),
replacement="twisted.internet.defer.Deferred.addTimeout",
)
def timeout(deferred: "Deferred[object]") -> None:
deferred.errback(Failure(TimeoutError("Callback timed out")))
def passthru(arg: _T) -> _T:
return arg
def _failthru(arg: Failure) -> Failure:
return arg
def setDebugging(on: bool) -> None:
"""
Enable or disable L{Deferred} debugging.
When debugging is on, the call stacks from creation and invocation are
recorded, and added to any L{AlreadyCalledError}s we raise.
"""
Deferred.debug = bool(on)
def getDebugging() -> bool:
"""
Determine whether L{Deferred} debugging is enabled.
"""
return Deferred.debug
def _cancelledToTimedOutError(value: _T, timeout: float) -> _T:
"""
A default translation function that translates L{Failure}s that are
L{CancelledError}s to L{TimeoutError}s.
@param value: Anything
@param timeout: The timeout
@raise TimeoutError: If C{value} is a L{Failure} that is a L{CancelledError}.
@raise Exception: If C{value} is a L{Failure} that is not a L{CancelledError},
it is re-raised.
@since: 16.5
"""
if isinstance(value, Failure):
value.trap(CancelledError)
raise TimeoutError(timeout, "Deferred")
return value
class _Sentinel(Enum):
"""
@cvar _NO_RESULT:
The result used to represent the fact that there is no result.
B{Never ever ever use this as an actual result for a Deferred}.
You have been warned.
@cvar _CONTINUE:
A marker left in L{Deferred.callback}s to indicate a Deferred chain.
Always accompanied by a Deferred instance in the args tuple pointing at
the Deferred which is chained to the Deferred which has this marker.
"""
_NO_RESULT = object()
_CONTINUE = object()
# Cache these values for use without the extra lookup in deferred hot code paths
_NO_RESULT = _Sentinel._NO_RESULT
_CONTINUE = _Sentinel._CONTINUE
# type note: this should be Callable[[object, ...], object] but mypy doesn't allow.
# Callable[[object], object] is next best, but disallows valid callback signatures
DeferredCallback = Callable[..., object]
# type note: this should be Callable[[Failure, ...], object] but mypy doesn't allow.
# Callable[[Failure], object] is next best, but disallows valid callback signatures
DeferredErrback = Callable[..., object]
_CallbackOrderedArguments = Tuple[object, ...]
_CallbackKeywordArguments = Mapping[str, object]
_CallbackChain = Tuple[
Tuple[
Union[DeferredCallback, Literal[_Sentinel._CONTINUE]],
_CallbackOrderedArguments,
_CallbackKeywordArguments,
],
Tuple[
Union[DeferredErrback, DeferredCallback, Literal[_Sentinel._CONTINUE]],
_CallbackOrderedArguments,
_CallbackKeywordArguments,
],
]
_NONE_KWARGS: _CallbackKeywordArguments = MappingProxyType({})
_SelfResultT = TypeVar("_SelfResultT")
_NextResultT = TypeVar("_NextResultT")
class DebugInfo:
"""
Deferred debug helper.
"""
failResult: Optional[Failure] = None
creator: Optional[List[str]] = None
invoker: Optional[List[str]] = None
def _getDebugTracebacks(self) -> str:
info = ""
if self.creator is not None:
info += " C: Deferred was created:\n C:"
info += "".join(self.creator).rstrip().replace("\n", "\n C:")
info += "\n"
if self.invoker is not None:
info += " I: First Invoker was:\n I:"
info += "".join(self.invoker).rstrip().replace("\n", "\n I:")
info += "\n"
return info
def __del__(self) -> None:
"""
Print tracebacks and die.
If the *last* (and I do mean *last*) callback leaves me in an error
state, print a traceback (if said errback is a L{Failure}).
"""
if self.failResult is not None:
# Note: this is two separate messages for compatibility with
# earlier tests; arguably it should be a single error message.
log.critical("Unhandled error in Deferred:", isError=True)
debugInfo = self._getDebugTracebacks()
if debugInfo:
format = "(debug: {debugInfo})"
else:
format = ""
log.failure(format, self.failResult, debugInfo=debugInfo)
class Deferred(Awaitable[_SelfResultT]):
"""
This is a callback which will be put off until later.
Why do we want this? Well, in cases where a function in a threaded
program would block until it gets a result, for Twisted it should
not block. Instead, it should return a L{Deferred}.
This can be implemented for protocols that run over the network by
writing an asynchronous protocol for L{twisted.internet}. For methods
that come from outside packages that are not under our control, we use
threads (see for example L{twisted.enterprise.adbapi}).
For more information about Deferreds, see doc/core/howto/defer.html or
U{http://twistedmatrix.com/documents/current/core/howto/defer.html}
When creating a Deferred, you may provide a canceller function, which
will be called by d.cancel() to let you do any clean-up necessary if the
user decides not to wait for the deferred to complete.
@ivar called: A flag which is C{False} until either C{callback} or
C{errback} is called and afterwards always C{True}.
@ivar paused: A counter of how many unmatched C{pause} calls have been made
on this instance.
@ivar _suppressAlreadyCalled: A flag used by the cancellation mechanism
which is C{True} if the Deferred has no canceller and has been
cancelled, C{False} otherwise. If C{True}, it can be expected that
C{callback} or C{errback} will eventually be called and the result
should be silently discarded.
@ivar _runningCallbacks: A flag which is C{True} while this instance is
executing its callback chain, used to stop recursive execution of
L{_runCallbacks}
@ivar _chainedTo: If this L{Deferred} is waiting for the result of another
L{Deferred}, this is a reference to the other Deferred. Otherwise,
L{None}.
"""
called = False
paused = 0
_debugInfo: Optional[DebugInfo] = None
_suppressAlreadyCalled = False
# Are we currently running a user-installed callback? Meant to prevent
# recursive running of callbacks when a reentrant call to add a callback is
# used.
_runningCallbacks = False
# Keep this class attribute for now, for compatibility with code that
# sets it directly.
debug = False
_chainedTo: "Optional[Deferred[Any]]" = None
def __init__(
self, canceller: Optional[Callable[["Deferred[Any]"], None]] = None
) -> None:
"""
Initialize a L{Deferred}.
@param canceller: a callable used to stop the pending operation
scheduled by this L{Deferred} when L{Deferred.cancel} is invoked.
The canceller will be passed the deferred whose cancellation is
requested (i.e., C{self}).
If a canceller is not given, or does not invoke its argument's
C{callback} or C{errback} method, L{Deferred.cancel} will
invoke L{Deferred.errback} with a L{CancelledError}.
Note that if a canceller is not given, C{callback} or
C{errback} may still be invoked exactly once, even though
defer.py will have already invoked C{errback}, as described
above. This allows clients of code which returns a L{Deferred}
to cancel it without requiring the L{Deferred} instantiator to
provide any specific implementation support for cancellation.
New in 10.1.
@type canceller: a 1-argument callable which takes a L{Deferred}. The
return result is ignored.
"""
self.callbacks: List[_CallbackChain] = []
self._canceller = canceller
if self.debug:
self._debugInfo = DebugInfo()
self._debugInfo.creator = traceback.format_stack()[:-1]
def addCallbacks(
self,
callback: Union[
Callable[..., _NextResultT],
Callable[..., Deferred[_NextResultT]],
Callable[..., Failure],
Callable[
...,
Union[_NextResultT, Deferred[_NextResultT], Failure],
],
],
errback: Union[
Callable[..., _NextResultT],
Callable[..., Deferred[_NextResultT]],
Callable[..., Failure],
Callable[
...,
Union[_NextResultT, Deferred[_NextResultT], Failure],
],
None,
] = None,
callbackArgs: Tuple[Any, ...] = (),
callbackKeywords: Mapping[str, Any] = _NONE_KWARGS,
errbackArgs: _CallbackOrderedArguments = (),
errbackKeywords: _CallbackKeywordArguments = _NONE_KWARGS,
) -> "Deferred[_NextResultT]":
"""
Add a pair of callbacks (success and error) to this L{Deferred}.
These will be executed when the 'master' callback is run.
@note: The signature of this function was designed many years before
PEP 612; ParamSpec provides no mechanism to annotate parameters
like C{callbackArgs}; this is therefore inherently less type-safe
than calling C{addCallback} and C{addErrback} separately.
@return: C{self}.
"""
if errback is None:
errback = _failthru
# Default value used to be None and callers may be using None
if callbackArgs is None:
callbackArgs = () # type: ignore[unreachable]
if callbackKeywords is None:
callbackKeywords = {} # type: ignore[unreachable]
if errbackArgs is None:
errbackArgs = () # type: ignore[unreachable]
if errbackKeywords is None:
errbackKeywords = {} # type: ignore[unreachable]
# Note that this logic is duplicated in addCallbac/addErrback/addBoth
# for performance reasons.
self.callbacks.append(
(
(callback, callbackArgs, callbackKeywords),
(errback, errbackArgs, errbackKeywords),
)
)
if self.called:
self._runCallbacks()
# type note: The Deferred's type has changed here, but *idiomatically*
# the caller should treat the result as the new type, consistently.
return self # type:ignore[return-value]
# BEGIN way too many @overload-s for addCallback, addErrback, and addBoth:
# these must be accomplished with @overloads, rather than a big Union on
# the result type as you might expect, because the fact that
# _NextResultT has no bound makes mypy get confused and require the
# return types of functions to be combinations of Deferred and Failure
# rather than the actual return type. I'm not entirely sure what about the
# semantics of <nothing> create this overzealousness on the part of trying
# to assign a type; there *might* be a mypy bug in there somewhere.
# Possibly https://github.com/python/typing/issues/548 is implicated here
# because TypeVar for the *callable* with a variadic bound might express to
# Mypy the actual constraint that we want on its type.
@overload
def addCallback(
self,
callback: Callable[Concatenate[_SelfResultT, _P], Failure],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addCallback(
self,
callback: Callable[
Concatenate[_SelfResultT, _P],
Union[Failure, Deferred[_NextResultT]],
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addCallback(
self,
callback: Callable[Concatenate[_SelfResultT, _P], Union[Failure, _NextResultT]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addCallback(
self,
callback: Callable[Concatenate[_SelfResultT, _P], Deferred[_NextResultT]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addCallback(
self,
callback: Callable[
Concatenate[_SelfResultT, _P],
Union[Deferred[_NextResultT], _NextResultT],
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addCallback(
self,
callback: Callable[Concatenate[_SelfResultT, _P], _NextResultT],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
def addCallback(self, callback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
"""
Convenience method for adding just a callback.
See L{addCallbacks}.
"""
# This could be implemented as a call to addCallbacks, but doing it
# directly is faster.
self.callbacks.append(((callback, args, kwargs), (_failthru, (), {})))
if self.called:
self._runCallbacks()
return self
@overload
def addErrback(
self,
errback: Callable[Concatenate[Failure, _P], Deferred[_NextResultT]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
...
@overload
def addErrback(
self,
errback: Callable[Concatenate[Failure, _P], Failure],
*args: _P.args,
**kwargs: _P.kwargs,
) -> "Deferred[Union[_SelfResultT]]":
...
@overload
def addErrback(
self,
errback: Callable[Concatenate[Failure, _P], _NextResultT],
*args: _P.args,
**kwargs: _P.kwargs,
) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
...
def addErrback(self, errback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
"""
Convenience method for adding just an errback.
See L{addCallbacks}.
"""
# This could be implemented as a call to addCallbacks, but doing it
# directly is faster.
self.callbacks.append(((passthru, (), {}), (errback, args, kwargs)))
if self.called:
self._runCallbacks()
return self
@overload
def addBoth(
self,
callback: Callable[Concatenate[Union[_SelfResultT, Failure], _P], Failure],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[
Concatenate[Union[_SelfResultT, Failure], _P],
Union[Failure, Deferred[_NextResultT]],
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[
Concatenate[Union[_SelfResultT, Failure], _P], Union[Failure, _NextResultT]
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[
Concatenate[Union[_SelfResultT, Failure], _P], Deferred[_NextResultT]
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[
Concatenate[Union[_SelfResultT, Failure], _P],
Union[Deferred[_NextResultT], _NextResultT],
],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[Concatenate[Union[_SelfResultT, Failure], _P], _NextResultT],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_NextResultT]:
...
@overload
def addBoth(
self,
callback: Callable[Concatenate[_T, _P], _T],
*args: _P.args,
**kwargs: _P.kwargs,
) -> Deferred[_SelfResultT]:
...
def addBoth(self, callback: Any, *args: Any, **kwargs: Any) -> "Deferred[Any]":
"""
Convenience method for adding a single callable as both a callback
and an errback.
See L{addCallbacks}.
"""
# This could be implemented as a call to addCallbacks, but doing it
# directly is faster.
call = (callback, args, kwargs)
self.callbacks.append((call, call))
if self.called:
self._runCallbacks()
return self
# END way too many overloads
def addTimeout(
self,
timeout: float,
clock: IReactorTime,
onTimeoutCancel: Optional[
Callable[
[Union[_SelfResultT, Failure], float],
Union[_NextResultT, Failure],
]
] = None,
) -> "Deferred[Union[_SelfResultT, _NextResultT]]":
"""
Time out this L{Deferred} by scheduling it to be cancelled after
C{timeout} seconds.
The timeout encompasses all the callbacks and errbacks added to this
L{defer.Deferred} before the call to L{addTimeout}, and none added
after the call.
If this L{Deferred} gets timed out, it errbacks with a L{TimeoutError},
unless a cancelable function was passed to its initialization or unless
a different C{onTimeoutCancel} callable is provided.
@param timeout: number of seconds to wait before timing out this
L{Deferred}
@param clock: The object which will be used to schedule the timeout.
@param onTimeoutCancel: A callable which is called immediately after
this L{Deferred} times out, and not if this L{Deferred} is
otherwise cancelled before the timeout. It takes an arbitrary
value, which is the value of this L{Deferred} at that exact point
in time (probably a L{CancelledError} L{Failure}), and the
C{timeout}. The default callable (if C{None} is provided) will
translate a L{CancelledError} L{Failure} into a L{TimeoutError}.
@return: C{self}.
@since: 16.5
"""
timedOut = [False]
def timeItOut() -> None:
timedOut[0] = True
self.cancel()
delayedCall = clock.callLater(timeout, timeItOut)
def convertCancelled(
result: Union[_SelfResultT, Failure],
) -> Union[_SelfResultT, _NextResultT, Failure]:
# if C{deferred} was timed out, call the translation function,
# if provided, otherwise just use L{cancelledToTimedOutError}
if timedOut[0]:
toCall = onTimeoutCancel or _cancelledToTimedOutError
return toCall(result, timeout)
return result
def cancelTimeout(result: _T) -> _T:
# stop the pending call to cancel the deferred if it's been fired
if delayedCall.active():
delayedCall.cancel()
return result
# Note: Mypy cannot infer this type, apparently thanks to the ambiguity
# of _SelfResultT / _NextResultT both being unbound. Explicitly
# annotating it seems to do the trick though.
converted: Deferred[Union[_SelfResultT, _NextResultT]] = self.addBoth(
convertCancelled
)
return converted.addBoth(cancelTimeout)
def chainDeferred(self, d: "Deferred[_SelfResultT]") -> "Deferred[None]":
"""
Chain another L{Deferred} to this L{Deferred}.
This method adds callbacks to this L{Deferred} to call C{d}'s callback
or errback, as appropriate. It is merely a shorthand way of performing
the following::
d1.addCallbacks(d2.callback, d2.errback)
When you chain a deferred C{d2} to another deferred C{d1} with
C{d1.chainDeferred(d2)}, you are making C{d2} participate in the
callback chain of C{d1}.
Thus any event that fires C{d1} will also fire C{d2}.
However, the converse is B{not} true; if C{d2} is fired, C{d1} will not
be affected.
Note that unlike the case where chaining is caused by a L{Deferred}
being returned from a callback, it is possible to cause the call
stack size limit to be exceeded by chaining many L{Deferred}s
together with C{chainDeferred}.
@return: C{self}.
"""
d._chainedTo = self
return self.addCallbacks(d.callback, d.errback)
def callback(self, result: Union[_SelfResultT, Failure]) -> None:
"""
Run all success callbacks that have been added to this L{Deferred}.
Each callback will have its result passed as the first argument to
the next; this way, the callbacks act as a 'processing chain'. If
the success-callback returns a L{Failure} or raises an L{Exception},
processing will continue on the *error* callback chain. If a
callback (or errback) returns another L{Deferred}, this L{Deferred}
will be chained to it (and further callbacks will not run until that
L{Deferred} has a result).
An instance of L{Deferred} may only have either L{callback} or
L{errback} called on it, and only once.
@param result: The object which will be passed to the first callback
added to this L{Deferred} (via L{addCallback}), unless C{result} is
a L{Failure}, in which case the behavior is the same as calling
C{errback(result)}.
@raise AlreadyCalledError: If L{callback} or L{errback} has already been
called on this L{Deferred}.
"""
self._startRunCallbacks(result)
def errback(self, fail: Optional[Union[Failure, BaseException]] = None) -> None:
"""
Run all error callbacks that have been added to this L{Deferred}.
Each callback will have its result passed as the first
argument to the next; this way, the callbacks act as a
'processing chain'. Also, if the error-callback returns a non-Failure
or doesn't raise an L{Exception}, processing will continue on the
*success*-callback chain.
If the argument that's passed to me is not a L{Failure} instance,
it will be embedded in one. If no argument is passed, a
L{Failure} instance will be created based on the current
traceback stack.
Passing a string as `fail' is deprecated, and will be punished with
a warning message.
An instance of L{Deferred} may only have either L{callback} or
L{errback} called on it, and only once.
@param fail: The L{Failure} object which will be passed to the first
errback added to this L{Deferred} (via L{addErrback}).
Alternatively, a L{Exception} instance from which a L{Failure} will
be constructed (with no traceback) or L{None} to create a L{Failure}
instance from the current exception state (with a traceback).
@raise AlreadyCalledError: If L{callback} or L{errback} has already been
called on this L{Deferred}.
@raise NoCurrentExceptionError: If C{fail} is L{None} but there is
no current exception state.
"""
if fail is None:
fail = Failure(captureVars=self.debug)
elif not isinstance(fail, Failure):
fail = Failure(fail)
self._startRunCallbacks(fail)
def pause(self) -> None:
"""
Stop processing on a L{Deferred} until L{unpause}() is called.
"""
self.paused += 1
def unpause(self) -> None:
"""
Process all callbacks made since L{pause}() was called.
"""
self.paused -= 1
if self.paused:
return
if self.called:
self._runCallbacks()
def cancel(self) -> None:
"""
Cancel this L{Deferred}.
If the L{Deferred} has not yet had its C{errback} or C{callback} method
invoked, call the canceller function provided to the constructor. If
that function does not invoke C{callback} or C{errback}, or if no
canceller function was provided, errback with L{CancelledError}.
If this L{Deferred} is waiting on another L{Deferred}, forward the
cancellation to the other L{Deferred}.
"""
if not self.called:
canceller = self._canceller
if canceller:
canceller(self)
else:
# Arrange to eat the callback that will eventually be fired
# since there was no real canceller.
self._suppressAlreadyCalled = True
if not self.called:
# There was no canceller, or the canceller didn't call
# callback or errback.
self.errback(Failure(CancelledError()))
elif isinstance(self.result, Deferred):
# Waiting for another deferred -- cancel it instead.
self.result.cancel()
def _startRunCallbacks(self, result: object) -> None:
if self.called:
if self._suppressAlreadyCalled:
self._suppressAlreadyCalled = False
return
if self.debug:
if self._debugInfo is None:
self._debugInfo = DebugInfo()
extra = "\n" + self._debugInfo._getDebugTracebacks()
raise AlreadyCalledError(extra)
raise AlreadyCalledError
if self.debug:
if self._debugInfo is None:
self._debugInfo = DebugInfo()
self._debugInfo.invoker = traceback.format_stack()[:-2]
self.called = True
# Clear the canceller to avoid any circular references. This is safe to
# do as the canceller does not get called after the deferred has fired
self._canceller = None
self.result = result
self._runCallbacks()
def _continuation(self) -> _CallbackChain:
"""
Build a tuple of callback and errback with L{_Sentinel._CONTINUE}.
"""
triple = (_CONTINUE, (self,), _NONE_KWARGS)