-
Notifications
You must be signed in to change notification settings - Fork 538
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3225 from armanbilge/feature/batching-macrotask-e…
…xecutor Introduce a `BatchingMacrotaskExecutor`
- Loading branch information
Showing
14 changed files
with
486 additions
and
71 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
* 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.effect | ||
|
||
private object Platform { | ||
final val isJs = true | ||
final val isJvm = false | ||
final val isNative = false | ||
} |
149 changes: 149 additions & 0 deletions
149
core/js/src/main/scala/cats/effect/unsafe/BatchingMacrotaskExecutor.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
/* | ||
* 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.effect | ||
package unsafe | ||
|
||
import cats.effect.tracing.TracingConstants | ||
|
||
import org.scalajs.macrotaskexecutor.MacrotaskExecutor | ||
|
||
import scala.collection.mutable | ||
import scala.concurrent.ExecutionContextExecutor | ||
import scala.scalajs.{js, LinkingInfo} | ||
import scala.util.control.NonFatal | ||
|
||
/** | ||
* An `ExecutionContext` that improves throughput by providing a method to `schedule` fibers to | ||
* execute in batches, instead of one task per event loop iteration. This optimization targets | ||
* the typical scenario where a UI or I/O event handler starts/resumes a small number of | ||
* short-lived fibers and then yields to the event loop. | ||
* | ||
* This `ExecutionContext` also maintains a fiber bag in development mode to enable fiber dumps. | ||
* | ||
* @param batchSize | ||
* the maximum number of batched runnables to execute before yielding to the event loop | ||
*/ | ||
private[effect] final class BatchingMacrotaskExecutor( | ||
batchSize: Int, | ||
reportFailure0: Throwable => Unit | ||
) extends ExecutionContextExecutor { | ||
|
||
private[this] val queueMicrotask: js.Function1[js.Function0[Any], Any] = | ||
if (js.typeOf(js.Dynamic.global.queueMicrotask) == "function") | ||
js.Dynamic.global.queueMicrotask.asInstanceOf[js.Function1[js.Function0[Any], Any]] | ||
else { | ||
val resolved = js.Dynamic.global.Promise.resolved(()) | ||
task => resolved.`then`(task) | ||
} | ||
|
||
/** | ||
* Whether the `executeBatchTask` needs to be rescheduled | ||
*/ | ||
private[this] var needsReschedule = true | ||
private[this] val fibers = new JSArrayQueue[IOFiber[_]] | ||
|
||
private[this] object executeBatchTaskRunnable extends Runnable { | ||
def run() = { | ||
// do up to batchSize tasks | ||
var i = 0 | ||
while (i < batchSize && !fibers.isEmpty()) { | ||
val fiber = fibers.take() | ||
|
||
if (LinkingInfo.developmentMode) | ||
if (fiberBag ne null) | ||
fiberBag -= fiber | ||
|
||
try fiber.run() | ||
catch { | ||
case t if NonFatal(t) => reportFailure(t) | ||
case t: Throwable => IOFiber.onFatalFailure(t) | ||
} | ||
|
||
i += 1 | ||
} | ||
|
||
if (!fibers.isEmpty()) // we'll be right back after this (post) message | ||
MacrotaskExecutor.execute(this) | ||
else // the batch task will need to be rescheduled when more fibers arrive | ||
needsReschedule = true | ||
|
||
// yield to the event loop | ||
} | ||
} | ||
|
||
private[this] val executeBatchTaskJSFunction: js.Function0[Any] = | ||
() => executeBatchTaskRunnable.run() | ||
|
||
/** | ||
* Execute the `runnable` in the next iteration of the event loop. | ||
*/ | ||
def execute(runnable: Runnable): Unit = | ||
MacrotaskExecutor.execute(monitor(runnable)) | ||
|
||
/** | ||
* Schedule the `fiber` for the next available batch. This is often the currently executing | ||
* batch. | ||
*/ | ||
def schedule(fiber: IOFiber[_]): Unit = { | ||
if (LinkingInfo.developmentMode) | ||
if (fiberBag ne null) | ||
fiberBag += fiber | ||
|
||
fibers.offer(fiber) | ||
|
||
if (needsReschedule) { | ||
needsReschedule = false | ||
// start executing the batch immediately after the currently running task suspends | ||
// this is safe b/c `needsReschedule` is set to `true` only upon yielding to the event loop | ||
queueMicrotask(executeBatchTaskJSFunction) | ||
() | ||
} | ||
} | ||
|
||
def reportFailure(t: Throwable): Unit = reportFailure0(t) | ||
|
||
def liveTraces(): Map[IOFiber[_], Trace] = | ||
fiberBag.iterator.filterNot(_.isDone).map(f => f -> f.captureTrace()).toMap | ||
|
||
@inline private[this] def monitor(runnable: Runnable): Runnable = | ||
if (LinkingInfo.developmentMode) | ||
if (fiberBag ne null) | ||
runnable match { | ||
case r: IOFiber[_] => | ||
fiberBag += r | ||
() => { | ||
// We have to remove r _before_ running it, b/c it may be re-enqueued while running | ||
// b/c JS is single-threaded, nobody can observe the bag while the fiber is running anyway | ||
fiberBag -= r | ||
r.run() | ||
} | ||
case _ => runnable | ||
} | ||
else runnable | ||
else | ||
runnable | ||
|
||
private[this] val fiberBag = | ||
if (LinkingInfo.developmentMode) | ||
if (TracingConstants.isStackTracing && FiberMonitor.weakRefsAvailable) | ||
mutable.Set.empty[IOFiber[_]] | ||
else | ||
null | ||
else | ||
null | ||
|
||
} |
45 changes: 0 additions & 45 deletions
45
core/js/src/main/scala/cats/effect/unsafe/FiberAwareExecutionContext.scala
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
core/js/src/main/scala/cats/effect/unsafe/JSArrayQueue.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
/* | ||
* 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.effect.unsafe | ||
|
||
import scala.scalajs.js | ||
|
||
/** | ||
* A JS-Array backed circular buffer FIFO queue. It is careful to grow the buffer only using | ||
* `push` to avoid creating "holes" on V8 (this is a known shortcoming of the Scala.js | ||
* `j.u.ArrayDeque` implementation). | ||
*/ | ||
private final class JSArrayQueue[A] { | ||
|
||
private[this] val buffer = js.Array[A](null.asInstanceOf[A]) | ||
|
||
private[this] var startIndex: Int = 0 | ||
private[this] var endIndex: Int = 1 | ||
private[this] var empty: Boolean = true | ||
|
||
@inline def isEmpty(): Boolean = empty | ||
|
||
@inline def take(): A = { | ||
val a = buffer(startIndex) | ||
buffer(startIndex) = null.asInstanceOf[A] | ||
startIndex += 1 | ||
if (startIndex == endIndex) | ||
empty = true | ||
if (startIndex >= buffer.length) | ||
startIndex = 0 | ||
a | ||
} | ||
|
||
@inline def offer(a: A): Unit = { | ||
growIfNeeded() | ||
endIndex += 1 | ||
if (endIndex > buffer.length) | ||
endIndex = 1 | ||
buffer(endIndex - 1) = a | ||
empty = false | ||
} | ||
|
||
@inline private[this] def growIfNeeded(): Unit = | ||
if (!empty) { // empty queue always has capacity >= 1 | ||
if (startIndex == 0 && endIndex == buffer.length) { | ||
buffer.push(null.asInstanceOf[A]) | ||
() | ||
} else if (startIndex == endIndex) { | ||
var i = 0 | ||
while (i < endIndex) { | ||
buffer.push(buffer(i)) | ||
buffer(i) = null.asInstanceOf[A] | ||
i += 1 | ||
} | ||
endIndex = buffer.length | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.