Scoop API

scoop:scoop.http.asyncio:0.1.0

src/websocket/deflate_output.scoop

Selected production source · src/websocket/deflate_output.scoop

1package scoop.http.asyncio
3import scoop.compression.*
4import scoop.http.*
5import scoop.platform.memory.NativeByteBuffer
7internal suspend fun writeWsDeflate(state: WsState, message: WsOutgoing, input: NativeByteBuffer, count: Long): Long {
8 state.lock.withLock {
9 wsOpen(state)
10 startWsDeflateOutput(state, message)
11 val codec = state.deflate!!
12 val bytes = input.readBytes(count)
13 codec.encodingValidator!!.receive(bytes)
14 codec.encoderInput.clear()
15 codec.encoderInput.writeBytes(bytes)
16 }
17 drainWsDeflateOutput(state, message, WsDeflateAction.Process)
18 return count
21internal suspend fun flushWsDeflate(state: WsState, finish: Boolean) {
22 val message = state.lock.withLock {
23 wsOpen(state)
24 val value = state.outgoing!!
25 startWsDeflateOutput(state, value)
26 if (finish) state.deflate!!.encodingValidator!!.finish()
27 value
28 }
29 drainWsDeflateOutput(state, message, if (finish) WsDeflateAction.Finish else WsDeflateAction.Flush)
32private enum WsDeflateAction { Process, Flush, Finish }
34private suspend fun drainWsDeflateOutput(state: WsState, message: WsOutgoing, action: WsDeflateAction) {
35 val codec = state.deflate!!
36 while (true) {
37 val (step, done) = state.lock.withLock {
38 wsOpen(state)
39 codec.encoderOutput.clear()
40 val step = when (action) {
41 case Process -> codec.encoder.process(codec.encoderInput, codec.encoderOutput)
42 case Flush -> codec.encoder.flush(codec.encoderOutput)
43 case Finish -> codec.encoder.finishMessage(codec.encoderOutput)
44 }
45 if (step.state == CompressionState.Finished) {
46 codec.encoderFinished = true
47 val validator = codec.encodingValidator!!
48 codec.encodingValidator = None
49 validator.close()
50 }
51 val done = step.state != CompressionState.NeedOutput &&
52 (action != WsDeflateAction.Process || codec.encoderInput.readableBytes == 0L)
53 (step, done)
54 }
55 if (step.produced != 0L) submitWsWrite(state, WsWriteAction.Data(message, codec.encoderOutput, step.produced))
56 if (done) return
57 }
60private fun startWsDeflateOutput(state: WsState, message: WsOutgoing) {
61 val codec = state.deflate!!
62 if (present(codec.encodingValidator)) return
63 val validator = WebSocketMessageValidator(message.type, Long.MAX_VALUE)
64 try {
65 if (codec.encoderFinished) codec.encoder.nextMessage()
66 codec.encoderFinished = false
67 codec.encodingValidator = Some(validator)
68 } catch (error: Throwable) { throw messageCleanup(Some(error)) { validator.close() }!! }