-
Notifications
You must be signed in to change notification settings - Fork 506
/
IOFiber.scala
1613 lines (1363 loc) · 51.2 KB
/
IOFiber.scala
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
/*
* Copyright 2020-2024 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cats.effect
import cats.arrow.FunctionK
import cats.effect.tracing._
import cats.effect.unsafe._
import scala.annotation.{switch, tailrec}
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.control.NonFatal
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.atomic.AtomicBoolean
import Platform.static
/*
* Rationale on memory barrier exploitation in this class...
*
* This class extends `java.util.concurrent.atomic.AtomicBoolean`
* (through `IOFiberPlatform`) in order to forego the allocation
* of a separate `AtomicBoolean` object. All credit goes to
* Viktor Klang.
* https://viktorklang.com/blog/Futures-in-Scala-2.12-part-8.html
*
* The runloop is held by a single thread at any moment in
* time. This is ensured by the `suspended` AtomicBoolean,
* which is set to `true` when evaluation of an `Async` causes
* us to semantically block. Releasing the runloop can thus
* only be done by passing through a write barrier (on `suspended`),
* and relocating that runloop can itself only be achieved by
* passing through that same read/write barrier (a CAS on
* `suspended`).
*
* Separate from this, the runloop may be *relocated* to a different
* thread – for example, when evaluating Cede. When this happens,
* we pass through a read/write barrier within the Executor as
* we enqueue the action to restart the runloop, and then again
* when that action is dequeued on the new thread. This ensures
* that everything is appropriately published.
*
* By this argument, the `conts` stack is non-volatile and can be
* safely implemented with an array. It is only accessed by one
* thread at a time (so there are no atomicity concerns), and it
* only becomes relevant to another thread after passing through
* either an executor or the `suspended` gate, both of which
* would ensure safe publication of writes. `ctxs`, `currentCtx`,
* `masks`, `objectState`, and `booleanState` are all subject to
* similar arguments. `cancel` and `join` are only made visible
* by the Executor read/write barriers, but their writes are
* merely a fast-path and are not necessary for correctness.
*/
private final class IOFiber[A](
initState: IOLocalState,
cb: OutcomeIO[A] => Unit,
startIO: IO[A],
startEC: ExecutionContext,
rt: IORuntime
) extends IOFiberPlatform[A]
with FiberIO[A]
with Runnable {
/* true when fiber blocking (ensures that we only unblock *once*) */
suspended: AtomicBoolean =>
import IOFiber._
import IO.{println => _, _}
import IOFiberConstants._
import TracingConstants._
private[this] var localState: IOLocalState = initState
private[this] var currentCtx: ExecutionContext = startEC
private[this] val objectState: ArrayStack[AnyRef] = ArrayStack()
private[this] val finalizers: ArrayStack[IO[Unit]] = ArrayStack()
private[this] val callbacks: CallbackStack[OutcomeIO[A]] = CallbackStack.of(cb)
private[this] var resumeTag: Byte = ExecR
private[this] var resumeIO: IO[Any] = startIO
private[this] val runtime: IORuntime = rt
private[this] val tracingEvents: RingBuffer =
if (TracingConstants.isStackTracing) RingBuffer.empty(runtime.traceBufferLogSize) else null
/*
* Ideally these would be on the stack, but they can't because we sometimes need to
* relocate our runloop to another fiber.
*/
private[this] var conts: ByteStack.T = _
private[this] var canceled: Boolean = false
private[this] var masks: Int = 0
private[this] var finalizing: Boolean = false
@volatile
private[this] var outcome: OutcomeIO[A] = _
override def run(): Unit = {
// insert a read barrier after every async boundary
readBarrier()
(resumeTag: @switch) match {
case 0 => execR()
case 1 => asyncContinueSuccessfulR()
case 2 => asyncContinueFailedR()
case 3 => asyncContinueCanceledR()
case 4 => asyncContinueCanceledWithFinalizerR()
case 5 => blockingR()
case 6 => cedeR()
case 7 => autoCedeR()
case 8 => () // DoneR
}
}
/* backing fields for `cancel` and `join` */
/* this is swapped for an `IO.unit` when we complete */
private[this] var _cancel: IO[Unit] = IO uncancelable { _ =>
canceled = true
// println(s"${name}: attempting cancelation")
/* check to see if the target fiber is suspended */
if (resume()) {
/* ...it was! was it masked? */
if (isUnmasked()) {
/* ...nope! take over the target fiber's runloop and run the finalizers */
// println(s"<$name> running cancelation (finalizers.length = ${finalizers.unsafeIndex()})")
/* if we have async finalizers, runLoop may return early */
IO.async_[Unit] { fin =>
// println(s"${name}: canceller started at ${Thread.currentThread().getName} + ${suspended.get()}")
val ec = currentCtx
resumeTag = AsyncContinueCanceledWithFinalizerR
objectState.push(fin)
scheduleFiber(ec, this)
}
} else {
/*
* it was masked, so we need to wait for it to finish whatever
* it was doing and cancel itself
*/
suspend() /* allow someone else to take the runloop */
join.void
}
} else {
// println(s"${name}: had to join")
/* it's already being run somewhere; await the finalizers */
join.void
}
}
/* this is swapped for an `IO.pure(outcome)` when we complete */
private[this] var _join: IO[OutcomeIO[A]] = IO.asyncCheckAttempt { cb =>
IO {
if (outcome == null) {
val handle = callbacks.push(oc => cb(Right(oc)))
/* double-check */
if (outcome != null) {
callbacks.clearHandle(handle)
Right(outcome)
} else {
Left(Some(IO { callbacks.clearHandle(handle); () }))
}
} else {
Right(outcome)
}
}
}
def cancel: IO[Unit] = {
// The `_cancel` field is published in terms of the `suspended` atomic variable.
readBarrier()
_cancel
}
def join: IO[OutcomeIO[A]] = {
// The `_join` field is published in terms of the `suspended` atomic variable.
readBarrier()
_join
}
/* masks encoding: initMask => no masks, ++ => push, -- => pop */
@tailrec
private[this] def runLoop(
_cur0: IO[Any],
cancelationIterations: Int,
autoCedeIterations: Int): Unit = {
/*
* `cur` will be set to `EndFiber` when the runloop needs to terminate,
* either because the entire IO is done, or because this branch is done
* and execution is continuing asynchronously in a different runloop invocation.
*/
if (_cur0 eq IO.EndFiber) {
return
}
var nextCancelation = cancelationIterations - 1
var nextAutoCede = autoCedeIterations
if (nextCancelation <= 0) {
// Ensure that we see cancelation.
readBarrier()
nextCancelation = runtime.cancelationCheckThreshold
// automatic yielding threshold is always a multiple of the cancelation threshold
nextAutoCede -= nextCancelation
if (nextAutoCede <= 0) {
resumeTag = AutoCedeR
resumeIO = _cur0
val ec = currentCtx
rescheduleFiber(ec, this)
return
}
}
if (shouldFinalize()) {
val fin = prepareFiberForCancelation(null)
runLoop(fin, nextCancelation, nextAutoCede)
} else {
/* Null IO, blow up but keep the failure within IO */
val cur0: IO[Any] = if (_cur0 == null) {
IO.Error(new NullPointerException())
} else {
_cur0
}
// System.out.println(s"looping on $cur0")
/*
* The cases have to use continuous constants to generate a `tableswitch`.
* Do not name or reorder them.
*/
(cur0.tag: @switch) match {
case 0 =>
val cur = cur0.asInstanceOf[Pure[Any]]
runLoop(succeeded(cur.value, 0), nextCancelation, nextAutoCede)
case 1 =>
val cur = cur0.asInstanceOf[Error]
val ex = cur.t
if (!NonFatal(ex))
onFatalFailure(ex)
runLoop(failed(ex, 0), nextCancelation, nextAutoCede)
case 2 =>
val cur = cur0.asInstanceOf[Delay[Any]]
if (isStackTracing) {
pushTracingEvent(cur.event)
}
var error: Throwable = null
val r =
try cur.thunk()
catch {
case t if NonFatal(t) =>
error = t
case t: Throwable =>
onFatalFailure(t)
}
val next =
if (error == null) succeeded(r, 0)
else failed(error, 0)
runLoop(next, nextCancelation, nextAutoCede)
/* RealTime */
case 3 =>
runLoop(
succeeded(runtime.scheduler.nowMicros().micros, 0),
nextCancelation,
nextAutoCede)
/* Monotonic */
case 4 =>
runLoop(
succeeded(runtime.scheduler.monotonicNanos().nanos, 0),
nextCancelation,
nextAutoCede)
/* ReadEC */
case 5 =>
runLoop(succeeded(currentCtx, 0), nextCancelation, nextAutoCede)
case 6 =>
val cur = cur0.asInstanceOf[Map[Any, Any]]
if (isStackTracing) {
pushTracingEvent(cur.event)
}
val ioe = cur.ioe
val f = cur.f
def next(v: Any): IO[Any] = {
var error: Throwable = null
val result =
try f(v)
catch {
case t if NonFatal(t) =>
error = t
case t: Throwable =>
onFatalFailure(t)
}
if (error == null) succeeded(result, 0) else failed(error, 0)
}
(ioe.tag: @switch) match {
case 0 =>
val pure = ioe.asInstanceOf[Pure[Any]]
runLoop(next(pure.value), nextCancelation - 1, nextAutoCede)
case 1 =>
val error = ioe.asInstanceOf[Error]
val ex = error.t
if (!NonFatal(ex))
onFatalFailure(ex)
runLoop(failed(ex, 0), nextCancelation - 1, nextAutoCede)
case 2 =>
val delay = ioe.asInstanceOf[Delay[Any]]
if (isStackTracing) {
pushTracingEvent(delay.event)
}
// this code is inlined in order to avoid two `try` blocks
var error: Throwable = null
val result =
try f(delay.thunk())
catch {
case t if NonFatal(t) =>
error = t
case t: Throwable =>
onFatalFailure(t)
}
val nextIO = if (error == null) succeeded(result, 0) else failed(error, 0)
runLoop(nextIO, nextCancelation - 1, nextAutoCede)
case 3 =>
val realTime = runtime.scheduler.nowMicros().micros
runLoop(next(realTime), nextCancelation - 1, nextAutoCede)
case 4 =>
val monotonic = runtime.scheduler.monotonicNanos().nanos
runLoop(next(monotonic), nextCancelation - 1, nextAutoCede)
case 5 =>
val ec = currentCtx
runLoop(next(ec), nextCancelation - 1, nextAutoCede)
case _ =>
objectState.push(f)
conts = ByteStack.push(conts, MapK)
runLoop(ioe, nextCancelation, nextAutoCede)
}
case 7 =>
val cur = cur0.asInstanceOf[FlatMap[Any, Any]]
if (isStackTracing) {
pushTracingEvent(cur.event)
}
val ioe = cur.ioe
val f = cur.f
def next(v: Any): IO[Any] =
try f(v)
catch {
case t if NonFatal(t) =>
failed(t, 0)
case t: Throwable =>
onFatalFailure(t)
}
(ioe.tag: @switch) match {
case 0 =>
val pure = ioe.asInstanceOf[Pure[Any]]
runLoop(next(pure.value), nextCancelation - 1, nextAutoCede)
case 1 =>
val error = ioe.asInstanceOf[Error]
val ex = error.t
if (!NonFatal(ex))
onFatalFailure(ex)
runLoop(failed(ex, 0), nextCancelation - 1, nextAutoCede)
case 2 =>
val delay = ioe.asInstanceOf[Delay[Any]]
if (isStackTracing) {
pushTracingEvent(delay.event)
}
// this code is inlined in order to avoid two `try` blocks
val result =
try f(delay.thunk())
catch {
case t if NonFatal(t) =>
failed(t, 0)
case t: Throwable =>
onFatalFailure(t)
}
runLoop(result, nextCancelation - 1, nextAutoCede)
case 3 =>
val realTime = runtime.scheduler.nowMicros().micros
runLoop(next(realTime), nextCancelation - 1, nextAutoCede)
case 4 =>
val monotonic = runtime.scheduler.monotonicNanos().nanos
runLoop(next(monotonic), nextCancelation - 1, nextAutoCede)
case 5 =>
val ec = currentCtx
runLoop(next(ec), nextCancelation - 1, nextAutoCede)
case _ =>
objectState.push(f)
conts = ByteStack.push(conts, FlatMapK)
runLoop(ioe, nextCancelation, nextAutoCede)
}
case 8 =>
val cur = cur0.asInstanceOf[Attempt[Any]]
val ioa = cur.ioa
(ioa.tag: @switch) match {
case 0 =>
val pure = ioa.asInstanceOf[Pure[Any]]
runLoop(succeeded(Right(pure.value), 0), nextCancelation - 1, nextAutoCede)
case 1 =>
val error = ioa.asInstanceOf[Error]
val t = error.t
if (!NonFatal(t))
onFatalFailure(t)
// We need to augment the exception here because it doesn't get
// forwarded to the `failed` path.
Tracing.augmentThrowable(runtime.enhancedExceptions, t, tracingEvents)
runLoop(succeeded(Left(t), 0), nextCancelation - 1, nextAutoCede)
case 2 =>
val delay = ioa.asInstanceOf[Delay[Any]]
if (isStackTracing) {
pushTracingEvent(delay.event)
}
// this code is inlined in order to avoid two `try` blocks
var error: Throwable = null
val result =
try delay.thunk()
catch {
case t if NonFatal(t) =>
// We need to augment the exception here because it doesn't
// get forwarded to the `failed` path.
Tracing.augmentThrowable(runtime.enhancedExceptions, t, tracingEvents)
error = t
case t: Throwable =>
onFatalFailure(t)
}
val next =
if (error == null) succeeded(Right(result), 0) else succeeded(Left(error), 0)
runLoop(next, nextCancelation - 1, nextAutoCede)
case 3 =>
val realTime = runtime.scheduler.nowMicros().micros
runLoop(succeeded(Right(realTime), 0), nextCancelation - 1, nextAutoCede)
case 4 =>
val monotonic = runtime.scheduler.monotonicNanos().nanos
runLoop(succeeded(Right(monotonic), 0), nextCancelation - 1, nextAutoCede)
case 5 =>
val ec = currentCtx
runLoop(succeeded(Right(ec), 0), nextCancelation - 1, nextAutoCede)
case _ =>
conts = ByteStack.push(conts, AttemptK)
runLoop(ioa, nextCancelation, nextAutoCede)
}
case 9 =>
val cur = cur0.asInstanceOf[HandleErrorWith[Any]]
if (isStackTracing) {
pushTracingEvent(cur.event)
}
objectState.push(cur.f)
conts = ByteStack.push(conts, HandleErrorWithK)
runLoop(cur.ioa, nextCancelation, nextAutoCede)
/* Canceled */
case 10 =>
canceled = true
if (isUnmasked()) {
/* run finalizers immediately */
val fin = prepareFiberForCancelation(null)
runLoop(fin, nextCancelation, nextAutoCede)
} else {
runLoop(succeeded((), 0), nextCancelation, nextAutoCede)
}
case 11 =>
val cur = cur0.asInstanceOf[OnCancel[Any]]
finalizers.push(EvalOn(cur.fin, currentCtx))
// println(s"pushed onto finalizers: length = ${finalizers.unsafeIndex()}")
/*
* the OnCancelK marker is used by `succeeded` to remove the
* finalizer when `ioa` completes uninterrupted.
*/
conts = ByteStack.push(conts, OnCancelK)
runLoop(cur.ioa, nextCancelation, nextAutoCede)
case 12 =>
val cur = cur0.asInstanceOf[Uncancelable[Any]]
if (isStackTracing) {
pushTracingEvent(cur.event)
}
masks += 1
val id = masks
val poll = new Poll[IO] {
def apply[B](ioa: IO[B]): IO[B] =
IO.Uncancelable.UnmaskRunLoop(ioa, id, IOFiber.this)
}
val next =
try cur.body(poll)
catch {
case t if NonFatal(t) =>
IO.raiseError(t)
case t: Throwable =>
onFatalFailure(t)
}
/*
* The uncancelableK marker is used by `succeeded` and `failed`
* to unmask once body completes.
*/
conts = ByteStack.push(conts, UncancelableK)
runLoop(next, nextCancelation, nextAutoCede)
case 13 =>
val cur = cur0.asInstanceOf[Uncancelable.UnmaskRunLoop[Any]]
val self = this
/*
* we keep track of nested uncancelable sections.
* The outer block wins.
*/
if (masks == cur.id && (self eq cur.self)) {
masks -= 1
/*
* The UnmaskK marker gets used by `succeeded` and `failed`
* to restore masking state after `cur.ioa` has finished
*/
conts = ByteStack.push(conts, UnmaskK)
}
runLoop(cur.ioa, nextCancelation, nextAutoCede)
case 14 =>
val cur = cur0.asInstanceOf[IOCont[Any, Any]]
/*
* Takes `cb` (callback) and `get` and returns an IO that
* uses them to embed async computations.
* This is a CPS'd encoding that uses higher-rank
* polymorphism to statically forbid concurrent operations
* on `get`, which are unsafe since `get` closes over the
* runloop.
*
*/
val body = cur.body
if (isStackTracing) {
pushTracingEvent(cur.event)
}
/*
*`get` and `cb` (callback) race over the runloop.
* If `cb` finishes after `get`, `get` just terminates by
* suspending, and `cb` will resume the runloop via
* `asyncContinue`.
*
* If `get` wins, it gets the result from the `state`
* `AtomicReference` and it continues, while the callback just
* terminates (`stateLoop`, when `(tag ne null) && (tag ne waiting)`)
*
* The two sides communicate with each other through
* `state` to know who should take over, and through
* `suspended` (which is manipulated via suspend and
* resume), to negotiate ownership of the runloop.
*
* In case of interruption, neither side will continue,
* and they will negotiate ownership with `cancel` to decide who
* should run the finalisers (i.e. call `asyncCancel`).
*
*/
val state = new ContState(finalizing)
val cb: Either[Throwable, Any] => Unit = { e =>
// if someone called `cb` with `null`,
// we'll pretend it's an NPE:
val result = if (e eq null) {
Left(new NullPointerException())
} else {
e
}
/*
* We *need* to own the runloop when we return, so we CAS loop
* on `suspended` (via `resume`) to break the race condition where
* `state` has been set by `get, `but `suspend()` has not yet run.
* If `state` is set then `suspend()` should be right behind it
* *unless* we have been canceled.
*
* If we were canceled, `cb`, `cancel` and `get` are in a 3-way race
* to run the finalizers.
*/
@tailrec
def loop(): Unit = {
// println(s"cb loop sees suspended ${suspended.get} on fiber $name")
/* try to take ownership of the runloop */
if (resume()) {
// `resume()` is a volatile read of `suspended` through which
// `wasFinalizing` and `handle` are published
if (finalizing == state.wasFinalizing) {
if (isStackTracing) {
state.handle.deregister()
}
val ec = currentCtx
if (!shouldFinalize()) {
/* we weren't canceled or completed, so schedule the runloop for execution */
result match {
case Left(t) =>
resumeTag = AsyncContinueFailedR
objectState.push(t)
case Right(a) =>
resumeTag = AsyncContinueSuccessfulR
objectState.push(a.asInstanceOf[AnyRef])
}
} else {
/*
* we were canceled, but since we have won the race on `suspended`
* via `resume`, `cancel` cannot run the finalisers, and we have to.
*/
resumeTag = AsyncContinueCanceledR
}
scheduleFiber(ec, this)
} else {
/*
* we were canceled while suspended, then our finalizer suspended,
* then we hit this line, so we shouldn't own the runloop at all
*/
suspend()
}
} else if (finalizing == state.wasFinalizing && !shouldFinalize() && outcome == null) {
/*
* If we aren't canceled or completed, and we're
* still in the same finalization state, loop on
* `suspended` to wait until `get` has released
* ownership of the runloop.
*/
loop()
}
/*
* If we are canceled or completed or in hte process of finalizing
* when we previously weren't, just die off and let `cancel` or `get`
* win the race to `resume` and run the finalisers.
*/
}
val waiting = state.waiting
/*
* CAS loop to update the Cont state machine:
* null - initial
* waiting - (Get) waiting
* anything else - (Cb) result
*
* If state is "initial" or "waiting", update the state,
* and then if `get` has been flatMapped somewhere already
* and is waiting for a result (i.e. it has suspended),
* acquire runloop to continue.
*
* If not, `cb` arrived first, so it just sets the result and die off.
*
* If `state` is "result", the callback has been already invoked, so no-op
* (guards from double calls).
*/
@tailrec
def stateLoop(): Unit = {
val tag = state.get()
if ((tag eq null) || (tag eq waiting)) {
if (!state.compareAndSet(tag, result)) {
stateLoop()
} else {
if (tag eq waiting) {
/*
* `get` has been sequenced and is waiting
* reacquire runloop to continue
*/
loop()
}
}
}
}
stateLoop()
}
val get: IO[Any] = IOCont.Get(state)
val next =
try {
body[IO].apply(cb, get, FunctionK.id)
} catch {
case t if NonFatal(t) =>
IO.raiseError(t)
case t: Throwable =>
onFatalFailure(t)
}
runLoop(next, nextCancelation, nextAutoCede)
case 15 =>
val cur = cur0.asInstanceOf[IOCont.Get[Any]]
val state = cur.state
/*
* If get gets canceled but the result hasn't been computed yet,
* restore the state to "initial" (null) to ensure a subsequent `Get` in
* a finalizer still works with the same logic.
*/
val fin = IO {
state.compareAndSet(state.waiting, null)
()
}
finalizers.push(fin)
conts = ByteStack.push(conts, OnCancelK)
if (state.compareAndSet(null, state.waiting)) {
/*
* `state` was "initial" (null), so `get` has arrived before the callback,
* it needs to set the state to "waiting" and suspend: `cb` will
* resume with the result once that's ready
*/
/*
* we set the finalizing check to the *suspension* point, which may
* be in a different finalizer scope than the cont itself.
* `wasFinalizing` is published by a volatile store on `suspended`.
*/
state.wasFinalizing = finalizing
if (isStackTracing) {
state.handle = monitor()
finalizers.push(IO {
state.handle.deregister()
()
})
// remove the above finalizer if the Get completes without getting cancelled
conts = ByteStack.push(conts, OnCancelK)
}
/*
* You should probably just read this as `suspended.compareAndSet(false, true)`.
* This CAS should always succeed since we own the runloop,
* but we need it in order to introduce a full memory barrier
* which ensures we will always see the most up-to-date value
* for `canceled` in `shouldFinalize`, ensuring no finalisation leaks
*/
suspended.getAndSet(true)
/*
* race condition check: we may have been canceled
* after setting the state but before we suspended
*/
if (shouldFinalize()) {
/*
* if we can re-acquire the run-loop, we can finalize,
* otherwise somebody else acquired it and will eventually finalize.
*
* In this path, `get`, the `cb` callback and `cancel`
* all race via `resume` to decide who should run the
* finalisers.
*/
if (resume()) {
if (shouldFinalize()) {
val fin = prepareFiberForCancelation(null)
runLoop(fin, nextCancelation, nextAutoCede)
} else {
suspend()
}
}
}
} else {
/*
* State was no longer "initial" (null), as the CAS above failed; so the
* callback has already been invoked and the state is "result".
* We leave the "result" state unmodified so that `get` is idempotent.
*
* Note that it's impossible for `state` to be "waiting" here:
* - `cont` doesn't allow concurrent calls to `get`, so there can't be
* another `get` in "waiting" when we execute this.
*
* - If a previous `get` happened before this code, and we are in a `flatMap`
* or `handleErrorWith`, it means the callback has completed once
* (unblocking the first `get` and letting us execute), and the state is still
* "result".
*
* - If a previous `get` has been canceled and we are being called within an
* `onCancel` of that `get`, the finalizer installed on the `Get` node by `Cont`
* has restored the state to "initial" before the execution of this method,
* which would have been caught by the previous branch unless the `cb` has
* completed and the state is "result"
*/
val result = state.get()
if (!shouldFinalize()) {
/* we weren't canceled, so resume the runloop */
val next = result match {
case Left(t) => failed(t, 0)
case Right(a) => succeeded(a, 0)
}
runLoop(next, nextCancelation, nextAutoCede)
} else if (outcome == null) {
/*
* we were canceled, but `cancel` cannot run the finalisers
* because the runloop was not suspended, so we have to run them
*/
val fin = prepareFiberForCancelation(null)
runLoop(fin, nextCancelation, nextAutoCede)
}
}
/* Cede */
case 16 =>
resumeTag = CedeR
rescheduleFiber(currentCtx, this)
case 17 =>
val cur = cur0.asInstanceOf[Start[Any]]
val ec = currentCtx
val fiber = new IOFiber[Any](
localState,
null,
cur.ioa,
ec,
runtime
)
// println(s"<$name> spawning <$childName>")
scheduleFiber(ec, fiber)
runLoop(succeeded(fiber, 0), nextCancelation, nextAutoCede)
case 18 =>
val cur = cur0.asInstanceOf[RacePair[Any, Any]]
val next =
IO.async[Either[(OutcomeIO[Any], FiberIO[Any]), (FiberIO[Any], OutcomeIO[Any])]] {
cb =>
IO {
val ec = currentCtx
val rt = runtime
val fiberA = new IOFiber[Any](
localState,
null,
cur.ioa,
ec,
rt
)
val fiberB = new IOFiber[Any](
localState,
null,
cur.iob,
ec,
rt
)
fiberA.setCallback(oc => cb(Right(Left((oc, fiberB)))))
fiberB.setCallback(oc => cb(Right(Right((fiberA, oc)))))
scheduleFiber(ec, fiberA)
scheduleFiber(ec, fiberB)
val cancel =
for {
cancelA <- fiberA.cancel.start
cancelB <- fiberB.cancel.start
_ <- cancelA.join
_ <- cancelB.join
} yield ()
Some(cancel)
}
}
runLoop(next, nextCancelation, nextAutoCede)
case 19 =>
val cur = cur0.asInstanceOf[Sleep]
val delay = cur.delay
val next =
if (delay.length > 0)
IO.async[Unit] { cb =>
IO {
val scheduler = runtime.scheduler
val cancelIO =
if (scheduler.isInstanceOf[WorkStealingThreadPool[_]]) {
val cancel =
scheduler
.asInstanceOf[WorkStealingThreadPool[_]]
.sleepInternal(delay, cb)
IO.Delay(cancel, null)
} else {
val cancel = scheduler.sleep(delay, () => cb(RightUnit))
IO(cancel.run())
}
Some(cancelIO)
}
}
else IO.cede
runLoop(next, nextCancelation, nextAutoCede)
case 20 =>
val cur = cur0.asInstanceOf[EvalOn[Any]]
/* fast-path when it's an identity transformation */
if (cur.ec eq currentCtx) {
runLoop(cur.ioa, nextCancelation, nextAutoCede)
} else {
val ec = cur.ec
objectState.push(currentCtx)
currentCtx = ec
conts = ByteStack.push(conts, EvalOnK)
resumeTag = AutoCedeR
resumeIO = cur.ioa
if (isStackTracing) {
val handle = monitor()
objectState.push(handle)
}
scheduleOnForeignEC(ec, this)
}
case 21 =>
val cur = cur0.asInstanceOf[Blocking[Any]]
/* we know we're on the JVM here */
if (isStackTracing) {
pushTracingEvent(cur.event)
}
if (cur.hint eq IOFiber.TypeBlocking) {
val ec = currentCtx