scoop:scoop.asyncio:0.1.0
src/runtime_event_loop.scoop
Selected production source · src/runtime_event_loop.scoop
1
package scoop.asyncio3
import scoop.concurrent.BlockingTaskPool4
import scoop.concurrent.CoroutineWorkerDriver5
import scoop.concurrent.MultiThreadExecutor6
import scoop.time.Duration7
import scoop.platform.net.*8
import scoop.platform.system.OsString9
import scoop.platform.fs.*10
import scoop.platform.process.Command12
// One public service binding; resources retain one of its physical reactor owners.13
internal class RuntimeEventLoop private constructor(count: Int): EventLoop, Closeable, LoopWorkers {14
val identity = RuntimeWorkerContext.nextIdentity()15
private val reactors =16
Array<RuntimeReactor>(count.toLong()) { index -> RuntimeReactor(this, index.toInt()) }17
private val assignment = AtomicInt(0)18
private var execution: MultiThreadExecutor? = None19
var rootFailure: Throwable? = None21
companion object {22
fun create(count: Int, pool: BlockingTaskPool): RuntimeEventLoop {23
val runtime = RuntimeEventLoop(count)24
try {25
for (reactor in runtime.reactors)26
reactor.open(pool)27
return runtime28
} catch (error: Throwable) {29
runtime.use { _ -> throw error }30
}31
}32
}34
val drivers: Array<CoroutineWorkerDriver> get() =35
Array<CoroutineWorkerDriver>(reactors.size) { index -> reactors[index] }37
fun bindExecutor(executor: MultiThreadExecutor) {38
execution = Some(executor)39
}41
fun bindRoot(job: Job) {42
for (reactor in reactors)43
reactor.owner.bindRoot(job)44
}46
public override fun isCurrentWorker(index: Int): Boolean = RuntimeWorkerContext.current(identity) == index48
public override fun nextOwner(): LoopOwner {49
var current = assignment.load(MemoryOrder.Relaxed)50
while (true) {51
val next =52
if (current + 1 == reactors.size.toInt())53
054
else55
current + 156
if (assignment.compareAndSet(current, next, MemoryOrder.Relaxed, MemoryOrder.Relaxed))57
return reactors[current.toLong()].owner58
current = assignment.load(MemoryOrder.Relaxed)59
}60
}62
private fun owner(): LoopOwner {63
val index = RuntimeWorkerContext.current(identity)64
return if (index >= 0)65
reactors[index.toLong()].owner66
else67
nextOwner()68
}70
public override val executor: CoroutineExecutor get() {71
val executor = execution ?: throw IllegalStateException(Some("event loop is not running"))72
if (executor.isTerminated)73
throw IllegalStateException(Some("event loop executor has terminated"))74
return executor75
}77
public override fun close() {78
var failure = rootFailure79
for (reactor in reactors) {80
reactor.close()81
failure = runtimeFailure(failure, reactor.failure)82
}83
when (failure) {84
case Some(val error) -> throw error85
case None -> {}86
}87
}89
public override suspend fun sleep(duration: Duration) {90
sleepOnLoop(owner(), duration)91
}92
public override fun schedule(duration: Duration, completion: (Throwable?) -> Unit): Disposable =93
scheduleOnLoop(owner(), duration, completion)94
public override suspend fun resolve(host: OsString, port: Int, family: AddressFamily?): Array<95
SocketAddress96
> = resolveOnLoop(owner(), host, port, family)97
public override suspend fun openFile(path: Path, options: OpenOptions): AsyncFile =98
openFileOnLoop(owner(), path, options)99
public override suspend fun openTty(): AsyncTty = openTtyOnLoop(owner())100
public override suspend fun spawnPty(101
command: Command,102
columns: Long,103
rows: Long,104
searchPath: Boolean105
): AsyncPty = spawnPtyOnLoop(owner(), command, columns, rows, searchPath)106
public override suspend fun metadata(path: Path, followLinks: Boolean): FileMetadata =107
metadataOnLoop(owner(), path, followLinks)108
public override suspend fun moveFile(109
source: Path,110
destination: Path,111
replaceExisting: Boolean112
) {113
moveFileOnLoop(owner(), source, destination, replaceExisting)114
}115
public override suspend fun deleteFile(path: Path) {116
deleteFileOnLoop(owner(), path)117
}118
public override suspend fun createDirectories(path: Path, mode: Int) {119
createDirectoriesOnLoop(owner(), path, mode)120
}121
public override suspend fun createTempFile(parent: Path?, prefix: String): TemporaryFile =122
createTemporaryFileOnLoop(owner(), parent, prefix)123
public override suspend fun openDirectory(path: Path): AsyncDirectoryEntries =124
openDirectoryOnLoop(owner(), path)125
public override suspend fun connectTcp(address: SocketAddress): AsyncTcpStream =126
connectTcpOnLoop(owner(), address)127
public override suspend fun connectTcp(128
host: OsString,129
port: Int,130
options: TcpConnectOptions131
): AsyncTcpStream = connectTcpHostOnLoop(owner(), host, port, options)132
public override suspend fun listenTcp(133
address: SocketAddress,134
backlog: Int,135
reuseAddress: Boolean136
): AsyncTcpListener = listenTcpOnLoop(owner(), address, backlog, reuseAddress)137
public override suspend fun bindUdp(138
address: SocketAddress,139
reuseAddress: Boolean140
): AsyncUdpSocket = bindUdpOnLoop(owner(), address, reuseAddress)141
}143
private fun runtimeFailure(primary: Throwable?, next: Throwable?): Throwable? =144
when (next) {145
case None -> primary146
case Some(val next) -> when (primary) {147
case None -> Some(next)148
case Some(val primary) -> if (next is CancellationException)149
Some(primary)150
else151
if (primary is CancellationException)152
Some(next)153
else154
Some(ResourceUseException(primary, next))155
}156
}