scoop:scoop.http:0.1.0
src/websocket/frames/sequence.scoop
Selected production source · src/websocket/frames/sequence.scoop
1
package scoop.http3
internal class WebSocketSequence(private val compressionEnabled: Boolean, private val maxBytes: Long) : Closeable {4
private var message: WebSocketMessageType? = None5
private var validator: WebSocketMessageValidator? = None6
private var bytes: Long = 0L7
var hasCloseFrame: Boolean = false8
val isMessageOpen: Boolean get() = when (message) { case Some(_) -> true; case None -> false }10
fun check(head: WebSocketFrameHead) {11
if (webSocketControl(head.opcode)) {12
if (!head.isFinal || head.isCompressed || head.payloadLength > 125L)13
webSocketFrameError("control frames require FIN, no RSV1 and at most 125 payload bytes")14
if (hasCloseFrame && head.opcode == WebSocketOpcode.Close) webSocketFrameError("duplicate Close frame")15
return16
}17
if (hasCloseFrame) webSocketFrameError("data frame after Close")18
if (head.opcode == WebSocketOpcode.Continuation) {19
if (!isMessageOpen || head.isCompressed) webSocketFrameError("invalid continuation frame")20
} else {21
if (isMessageOpen) webSocketFrameError("new data frame before the previous message ended")22
if (head.isCompressed && !compressionEnabled) webSocketFrameError("RSV1 requires negotiated compression")23
}24
if (head.payloadLength > maxBytes - bytes) throw WebSocketFrameException(1009U, "message exceeds its wire byte limit")25
}27
fun begin(head: WebSocketFrameHead) {28
if (webSocketControl(head.opcode)) return29
if (head.opcode != WebSocketOpcode.Continuation) {30
val type = if (head.opcode == WebSocketOpcode.Text) WebSocketMessageType.Text else WebSocketMessageType.Binary31
val created: WebSocketMessageValidator? = if (head.isCompressed) None else Some(WebSocketMessageValidator(type, maxBytes))32
message = Some(type)33
validator = created34
}35
bytes += head.payloadLength36
}38
fun receive(head: WebSocketFrameHead, data: Array<Byte>) {39
if (webSocketControl(head.opcode)) return40
when (validator) { case Some(val value) -> value.receive(data); case None -> {} }41
}43
fun finish(head: WebSocketFrameHead) {44
if (webSocketControl(head.opcode) || !head.isFinal) return45
when (validator) { case Some(val value) -> value.finish(); case None -> {} }46
close()47
}49
fun closeFrame() { close(); hasCloseFrame = true }51
public override fun close() {52
val owned = validator53
validator = None54
message = None55
bytes = 0L56
when (owned) { case Some(val value) -> value.close(); case None -> {} }57
}58
}