Scoop API

scoop:scoop.http.asyncio:0.1.0

src/http2_idle_timer.scoop

Selected production source · src/http2_idle_timer.scoop

1package scoop.http.asyncio
3import scoop.platform.time.MonotonicTimeSource
4import scoop.time.Duration
6internal fun startH2Idle(idle: H2Idle) {
7 val state = idle.state
8 val scope =
9 state.lock.withLock {
10 if (idle.active && !state.closing)
11 state.ownerScope
12 else
13 None
14 }
15 if (!present(scope)) {
16 finishH2Idle(idle);
17 return
18 }
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.active
26 }
27 if (stopped)
28 timer.cancel()
29 } catch (error: Throwable) {
30 state.lock.withLock { terminateH2(state, error) }
31 finishH2Idle(idle)
32 }
35private fun launchH2Idle(scope: CoroutineScope, idle: H2Idle): Job {
36 val state = idle.state
37 val loop = state.loop
38 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 task
60 }
63private suspend fun runH2Idle(idle: H2Idle) {
64 val state = idle.state
65 while (true) {
66 val remaining =
67 state.lock.withLock {
68 if (idle.active && !state.closing)
69 Some(idle.clock.remaining(MonotonicTimeSource.markNow()))
70 else
71 None
72 }
73 if (remaining == None)
74 return
75 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 false
82 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 return
94 }
97private fun finishH2Idle(idle: H2Idle) {
98 val state = idle.state
99 val stream = idle.stream
100 val actions = ArrayList<() -> Unit>()
101 state.lock.withLock {
102 if (idle.finished)
103 return@withLock
104 idle.finished = true;
105 idle.active = false;
106 idle.timer = None
107 if (present(stream.readIdle) && stream.readIdle!! === idle)
108 stream.readIdle = None
109 if (present(stream.writeIdle) && stream.writeIdle!! === idle)
110 stream.writeIdle = None
111 stream.idleTimers -= 1L;
112 state.idleTimers -= 1L
113 if (stream.idleTimers == 0L) {
114 for (waiter in stream.idleCloseWaiters)
115 actions.add { waiter.resume(Unit) }
116 stream.idleCloseWaiters.clear()
117 }
118 Unit
119 }
120 for (action in actions)
121 action()
122 driveH2(state)