scoop:scoop.asyncio:0.1.0
src/pty_endpoint.scoop
Selected production source · src/pty_endpoint.scoop
1
package scoop.asyncio3
import scoop.concurrent.AsyncMutex4
import scoop.platform.memory.NativeByteBuffer5
import scoop.platform.process.ExitStatus6
import scoop.platform.process.requirePtySize7
import scoop.platform.system.OperatingSystem8
import scoop.platform.system.operatingSystem10
private enum PtyPhase {11
Open, Closing, Closed12
}14
private enum PtyConsole {15
Active, Ending, Ended16
}18
internal class PtyEndpoint(val loop: LoopOwner, val pointer: Ptr<Unit>) : AsyncPty, LoopResource {19
private val gate = IoLock()20
private var phase = PtyPhase.Open21
private var directions = 022
private val reader = PtyTransfer(this, false)23
private val writer = PtyTransfer(this, true)24
private val resizeLock = AsyncMutex()26
// These controls and completions run on the owner.27
private val exit = PtyExitWaiters(loop)28
private var watcher: CallbackOperation? = None29
private var resizeOperation: CallbackOperation? = None30
private var console = PtyConsole.Active31
private var outputDetached = false32
private var finalizing = false33
private var closeFailure: Throwable? = None34
private val closeWaiters = ArrayList<(Throwable?) -> Unit>()36
val isClosing: Boolean get() = gate.withLock { phase != PtyPhase.Open }38
fun acquire(writing: Boolean) {39
val bit = direction(writing)40
gate41
.withLock {42
if (phase != PtyPhase.Open) throw IoClosedException()43
if ((directions and bit) != 0)44
throw IllegalStateException(Some("I/O direction is busy"))45
directions = directions or bit46
}47
}49
fun release(writing: Boolean) {50
val closing = gate51
.withLock {52
directions = directions and direction(writing).inv()53
phase == PtyPhase.Closing54
}55
if (closing) loop.post { advanceClose() }56
}58
fun activate() {59
@Unsafe60
{61
val status = nativePtyAssociate(loop.nativePointer(), pointer)62
if (status.code != 0) throw backendFailure("associate pseudoterminal", status)63
}64
watchExit()65
}67
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long =68
suspendCoroutine(reader.prepare(buffer, count, loop.requireJob()))70
public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long =71
suspendCoroutine(writer.prepare(buffer, count, loop.requireJob()))73
public override suspend fun flush() {74
loop.requireJob()75
acquire(true)76
release(true)77
}79
public override suspend fun wait(): ExitStatus = exit.await(loop.requireJob()) { isClosing }81
public override suspend fun resize(columns: Long, rows: Long) {82
val job = loop.requireJob()83
requirePtySize(columns, rows)84
resizeLock.withLock { this @PtyEndpoint.performResize(columns.toInt(), rows.toInt(), job) }85
}87
private suspend fun performResize(columns: Int, rows: Int, job: Job): Unit = suspendCoroutine<88
Unit89
> { continuation ->90
loop91
.post {92
if (isClosing || console != PtyConsole.Active) {93
continuation.resumeWithException(IoClosedException())94
return@post95
}96
val operation = CallbackOperation(97
loop, loop.nextOperation(),98
{ native, id ->99
@Unsafe100
{101
return@CallbackOperation nativeStatus(102
id, nativePtyResize(native, pointer, id, columns, rows)103
)104
}105
},106
{ native, id ->107
@Unsafe {108
nativeWorkCancel(native, id)109
}110
},111
{ event, selected ->112
resizeOperation = None113
finishUnit(114
continuation,115
completionFailure("resize pseudoterminal", event.result, selected)116
)117
advanceControl()118
}119
)120
resizeOperation = Some(operation)121
operation.subscribe(job)122
loop.submit(operation)123
}124
}126
private fun watchExit() {127
val operation = CallbackOperation(128
loop, loop.nextOperation(),129
{ native, id ->130
@Unsafe131
{132
return@CallbackOperation nativeStatus(id, nativePtyWatch(native, pointer, id))133
}134
},135
{ native, id ->136
@Unsafe {137
nativePtyCancel(native, id)138
}139
},140
{ event, selected -> recordExit(event.result, selected) }141
)142
watcher = Some(operation)143
loop.submit(operation)144
}146
private fun recordExit(result: IoResult, selected: Throwable?) {147
watcher = None148
if (isClosing) {149
advanceClose()150
return151
}152
when (completionFailure("watch pseudoterminal child", result, selected)) {153
case Some(val failure) -> exit.publish(PtyExit.Failure(failure))155
case None -> {156
val observed = observeChild()157
if (observed.status == -2L) {158
watchExit()159
return160
}161
val windows = operatingSystem == OperatingSystem.Windows162
if (observed.status < 0L) {163
val status = NativeIoStatus(if (windows) 9 else 5, observed.error)164
exit165
.publish(166
PtyExit.Failure(backendFailure("wait for pseudoterminal child", status))167
)168
} else {169
val status = if (windows || observed.status < 256L)170
ExitStatus.Exited(observed.status.toInt())171
else172
ExitStatus.Signaled((observed.status - 256L).toInt())173
exit.publish(PtyExit.Status(status))174
}175
}176
}177
advanceControl()178
}180
private fun observeChild(): NativePtyWait {181
@Unsafe182
{183
return nativePtyTryWait(pointer)184
}185
}187
private fun advanceControl() {188
if (isClosing) {189
advanceClose()190
return191
}192
if (operatingSystem !=193
OperatingSystem.Windows ||194
console !=195
PtyConsole.Active ||196
operationPending(resizeOperation)197
)198
return199
when (exit.result) {200
case Some(PtyExit.Status(_)) -> endConsole()201
case _ -> {}202
}203
}205
private fun endConsole() {206
console = PtyConsole.Ending207
loop208
.submit(209
CallbackOperation(210
loop, loop.nextOperation(),211
{ native, id ->212
@Unsafe213
{214
return@CallbackOperation nativeStatus(215
id,216
nativePtyEndConsole(native, pointer, id)217
)218
}219
},220
{ _, _ -> },221
{ event, selected ->222
console = PtyConsole.Ended223
when (completionFailure("end pseudoconsole", event.result, selected)) {224
case Some(val failure) -> {225
recordCloseFailure(failure)226
closeFromLoop()227
}229
case None -> advanceClose()230
}231
}232
)233
)234
}236
public override suspend fun close() {237
if (gate.withLock { phase == PtyPhase.Closed }) return238
loop.requireJob(false)239
suspendCoroutine<Unit> { continuation ->240
loop.post { closeOnLoop { failure -> finishUnit(continuation, failure) } }241
}242
}244
fun closeOnLoop(waiter: (Throwable?) -> Unit) {245
val previous = gate246
.withLock {247
val old = phase248
if (old == PtyPhase.Open) phase = PtyPhase.Closing249
old250
}251
if (previous == PtyPhase.Closed) {252
loop.enqueueReady { waiter(None) }253
return254
}255
closeWaiters.add(waiter)256
if (previous == PtyPhase.Closing) return257
val closed = IoClosedException()258
reader.requestFailure(closed)259
writer.requestFailure(closed)260
watcher?.requestFailure(closed)261
resizeOperation?.requestFailure(closed)262
when (exit.result) {263
case None -> exit.publish(PtyExit.Failure(closed))264
case Some(_) -> {}265
}266
advanceClose()267
}269
private fun advanceClose() {270
if (finalizing || !isClosing) return271
val busy = gate.withLock { directions }272
if (!outputDetached && (busy and direction(false)) == 0) {273
outputDetached = true274
@Unsafe275
{276
val status = nativePtyCloseOutput(pointer)277
if (status.code != 0)278
recordCloseFailure(backendFailure("close pseudoterminal output", status))279
}280
}281
if (busy !=282
0 ||283
operationPending(watcher) ||284
operationPending(resizeOperation) ||285
console ==286
PtyConsole.Ending287
)288
return289
finalizing = true290
loop291
.submit(292
CallbackOperation(293
loop, loop.nextOperation(),294
{ native, id ->295
@Unsafe296
{297
return@CallbackOperation nativeStatus(298
id,299
nativePtyClose(native, pointer, id)300
)301
}302
},303
{ _, _ -> },304
{ event, selected ->305
when (completionFailure("close pseudoterminal", event.result, selected)) {306
case Some(val error) -> recordCloseFailure(error)307
case None -> {}308
}309
reader.closeSlot()310
writer.closeSlot()311
gate.withLock { phase = PtyPhase.Closed }312
loop.forget(this)313
for (waiter in closeWaiters)314
loop.enqueueReady { waiter(closeFailure) }315
closeWaiters.clear()316
}317
)318
)319
}321
private fun recordCloseFailure(error: Throwable) {322
closeFailure = Some(323
when (closeFailure) {324
case Some(val primary) -> ResourceUseException(primary, error)325
case None -> error326
}327
)328
}330
public override fun closeFromLoop() {331
closeOnLoop { failure ->332
when (failure) {333
case Some(val error) -> loop.cleanupFailed(error)334
case None -> {}335
}336
}337
}338
}340
private fun direction(writing: Boolean): Int = if (writing) 2 else 1342
private fun operationPending(operation: CallbackOperation?): Boolean = when (operation) {343
case Some(_) -> true344
case None -> false345
}