<?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 itwasneo on Medium]]></title>
        <description><![CDATA[Stories by itwasneo on Medium]]></description>
        <link>https://medium.com/@itwasneo?source=rss-471a81bad400------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E6Ti4Ej03bCM-S32ew8iMA.jpeg</url>
            <title>Stories by itwasneo on Medium</title>
            <link>https://medium.com/@itwasneo?source=rss-471a81bad400------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:09:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itwasneo/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[On Luck and Uncertainty]]></title>
            <link>https://medium.com/@itwasneo/on-luck-and-uncertainty-b75a20d0df68?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/b75a20d0df68</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[luck]]></category>
            <category><![CDATA[uncertainty]]></category>
            <category><![CDATA[self]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 16:38:15 GMT</pubDate>
            <atom:updated>2023-07-26T16:38:15.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-YemHE6xGUWICa2O" /><figcaption>Photo by <a href="https://unsplash.com/@soymeraki?utm_source=medium&amp;utm_medium=referral">Javier Allegue Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The reality that you have no effect on should <strong>NOT</strong> affect the way you live.</p><p>Some people may seem <em>luckier</em> than you <strong>OR</strong> they made and keep making better choices than you. You have <strong>NO</strong> power on that.</p><p>You can’t manage the <em>uncertainty</em>. Trying to <strong>manage</strong> the uncertainty results in crisis. You can only <strong>fight</strong> with it.</p><p>Chances and opportunities are not as rare as commonly thought.</p><p>Yes, there are <em>turning points</em> in life, but compared to those chances and opportunities, the <strong>intangible</strong> reality has much more power on these points than your willpower (sadly).</p><p>That’s why it is logically pointless and extremely shallow to envy other people’s lives.</p><p>Sincerely everybody knows that if there was a choice, they would pick their own <strong>inner-self</strong> again and again. All the other choices would depend on the external factors.</p><p>You can only <strong>fight</strong> with the <em>uncertainty</em>.</p><p>As long as it can’t go beyond its senses, the reality of one is its <em>life</em> it <strong>experiences</strong>.</p><p>Enjoying the <strong>fight</strong> with the <em>uncertainty</em> would make that <strong>experience</strong> even more enjoyable.</p><p>No matter what their thoughts are on themselves, everybody is a being and has a <strong>relative</strong> value for every other being.</p><p>It is irrelevant to <strong>rage against</strong> the value that you don’t prefer. It is relevant to <strong>fight</strong> for changing it.</p><p><em>P.S. You can put a question mark at the end of each sentences above and answer them with “it depends!” like a true senior.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b75a20d0df68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Pair Program with ChatGPT]]></title>
            <link>https://medium.com/@itwasneo/lets-pair-program-with-chatgpt-6e824775a458?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e824775a458</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[notetaking]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 20:16:53 GMT</pubDate>
            <atom:updated>2022-12-20T20:16:53.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6i1DKkl5OTLwbeq" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wanted to create a program, but weren’t sure where to start 🤔? Or maybe you have an idea for a program, but don’t have the skills or knowledge to implement it on your own . In this blog post, I’ll show you how you can use a language model 🤖 to help you write a program, step by step 🚀.</p><p>A language model is a type of artificial intelligence that has been trained to understand and generate natural language. This allows it to answer questions , provide explanations , and even write code , making it a powerful tool for anyone interested in programming 💡.</p><p>In this post, we’ll use a language model to write a simple program together , and see how it can help us overcome common challenges and obstacles along the way 🛠. So let’s get started! 🚀</p><p># As always you can find the project repository <a href="https://github.com/itwasneo/sb-capture-browser">here</a>.</p><h4>Creating a Directory Watcher with a Language Model</h4><p>In the book “Building a Second Brain” by Tiago Forte, the author talks about the importance of capturing and organizing the daily influx of information in order to increase productivity and creativity. This concept inspired me to create the directory watcher program that we will be working on.</p><p>In this story, we will be writing a Rust program that tracks changes to the Bookmarks file of the Brave browser. This program, called a directory watcher, will monitor the specified directory and detect when the Bookmarks file is created, deleted, or modified. The directory watcher will then log these changes to a file, allowing you to keep track of your Bookmarks and ensure that they are up to date.</p><p>Our goal is to create a useful tool that can help Brave users manage and organize their Bookmarks more effectively. By using a language model to assist with the program’s implementation, we will be able to quickly and easily create a functional directory watcher that can be used by anyone with a Brave browser. This will not only benefit the users of the directory watcher, but also demonstrate the capabilities of language models for programming tasks.</p><p># Let’s ask our first question to ChatGPT, because I don’t know how to track the events in a file directory in Rust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*u3grCMgTf7TjHBJrB3_ghw.png" /></figure><p># Well, it seems promising. What if I don’t want to track the current directory, what if I want to give the directory as a command line argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*dxrlONGygPWhdGfnl1qx-g.png" /></figure><p># Wow, I have FileTrackerCommand struct now 😄. Cool we are going great. Or are we? If you implement the code as we go, you would notice that there are actually lots of compilation errors. There is no “prompt” crate for example. (well there is if you look at the <a href="https://crates.io/">crates.io</a>, but that’s not we are looking for). Or there is no “watcher” function that will create a new watcher instance. When I ask about the “prompt” crate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*SZIJqOOjCyNpZLayJpFPtw.png" /></figure><p># ChatGPT has no access to the internet, external resources such as crates or libraries etc.. As it mentioned in the second paragraph it only provides the intuition and the necessities when it comes to code generation as the context of the code get broader and broader(that is my observation). Finding the right crate and implementing it in the context that ChatGPT provide is up to you. I know how to get command line arguments with standard library std::env, but I wonder whether ChatBot has a better solution because I want to use tagged command line arguments for possible features that I wanted to implement in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*EmS5C9i5npGTjt0mCMULAQ.png" /></figure><p># clap crate seems very promising. I used it to extract “-d” tagged command line argument for directory.</p><p>In general, most web browsers, including Brave, will save bookmarks on a user’s local machine in a file or database. This allows the user to access their bookmarks even when they are not connected to the internet. The specific details of how this is done, including the location of the file or database on a Linux machine, can vary depending on the browser and the specific settings and configuration of the user’s system.</p><p># Brave browser keeps your Bookmarks in a file called “Bookmarks” (without the extension) in JSON format. Everytime you add a new bookmark, it deletes old Bookmark file and creates a new one. So what we need is to track the Create and Delete events happening in the directory where the Bookmarks file is present. Let’s ask how we track only the Create and Delete events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Di_ROxkeXwfx0cL3GhwWkQ.png" /></figure><p># It seems fine again, but this time it also gave me an alternative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*URVOkfqrnLd615hcT0VDCA.png" /></figure><p># Well, that’s interesting because, I would definitely want to filter the event before I process them 👌👌But again, if you try to run this code as it is, it will give lots of errors, especially for watcher implementation. Here ChatGPT gives the general idea (maybe the code that it provides were actually valid for the previous versions of the crate, that might also be the case.) Anyway I modified the code to the following, you can compare and judge by yourself.</p><pre>use clap::{arg, command, value_parser};<br>use notify::{<br>    event::{ModifyKind, RenameMode},<br>    Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher,<br>};<br>use std::{<br>    path::{Path, PathBuf},<br>    sync::mpsc::{channel, RecvError},<br>};<br><br>// Define a custom command for tracking changes to a directory<br>#[derive(Debug)]<br>struct FileTrackerCommand {<br>    directory: String,<br>}<br><br>impl FileTrackerCommand {<br>    fn execute(&amp;self) -&gt; Result&lt;(), RecvError&gt; {<br>        // Create a channel to receive file system events<br>        let (tx, rx) = channel();<br><br>        // Create a file watcher that listens for events in the specified directory<br>        let mut watcher = RecommendedWatcher::new(tx, Config::default()).unwrap();<br>        watcher<br>            .watch(Path::new(&amp;self.directory), RecursiveMode::Recursive)<br>            .unwrap();<br><br>        // Listen for file system events<br>        for event in rx.iter().filter_map(|event| match event {<br>            Ok(e) =&gt; {<br>                if e.kind == EventKind::Modify(ModifyKind::Name(RenameMode::Both))<br>                   &amp;&amp; e.paths.contains(&amp;PathBuf::from(&quot;/home/man/snap/brave/188/.config/BraveSoftware/Brave-Browser/Default/Bookmarks&quot;)) {<br>                    Some(e)<br>                } else {<br>                    None<br>                }<br>            }<br>            Err(_err) =&gt; None,<br>        }) {<br>            println!(&quot;{:?}&quot;, event)<br>        }<br><br>        Ok(())<br>    }<br>}<br><br>fn main() -&gt; Result&lt;(), RecvError&gt; {<br>    // Parse command line arguments<br><br>    let matches = command!()<br>        .arg(arg!(dir: -d &lt;DIRECTORY&gt;).value_parser(value_parser!(String)))<br>        .get_matches();<br>    // Create a FileTrackerCommand instance using the value of the `-d` or `--directory` argument<br>    let command = FileTrackerCommand {<br>        directory: matches.get_one::&lt;String&gt;(&quot;dir&quot;).unwrap().to_owned(),<br>    };<br><br>    // Execute the command<br>    command.execute()<br>}</pre><p>After conducting some tests, I discovered that when I add a new bookmark to my web browser, multiple events are emitted by the file system in the directory that I am monitoring with my tracker. It is difficult to distinguish between these events and take appropriate actions based on them. Therefore, I have decided to add another task to my program which will periodically check the modification date of the Bookmarks file, in order to better track and respond to changes to the bookmarks. This will allow me to more accurately monitor and manage the bookmarks in my web browser.</p><p># In order to achieve this, let’s first ask how to track a files modification date periodically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*77pr-VTpWwfbNsnUOpBHGg.png" /></figure><p># Again seems promising, but I want this task to be run concurrently with the directory tracker. It would be really good if it also uses rust’s async runtime “tokio”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*iMbdJwxBtSeDGjCdUnoNcA.png" /></figure><p># Sometimes it freezes and doesn’t give you the full answer. First thing that comes to my mind was “continue” maybe ? please?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*WXcX4QmDw3d857MamozdsA.png" /></figure><p># Aaand it continues 😄. It messes up with formatting but I don’t think I’m in the place of whining 😄😄😄</p><p>At this point, I need to make some modifications to the code in order to make it compatible with our current setup and run properly.</p><pre>use clap::{arg, command, value_parser};<br>use notify::{<br>    event::{ModifyKind, RenameMode},<br>    Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher,<br>};<br>use std::{<br>    fs::{self, File},<br>    io::Write,<br>    path::{Path, PathBuf},<br>    sync::{Arc, Mutex},<br>    time::Duration,<br>};<br>use tokio::{join, runtime::Handle, sync::mpsc::channel};<br><br>type FileMutex = Arc&lt;Mutex&lt;File&gt;&gt;;<br><br>async fn check_file(file_path: String, check_interval: Duration, output_file: FileMutex) {<br>    loop {<br>        let initial_metadata = fs::metadata(file_path.clone()).unwrap();<br>        let initial_modified_time = initial_metadata.modified().unwrap();<br><br>        tokio::time::sleep(check_interval).await;<br><br>        let current_metadata = fs::metadata(file_path.clone()).unwrap();<br>        let current_modified_time = current_metadata.modified().unwrap();<br><br>        if initial_modified_time != current_modified_time {<br>            let mut output_file = output_file.lock().unwrap();<br>            output_file<br>                .write_all(&quot;The file&#39;s modification time has changed\n&quot;.as_bytes())<br>                .unwrap();<br>        }<br>    }<br>}<br><br>async fn check_directory(directory_path: String, output_file: FileMutex) {<br>    let (tx, mut rx) = channel::&lt;Event&gt;(1);<br>    let target_file = PathBuf::from(format!(&quot;{}{}&quot;, directory_path, &quot;Bookmarks&quot;));<br>    let handle = Handle::current();<br><br>    let mut watcher = RecommendedWatcher::new(<br>        move |res: Result&lt;Event, notify::Error&gt;| {<br>            handle.block_on(async { tx.send(res.unwrap()).await.unwrap() })<br>        },<br>        Config::default(),<br>    )<br>    .unwrap();<br><br>    watcher<br>        .watch(Path::new(&amp;directory_path), RecursiveMode::Recursive)<br>        .unwrap();<br>    while let Some(event) = rx.recv().await {<br>        if event.kind == EventKind::Modify(ModifyKind::Name(RenameMode::Both))<br>            &amp;&amp; event.paths.contains(&amp;target_file)<br>        {<br>            let mut output_file = output_file.lock().unwrap();<br>            output_file<br>                .write_all(format!(&quot;{:?}\n&quot;, event).as_bytes())<br>                .unwrap();<br>        }<br>    }<br>}<br><br>#[tokio::main]<br>async fn main() {<br>    // Parse command line arguments<br>    let matches = command!()<br>        .arg(arg!(file: -f &lt;FILE&gt;).value_parser(value_parser!(String)))<br>        .arg(arg!(directory: -d &lt;DIRECTORY&gt;).value_parser(value_parser!(String)))<br>        .get_matches();<br><br>    let file_arg = matches.get_one::&lt;String&gt;(&quot;file&quot;).unwrap();<br>    let dir_arg = matches.get_one::&lt;String&gt;(&quot;directory&quot;).unwrap();<br>    let file_path = format!(&quot;{}{}&quot;, dir_arg, file_arg);<br>    let dir_path = dir_arg.to_owned();<br>    let check_interval = std::time::Duration::from_secs(5);<br>    let file = fs::File::create(&quot;./test.txt&quot;).unwrap();<br>    let file_mutex = Arc::new(Mutex::new(file));<br>    let file_checker_mutex = Arc::clone(&amp;file_mutex);<br><br>    let (_first, _second) = join!(<br>        tokio::spawn(async move {<br>            check_file(file_path, check_interval, file_checker_mutex).await;<br>        }),<br>        tokio::spawn(async move {<br>            check_directory(dir_path, file_mutex).await;<br>        })<br>    );<br>}</pre><p># Here, I wanted to log the events in common text file (<strong>test.txt</strong>), so that I could be assured the concurrent tasks are working correctly.</p><p>If you want to log the events that are generated by the two tasks in a common text file, you can use a mutex to ensure that only one task can write to the file at a time. A mutex (short for “mutual exclusion”) is a synchronization mechanism that allows multiple threads to share access to a resource, but only one thread can access the resource at a time. This can be useful in cases where multiple tasks need to access the same resource, but the resource is not designed to be accessed concurrently.</p><p>To determine which link was added as a bookmark, you can store the previous state of the bookmark file and compare it to the current state whenever a new event occurs. You can do this by reading the initial state of the bookmark file and storing it in a variable, and then reading the current state of the file whenever a change event is detected. You can then compare the initial and current states of the file to determine which link was added. You can do this comparison using a function that takes the initial and current states as arguments and returns the added bookmark as a string. This way, you can determine which link was added to the bookmark file whenever a change event is detected, and you can update the previous state variable to the current state to prepare for the next change event.</p><p># Instead of string comparison between old and new state of Bookmark file content, let’s deserialize the content into proper rust structs. If you look at the Brave Browser’s Bookmark file content it has the structure such as in the prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*cDO-9xeGBuXZn9P3aECSUQ.png" /></figure><p># I know this was probably the simplest task that I gave to ChatGPT until now, but wasn’t this very intuitive? Did you notice the directory <em>enum</em> and the “not use of <em>type</em> keyword as a field using serde feature”. It has few missing optional fields here and there but what it is more than enough…In order to keep track of each bookmark, I need to store them. Looking at this structure, I think I need an extractor function that will recursive look at each Folder inside the Bookmarks object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*_7IAGxfRVz-QgaM7MMRwBw.png" /></figure><p># Look at this function… It uses <em>VecDeque</em> LOL. It would be better if it were be storing Bookmarks inside a hash map instead of a Vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*oB4WddztWoAURUfpTun5Jw.png" /></figure><p># That’s better. But we still have a slight problem here. Child struct it provided has no field for keeping its <em>parent</em> folder. I need to know that information because I only want the Bookmarks that are accumulating under “<em>capture</em>” folder. (Which is the first step of Note Taking explained in the Tiago Forte’s book: <em>capture</em> — <em>organize</em>— <em>distill</em> — <em>express</em>)Let’s ask how we can overcome this problem, shall we…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*xPkoa4BkdbbDrYkL6Ru31g.png" /></figure><p># …. I can definitely live with this, but it’s a little bit over-engineered. Since I will only look up for single folder name, I decided to manually search for the folder name, and extract the Bookmarks under it. After some modifications, I had a working piece of code that accumulates all the articles and resources that I bookmarked for further processing…</p><p>As the curtains close on this journey through the inner workings of ChatGPT, it is time to reveal the shocking truth: the vast majority of this article, including the code snippets and analysis, were not written by a human, but rather by the very machine learning model that we set out to explore.</p><p>Yes, you read that correctly. ChatGPT, the language model trained by OpenAI, was responsible for crafting the vast majority of this story, leaving only a skeletal outline for a human writer to flesh out.</p><p>This may come as a surprise to some, but it is a testament to the incredible capabilities of modern machine learning models. ChatGPT has proven itself to be not just a tool, but a true collaborator, capable of generating complex and nuanced content with a level of detail and accuracy that rivals that of a human expert.</p><p>As we move forward into an increasingly automated world, it is important to not only be aware of the capabilities of these powerful models, but to also consider their potential impact on various industries and disciplines.</p><p>It’s important to note that while ChatGPT was a valuable collaborator, the code snippets provided did require some modification to work correctly. It’s always important to verify any information or suggestions you receive, even if they come from a language model like myself. 🧐 So while I hope that I was able to assist you in creating this piece, I encourage you to do your own research and due diligence to ensure that the final product is accurate and reliable. 🔍</p><p>I couldn’t have done it without Assistant’s help, and I’m grateful for its assistance in creating this piece. So, a huge thank you to ChatGPT for its invaluable contribution. 🙏</p><p>The future may be uncertain, but one thing is certain: ChatGPT and other advanced language models will play a crucial role in shaping it.</p><p># <strong>MAJOR NOTE</strong>: Everything except the comments that are starting with the # sign belongs to the ChatGPT, emojis included… See you in next story 👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e824775a458" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark Side of the Deserialization in Java: Solution was with us for years]]></title>
            <link>https://medium.com/@itwasneo/dark-side-of-the-deserialization-in-java-solution-was-with-us-for-years-4badb819be3d?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/4badb819be3d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java-records]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[deserialization]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 14:23:03 GMT</pubDate>
            <atom:updated>2022-11-21T14:23:03.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xWqM9BHL89NqQw7r" /><figcaption>Photo by <a href="https://unsplash.com/@dennyshess?utm_source=medium&amp;utm_medium=referral">Dennys Hess</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Around a month ago, there was a <strong>Devoxx</strong> conference for Java held in Belgium. I’ve always liked Devoxx conferences. They have really good talks. <a href="https://www.youtube.com/watch?v=WWsN9Y5OtZQ">One</a> of those talks was on <em>object deserialization </em>in Java and possible exploits it may cause. Yes, I know this is a really old topic, there has been around for years, but still I believe that it should be addressed more, especially while <strong>modern</strong> Java has been providing very simple and elegant solutions. This will be a relatively short story with a small example resolving the problem.</p><p><a href="https://github.com/itwasneo/classes-vs-records"><strong>PROJECT REPOSITORY</strong></a></p><h4>What is wrong with the deserialization anyway?</h4><p>Well it’s simple, Java does NOT use public constructors to deserialize objects to their corresponding classes, which means that any <strong>validation</strong> or <strong>logic</strong> that you apply during class instance creation will not be applied during <em>deserialization</em>. 🤔 It may already sound very suspicious and dangerous, but it will be crystal clear with an example</p><h4>REST API with activej</h4><p>Let’s create a simple REST API that has 2 POST endpoints (<strong>/class</strong>, <strong>/record</strong>) using <a href="https://activej.io/"><em>activej</em></a> (another very cool Java web framework). Basically, we’re going to send the same JSON object to these endpoints. One of the endpoints will try to <em>deserialize</em> to a Java <em>Class </em>and the other one will try to <em>deserialize </em>it to Java <em>Record</em>.</p><pre>package com.itwasneo.activejhttptemplate;<br><br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import io.activej.bytebuf.ByteBuf;<br>import io.activej.http.*;<br>import io.activej.inject.Injector;<br>import io.activej.inject.annotation.Provides;<br>import io.activej.inject.module.ModuleBuilder;<br>import io.activej.launcher.Launcher;<br>import io.activej.launchers.http.HttpServerLauncher;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>import java.io.IOException;<br><br>public class Application extends HttpServerLauncher {<br><br>    private static final Logger logger = LoggerFactory.getLogger(ActiveJHTTPTemplateApplication.class);<br>    <br>    // activej uses its own dependency injection library<br>    private static final Injector injector = Injector.of(ModuleBuilder.create()<br>            // ObjectMapper<br>            .bind(ObjectMapper.class).to(ObjectMapper::new)<br>            .build());<br><br>    @Provides<br>    AsyncServlet servlet() {<br><br>        ObjectMapper om = injector.getInstance(ObjectMapper.class);<br><br>        return RoutingServlet.create()<br>                .map(HttpMethod.GET, &quot;/&quot;, request -&gt;<br>                        HttpResponse.ok200().withPlainText(&quot;Hello world&quot;)<br>                ).map(<br>                        HttpMethod.POST, &quot;/record&quot;, req -&gt; req.loadBody()<br>                                .map(promise -&gt; {<br>                                    ByteBuf body = req.getBody();<br>                                    try {<br>                                        byte[] bodyBytes = body.getArray();<br>                                        <br>                                        // Trying to deserialize request body into PersonRecord record instance.<br>                                        PersonRecord personRecord = om.readValue(bodyBytes, PersonRecord.class);<br>                                        <br>                                        return HttpResponse.ok200().withPlainText(String.format(&quot;Person with name %s and age %s is created.&quot;, personRecord.name(), personRecord.age()));<br>                                    } catch (IOException e) {<br>                                        return HttpResponse.ofCode(500).withPlainText(&quot;Invalid Person!!!&quot;);<br>                                    }<br>                                })<br>                ).map(<br>                        HttpMethod.POST, &quot;/class&quot;, req -&gt; req.loadBody()<br>                                .map(promise -&gt; {<br>                                    ByteBuf body = req.getBody();<br>                                    try {<br>                                        byte[] bodyBytes = body.getArray();<br>                                        <br>                                        // Trying to deserialize the request body into PersonClass class instance.<br>                                        PersonClass personClass = om.readValue(bodyBytes, PersonClass.class);<br>                                          <br>                                        return HttpResponse.ok200().withPlainText(String.format(&quot;Person with name %s and age %s is created.&quot;, personClass.name, personClass.age));<br>                                    } catch (Exception e) {<br>                                        return HttpResponse.ofCode(500).withPlainText(&quot;Invalid Person&quot;);<br>                                    }<br>                                }));<br>    }<br><br>    public static void main(String[] args) throws Exception {<br>        Launcher launcher = new ActiveJHTTPTemplateApplication();<br>        launcher.launch(args);<br>    }<br>}</pre><p>Imagine that these endpoints are a “sign up” endpoint for our app and there is an age restriction to use it. Let’s put this restriction into our <strong>Person</strong> <em>class</em> and <strong>Person</strong> <em>record</em> constructors.</p><pre>package com.itwasneo.activejhttptemplate;<br><br>public record PersonRecord(<br>        String name,<br>        int age) {<br>    public PersonRecord {<br>        if (age &gt; 20) {<br>            throw new ClassCastException();<br>        }<br>    }<br>}</pre><pre>package com.itwasneo.application;<br><br>import java.io.Serializable;<br><br>public class PersonClass implements Serializable {<br><br> public String name;<br><br> public int age;<br><br> public PersonClass (<br>   String name,<br>   int age) {<br>  this.name = name;<br>  if (age &gt; 20) {<br>   throw new ClassCastException();<br>  }<br>  this.age = age;<br> }<br><br> public PersonClass() {}<br>}</pre><p>If we try each endpoint with a <strong>Person</strong> JSON object with a restricted age, we will see <strong>/class </strong>endpoint <strong>can</strong> <em>deserialize</em> it without any errors. On the other hand, <strong>/record</strong> endpoint <strong>can not</strong> <em>deserialize</em>, because Java uses the <em>Canonical</em> constructors to <em>deserialize</em> objects into records.</p><pre>$ curl -X POST http://localhost:8080/class -d &#39;{ &quot;name&quot;: &quot;morpheus&quot;, &quot;age&quot;: 50}&#39;<br>Person with name morpheus and age 50 is created.%</pre><pre>$ curl -X POST http://localhost:8080/record -d &#39;{ &quot;name&quot;: &quot;morpheus&quot;, &quot;age&quot;: 50}&#39;<br>Invalid Person!!!%</pre><p>In this case, this record feature makes the <strong>validation</strong> (or any other logic) become an <strong>implicit feature</strong> of the object deserialization at the actual deserialization level: can be very powerful 🔥🔥🔥 IMO</p><h4>Conclusion</h4><p>Java <em>Records</em> have been with us since Java 14, use them. They will keep evolving and become the building blocks for some upcoming JDK features such as “<a href="https://blogs.oracle.com/javamagazine/post/java-pattern-matching-switch-when-null"><em>pattern matching</em></a>”, exciting stuff 🎉🎉🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4badb819be3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yet Another Yew App: Rust, wasm, Server Sent Events and more]]></title>
            <link>https://medium.com/@itwasneo/yet-another-yew-app-rust-wasm-server-sent-events-and-more-5cd801d687b?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd801d687b</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[yew]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[wasm]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 20:05:05 GMT</pubDate>
            <atom:updated>2022-09-20T20:07:42.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d_9H8pgvl0tvw0e0" /><figcaption>Photo by <a href="https://unsplash.com/@yanutkaa1?utm_source=medium&amp;utm_medium=referral">Yana Gorbunova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>TL;DR</h4><p>I will use <em>Rust</em>’s beloved component based web framework <em>Yew</em> to visualize <em>Server-Sent-Events</em>. The topics that will be referred in this story:</p><ul><li>Yew #[<em>function_component</em>]<br><em>- use_state()<br>- use_mut_ref()<br>- use_reducer_eq()<br>- use_effect()</em></li><li>Yew <em>Agents</em><br>- <em>Event Bus</em> implementation for <em>inter-component</em> communication</li><li><em>wasm-bindgen</em> and <em>web-sys</em><br>- <em>Closures</em><br>- <em>EventSource (Server-Sent Events)</em></li></ul><p><a href="https://github.com/itwasneo/yet-another-yew-app"><strong><em>PROJECT REPOSITORY</em></strong></a></p><h4>Introduction</h4><p>For some reason, I couldn’t ever feel excited or motivated enough about “<strong>Front-End</strong>” side of web development to build some fully-fledged web, cross-platform applications or to even improve my abilities and skill set about the topic. Maybe it is because of<em> JavaScript</em> ecosystem or maybe <em>JavaScript</em> itself. I don’t really know. There is something about it;<em> sneaky</em> and <em>dirty</em> that makes me not want to touch it.</p><p>So how can I write a web application without writing a single line of <em>Js</em>? I know, I know yeess… <em>WebAssembly</em>. Since I’m not some kind of a computer guru or a tech influencer , I won’t even bother to explain what it is, how it is more advantageous or disadvantageous against <em>Js</em> etc. One thing that is interesting about <em>WebAssembly</em> and that I “can” explain or “<strong>quote</strong>” is the first sentence you read on <a href="https://en.wikipedia.org/wiki/WebAssembly">WebAssembly wiki page</a> 😎</p><blockquote><strong>WebAssembly</strong> (sometimes abbreviated <strong>Wasm</strong>) defines a <a href="https://en.wikipedia.org/wiki/Software_portability">portable</a> <a href="https://en.wikipedia.org/wiki/Binary_code">binary-code</a> format and a corresponding text format for <a href="https://en.wikipedia.org/wiki/Executable">executable programs</a> as well as <a href="https://en.wikipedia.org/wiki/Software">software</a> interfaces for facilitating interactions between such programs and their host environment.</blockquote><p>You may noticed that there is no “Web” word in the definition (except the name itself) 🤔. That is because WebAssembly is NOT specific to Web. In theory, you should be able to execute your code on any <em>structured stack machine</em> with <em>minimum effort</em> as long as it is compiled to a <em>wasm target</em>.</p><p>I’ve been really into <em>Rust</em> lately and there is something about it;<em> sneaky</em> and <em>dirty</em> that makes me want not just to touch but <em>absorb</em> it through my skin. And guess what? You CAN target your Rust code to be compiled to <em>wasm </em>😈</p><h4>Project Recipe</h4><p>This time, the recipe will be very simple.</p><ul><li><strong><em>yet-another-yew-app</em></strong>: Yew is a Rust Web frameworacmndasdhqw… Who am I to explain their product? <a href="https://yew.rs/">Official Site</a>. This instance will consume 2 different Server-Sent Event sources and visualize the relation in a component-based web app.</li><li><a href="https://medium.com/@itwasneo/scale-your-database-with-kafka-connect-part-1-f07fc6a1cffe"><strong><em>kafka-connect-project</em></strong></a><strong><em>:</em></strong> This is a project that I created for my previous Medium story. For this project, I will need 2 different Server-Sent Event sources. I will use the 2 “micro-services” inside <strong>kafka-connect-project</strong> as my Event sources. (To make these “micro-services” support Server-Sent-Events, I had to make little modifications which are out of context for this story. You can find the <strong>kafka-connect-project</strong> in the <a href="https://github.com/itwasneo/kafka-connect-project">github repository</a>. The official documentation about <em>javalin app</em>s’ SSE support is <a href="https://javalin.io/news/2019/01/17/javalin-2.6.0-released.html">here</a>.)</li></ul><p>Shall we?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FvEcyRJ5yysqk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FvEcyRJ5yysqk%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FvEcyRJ5yysqk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="178" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5c6703c631af9871251d504b5dc9cde/href">https://medium.com/media/c5c6703c631af9871251d504b5dc9cde/href</a></iframe><h4>Very Basic Yew Project Structure</h4><p>We should start with the development environment. You can follow the steps in this <a href="https://yew.rs/docs/getting-started/introduction">Yew documentation page</a> to install necessary tooling. After that, I suggest you to implement the steps inside <a href="https://yew.rs/docs/getting-started/build-a-sample-app">Build a sample app</a> page so that you have an up-and-ready project structure with a <em>main.rs</em> file inside <em>src</em> folder like the following:</p><figure><img alt="Basic Project Structure" src="https://cdn-images-1.medium.com/max/124/1*HiQHgiLAC1W8t1AK6LtvnQ.png" /></figure><p>I called my project “<strong>yet-another-yew-app</strong>” and I will use <a href="https://trunkrs.dev/"><em>trunk</em></a> for my builds and packaging. Let’s start with our <em>Cargo.toml</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e4fcb0508c06f25aeca571337304c66/href">https://medium.com/media/9e4fcb0508c06f25aeca571337304c66/href</a></iframe><p><strong>[package] </strong>tag consists basic information about your project.</p><p><strong>[profile.release] </strong><a href="https://doc.rust-lang.org/cargo/reference/profiles.html"><em>profile</em></a><em> </em>tag provides a way to alter the compiler settings, influencing things like optimizations and debugging symbols. In this case, we are setting <em>lto</em> (link time optimization) to be true for our release compilations. You can find more details about other possible optimizations for your Yew apps <a href="https://yew.rs/docs/advanced-topics/optimizations">here</a>. 👌</p><p><strong>[dependencies]</strong> well, here you specify the <em>crates</em> (<strong><em>rustacean</em></strong> way to say <em>libraries</em>) that your project will need. I will explain each of them as we use them inside the project files.</p><p>I will need 2 components(<strong>event_source_component.rs</strong>, <strong>latency_component.rs</strong>) and 2 services(<strong>event_source.rs</strong>, <strong>event_bus.rs</strong>) for this project. I will keep them in separated modules called <strong>components</strong> and <strong>services</strong> surprisingly. Let’s create the directories and files alongside with their <em>mod.rs</em> files. The final project structure will be like this:</p><figure><img alt="Complete Project Structure" src="https://cdn-images-1.medium.com/max/247/1*65gCuoYbhgW4L30FxAY03Q.png" /></figure><p>In order to use <strong>components</strong> and <strong>services</strong> modules inside our <em>main.rs</em> file, we should create corresponding <strong><em>mod.rs</em></strong> files inside their module directory and make the individual elements accessible with the following lines. (For more information about multi-module setups checkout <a href="https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html">here</a>.)</p><p><strong>mod.rs</strong> file inside <strong>components</strong> directory:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252836%252C32%252C38%252C1%2529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpub%252520mod%252520event_source_component%25253B%25250Apub%252520mod%252520latency_component%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252836%25252C32%25252C38%25252C1%252529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpub%25252520mod%25252520event_source_component%2525253B%2525250Apub%25252520mod%25252520latency_component%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf172480bc3aa18c8d58112196768e9a/href">https://medium.com/media/bf172480bc3aa18c8d58112196768e9a/href</a></iframe><p><strong>mod.rs </strong>file inside <strong>services</strong> directory:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252836%252C32%252C38%252C1%2529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpub%252520mod%252520event_source%25253B%25250Apub%252520mod%252520event_bus%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252836%25252C32%25252C38%25252C1%252529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpub%25252520mod%25252520event_source%2525253B%2525250Apub%25252520mod%25252520event_bus%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3968c3d5f2e192f5a1f0675d20262e/href">https://medium.com/media/7d3968c3d5f2e192f5a1f0675d20262e/href</a></iframe><p>Finally inside the <strong>main.rs file</strong>, we are adding each module:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252836%252C32%252C38%252C1%2529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dmod%252520services%25253B%25250Amod%252520components%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252836%25252C32%25252C38%25252C1%252529%26t%3Dvscode%26wt%3Dnone%26l%3Drust%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D20px%26wc%3Dfalse%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dmod%25252520services%2525253B%2525250Amod%25252520components%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7cbdfdb3af9a4eb32fbf8c9b1e61f9a/href">https://medium.com/media/a7cbdfdb3af9a4eb32fbf8c9b1e61f9a/href</a></iframe><p>OK, now that we finished with our project’s skeleton, let’s start to work on individual elements. The first stop is … 👉 <strong>event_source.rs</strong></p><h4>Handling Server-Sent-Events with Closure and Callback</h4><p>Before get into the Rust code, let’s look at the <em>JavaScript</em> example inside the official <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource"><em>EventSource API</em> documentation provided by mozilla</a> so that we determine what we need as dependency:</p><pre>1) const evtSource = new EventSource(&#39;sse.php&#39;);<br>2) const eventList = document.querySelector(&#39;ul&#39;);<br>3) evtSource.onmessage = (e) =&gt; {<br>    const newElement = document.createElement(&quot;li&quot;);</pre><pre>    newElement.textContent = `message: ${e.data}`;<br>    eventList.appendChild(newElement);<br>  }</pre><p>In the first section, it creates an <em>EventSource</em> object. For this we need a binding to this <em>EventSource API</em> which is provided by our dependency <em>web-sys.</em></p><p>In the second section, it gets a <em>DOM element</em> which will be modified inside the <em>onmessage</em> callback of the <em>EventSource</em> object. We are not going to bring our components into our <strong>event_source</strong> service scope. Instead we want them provide us a <em>Callback</em> (a function pointer).😈 We will use yew’s <em>Callback</em> wrapper for this one.</p><p>In the third section, it defines <em>EventSource</em> object’s <em>onmessage</em> callback which is a <em>Closure</em> that take an event (e) and use it inside its function scope. To define a <em>Closure</em> we will need <em>wasm-bindgen</em>’s <em>Closure</em> handle.</p><p>Other than these we will need an additional dependency to <em>deserialize</em> our <em>Server Sent Event</em> into our defined event data struct. And this dependency will be… drum rolls… yes <em>serde</em>.</p><p>OK, we know our dependencies, let’s fill <strong>event_source.rs</strong> with some code, starting with the dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0000f6382c063640529390c5dcf6d6/href">https://medium.com/media/fa0000f6382c063640529390c5dcf6d6/href</a></iframe><ul><li><strong>Line 1–4</strong>: Indicating dependencies</li><li><strong>Line 6–20</strong>: Defining our <em>EventSource</em> data struct. <em>Default</em> <em>trait</em> (<em>rustacean</em> way to say interface) is implemented to be used in situations where you want to create a default instance of <strong>EventSourceData</strong> struct, a shortcut basically.</li><li><strong>Line 22–25</strong>: We define another struct called <strong>EventSourceService</strong>. This struct will have an <em>EventSource</em> object alongside with its <em>Closure</em>(_cb) which will represent its <em>onmessage</em> callback. (The reason why we actually <strong>need</strong> to store the <em>Closure</em> is a little be tricky, I will come to that.)</li><li><strong>Line 27–44</strong>: We define a new method called “<strong>new”</strong> for <strong>EventSourceService</strong> which takes a <strong>url</strong> String for its <em>EventSource</em> object and a <em>Callback</em> function (that takes <strong>EventSouceData</strong> as its <strong>input type</strong>).<br><strong>- Line 28</strong>: We create an <em>EventSource</em> object using the <strong>url</strong> parameter. (normally you should handle your errors instead of using unwrap)<br><strong>- Line 30–36:</strong> Lots of moving parts here 😮‍💨 Here we define a <em>Closure</em> which will be called each time our <em>EventSource</em> object has a new event. If you look at <a href="https://docs.rs/wasm-bindgen/0.2.83/wasm_bindgen/closure/struct.Closure.html#method.new">the official documentation about the <em>wasm-bindgen’s Closure</em></a> functions, they have some requirements. First of all they must implement <em>Fn</em> or <em>FnMut</em> traits (We define our <em>Closure</em> function to be <em>FnMut</em> here, because it should have a mutable access to its environment to be called. Second, they shouldn’t have any <em>stack references</em> that’s why we used the <em>move</em> keyword here. (Wrapping a <em>Rust closure</em> with <em>Box</em> means that it will be allocated in the <em>heap</em> which is another necessity.) Inside the <em>Closure</em> (<strong>Line 32</strong>), we capture the data field of the event, convert it to String, then we deserialize it using <em>serde</em> to a <strong>EventSourceData</strong> struct. <strong>Line 34</strong> is <strong>very critic</strong>. Here we are actually calling the Callback function (that we get as a function parameter for method<strong> “new”</strong>) using the <em>emit</em> method. We give the new <strong>EventSourceData </strong>(e) as input.</li><li><strong>Line 38</strong>: After defining our <em>Closure</em> to be called for our <em>EventSource</em> object’s <em>onmessage</em> callback, we actually set it using <em>set_onmessage</em> method. As I mentioned before, we have to <strong>store</strong> our <em>Closure</em> in our <strong>EventSourceService</strong> struct, that’s because the <em>set_onmessage</em> method takes the <em>Closure</em> we defined <strong>as reference</strong> and because of <a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html"><em>Rust’s ownership principle</em></a> this <em>Closure</em> will be <strong>dropped</strong> when the program goes out this method’s scope. By storing the Closure inside our struct we actually <strong>prevent it to be dropped</strong>. This way <em>Closure</em> will only get dropped when the <strong>EventSourceService</strong> that it belongs gets dropped.</li><li><strong>Line 40–43</strong>: We are returning an instance of <strong>EventSourceService</strong> with corresponding field values that we just created.</li></ul><p>Phew!! Our service is ready 🚀. Let’s continue with… 👉 <strong>event_source_component.rs</strong></p><h4>Using an external service inside a function component using use_state and use_ref hooks</h4><p>We won’t need any additional dependency for now except the <a href="https://docs.rs/yew/latest/yew/prelude/index.html"><em>yew::prelude</em></a><em> </em>which consists commonly used yew thingies and our newly created <strong>EventSourceService</strong>, so we can start coding without any hesitation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d557e40baee1db150b402f237ff5dc5/href">https://medium.com/media/5d557e40baee1db150b402f237ff5dc5/href</a></iframe><ul><li><strong>Line 1–2</strong>: We add our dependencies.</li><li><strong>Line 4–8</strong>: Here we define a struct called <strong>Props</strong> to represent our component’s <a href="https://yew.rs/docs/concepts/function-components/attribute"><em>properties</em></a>.</li><li><strong>Line 10–40</strong>: This is where we define our function component. <em>#[function_component(NameOfYourComponent)</em>] attribute indicates that the following function will represent a<em> function component</em>. As you can see the function takes <em>props</em> parameter referencing to <strong>Props</strong> struct and returns an <em>Html</em> instance. Every function component should return an <em>Html</em> instance. <a href="https://yew.rs/docs/concepts/function-components/introduction">More info about <em>function components</em></a>.<br><strong>- Line 13</strong>: We use our first hook here which is <em>use_state</em>. This hook is used to <em>manage the state</em> in a function component. If you are familiar with React, it works the same way. Our component will have a state value which is a type of <strong>EventSourceData</strong> and its initial value is <strong>EventSourceData</strong> struct’s default values that we defined inside <strong>event_source.rs</strong>. Any change in the state value will <em>trigger a re-render</em>.<br><strong>- Line 15–20</strong>: Hmmm…🤔 Things are getting interesting. Do you remember the method “<strong>new”</strong> of <strong>EventSourceService</strong>? That method was taking 2 parameters: a <strong>url</strong> String and a <em>Callback</em> which takes an input of <strong>EventSourceData</strong> type. Yesss, that is right. Here we define <strong>that</strong> <em>Callback</em> which takes an <strong>EventSourceData</strong> as its input and <em>sets our component state with new data upon receiving a new call</em>.<br><strong>- Line 22</strong>: Our second hook will be used here which is <em>use_ref</em>. <a href="https://yew.rs/docs/concepts/function-components/pre-defined-hooks#use_ref">From the official documentation</a>: “<em>use_ref</em> is used for obtaining an <strong>immutable reference</strong> to a value. Its state <strong>persists</strong> across renders.” We will create an <strong>EventSourceService</strong> within <em>use_ref</em> hook so that we won’t lose it upon re-renders. (You may noticed that we put the component’s <strong>url</strong> <em>property</em> and the previously initialized <em>Callback</em> as input for <strong>EventSourceService::new</strong> method)<br>- <strong>Line 24–39: </strong>You can think of this final section as our component’s <em>view</em> or representation in DOM. Using the <em>html!</em> macro you can create <em>Html</em> instances. You can use both <em>HTML</em> and <em>Rust</em> code inside <em>html!</em> macro which is very convenient. Every time an <em>Event</em> captured by <strong>EventSourceService</strong>, our component’s state will be changed and that will trigger a re-render and new state will be represented inside the corresponding HTML elements.</li></ul><p>We are going great. Our first component is also done 🚀. Let’s modify our main.rs file, add some styling and run our application for the first time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff6VfCFyOL5KmiICskp%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ff6VfCFyOL5KmiICskp%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ff6VfCFyOL5KmiICskp%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/561e8e93ba8c3e90a3e93cc90a39e770/href">https://medium.com/media/561e8e93ba8c3e90a3e93cc90a39e770/href</a></iframe><h4>Running the Yew App for the first time</h4><p>Inside our <strong>main.rs</strong> file we will need another component to represent the main component of our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8633c42d95a4b43f2f4a27635dc85639/href">https://medium.com/media/8633c42d95a4b43f2f4a27635dc85639/href</a></iframe><ul><li><strong>Line 7–23:</strong> We define our main component called <strong>App</strong>. In Line 14 and Line 15, we inserted our <strong>EventSourceComponents</strong>. You may noticed that we set our component <em>properties </em>(<strong>url</strong>, <strong>title</strong>) here.</li><li><strong>Line 25–27:</strong> This is the main entry point of our Yew application.<br><strong>- Line 26:</strong> <em>wasm-logger</em> enables us to print our debug and error messages into browser console. Very useful piece of tooling.<br><strong>- Line 27:</strong> We start our application with <em>start_app</em> method which creates an instance of component type (App in our case) and puts it into <em>body</em> tag of our <strong>index.html</strong> file.</li></ul><p>We are done with the <strong>main.rs</strong> file for now.</p><p>For styling, I’ve created an <a href="https://github.com/itwasneo/yet-another-yew-app/blob/master/index.css"><strong>index.css</strong></a> file (with my remarkable css skills) in the root directory. In order to use it, we need some tweaks inside our index.html file, so that <em>trunk</em> can find and process the css file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ac14bc121f3c05b59ece1bdc9494f26/href">https://medium.com/media/3ac14bc121f3c05b59ece1bdc9494f26/href</a></iframe><p><strong>Line 7:</strong> This is where we include our index.css file to <em>trunk</em>’s build and packaging process. (You can add variety of <em>assets</em>, <a href="https://trunkrs.dev/assets/">just check</a>).</p><p>Only thing that is missing that prevent our application to work correctly is a service to send us Server Sent Events. Like I told you at the beginning, I will use the services inside the <strong>kafka-connect-project</strong> that I made previously, but at this point, not to create additional complexity for the story I will just use dummy services. You can see the <a href="https://github.com/itwasneo/yet-another-yew-app/tree/master/dummy-sse-services">dummy-sse-service</a> inside the project repository. I also created a <a href="https://github.com/itwasneo/yet-another-yew-app/blob/master/docker-compose-dummy-sse-services.yml"><em>docker-compose</em> file</a> that will create 2 instances of this dummy service to be run at port 7070 and 7071.</p><p>Just run the services with the following <em>docker-compose</em> command:</p><pre>docker-compose --file docker-compose-dummy-sse-services.yml up -d --build</pre><p>Now that we have our SSE services, we can run our app with trunk serve . If you see something like below hosted on localhost:8080, you are good to go. (<strong>Notice the epoch value changes!!</strong>🚀)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7M6UrxK984vT7Cd7_qnTg.gif" /></figure><h4>Creating an Event Bus using Yew Agents</h4><p>We’re going great so far 🎉 🎉 🎉. In order to finish the project we will need 1 more service and 1 more component. Let’s start with the service which will be the <strong>event_bus.rs</strong></p><p>What we want to achieve with this service is to provide our components a communication bus, so that they can share information with each other. We want our <strong>EventSourceComponent</strong>s to send messages to other component that we will create (which will be <strong>LatencyComponent</strong> COMING UP SOON!). This we can achieve with <a href="https://yew.rs/docs/concepts/agents">Yew Agents</a>. Coding starts…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F0lGOCxq1V8N7E1icuQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F0lGOCxq1V8N7E1icuQ%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F0lGOCxq1V8N7E1icuQ%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e08f981039cf337d63668372ac12aa/href">https://medium.com/media/45e08f981039cf337d63668372ac12aa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61cb269e20876abfc39d149aa421a94e/href">https://medium.com/media/61cb269e20876abfc39d149aa421a94e/href</a></iframe><ul><li><strong>Line 1–2:</strong> Adding dependencies</li><li><strong>Line 4–8:</strong> Here we define an <em>Enum</em> that will represent our <em>Agent</em>’s <em>Input</em> and <em>Output</em> types.</li><li><strong>Line 10–14:</strong> Another <em>Enum</em> that we will use later with <strong>EventSourceComponent</strong>. I will explain this there.</li><li><strong>Line 16–19</strong>: We define our <strong>EventBus</strong> struct. It has a field of <a href="https://docs.rs/yew/0.6.0/yew/agent/struct.AgentLink.html"><em>AgentLink</em></a> called <strong>link</strong> (a link to <em>Agent</em>’s <strong>scope</strong> to create callbacks.) and a <em>HashSet</em> called <strong>subscribers</strong> (represents the components that are <strong>subscribed</strong> to this Event Bus)</li><li><strong>Line 20–49</strong>: We implement the <em>Agent</em> trait for our <strong>EventBus</strong> struct.<br><strong>- Line 21–24</strong>: <em>Agent</em> trait has 4 types. <a href="https://yew.rs/docs/concepts/agents#reaches"><em>Reach</em></a> type being “Context” means that there will exist <strong>at most</strong> <strong>one</strong> instance of this <em>Agent</em> at any given time (it suits to our case.) We won’t use the <a href="https://docs.rs/yew/0.6.0/yew/agent/trait.Agent.html#associatedtype.Message"><em>Message</em></a> type with this Agent so we give it a unit type. Lastly, for <em>Input</em> and <em>Output</em> type we use <strong>BusMessage</strong> enum.<br><strong>- Line 26–31</strong>: Implementation of <em>create</em> method of <em>Agent</em> trait for our struct.<br><strong>- Line 33:</strong> We won’t need an <em>update</em> method for our <em>Agent</em>, that’s why it is empty.<br><strong>- Line 35: </strong>Here we basically define how our <em>Agent</em> will handle the incoming messages. It will iterate over its <strong>subscribers</strong> and send the message to each of them using its <em>AgentLink</em>.<br><strong>- Line 41–49:</strong> These methods define how our <em>Agent</em> will react to any <em>connection</em> (<strong>subscribe</strong>) and <em>disconnection</em> (<strong>unsubscribe</strong>) event. (At Line 42 we check whether the <a href="https://docs.rs/yew/0.6.0/yew/agent/struct.HandlerId.html"><em>HanderId</em></a> that belongs to a component is actually valid or “<strong>respondable</strong>”)</li></ul><p>OK, We’re almost there. Let’s implement our last component in <strong>latency_component.rs</strong> and wrap up our project.</p><h4>Listening an EventBus inside a function component using use_mut_ref, use_reducer_eq and use_effect</h4><p>This one will be a little bit tricky. What we want to do is to listen incoming messages from 2 <strong>EventSourceComponent</strong> via our <strong>EventBus</strong>, calculate the difference between the epoch values and render the result. Upon each calculations we will also re-arrange the distance (gap) between the components relative to the magnitude of the result. Let’s look at the code 😎</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9298c8dafc94c28ed79a97865f87acb/href">https://medium.com/media/d9298c8dafc94c28ed79a97865f87acb/href</a></iframe><p>This time, I will not go over the code sequentially.</p><ul><li><strong>Line 1–4</strong>: We added our dependencies. <em>gloo-utils</em> crate consists of common libraries of <em>web-sys</em>. We will use it to access the <em>document.</em></li><li><strong>Line 35–37</strong>: We created 2 variables <strong>main</strong> and <strong>replica</strong> with <a href="https://yew.rs/docs/concepts/function-components/pre-defined-hooks#use_mut_ref"><em>use_mut_ref</em></a> hook which provides <em>mutable references</em> to these variables during the lifetime of this component. Beware that these are not representing our components “<em>state</em>”. On the other hand, for latency variable we used <a href="https://yew.rs/docs/concepts/function-components/pre-defined-hooks#use_reducer_eq"><em>use_reducer_eq</em></a> hook, which you can use for more complex (relatively) state representations. In order to use <em>use_reducer_eq</em> hook, we need a <em>state</em> struct that implements <em>Reducible</em> trait.</li><li><strong>Line 11–31:</strong> Here we defined the necessary <em>state</em> struct for <em>use_reducer_eq</em> hook called <strong>LatencyState</strong> which has a single field named <strong>latency</strong>. We implement <em>Default</em> trait for convenience. We also need to implement the <em>Reducible</em> trait (Line 21–31). <em>Reducible</em> trait has a type called <em>Action</em> which will be used for its <em>reduce</em> method, which is also convenient. This way we can define <strong>different state changes</strong> based on <strong>different action types</strong> that the <em>reduce</em> function gets. For this we define an <em>Enum</em> at the top (Line 6–9). Depending on the action we receive, we either <strong>Wait</strong> and <strong>don’t change the state</strong> value or <strong>Update</strong> our state subtracting the new <strong>main</strong> value from the <strong>replica</strong>.</li><li><strong>Line 57–74</strong>: Here we create our connection to our <strong>EventBus</strong>. As you may remember, we used <em>use_ref</em> hook to persist our <strong>EventSourceService</strong> instance inside <strong>EventSourceComponent.</strong> Here, we will do the same and use <em>EventBus::bridge</em> method (it subscribe to <strong>Eventbus</strong>) to initialize our connection and persist it with <em>use_ref</em> hook. Inside the <em>bridge</em> Callback function we update our <strong>main</strong> and <strong>replica</strong> values and call our <em>reducer</em>’s (it was the<strong> latency</strong> variable) <em>dispatch</em> method (which calls the <em>reduce</em> method that we defined for <strong>LatencyState</strong> under the hood). This way every time we get a <strong>BusMessage::Main</strong>, we wait and don’t update the state. And when <strong>BusMessage::Replica</strong> arrives, we calculate the difference between the <strong>replica</strong> and <strong>main</strong> and we <strong>update the state</strong>.</li><li><strong>Line 39–55</strong>: Another cool feature, you may also know this from React like frameworks: <em>use_effect</em> hook. Here we use it to re-arrange the distance (gap css style value) between the elements inside div with an ID of “<strong>showcase</strong>”. (<strong>At line 45</strong>, you may noticed that I divide the latency value with 1000, that’s because the <strong>dummy-sse-services </strong>that I created have 2000ms <strong>delay</strong> between their sent events. I will be changing this modification, when I use the actual <strong>kafka-connect-project</strong>)</li><li><strong>Line 76–85</strong>: We defined our <em>view</em>, nothing special going on here…</li></ul><p>Wow, we are almost done. Let’s add our new component to the equation in <strong>main.rs</strong> and give it a go…🤔 I guess…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1WHAlOdc9ZNUZq85JI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1WHAlOdc9ZNUZq85JI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1WHAlOdc9ZNUZq85JI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4bee59057ff9db97f39390e668a98b0/href">https://medium.com/media/a4bee59057ff9db97f39390e668a98b0/href</a></iframe><p>Well, you got me. We sure implement the <strong>receiving</strong> the <strong>EventBus</strong> <strong>message</strong> in <strong>LatencyComponent</strong>, but we didn’t actually <strong>send</strong> any <strong>EventBus</strong> <strong>message</strong> from our <strong>EventSourceComponents</strong> 👎. Let’s add that real quick.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46c3e3246e7f5c4cd24f717ff6a203a2/href">https://medium.com/media/46c3e3246e7f5c4cd24f717ff6a203a2/href</a></iframe><ul><li><strong>Line 8</strong>: First, we add a new property called topic of type <strong>BusMessageTopic </strong>(We defined this <em>Enum</em> in <strong>event_bus.rs</strong>). This way we can determine for which <strong>topic</strong> our <strong>EventSourceComponent</strong> will serve.</li><li><strong>Line 16–27:</strong> This time, we create a <em>mutable reference</em> to an <strong>EventBus</strong> <a href="https://docs.rs/yew-agent/0.1.0/yew_agent/trait.Dispatched.html"><em>dispatcher</em></a> (Because in order to use “<em>send</em>” method you need a <em>mutable reference</em>.) Using the <em>dispatcher</em> we send the appropriate <strong>BusMessage</strong> inside an <em>use_effect</em> hook.</li></ul><p>Phew, I think that’s it. Let’s modify our <strong>App</strong> component inside main.rs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551e55183b143c623019a1f9d0503fae/href">https://medium.com/media/551e55183b143c623019a1f9d0503fae/href</a></iframe><ul><li><strong>Line 7:</strong> Notice the “<strong>id</strong>”</li><li><strong>Line 8 and Line 12:</strong> Notice the new “<strong>topic</strong>” property</li><li><strong>Line 10:</strong> We added our <strong>LatencyComponent</strong> Yay!!</li></ul><p>trunk serve 🚀🚀🚀</p><p>If everything goes fine, you see something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfFq77CMgJf0Hyfz3C-tsw.gif" /></figure><h4>Vamos Connect</h4><p>Our App seems to be working like the way we want with the dummy SSE services. For the last part of this story, let me use the actual “micro-services” that I created in the previous story and see how many milliseconds it takes to replicate a Database operation into an in-memory Database using Kafka Connect API in a local setup. (The services inside the <strong>kafka-connect-project</strong> are also serving from <strong>7070/sse</strong> and <strong>7071/sse</strong>, so you can also try it without any additional modification). Final version looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iv2Mwsi3Jz9sQJczSC4u-g.gif" /></figure><p>Well, well not bad Connect 👏👏👏.</p><h4>Conclusion</h4><p>What can I say? I really like Rust and this is just the tip of the iceberg. Yew framework, alongside other Rust/wasm frameworks, provides great tools to create Web Applications and I will definitely keep an eye them. If you notice any misuse or anti-pattern in my code, please don’t hesitate to reply. I’m just a newbie Rust learner. Be kind to yourself and see you in the next story 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd801d687b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scale Your DB with Kafka Connect? Part 2]]></title>
            <link>https://medium.com/@itwasneo/scale-your-db-with-kafka-connect-part-2-716edf8f2770?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/716edf8f2770</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 15:51:10 GMT</pubDate>
            <atom:updated>2022-09-18T02:16:19.678Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Scale Your Database with Kafka Connect? Part 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ig8DoO4LPvN88uz1" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=medium&amp;utm_medium=referral">David Clode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>TL;DR</h4><p>Using Kafka Connect topics to replicate the original database into an application-owned in-memory database.</p><p>Topics that will be covered:</p><ul><li><a href="#6d19">Connecting to <em>binance</em> web socket to populate the main database</a>.</li><li><a href="#75ce">Creating a <em>javalin</em> application that will listen Kafka Connect topic</a>.</li><li>Replicating the database into an H2 database using Kafka Connect topic records.</li><li><a href="#f949">Dockerizing <em>javalin</em> applications</a></li></ul><p><a href="https://github.com/itwasneo/kafka-connect-project"><strong><em>PROJECT REPOSITORY</em></strong></a></p><h4>Introduction</h4><p>In the first part of this series, we created a working kafka-connect environment running on bunch of docker containers. Although we have shown that our database operations mirror themselves on specific kafka topics with an <em>immutable</em> series of events, we didn’t actually see the database “<em>replication</em>”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXb1WCpq5wi4yjWfWYQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXb1WCpq5wi4yjWfWYQ%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXb1WCpq5wi4yjWfWYQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4ae650b98830bc00305068f47afabf/href">https://medium.com/media/ac4ae650b98830bc00305068f47afabf/href</a></iframe><p>In this part, we are going to build 2 “<em>micro-services</em>” using <strong>javalin</strong> framework. Why <a href="https://javalin.io/"><strong>javalin</strong></a> you may ask? It’s simple, lightweight and batteries not included. When it comes to any “<em>framework</em>”, I liked to use the ones that makes batteries available, but make me choose which one I like to use. javalin is just like what I want.</p><p>First service that we will build is actually going to populate our database. As you may remember, we’ve created a table called <strong>mini_ticker</strong> in the first part. Well, there was a reason for that. To keep things interesting, with the service that we will build, we are going to connect to <strong>binance </strong>(a cryptocurrency exchange) web socket and listen for <strong>mini_ticker</strong> stream for individual cryptocurrency pairs and save each web socket message to our <strong>mini_ticker</strong> table.</p><p>As we’ve seen at the end of the first part, each operation will create an event (or record) in our <strong>pg_dev.public.mini_ticker</strong> topic. Listening these events, the second service that we build, is going to populate its own in-memory database (we will use H2). This way we will “replicate” our original database, inside a separate micro-service.</p><h4><strong>Creating a javalin application that listens a web socket</strong></h4><p>1.First we create a new Java application called crypto-aggr which uses Maven as build system.</p><p>2.Then we add our dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e1a8229c3e6b977bc3585d491cb646b/href">https://medium.com/media/0e1a8229c3e6b977bc3585d491cb646b/href</a></iframe><p>3. We create 3 utility classes: <em>ConnectionPool</em>, <em>Client</em> and <em>Socket</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06e31c0916fc89cdad9cf750e48169bb/href">https://medium.com/media/06e31c0916fc89cdad9cf750e48169bb/href</a></iframe><p>ConnectionPool.java class will handle our database connections. We will configure the <strong><em>HikariDataSource</em></strong> with our <strong><em>datasource.properties</em></strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8be4e2dfd7138d67f1d9c10972047043/href">https://medium.com/media/8be4e2dfd7138d67f1d9c10972047043/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ca64829704583278882601782107f3/href">https://medium.com/media/a8ca64829704583278882601782107f3/href</a></iframe><p>In the Socket.java class, we implement a classic Web Socket. Every time we get a web socket message, we call <strong><em>onText</em></strong> method and inside this method we get a new connection from the connection pool and insert a new row. We use an inner class called <strong><em>Payload</em></strong> to read the object from string web socket message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa7c544cefe5df2fd483e9c22373ee7e/href">https://medium.com/media/aa7c544cefe5df2fd483e9c22373ee7e/href</a></iframe><p>In Client.java class, we establish the binance web socket connection and subscribe to BTCUSDT mini ticker stream in a static code block. In order to handle the message serialization, we again used an inner class called <strong><em>ClientMessage</em></strong>.</p><p>4. And finally, we implement our main method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebcf969d27652d204940304861ad7f25/href">https://medium.com/media/ebcf969d27652d204940304861ad7f25/href</a></iframe><p>With javalin you can start a simple web server using a single line of code.</p><pre>&gt; Javalin app <strong>=</strong> Javalin.create().start(7070);</pre><p><strong><em>app.events</em></strong> allows us to execute certain processes at specific lifecycle hooks. Here we initialize our<em> ConnectionPool</em> and web socket <em>Client</em> while the server is starting. At this point we are not communicating with the server, but we will. If you run the program, you should see an output like the following:</p><pre>[main] INFO org.eclipse.jetty.util.log - Logging initialized @238ms to org.eclipse.jetty.util.log.Slf4jLog</pre><pre>[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...</pre><pre>[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@28f2a10f</pre><pre>[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.</pre><pre>[WebSocketClient@417557780-25] INFO com.itwasneo.cryptoaggr.utils.Socket - Connected to the websocket.</pre><pre>[main] INFO io.javalin.Javalin - Starting Javalin ...</pre><pre>[main] INFO io.javalin.Javalin - You are running Javalin 4.6.4 (released July 8, 2022).</pre><pre>[main] INFO io.javalin.Javalin - Listening on http://localhost:7070/</pre><pre>[main] INFO io.javalin.Javalin - Javalin started in 2486ms \o/</pre><pre>[WebSocketClient@417557780-23] ERROR com.itwasneo.cryptoaggr.utils.Socket - Error parsing ws message, exception: Unrecognized field &quot;result&quot; (class com.itwasneo.cryptoaggr.utils.Socket$Payload), not marked as ignorable (2 known properties: &quot;stream&quot;, &quot;data&quot;])</pre><pre>at [Source: (String)&quot;{&quot;result&quot;:null,&quot;id&quot;:1}&quot;; line: 1, column: 15] (through reference chain: com.itwasneo.cryptoaggr.utils.Socket$Payload[&quot;result&quot;])</pre><pre>[WebSocketClient@417557780-25] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-23] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-25] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-23] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-25] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-23] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><pre>[WebSocketClient@417557780-25] INFO com.itwasneo.cryptoaggr.utils.Socket - INSERTED</pre><p>(After we sent our subscription message to binance web socket, the first message we receive is {“result”:null,”id”:1}, which doesn’t match up with our Payload class fields, so we can simply ignore the single<strong><em> ERROR</em></strong> we are getting here.)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FmGK1g88HZRa2FlKGbz%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FmGK1g88HZRa2FlKGbz%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FmGK1g88HZRa2FlKGbz%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/06438c55305cd863b41ac6e19c262f31/href">https://medium.com/media/06438c55305cd863b41ac6e19c262f31/href</a></iframe><p>Fantastic!!! Since we populate our database automatically with binance data, let’s start with the second “<em>micro service</em>”.</p><h4><strong>Creating a javalin application that listens a kafka topic and uses an in-memory H2 database</strong></h4><p>1.First we create a new Java application called crypto-connect which uses Maven build system.</p><p>2. Then we add our dependencies</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff6e8e4925f6d0d8a3c5ae77eb47e0e/href">https://medium.com/media/fff6e8e4925f6d0d8a3c5ae77eb47e0e/href</a></iframe><p>In order to obtain <strong><em>kafka-avro-serializer</em></strong>, we need to add an external maven repository belonging <strong><em>confluent</em></strong>.</p><p>3. This time, we create 2 utility classes: <em>ConnectionPool</em> and <em>Kafka</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7894ab18b2ac1d610dbd38f1ed4b9580/href">https://medium.com/media/7894ab18b2ac1d610dbd38f1ed4b9580/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc4696e7cf7685b2db48caa688704bbf/href">https://medium.com/media/dc4696e7cf7685b2db48caa688704bbf/href</a></iframe><p>Unlike our first <em>ConnectionPool.java</em> class inside the <em>crypto-aggr</em> application, this time we will create our <strong>mini_ticker</strong> table inside our in-memory database each time we initialize our ConnectionPool. (Due to the fact that every time we stop the application we discard the <strong>in-memory</strong> database completely.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/721cd984db5b22e68dda676ba033dc4a/href">https://medium.com/media/721cd984db5b22e68dda676ba033dc4a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ea68ed027c28fac14f373edbc224b33/href">https://medium.com/media/9ea68ed027c28fac14f373edbc224b33/href</a></iframe><p>Inside <em>Kafka.java</em> class, we implement a basic Kafka consumer. In a static code block, we configure our Kafka consumer using <em>kafka.properties</em> file, subscribe to our <strong>pg_dev.public.mini_ticker</strong> topic and start polling. Each time we consume a <strong>record</strong> or <strong>message</strong> from the topic, we either merge a new row into our in-memory database, or delete a row from it depending on the <strong>__deleted</strong> flag of each record.</p><p>4. And finally, we write our main method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34837e20886fede91f16b5c9a0d03e3e/href">https://medium.com/media/34837e20886fede91f16b5c9a0d03e3e/href</a></iframe><p>In order to test whether this service working correctly or not, we need our utilities up and running. After running our <em>docker-compose-crypto-utils.yml</em><strong> </strong>file and connecting kafka-connect to our postgres database, we can run our second “micro-service”.</p><p>At the end of the application log, you should see something like the following:</p><pre>.</pre><pre>.</pre><pre>.</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><pre>[main] INFO com.itwasneo.cryptoconnect.utils.Kafka - INSERTED 1 ROW</pre><p>These rows are corresponding to the <em>insertion</em> operation that we did in the previous section with the first micro service.</p><p>As you can see, in our <strong>pg_dev.public.mini_ticker</strong> topic created by <em>kafka-connect</em> we have an <em>immutable source of truth</em> that we can use to replicate our entire table <strong>from scratch</strong>.</p><p>If you run both services at the same time, you will see that once a new row inserted into our postgres table by the <em>crypto-aggr</em> app, a new row is created by <em>crypto-connect</em> app inside its own database.</p><p>Let’s dockerize the two applications we just created, and add them to our docker-compose file.</p><h4>Dockerizing javalin applications</h4><p>Before anything else, I will leave the actual <em>javalin</em> <a href="https://javalin.io/tutorials/docker">documentation</a> about dockerizing its applications. I personally didn’t follow it line by line.</p><p>1.Add the following <em>maven</em> files into your <strong>pom.xml </strong>in order to be able to create an <a href="https://stackoverflow.com/questions/11947037/what-is-an-uber-jar"><em>uber-jar</em></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1da42b6a7a7dc8daecb4837b5688880d/href">https://medium.com/media/1da42b6a7a7dc8daecb4837b5688880d/href</a></iframe><p>2. Create a <a href="https://stackoverflow.com/questions/11947037/what-is-an-uber-jar"><strong>uber jar</strong></a><strong> </strong>file with mvn clean package command.</p><p>3. Create a Dockerfile inside the individual project directories. (I keep properties files inside <strong>config</strong> folder in the projects’ root directories. <strong>Important</strong>: Inside config/dev directory, there are docker versions of properties files. Here we use them not the properties files for the local setup to create our <em>docker image</em>s.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ce9ee78cb286ba1ffedf900b13e163/href">https://medium.com/media/83ce9ee78cb286ba1ffedf900b13e163/href</a></iframe><p>4. Add the applications into your docker-compose file. (You can see the final version of docker-compose file <a href="https://github.com/itwasneo/kafka-connect-project/blob/master/docker-compose.yml">here</a>.)</p><p>5. docker-compose up -d --build</p><p><strong>Important Note</strong>: After you run the docker containers, don’t forget to connect the Kafka Connect to postgres as I mentioned in the <a href="https://medium.com/@itwasneo/scale-your-database-with-kafka-connect-part-1-f07fc6a1cffe">part 1</a> of this series.</p><p>Now that the entire “cluster” is up running, you can see that crypto-aggr app is writing into postgres and crypto-connect app creates an in-memory database that belongs only to itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FI2TqO0oJBaNoc%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FI2TqO0oJBaNoc%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FI2TqO0oJBaNoc%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/e15454c85c1e1620b011689296ec375b/href">https://medium.com/media/e15454c85c1e1620b011689296ec375b/href</a></iframe><h4>Latency???</h4><p>Since all the instances are running on my local machine, it would be unrealistic and pointless to measure the latency between the availability of same “mini_ticker” values in main and in-memory databases. In my local setup it takes about 8–15ms on average to a newly inserted data to be replicated, but like I said it is not realistic.</p><h4>Conclusion</h4><p>Kafka Connect API is a great piece of tooling (along with other Kafka products such Kafka Streams, ksqldb etc.) that has a potential to be used in different ways. With the rise of “micro-services” architectural system designs, event driven systems became a reliable methodology and Kafka ecosystem is perfectly suited to this approach. Before I finished this story, I want to suggest <a href="https://www.goodreads.com/book/show/39793332-designing-event-driven-systems"><em>an excellent book about Event Driven Systems by Ben Stopford</em></a>. It was an overall engrossing book with different approaches to modern system designs. I hope you enjoy reading it as well as I did. See you in the next story 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716edf8f2770" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scale Your Database with Kafka Connect? Part 1]]></title>
            <link>https://medium.com/@itwasneo/scale-your-database-with-kafka-connect-part-1-f07fc6a1cffe?source=rss-471a81bad400------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07fc6a1cffe</guid>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[itwasneo]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 15:04:39 GMT</pubDate>
            <atom:updated>2022-09-14T15:55:39.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wCz_Nvs_qo0DItzn" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=medium&amp;utm_medium=referral">David Clode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If I had a dollar for every time I complain about the legacy database the company has been using being the bottleneck of the whole system… The aim of this project is to show a practical way to scale the persistence layer of a system with kafka-connect. As “<strong>micro-services architectures</strong>” rise with their impeccable glory, the amount of time spent on the cable has shared the same glory with its creator. Consecutively, applications’ being close to the <em>data</em> has become more and more significant. In-memory for the rescue right?</p><p>The things that I implement for this project may not be suitable for certain cases, and by “<em>certain</em>” I mean “<em>most</em>” of the enterprise solutions, but they were fun to implement anyway.</p><p>Although the Connect API was introduced at Kafka 0.9 release back in 2015, I think it is a really cool piece of technology that can be utilized in different forms. Before going into more detail about my project let me talk a little bit about kafka-connect and leave some links to their official documentations, because surely their explanation will be better than mine.</p><h4>What is kafka-connect?</h4><p>In essence, kafka-connect is a “<strong>connector</strong>” tool between Apache Kafka and other data systems. It can ingest databases to Kafka topics as a “<strong>source</strong>” connector or as a “<strong>sink</strong>” connector it can feed other data systems such as Elasticsearch. You can think of it as an ETL tool with low latency, high scalability and simple extensibility, so basically you <em>can’t</em> think of it as an ETL tool.</p><p>Here is the <a href="https://docs.confluent.io/platform/current/connect/index.html">official documents</a> by Confluent for more details. And of course an <a href="https://www.youtube.com/watch?v=J6adhl3wEj4">introductory video</a> for the visual learners.</p><h4>Project Recipe</h4><p>First let me give you the <a href="https://github.com/itwasneo/kafka-connect-project">github repository</a> for this project.</p><p>What I wanted to achieve with this project is basically to implement a pipeline between a relational database system and a REST application. It will be a step by step tutorial for each implementation, because although there are official documentations for every technical complexity in web, you deeply know that they won’t ever work at the first try. Here are the components:</p><ul><li><strong><em>postgres</em></strong><em>: Persistence layer.</em></li><li><strong><em>kafka</em></strong><em>: Connector will ingest data from postgres into Kafka topics.</em></li><li><strong><em>kafka-connect</em></strong><em>: PostgreSQL Source connector by Debezium. (</em><a href="https://docs.confluent.io/home/connect/self-managed/kafka_connectors.html"><em>List</em></a><em> of self-managed connectors for kafka-connect.)</em></li><li><strong><em>crypto-aggr</em></strong><em>: Aggregator java application (using javalin framework) that will populate </em>the database.</li><li><strong><em>crypto-connect</em></strong><em>: Another java application (using javalin framework) that will ingest a Kafka topic created by kafka-connect and create its own in-memory database.</em></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKzM1lAfJjCWNq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKzM1lAfJjCWNq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKzM1lAfJjCWNq%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="356" frameborder="0" scrolling="no"><a href="https://medium.com/media/46102b7cf2dd1bfa43f60d51ed9ccec4/href">https://medium.com/media/46102b7cf2dd1bfa43f60d51ed9ccec4/href</a></iframe><p>Other than these base components, there are several other instances that have to be run alongside the rest in order the whole cluster to be working properly. At the end, all the components will be run with a single docker-compose file, but first we will write a proper docker-compose file just for kafka-connect and postgres.</p><h4>Proper docker-compose File for kafka-connect and postgres That Works</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e35522c46a0d91c403fb475047160b9f/href">https://medium.com/media/e35522c46a0d91c403fb475047160b9f/href</a></iframe><p>It will get longer with the 2 additional applications, but for now I will explain each container in this docker-compose file.</p><ul><li><strong><em>db:</em></strong> As I mentioned before,<em> </em>I will use postgres as the main database<em>. </em>Default username for postgres image is <strong>postgres</strong>. In order not to lose the data at each execution I will assign a volume under <strong>volumes</strong> section. That will create a <strong>data</strong> folder in the current directory and persist data. Another important point to mention is the <strong>wal_level</strong> setting command. kafka-connect listens (write-ahead logging) to detect any data change in database tables and using those log entries creates topic messages for individual topics. For more detail about the <a href="https://postgresqlco.nf/doc/en/param/wal_level/">wal_level settings for postgres</a>.</li><li><strong><em>zookeeper</em></strong><em>: </em>This is a coordination service that will be used to manage kafka. (Synchronization and group services.)</li><li><strong><em>kafka</em></strong><em>: </em>This is the container that will run the kafka broker. Basic settings are applied through environment variables. <strong>KAFKA_AUTO_CREATE_TOPICS_ENABLE </strong>variable should be set to <strong>true</strong> for automatic topic creation by kafka-connect.</li><li><strong><em>schema-registry</em></strong><em>: </em>Schema API that will be utilized by kafka-connect as well as our kafka client inside crypto-connect javalin app. Basic functionality of this service is to be a serving layer for our data schemas. For more detail about <a href="https://docs.confluent.io/platform/current/schema-registry/index.html">schema registry</a>.</li><li><strong><em>kafka-connect</em></strong><em>:</em> And finally, our queen, khaleesi, mother of change-sets… In order to run this container properly, I had to try lots of different settings and modifications, but most of these environment variables can be found in the official documentations. As a Key Converter I used basic String converter, but to represent values I choose the AVRO format, because why not. Another important thing to mention is the plugin installations. As I mentioned earlier, you need proper connectors for different data systems (in this case postgres). With the <strong>command</strong> section, we install the proper plugin (debezium connector) when the container boot up (packages that are installed via confluent-hub command will go to the <strong>/usr/share/confluent-hub-components</strong> directory.). <strong>CONNECT_PLUGIN_PATH </strong>should be also indicated with the proper directories delimited by comma.</li><li><strong><em>ksqldb</em></strong><em>: </em>We will use ksqldb just as an observer to our kafka topics. Normally ksqldb is a much more powerful tool for stream processing applications. For more information about <a href="https://ksqldb.io/overview.html">ksqldb</a>.</li></ul><p>You can find this docker-compose file with the name “docker-compose-crypto-utils.yml” in the <a href="https://github.com/itwasneo/kafka-connect-project">repository</a> as well. Let’s run it.</p><pre>&gt; docker-compose --file docker-compose-crypto-utils.yml up -d</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F6wmz6Qo40eTDf4tW3Z%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F6wmz6Qo40eTDf4tW3Z%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F6wmz6Qo40eTDf4tW3Z%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a2a74afc4594dd54b509f64e4bb77af/href">https://medium.com/media/1a2a74afc4594dd54b509f64e4bb77af/href</a></iframe><h4>Creating a Database and a Table in postgres Using psql</h4><p>First let’s connect to our postgres database and create a table. You can attach to the postgres container and start a <strong>psql</strong> session using our default user <strong>postgres</strong> with the following docker command. (For further detail about <a href="https://www.postgresql.org/docs/current/app-psql.html">psql</a>)</p><pre>&gt; docker exec -it postgres psql -U postgres</pre><p>You can list the existing databases with the following command which for now only lists the default databases.</p><pre>&gt; \l</pre><p>In order to create a database to work with execute the following. This will create a database named <strong>pg_dev</strong> whose owner is our default <strong>postgres </strong>user.</p><pre>&gt;<strong> CREATE</strong> <strong>DATABASE</strong> pg_dev <strong>OWNER</strong> postgres;</pre><p>Now let’s connect to our newly created database and create a table called <strong>mini_ticker</strong> with the corresponding fields. (I will explain the mini_ticker model in the following sections. For now, I just wanted our messaging and persistence layers to be fully available, before getting into the development of our web apps)</p><pre>&gt; \c pg_dev</pre><pre>&gt;<strong> CREATE</strong> <strong>TABLE</strong> mini_ticker (id serial <strong>PRIMARY</strong> <strong>KEY</strong>, current_time_millis <strong>BIGINT</strong>, epoch_time <strong>BIGINT</strong>, pair <strong>VARCHAR</strong>(10), <strong>close</strong> <strong>VARCHAR</strong>(20), <strong>open</strong> <strong>VARCHAR</strong>(20), volume <strong>VARCHAR</strong>(20));</pre><p>After successfully running the create script, you should see your table when you execute the following command.</p><pre>&gt; \dt</pre><p>And finally let’s insert a dummy row.</p><pre>&gt;<strong> INSERT</strong> <strong>INTO</strong> mini_ticker(current_time_millis, epoch_time, pair, <strong>close</strong>, <strong>open</strong>, volume) <strong>VALUES</strong> (9999, 9999, &#39;BTCUSDT&#39;, &#39;10000&#39;, &#39;10001&#39;, &#39;10002&#39;);</pre><h4>Connecting kafka-connect to our database</h4><p>Now that we have a proper database and a table, we can connect our kafka-connect instance to our database and start to listen change events. But before doing that let’s first check current state in our kafka instance through ksqldb. We can attach to ksqldb container and run <strong>ksql</strong> CLI tool with the following docker command.</p><pre>&gt; docker exec -it ksqldb ksql http://localhost:8088</pre><p>Inside the CLI, in order to see the current topics in our kafka instance we can run the following:</p><pre>&gt; show topics;</pre><p>It should return something like this:</p><pre>Kafka Topic                    | Partitions | Partition Replicas</pre><pre>------------------------------------------------------------------</pre><pre>crypto-ksqlksql_processing_log | 1          | 1</pre><pre>docker-connect-configs         | 1          | 1</pre><pre>docker-connect-offsets         | 25         | 1</pre><pre>docker-connect-status          | 5          | 1</pre><pre>------------------------------------------------------------------</pre><p>These are the default topics that are created by kafka-connect and ksqldb instances.</p><p>Now let’s exit from ksql CLI tool with exit; command and connect our kafka-connect instance to our database.</p><h4>curl for kafka-connect with debezium postgres connector</h4><p>kafka-connect has an API that we can communicate through HTTP requests, so in order create a connection between kafka-connect and postgres database we can simply run the following curl command in our terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a851f6670f78e8875d8e05c51b9fe1a/href">https://medium.com/media/2a851f6670f78e8875d8e05c51b9fe1a/href</a></iframe><p>Inside the <strong>config</strong> tag, you can see the necessary configuration for the kafka-connect source connector. You can see the details of the configurations at the [<a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html">debezium’s official documentations</a>].</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkEoMQOrW4SbKcVaubX%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkEoMQOrW4SbKcVaubX%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkEoMQOrW4SbKcVaubX%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/db31f402dd93054ff22ec800d3a74e19/href">https://medium.com/media/db31f402dd93054ff22ec800d3a74e19/href</a></iframe><p>After executing POST curl, we can check if we successfully create a connector with the following curl command.</p><pre>&gt; curl -s &quot;http://localhost:8083/connectors?expand=info&amp;expand=status&quot;</pre><p>It should return something like the following:</p><pre>{&quot;pg-connector&quot;:{&quot;info&quot;:{&quot;name&quot;:&quot;pg-connector&quot;,&quot;config&quot;:{&quot;connector.class&quot;:&quot;io.debezium.connector.postgresql.PostgresConnector&quot;,&quot;database.user&quot;:&quot;postgres&quot;,&quot;database.dbname&quot;:&quot;pg_dev&quot;,&quot;transforms.unwrap.delete.handling.mode&quot;:&quot;rewrite&quot;,&quot;topic.creation.default.partitions&quot;:&quot;1&quot;,&quot;slot.name&quot;:&quot;dbname_debezium&quot;,&quot;publication.name&quot;:&quot;dbname_publication&quot;,&quot;transforms&quot;:&quot;unwrap&quot;,&quot;database.server.name&quot;:&quot;pg_dev&quot;,&quot;heartbeat.interval.ms&quot;:&quot;5000&quot;,&quot;plugin.name&quot;:&quot;pgoutput&quot;,&quot;database.port&quot;:&quot;5432&quot;,&quot;database.hostname&quot;:&quot;postgres&quot;,&quot;database.password&quot;:&quot;example&quot;,&quot;poll.interval.ms&quot;:&quot;1&quot;,&quot;transforms.unwrap.drop.tombstones&quot;:&quot;true&quot;,&quot;topic.creation.default.replication.factor&quot;:&quot;1&quot;,&quot;name&quot;:&quot;pg-connector&quot;,&quot;transforms.unwrap.add.fields&quot;:&quot;source.ts_ms&quot;,&quot;transforms.unwrap.type&quot;:&quot;io.debezium.transforms.ExtractNewRecordState&quot;,&quot;table.include.list&quot;:&quot;public.(.*)&quot;},&quot;tasks&quot;:[{&quot;connector&quot;:&quot;pg-connector&quot;,&quot;task&quot;:0}],&quot;type&quot;:&quot;source&quot;},&quot;status&quot;:{&quot;name&quot;:&quot;pg-connector&quot;,&quot;connector&quot;:{&quot;state&quot;:&quot;RUNNING&quot;,&quot;worker_id&quot;:&quot;kafka-connect:8083&quot;},&quot;tasks&quot;:[{&quot;id&quot;:0,&quot;state&quot;:&quot;RUNNING&quot;,&quot;worker_id&quot;:&quot;kafka-connect:8083&quot;}],&quot;type&quot;:&quot;source&quot;}}}%</pre><p>We can see that we have a connector called <strong>pg-connector</strong> and its state is <strong>RUNNING</strong>. GREAT!!!</p><p>Now let’s check the current state of our kafka instance. Connect to ksqldb container and run show topics; command again.</p><pre>Kafka Topic                    | Partitions | Partition Replicas</pre><pre>------------------------------------------------------------------</pre><pre>crypto-ksqlksql_processing_log | 1          | 1</pre><pre>docker-connect-configs         | 1          | 1</pre><pre>docker-connect-offsets         | 25         | 1</pre><pre>docker-connect-status          | 5          | 1</pre><pre><strong>pg_dev.public.mini_ticker</strong>      | 1          | 1</pre><pre>------------------------------------------------------------------</pre><p>Wow, we have a new topic with the name of our new table. Let’s check the events inside this topic with the following command.</p><pre><strong>PRINT</strong> &#39;pg_dev.public.mini_ticker&#39; <strong>FROM</strong> BEGINNING;</pre><p>You should see something like the following.</p><pre>Key format: HOPPING(KAFKA_INT) or TUMBLING(KAFKA_INT) or HOPPING(KAFKA_STRING) or TUMBLING(KAFKA_STRING) or KAFKA_STRING</pre><pre>Value format: AVRO</pre><pre>rowtime: 2022/08/08 17:33:13.066 Z, key: [1400140405@7166488599636816253/-], value: {&quot;id&quot;: 1, &quot;current_time_millis&quot;: 9999, &quot;epoch_time&quot;: 9999, &quot;pair&quot;: &quot;BTCUSDT&quot;, &quot;close&quot;: &quot;10000&quot;, &quot;open&quot;: &quot;10001&quot;, &quot;volume&quot;: &quot;10002&quot;, &quot;__source_ts_ms&quot;: 1659979992956, &quot;__deleted&quot;: &quot;false&quot;}, partition: 0</pre><p>This event is actually our first <strong>INSERT</strong> operation to the <em>mini_ticker</em> table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FjP48ZlzfVYsELg4ZVK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FjP48ZlzfVYsELg4ZVK%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FjP48ZlzfVYsELg4ZVK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6582939fed5b8595015cf8c05e99e45d/href">https://medium.com/media/6582939fed5b8595015cf8c05e99e45d/href</a></iframe><p>Let’s insert another row and see the change inside the kafka topic.</p><pre>Key format: HOPPING(KAFKA_INT) or TUMBLING(KAFKA_INT) or HOPPING(KAFKA_STRING) or TUMBLING(KAFKA_STRING) or KAFKA_STRING</pre><pre>Value format: AVRO</pre><pre>rowtime: 2022/08/08 17:33:13.066 Z, key: [1400140405@7166488599636816253/-], value: {&quot;id&quot;: 1, &quot;current_time_millis&quot;: 9999, &quot;epoch_time&quot;: 9999, &quot;pair&quot;: &quot;BTCUSDT&quot;, &quot;close&quot;: &quot;10000&quot;, &quot;open&quot;: &quot;10001&quot;, &quot;volume&quot;: &quot;10002&quot;, &quot;__source_ts_ms&quot;: 1659979992956, &quot;__deleted&quot;: &quot;false&quot;}, partition: 0</pre><pre>rowtime: 2022/08/08 17:54:01.767 Z, key: [1400140405@7166488599636816509/-], value: {&quot;id&quot;: 2, &quot;current_time_millis&quot;: 9998, &quot;epoch_time&quot;: 9998, &quot;pair&quot;: &quot;ETHUSDT&quot;, &quot;close&quot;: &quot;12345&quot;, &quot;open&quot;: &quot;12345&quot;, &quot;volume&quot;: &quot;12345&quot;, &quot;__source_ts_ms&quot;: 1659981241755, &quot;__deleted&quot;: &quot;false&quot;}, partition: 0</pre><p>As we can see, each <strong>INSERT</strong> operation creates a <em>new entry</em> inside the topic. What about the <strong>DELETE</strong> you may ask. Let’s delete the first row.</p><pre><strong>DELETE</strong> <strong>FROM</strong> mini_ticker <strong>WHERE</strong> ID <strong>=</strong> 1;</pre><p>After the <strong>DELETE</strong> operation our kafka topic looks like the following.</p><pre>Key format: HOPPING(KAFKA_INT) or TUMBLING(KAFKA_INT) or HOPPING(KAFKA_STRING) or TUMBLING(KAFKA_STRING) or KAFKA_STRING</pre><pre>Value format: AVRO</pre><pre>rowtime: 2022/08/08 17:33:13.066 Z, key: [1400140405@7166488599636816253/-], value: {&quot;id&quot;: 1, &quot;current_time_millis&quot;: 9999, &quot;epoch_time&quot;: 9999, &quot;pair&quot;: &quot;BTCUSDT&quot;, &quot;close&quot;: &quot;10000&quot;, &quot;open&quot;: &quot;10001&quot;, &quot;volume&quot;: &quot;10002&quot;, &quot;__source_ts_ms&quot;: 1659979992956, &quot;__deleted&quot;: &quot;false&quot;}, partition: 0</pre><pre>rowtime: 2022/08/08 17:54:01.767 Z, key: [1400140405@7166488599636816509/-], value: {&quot;id&quot;: 2, &quot;current_time_millis&quot;: 9998, &quot;epoch_time&quot;: 9998, &quot;pair&quot;: &quot;ETHUSDT&quot;, &quot;close&quot;: &quot;12345&quot;, &quot;open&quot;: &quot;12345&quot;, &quot;volume&quot;: &quot;12345&quot;, &quot;__source_ts_ms&quot;: 1659981241755, &quot;__deleted&quot;: &quot;false&quot;}, partition: 0</pre><pre>rowtime: 2022/08/08 17:56:58.509 Z, key: [1400140405@7166488599636816253/-], value: {&quot;id&quot;: 1, &quot;current_time_millis&quot;: null, &quot;epoch_time&quot;: null, &quot;pair&quot;: null, &quot;close&quot;: null, &quot;open&quot;: null, &quot;volume&quot;: null, &quot;__source_ts_ms&quot;: 1659981418499, &quot;__deleted&quot;: &quot;true&quot;}, partition: 0</pre><p>As we can see, we have another event with true <strong>__deleted</strong> field in the message queue. By default, debezium connector removes the records for DELETE operations from the event stream but the way we configure the connector prevents this behavior. (When we create the connector with the first curl command we set <strong>transforms.unwrap.delete.handling.mode</strong> to <strong>rewrite</strong>) This way we have a single <strong>source of truth</strong> that we can use to replicate our database.</p><p>Now that we have a working kafka-connect setup, in the <a href="https://medium.com/@itwasneo/scale-your-db-with-kafka-connect-part-2-716edf8f2770">second part</a> we will write the two “micro-services”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07fc6a1cffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>