2015-05-05 15:02:11 +02:00
|
|
|
/**
|
2016-02-23 12:58:39 +01:00
|
|
|
* Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
|
2015-05-05 15:02:11 +02:00
|
|
|
*/
|
2016-02-16 17:47:27 +01:00
|
|
|
package akka.stream.scaladsl
|
2015-05-05 15:02:11 +02:00
|
|
|
|
|
|
|
|
import java.nio.ByteOrder
|
|
|
|
|
|
2016-01-20 10:00:37 +02:00
|
|
|
import akka.NotUsed
|
2016-05-24 18:10:44 +09:00
|
|
|
import akka.stream.impl.Stages.DefaultAttributes
|
|
|
|
|
import akka.stream.{ Attributes, Inlet, Outlet, FlowShape }
|
2015-05-05 15:02:11 +02:00
|
|
|
import akka.stream.stage._
|
2016-02-16 17:47:27 +01:00
|
|
|
import akka.util.{ ByteIterator, ByteString }
|
2015-05-05 15:02:11 +02:00
|
|
|
|
|
|
|
|
import scala.annotation.tailrec
|
|
|
|
|
|
|
|
|
|
object Framing {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Creates a Flow that handles decoding a stream of unstructured byte chunks into a stream of frames where the
|
|
|
|
|
* incoming chunk stream uses a specific byte-sequence to mark frame boundaries.
|
|
|
|
|
*
|
2016-02-02 08:45:41 +01:00
|
|
|
* The decoded frames will not include the separator sequence.
|
2015-05-05 15:02:11 +02:00
|
|
|
*
|
|
|
|
|
* If there are buffered bytes (an incomplete frame) when the input stream finishes and ''allowTruncation'' is set to
|
|
|
|
|
* false then this Flow will fail the stream reporting a truncated frame.
|
|
|
|
|
*
|
|
|
|
|
* @param delimiter The byte sequence to be treated as the end of the frame.
|
2016-02-16 17:47:27 +01:00
|
|
|
* @param allowTruncation If `false`, then when the last frame being decoded contains no valid delimiter this Flow
|
2015-05-05 15:02:11 +02:00
|
|
|
* fails the stream instead of returning a truncated frame.
|
|
|
|
|
* @param maximumFrameLength The maximum length of allowed frames while decoding. If the maximum length is
|
|
|
|
|
* exceeded this Flow will fail the stream.
|
|
|
|
|
*/
|
2016-01-20 10:00:37 +02:00
|
|
|
def delimiter(delimiter: ByteString, maximumFrameLength: Int, allowTruncation: Boolean = false): Flow[ByteString, ByteString, NotUsed] =
|
2016-05-24 18:10:44 +09:00
|
|
|
Flow[ByteString].via(new DelimiterFramingStage(delimiter, maximumFrameLength, allowTruncation))
|
2015-05-05 15:02:11 +02:00
|
|
|
.named("delimiterFraming")
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Creates a Flow that decodes an incoming stream of unstructured byte chunks into a stream of frames, assuming that
|
|
|
|
|
* incoming frames have a field that encodes their length.
|
|
|
|
|
*
|
|
|
|
|
* If the input stream finishes before the last frame has been fully decoded this Flow will fail the stream reporting
|
|
|
|
|
* a truncated frame.
|
|
|
|
|
*
|
|
|
|
|
* @param fieldLength The length of the "size" field in bytes
|
|
|
|
|
* @param fieldOffset The offset of the field from the beginning of the frame in bytes
|
|
|
|
|
* @param maximumFrameLength The maximum length of allowed frames while decoding. If the maximum length is exceeded
|
|
|
|
|
* this Flow will fail the stream. This length *includes* the header (i.e the offset and
|
|
|
|
|
* the length of the size field)
|
|
|
|
|
* @param byteOrder The ''ByteOrder'' to be used when decoding the field
|
|
|
|
|
*/
|
|
|
|
|
def lengthField(fieldLength: Int,
|
|
|
|
|
fieldOffset: Int = 0,
|
|
|
|
|
maximumFrameLength: Int,
|
2016-01-20 10:00:37 +02:00
|
|
|
byteOrder: ByteOrder = ByteOrder.LITTLE_ENDIAN): Flow[ByteString, ByteString, NotUsed] = {
|
2015-05-05 15:02:11 +02:00
|
|
|
require(fieldLength >= 1 && fieldLength <= 4, "Length field length must be 1, 2, 3 or 4.")
|
2016-04-17 23:01:46 +08:00
|
|
|
Flow[ByteString].via(new LengthFieldFramingStage(fieldLength, fieldOffset, maximumFrameLength, byteOrder))
|
2015-05-05 15:02:11 +02:00
|
|
|
.named("lengthFieldFraming")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns a BidiFlow that implements a simple framing protocol. This is a convenience wrapper over [[Framing#lengthField]]
|
|
|
|
|
* and simply attaches a length field header of four bytes (using big endian encoding) to outgoing messages, and decodes
|
|
|
|
|
* such messages in the inbound direction. The decoded messages do not contain the header.
|
|
|
|
|
*
|
|
|
|
|
* This BidiFlow is useful if a simple message framing protocol is needed (for example when TCP is used to send
|
|
|
|
|
* individual messages) but no compatibility with existing protocols is necessary.
|
|
|
|
|
*
|
|
|
|
|
* The encoded frames have the layout
|
|
|
|
|
* {{{
|
|
|
|
|
* [4 bytes length field, Big Endian][User Payload]
|
|
|
|
|
* }}}
|
|
|
|
|
* The length field encodes the length of the user payload excluding the header itself.
|
|
|
|
|
*
|
|
|
|
|
* @param maximumMessageLength Maximum length of allowed messages. If sent or received messages exceed the configured
|
|
|
|
|
* limit this BidiFlow will fail the stream. The header attached by this BidiFlow are not
|
|
|
|
|
* included in this limit.
|
|
|
|
|
*/
|
2016-01-20 10:00:37 +02:00
|
|
|
def simpleFramingProtocol(maximumMessageLength: Int): BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = {
|
2016-03-09 13:28:56 +01:00
|
|
|
BidiFlow.fromFlowsMat(simpleFramingProtocolEncoder(maximumMessageLength), simpleFramingProtocolDecoder(maximumMessageLength))(Keep.left)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Protocol decoder that is used by [[Framing#simpleFramingProtocol]]
|
|
|
|
|
*/
|
|
|
|
|
def simpleFramingProtocolDecoder(maximumMessageLength: Int): Flow[ByteString, ByteString, NotUsed] =
|
|
|
|
|
lengthField(4, 0, maximumMessageLength + 4, ByteOrder.BIG_ENDIAN).map(_.drop(4))
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Protocol encoder that is used by [[Framing#simpleFramingProtocol]]
|
|
|
|
|
*/
|
|
|
|
|
def simpleFramingProtocolEncoder(maximumMessageLength: Int): Flow[ByteString, ByteString, NotUsed] =
|
|
|
|
|
Flow[ByteString].transform(() ⇒ new PushStage[ByteString, ByteString] {
|
2015-05-05 15:02:11 +02:00
|
|
|
override def onPush(message: ByteString, ctx: Context[ByteString]): SyncDirective = {
|
2016-02-01 12:52:23 +01:00
|
|
|
val msgSize = message.size
|
|
|
|
|
if (msgSize > maximumMessageLength)
|
|
|
|
|
ctx.fail(new FramingException(s"Maximum allowed message size is $maximumMessageLength but tried to send $msgSize bytes"))
|
2015-05-05 15:02:11 +02:00
|
|
|
else {
|
2016-02-01 12:52:23 +01:00
|
|
|
val header = ByteString((msgSize >> 24) & 0xFF, (msgSize >> 16) & 0xFF, (msgSize >> 8) & 0xFF, msgSize & 0xFF)
|
2015-05-05 15:02:11 +02:00
|
|
|
ctx.push(header ++ message)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
class FramingException(msg: String) extends RuntimeException(msg)
|
|
|
|
|
|
2016-02-01 12:52:23 +01:00
|
|
|
private final val bigEndianDecoder: (ByteIterator, Int) ⇒ Int = (bs, length) ⇒ {
|
|
|
|
|
var count = length
|
|
|
|
|
var decoded = 0
|
|
|
|
|
while (count > 0) {
|
|
|
|
|
decoded <<= 8
|
|
|
|
|
decoded |= bs.next().toInt & 0xFF
|
|
|
|
|
count -= 1
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
2016-02-01 12:52:23 +01:00
|
|
|
decoded
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
|
2016-02-01 12:52:23 +01:00
|
|
|
private final val littleEndianDecoder: (ByteIterator, Int) ⇒ Int = (bs, length) ⇒ {
|
|
|
|
|
val highestOctet = (length - 1) << 3
|
|
|
|
|
val Mask = ((1L << (length << 3)) - 1).toInt
|
|
|
|
|
var count = length
|
|
|
|
|
var decoded = 0
|
|
|
|
|
while (count > 0) {
|
|
|
|
|
decoded >>>= 8
|
|
|
|
|
decoded += (bs.next().toInt & 0xFF) << highestOctet
|
|
|
|
|
count -= 1
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
2016-02-01 12:52:23 +01:00
|
|
|
decoded & Mask
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private class DelimiterFramingStage(val separatorBytes: ByteString, val maximumLineBytes: Int, val allowTruncation: Boolean)
|
2016-05-24 18:10:44 +09:00
|
|
|
extends GraphStage[FlowShape[ByteString, ByteString]] {
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-05-24 18:10:44 +09:00
|
|
|
val in = Inlet[ByteString]("DelimiterFramingStage.in")
|
|
|
|
|
val out = Outlet[ByteString]("DelimiterFramingStage.out")
|
|
|
|
|
override val shape: FlowShape[ByteString, ByteString] = FlowShape(in, out)
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-05-24 18:10:44 +09:00
|
|
|
override def initialAttributes: Attributes = DefaultAttributes.delimiterFraming
|
|
|
|
|
override def toString: String = "DelimiterFraming"
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-05-24 18:10:44 +09:00
|
|
|
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler {
|
|
|
|
|
private val firstSeparatorByte = separatorBytes.head
|
|
|
|
|
private var buffer = ByteString.empty
|
|
|
|
|
private var nextPossibleMatch = 0
|
|
|
|
|
|
|
|
|
|
override def onPush(): Unit = {
|
|
|
|
|
buffer ++= grab(in)
|
|
|
|
|
doParse()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
override def onPull(): Unit = doParse()
|
|
|
|
|
|
|
|
|
|
override def onUpstreamFinish(): Unit = {
|
|
|
|
|
if (buffer.isEmpty) {
|
|
|
|
|
completeStage()
|
|
|
|
|
} else if (isAvailable(out)) {
|
|
|
|
|
doParse()
|
|
|
|
|
} // else swallow the termination and wait for pull
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private def tryPull(): Unit = {
|
|
|
|
|
if (isClosed(in)) {
|
|
|
|
|
if (allowTruncation) {
|
|
|
|
|
push(out, buffer)
|
|
|
|
|
completeStage()
|
|
|
|
|
} else
|
|
|
|
|
failStage(new FramingException(
|
|
|
|
|
"Stream finished but there was a truncated final frame in the buffer"))
|
|
|
|
|
} else pull(in)
|
|
|
|
|
}
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-05-24 18:10:44 +09:00
|
|
|
@tailrec
|
|
|
|
|
private def doParse(): Unit = {
|
|
|
|
|
val possibleMatchPos = buffer.indexOf(firstSeparatorByte, from = nextPossibleMatch)
|
|
|
|
|
if (possibleMatchPos > maximumLineBytes)
|
|
|
|
|
failStage(new FramingException(s"Read ${buffer.size} bytes " +
|
|
|
|
|
s"which is more than $maximumLineBytes without seeing a line terminator"))
|
|
|
|
|
else if (possibleMatchPos == -1) {
|
|
|
|
|
if (buffer.size > maximumLineBytes)
|
|
|
|
|
failStage(new FramingException(s"Read ${buffer.size} bytes " +
|
|
|
|
|
s"which is more than $maximumLineBytes without seeing a line terminator"))
|
|
|
|
|
else {
|
|
|
|
|
// No matching character, we need to accumulate more bytes into the buffer
|
|
|
|
|
nextPossibleMatch = buffer.size
|
|
|
|
|
tryPull()
|
|
|
|
|
}
|
2015-05-05 15:02:11 +02:00
|
|
|
} else if (possibleMatchPos + separatorBytes.size > buffer.size) {
|
|
|
|
|
// We have found a possible match (we found the first character of the terminator
|
|
|
|
|
// sequence) but we don't have yet enough bytes. We remember the position to
|
|
|
|
|
// retry from next time.
|
|
|
|
|
nextPossibleMatch = possibleMatchPos
|
2016-05-24 18:10:44 +09:00
|
|
|
tryPull()
|
|
|
|
|
} else if (buffer.slice(possibleMatchPos, possibleMatchPos + separatorBytes.size) == separatorBytes) {
|
|
|
|
|
// Found a match
|
|
|
|
|
val parsedFrame = buffer.slice(0, possibleMatchPos).compact
|
|
|
|
|
buffer = buffer.drop(possibleMatchPos + separatorBytes.size)
|
|
|
|
|
nextPossibleMatch = 0
|
|
|
|
|
if (isClosed(in) && buffer.isEmpty) {
|
|
|
|
|
push(out, parsedFrame)
|
|
|
|
|
completeStage()
|
|
|
|
|
} else push(out, parsedFrame)
|
2015-05-05 15:02:11 +02:00
|
|
|
} else {
|
2016-05-24 18:10:44 +09:00
|
|
|
// possibleMatchPos was not actually a match
|
|
|
|
|
nextPossibleMatch += 1
|
|
|
|
|
doParse()
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
}
|
2016-05-24 18:10:44 +09:00
|
|
|
setHandlers(in, out, this)
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-01 12:52:23 +01:00
|
|
|
private final class LengthFieldFramingStage(
|
2015-05-05 15:02:11 +02:00
|
|
|
val lengthFieldLength: Int,
|
|
|
|
|
val lengthFieldOffset: Int,
|
|
|
|
|
val maximumFrameLength: Int,
|
2016-04-17 23:01:46 +08:00
|
|
|
val byteOrder: ByteOrder) extends GraphStage[FlowShape[ByteString, ByteString]] {
|
2015-05-05 15:02:11 +02:00
|
|
|
private val minimumChunkSize = lengthFieldOffset + lengthFieldLength
|
2016-02-01 12:52:23 +01:00
|
|
|
private val intDecoder = byteOrder match {
|
|
|
|
|
case ByteOrder.BIG_ENDIAN ⇒ bigEndianDecoder
|
|
|
|
|
case ByteOrder.LITTLE_ENDIAN ⇒ littleEndianDecoder
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
|
2016-04-17 23:01:46 +08:00
|
|
|
val in = Inlet[ByteString]("LengthFieldFramingStage.in")
|
|
|
|
|
val out = Outlet[ByteString]("LengthFieldFramingStage.out")
|
|
|
|
|
override val shape: FlowShape[ByteString, ByteString] = FlowShape(in, out)
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-04-17 23:01:46 +08:00
|
|
|
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler {
|
|
|
|
|
private var buffer = ByteString.empty
|
|
|
|
|
private var frameSize = Int.MaxValue
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-04-17 23:01:46 +08:00
|
|
|
/**
|
|
|
|
|
* push, and reset frameSize and buffer
|
|
|
|
|
*
|
|
|
|
|
*/
|
|
|
|
|
private def pushFrame() = {
|
|
|
|
|
val emit = buffer.take(frameSize).compact
|
2016-02-01 12:52:23 +01:00
|
|
|
buffer = buffer.drop(frameSize)
|
|
|
|
|
frameSize = Int.MaxValue
|
2016-04-17 23:01:46 +08:00
|
|
|
push(out, emit)
|
|
|
|
|
if (buffer.isEmpty && isClosed(in)) {
|
|
|
|
|
completeStage()
|
|
|
|
|
}
|
2016-02-01 12:52:23 +01:00
|
|
|
}
|
|
|
|
|
|
2016-04-17 23:01:46 +08:00
|
|
|
/**
|
|
|
|
|
* try to push downstream, if failed then try to pull upstream
|
|
|
|
|
*
|
|
|
|
|
*/
|
|
|
|
|
private def tryPushFrame() = {
|
|
|
|
|
val buffSize = buffer.size
|
|
|
|
|
if (buffSize >= frameSize) {
|
|
|
|
|
pushFrame()
|
|
|
|
|
} else if (buffSize >= minimumChunkSize) {
|
|
|
|
|
val parsedLength = intDecoder(buffer.iterator.drop(lengthFieldOffset), lengthFieldLength)
|
|
|
|
|
frameSize = parsedLength + minimumChunkSize
|
|
|
|
|
if (frameSize > maximumFrameLength) {
|
|
|
|
|
failStage(new FramingException(s"Maximum allowed frame size is $maximumFrameLength but decoded frame header reported size $frameSize"))
|
|
|
|
|
} else if (buffSize >= frameSize) {
|
|
|
|
|
pushFrame()
|
|
|
|
|
} else tryPull()
|
|
|
|
|
} else tryPull()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private def tryPull() = {
|
|
|
|
|
if (isClosed(in)) {
|
|
|
|
|
failStage(new FramingException("Stream finished but there was a truncated final frame in the buffer"))
|
|
|
|
|
} else pull(in)
|
|
|
|
|
}
|
2015-05-05 15:02:11 +02:00
|
|
|
|
2016-04-17 23:01:46 +08:00
|
|
|
override def onPush(): Unit = {
|
|
|
|
|
buffer ++= grab(in)
|
|
|
|
|
tryPushFrame()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
override def onPull() = tryPushFrame()
|
|
|
|
|
|
|
|
|
|
override def onUpstreamFinish(): Unit = {
|
|
|
|
|
if (buffer.isEmpty) {
|
|
|
|
|
completeStage()
|
|
|
|
|
} else if (isAvailable(out)) {
|
|
|
|
|
tryPushFrame()
|
|
|
|
|
} // else swallow the termination and wait for pull
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setHandlers(in, out, this)
|
|
|
|
|
}
|
2015-05-05 15:02:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|