-
Notifications
You must be signed in to change notification settings - Fork 21
Added akka stream decoding flow and sink #18
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
libraryDependencies ++= Seq( | ||
"com.typesafe.akka" %% "akka-stream" % "2.6.4", | ||
"com.typesafe.akka" %% "akka-testkit" % "2.6.4" % Test | ||
) |
3 changes: 3 additions & 0 deletions
3
modules/akka-stream/src/main/scala/ru/tinkoff/phobos/akka_stream.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package ru.tinkoff.phobos | ||
|
||
object akka_stream extends ops.AkkaStreamOps |
76 changes: 76 additions & 0 deletions
76
modules/akka-stream/src/main/scala/ru/tinkoff/phobos/ops/AkkaStreamOps.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package ru.tinkoff.phobos.ops | ||
|
||
import akka.NotUsed | ||
import akka.stream.scaladsl.{Flow, Keep, Sink} | ||
import javax.xml.stream.XMLStreamConstants | ||
import ru.tinkoff.phobos.decoding._ | ||
import scala.concurrent.Future | ||
|
||
private[phobos] trait AkkaStreamOps { | ||
|
||
/** | ||
* @note - works only for streams emmiting single xml document | ||
* */ | ||
def decodingFlow[A: XmlDecoder](charset: String = "UTF-8"): Flow[Array[Byte], Either[DecodingError, A], NotUsed] = { | ||
val xmlDecoder = XmlDecoder[A] | ||
Flow[Array[Byte]] | ||
.fold(Option.empty[SinkDecoderState[A]]) { (stateOpt, bytes) => | ||
val state = stateOpt.getOrElse(SinkDecoderState.initial(xmlDecoder, charset)) // trick to make this flow reusable (because of mutable Cursor) | ||
import state.{cursor, elementDecoder, xmlStreamReader} | ||
xmlStreamReader.getInputFeeder.feedInput(bytes, 0, bytes.length) | ||
do { | ||
cursor.next() | ||
} while (cursor.getEventType == XMLStreamConstants.DTD || cursor.getEventType == XMLStreamConstants.START_DOCUMENT) | ||
|
||
Some { | ||
state withEncoder { | ||
if (elementDecoder.result(cursor.history).isRight) { | ||
elementDecoder | ||
} else { | ||
elementDecoder.decodeAsElement(cursor, xmlDecoder.localname, xmlDecoder.namespaceuri) | ||
} | ||
} | ||
} | ||
} | ||
.map { | ||
case None => | ||
throw DecodingError("Got an internal error while decoding byte stream", Nil) | ||
|
||
case Some(SinkDecoderState(_, cursor, elementDecoder)) => | ||
elementDecoder.result(cursor.history) | ||
} | ||
} | ||
|
||
/** | ||
* @note - works only for streams emmiting single xml document | ||
* */ | ||
def decodingFlowUnsafe[A: XmlDecoder](charset: String = "UTF-8"): Flow[Array[Byte], A, NotUsed] = | ||
decodingFlow(charset).map(_.fold(throw _, identity)) | ||
|
||
def decodingSink[A: XmlDecoder](charset: String = "UTF-8"): Sink[Array[Byte], Future[Either[DecodingError, A]]] = | ||
decodingFlow(charset).toMat(Sink.head)(Keep.right) | ||
|
||
def decodingSinkUnsafe[A: XmlDecoder](charset: String = "UTF-8"): Sink[Array[Byte], Future[A]] = | ||
decodingFlowUnsafe(charset).toMat(Sink.head)(Keep.right) | ||
} | ||
|
||
private[phobos] case class SinkDecoderState[A]( | ||
xmlStreamReader: XmlStreamReader, | ||
cursor: Cursor, | ||
elementDecoder: ElementDecoder[A] | ||
) { | ||
def withEncoder(that: ElementDecoder[A]): SinkDecoderState[A] = copy(elementDecoder = that) | ||
} | ||
|
||
private[phobos] object SinkDecoderState { | ||
|
||
def initial[A](xmlDecoder: XmlDecoder[A], charset: String): SinkDecoderState[A] = { | ||
val sr: XmlStreamReader = XmlDecoder.createStreamReader(charset) | ||
val cursor = new Cursor(sr) | ||
SinkDecoderState( | ||
xmlStreamReader = sr, | ||
cursor = cursor, | ||
elementDecoder = xmlDecoder.elementdecoder | ||
) | ||
} | ||
} |
138 changes: 138 additions & 0 deletions
138
modules/akka-stream/src/test/scala/ru/tinkoff/phobos/test/AkkaStreamTest.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
package ru.tinkoff.phobos.test | ||
|
||
import akka.actor.ActorSystem | ||
import akka.stream.scaladsl.{Sink, Source} | ||
import akka.stream.{Materializer, SystemMaterializer} | ||
import akka.testkit.TestKit | ||
import org.scalatest.BeforeAndAfterAll | ||
import org.scalatest.concurrent.ScalaFutures | ||
import org.scalatest.wordspec.AsyncWordSpecLike | ||
import ru.tinkoff.phobos.akka_stream._ | ||
import ru.tinkoff.phobos.annotations.{ElementCodec, XmlCodec} | ||
import ru.tinkoff.phobos.syntax.text | ||
|
||
import scala.concurrent.Await | ||
import scala.concurrent.duration._ | ||
import scala.util.Failure | ||
|
||
class AkkaStreamTest | ||
extends TestKit(ActorSystem("akka-stream-test")) with AsyncWordSpecLike with ScalaFutures with BeforeAndAfterAll { | ||
|
||
override implicit val patienceConfig: PatienceConfig = PatienceConfig(timeout = 5.seconds, interval = 200.millis) | ||
private implicit lazy val mat: Materializer = SystemMaterializer(system).materializer | ||
|
||
override def beforeAll(): Unit = { | ||
system.registerOnTermination { | ||
mat.shutdown() | ||
} | ||
} | ||
|
||
override def afterAll(): Unit = system.terminate() | ||
|
||
import AkkaStreamTest._ | ||
|
||
"Akka decodingFlow" should { | ||
"decode case classes correctly" in { | ||
|
||
val xml = """ | ||
|<foo> | ||
| <qux>1234</qux> | ||
| <bars>2</bars> | ||
| <maybeBar>1</maybeBar> | ||
| <bars>3</bars> | ||
|</foo> | ||
|""".stripMargin | ||
|
||
val foo = Foo(1234, Some(Bar(1)), List(Bar(2), Bar(3))) | ||
val bytesSource = Source.fromIterator(() => xml.grouped(5).map(_.getBytes)) | ||
|
||
val result = bytesSource | ||
.via(decodingFlow[Foo]()) | ||
.runWith(Sink.head) | ||
.futureValue | ||
|
||
assert(result.isRight) | ||
assert(result contains foo) | ||
} | ||
|
||
"raise correct errors" in { | ||
|
||
val xml = """ | ||
|<foo> | ||
| <quxar>safgd</quxar> | ||
| <bars>2</bars> | ||
| <maybeBar>1</maybeBar> | ||
| <bars>3</bars> | ||
|</foo> | ||
|""".stripMargin | ||
|
||
val bytesSource = Source.fromIterator(() => xml.grouped(5).map(_.getBytes)) | ||
|
||
val result = bytesSource | ||
.via(decodingFlow[Foo]()) | ||
.runWith(Sink.head) | ||
.futureValue | ||
|
||
assert(result.isLeft) | ||
} | ||
|
||
"is reusable" in { | ||
|
||
val foo = Foo(1234, Some(Bar(1)), List(Bar(2), Bar(3))) | ||
val xml = """ | ||
|<foo> | ||
| <qux>1234</qux> | ||
| <bars>2</bars> | ||
| <maybeBar>1</maybeBar> | ||
| <bars>3</bars> | ||
|</foo> | ||
|""".stripMargin | ||
|
||
val fooFlow = decodingFlow[Foo]() | ||
|
||
def bytesSource = Source.fromIterator(() => xml.grouped(5).map(_.getBytes)) | ||
|
||
val result = Source(1 to 20) | ||
.mapAsyncUnordered(parallelism = Runtime.getRuntime.availableProcessors()) { _ => | ||
bytesSource | ||
.via(fooFlow) | ||
.runWith(Sink.head) | ||
} | ||
.runWith(Sink.seq) | ||
.futureValue | ||
|
||
assert(result.forall(_.contains(foo))) | ||
} | ||
} | ||
|
||
"Akka decodingFlowUnsafe" should { | ||
"decode case classes correctly" in { | ||
|
||
val xml = """ | ||
|<foo> | ||
| <qux>1234</qux> | ||
| <bars>2</bars> | ||
| <maybeBar>1</maybeBar> | ||
| <bars>3</bars> | ||
|</foo> | ||
|""".stripMargin | ||
|
||
val foo = Foo(1234, Some(Bar(1)), List(Bar(2), Bar(3))) | ||
val bytesSource = Source.fromIterator(() => xml.grouped(5).map(_.getBytes)) | ||
|
||
val result = bytesSource | ||
.via(decodingFlowUnsafe[Foo]()) | ||
.runWith(Sink.head) | ||
.futureValue | ||
|
||
assert(result == foo) | ||
} | ||
} | ||
} | ||
|
||
object AkkaStreamTest { | ||
@ElementCodec | ||
case class Bar(@text txt: Int) | ||
@XmlCodec("foo") | ||
case class Foo(qux: Int, maybeBar: Option[Bar], bars: List[Bar]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Как насчёт сделать такой же трюк для мониска заодно?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А для чего этот трюк?