<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Visokih on Medium]]></title>
        <description><![CDATA[Stories by Andrew Visokih on Medium]]></description>
        <link>https://medium.com/@andrew.visokih_88808?source=rss-46d6786ef29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qzRZPpqEMR2UsA_G</url>
            <title>Stories by Andrew Visokih on Medium</title>
            <link>https://medium.com/@andrew.visokih_88808?source=rss-46d6786ef29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:24:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrew.visokih_88808/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java/Kotlin/GraalVm and Golang.]]></title>
            <link>https://blog.devgenius.io/java-kotlin-graalvm-and-golang-7fb979ef4c03?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb979ef4c03</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 11:50:04 GMT</pubDate>
            <atom:updated>2022-12-21T21:11:59.562Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Java/Kotlin/GraalVm and Golang. What is the situation. The most performant frameworks, memory consuming, easy to develop.</strong></h3><p>There are a lot of stories that Golang is faster then Java. I saw many benchmarks, that tells nothing and just compare particular frameworks.</p><p>Currently industry standard in Java is Spring. It is a monster and comparison with low weight Golang Frameworks doesn’t make any sense. Main goal of Spring is to standardize development of huge application and give ability for developers just pointed on busies logic. Opposite, Golang is used for micro services. It doesn’t have such huge frameworks.</p><p>Also let’s look on <a href="https://www.techempower.com/benchmark">https://www.techempower.com/benchmark</a>. There are plenty of low weight Java frameworks in first 20 and there no Golang frameworks. Java is highly customizable and design to run everywhere. Also java has GraalVm to solve AOT problem and reduce memory consuming, so that infrastructure costs.</p><p>I want to answer this question at least for myself :).</p><p>Will try to point on the most low weight and performant frameworks in 3 areas:</p><ol><li>Http server</li><li>Serialization/Deserialization</li><li>Data Base driver</li></ol><p>Perform analysis on 3 areas: Easy to Develop, Memory Consuming and Performance</p><p>Scenario will be useless form business prospective but as full as possible with technical scenarios:</p><ul><li>send request for user creation with 4 fields: id, name, email, age</li><li>Deserialize request</li><li>create user in Pstgres DB</li><li>select user from DB</li><li>delete user</li><li>Serialize selected user</li><li>Send response</li></ul><h3><strong>Jvm HTTP solution</strong></h3><p>For Development will take Kotlin as a primary programming language</p><p>Regarding HTTP server without doubts will take plain Netty Server without any additional framework + Reactor to conveniently use Mono and Flux. One of the leaders of <a href="https://www.techempower.com/benchmark">techempower</a> benchmark from java side VertX uses it. Also I use it on daily basis, pretty familiar with it :)</p><p>Will avoid Proxies, Beans and other stuff usual for java. Just a manual startup.<br>For my build.gradle will add next lines:</p><pre>implementation(platform(&quot;io.projectreactor:reactor-bom:2022.0.0-RC1&quot;))<br>implementation(&quot;io.projectreactor.netty:reactor-netty-core&quot;)<br>implementation(&quot;io.projectreactor.netty:reactor-netty-http&quot;)</pre><p>main file will look like:</p><pre>fun main() {<br>    val port = 8089<br>    val server = HttpServer.create()<br>        .route { routes: HttpServerRoutes -&gt;<br>            routes.post(<br>                &quot;/api&quot;<br>            ) { request, response -&gt; Handler.handle(request, response) }<br>        }<br>        .host(&quot;0.0.0.0&quot;)<br>        .port(port)<br>        .bindNow()<br><br>    println(&quot;Starting on port $port ...&quot;)<br><br>    server.onDispose()<br>        .block()<br>}</pre><p>As I mentioned, my microservice will have single endpoint and going to handle all incoming requests.</p><h3>Jvm Serialization solution</h3><p>T<a href="https://www.techempower.com/benchmark">echempower</a> benchmark has tab, devoted to Serialization. From this tab I can make interesting conclusions. E.g. Vertx is very high in all benchmark, except Serialization. It uses Jackson for this. Might be major of java frameworks are using it. I started looking for something ready and more performant. I found this benchmark: <a href="https://github.com/fabienrenaud/java-json-benchmark">https://github.com/fabienrenaud/java-json-benchmark</a></p><p>According to this benchmark <a href="https://github.com/ngs-doo/dsl-json">dsl-json</a> is the leader of Serialization performance in Java world. Never head about this library. <br>But checking other benchmark, I got that serialization isnot the strongest part of java. :) <a href="https://github.com/kostya/benchmarks">https://github.com/kostya/benchmarks</a><br>You see leaders as expected are Rust and C++. But this lib can consider as fastest. Added to gradle file:</p><pre>implementation(&quot;com.dslplatform:dsl-json-java8:1.9.9&quot;)<br>kapt(&quot;com.dslplatform:dsl-json-java8:1.9.9&quot;)</pre><p>and to the request handler:</p><pre>// Init object mappper<br>val objectMapper = DslJson(Settings.withRuntime&lt;Any&gt;().includeServiceLoader())<br>......................................<br>request.receive()<br>                .aggregate()<br>                .asByteArray()<br>                .map { bytes -&gt; objectMapper.deserialize(UserDto::class.java, bytes.inputStream()) }<br>.......................................................<br>// serialization stuff for the response<br> .map {<br>                    val outputStream = ByteArrayOutputStream()<br>                    objectMapper.serialize(it, outputStream)<br>                    outputStream.toByteArray()<br>                }</pre><p>After this I just tried simple scenario with receiving request with plain json, deserialize it, print to console, serialize again and send response. created docker container and executed apache benchmark:</p><pre>// warm up jvm<br>ab -p performance/test.json -T application/json -c 100 -n 20000 http://localhost:8089/api<br>// regular benchmark<br>ab -p performance/test.json -T application/json -c 100 -n 2000000 http://localhost:8089/api</pre><p>The best RPS was 18K r/s. Middle was about 16K r/s.</p><h3>Adding GraalVm</h3><p>I guess the performance of jvm is high but what about memory usage and artifact size? How can I reduce infrastructure costs? I guess this is the main question for major people, who use java in microservices architecture. Because java is not about low memory consuming. Let’s try to solve this issue with GraalVm …..</p><p>I guess many people can think this way :). For me it is the same as Welcome to the Hell :)</p><p>My goal is to have the single executable binary. I was needed to have static image. Of course by default nothing works for me. :)</p><p>In Oracle documentation i found how to install <a href="https://docs.oracle.com/en/graalvm/enterprise/20/docs/reference-manual/native-image/StaticImages/">https://docs.oracle.com/en/graalvm/enterprise/20/docs/reference-manual/native-image/StaticImages/</a></p><p>Several hours spent to setup musl-gcc compiler and zlib on my Ubuntu. I don’t know how windows users can overcome so many stuff I figure out while installation :(. Finally got it working, but this is not the end of my adventures. I spent time excluding different classes from compilation and</p><pre>--initialize-at-run-time</pre><p>Also libs I use, have a plenty of Proxy clases, that is why was needed to add reflection-config.json and one more flag to the compilation. Netty wasn’t compiled by default. Was needed to investigate there repository and solving problems one by one created this reflection config.</p><pre>-H:ReflectionConfigurationResources=${.}/reflection-config.json</pre><p>with number of initializations inside loke this:</p><pre>..................................<br>{<br>  &quot;name&quot;: &quot;io.netty.channel.epoll.EpollServerSocketChannel&quot;,<br>  &quot;methods&quot;: [<br>    { &quot;name&quot;: &quot;&lt;init&gt;&quot;, &quot;parameterTypes&quot;: [] }<br>  ]<br>},<br>...........................................</pre><p>and also JNI config</p><pre>-H:JNIConfigurationResources=${.}/jni-config.json</pre><p>All this stuff is available in the repository.</p><p>Finally command:</p><pre>export PATH={{TOOLCHAIN_DIR}}/bin:$PATH &amp;&amp; {{JAVA_HOME}}/bin/native-image - static - libc=musl - no-fallback -cp ./build/libs/fast-http-1.0-SNAPSHOT-all.jar -H:Name=app -H:Class=com.fasthttp.MainKt -H:+JNI -H:+ReportUnsupportedElementsAtRuntime</pre><p>has been executed and I’ve got native image. Also installed upx utility to compress Linux binaries and for my Netty server with Serialization lib I had binary with size of 5.5 mb.</p><p>Let’s pack to the docker and execute Apache benchmark. As expected I’ve got results worse then for JIT version in terms of performance.</p><p>The best execution was about 14K r/s. In general it was about 12K r/s. With smaller image performance becomes smaller also. :)</p><h3>JVM data base driver</h3><p>This was the simplest solution. Just visit <a href="https://www.techempower.com/benchmarks/#section=data-r21&amp;test=query">https://www.techempower.com/benchmarks/#section=data-r21&amp;test=query</a>. In benchmarks for dingle query postgres vertx driver is on the second position, for multiple queries it is on the third position. Looks nice, it outperformes major part of c++ and rust libs and it is async. Just add to gradle file:</p><pre>implementation(&quot;io.vertx:vertx-pg-client:4.3.5&quot;)</pre><p>unfortunately for GraalVm version to be compiled was needed to add several libraries:</p><pre>implementation(&quot;com.ongres.scram:common:2.1&quot;)<br>implementation(&quot;com.ongres.scram:client:2.1&quot;)</pre><p>Also for GraalVm version faced an issue with Date serialization. Got failures for DataTypeCodec class while runtime with Locale.Root. I found several explanations of this issue for native run.</p><p>Wasn’t able to solve an issue directly for this class inside lib, that why just overridden it with my own class with the same name and same package :) . Good for java.</p><p>Implementation was pretty straightforward. Created plain SQL constants:</p><pre>const val GET_USER = &quot;&quot;&quot;SELECT * FROM users as u<br>WHERE u.id=%d&quot;&quot;&quot;<br><br>const val INSERT_USER = &quot;&quot;&quot;INSERT INTO users (name, email, age)<br>values (&#39;%s&#39;, &#39;%s&#39;, %d) RETURNING id&quot;&quot;&quot;<br><br>const val DELETE_USER = &quot;&quot;&quot;DELETE FROM users as u<br>WHERE u.id=%d&quot;&quot;&quot;</pre><p>while initialization just create connection:</p><pre>init {<br>    val connectOptions = PgConnectOptions().setPort(5432)<br>        .setHost(&quot;db&quot;)<br>        .setDatabase(&quot;postgres&quot;)<br>        .setUser(&quot;postgres&quot;)<br>        .setPassword(&quot;postgres&quot;);<br>    val poolOptions = PoolOptions().setMaxSize(5)<br>    client = PgPool.client(connectOptions, poolOptions);<br>}</pre><p>Query implementation is also straightforward:</p><pre>val  future: Future&lt;RowSet&lt;Row&gt;&gt; = client<br>    .query(String.format(DELETE_USER, usr.id))<br>    .execute()</pre><p>each query to db should return Mono. But with vertx postgres it returns io.vertx.core.Future. I can’t use Mono.fromFuture() because Vertx future isn’t a Completable future, but looked on code and found I can get CompletionStage from vertx future, so that I can cast this object to mono with Mono.fromCompletionStage(..)</p><pre>Mono.fromCompletionStage(future.toCompletionStage())</pre><p>and after this I can use Mono and Flux stuff for any transformation. Full code is available in the repository.</p><p>Finally got solution working end-to-end. That it for java.</p><h3>Golang HTTP solution</h3><p>Fortunately for Golang there are no so many solutions :). In Go there are usually only one way. But here were 2 solutions. Golang has standart powerful http library. But for performance exists fasthttp lib. Also regarding Techempower benchmark most performant is fiber based on this library. I decided to take fasthttp for my test for this reasons: <a href="https://github.com/valyala/fasthttp">https://github.com/valyala/fasthttp</a>. Pretty the same implementation as for Kotlin:</p><pre>func main() {<br>   fmt.Println(&quot;Starting server on &quot;, &quot;8089&quot;)<br>   err := fasthttp.ListenAndServe(&quot;:8089&quot;, Handle)<br>   if err != nil {<br>      panic(err)<br>   }<br>}</pre><h3>Golang Serialization solution</h3><p>For the serialization I used the same benchmarks as for java. Found <a href="https://jsoniter.com/">https://jsoniter.com/</a>. Per benchmarks the most performant serialize/deserialize lib for golang. It for several places outperformed java version. Also for <a href="https://jsoniter.com/">jsoniter</a> java version exists, but for some reasons it wasn’t mentioned in benchmarks :(.</p><p>Also this lib is compatible with standard library. it is needed only to call this construction:</p><pre>var json = jsoniter.ConfigCompatibleWithStandardLibrary</pre><p>and you can use the usual approach just with higher performance:</p><pre>b := ctx.Request.Body()<br>user := dto.User{}<br>if err := json.Unmarshal(b, &amp;user); err != nil {<br>.........<br></pre><pre>b, err = json.Marshal(&amp;usr)<br>...........</pre><p>Code is available in the repository. Executed Apache Benchmark. Results are even worse then for GraalVm version but pretty near.</p><p>The best execution was about 13K r/s. In general it was about 8K r/s. Interesting, seems Netty does this magic performance. :) . But binary size after compression is twice less 2.5 mb.</p><h3>Golang data base driver</h3><p>I decided to use the same approach as for java. Something low level and high performance for postgres. And coe up with the pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features. Same approach. Created 3 constants and executed plain sql queries. Scan also did manually.</p><p>Just an example. Code is available in repo. Pretty straightforward, no need additional explanations:</p><pre>import . &quot;github.com/jackc/pgx/v5/pgxpool&quot;<br><br>....<br>dbPool, err := New(context.Background(), dbString)<br>.........<br>usr := dto.User{}<br> err = con.QueryRow(ctx, GET_USER, id).Scan(<br>  &amp;usr.Id,<br>  &amp;usr.Username,<br>  &amp;usr.Email,<br>  &amp;usr.Age,<br> )</pre><h3><strong>Results of tests</strong></h3><p>Let’s try to analyze what we have with this exesise:</p><ol><li><strong>Artifact sizes:</strong></li></ol><p>Java JIT: jar file is 12 MB. Of course the result docker container will be bigger. We need to have JVM inside.</p><p>Java AOT(GraalVm): Rough binary has size 49Mb. But after compressing with upx utility I have 11Mb.</p><p>Golang: Rough binary size 14 Mb. After compression it has 5.5Mb</p><p>2. <strong>Docker container size:</strong></p><p>Java JIT: It has the largest container — 306 MB</p><p>Java AOT(GraalVm): 30Mb</p><p>Golang: 17 Mb</p><p>3.<strong> Apache Benchmark:</strong></p><p>I executed next scripts:</p><pre>ab -p performance/test.json -T application/json -c 100 -n 20000 http://localhost:8089/api<br>ab -p performance/test.json -T application/json -c 100 -n 1000000 http://localhost:8089/api</pre><p>First is just to warm up applications. This is important for java. :)</p><p>First I tried to limit RAM with 50 Mb. Java (AOP &amp; JIT) failed with OOM. Golang was ok even 20 Mb without significant performance degradation. It even was OK for 10 Mb RAM.</p><p>Minimum RAM for java was 100Mb. That is why Docker for each applications will start with next settings:</p><pre>docker run -it -d --memory=100m --cpus=4 -p 8089:8089 --network fast-http ${image name}<br><br>// postgres and container should be in the same network</pre><p>Game begins :) :</p><ol><li><strong>Java AOT (GraalVm):</strong></li></ol><pre>Memory usage: <br>  Cold start: &quot;Out of the box it allocates 75 Mb from the beginning&quot;<br>  When tests started: &quot;It was 99 Mb all the time test was running&quot;<br>  CPU: &quot;Intensive usage. Always shown more than 100 %.&quot; - 150 - 250<br>RPS: <br>  1. For first 20K requests it shown 1172 reqests/second<br>  2. For the main benchmark it shown 337  requests/second - seems single instance of postgres is overloaded. But I haven&#39;t seen any high load on postgres side</pre><p>2. Golang:</p><pre>Memory usage: <br>  Cold start: &quot;Out of the box it allocates 2 Mb from the beginning&quot;<br>  When tests started: &quot;It was 22 Mb all the time test was running&quot;<br>  CPU: &quot;High Intensive usage. Always shown more than 100 %.&quot; - 250 - 330<br>RPS: <br>  1. For first 20K requests it shown 259 reqests/second<br>  2. For the main benchmark it shown 223  requests/second - stable. Not familiar with pgx driver</pre><p>3. <strong>Java JIT:</strong></p><pre>Memory usage: <br>  Cold start: &quot;Out of the box it allocates 34Mb from the beginning&quot;<br>  When tests started: &quot;It was 75 Mb all the time test was running&quot;<br>  CPU: &quot;Low Intensive usage. From the beginning was about 62%. Then when JVM warms up it become 45% or even lower&quot; 30% some time<br>RPS: <br>  1. For first 20K requests it shown 1185 reqests/second<br>  2. For the main benchmark it shown 332  requests/second - same as for AOT. Guess have some DB limitations </pre><h3>Conclusions</h3><p>As expected jvm requires resources. Golang can work with very limited resources.</p><p>GraalVM without doubts solves problem with artifact size in comparing to JIT but gives a lot of complexity in environment set up an compilation stage. It is not true if you think, you can take plain JVM application and compile it under GraalVM. It is a pain comparing with golang set up.</p><p>Development with GraalVM take time. You can make a coffee break each time :). Just to speed up I use plain JVM while development. But there are no guarantee it would work with AOT. :)</p><p>Error management in golang is a Hell. But this might be I am from Java world. :)</p><p>Easy to develop: I don’t see any dificults for both Java JIT and Golang. Velocity of Compilation for Golang of course the highest. Won’t be able to have coffee brakes :) . For GraalVM not easy stuff. Should spend more time to get all this stuff working.</p><p>Performance. For chosen frameworks Java outperforms Golang. But I guess for more usual choose situation might be an opposite. Perhaps if I try to tune JVM results can be different.</p><p>Meanwhile I tried to implement this stuff in Rust and artifact size was less then 1Mb after all optimizations. :)</p><p>Btw. <em>Regarding performance results are useless :). Choose of concrete stack for project is more complex task, doesn’t relate to stuff described there.</em></p><p>Repositories are available</p><ul><li><a href="https://github.com/aviplayer/fast-web-java">GitHub - aviplayer/fast-web-java: Invesiogation performance java</a></li><li><a href="https://github.com/aviplayer/fast-http-golang">GitHub - aviplayer/fast-http-golang: Golang performance obsession</a></li></ul><p>For the configuration, compilation and execution I used justfile. Please change variables on the top of Justfiles to your paths.</p><p>Need to start postgres before the tests. Just cd to infra dir and run docker compose up -d</p><p>then from the Root of the project:</p><p>for java JIT:</p><pre>just docker-java</pre><p>for java AOT after all this this weird set up is done :)</p><pre>just docker-native</pre><p>for Golang from root of the project</p><pre>just run</pre><p>To execute tests from root of the java project:</p><pre>just test</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb979ef4c03" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/java-kotlin-graalvm-and-golang-7fb979ef4c03">Java/Kotlin/GraalVm and Golang.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Native (Server side development)]]></title>
            <link>https://medium.com/@andrew.visokih_88808/kotlin-native-server-side-development-8f8f5a781bd0?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8f5a781bd0</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[annotation-processor]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Sat, 28 May 2022 21:05:41 GMT</pubDate>
            <atom:updated>2022-05-28T21:05:41.974Z</atom:updated>
            <content:encoded><![CDATA[<p>In new version of Kotlin Native with new memory model also appeared support for native development with Ktor server. Interesting, if it can compete with Golang and also how mature is it. I decided to try with some kind of <em>Hello Word </em>application. Something very simple. Let’s imagine we have table <em>users</em>. And just create a simple GRUD application.</p><p>But there are no driver for postgres db on Kotlin Native. How to fix it? Fortunately, Kotlin Native has a good C interop support. And there is a <strong>libpq(postgres C driver). </strong>I can extend it to be used from Kotlin Native side with Ktor. Let’s go and try …</p><p>I don’t want to install postgres directly on my Ubuntu. Going to use it inside docker container. Started googling to find not only C header files but also compiled libs. Fortunately, found them on <a href="https://www.enterprisedb.com/download-postgresql-binaries">https://www.enterprisedb.com/download-postgresql-binaries</a>. Download and extract on my laptop. Finally, my libpq.def file looks like:</p><pre>headers = {project-dir}/headers/libpq-fe.h<br>headerFilter = {project-dir}/headers/*<br>staticLibraries = libpq.a<br>libraryPaths = {project-dir}/libs<br>linkerOpts = -l{project-dir}/libs/libldap-2.4.so.2 -l{project-dir}/libs/libgssapi_krb5.so.2 -l{project-dir}/libs/libssl.so.1.1 -l{project-dir}/libs/libcrypto.so.1.1</pre><p>also was needed to create gradle task, to automate set of project-dir. Kotlin Native still not support relative paths, but we have gradle :). Also for some reason this construction:</p><blockquote>linkerOpts = -L{project-dir} -llibldap-2.4.so.2</blockquote><p>is not working on Ubuntu. On windows it was working. My gradle task looks:</p><pre>tasks.register&lt;Copy&gt;(&quot;replace-progect-dir&quot;) <strong>{<br>    </strong>val dir = &quot;${project.rootDir}&quot;<br>    file(&quot;$dir/web/src/nativeInterop/cinterop&quot;).walk()<br>        .filter <strong>{ it</strong>.name == &quot;libpq.def&quot; <strong>}<br>        </strong>.forEach <strong>{<br>            it</strong>.writeText(<br>                <strong>it</strong>.readText().replace(<br>                &quot;{project-dir}&quot;, dir<br>                )<br>            )<br>        <strong>}<br>}</strong></pre><p>I tried to compile and it is working. Then, need to implement simple db communication layer. With simple annotation processor.</p><p>I want to have something like this:</p><pre>@Entity(table = &quot;users&quot;)<br>class User(<br>    @Column(name = &quot;id&quot;) var id: String? = null,<br>    @Column(name = &quot;username&quot;) var username: String? = null,<br>    @Column(name = &quot;firstname&quot;)  var firstname: String? = null,<br>    @Column(name = &quot;lastname&quot;)  var lastname: String? = null,<br>)</pre><p>and generate something like this:</p><pre>fun User.setVal(name: String, value: String?){<br>   when (name) {<br>      &quot;id&quot; -&gt; id = value <br>      &quot;username&quot; -&gt; username = value <br>      &quot;firstname&quot; -&gt; firstname = value <br>      &quot;lastname&quot; -&gt; lastname = value <br>   }<br>}</pre><p>Several serialization and deserialization functions. Something simple, just to understand if it easy or not.</p><p>And finally I found in lib for this: com.google.devtools.ksp:symbol-processing-api. KSP also working with Kotlin Native. For code generation I decided to use com.squareup:javapoet. It is a common approach for Java and Kotlin annotation processing. Code is available on Github. Link is provided at the end of article . Solution is pretty straightforward in about 80 lines of code.</p><p>Per there documentation just override process method with my code generation:</p><pre>override fun process(resolver: Resolver): List&lt;KSAnnotated&gt;</pre><p>and overide class visitor with internal code generation for particular annotation:</p><pre>override fun visitClassDeclaration(<br>    classDeclaration: KSClassDeclaration,<br>    data: OutputStreamWriter<br>)</pre><p>and finally added dependency for code generation to my main module:</p><pre>dependencies <strong>{<br>    </strong>ksp(project(&quot;:processor&quot;))<br><strong>}</strong></pre><p>Unfortunately, IDE doesn’t support generated code. Everything was red. I tried several solutions, mentioned online. But wasn’t success. Finally decided to add module dependency in Intelij. And also marked</p><blockquote>{project-dir}/web/build/generated/ksp/native/nativeMain/kotlin</blockquote><p>as source dir. Project is green. Let’s implement routing and db layers</p><p>For routing everything is pretty simple.</p><pre>fun main() {<br>    val db: DB = DB()<br>    <em>embeddedServer</em>(CIO, port = 8083) <strong>{<br>        </strong>install(ContentNegotiation) <strong>{<br>            </strong>json(<em>Json </em><strong>{<br>                </strong>prettyPrint = true<br>                isLenient = true<br>            <strong>}</strong>)<br>        <strong>}<br>        </strong>routing <strong>{<br>            </strong>get(&quot;/users&quot;) <strong>{<br>                </strong>call.respond(db.getUsers())<br>            <strong>}<br>            </strong>post(&quot;/users&quot;) <strong>{<br>                </strong>val usr = call.receive&lt;UserDto&gt;()<br>                call.respondText <strong>{  </strong>db.addUser(usr)!! <strong>}<br>            }<br>        }<br>    }</strong>.start(wait = true)<br>}</pre><p>Installing ContentNegotiation is a Ktor way of serialization. Also added @Serializable annotation to User dto class. And several dependencies to my gradle file:</p><pre>implementation(&quot;io.ktor:ktor-server-content-negotiation:$ktor_version&quot;)<br>implementation(&quot;io.ktor:ktor-serialization-kotlinx-json:$ktor_version&quot;)</pre><p>this part is well documented on Ktor side. Then to finalize project I need to implement DB communication layer…</p><p>This was most painful part for me, because I was needed to read specifications for this C library(libpq) :)</p><p>First of all I need to create connection. Simple implementation. Without thinking about pools, concurrency etc. . To understand if it possible in general:</p><pre>init {<br>    val connStr = &quot;host=$Host port=$Port user=$Usr password=$Password dbname=$DataBase&quot;<br>    conn = <em>PQconnectdb</em>(connStr)!!<br>    if(<em>PQstatus</em>(conn) != ConnStatusType.CONNECTION_OK){<br>        <em>println</em>(&quot;Connection to database failed ${<em>PQstatus</em>(conn)} &quot;)<br>        do_exit(conn)<br>    }else{<br>        <em>println</em>(&quot;Connected to $Host:$Port/$DataBase with $Usr&quot;)<br>    }<br>}</pre><p>For getAllUsers implementation is next:</p><pre>val res = <em>PQexec</em>(conn, &quot;SELECT * FROM users LIMIT 5&quot;)<br>if (<em>PQresultStatus</em>(res) != PGRES_TUPLES_OK) {<br>    <em>println</em>(&quot;No data retrieved&quot;)<br>    <em>PQclear</em>(res)<br>}else{<br>    val rows = <em>PQntuples</em>(res)<br>    for(i in 0 until rows){<br>        val usr = User()<br>        val colls = usr.getColumnNames()<br>        colls.forEach <strong>{<br>            </strong>val colNum = <em>PQfnumber</em>(res, it);<br>            val colVal = <em>PQgetvalue</em>(res, i, colNum)?.toKString()<br>            usr.setVal(it, colVal)<br>        <strong>}<br>        </strong>users.add(usr)<br>    }<br>    <em>PQclear</em>(res)<br>}</pre><p>Usage of generated code :) for User class usr.getColumnNames() and usr.setVal(it, colVal). Other just C native functions and constants. Nothing special. Everything mentioned in documentation: <a href="https://www.postgresql.org/docs/9.5/libpq.html">https://www.postgresql.org/docs/9.5/libpq.html</a></p><p>Same with addUser function:</p><pre>fun addUser(usr: UserDto): String?{<br>    val insert = &quot;&quot;&quot;insert into users (username, firstname, lastname)<br>            values(&#39;${usr.username}&#39;, &#39;${usr.firstname}&#39;, &#39;${usr.lastname}&#39;) <br>            <br>            RETURNING id;&quot;&quot;&quot;<br>    <em>println</em>(&quot;inserting ... $insert&quot;)<br>    val res = <em>PQexec</em>(conn, insert)<br>    if (<em>PQresultStatus</em>(res) != PGRES_TUPLES_OK) {<br>        <em>println</em>(&quot;Insert failed for $usr with status ${<em>PQresultStatus</em>(res)}&quot;)<br>        <em>PQclear</em>(res)<br>        return &quot;-1&quot;<br>    }<br>    return <em>PQgetvalue</em>(res, 0, 0)?.toKString()<br>}</pre><p>Simple implementation is ready.</p><p>Conclusions:</p><ol><li>With Ktor Native it is a great step in terms of maturity and usability of technology</li><li>Still lack of frameworks and implementations for Kotlin Native in terms of web development.</li><li>In any case it is interesting, how team develops this technology. I see a great potential in it. Going to watch attentively on what they are doing.</li></ol><p>All investigations available on Github.</p><p><strong>Infra</strong>: docker compose</p><p><strong>Annotations</strong>: annotation interfaces to share between modules</p><p><strong>Processing</strong>: annotation processing implementation</p><p><strong>Web</strong>: main application with all logic inside</p><p><a href="https://github.com/aviplayer/ktor_native">Link to Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8f5a781bd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Native and Rust interoperability.]]></title>
            <link>https://towardsdev.com/kotlin-native-and-rust-interoperability-b7b736c7fc0a?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7b736c7fc0a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 17:26:12 GMT</pubDate>
            <atom:updated>2022-02-04T12:37:04.584Z</atom:updated>
            <content:encoded><![CDATA[<p>There are two modern programming languages (Rust and Kotlin) which obviously are the future programming languages. They both allow to write code with low boilerplate and use modern and both use expressive syntax.</p><p>Also I am looking for how Kotlin develops in several areas. Without doubts it is the number 2 in Java world, also mobile development (KMM and android) and JS. Seems Kotlin is everywhere. One programming language for all :) . Also Kotlin Native. Unfortunately, Kotlin Native still doesn’t have server side support. <a href="http://There is an issue for  Ktor to support Kotlin Native.">https://github.com/ktorio/ktor/issues/571#issuecomment-562118651</a>. Also there’s <a href="https://github.com/KwangIO/kwang">kwang</a> but it doesn’t seems to be maintained anymore.</p><p>I decided to try with Rust, as a server implementation. And come up with some API from Rust to be used on Kotlin Side…</p><p>I decided to develop using async framework. Something based on Tokio. I am pretty familiar with this approach from Java with Reactive Streams. First attempt was with Actix framework. Prototype was working but it is too high level for writing such frameworks. I decided to use something match more low-level based on Tokio and something which also can save time and adopted for this purposes. And finally I found this in Rust. <strong>Hyper.</strong></p><p>On there page are the next words:</p><blockquote>hyper is a relatively low-level library, meant to be a building block for libraries and applications.</blockquote><p>That is directly what I was looking for …..</p><p>Let’s start implementation. It is clear that I need to expose C interface. Rust has nice support for this. Project has 2 modules: <strong>dynlib </strong>this is directly the dynamic lib module to be used from Kotlin and <strong>main </strong>module, simple module to check the API is working at list from Rust.</p><p>Interface for starting server is</p><blockquote>#[no_mangle]<br>pub extern “C” fn start_rust_server(raw_addr: *mut c_char)</blockquote><p>no_mangle just to force Rust compiler don’t change function name and other syntax is Rust &amp; C interop specific. Parameter is just a C String to be passed from Kotlin.</p><p>From Rust it can be called something like this:</p><blockquote>let addr_bytes = b”127.0.0.1:8087&quot;.to_vec();</blockquote><blockquote>let c_ctring = CString::from_vec_unchecked(addr_bytes); <strong>start_rust_server(c_ctring.into_raw())</strong></blockquote><p>Implementation of this function is pretty straight forward:</p><blockquote>let body = async move {</blockquote><blockquote>// Just a C_String conversion. utility function. You can check it in Repo</blockquote><blockquote>let addr_string = utils::c_chars_to_string(raw_addr);</blockquote><blockquote>// Then string validation</blockquote><blockquote>let addr = addr_string.parse().expect( format!(“wrong server address {}”, addr_string).as_str() );</blockquote><blockquote>let some_state = “state”.to_string();</blockquote><blockquote>// Simple state of application</blockquote><blockquote>let new_service = make_service_fn(move |_| { let app_state = AppState { state_thing: some_state.clone(), };</blockquote><blockquote>// Async block directly to execute Tokio runtime. Just expose the plain function then block it</blockquote><blockquote>async {</blockquote><blockquote>// Will cover route later</blockquote><blockquote>Ok::&lt;_, Error&gt;(service_fn(move |req| { router::route(req, app_state.clone()) })) }</blockquote><blockquote>});</blockquote><blockquote>// Just a hyper way to start server</blockquote><blockquote>let server = Server::bind(&amp;addr) .serve(new_service);</blockquote><blockquote>println!(“Server starting {} …”, addr);</blockquote><blockquote>if let Err(e) = server.await { eprintln!(“server error: {}”, e); }</blockquote><blockquote>};</blockquote><blockquote>// We created async Runtime. Now just need to block it …</blockquote><blockquote>println!(“Starting tokio runtime …”); RUNTIME.block_on(body.into_local_ffi());</blockquote><p>One thing. I need to do. Just Tokio RUNTIME need to be static. It should exist all the program life. For this Rust has a lazy_static approach for such non constant properties:</p><blockquote>lazy_static! { static ref RUNTIME: Runtime = Runtime::new().unwrap(); }</blockquote><p>Server is starting from both Kotlin and Rust….</p><p>Now we need to create routes. For POC purposes I decided to create to kind of routes: GET and POST. From Kotlin we will need to provide method, uri and callback. I decided to split route creation in 2 functions for get and post. That is why only 2 params are needed: uri and callback (callback is function which receives body or params, executes business logic like DB calls and etc. and provides the response body. For now as a C_String).</p><p>Interface would be the next:</p><blockquote>pub extern “C” fn get(uri_raw: *mut c_char, callback: extern “C” fn(*mut c_char) -&gt; *mut c_char)</blockquote><p>Body of the function will be the next:</p><blockquote>// the same. we are creating async block</blockquote><blockquote>let async_block = async move {</blockquote><blockquote>// utility function for creation string from raw pointer</blockquote><blockquote>let uri = utils::c_chars_to_string(uri_raw);</blockquote><blockquote>// Creating handler from FFI function. Will explain latter</blockquote><blockquote>let handler_box = create_param_handler(callback);</blockquote><blockquote>// That is interesting. Will explain latter</blockquote><blockquote>ROUTER.lock().await.get(uri.as_str(), handler_box);</blockquote><blockquote>println!(“Handler added for {}”, uri) };</blockquote><blockquote>The same blocking call</blockquote><blockquote>RUNTIME.block_on(async_block);</blockquote><p>Regarding ROUTER property. We need Global Property with static life time. It should be mutable and thread safe. When I tried Mutex from std lib, I’ve got the compilation error. It is impossible to use std Mutex with async function. Fortunately, there is a solution with another module with the same name.</p><blockquote>use futures::lock::Mutex;</blockquote><p>I added a property to lazy_static block. Here is the usual approach in Rust for solving such kind of things. I wouldn’t explain the interior mutability there. Just a sample of code:</p><blockquote>lazy_static! {</blockquote><blockquote>static ref RUNTIME: Runtime = Runtime::new().unwrap();</blockquote><blockquote>// Router is just a global implementation of all the routes.</blockquote><blockquote>static ref ROUTER: Arc&lt;Mutex&lt;Router&gt;&gt; = Arc::new(Mutex::new( Router::new()));}</blockquote><p>Router struct contains direct routes as HashMap:</p><blockquote>pub struct Router {</blockquote><blockquote>method_map: HashMap&lt;Method, InternalRouter&lt;Box&lt;dyn Handler&gt;&gt;&gt;</blockquote><blockquote>}</blockquote><p>Where Handler is async trait. Abstraction on callback:</p><blockquote>#[async_trait]pub trait Handler: Send + Sync + ‘static {</blockquote><blockquote>async fn invoke(&amp;self, context: Context) -&gt; hyper::Response&lt;hyper::Body&gt;;</blockquote><blockquote>}</blockquote><p>InternalRouter is a specific implementation</p><blockquote>use route_recognizer::{Params, Router as InternalRouter};</blockquote><p>Just a syntax sugar to select particular router.</p><p>Regarding router. Inside create server function:</p><p><em>router::route(req, app_state.clone())</em></p><p>Just one more async impl. :)</p><pre>pub async fn route(<br>    req: Request&lt;hyper::Body&gt;,<br>    app_state: AppState,<br>) -&gt; Result&lt;hyper::Response&lt;hyper::Body&gt;, Error&gt; {</pre><pre>// Get the router<br>    let router = ROUTER.lock().await;</pre><pre>// Proceed request and return response </pre><pre>// router.route(..) explained in next pease of code<br>   let found_handler = router.route(req.uri().path(), req.method());<br>    let resp = found_handler<br>        .handler<br>        .invoke(Context::new(app_state, req, found_handler.params))<br>        .await;<br>    Ok(resp)<br>}</pre><p>One more route function belongs to code Router struct:</p><pre>pub fn route(&amp;self, path: &amp;str, method: &amp;Method) -&gt; RouterMatch&lt;<em>&#39;_</em>&gt; {<br>        if let Some(r) = self<br>            .method_map<br>            .get(method)<br>            .and_then(|r| r.recognize(path).ok())<br>        {<br>            RouterMatch {<br>                handler: &amp;***r.handler(),<br>                params: r.params().clone(),<br>            }<br>        } else {<br>            RouterMatch {<br>                handler: &amp;not_found_handler,<br>                params: Params::new(),<br>            }<br>        }<br>    }<br>}</pre><p>Nothing special. Using Router Recognizer crate we just checking if specific route exists and returning it. In case of absence we just returning the default. Detailed implementation you can check in the repo.</p><p>Now let’s create server from Rust:</p><pre>// Creating uri&#39;s. They just a C Strings representation. In general raw pointers. All block that is why is unsafe.</pre><pre>let uri_get = CString::from_vec_unchecked(b&quot;/param/:param&quot;<br>    .to_vec()).into_raw();<br>let uri_post = CString::from_vec_unchecked(b&quot;/body&quot;<br>    .to_vec()).into_raw();</pre><pre>// Creating C functional pointers with returning value</pre><pre>extern &quot;C&quot; fn callback_get(name: *mut c_char) -&gt; *mut c_char {<br>    let c_name =<br>        unsafe {<br>            CString::from_raw(name)<br>        };<br>    let res = format!(&quot;Hello from {:?}&quot;, c_name).as_bytes().to_vec();<br>    unsafe {<br>        CString::from_vec_unchecked(res).into_raw()<br>    }<br>}<br><br>extern &quot;C&quot; fn callback_post(json_raw: *mut c_char) -&gt; *mut c_char {<br>    let json =<br>        unsafe {<br>            CString::from_raw(json_raw)<br>        };<br>    println!(&quot;Got json: \n{:?}&quot;, json);<br>    let res = &quot;{\&quot;response\&quot;:\&quot;hello\&quot;}&quot;.as_bytes().to_vec();<br>    unsafe {<br>        CString::from_vec_unchecked(res).into_raw()<br>    }<br>}</pre><pre>Adding routes for get and post<br>get(uri_get, callback_get);<br>post(uri_post, callback_post);<br>println!(&quot;server is starting ....&quot;);<br>let addr_bytes = b&quot;127.0.0.1:8087&quot;.to_vec();<br>let c_ctring = CString::from_vec_unchecked(addr_bytes);</pre><pre>// Finally start server<br>start_rust_server(c_ctring.into_raw())</pre><p>Compile and run. It’s working ….</p><p>One more thing from Rust we need to create C header file. Just set up C bindgen:</p><pre>extern crate cbindgen;<br>use std::env;<br>fn main() {<br>    let crate_dir = env::var(&quot;CARGO_MANIFEST_DIR&quot;).unwrap();<br>    let mut config: cbindgen::Config = Default::default();<br>    config.language = cbindgen::Language::C;<br>    cbindgen::generate_with_config(&amp;crate_dir, config)<br>        .unwrap()<br>        .write_to_file(&quot;target/lib-server.h&quot;);<br>}</pre><p>Got the generated header file:</p><pre>#include &lt;stdarg.h&gt;<br>#include &lt;stdbool.h&gt;<br>#include &lt;stdint.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>void start_rust_server(char *raw_addr);<br><br>void get(char *uri_raw, char *(*callback)(char*));<br><br>void post(char *uri_raw, char *(*callback)(char*));</pre><p>Will use it from kotlin with dynamic lib</p><p>Now let’s try from Kotlin.</p><p>No need to describe the whole procedure of set up. Kotlin has nice documentation for this. Just go step by step.</p><p>And finally listing:</p><pre>import libserver.*<br><br>val arena = Arena()<br>fun main(args: Array&lt;String&gt;) {<br>    val getURI = &quot;/param/:param&quot;.cstr;<br>    memScoped {<br>        val cFunctionPointerGet = staticCFunction&lt;CPointer&lt;ByteVar&gt;?, CPointer&lt;ByteVar&gt;?&gt; {<br>            println(&quot;Getting json in kotlin&quot;)<br>            &quot;{\&quot;response\&quot;:\&quot;hello\&quot;}&quot;.cstr.getPointer(arena)<br>        }<br>        get(getURI, cFunctionPointerGet)<br>        println(&quot;Starting point ...&quot;)<br>        val addr = &quot;127.0.0.1:8087&quot;.cstr<br>        start_rust_server(addr)<br>        println(&quot;After server started ...&quot;)<br>    }<br>}</pre><p>tried but it doesn’t work. I see that everything is working in Rust but fails in Kotlin Native. Noticed that function working with primitive types is OK but if you are trying to use C pointers, it fail. WTF. Decided to submit bug:</p><p><a href="https://youtrack.jetbrains.com/issue/KT-50821">https://youtrack.jetbrains.com/issue/KT-50821</a></p><p>Guys from Kotlin Native team reacted almost immediately. Ha-ha. My fail. After function finished, Rust tries to deallocate C String references, provided from Kotlin and fails. … :(</p><p>Ha-ha I missed main concepts of Rust:</p><ul><li>ownership</li><li>borrowing</li><li>lifetimes</li></ul><p>Nice from Rust, this avoids memory leaks. I guess code in C/C++ will compile and this memory leaks will exists forever.</p><p>Just for this project decided to cache this strings on Rust side to avoid deallocating in some constant variable with static life time.</p><p>It was needed to rewrite both. Kotlin Native and Rust sides. Of course this is a hack and will increase memory consumption but it is a pet project and my weekends are near the end. Tomorrow will need to move back to Java world…</p><p>Fixes you can check in the repository. Also I divided it in 2 projects. Rust and Kotlin. Kotlin needs a bit optimization for paths and current compilation is adopted only for Windows. But it easy to compile for other OS.</p><p>Conclusions:</p><ol><li>Rust is really safe. Even a bit overwhelmed in it safety. And you can’t even avoid it …</li><li>Kotlin Native looks also nice. With new concurrency model, but what about server side?</li><li>Be very careful while FFI usage and usage Rust from another languages. It might surprise you … :)</li></ol><p>And finally GitHub links:</p><p>Rust: <a href="https://github.com/aviplayer/rust_interop_server.git">https://github.com/aviplayer/rust_interop_server.git</a></p><p>Kotlin: <a href="https://github.com/aviplayer/kotlin_rust_interop.git">https://github.com/aviplayer/kotlin_rust_interop.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7b736c7fc0a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/kotlin-native-and-rust-interoperability-b7b736c7fc0a">Kotlin Native and Rust interoperability.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 17, Rust interoperability — new FFI working with Rust]]></title>
            <link>https://medium.com/@andrew.visokih_88808/java-17-rust-interoperability-new-ffi-working-with-rust-ebe140cd9448?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe140cd9448</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 22:22:11 GMT</pubDate>
            <atom:updated>2021-11-06T22:36:42.163Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 17, Rust interoperability — new FFI working with Rust</h3><p>There are a plenty of articles how to integrate Rust with Java using JNI:</p><p>1. <a href="https://itnext.io/rust-jvm-ab4de9f14eb6">Rust with Java</a></p><p>2. <a href="https://github.com/GabrielMajeri/kotlin-rust">Rust with Kotlin</a></p><p>Even there is a crate for this: <a href="https://docs.rs/jni/0.19.0/jni/">JNI crate</a></p><p>But it requires several drawbacks:</p><ul><li>JNI involves several tedious artifacts: a Java API (native methods), a C header file derived from the Java API, and a C implementation that calls the native library of interest. Java developers must work across multiple toolchains to keep platform-dependent artifacts in sync, which is especially burdensome when the native library evolves rapidly.</li><li>JNI can only interoperate with libraries written in languages, typically C and C++, that use the calling convention of the operating system and CPU for which the JVM was built. A native method cannot be used to invoke a function written in a language that uses a different convention.</li><li>JNI does not reconcile the Java type system with the C type system. Aggregate data in Java is represented with objects, but aggregate data in C is represented with structs, so any Java object passed to a native method must be laboriously unpacked by native code. For example, consider a record class Person in Java: Passing a Person object to a native method will require the native code to use JNI&#39;s C API to extract fields (e.g., firstName and lastName) from the object. As a result, Java developers sometimes flatten their data into a single object (e.g., a byte array or a direct byte buffer) but more often, since passing Java objects via JNI is slow, they use the Unsafe API to allocate off-heap memory and pass its address to a native method as a long — which makes the Java code tragically unsafe!</li></ul><p>With Java 17 we have <a href="https://openjdk.java.net/jeps/412">FFI(Foreign Functions Interface)</a> fixes all this drawbacks. Unfortunately package is jdk.incubator.foreign, that means will change soon and not production ready, but can try, how convenient it is</p><h3><strong>Set up:</strong></h3><p>We need to provide several options for incubator.foreign package to be available:</p><ol><li>for javac :</li></ol><blockquote>— add-modules jdk.incubator.foreign</blockquote><p>in idea you need to add it to Preferences -&gt; Build, Execution, Deployment -&gt; Java Compiler -&gt; Additional Command Line Parameters</p><p>2. also VM options should be added:</p><blockquote>— add-modules jdk.incubator.foreign — enable-native-access=ALL-UNNAMED</blockquote><p>Now ready start implementation ….</p><h3><strong>Calling Rust function from java:</strong></h3><p>On rust side we need to add type of library to be compiled in Cargo:</p><pre>[lib]<br>crate_type = [&quot;cdylib&quot;]</pre><p>Let’s create plain function, that just prints something using Rust FFI. All the interoperability can be done using Clang.</p><pre>#[no_mangle]<br>pub extern &quot;system&quot; fn print_from_rust() {<br>    println!(&quot;--- RUST execute something  from rust&quot;)<br>}</pre><p>no_mangle, just not override external functions by compiler.</p><blockquote>cargo build</blockquote><p>We have dynamic library now. In my case target/debug/libdynamiclib.dylib. On java side first need to load it. The same way as for JNI:</p><pre>public class Main {<br>    public static void main(String[] args) throws Throwable {<br>        var libPath = Optional.<em>ofNullable</em>(args[0])<br>                .orElseThrow(() -&gt; new IllegalArgumentException(&quot;No library path provided!!!&quot;));<br>        System.<em>load</em>(libPath);<br>...................................................................</pre><p>Provided library path as command line argument. Let’s load our method:</p><pre>var loaderLookup = SymbolLookup.<em>loaderLookup</em>();<br>var print = loaderLookup.lookup(&quot;print_from_rust&quot;).orElseThrow();</pre><p>SymbolLookup just initialize loaderLookup to find particular function in loaded library.</p><p>Let’s execute particular rust function:</p><pre>MethodHandle printInRust = CLinker.<em>getInstance</em>().downcallHandle(<br>        print,<br>        MethodType.<em>methodType</em>(void.class),<br>        FunctionDescriptor.<em>ofVoid</em>()<br>);<br>printInRust.invokeExact();</pre><p>We need to create <em>MethodHandle</em> object. In new FFI interface it possible with <em>downcallHandle</em> method.</p><p>We need to provide MemoryAddress of our function, 2-nd parameter is the signature of our function. In our case it is void and Function Descriptor. Also void without parameters.</p><p>Compile and run. We can see printing from Rust function.</p><h3>Providing parameters to function:</h3><p>Let’s print in rust String, provided from Java:</p><pre>#[no_mangle]<br>pub extern &quot;system&quot; fn get_string_in_rust(raw: *mut c_char) {<br>    unsafe {<br>        let c_string = CString::from_raw(raw);<br>        match c_string.into_string() {<br>            Ok(java_str) =&gt; {<br>                println!(&quot;--- RUST get from java {}&quot;, java_str)<br>            }<br>            Err(err) =&gt; {<br>                panic!(err)<br>            }<br>        };<br>    }<br>}</pre><p>As I mentioned, communication done using <a href="https://doc.rust-lang.org/std/ffi/index.html">Rust FFI interface</a>. In this case using raw pointers inRust we need to use unsafe block, convert fist to C string, and finally create Rust string. That all. Let see how is going on Java side:</p><pre>var executeRust = loaderLookup.lookup(&quot;get_string_in_rust&quot;).orElseThrow();<br>MethodHandle sendToRust = CLinker.<em>getInstance</em>().downcallHandle(<br>        executeRust,<br>        MethodType.<em>methodType</em>(void.class, MemoryAddress.class),<br>        FunctionDescriptor.<em>ofVoid</em>(<br>                CLinker.C_POINTER<br>        )<br>);<br>MemorySegment str = CLinker.<em>toCString</em>(&quot;Java String&quot;, <em>newImplicitScope</em>());<br>sendToRust.invokeExact(str.address());</pre><p>What has changed regarding previous case. We are providing memory addresses to method signature and functional descriptor. Also allocating memory and providing directly pointer to this memory segment. You remember rust implementation…. Compile and run.</p><h3>Providing parameters to rust function and getting response in Java:</h3><p>Rust:</p><pre>#[no_mangle]<br>pub extern &quot;system&quot; fn return_string_from_rust(mut raw: *mut c_char) -&gt; *mut c_char {<br>    unsafe {<br>        let mut c_string = CString::from_raw(raw);<br>        return match c_string.into_string() {<br>            Ok(java_str) =&gt; {<br>                println!(&quot;--- RUST got string from java  {:?}&quot;, java_str);<br>                let str_bytes = b&quot;string from rust&quot;.to_vec();<br>                c_string = CString::from_vec_unchecked(str_bytes);<br>                println!(&quot;--- RUST prepare string {:?}&quot;, c_string);<br>                c_string.into_raw()<br>            }<br>            Err(err) =&gt; {<br>                panic!(err)<br>            }<br>        };<br>    }<br>}</pre><p>We print string from java, then creating a new one and returning raw pointer to java. Changed a little bit.</p><p>Java side:</p><pre>var getFromRust = CLinker.<em>getInstance</em>().downcallHandle(<br>        getStringFromRust,<br>        MethodType.<em>methodType</em>(MemoryAddress.class, MemoryAddress.class),<br>        FunctionDescriptor.<em>of</em>(<br>                CLinker.C_POINTER,<br>                CLinker.C_POINTER<br>        )<br>);<br>var javaStr = CLinker.<em>toCString</em>(&quot;from java&quot;, <em>newImplicitScope</em>());<br>var memory = (MemoryAddress)getFromRust.invokeExact(javaStr.address());<br>var res = memory.asSegment(16, <em>newImplicitScope</em>());<br>System.out.printf(&quot;JAVA %s&quot;, new String(res.toByteArray()));</pre><p>What has changed? Method signature and Function descriptor. We have only memory Addresses now. Now in Java we got memory address. We need to read bytes and create String from them. Compile and run.</p><h3>Execute Java function from rust:</h3><p>New FFI allows creating callbacks, can be executed from native code. Let’s provide simple callback, just getting string as a param in rust and sends it to java.</p><p>Rust:</p><pre>#[no_mangle]<br>pub extern &quot;system&quot; fn call_back(cb: extern fn(raw: *mut c_char) -&gt; *mut c_char) -&gt; *mut c_char {<br>    unsafe {<br>        let str_bytes = b&quot;callback from rust&quot;.to_vec();<br>        let c_string = CString::from_vec_unchecked(str_bytes);<br>        cb( c_string.into_raw())<br>    }<br>}</pre><p>Need to provide extern function as a parameter. and return call of this function.</p><p>On java side:</p><pre>var change_by_ref = loaderLookup.lookup(&quot;call_back&quot;).orElseThrow();<br>class CallFromRust {<br>        static MemoryAddress getString(MemoryAddress addr) {<br>            return addr;<br>        }<br>    }<br>    MethodHandle stringHandle<br>            = MethodHandles.<em>lookup</em>()<br>            .findStatic(CallFromRust.class, &quot;getString&quot;,<br>                    MethodType.<em>methodType</em>(MemoryAddress.class,<br>                            MemoryAddress.class));<br>    MemoryAddress javaFuncPointer =<br>            CLinker.<em>getInstance</em>().upcallStub(stringHandle,<br>                    FunctionDescriptor.<em>of</em>(<br>                            CLinker.C_POINTER,<br>                            CLinker.C_POINTER),<br>                    <em>newImplicitScope</em>());<br>    MethodHandle executeJavaFromRust = CLinker.<em>getInstance</em>().downcallHandle(<br>            change_by_ref,<br>            MethodType.<em>methodType</em>(MemoryAddress.class, MemoryAddress.class),<br>            FunctionDescriptor.<em>of</em>(<br>                    CLinker.C_POINTER,<br>                    CLinker.C_POINTER<br>            )<br>    );<br>    var javaMemory = (MemoryAddress)executeJavaFromRust.invoke(javaFuncPointer);<br>    var resJavaFunc = javaMemory.asSegment(18, <em>newImplicitScope</em>());<br>    System.out.printf(&quot;JAVA %S&quot;, new String(resJavaFunc.toByteArray()));<br>}</pre><p>First we are creating class CallFromRust with static method, which we are going to use as a callback. Then just converting it to MethodHandle to send as a function pointer to Rust. One thing, we are using for this upcallStub method. Regarding Rust function, everything is the same as for previous example. We using memory addresses. Providing pointer to function as a parameter, Compile and run.</p><h3>Conclusions:</h3><ol><li>Need some C background to understand what is going on</li><li>Looks better and easier then JNI</li><li>Hope will have better interfaces for interoperability</li><li>Unfortunately, Rust requires unsafe code</li></ol><p><a href="https://github.com/aviplayer/rust_java_ffi">GitHub repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe140cd9448" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quarkus and react — both with kotlin.]]></title>
            <link>https://medium.com/@andrew.visokih_88808/quarkus-and-react-both-with-kotlin-a61049c86e4a?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61049c86e4a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[quarkus]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Thu, 04 Nov 2021 09:22:30 GMT</pubDate>
            <atom:updated>2021-11-04T09:22:30.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quarkus and react — both with kotlin.</h3><p>It is interesting how java world started competition with Golang for cloud solutions. Golang overcomes java by performance metrics and less memory consumption but GraalVM did this advantage less and even possible to use other technologies compatible with LLVM compiler. Of course — Rust is one love, but I am still living in java world and java is number one for Enterprises. I am from Spring world but currently the leader in Java Native approach is Read Hat with Quarkus. Let’s look on the first page:</p><blockquote><em>Quarkus is a full-stack, Kubernetes-native </em><a href="https://www.redhat.com/en/topics/cloud-native-apps/what-is-a-Java-framework"><em>Java framework</em></a><em> made for Java virtual machines (JVMs) and native compilation, optimizing Java specifically for containers and enabling it to become an effective platform for </em><a href="https://www.redhat.com/en/topics/cloud-native-apps/what-is-serverless"><em>serverless</em></a><em>, </em><a href="https://www.redhat.com/en/topics/cloud"><em>cloud</em></a><em>, and </em><a href="https://www.redhat.com/en/topics/containers/what-is-kubernetes"><em>Kubernetes</em></a><em> environments.</em></blockquote><p>This is the case to try in order to understand how convenient to use it and how maturer is it. Also I decided to implement it in kotlin. Just to be in scope of one language. Kotlin can be compiled in to java script and it has React wrappers.</p><p>Simple flow to be implemented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YFwdhPWXbLoLMynX-wK3g.png" /></figure><p><a href="https://medium.com/@andrew.visokih_88808/all-in-rust-full-stack-application-where-both-backend-and-frontend-developed-using-rustlang-2a85f60122c1">The same was implemented for rust is available: (Rust Full stack application where both backend and frontend developed using Rustlang)</a> Please check for details. Let’s start implementation:</p><p>For migrations I decided to use flyway. Nothing interesting, just add db script and db configuration to application.yaml file.</p><p>Producer. Service, responsible for getting users from github by http and publishing to kafka.</p><p>For this I decided to use reactive approach. As http client I used smallrye-mutiny-vertx-web-client. Analog is Spring web client based on webflux. Function, publishes messages to kafka, is a single parameter:</p><pre>fun getAllUsers(fn: (Array&lt;User&gt;) -&gt; (Unit)): UniAwait&lt;Array&lt;User&gt;&gt;? {<br>    return client<br>        .get(&quot;/users&quot;)<br>        .putHeader(&quot;User-Agent&quot;, &quot;Quarkus App&quot;)<br>        .addQueryParam(&quot;since&quot;, &quot;0&quot;)<br>        .addQueryParam(&quot;per_page&quot;, &quot;10&quot;)<br>        .method(HttpMethod.GET)<br>        .send()<br>        .onItem()<br>        .transform <strong>{ </strong>res <strong>-&gt;<br>            </strong>res.bodyAsJson(Array&lt;User&gt;::class.java)<br>        <strong>}<br>        </strong>.invoke(fn)<br>        .await();<br>}</pre><p>Looks easy and clear.</p><p>For communication with kafka I choose quarkus-smallrye-reactive-messaging-kafka. To use it need to specify several params in application.properties file:</p><pre>kafka.bootstrap.servers=localhost:11002<br>mp.messaging.outgoing.users.topic=users<br>mp.messaging.outgoing.users.value.serializer=org.apache.kafka.common.serialization.StringSerializer<br>mp.messaging.outgoing.users.connector=smallrye-kafka</pre><p>inject bean</p><pre>@Inject<br>lateinit var emitterCfg: EmitterConfig</pre><p>and add publish to kafka function to previous function call:</p><pre>client?.getAllUsers <strong>{ </strong>users <strong>-&gt;<br>    </strong>emitterCfg.sendMsg(<br>        objectMapper.writeValueAsString(users)<br>    )<br>}</pre><p>That is all. Easy and clear. With kotlin syntax looks nice</p><p>Let’s implement main service, responsible for getting messages from kafka, saving to data base and providing the rest endpoints.</p><p>For communication with db also choose reactive frameworks: quarkus-reactive-pg-client and quarkus-hibernate-reactive-panache</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>data class User(<br>    @Id<br>    var id: Long? = null,<br><br>    @Column(name = &quot;login&quot;)<br>    var login: String? = null,<br><br>    @Column(name = &quot;node_id&quot;)<br>    var nodeId: String? = null,<br><br>    @Column(name = &quot;avatar_url&quot;)<br>    var avatarUrl: String? = null,<br><br>    @Column(name = &quot;site_admin&quot;)<br>    var siteAdmin: Boolean? = null<br>)</pre><p>For model syntax looks clear for java developers. Kotlin specifics only, need to initialize properties by null, kotlin will generate constructors for you.</p><p>Than just announce repository:</p><pre>@ApplicationScoped<br>class UserRepository: PanacheRepository&lt;User&gt;</pre><p>And finally get message from kafka and save it:</p><pre>@Incoming(&quot;users&quot;)<br>fun consume(users: Array&lt;UserDto&gt;) {<br>    users.toList().stream().forEach <strong>{<br>        </strong>val usrDao = userMapper.toDao(<strong>it</strong>)<br>        val usr = userRepository.persist(usrDao)<br>            .await()<br>    <strong>}<br></strong>}</pre><p>Mapping dto to dao done with mapstruct. Also familiar for java developers.</p><p>And finally Rest Controller with quarkus-resteasy-reactive:</p><pre>@GET<br>fun getUsers(): Multi&lt;UserDto&gt; {<br><br>    return userRepository.streamAll()<br>        .map <strong>{ </strong>usr <strong>-&gt; </strong>userMapper.toDto(usr) <strong>}<br><br></strong>}</pre><p>That is all.</p><p>Let’s implement client application with kotlin. I found react and react router wrappers for kotlin. Started implementation from the fetch tasks for all users and particular user by id:</p><pre>suspend fun fetchUsers(): Array&lt;UserDto&gt; {<br>    val response = window<br>        .fetch(&quot;http://localhost:8085/users&quot;).await()<br>        .text()<br>        .await()<br>    val format = <em>Json </em><strong>{ </strong>ignoreUnknownKeys = true <strong>}<br>    </strong>val users = format.decodeFromString&lt;Array&lt;UserDto&gt;&gt;(response)<br>    console.log(&quot;response is &quot;, users)<br>    return users<br>}</pre><p>suspend = async. Kotlin way :). Coroutines need to be added to project dependencies.</p><p>Then react hooks need to be added to particular component implementation:</p><pre>val (users, setUsers) = <em>useState</em>(<em>emptyList</em>&lt;UserDto&gt;())<br><em>useEffect</em>(users) <strong><br></strong><br>    val mainScope = <em>MainScope</em>()<br>    mainScope.launch <strong>{<br>        </strong>val users = fetchUsers()<br>        setUsers(users.asList())<br>    <strong>}<br>}</strong></pre><p>Don’t see any big difference from typescript, just kotlin coroutines specifics.</p><p>And now kotlin DSL for html. Also added styled components as a dependency:</p><pre>styledDiv <strong>{<br>    </strong>css <strong>{<br>        </strong>+UsersStyles.usersContainer<br>    <strong>}<br>    </strong>users.toList()<br>        .map <strong>{<br>            </strong>styledDiv <strong>{<br>                </strong>css <strong>{<br>                    </strong>+UsersStyles.userLink<br>                <strong>}<br>                </strong>li <strong>{<br>                    </strong>routeLink(&quot;/${<strong>it</strong>.id}&quot;) <strong>{<br>                        </strong>+&quot;${<strong>it</strong>.login}&quot;<br>                    <strong>}<br>                }<br>            }<br>        }<br>}</strong></pre><p>routerLink from react router kotlin wrapper.</p><p>And finally my main function:</p><pre>fun main() {<br>    window.onload = <strong>{<br>        </strong><em>render</em>(document.getElementById(&quot;root&quot;)) <strong>{<br>            </strong>browserRouter <strong>{<br>                </strong>switch <strong>{<br>                    </strong>route(&quot;/&quot;, exact = true) <strong>{<br>                        </strong>child(UserContainer) <strong>{}<br>                    }<br>                    </strong>route&lt;IdProps&gt;(&quot;/:id&quot;) <strong>{ </strong>props <strong>-&gt;<br>                        </strong>div <strong>{<br>                            </strong>routeLink(&quot;/&quot;) <strong>{<br>                                </strong>+&quot;Go back&quot;<br>                            <strong>}<br>                            </strong>renderUserComponent(props.match.params.id)<br>                        <strong>}<br>                    }<br>                }<br>            }<br>        }<br>    }<br></strong>}</pre><p>That is all. Looks easy. Code is pretty straightforward.</p><p><strong>Conclusions:</strong></p><ol><li>Quarkus looks mature. No problems with development and build. Pretty well documented.</li><li>Kotlin adds a piece of sugar for all of it. Code looks pretty nice, without additional boilerplate</li><li>It is easy to switch from Spring. Approach looks pretty familiar, just need some time to get deeper in to specifics.</li><li>Kotlin js for me looks match more complex than typescript. I don’t recommend to start front-end project with kotlin js. It would be difficult and time consuming for both java and front end developers. I tried redux wrapper with Thunk, it was a piece of hell…</li></ol><p>Repositories available on GitHub:</p><ol><li><a href="https://github.com/aviplayer/kotlin-quarkus-microservices">Quarkus application</a></li><li><a href="https://github.com/aviplayer/kotlin-react">React kotlin application</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61049c86e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All in Rust (Full stack application where both backend and frontend developed using Rustlang)]]></title>
            <link>https://medium.com/@andrew.visokih_88808/all-in-rust-full-stack-application-where-both-backend-and-frontend-developed-using-rustlang-2a85f60122c1?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a85f60122c1</guid>
            <category><![CDATA[actix-web]]></category>
            <category><![CDATA[tokio]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Sat, 23 Oct 2021 18:36:32 GMT</pubDate>
            <atom:updated>2021-10-23T18:36:32.258Z</atom:updated>
            <content:encoded><![CDATA[<p>While writing previous article <a href="https://medium.com/@andrew.visokih_88808/there-are-a-lot-of-talks-about-rust-52b99b3bcdc6">There are a lot of talks about Rust</a> several cases of web development hasn’t bean covered. I decided to develop simple application to cover them. Simple flow, usually uses while development of microservices: get something via http -&gt; publish to message queue -&gt; read from message queue -&gt; save to data base -&gt; create frontend application to visualize results. Decided to use Github api with next flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGNLJ7zyBGSNz9t0j5Ue9g.png" /></figure><p>Simple flow. Nothing interesting. Just one thing, everything, including frontend developed using Rust :). Let’s go. Start from infrastructure…</p><p>For DB let’s use Postgress. For Message Queue might be Kafka? For local infrastructure it will be resource consuming. You need Zookeeper and some tool to visualize … They developed with Java and usually my computer hangs, when I starting them.</p><p>I’ve head about Redpanda. It is 100% compatible with Kafka Api, no need Zookeeper, no JVM and less resource consuming, developed with C++. As mentioned on their page: <strong>Built for performance. </strong>Case to try it…</p><p>Part of docker-compose file for local infra looks next:</p><pre>services:<br>  postgres:<br>    image: postgres:12.3-alpine<br>    restart: on-failure<br>    environment:<br>      - POSTGRES_PASSWORD=root<br>      - PGDATA=/var/lib/postgresql/data/pgdata<br>    volumes:<br>      - ./postgres:/docker-entrypoint-initdb.d<br>      - postgres:/var/lib/postgresql/data<br>    ports:<br>      - 11001:5432<br>    networks:<br>      - main<br><br>  redpanda:<br>    image: vectorized/redpanda:v21.5.3<br>    restart: on-failure<br>    user: root<br>    mem_limit: 128MB<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;rpk&quot;, &quot;cluster&quot;, &quot;info&quot;]<br>    volumes:<br>      - ./redpanda:/etc/redpanda<br>      - redpanda:/var/lib/redpanda/data<br>    ports:<br>      - 11002:11002<br>    networks:<br>      - main</pre><p>Let’s start development. Application divided in to 4 services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kq6iRYhIhts_lHg6SKMnA.png" /></figure><p>Migration service uses to create Data Base structure. We have only one table users with all info inside. It has been described in article <a href="https://medium.com/@andrew.visokih_88808/there-are-a-lot-of-talks-about-rust-52b99b3bcdc6">There are a lot of talks about Rust</a>. Nothing interesting. Compile and run. We db structure in place.</p><p>Producer service reads users from GitHub by chunks. Chunks organized in next way: we have number of all users and number of users for each chunk. Each chunk will be produced immediately to the redpanda topic. For configuration I use structopt crate. Config looks next way:</p><pre>#[derive(StructOpt, Debug, Clone)]<br>#[structopt(name = &quot;producer&quot;)]<br>pub struct EnvConfig {<br>    #[structopt(short=&quot;t&quot;, long, default_value = &quot;users&quot;)]<br>    pub kafka_topic: String,<br><br>    #[structopt(short=&quot;b&quot;, long, default_value = &quot;127.0.0.1:11002&quot;)]<br>    pub kafka_brokers: String,<br><br>    #[structopt(short=&quot;l&quot;, long, default_value = &quot;info&quot;)]<br>    pub log_level: Level,<br><br>    #[structopt(short=&quot;u&quot;, long, default_value = &quot;40&quot;)]<br>    pub num_of_users: u8,<br><br>    #[structopt(short=&quot;r&quot;, long, default_value = &quot;10&quot;)]<br>    pub num_of_users_per_request: u8,<br>}</pre><p>This crate allows to override config properties using environment variables.</p><p>For getting request use request crate:</p><pre>pub async fn get_users(since: u8, per_page: u8) -&gt; Result&lt;reqwest::Response, ProducerError&gt; {<br>    reqwest::Client::new()<br>        .get(&quot;https://api.github.com/users&quot;)<br>        .header(&quot;user-agent&quot;, &quot;producer&quot;)<br>        .query(<br>            &amp;[<br>                (&quot;since&quot;, since),<br>                (&quot;per_page&quot;, per_page)<br>            ]<br>        )<br>        .send()<br>        .await<br>        .map_err(|e| ProducerError::BackendError(format!(&quot;Server unavailable: {}&quot;, e)))<br>}</pre><p>Looks simple. No need additional explanation. And finally in loop consume users and publish them to the topic. Code of each iteration:</p><pre>let response = github::get_users(curr_position, curr_per_page).await;<br>match response {<br>    Ok(resp) =&gt; {<br>        let users = resp.json::&lt;Vec&lt;common::User&gt;&gt;()<br>            .await.unwrap_or(vec![]);  <em>// Parsing error should be validated<br>        </em>let users_str_rep = serde_json::to_string(&amp;users).unwrap_or(&quot;[]&quot;.into());<br>        let record = FutureRecord::to(&amp;topic)<br>            .key(&quot;users&quot;.into())<br>            .payload(&amp;users_str_rep);<br><br>        let produce_future = producer.send(<br>            record, rdkafka::util::Timeout::from(Duration::from_millis(0)),<br>        );<br>        match produce_future.await {<br>            Ok(res) =&gt; debug!(&quot;Sent: {:?}&quot;, res),<br>            Err(err) =&gt; error!(&quot;Future cancelled: {:?}&quot;, err)<br>        }<br>    }<br>    Err(err) =&gt; {<br>        error!(&quot;Error while response {:?}&quot;, err);<br>        <em>// Possibly retry to be implemented!!!<br>    </em>}<br>}</pre><p>serge, crate for serialization and deserialization.</p><p>for redpanda communication use Apache Kafka client library: fully asynchronous, futures-enabled Kafka client library for Rust based on librdkafka. rust-rdkafka provides a safe Rust interface to librdkafka.</p><p><em>librdkafka is a C library implementation of the </em><a href="https://kafka.apache.org/"><em>Apache Kafka</em></a><em> protocol, providing Producer, Consumer and Admin clients. It was designed with message delivery reliability and high performance in mind, current figures exceed 1 million msgs/second for the producer and 3 million msgs/second for the consumer.</em></p><p>Compile and run. Users are in place.</p><p>Web service contains 2 in 1. Rest endpoints developed with actix-web, tokio and tokio-postgress. Nice implementation of async communication, this is tokio. actix-web is implemented over tokio and fully compatible with it. no need any addional runtime for tokio-postgress. Just version of actix should be compatible with tokio version. For this project uses new actix-web = “4.0.0-beta.1”. It is compatible with tokio version 1.</p><p>Tokio postgress doesn’t have implementation of pool of connection. I use deadpool_postgres crate to create pool of connections. Let’s create struct for pool</p><pre>pub struct Db {<br>    pub connection: Option&lt;Pool&gt;,<br>}</pre><p>Initialize it later. This struct need to have static life time. I hope you now this lifetime concept in rust. This struct need to be provided also for consumer and initialize later. To achieve it let’s use lazy_static! macro</p><pre>lazy_static! {<br>    static ref DB: db::Db = {<br>        let cfg: EnvConfig = EnvConfig::from_args();<br>        let conn = connection::Connection::new(cfg.clone());<br>        db::Db::new(conn)<br>    };<br>}</pre><p>then we need to create server, before wrapping DB in Mutex:</p><pre>let storage = web::Data::new(Mutex::new(DB));<br>HttpServer::new(move || {<br>    App::new()<br>        .wrap(middleware::Logger::default())<br>        .app_data(storage.clone())<br>        .configure(Router::init_routes)<br>})<br>    .bind(server_address)?<br>    .run()<br>    .await</pre><p>initialization of routers:</p><pre>pub fn init_routes(config: &amp;mut web::ServiceConfig) {<br>    config<br>        .route(&quot;/users&quot;, web::get().to(get_users))<br>        .route(&quot;/users/{id}&quot;, web::get().to(get_user));<br>}</pre><p>Implementation of each route is very simple. Just provide the code without any explanation:</p><pre>pub async fn get_users(data: web::Data&lt;Mutex&lt;&amp;db::Db&gt;&gt;) -&gt; impl Responder {<br>    let mut data = data.lock().unwrap();<br>    match data.get_users().await {<br>        Ok(users) =&gt; {<br>            let usrs = Users {<br>                users<br>            };<br>            usrs<br>        }<br>        Err(err) =&gt; {<br>            error!(&quot;Error in get  users {}&quot;, err);<br>            Users { users: vec![] }<br>        }<br>    }<br>}</pre><p>Everything done with actix dependency injection. Code posted above. And we are getting access to db in each handler.</p><p>Also we need to start consumer in parallel. The same lib as for producer. Let’s spawn consumer asynchronously with tokio:</p><pre>let futures = (0..3)<br>    .map(|_| {<br>        tokio::spawn({<br>            kafka::KafkaConsumer::receive_messages(cfg.clone(), db_worker)<br>        })<br>    });<br>info!(&quot;Spawning  consumers in  {} threads&quot;, futures.len() as i32);<em><br></em>for thread in futures {<br>    thread.await;<br>}</pre><p>Both, consuming messages and actix server should be joined with same DB worker:</p><pre>join(<br>    kafka::start_consumer(cfg.clone(), &amp;DB),<br>    start_server(cfg.host.as_str(), cfg.port, &amp;DB),<br>).await;</pre><p>And finally we need to start consumer in infinite loop:</p><pre>let mut msg_stream = consumer.start();<br><em>// iterate over all messages blocking<br></em>while let Some(msg) = msg_stream.next().await {<br>    <em>// we cant borrow cfg to the async function, since that would require static a lifetime<br>    // therefore, we copy it<br>    </em>info!(&quot;Got the message {:?}&quot;, msg);<br>    let cfg = cfg.clone();<br><br>    match msg {<br>        Ok(msg) =&gt; {<br>            <em>// payload can be empty<br>            </em>match msg.payload() {<br>                Some(payload) =&gt; {<br>                    let str_msg = str::from_utf8(payload).unwrap();<br>                    let users: Vec&lt;common::User&gt; = serde_json::from_str(&amp;str_msg).unwrap();<br>                    debug!(&quot;Received message: {}&quot;, str_msg);<br>                    info!(&quot;Received users: {}&quot;, users.len());<br>                    for user in users {<br>                        db_worker.insert_user(user).await;<br>                    }<br>                }<br>                None =&gt; {<br>                    error!(&quot;Message with empty payload&quot;);<br>                }<br>            }<br>            <em>// now we can store the offset to be committed in the next auto-commit so this<br>            // message will never be processed again<br>            </em>let res = consumer.store_offset(&amp;msg);<br>            match res {<br>                Ok(()) =&gt; {}<br>                Err(e) =&gt; error!(&quot;Could not commit message: {} &quot;, e)<br>            }<br>        }<br>        Err(e) =&gt; {<br>            error!(&quot;Could not receive and will not process message: {}&quot;,e)<br>        }<br>    };<br>}</pre><p>Comments are provided directly in code. Compile and run. Now we have rest endpoints with users stored in database. Let’s develop frontend application in rust.</p><p>For frontend I found yew UI framework. It looks nice and I am familiar with React :)</p><p><em>Yew is a modern Rust framework for creating multi-threaded front-end web apps with WebAssembly.</em></p><ul><li><em>Features a macro for declaring interactive HTML with Rust expressions. Developers who have experience using JSX in React should feel quite at home when using Yew.</em></li><li><em>Achieves high performance by minimizing DOM API calls for each page render and by making it easy to offload processing to background web workers.</em></li><li><em>Supports JavaScript interoperability, allowing developers to leverage NPM packages and integrate with existing JavaScript applications.</em></li></ul><p>Checking yew guidelines, they recommended to go with trunc. Let’s install it:</p><blockquote>cargo install trunk wasm-bindgen-cli</blockquote><p>Yew uses next components circle:</p><p>create -&gt; update -&gt; change -&gt; view</p><p>Need to implement this hooks.</p><p>But before determine structures:</p><pre>enum Msg {<br>    MakeReq,<br>    Resp(Result&lt;UsersResponse, anyhow::Error&gt;),<br>}<br><br><br>struct UsersApp {<br>    link: ComponentLink&lt;Self&gt;,<br>    users: Option&lt;Vec&lt;User&gt;&gt;,<br>    fetch_task: Option&lt;FetchTask&gt;,<br>}</pre><p>Then need to implement Component interface for UserApp</p><pre>impl Component for UsersApp {<br>    type Message = Msg;<br>    type Properties = ();<br>    fn create(_props: Self::Properties, link: ComponentLink&lt;Self&gt;) -&gt; Self {<br>        link.send_message(Msg::MakeReq);<br>        Self {<br>            link,<br>            users: None,<br>            fetch_task: None,<br>        }<br>    }</pre><p>Just init components and send message to make a request</p><p>Next hook:</p><pre>fn update(&amp;mut self, msg: Self::Message) -&gt; ShouldRender {<br>    match msg {<br>        Msg::MakeReq =&gt; {<br>            self.users = None;<br>            let req = Request::get(&quot;http://localhost:11007/users&quot;)<br>                .body(Nothing)<br>                .expect(&quot;can make req to users endpoint&quot;);<br><br>            let cb = self.link.callback(<br>                |response: Response&lt;Json&lt;Result&lt;UsersResponse, anyhow::Error&gt;&gt;&gt;| {<br>                    let Json(data) = response.into_body();<br>                    Msg::Resp(data)<br>                },<br>            );<br><br>            let task = FetchService::fetch(req, cb).expect(&quot;can create task&quot;);<br>            self.fetch_task = Some(task);<br>            ()<br>        }<br>        Msg::Resp(resp) =&gt; {<br>            if let Ok(data) = resp {<br>                self.users = Some(data.users);<br>            }<br>        }<br>    }<br>    true<br>}</pre><p>for update hook we requesting users, deserialize them and assign to UsersApp.users property</p><p>Leave change hook empty for now</p><p>just posting code here:</p><pre>&lt;div class=classes!(&quot;content&quot;)&gt;<br>                       &lt;Router&lt;AppRoute, ()&gt;<br>                           render = Router::render(move |switch: AppRoute| {<br>                               match switch {<br>                                   AppRoute::Detail(user_id) =&gt; {<br>                                       html! {<br>                                           &lt;div&gt;<br>                                                &lt;user::detail::Detail user_id=user_id/&gt;<br>                                           &lt;/div&gt;}<br>                                   }<br>                                   AppRoute::Home =&gt; {<br>                                       html! {<br>                                           &lt;div&gt;<br>                                               &lt;div class=classes!(&quot;refresh&quot;)&gt;<br>                                                   &lt;button onclick=cb.clone()&gt;<br>                                                       { &quot;refresh&quot; }<br>                                                   &lt;/button&gt;<br>                                               &lt;/div&gt;<br>                                               &lt;user::list::List users=users.clone()/&gt;<br>                                           &lt;/div&gt;<br>                                       }<br>                                   }<br>                               }<br>                           })<br>                       /&gt;<br>                   &lt;/div&gt;<br>               &lt;/div&gt;<br>           }<br>}</pre><p>yew uses html macro, which allows to insert html elements. Also use yew-router library to implement react like component routing:</p><pre>AppRoute::Detail(user_id) =&gt; {<br>    html! {<br>        &lt;div&gt;<br>             &lt;user::detail::Detail user_id=user_id/&gt;<br>        &lt;/div&gt;}<br>}</pre><p>directly loads users details in to single page application. Not posting code of list component and user details component, because it pretty the same and implements the same concepts. Will post the link to Github repo at the end.</p><p>Main function is pretty simple:</p><pre>fn main() {<br>    yew::start_app::&lt;UsersApp&gt;();<br>}</pre><blockquote>trunk serve</blockquote><p>Application is up and running. Webassembly is nice, so fast. :)</p><p>Conclusions:</p><ol><li>Rust is nice :)</li><li>It is possible to implement microservices with Rust. Of course with Java I can implement it with less code and faster, but might be that’s because I am using Java for more than 10 years :). But if you need an application, pointed on high performance and less resource usage, Rust is a choice. There are posts in internet of usage Rust in production for webdevelopment.</li><li>Yew works nice. It is possible to implement webassembly modules, but debugging can be a case. Using console.log and other stuff is not so convenient as for js/typescript.</li><li>Rust can use C/C++ libs with match more convenient interfaces. It can fill the gaps.</li><li>With it features Rust can be the language for next 20 years. My opinion is that Rust is what C++ can be without backward compatibility :).</li><li>Development of web application with Rust is not so hard as I expected, pretty same as Java and Go. But still not so mature as Java frameworks like Spring.</li></ol><p>And finally <a href="https://github.com/aviplayer/rust_microservices">link to Github repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a85f60122c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There are a lot of talks about Rust.]]></title>
            <link>https://medium.com/@andrew.visokih_88808/there-are-a-lot-of-talks-about-rust-52b99b3bcdc6?source=rss-46d6786ef29------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b99b3bcdc6</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Andrew Visokih]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 18:53:16 GMT</pubDate>
            <atom:updated>2021-08-13T21:04:32.091Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a lot of talks about Rust. How it is safe and performance of it. Also it is positioning to replace C++. But what about web development. We know about wasm. But almost nothing about web server.<br>I was playing with Rust for several months. Nothing special. Algorithms, wasm, other basic concepts. Rust completely changed my mind. That was not easy way for me to get aquatinted with all concepts like borrowing, life time, smart pointers and etc… But what about web development? How easy is to write code on Rust?</p><p>I decided to start from plain application with several layers. Just routine tasks for web development:</p><blockquote>get something from DB and provide API response. Nothing interesting. Just only one thing. I was trying to do it in Rust.</blockquote><p>The idea is that we have several types of notifications: email, sms and web hooks. We just need to get all notifications and get particular notification by Id. Thats all.</p><p>My current stack is Java 11 + Spring Boot. We are using reactive Reactive stack (r2dbc with postgress, spring boot webflux and other stack based on Reactor Netty ). I tried to find something similar.</p><p>There is a story about Actix Web. For some time it was the performance leader. Also interesting story about it. But what about db access? Actix doesn’t have any. I tried to find something uses asynchronous approach. Tokio is the most famous approach. I decided to try tokio-postgres for db access level. <br>Before start coding one clause still not covered. DB migrations. I found refinery: makes running migrations for different databases as easy as possible. Let’s start from migrations:</p><p>let’s set up rafinery. All migrations are inside migrations directory:</p><pre>mod embedded {<br>    use refinery::embed_migrations;<br><br>    embed_migrations!(&quot;migrations&quot;);<br>}</pre><p>Let’s implement migration logic:</p><pre>async fn run_migrations() -&gt; std::result::Result&lt;(), Error&gt; {<br>    println!(&quot;Running DB migrations...&quot;);<br>    let db_string =  &amp;format!(&quot;host={} port={} user={} password={} dbname={}&quot;, &quot;localhost&quot;, 11001, &quot;local&quot;, &quot;local&quot;, &quot;notifications_db&quot;);<br>    let (mut client, con) =<br>        tokio_postgres::connect(db_string, NoTls)<br>            .await.expect(&quot;Connection failed&quot;);<br><br>    tokio::spawn(async move {<br>        if let Err(e) = con.await {<br>            eprintln!(&quot;connection error: {}&quot;, e);<br>        }<br>    });<br>    let migration_report = embedded::migrations::runner()<br>        .run_async(&amp;mut client)<br>        .await?;<br>    for migration in migration_report.applied_migrations() {<br>        println!(<br>            &quot;Migration Applied -  Name: {}, Version: {}&quot;,<br>            migration.name(),<br>            migration.version()<br>        );<br>    }<br>    println!(&quot;DB migrations finished!&quot;);<br><br>    Ok(())<br>}</pre><p>And finally main function with annotation to use tokio runtime:</p><pre>#[tokio::main]<br>async fn main() {<br>    run_migrations().await.expect(&quot;can&#39;t run DB migrations: {}&quot;);<br>}</pre><p>That’s all. Is it easy?</p><p>Now let’s implement server. Actix has it own runtime. There will be a separate module.<br>Lets create server…</p><pre>pub(crate) async fn start_server() -&gt; std::io::Result&lt;()&gt; {<br>    let server_address = &quot;127.0.0.1:3005&quot;;<br>    println!(&quot;Server is running {}&quot;, server_address);<br>    let server = HttpServer::new(|| {<br>        App::new()<br>            .wrap(middleware::Logger::default())<br>            .configure(Router::init_routes)<br>    })<br>        .bind(server_address)?<br>        .run()<br>        .await?;<br>    Ok(server)<br>}</pre><p>We specified server and port. Added logger middleware and specify router function. Router will be implemented later.<br>Looks also easy. No need an additional explanation.</p><p>Now routers need to be implemented. Let start from db access layer implementation.<br>I started with specifying connection pool structure:</p><pre>#[derive(Clone)]<br>pub struct PgConnection {<br>    pub config: Config,<br>    pub pg_connection: Option&lt;Pool&gt;,<br>}</pre><p>Pool and Config are members of crate deadpool_postgres.<br>PgConnection implementation:<br>first of all lets specify <em>create_config() -&gt; Config</em> method. Nothing interesting. Just creating a Postgress config.<br>Than lets implement constructor:</p><pre>pub fn new() -&gt; PgConnection {<br>    let config = PgConnection::create_config();<br>    PgConnection {<br>        config,<br>        pg_connection: None,<br>    }<br>}</pre><p>Simple constructor with no connections available. <br> Utility method for creating pool of connections:</p><pre>fn new_connection(&amp;self) -&gt; Pool {<br>    match self.config.create_pool(NoTls) {<br>        Ok(pool) =&gt; {<br>            pool<br>        }<br>        Err(error) =&gt; {<br>            panic!(&quot;Connection Pool Critical Error: \n{}&quot;, error);<br>        }<br>    }<br>}</pre><p>And finally create connection:</p><pre>pub fn create_connection(&amp;mut self) {<br>    let pool = self.new_connection();<br>    self.pg_connection = Some(pool);<br>}</pre><p>then last method is method for accessing the client, which directly communicates with Db:</p><pre>async fn get_client(&amp;mut self) -&gt; Client {<br>    let pool = match &amp;self.pg_connection {<br>        Some(pool) =&gt; {<br>            pool<br>        }<br>        None =&gt; {<br>            &amp;self.create_connection();<br>            self.pg_connection.as_ref().unwrap()<br>        }<br>    };<br>    match pool.get().await {<br>        Ok(client) =&gt; client,<br>        Err(error) =&gt; {<br>            eprint!(&quot;Connection error: \n {}&quot;, error);<br>            let pool = self.new_connection();<br>            let client = pool.get().await.unwrap();<br>            self.pg_connection.replace(pool);<br>            client<br>        }<br>    }<br>}</pre><p>Implementation is pretty straightforward. We are checking the connection. If connection we are using it, if not we just creating connection. Then we need client to communicate with DB. if we are getting an error, we assume, connection is not available. We just need to recreate it and return new db client. Go to implementation of directly db requests. First is insert operation:</p><pre>pub async fn insert_notification(&amp;<em>&#39;a </em>mut self, db_notification: &amp;DbENRecord) -&gt; Result&lt;i32, Error&gt; {<br>    let client = self.get_client().await;<br>    let stmt = client.prepare(INSERT_NOTIFICATION).await.unwrap();<br>    let rows = client.query(&amp;stmt,<br>                            &amp;[&amp;db_notification.title, &amp;db_notification.notification_type, &amp;db_notification.template,<br>                                &amp;db_notification.email, &amp;db_notification.pwd, &amp;db_notification.smtp_server,<br>                                &amp;db_notification.smtp_port, &amp;db_notification.description])<br>        .await?;<br>    let value: i32 = rows[0].get(0);<br>    print!(&quot;New Id {}&quot;, value);<br>    Ok(value)<br>}</pre><p>Method returns a new id.<br> DbENRecord is an object model of notification:</p><pre>#[derive(Debug, serde::Serialize)]<br>pub struct DbENRecord {<br>    id: i32,<br>    title: String,<br>    notification_type: i32,<br>    template: String,<br>    email: String,<br>    pwd: String,<br>    smtp_server: String,<br>    smtp_port: i32,<br>    description: String,<br>}</pre><p>INSERT_NOTIFICATION is a constant</p><pre>const INSERT_NOTIFICATION: &amp;str = &quot;insert into email_notifications<br>(title, notification_type, template, email, pwd, smtp_server, smtp_port, description)<br>values($1, $2, $3, $4, $5, $6, $7, $8)<br>returning id&quot;;</pre><p>Go to select all records implementation.</p><pre>pub async fn select_notifications(&amp;mut self) -&gt; Result&lt;Vec&lt;DbENRecord&gt;, Error&gt; {<br>    let client = self.get_client().await;<br>    let stmt = client.prepare(SELECT_NOTIFICATIONS).await.unwrap();<br>    let rows = client.query(&amp;stmt, &amp;[]).await?;<br>    let mut result: Vec&lt;DbENRecord&gt; = Vec::new();<br>    {<br>        for row in rows {<br>            let record = DbENRecord::record_from_future(row);<br>            result.push(record);<br>        }<br>    }<br>    Ok(result)<br>}</pre><p>where <br>SELECT_NOTIFICATIONS is a request constant:<br><br>record_from_future is an implementation of DbENRecord deserialization function.</p><pre>const SELECT_NOTIFICATIONS: &amp;str = &quot;select id, title, notification_type, template, email, pwd, smtp_server, smtp_port, description<br>from email_notifications&quot;;<br>const SELECT_NOTIFICATION: &amp;str = &quot;<br>where id=$1&quot;;</pre><p>That all for db layer. There are some additional methods and tests. If you interested in just check the repository, will provide link at the end.</p><p>Now router…</p><pre>pub async fn get_notifications(db: web::Data&lt;PgConnection&gt;) -&gt; Result&lt;HttpResponse&lt;Body&gt;, Error&gt; {<br>    let records = Runtime::new()<br>        .expect(&quot;Failed to create Tokio runtime&quot;)<br>        .block_on(db.select_notifications_imut());<br>    Router::return_response(records)<br>}</pre><p>A blocking call of select. One thing is that we need to create tokio runtime for this. There are 2 different runtimes.</p><p>In <em>main.rs</em> we determine, that we are using actix runtime:</p><pre>#[actix_web::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    std::env::set_var(&quot;RUST_LOG&quot;, &quot;actix_web=trace&quot;);<br>    env_logger::init();<br>    start_server()<br>        .await<br>}</pre><p>But we are making requests using tokio. It needs its own runtime. That is why I created it. Also return_response:</p><pre>fn return_response&lt;T&gt;(db_res: Result&lt;T, tokio_postgres::Error&gt;) -&gt; Result&lt;HttpResponse&lt;Body&gt;, Error&gt;<br>where T: serde::Serialize<br>{<br>    let res = db_res.map(|recs| HttpResponse::Ok().json(recs))<br>        .map_err(|err| {<br>            eprintln!(&quot;{}&quot;, err);<br>            HttpResponse::InternalServerError()<br>        })?;<br>    Ok(res)<br>}</pre><p>No need any explanations. As for person, who is aware about web development, can easy understand what is happening.<br> And finally init routers function itself:</p><pre>pub fn init_routes(config: &amp;mut web::ServiceConfig) {<br>    let mut pool = PgConnection::new();<br>    pool.create_connection();<br><br>    config<br>        .data(pool)<br>        .route(&quot;/notifications&quot;, web::get().to(Router::get_notifications))<br>        .route(&quot;/notifications/{id}&quot;, ....</pre><p>Implementation of methods has been explained before. Weekend finished. Tomorrow java is waiting for me.</p><p>Conclusions:</p><p>1. Of course development with such mature frameworks as Spring with it Dependency Injection and Inversion of Control is much faster and cleaner than such low level implementation in Rust. But the main case is performance. And using Rust it possible to implement fast web server.</p><p>2. Code is quite clear and there are no any headache to implement server with Rust.<br> 3. Rust generics are awesome. :)<br> 4. One more case of usual web-development is not covered. Processing… I will investigate an ability Rust to work with Kafka.</p><p><a href="https://github.com/aviplayer/notifications_rust">Github link to the repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b99b3bcdc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>