scoop:scoop.http.asyncio:0.1.0
src/http2_idle_timer.scoop
Selected production source · src/http2_idle_timer.scoop
1
package scoop.http.asyncio3
import scoop.platform.time.MonotonicTimeSource4
import scoop.time.Duration6
internal fun startH2Idle(idle: H2Idle) {7
val state = idle.state8
val scope =9
state.lock.withLock {10
if (idle.active && !state.closing)11
state.ownerScope12
else13
None14
}15
if (!present(scope)) {16
finishH2Idle(idle);17
return18
}19
try {20
val timer = launchH2Idle(scope!!, idle)21
val stopped =22
state.lock.withLock {23
if (idle.active)24
idle.timer = Some(timer)25
!idle.active26
}27
if (stopped)28
timer.cancel()29
} catch (error: Throwable) {30
state.lock.withLock { terminateH2(state, error) }31
finishH2Idle(idle)32
}33
}35
private fun launchH2Idle(scope: CoroutineScope, idle: H2Idle): Job {36
val state = idle.state37
val loop = state.loop38
val claimed = AtomicBoolean(false)39
context(loop) {40
val task =41
scope.launch {42
if (claimed.compareAndSet(false, true)) {43
try {44
runH2Idle(idle)45
}46
catch (_: CancellationException) {}47
catch (error: Throwable) {48
state.lock.withLock { terminateH2(state, error) }49
}50
finally {51
finishH2Idle(idle)52
}53
}54
}55
task.invokeOnCancellation {56
_ -> if (claimed.compareAndSet(false, true))57
finishH2Idle(idle)58
}59
return task60
}61
}63
private suspend fun runH2Idle(idle: H2Idle) {64
val state = idle.state65
while (true) {66
val remaining =67
state.lock.withLock {68
if (idle.active && !state.closing)69
Some(idle.clock.remaining(MonotonicTimeSource.markNow()))70
else71
None72
}73
if (remaining == None)74
return75
if (remaining!! > Duration.ZERO)76
state.loop.sleep(remaining!!)77
val actions = ArrayList<() -> Unit>()78
val expired =79
state.lock.withLock {80
if (!idle.active || state.closing)81
false82
else {83
val error = idle.clock.expired(MonotonicTimeSource.markNow())84
if (present(error))85
resetH2Stream(state, idle.stream, error!!, 8U, actions)86
present(error)87
}88
}89
for (action in actions)90
action()91
driveH2(state)92
if (expired)93
return94
}95
}97
private fun finishH2Idle(idle: H2Idle) {98
val state = idle.state99
val stream = idle.stream100
val actions = ArrayList<() -> Unit>()101
state.lock.withLock {102
if (idle.finished)103
return@withLock104
idle.finished = true;105
idle.active = false;106
idle.timer = None107
if (present(stream.readIdle) && stream.readIdle!! === idle)108
stream.readIdle = None109
if (present(stream.writeIdle) && stream.writeIdle!! === idle)110
stream.writeIdle = None111
stream.idleTimers -= 1L;112
state.idleTimers -= 1L113
if (stream.idleTimers == 0L) {114
for (waiter in stream.idleCloseWaiters)115
actions.add { waiter.resume(Unit) }116
stream.idleCloseWaiters.clear()117
}118
Unit119
}120
for (action in actions)121
action()122
driveH2(state)123
}