-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathfutures.nim
More file actions
288 lines (238 loc) · 9.84 KB
/
Copy pathfutures.nim
File metadata and controls
288 lines (238 loc) · 9.84 KB
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
#
# Chronos
#
# (c) Copyright 2015 Dominik Picheta
# (c) Copyright 2018-2025 Status Research & Development GmbH
#
# Licensed under either of
# Apache License, version 2.0, (LICENSE-APACHEv2)
# MIT license (LICENSE-MIT)
{.push raises: [].}
import ./[config, srcloc]
export srcloc
when chronosStackTrace:
type StackTrace = string
type
LocationKind* {.pure.} = enum
Create
Finish
# TODO forbid nested poll
# TODO https://github.com/nim-lang/Nim/issues/25976
CallbackFunc* = proc (arg: pointer) {.gcsafe, raises: [].}
CallbackFlag* {.pure.} = enum
Continuation
## When set and attached to a future with `FutureFlag.SyncContinuations`,
## the callback is scheduled to run before processing other already
## queued events such as timer handlers and I/O.
##
## Only works when the `chronosSyncContinuations` config is enabled.
# Internal type, not part of API
InternalAsyncCallback* = object
function*: CallbackFunc
udata*: pointer
FutureState* {.pure.} = enum
Pending, Completed, Cancelled, Failed
FutureFlag* {.pure.} = enum
OwnCancelSchedule
## When OwnCancelSchedule is set, the owner of the future is responsible
## for implementing cancellation in one of 3 ways:
##
## * ensure that cancellation requests never reach the future by means of
## not exposing it to user code, `await` and `tryCancel`
## * set `cancelCallback` to `nil` to stop cancellation propagation - this
## is appropriate when it is expected that the future will be completed
## in a regular way "soon"
## * set `cancelCallback` to a handler that implements cancellation in an
## operation-specific way
##
## If `cancelCallback` is not set and the future gets cancelled, a
## `Defect` will be raised.
SyncContinuations
## When set, `CallbackFlag.Continuation` callbacks are scheduled
## to run before processing other already queued events such as
## timer handlers and I/O.
##
## Only works when the `chronosSyncContinuations` config is enabled.
FutureFlags* = set[FutureFlag]
InternalFutureBase* = object of RootObj
# Internal untyped future representation - the fields are not part of the
# public API and neither is `InternalFutureBase`, ie the inheritance
# structure may change in the future (haha)
internalLocation*: array[LocationKind, ptr SrcLoc]
internalContinuation*, internalCallback*: InternalAsyncCallback
## The vast majority of futures track a single callback only (the one
## installed by `await`) - to avoid allocating a seq (which involves
## making a separate allocation with space for several callbacks), we keep
## a spot in each future for that first one - the seq below will stay
## empty until a second callback is added
internalContinuations*, internalCallbacks*: seq[InternalAsyncCallback]
internalCancelcb*: CallbackFunc
internalChild*: FutureBase
internalState*: FutureState
internalFlags*: FutureFlags
internalError*: ref CatchableError ## Stored exception
internalClosure*: iterator(f: FutureBase): FutureBase {.raises: [], gcsafe.}
when chronosFutureId:
internalId*: uint
when chronosStackTrace:
internalErrorStackTrace*: StackTrace
internalStackTrace*: StackTrace ## For debugging purposes only.
when chronosFutureTracking:
internalNext*: FutureBase
internalPrev*: FutureBase
FutureBase* = ref object of InternalFutureBase
## Untyped Future
Future*[T] = ref object of FutureBase ## Typed future.
when T isnot void:
internalValue*: T ## Stored value
FutureDefect* = object of Defect
cause*: FutureBase
FutureError* = object of CatchableError
future*: FutureBase
CancelledError* = object of FutureError
## Exception raised when accessing the value of a cancelled future
func raiseFutureDefect(msg: static string, fut: FutureBase) {.
noinline, noreturn.} =
raise (ref FutureDefect)(msg: msg, cause: fut)
when chronosFutureId:
var currentID* {.threadvar.}: uint
template id*(fut: FutureBase): uint = fut.internalId
else:
template id*(fut: FutureBase): uint =
cast[uint](addr fut[])
when chronosFutureTracking:
type
FutureList* = object
head*: FutureBase
tail*: FutureBase
count*: uint
var futureList* {.threadvar.}: FutureList
# Internal utilities - these are not part of the stable API
proc internalInitFutureBase*(fut: FutureBase, loc: ptr SrcLoc,
state: FutureState, flags: FutureFlags) =
fut.internalState = state
fut.internalLocation[LocationKind.Create] = loc
fut.internalFlags = flags
if FutureFlag.OwnCancelSchedule in flags:
# Owners must replace `cancelCallback` with `nil` if they want to ignore
# cancellations
fut.internalCancelcb = proc(_: pointer) =
raiseAssert "Cancellation request for non-cancellable future"
if state != FutureState.Pending:
fut.internalLocation[LocationKind.Finish] = loc
when chronosFutureId:
currentID.inc()
fut.internalId = currentID
when chronosStackTrace:
fut.internalStackTrace = getStackTrace()
when chronosFutureTracking:
if state == FutureState.Pending:
fut.internalNext = nil
fut.internalPrev = futureList.tail
if not(isNil(futureList.tail)):
futureList.tail.internalNext = fut
futureList.tail = fut
if isNil(futureList.head):
futureList.head = fut
futureList.count.inc()
# Public API
template init*[T](F: type Future[T], fromProc: static[string] = ""): Future[T] =
## Creates a new pending future.
##
## Specifying ``fromProc``, which is a string specifying the name of the proc
## that this future belongs to, is a good habit as it helps with debugging.
let res = Future[T]()
internalInitFutureBase(res, getSrcLocation(fromProc), FutureState.Pending, {})
res
template init*[T](F: type Future[T], fromProc: static[string] = "",
flags: static[FutureFlags]): Future[T] =
## Creates a new pending future.
##
## Specifying ``fromProc``, which is a string specifying the name of the proc
## that this future belongs to, is a good habit as it helps with debugging.
let res = Future[T]()
internalInitFutureBase(res, getSrcLocation(fromProc), FutureState.Pending,
flags)
res
template completed*(
F: type Future, fromProc: static[string] = ""): Future[void] =
## Create a new completed future
let res = Future[void]()
internalInitFutureBase(res, getSrcLocation(fromProc), FutureState.Completed,
{})
res
template completed*[T: not void](
F: type Future, valueParam: T, fromProc: static[string] = ""): Future[T] =
## Create a new completed future
let res = Future[T](internalValue: valueParam)
internalInitFutureBase(res, getSrcLocation(fromProc), FutureState.Completed,
{})
res
template failed*[T](
F: type Future[T], errorParam: ref CatchableError,
fromProc: static[string] = ""): Future[T] =
## Create a new failed future
let res = Future[T](internalError: errorParam)
internalInitFutureBase(res, getSrcLocation(fromProc), FutureState.Failed, {})
when chronosStackTrace:
res.internalErrorStackTrace =
if getStackTrace(res.error) == "":
getStackTrace()
else:
getStackTrace(res.error)
res
func state*(future: FutureBase): FutureState =
future.internalState
func flags*(future: FutureBase): FutureFlags =
future.internalFlags
func finished*(future: FutureBase): bool {.inline.} =
## Determines whether ``future`` has finished, i.e. ``future`` state changed
## from state ``Pending`` to one of the states (``Finished``, ``Cancelled``,
## ``Failed``).
future.state != FutureState.Pending
func cancelled*(future: FutureBase): bool {.inline.} =
## Determines whether ``future`` has cancelled.
future.state == FutureState.Cancelled
func failed*(future: FutureBase): bool {.inline.} =
## Determines whether ``future`` finished with an error.
future.state == FutureState.Failed
func completed*(future: FutureBase): bool {.inline.} =
## Determines whether ``future`` finished with a value.
future.state == FutureState.Completed
func location*(future: FutureBase): array[LocationKind, ptr SrcLoc] =
future.internalLocation
func value*[T: not void](future: Future[T]): lent T =
## Return the value in a completed future - raises Defect when
## `fut.completed()` is `false`.
##
## See `read` for a version that raises a catchable error when future
## has not completed.
when chronosStrictFutureAccess:
if not future.completed():
raiseFutureDefect("Future not completed while accessing value", future)
future.internalValue
func value*(future: Future[void]) =
## Return the value in a completed future - raises Defect when
## `fut.completed()` is `false`.
##
## See `read` for a version that raises a catchable error when future
## has not completed.
when chronosStrictFutureAccess:
if not future.completed():
raiseFutureDefect("Future not completed while accessing value", future)
func error*(future: FutureBase): ref CatchableError =
## Return the error of `future`, or `nil` if future did not fail.
##
## See `readError` for a version that raises a catchable error when the
## future has not failed.
when chronosStrictFutureAccess:
if not future.failed() and not future.cancelled():
raiseFutureDefect(
"Future not failed/cancelled while accessing error", future)
future.internalError
when chronosFutureTracking:
func next*(fut: FutureBase): FutureBase = fut.internalNext
func prev*(fut: FutureBase): FutureBase = fut.internalPrev
when chronosStackTrace:
func errorStackTrace*(fut: FutureBase): StackTrace = fut.internalErrorStackTrace
func stackTrace*(fut: FutureBase): StackTrace = fut.internalStackTrace