-
Notifications
You must be signed in to change notification settings - Fork 509
/
Queue.scala
1279 lines (1076 loc) · 41.1 KB
/
Queue.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-2022 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
package effect
package std
import cats.effect.kernel.{Async, Cont, Deferred, GenConcurrent, MonadCancelThrow, Poll, Ref}
import cats.effect.kernel.syntax.all._
import cats.syntax.all._
import scala.annotation.tailrec
import scala.collection.immutable.{Queue => ScalaQueue}
import scala.collection.mutable.ListBuffer
import java.util.concurrent.atomic.{AtomicLong, AtomicLongArray, AtomicReference}
/**
* A purely functional, concurrent data structure which allows insertion and retrieval of
* elements of type `A` in a first-in-first-out (FIFO) manner.
*
* Depending on the type of queue constructed, the [[Queue#offer]] operation can block
* semantically until sufficient capacity in the queue becomes available.
*
* The [[Queue#take]] operation semantically blocks when the queue is empty.
*
* The [[Queue#tryOffer]] and [[Queue#tryTake]] allow for usecases which want to avoid fiber
* blocking a fiber.
*/
abstract class Queue[F[_], A] extends QueueSource[F, A] with QueueSink[F, A] { self =>
/**
* Modifies the context in which this queue is executed using the natural transformation `f`.
*
* @return
* a queue in the new context obtained by mapping the current one using `f`
*/
def mapK[G[_]](f: F ~> G): Queue[G, A] =
new Queue[G, A] {
def offer(a: A): G[Unit] = f(self.offer(a))
def tryOffer(a: A): G[Boolean] = f(self.tryOffer(a))
def size: G[Int] = f(self.size)
val take: G[A] = f(self.take)
val tryTake: G[Option[A]] = f(self.tryTake)
}
}
object Queue {
/**
* Constructs an empty, bounded queue holding up to `capacity` elements for `F` data types
* that are [[cats.effect.kernel.GenConcurrent]]. When the queue is full (contains exactly
* `capacity` elements), every next [[Queue#offer]] will be backpressured (i.e. the
* [[Queue#offer]] blocks semantically).
*
* @param capacity
* the maximum capacity of the queue
* @return
* an empty, bounded queue
*/
def bounded[F[_], A](capacity: Int)(implicit F: GenConcurrent[F, _]): F[Queue[F, A]] = {
assertNonNegative(capacity)
// async queue can't handle capacity == 1 and allocates eagerly, so cap at 64k
if (1 < capacity && capacity < Short.MaxValue.toInt * 2) {
F match {
case f0: Async[F] =>
boundedForAsync[F, A](capacity)(f0)
case _ =>
boundedForConcurrent[F, A](capacity)
}
} else if (capacity > 0) {
boundedForConcurrent[F, A](capacity)
} else {
synchronous[F, A]
}
}
private[effect] def boundedForConcurrent[F[_], A](capacity: Int)(
implicit F: GenConcurrent[F, _]): F[Queue[F, A]] =
F.ref(State.empty[F, A]).map(new BoundedQueue(capacity, _))
private[effect] def boundedForAsync[F[_], A](capacity: Int)(
implicit F: Async[F]): F[Queue[F, A]] =
F.delay(new BoundedAsyncQueue(capacity))
private[effect] def unboundedForConcurrent[F[_], A](
implicit F: GenConcurrent[F, _]): F[Queue[F, A]] =
boundedForConcurrent[F, A](Int.MaxValue)
private[effect] def unboundedForAsync[F[_], A](implicit F: Async[F]): F[Queue[F, A]] =
F.delay(new UnboundedAsyncQueue())
/**
* Constructs a queue through which a single element can pass only in the case when there are
* at least one taking fiber and at least one offering fiber for `F` data types that are
* [[cats.effect.kernel.GenConcurrent]]. Both [[Queue#offer]] and [[Queue#take]] semantically
* block until there is a fiber executing the opposite action, at which point both fibers are
* freed.
*
* @return
* a synchronous queue
*/
def synchronous[F[_], A](implicit F: GenConcurrent[F, _]): F[Queue[F, A]] =
F.ref(SyncState.empty[F, A]).map(new Synchronous(_))
/**
* Constructs an empty, unbounded queue for `F` data types that are
* [[cats.effect.kernel.GenConcurrent]]. [[Queue#offer]] never blocks semantically, as there
* is always spare capacity in the queue.
*
* @return
* an empty, unbounded queue
*/
def unbounded[F[_], A](implicit F: GenConcurrent[F, _]): F[Queue[F, A]] =
F match {
case f0: Async[F] =>
unboundedForAsync(f0)
case _ =>
unboundedForConcurrent
}
/**
* Constructs an empty, bounded, dropping queue holding up to `capacity` elements for `F` data
* types that are [[cats.effect.kernel.GenConcurrent]]. When the queue is full (contains
* exactly `capacity` elements), every next [[Queue#offer]] will be ignored, i.e. no other
* elements can be enqueued until there is sufficient capacity in the queue, and the offer
* effect itself will not semantically block.
*
* @param capacity
* the maximum capacity of the queue
* @return
* an empty, bounded, dropping queue
*/
def dropping[F[_], A](capacity: Int)(implicit F: GenConcurrent[F, _]): F[Queue[F, A]] = {
assertPositive(capacity, "Dropping")
F.ref(State.empty[F, A]).map(new DroppingQueue(capacity, _))
}
/**
* Constructs an empty, bounded, circular buffer queue holding up to `capacity` elements for
* `F` data types that are [[cats.effect.kernel.GenConcurrent]]. The queue always keeps at
* most `capacity` number of elements, with the oldest element in the queue always being
* dropped in favor of a new elements arriving in the queue, and the offer effect itself will
* not semantically block.
*
* @param capacity
* the maximum capacity of the queue
* @return
* an empty, bounded, sliding queue
*/
def circularBuffer[F[_], A](capacity: Int)(
implicit F: GenConcurrent[F, _]): F[Queue[F, A]] = {
assertPositive(capacity, "CircularBuffer")
F.ref(State.empty[F, A]).map(new CircularBufferQueue(capacity, _))
}
private def assertNonNegative(capacity: Int): Unit =
if (capacity < 0)
throw new IllegalArgumentException(
s"Bounded queue capacity must be non-negative, was: $capacity")
else ()
private def assertPositive(capacity: Int, name: String): Unit =
if (capacity <= 0)
throw new IllegalArgumentException(
s"$name queue capacity must be positive, was: $capacity")
else ()
private final class Synchronous[F[_], A](stateR: Ref[F, SyncState[F, A]])(
implicit F: GenConcurrent[F, _])
extends Queue[F, A] {
def offer(a: A): F[Unit] =
F.deferred[Deferred[F, A]] flatMap { latch =>
F uncancelable { poll =>
val cleanupF = stateR modify {
case SyncState(offerers, takers) =>
val fallback = latch.tryGet flatMap {
case Some(offerer) => offerer.complete(a).void
case None => F.unit
}
SyncState(offerers.filter(_ ne latch), takers) -> fallback
}
val modificationF = stateR modify {
case SyncState(offerers, takers) if takers.nonEmpty =>
val (taker, tail) = takers.dequeue
SyncState(offerers, tail) -> taker.complete(a).void
case SyncState(offerers, takers) =>
SyncState(offerers.enqueue(latch), takers) ->
poll(latch.get).onCancel(cleanupF.flatten).flatMap(_.complete(a).void)
}
modificationF.flatten
}
}
def tryOffer(a: A): F[Boolean] = {
val modificationF = stateR modify {
case SyncState(offerers, takers) if takers.nonEmpty =>
val (taker, tail) = takers.dequeue
SyncState(offerers, tail) -> taker.complete(a).as(true)
case st =>
st -> F.pure(false)
}
modificationF.flatten.uncancelable
}
val take: F[A] =
F.deferred[A] flatMap { latch =>
val modificationF = stateR modify {
case SyncState(offerers, takers) if offerers.nonEmpty =>
val (offerer, tail) = offerers.dequeue
SyncState(tail, takers) -> offerer.complete(latch).void
case SyncState(offerers, takers) =>
SyncState(offerers, takers.enqueue(latch)) -> F.unit
}
val cleanupF = stateR update {
case SyncState(offerers, takers) =>
SyncState(offerers, takers.filter(_ ne latch))
}
F uncancelable { poll => modificationF.flatten *> poll(latch.get).onCancel(cleanupF) }
}
val tryTake: F[Option[A]] = {
val modificationF = stateR modify {
case SyncState(offerers, takers) if offerers.nonEmpty =>
val (offerer, tail) = offerers.dequeue
SyncState(tail, takers) -> F
.deferred[A]
.flatMap(d => offerer.complete(d) *> d.get.map(_.some))
case st =>
st -> none[A].pure[F]
}
modificationF.flatten.uncancelable
}
val size: F[Int] = F.pure(0)
}
private final case class SyncState[F[_], A](
offerers: ScalaQueue[Deferred[F, Deferred[F, A]]],
takers: ScalaQueue[Deferred[F, A]])
private object SyncState {
def empty[F[_], A]: SyncState[F, A] = SyncState(ScalaQueue(), ScalaQueue())
}
private sealed abstract class AbstractQueue[F[_], A](
capacity: Int,
state: Ref[F, State[F, A]]
)(implicit F: GenConcurrent[F, _])
extends Queue[F, A] {
protected def onOfferNoCapacity(
s: State[F, A],
a: A,
offerer: Deferred[F, Unit],
poll: Poll[F],
recurse: => F[Unit]): (State[F, A], F[Unit])
protected def onTryOfferNoCapacity(s: State[F, A], a: A): (State[F, A], F[Boolean])
def offer(a: A): F[Unit] =
F uncancelable { poll =>
F.deferred[Unit] flatMap { offerer =>
val modificationF = state modify {
case State(queue, size, takers, offerers) if takers.nonEmpty =>
val (taker, rest) = takers.dequeue
State(queue.enqueue(a), size + 1, rest, offerers) -> taker.complete(()).void
case State(queue, size, takers, offerers) if size < capacity =>
State(queue.enqueue(a), size + 1, takers, offerers) -> F.unit
case s =>
onOfferNoCapacity(s, a, offerer, poll, offer(a))
}
modificationF.flatten
}
}
def tryOffer(a: A): F[Boolean] =
state
.modify {
case State(queue, size, takers, offerers) if takers.nonEmpty =>
val (taker, rest) = takers.dequeue
State(queue.enqueue(a), size + 1, rest, offerers) -> taker.complete(()).as(true)
case State(queue, size, takers, offerers) if size < capacity =>
State(queue.enqueue(a), size + 1, takers, offerers) -> F.pure(true)
case s =>
onTryOfferNoCapacity(s, a)
}
.flatten
.uncancelable
val take: F[A] =
F.uncancelable { poll =>
F.deferred[Unit] flatMap { taker =>
val modificationF = state modify {
case State(queue, size, takers, offerers) if queue.nonEmpty && offerers.isEmpty =>
val (a, rest) = queue.dequeue
State(rest, size - 1, takers, offerers) -> F.pure(a)
case State(queue, size, takers, offerers) if queue.nonEmpty =>
val (a, rest) = queue.dequeue
// if we haven't made enough space for a new offerer, don't disturb the water
if (size - 1 < capacity) {
val (release, tail) = offerers.dequeue
State(rest, size - 1, takers, tail) -> release.complete(()).as(a)
} else {
State(rest, size - 1, takers, offerers) -> F.pure(a)
}
case State(queue, size, takers, offerers) =>
/*
* In the case that we're notified as we're canceled and the cancelation wins the
* race, we need to not only remove ourselves from the queue but also grab the next
* in line and notify *them*. Since this scenario cannot be detected reliably, we
* just unconditionally notify. If the notification was spurious, the taker we notify
* will end up going to the back of the queue, violating fairness.
*/
val cleanup = state modify { s =>
val takers2 = s.takers.filter(_ ne taker)
if (takers2.isEmpty) {
s.copy(takers = takers2) -> F.unit
} else {
val (taker, rest) = takers2.dequeue
s.copy(takers = rest) -> taker.complete(()).void
}
}
val await = poll(taker.get).onCancel(cleanup.flatten) *>
poll(take).onCancel(notifyNextTaker.flatten)
val (fulfill, offerers2) = if (offerers.isEmpty) {
(await, offerers)
} else {
val (release, rest) = offerers.dequeue
(release.complete(()) *> await, rest)
}
// it would be safe to throw cleanup around *both* polls, but we micro-optimize slightly here
State(queue, size, takers.enqueue(taker), offerers2) -> fulfill
}
modificationF.flatten
}
}
val tryTake: F[Option[A]] =
state
.modify {
case State(queue, size, takers, offerers) if queue.nonEmpty && offerers.isEmpty =>
val (a, rest) = queue.dequeue
State(rest, size - 1, takers, offerers) -> F.pure(a.some)
case State(queue, size, takers, offerers) if queue.nonEmpty =>
val (a, rest) = queue.dequeue
val (release, tail) = offerers.dequeue
State(rest, size - 1, takers, tail) -> release.complete(()).as(a.some)
case s =>
s -> F.pure(none[A])
}
.flatten
.uncancelable
val size: F[Int] = state.get.map(_.size)
private[this] val notifyNextTaker = state modify { s =>
if (s.takers.isEmpty) {
s -> F.unit
} else {
val (taker, rest) = s.takers.dequeue
s.copy(takers = rest) -> taker.complete(()).void
}
}
}
private final class BoundedQueue[F[_], A](capacity: Int, state: Ref[F, State[F, A]])(
implicit F: GenConcurrent[F, _]
) extends AbstractQueue(capacity, state) {
require(capacity > 0)
protected def onOfferNoCapacity(
s: State[F, A],
a: A,
offerer: Deferred[F, Unit],
poll: Poll[F],
recurse: => F[Unit]): (State[F, A], F[Unit]) = {
val State(queue, size, takers, offerers) = s
val cleanup = state modify { s =>
val offerers2 = s.offerers.filter(_ ne offerer)
if (offerers2.isEmpty) {
s.copy(offerers = offerers2) -> F.unit
} else {
val (offerer, rest) = offerers2.dequeue
s.copy(offerers = rest) -> offerer.complete(()).void
}
}
State(queue, size, takers, offerers.enqueue(offerer)) ->
(poll(offerer.get) *> poll(recurse)).onCancel(cleanup.flatten)
}
protected def onTryOfferNoCapacity(s: State[F, A], a: A): (State[F, A], F[Boolean]) =
s -> F.pure(false)
}
private final class DroppingQueue[F[_], A](capacity: Int, state: Ref[F, State[F, A]])(
implicit F: GenConcurrent[F, _]
) extends AbstractQueue(capacity, state) {
protected def onOfferNoCapacity(
s: State[F, A],
a: A,
offerer: Deferred[F, Unit],
poll: Poll[F],
recurse: => F[Unit]
): (State[F, A], F[Unit]) =
s -> F.unit
protected def onTryOfferNoCapacity(s: State[F, A], a: A): (State[F, A], F[Boolean]) =
s -> F.pure(false)
}
private final class CircularBufferQueue[F[_], A](capacity: Int, state: Ref[F, State[F, A]])(
implicit F: GenConcurrent[F, _]
) extends AbstractQueue(capacity, state) {
protected def onOfferNoCapacity(
s: State[F, A],
a: A,
offerer: Deferred[F, Unit],
poll: Poll[F],
recurse: => F[Unit]): (State[F, A], F[Unit]) = {
// dotty doesn't like cats map on tuples
val (ns, fb) = onTryOfferNoCapacity(s, a)
(ns, fb.void)
}
protected def onTryOfferNoCapacity(s: State[F, A], a: A): (State[F, A], F[Boolean]) = {
val State(queue, size, takers, offerers) = s
val (_, rest) = queue.dequeue
State(rest.enqueue(a), size, takers, offerers) -> F.pure(true)
}
}
private final case class State[F[_], A](
queue: ScalaQueue[A],
size: Int,
takers: ScalaQueue[Deferred[F, Unit]],
offerers: ScalaQueue[Deferred[F, Unit]])
private object State {
def empty[F[_], A]: State[F, A] =
State(ScalaQueue.empty, 0, ScalaQueue.empty, ScalaQueue.empty)
}
private val EitherUnit: Either[Nothing, Unit] = Right(())
private val FailureSignal: Throwable = new RuntimeException
with scala.util.control.NoStackTrace
/*
* Does not correctly handle bound = 0 because take waiters are async[Unit]
*/
private final class BoundedAsyncQueue[F[_], A](capacity: Int)(implicit F: Async[F])
extends Queue[F, A] {
require(capacity > 1)
private[this] val buffer = new UnsafeBounded[A](capacity)
private[this] val takers = new UnsafeUnbounded[Either[Throwable, Unit] => Unit]()
private[this] val offerers = new UnsafeUnbounded[Either[Throwable, Unit] => Unit]()
// private[this] val takers = new ConcurrentLinkedQueue[AtomicReference[Either[Throwable, Unit] => Unit]]()
// private[this] val offerers = new ConcurrentLinkedQueue[AtomicReference[Either[Throwable, Unit] => Unit]]()
def offer(a: A): F[Unit] =
F uncancelable { poll =>
F defer {
try {
// attempt to put into the buffer; if the buffer is full, it will raise an exception
buffer.put(a)
// println(s"offered: size = ${buffer.size()}")
// we successfully put, if there are any takers, grab the first one and wake it up
notifyOne(takers)
F.unit
} catch {
case FailureSignal =>
// capture whether or not we were successful in our retry
var succeeded = false
// a latch blocking until some taker notifies us
val wait = F.async[Unit] { k =>
F delay {
// add ourselves to the listeners queue
val clear = offerers.put(k)
try {
// now that we're listening, re-attempt putting
buffer.put(a)
// it worked! clear ourselves out of the queue
clear()
// our retry succeeded
succeeded = true
// manually complete our own callback
// note that we could have a race condition here where we're already completed
// async will deduplicate these calls for us
// additionally, the continuation (below) is held until the registration completes
k(EitherUnit)
// we *might* have negated a notification by succeeding here
// unnecessary wake-ups are mostly harmless (only slight fairness loss)
notifyOne(offerers)
// technically it's possible to already have waiting takers. notify one of them
notifyOne(takers)
// we're immediately complete, so no point in creating a finalizer
None
} catch {
case FailureSignal =>
// our retry failed, meaning the queue is still full and we're listening, so suspend
// println(s"failed offer size = ${buffer.size()}")
Some(F.delay(clear()))
}
}
}
val notifyAnyway = F delay {
// we might have been awakened and canceled simultaneously
// try waking up another offerer just in case
notifyOne(offerers)
}
// suspend until the buffer put can succeed
// if succeeded is true then we've *already* put
// if it's false, then some taker woke us up, so race the retry with other offers
(poll(wait) *> F.defer(if (succeeded) F.unit else poll(offer(a))))
.onCancel(notifyAnyway)
}
}
}
def tryOffer(a: A): F[Boolean] = F delay {
try {
buffer.put(a)
notifyOne(takers)
true
} catch {
case FailureSignal =>
false
}
}
val size: F[Int] = F.delay(buffer.size())
val take: F[A] =
F uncancelable { poll =>
F defer {
try {
// attempt to take from the buffer. if it's empty, this will raise an exception
val result = buffer.take()
// println(s"took: size = ${buffer.size()}")
// still alive! notify an offerer that there's some space
notifyOne(offerers)
F.pure(result)
} catch {
case FailureSignal =>
// buffer was empty
// capture the fact that our retry succeeded and the value we were able to take
var received = false
var result: A = null.asInstanceOf[A]
// a latch to block until some offerer wakes us up
// we need to use cont to avoid calling `get` on the double-check
val wait = F.cont[Unit, Unit](new Cont[F, Unit, Unit] {
override def apply[G[_]](implicit G: MonadCancelThrow[G]) = { (k, get, lift) =>
G uncancelable { poll =>
val lifted = lift {
F delay {
// register ourselves as a listener for offers
val clear = takers.put(k)
try {
// now that we're registered, retry the take
result = buffer.take()
// it worked! clear out our listener
clear()
// we got a result, so received should be true now
received = true
// we *might* have negated a notification by succeeding here
// unnecessary wake-ups are mostly harmless (only slight fairness loss)
notifyOne(takers)
// it's technically possible to already have queued offerers. wake up one of them
notifyOne(offerers)
// we skip `get` here because we already have a value
// this is the thing that `async` doesn't allow us to do
G.unit
} catch {
case FailureSignal =>
// println(s"failed take size = ${buffer.size()}")
// our retry failed, we're registered as a listener, so suspend
poll(get).onCancel(lift(F.delay(clear())))
}
}
}
lifted.flatten
}
}
})
val notifyAnyway = F delay {
// we might have been awakened and canceled simultaneously
// try waking up another taker just in case
notifyOne(takers)
}
// suspend until an offerer wakes us or our retry succeeds, then return a result
(poll(wait) *> F.defer(if (received) F.pure(result) else poll(take)))
.onCancel(notifyAnyway)
}
}
}
val tryTake: F[Option[A]] = F delay {
try {
val back = buffer.take()
notifyOne(offerers)
Some(back)
} catch {
case FailureSignal =>
None
}
}
override def tryTakeN(limit: Option[Int])(implicit F0: Monad[F]): F[List[A]] = {
QueueSource.assertMaxNPositive(limit)
F delay {
val _ = F0
val back = buffer.drain(limit.getOrElse(Int.MaxValue))
@tailrec
def loop(i: Int): Unit = {
if (i >= 0) {
var took = false
val f =
try {
val back = offerers.take()
took = true
back
} catch {
case FailureSignal => null
}
if (took) {
if (f != null) {
f(EitherUnit)
loop(i - 1)
} else {
loop(i)
}
}
}
}
// notify up to back.length offerers
loop(back.length)
back
}
}
def debug(): Unit = {
println(s"buffer: ${buffer.debug()}")
// println(s"takers: ${takers.debug()}")
// println(s"offerers: ${offerers.debug()}")
}
// TODO could optimize notifications by checking if buffer is completely empty on put
@tailrec
private[this] def notifyOne(
waiters: UnsafeUnbounded[Either[Throwable, Unit] => Unit]): Unit = {
// capture whether or not we should loop (structured in this way to avoid nested try/catch, which has a performance cost)
val retry =
try {
val f =
waiters
.take() // try to take the first waiter; if there are none, raise an exception
// we didn't get an exception, but the waiter may have been removed due to cancelation
if (f == null) {
// it was removed! loop and retry
true
} else {
// it wasn't removed, so invoke it
// taker may have already been invoked due to the double-check pattern, in which case this will be idempotent
f(EitherUnit)
// don't retry
false
}
} catch {
// there are no takers, so don't notify anything
case FailureSignal => false
}
if (retry) {
// loop outside of try/catch
notifyOne(waiters)
}
}
}
private final class UnboundedAsyncQueue[F[_], A]()(implicit F: Async[F]) extends Queue[F, A] {
private[this] val buffer = new UnsafeUnbounded[A]()
private[this] val takers = new UnsafeUnbounded[Either[Throwable, Unit] => Unit]()
def offer(a: A): F[Unit] = F delay {
buffer.put(a)
notifyOne()
}
def tryOffer(a: A): F[Boolean] = F delay {
buffer.put(a)
notifyOne()
true
}
val size: F[Int] = F.delay(buffer.size())
val take: F[A] = F defer {
try {
// attempt to take from the buffer. if it's empty, this will raise an exception
F.pure(buffer.take())
} catch {
case FailureSignal =>
// buffer was empty
// capture the fact that our retry succeeded and the value we were able to take
var received = false
var result: A = null.asInstanceOf[A]
// a latch to block until some offerer wakes us up
val wait = F.async[Unit] { k =>
F delay {
// register ourselves as a listener for offers
val clear = takers.put(k)
try {
// now that we're registered, retry the take
result = buffer.take()
// it worked! clear out our listener
clear()
// we got a result, so received should be true now
received = true
// complete our own callback. see notes in offer about raced redundant completion
k(EitherUnit)
// we *might* have negated a notification by succeeding here
// unnecessary wake-ups are mostly harmless (only slight fairness loss)
notifyOne()
// don't bother with a finalizer since we're already complete
None
} catch {
case FailureSignal =>
// println(s"failed take size = ${buffer.size()}")
// our retry failed, we're registered as a listener, so suspend
Some(F.delay(clear()))
}
}
}
// suspend until an offerer wakes us or our retry succeeds, then return a result
wait *> F.defer(if (received) F.pure(result) else take)
}
}
val tryTake: F[Option[A]] = F delay {
try {
Some(buffer.take())
} catch {
case FailureSignal =>
None
}
}
@tailrec
private[this] def notifyOne(): Unit = {
// capture whether or not we should loop (structured in this way to avoid nested try/catch, which has a performance cost)
val retry =
try {
val f =
takers.take() // try to take the first waiter; if there are none, raise an exception
// we didn't get an exception, but the waiter may have been removed due to cancelation
if (f == null) {
// it was removed! loop and retry
true
} else {
// it wasn't removed, so invoke it
// taker may have already been invoked due to the double-check pattern, in which case this will be idempotent
f(EitherUnit)
// don't retry
false
}
} catch {
// there are no takers, so don't notify anything
case FailureSignal => false
}
if (retry) {
// loop outside of try/catch
notifyOne()
}
}
}
// ported with love from https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/MpmcArrayQueue.java
private[effect] final class UnsafeBounded[A](bound: Int) {
require(bound > 1)
private[this] val buffer = new Array[AnyRef](bound)
private[this] val sequenceBuffer = new AtomicLongArray(bound)
private[this] val head = new AtomicLong(0)
private[this] val tail = new AtomicLong(0)
private[this] val LookAheadStep = Math.max(2, Math.min(bound / 4, 4096)) // TODO tunable
0.until(bound).foreach(i => sequenceBuffer.set(i, i.toLong))
def debug(): String = buffer.mkString("[", ", ", "]")
@tailrec
def size(): Int = {
val before = head.get()
val currentTail = tail.get()
val after = head.get()
if (before == after) {
val size = currentTail - after
if (size < 0)
0
else
size.toInt
} else {
size()
}
}
def put(data: A): Unit = {
@tailrec
def loop(currentHead: Long): Long = {
val currentTail = tail.get()
val seq = sequenceBuffer.get(project(currentTail))
if (seq < currentTail) {
if (currentTail - bound >= currentHead) {
val currentHead2 = head.get()
if (currentTail - bound >= currentHead2)
throw FailureSignal
else
loop(currentHead2)
} else {
loop(currentHead)
}
} else {
if (seq == currentTail && tail.compareAndSet(currentTail, currentTail + 1))
currentTail
else
loop(currentHead)
}
}
val currentTail = loop(Long.MinValue)
buffer(project(currentTail)) = data.asInstanceOf[AnyRef]
sequenceBuffer.incrementAndGet(project(currentTail))
()
}
def take(): A = {
@tailrec
def loop(currentTail: Long): Long = {
val currentHead = head.get()
val seq = sequenceBuffer.get(project(currentHead))
if (seq < currentHead + 1) {
if (currentHead >= currentTail) {
val currentTail2 = tail.get()
if (currentHead == currentTail2)
throw FailureSignal
else
loop(currentTail2)
} else {
loop(currentTail)
}
} else {
if (seq == currentHead + 1 && head.compareAndSet(currentHead, currentHead + 1))
currentHead
else
loop(currentTail)
}
}
val currentHead = loop(-1)
val back = buffer(project(currentHead)).asInstanceOf[A]
buffer(project(currentHead)) = null
sequenceBuffer.set(project(currentHead), currentHead + bound)
back
}
def drain(limit: Int): List[A] = {
val back = new ListBuffer[A]()
@tailrec
def loopOne(consumed: Int): Unit = {
if (consumed < limit) {
val next =
try {
back += take()
true
} catch {
case FailureSignal => false
}
if (next) {
loopOne(consumed + 1)
}
}
}
val maxLookAheadStep = Math.min(LookAheadStep, limit)
@tailrec
def loopMany(consumed: Int): Unit = {
if (consumed < limit) {
val remaining = limit - consumed
val step = Math.min(remaining, maxLookAheadStep)
val currentHead = head.get()
val lookAheadIndex = currentHead + step - 1
val lookAheadOffset = project(lookAheadIndex)
val lookAheadSeq = sequenceBuffer.get(lookAheadOffset)
val expectedLookAheadSeq = lookAheadIndex + 1