<?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 Joshua Mo  on Medium]]></title>
        <description><![CDATA[Stories by Joshua Mo  on Medium]]></description>
        <link>https://medium.com/@joshmo_dev?source=rss-54c5c81fa2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yf2n7bMQdS7MkihSxwGmXA.jpeg</url>
            <title>Stories by Joshua Mo  on Medium</title>
            <link>https://medium.com/@joshmo_dev?source=rss-54c5c81fa2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:15:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshmo_dev/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[Building Agentic RAG with Rust, OpenAI & Qdrant]]></title>
            <link>https://medium.com/@joshmo_dev/building-agentic-rag-with-rust-openai-qdrant-d3a0bb85a267?source=rss-54c5c81fa2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a0bb85a267</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Joshua Mo ]]></dc:creator>
            <pubDate>Fri, 24 May 2024 08:59:07 GMT</pubDate>
            <atom:updated>2024-05-24T09:04:43.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*V26UUWp4e9OyepcT.png" /></figure><p>Hey there! In this article, we’re gonna talk about building an agentic RAG workflow with Rust! We’ll be building an agent that can take a CSV file, parse it and embed it into Qdrant, as well as retrieving the relevant embeddings from Qdrant to answer questions from users about the contents of the CSV file.</p><p>Interested in deploying or just want to see what the final code looks like? You can find the repository <a href="https://github.com/joshua-mo-143/shuttle-agentic-rag">here.</a></p><h3>What is Agentic RAG?</h3><p>Agentic RAG, or Agentic Retrieval Augmented Generation, is the concept of mixing AI agents with RAG to be able to produce a workflow that is even better at being tailored to a specific use case than an agent workflow normally would be.</p><p>Essentially, the difference between this workflow and a regular agent workflow would be that each agent can individually access embeddings from a vector database to be able to retrieve contextually relevant data — resulting in more accurate answers across the board in an AI agent workflow!</p><h3>Getting Started</h3><p>To get started, use cargo shuttle init to create a new project.</p><p>Next, we’ll add the dependencies we need using a shell snippet:</p><pre>cargo add anyhow cargo add async-openai cargo add qdrant-client cargo add serde -F derive cargo add serde-json cargo add shuttle-qdrant cargo add uuid -F v4</pre><p>We’ll also need to make sure to have a Qdrant URL and an API key, as well as an OpenAI API key. Shuttle uses environment variables via a SecretStore macro in the main function, and can be stored in the Secrets.toml file:</p><p>Next, we’ll update our main function to have our Qdrant macro and our secrets macro. We’ll iterate through each secret and set it as an environment variable — this allows us to use our secrets globally, without having to reference the SecretStore variable at all:</p><h3>Building an agentic RAG workflow</h3><h3>Setting up our agent</h3><p>The agent itself is quite simple: it holds an OpenAI client, as well as a Qdrant client to be able to search for relevant document embeddings. Other fields can also be added here, depending on what capabilities your agent requires.</p><p>Next we’ll want to create a helper method for creating the agent, as well as a system message which we’ll feed into the model prompt later.</p><pre>static SYSTEM_MESSAGE: &amp;str = &quot;<br>        You are a world-class data analyst, specialising in analysing comma-delimited CSV files.<br><br>     Your job is to analyse some CSV snippets and determine what the results are for the question that the user is asking.<br><br>     You should aim to be concise. If you don&#39;t know something, don&#39;t make it up but say &#39;I don&#39;t know.&#39;.<br>&quot;<br><br>impl MyAgent {<br>    pub fn new(qdrant_client: QdrantClient) -&gt; Self {<br>        let api_key = std::env::var(&quot;OPENAI_API_KEY&quot;).unwrap();<br>        let config = OpenAIConfig::new().with_api_key(api_key);<br><br>        let openai_client = OpenAIClient::with_config(config);<br><br>        Self {<br>            openai_client,<br>            qdrant_client,<br>        }<br>    }<br>}</pre><h3>File parsing and embedding into Qdrant</h3><p>Next, we will implement a File struct for CSV file parsing - it should be able to hold the file path, contents as well as the rows as a Vec&lt;String&gt; (string array, or more accurately a vector of strings). There&#39;s a few reasons why we store the rows as a Vec&lt;String&gt;:</p><ul><li>Smaller chunks improve the retrieval accuracy, one of the biggest challenges that RAG has to deal with. Retrieving a wrong or otherwise inaccurate document can hamper accuracy significantly.</li><li>Improved retrieval accuracy leads to enhanced contextual relevance — which is quite important for complex queries that require specific question.</li><li>Processing and indexing smaller chunks</li></ul><pre>pub struct File {<br>    pub path: String,<br>    pub contents: String,<br>    pub rows: Vec&lt;String&gt;,<br>}<br><br>impl File {<br>    pub fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        let contents = std::fs::read_to_string(&amp;path)?;<br><br>        let path_as_str = format!(&quot;{}&quot;, path.display());<br><br>        let rows = contents<br>            .lines()<br>            .map(|x| x.to_owned())<br>            .collect::&lt;Vec&lt;String&gt;&gt;();<br><br>        Ok(Self {<br>            path: path_as_str,<br>            contents,<br>            rows<br>        })<br>    }<br>}</pre><p>While the above parsing method <em>is</em> serviceable (collecting all the lines into a Vec&lt;String&gt;), note that it is a naive implementation. Based on how your CSV files are delimited and/or if there is dirty data to clean up, you may want to either prepare your data so that it is already well-prepared, or include some form of data cleaning or validation. Some examples of this might be:</p><p>Next, we’ll go back to our agent and implement a method for embedding documents into Qdrant that will take the File struct we defined.</p><p>To do this, we need to do the following:</p><ul><li>Take the rows we created earlier and add them as the input for our embed request.</li><li>Create the embeddings (with openAI) and create a payload for storing alongside the embeddings in Qdrant. Note that although we use a uuid::Uuid for unique storage, you could just as easily use numbers by adding a number counter to your struct and incrementing it by 1 after you&#39;ve inserted an embedding.</li><li>Assuming there are no errors, return Ok(())</li></ul><pre>use async_openai::types::{ CreateEmbeddingRequest, EmbeddingInput };<br>use async_openai::Embeddings;<br>use qdrant_client::prelude::{Payload, PointStruct};<br><br>static COLLECTION: &amp;str = &quot;my-collection&quot;;<br><br>// text-embedding-ada-002 is the model name from OpenAI that deals with embeddings<br>static EMBED_MODEL: &amp;str = &quot;text-embedding-ada-002&quot;;<br><br>impl MyAgent {<br>pub async fn embed_document(&amp;self, file: File) -&gt; Result&lt;()&gt; {<br>        if file.rows.is_empty() {<br>            return Err(anyhow::anyhow!(&quot;There&#39;s no rows to embed!&quot;));<br>        }<br><br>        let request = CreateEmbeddingRequest {<br>            model: EMBED_MODEL.to_string(),<br>            input: EmbeddingInput::StringArray(file.rows.clone()),<br>            user: None,<br>            dimensions: Some(1536),<br>            ..Default::default()<br>        };<br><br>        let embeddings_result = Embeddings::new(&amp;self.openai_client).create(request).await?;<br><br>        for embedding in embeddings_result.data {<br>            let payload: Payload = serde_json::json!({<br>                &quot;id&quot;: file.path.clone(),<br>                &quot;content&quot;: file.contents,<br>                &quot;rows&quot;: file.rows<br>            })<br>            .try_into()<br>            .unwrap();<br><br>            println!(&quot;Embedded: {}&quot;, file.path);<br><br>            let vec = embedding.embedding;<br><br>            let points = vec![PointStruct::new(<br>                uuid::Uuid::new_v4().to_string(),<br>                vec,<br>                payload,<br>            )];<br>            self.qdrant_client<br>                .upsert_points(COLLECTION, None, points, None)<br>                .await?;<br>        }<br>        Ok(())<br>    }<br>}</pre><h3>Document searching</h3><p>Now that we’ve embedded our document, we’ll want a way to check whether our embeddings are contextually relevant to whatever prompt the user gives us. For this, we’ll create a search_document function that does the following:</p><ul><li>Embed the prompt using CreateEmbeddingRequest and get the embedding from the results. We&#39;ll be using this embedding in our document search. Because we&#39;ve only added one sentence to embed here (the prompt), it will only return one sentence - so we can create an iterator from the vector and attempt to find the first result.</li><li>Create a parameter list for our document search through the SearchPoints struct (see below). Here we need to set the collection name, the vector that we want to search against (ie the input), how many results we want to be returned if there are any matches, as well as the payload selector.</li><li>Search the database for results — if there are no results, return an an error; if there is a result, then return the result back.</li></ul><pre>use qdrant_client::qdrant::{<br>    with_payload_selector::SelectorOptions, SearchPoints, WithPayloadSelector,<br>};<br><br>impl MyAgent {<br>    async fn search_document(&amp;self, prompt: String) -&gt; Result&lt;String&gt; {<br>        let request = CreateEmbeddingRequest {<br>            model: EMBED_MODEL.to_string(),<br>            input: EmbeddingInput::String(prompt),<br>            user: None,<br>            dimensions: Some(1536),<br>            ..Default::default()<br>        };<br><br>        let embeddings_result = Embeddings::new(&amp;self.openai_client).create(request).await?;<br><br>        let embedding = &amp;embeddings_result.data.first().unwrap().embedding;<br><br>        let payload_selector = WithPayloadSelector {<br>            selector_options: Some(SelectorOptions::Enable(true)),<br>        };<br><br>        // set parameters for search<br>        let search_points = SearchPoints {<br>            collection_name: COLLECTION.to_string(),<br>            vector: embedding.to_owned(),<br>            limit: 1,<br>            with_payload: Some(payload_selector),<br>            ..Default::default()<br>        };<br><br>        // if the search is successful<br>        // attempt to iterate through the results vector and find a result<br>        let search_result = self.qdrant_client.search_points(&amp;search_points).await?;<br>        let result = search_result.result.into_iter().next();<br><br>        match result {<br>            Some(res) =&gt; Ok(res.payload.get(&quot;contents&quot;).unwrap().to_string()),<br>            None =&gt; Err(anyhow::anyhow!(&quot;There were no results that matched :(&quot;)),<br>        }<br>    }<br>}</pre><p>Now that everything we need to use our agent effectively is set up, we can set up a prompt function!</p><pre>use async_openai::types::{<br>    ChatCompletionRequestMessage, ChatCompletionRequestSystemMessageArgs,<br>    ChatCompletionRequestUserMessageArgs, CreateChatCompletionRequestArgs,<br>};<br><br>static PROMPT_MODEL: &amp;str = &quot;gpt-4o&quot;;<br><br>impl MyAgent {<br>    pub async fn prompt(&amp;self, prompt: &amp;str) -&gt; anyhow::Result&lt;String&gt; {<br>        let context = self.search_document(prompt.to_owned()).await?;<br>        let input = format!(<br>            &quot;{prompt}<br><br>            Provided context:<br>            {}<br>            &quot;,<br>            context // this is the payload from Qdrant<br>        );<br><br>        let res = self<br>            .openai_client<br>            .chat()<br>            .create(<br>                CreateChatCompletionRequestArgs::default()<br>                    .model(PROMPT_MODEL)<br>                    .messages(vec![<br>                        //First we add the system message to define what the Agent does<br>                        ChatCompletionRequestMessage::System(<br>                            ChatCompletionRequestSystemMessageArgs::default()<br>                                .content(SYSTEM_MESSAGE)<br>                                .build()?,<br>                        ),<br>                        //Then we add our prompt<br>                        ChatCompletionRequestMessage::User(<br>                            ChatCompletionRequestUserMessageArgs::default()<br>                                .content(input)<br>                                .build()?,<br>                        ),<br>                    ])<br>                    .build()?,<br>            )<br>            .await<br>            .map(|res| {<br>                //We extract the first one<br>                res.choices[0].message.content.clone().unwrap()<br>            })?;<br><br>        println!(&quot;Retrieved result from prompt: {res}&quot;);<br><br>        Ok(res)<br>    }<br>}</pre><h3>Hooking the agent up to our web service</h3><p>Because we separated the agent logic from our web service logic, we just need to connect the bits together and we should be done!</p><p>Firstly, we’ll create a couple of structs — the Prompt struct that will take a JSON prompt, and the AppState function that will act as shared application state in our Axum web server.</p><pre>#[derive(Deserialize)]<br>pub struct Prompt {<br>    prompt: String,<br>}<br><br>#[derive(Clone)]<br>pub struct AppState {<br>    agent: MyAgent,<br>}</pre><p>We’ll also introduce our prompt handler endpoint here:</p><pre>async fn prompt(<br>    State(state): State&lt;AppState&gt;,<br>    Json(json): Json&lt;Prompt&gt;,<br>) -&gt; Result&lt;impl IntoResponse&gt; {<br>    let prompt_response = state.agent.prompt(&amp;json.prompt).await?;<br><br>    Ok((StatusCode::OK, prompt_response))<br>}</pre><p>Then we need to parse our CSV file in the main function, create our AppState and embed the CSV, as well as setting up our router:</p><pre>#[shuttle_runtime::main]<br>async fn main(<br>    #[shuttle_qdrant::Qdrant] qdrant_client: QdrantClient,<br>    #[shuttle_runtime::Secrets] secrets: SecretStore,<br>) -&gt; shuttle_axum::ShuttleAxum {<br>    secrets.into_iter().for_each(|x| {<br>        set_var(x.0, x.1);<br>    });<br><br>    // note that this already assumes you have a file called &quot;test.csv&quot;<br>    // in your project root<br>    let file = File::new(&quot;test.csv&quot;.into())?;<br><br>    let state = AppState {<br>        agent: MyAgent::new(qdrant_client),<br>    };<br><br>    state.agent.embed_document(file).await?;<br><br>    let router = Router::new()<br>        .route(&quot;/&quot;, get(hello_world))<br>        .route(&quot;/prompt&quot;, post(prompt))<br>        .with_state(state);<br><br>    Ok(router.into())<br>}</pre><h3>Deploying</h3><p>To deploy, all you need to do is use cargo shuttle deploy (with the --ad flag if on a Git branch with uncommitted changes), sit back and watch the magic happen!</p><h3>Finishing Up</h3><p>Thanks for reading! With the power of combining AI agents and RAG, we can create powerful workflows to be able to satisfy many different use cases. With Rust, we can leverage performance benefits to be able to run our workflows safely and with a low memory footprint.</p><p><em>Originally published at </em><a href="https://dev.to/shuttle_dev/building-agentic-rag-with-rust-openai-qdrant-3bjd"><em>https://dev.to</em></a><em> on May 24, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a0bb85a267" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Uptime Monitor in Rust]]></title>
            <link>https://medium.com/@joshmo_dev/building-an-uptime-monitor-in-rust-74ced41291c7?source=rss-54c5c81fa2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ced41291c7</guid>
            <category><![CDATA[monitoring-software]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Joshua Mo ]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 00:00:23 GMT</pubDate>
            <atom:updated>2024-02-08T19:03:04.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WIQaOu5520RPL5AF.png" /></figure><p>In this article, we’re going to talk about building and deploying an uptime-monitoring web service in Rust!</p><p>Interested in just deploying your uptime monitor? You can find that in 2 steps:</p><ol><li>Open your terminal and run cargo shuttle init --from joshua-mo-143/shuttle-monitoring-template (requires cargo-shuttle installed) and follow the prompt</li><li>Run cargo shuttle deploy --allow-dirty and watch the magic happen!</li></ol><p>For everyone who wants to learn how to build it, let’s get started — if you get lost, you can find the repo with the final code <a href="https://github.com/joshua-mo-143/shuttle-monitoring-template">here.</a></p><h3>Getting Started</h3><p>Firstly, we’ll initialize our project using cargo shuttle init (requires cargo-shuttle to be installed). Make sure you pick Axum as the framework!</p><p>Now you’ll want to install all of your dependencies. You can do that with the following shell snippet below:</p><pre>cargo add askama-axum<br>cargo add askama -F with-axum<br>cargo add chrono -F clock,serde<br>cargo add futures-util<br>cargo add reqwest<br>cargo add serde -F derive<br>cargo add shuttle-shared-db -F sqlx,postgres<br>cargo add sqlx -F runtime-tokio-rustls,postgres,macros,chrono<br>cargo add validator -F derive</pre><p>Once that’s done, we will want to install sqlx-cli to handle adding migrations. We can then run sqlx migrate add init and it will create a new migrations folder, along with an SQL file in it that we can use for migrations. Add the following text into the migration file:</p><pre>create table if not exists websites (<br>    id serial primary key,<br>    url varchar not null,<br>    alias varchar(75) not null unique<br>);<br><br>create table if not exists logs (<br>    id serial primary key,<br>    website_id int not null references websites(id),<br>    status smallint,<br>    created_at timestamp with time zone not null default date_trunc(&#39;minute&#39;, current_timestamp),<br>    UNIQUE (website_id, created_at) <br>);</pre><p>Next, we’ll want to add a database annotation to our program and add it as shared state to our Axum web service:</p><pre>#[derive(Clone)]<br>struct AppState {<br>    db: PgPool,<br>}<br><br>impl AppState {<br>    fn new(db: PgPool) -&gt; Self {<br>        Self { db }<br>    }<br>}<br><br>#[shuttle_runtime::main]<br>async fn main(<br>    #[shuttle_shared_db::Postgres] db: PgPool<br>) -&gt; shuttle_axum::ShuttleAxum {<br>    // carry out migrations<br>    sqlx::migrate!().run(&amp;db).await.expect(&quot;Migrations went wrong :(&quot;);<br><br>    let state = AppState::new(db);<br><br>    let router = Router::new().route(&quot;/&quot;, get(hello_world)).with_state(state);<br><br>    Ok(router.into())<br>}</pre><p>With one line of code, we’ve now given ourselves a database! Locally, Shuttle will use Docker to provision a Postgres container for us. In production, we are automatically provisioned one by Shuttle’s servers with no input required on our part. Normally, it would be a bit of a pain to do manually but this has saved us some time.</p><p>Lastly, here is the list of imports we’ll be using — make sure to add this to the top of your main.rs file:</p><pre>use askama::Template;<br>use chrono::Timelike;<br>use askama_axum::IntoResponse as AskamaIntoResponse;<br>use axum::{<br>    extract::{Form, Path, State},<br>    http::StatusCode,<br>    response::{IntoResponse as AxumIntoResponse, Redirect, Response},<br>    routing::{get, post},<br>    Router,<br>};<br>use chrono::{DateTime, Utc};<br>use futures_util::StreamExt;<br>use reqwest::Client;<br>use serde::{Deserialize, Serialize};<br>use sqlx::PgPool;<br>use tokio::time::{self, Duration};<br>use validator::Validate;</pre><h3>Building</h3><p>There are three main parts to this: The frontend, the backend, and the actual monitoring task itself. Let’s start with the monitoring task first.</p><h3>Monitoring task</h3><p>The monitoring task itself is simple enough: we fetch the list of websites from the database, then sequentially send a HTTP request to each of them and record the results in Postgres. Firstly, we’ll create the struct that we want to represent the Website:</p><pre>#[derive(Deserialize, sqlx::FromRow, Validate)]<br>struct Website {<br>    #[validate(url)]<br>    url: String,<br>    alias: String<br>}</pre><p>Here we instantiate a reqwest client and then fetch all of the websites that we want to search for:</p><pre>async fn check_websites(db: PgPool) {<br>    let ctx = Client::new();<br><br>    let mut res = sqlx::query_as::&lt;_, Website&gt;(&quot;SELECT url, alias FROM websites&quot;).fetch(&amp;db);<br><br>    // .. rest of your code<br>}</pre><p>We <em>could</em> use fetch_all(), but by using fetch() we get a Stream back and can skip dealing with RowNotFound SQL errors by checking whether or not there are any rows to fetch.</p><p>Now that we have our list of websites (or lack thereof), we can try to send a request sequentially to each website that exists then store the results of the fetch in our database:</p><pre>while let Some(website) = res.next().await {<br>    let website = website.unwrap();<br><br>    let response = ctx.get(website.url).send().await.unwrap();<br><br>    sqlx::query(<br>        &quot;INSERT INTO logs (website_alias, status)<br>            VALUES<br>            ((SELECT id FROM websites where alias = $1), $2)&quot;<br>    )<br>        .bind(website.alias)<br>        .bind(response.status().as_u16() as i16)<br>        .execute(&amp;db).await<br>        .unwrap();<br>}</pre><p>While we don’t store the response body, at this point there’s not much reason to do so. The response status should give us all the information we need.</p><p>In the full function, we want to use tokio::time::interval to be able to accurately start the loop again. See below for the code block which includes this:</p><pre>async fn check_websites(db: PgPool) {<br>    let mut interval = time::interval(Duration::from_secs(60));<br>    loop {<br>        interval.tick().await;<br><br>        let ctx = Client::new();<br><br>        let mut res = sqlx::query_as::&lt;_, Website&gt;(&quot;SELECT url, alias FROM websites&quot;).fetch(&amp;db);<br><br>        while let Some(website) = res.next().await {<br>            let website = website.unwrap();<br><br>            let response = ctx.get(website.url).send().await.unwrap();<br><br>            sqlx::query(<br>                &quot;INSERT INTO logs (website_alias, status)<br>                        VALUES<br>                        ((SELECT id FROM websites where alias = $1), $2)&quot;<br>            )<br>                .bind(website.alias)<br>                .bind(response.status().as_u16() as i16)<br>                .execute(&amp;db).await<br>                .unwrap();<br>        }<br>    }<br>}</pre><h3>Backend</h3><p>Before we start our backend, we should probably add an error handling enum. Let’s add an enum with one arm, implement axum::response::IntoResponse for it (currently aliased in our program as AxumIntoResponse) and then implement From&lt;sqlx::Error&gt; for easy error propagation:</p><pre>enum ApiError {<br>    SQL(sqlx::Error)<br>}<br><br>impl From&lt;sqlx::Error&gt; for ApiError {<br>    fn from(e: sqlx::Error) -&gt; Self {<br>        Self::SQLError(e)<br>    }<br>}<br>impl AxumIntoResponse for ApiError {<br>    fn into_response(self) -&gt; Response {<br>        match self {<br>            Self::SQLError(e) =&gt; {<br>                (<br>                    StatusCode::INTERNAL_SERVER_ERROR,<br>                    format!(&quot;SQL Error: {e}&quot;)<br>                    ).into_response()<br>            }<br>        }<br>    }<br>}</pre><p>Now when we use any SQL queries, we can propagate the error by using ? instead of unwrapping or having to manually deal with error handling! Of course, there will be certain situations where we can handle errors manually, but this will save a lot of pattern matching (or alternatively, .unwrap()or .expect()) within our code. We can also use it as a return type in our handler functions.</p><p>To start working on our backend, we can create an initial route to add a URL to monitor. You may have noticed earlier we added the Validate derive trait. This allows us to validate the form data using preset rules and automatically return an error if the validation fails. In this case, we used #[validate(url)] - so if the string isn&#39;t in a URL format it will automatically break:</p><pre>async fn create_website(<br>    State(state): State&lt;AppState&gt;,<br>    Form(new_website): Form&lt;Website&gt;,<br>) -&gt; Result&lt;impl AxumIntoResponse, ApiError&gt; {<br>    if new_website.validate().is_err() {<br>        return Err((<br>            StatusCode::INTERNAL_SERVER_ERROR,<br>            &quot;Validation error: is your website a reachable URL?&quot;,<br>        ));<br>    }<br><br>    sqlx::query(&quot;INSERT INTO websites (url, alias) VALUES ($1, $2)&quot;)<br>        .bind(new_website.url)<br>        .bind(new_website.alias)<br>        .execute(&amp;state.db)<br>        .await<br>        .unwrap();<br><br>    Ok(Redirect::to(&quot;/&quot;))<br>}</pre><p>Now let’s write a route to grab all the websites we’re monitoring, as well as get a quick report on what the uptime was like in the last recorded 24 hours (filling in any gaps where required) for each website.</p><p>Like before with the monitoring tasks, we need to grab a list of all of the websites we’re currently tracking and add them to a vector of website data (except we will assume there are results there. If not, askama will handle it for us by automatically not rendering any records):</p><pre>#[derive(Serialize, Validate)]<br>struct WebsiteInfo {<br>    #[validate(url)]<br>    url: String,<br>    alias: String,<br>    data: Vec&lt;WebsiteStats&gt;,<br>}<br><br>#[derive(sqlx::FromRow, Serialize)]<br>pub struct WebsiteStats {<br>    time: DateTime&lt;Utc&gt;,<br>    uptime_pct: Option&lt;i16&gt;,<br>}<br><br>async fn get_websites(State(state): State&lt;AppState&gt;) -&gt; Result&lt;impl AskamaIntoResponse, ApiError&gt; {<br>    let websites = sqlx::query_as::&lt;_, Website&gt;(&quot;SELECT url, alias FROM websites&quot;)<br>        .fetch_all(&amp;state.db)<br>        .await?;<br><br>    let mut logs = Vec::new();<br><br>    for website in websites {<br>        let data = get_daily_stats(&amp;website.alias, &amp;state.db).await?;<br><br>        logs.push(WebsiteInfo {<br>            url: website.url,<br>            alias: website.alias,<br>            data,<br>        });<br>    }<br><br>    Ok(WebsiteLogs { logs })<br>}</pre><p>Once this is done, we’ll then need to make a new Vector. This will hold all the website URLs (and respective aliases) as well as a list of timestamps with the uptime percentage over the last 24 hours, calculated per hour from how many HTTP requests returned with 200 OK. We then need to check if there&#39;s any gaps and fill them in with a None. This lets the person viewing the data know that no data was recorded at the time (for example if we&#39;re either developing locally, or if the service itself had an outage and was unable to record data).</p><p>To start with, let’s write a function for getting the daily stats for a given URL:</p><pre>#[derive(sqlx::FromRow, Serialize)]<br>pub struct WebsiteStats {<br>    time: DateTime&lt;Utc&gt;,<br>    uptime_pct: Option&lt;i16&gt;,<br>}<br><br>async fn get_daily_stats(alias: &amp;str, db: &amp;PgPool) -&gt; Result&lt;Vec&lt;WebsiteStats&gt;, ApiError&gt; {<br>    let data = sqlx<br>        ::query_as::&lt;_, WebsiteStats&gt;(<br>            r#&quot;<br>            SELECT date_trunc(&#39;hour&#39;, created_at) as time,<br>            CAST(COUNT(case when status = 200 then 1 end) * 100 / COUNT(*) AS int2) as uptime_pct<br>            FROM logs<br>            LEFT JOIN websites on websites.id = logs.website_id<br>            WHERE websites.alias = $1<br>            group by time<br>            order by time asc<br>            limit 24<br>            &quot;#<br>        )<br>        .bind(alias)<br>        .fetch_all(db).await?;<br><br>    let number_of_splits = 24;<br>    let number_of_seconds = 3600;<br><br>    let data = fill_data_gaps(data, number_of_splits, SplitBy::Hour, number_of_seconds);<br><br>    Ok(data)<br>}</pre><p>Although the SQL function looks quite complicated, it basically retrieves a truncated date (down to the hour) and an uptime percentage based on the recorded data and what percentage recorded 200 OK response status. The query then aggregates them by timestamp and limits it to the last 24 hours.</p><p>Of course, this can lead to some awkward gaps in our data — for example, what if our monitoring web service goes down? We can’t exactly just go back in time and record the data! We can, however, make up for this by filling in the gaps with a new fill_data_gaps function that will inform the webpage viewer that there&#39;s no data points for a given time.</p><p>We can do this by declaring an enum:</p><pre>enum SplitBy {<br>    Hour,<br>    Day<br>}</pre><p>This enum will allow us to differentiate what period we want data over. We can abstract this block into its own function:</p><pre>fn fill_data_gaps(<br>    mut data: Vec&lt;WebsiteStats&gt;,<br>    splits: i32,<br>    format: SplitBy,<br>    number_of_seconds: i32<br>) -&gt; Vec&lt;WebsiteStats&gt; {<br>    // if the length of data is not as long as the number of required splits (24)<br>    // then we fill in the gaps<br>    if (data.len() as i32) &lt; splits {<br>        // for each split, format the time and check if the timestamp exists<br>        for i in 1..24 {<br>            let time = Utc::now() - chrono::Duration::seconds((number_of_seconds * i).into());<br>            let time = time<br>                .with_minute(0)<br>                .unwrap()<br>                .with_second(0)<br>                .unwrap()<br>                .with_nanosecond(0)<br>                .unwrap();<br><br>            let time = if matches!(format, SplitBy::Day) {<br>                time.with_hour(0).unwrap()<br>            } else {<br>                time<br>            };<br>            // if timestamp doesn&#39;t exist, push a timestamp with None<br>            if !data.iter().any(|x| x.time == time) {<br>                data.push(WebsiteStats {<br>                    time,<br>                    uptime_pct: None,<br>                });<br>            }<br>        }<br>        // finally, sort the data<br>        data.sort_by(|a, b| b.time.cmp(&amp;a.time));<br>    }<br><br>    data<br>}</pre><p>Once done, we’ll want to create a dynamic route for getting more information about a monitored URL. We can use this page to display things like past incidents/alerts. This function will follow most of the previous handler function except we’re fetching one URL and additionally grabbing any records of HTTP requests that didn’t return 200 OK and labelling them as &quot;Incidents&quot;.</p><p>As you can see below it is <em>mostly</em> the same as grabbing data for all websites, except now we also have last month’s data (split by day) to add to our return results:</p><pre>#[derive(Serialize, sqlx::FromRow, Template)]<br>#[template(path = &quot;single_website.html&quot;)]<br>struct SingleWebsiteLogs {<br>    log: WebsiteInfo,<br>    incidents: Vec&lt;Incident&gt;,<br>    monthly_data: Vec&lt;WebsiteStats&gt;,<br>}<br><br>#[derive(sqlx::FromRow, Serialize)]<br>pub struct Incident {<br>    time: DateTime&lt;Utc&gt;,<br>    status: i16,<br>}<br><br>async fn get_website_by_alias(<br>    State(state): State&lt;AppState&gt;,<br>    Path(alias): Path&lt;String&gt;,<br>) -&gt; Result&lt;impl AskamaIntoResponse, ApiError&gt; {<br>    let website = sqlx::query_as::&lt;_, Website&gt;(&quot;SELECT url, alias FROM websites WHERE alias = $1&quot;)<br>        .bind(&amp;alias)<br>        .fetch_one(&amp;state.db)<br>        .await?;<br><br>    let last_24_hours_data = get_daily_stats(&amp;website.alias, &amp;state.db).await?;<br>    let monthly_data = get_monthly_stats(&amp;website.alias, &amp;state.db).await?;<br><br>    let incidents = sqlx::query_as::&lt;_, Incident&gt;(<br>        &quot;SELECT logs.created_at as time, <br>         logs.status from logs <br>         left join websites on websites.id = logs.website_id <br>         where websites.alias = $1 and logs.status != 200&quot;,<br>    )<br>    .bind(&amp;alias)<br>    .fetch_all(&amp;state.db)<br>    .await?;<br><br>    let log = WebsiteInfo {<br>        url: website.url,<br>        alias,<br>        data: last_24_hours_data,<br>    };<br><br>    Ok(SingleWebsiteLogs {<br>        log,<br>        incidents,<br>        monthly_data,<br>    })<br>}</pre><p>Finally, we need to create a route for deleting a website. This will be a two-step process where we need to delete all of the website logs and then the URL itself, then return 200 OK if everything went well. We can use a transaction to rollback if there&#39;s an error anywhere in this process and manually return ApiError:</p><pre>async fn delete_website(<br>    State(state): State&lt;AppState&gt;,<br>    Path(alias): Path&lt;String&gt;,<br>) -&gt; Result&lt;impl AxumIntoResponse, ApiError&gt; {<br>    let mut tx = state.db.begin().await?;<br>    if let Err(e) = sqlx::query(&quot;DELETE FROM logs WHERE website_alias = $1&quot;)<br>        .bind(&amp;alias)<br>        .execute(&amp;mut *tx)<br>        .await {<br>            tx.rollback().await?;<br>            return Err(ApiError::SQLError(e));<br>        };<br><br>    if let Err(e) = sqlx::query(&quot;DELETE FROM websites WHERE alias = $1&quot;)<br>        .bind(&amp;alias)<br>        .execute(&amp;mut *tx)<br>        .await {<br>            tx.rollback().await?;<br>            return Err(ApiError::SQLError(e));<br>        }<br><br>    tx.commit().await?;<br><br>    Ok(StatusCode::OK)<br>}</pre><h3>Frontend</h3><p>We’ll want to make four files:</p><ul><li>A base.html file that will hold the head of our HTML so we don&#39;t need to write it in every file.</li><li>An index.html file.</li><li>A single_website.html file (for grabbing information about an individual monitored URL).</li><li>A styles.css file.</li></ul><p>We’ll first want to make our base.html file:</p><pre>&lt;!-- templates/base.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>        &lt;script src=&quot;https://unpkg.com/htmx.org@1.9.10&quot; integrity=&quot;sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;/styles.css&quot;/&gt;<br>     &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;<br>&lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;<br>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Roboto&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br><br>    &lt;title&gt;Shuttle Status Monitor&lt;/title&gt;<br>    {% block head %}{% endblock %}<br>&lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div id=&quot;content&quot;&gt;<br>            {% block content %}&lt;p&gt;Placeholder content&lt;/p&gt;{% endblock %}<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>This will be extended in the rest of the templates so that we won’t need to constantly copy and paste the HTML head every time we want to use HTMX or the Google fonts.</p><p>Here is the HTML for our main page:</p><pre>&lt;!-- index.html --&gt;<br>{% extends &quot;base.html&quot; %} {% block content %}<br>&lt;h1&gt;Shuttle Status Monitor&lt;/h1&gt;<br>&lt;form action=&quot;/websites&quot; method=&quot;POST&quot;&gt;<br>    &lt;input name=&quot;url&quot; placeholder=&quot;url&quot; required /&gt;<br>    &lt;input name=&quot;alias&quot; placeholder=&quot;alias&quot; required /&gt;<br>    &lt;button class=&quot;submit-button&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;div class=&quot;website-list&quot;&gt;<br>    {% for log in logs %}<br>    &lt;div class=&quot;website&quot;&gt;<br>        &lt;h2 class=&quot;website-name&quot;&gt;{{log.alias}} - {{log.url}}&lt;/h2&gt;<br>        &lt;div&gt;<br>            Last 24 hours: {% for timestamp in log.data %} {% match<br>            timestamp.uptime_pct %} {% when Some with (100) %}<br>            &lt;div class=&quot;tooltip&quot;&gt;<br>                🟢<br>                &lt;span class=&quot;tooltiptext&quot;<br>                    &gt;{{timestamp.time}} Uptime:<br>                    {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>                &gt;<br>            &lt;/div&gt;<br>            {% when None %}<br>            &lt;div class=&quot;tooltip&quot;&gt;<br>                ⚪<br>                &lt;span class=&quot;tooltiptext&quot;<br>                    &gt;{{timestamp.time}} No data here :(&lt;/span<br>                &gt;<br>            &lt;/div&gt;<br>            {% else %}<br>            &lt;div class=&quot;tooltip&quot;&gt;<br>                🔴<br><br>                &lt;span class=&quot;tooltiptext&quot;<br>                    &gt;{{timestamp.time}} Uptime:<br>                    {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>                &gt;<br>            &lt;/div&gt;<br><br>            {% endmatch %} {% endfor %}<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;a href=&quot;/websites/{{log.alias}}&quot; class=&quot;view-button&quot;&gt;View&lt;/a&gt;<br>            &lt;button<br>                hx-delete=&quot;/websites/{{log.alias}}&quot;<br>                class=&quot;delete-button&quot;<br>                hx-confirm=&quot;Are you sure you want to stop tracking this website?&quot;<br>                hx-target=&quot;closest .menu&quot;<br>                hx-swap=&quot;outerHTML&quot;<br>            &gt;<br>                Delete<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    {% endfor %}</pre><p>You may have noticed we’re using tooltips to display the time of day that the request was taken as well as displaying the uptime percentage on the webpage. In the CSS file, we add styling so that when you hover over a circle, a tooltip will display the timestamp the circle represents as well as the exact uptime percentage.</p><p>The single URL HTML webpage is also mostly the same, except we’re also adding an incident list:</p><pre>&lt;!-- single_website.html --&gt;<br>{% extends &quot;base.html&quot; %} {% block content %}<br>&lt;h1&gt;Shuttle Status Monitor&lt;/h1&gt;<br>&lt;a href=&quot;/&quot;&gt;Back to main page&lt;/a&gt;<br>&lt;div class=&quot;website&quot;&gt;<br>    &lt;h2 class=&quot;website-name&quot;&gt;{{log.alias}} - {{log.url}}&lt;/h2&gt;<br>    &lt;div&gt;<br>        Last 24 hours: {% for timestamp in log.data %} {% match<br>        timestamp.uptime_pct %} {% when Some with (100) %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            🟢<br>            &lt;span class=&quot;tooltiptext&quot;<br>                &gt;{{timestamp.time}} Uptime:<br>                {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>            &gt;<br>        &lt;/div&gt;<br>        {% when None %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            ⚪<br>            &lt;span class=&quot;tooltiptext&quot;&gt;{{timestamp.time}} No data here :(&lt;/span&gt;<br>        &lt;/div&gt;<br>        {% else %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            🔴<br><br>            &lt;span class=&quot;tooltiptext&quot;<br>                &gt;{{timestamp.time}} Uptime:<br>                {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>            &gt;<br>        &lt;/div&gt;<br><br>        {% endmatch %} {% endfor %}<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        Last 30 days: {% for timestamp in monthly_data %} {% match<br>        timestamp.uptime_pct %} {% when Some with (100) %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            🟢<br>            &lt;span class=&quot;tooltiptext&quot;<br>                &gt;{{timestamp.time}} Uptime:<br>                {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>            &gt;<br>        &lt;/div&gt;<br>        {% when None %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            ⚪<br>            &lt;span class=&quot;tooltiptext&quot;&gt;{{timestamp.time}} No data here :(&lt;/span&gt;<br>        &lt;/div&gt;<br>        {% else %}<br>        &lt;div class=&quot;tooltip&quot;&gt;<br>            🔴<br><br>            &lt;span class=&quot;tooltiptext&quot;<br>                &gt;{{timestamp.time}} Uptime:<br>                {{timestamp.uptime_pct.unwrap()}}%&lt;/span<br>            &gt;<br>        &lt;/div&gt;<br><br>        {% endmatch %} {% endfor %}<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;incident-list&quot;&gt;<br>    &lt;h2&gt;Incidents&lt;/h2&gt;<br>    {% if incidents.len() &gt; 0 %} {% for incident in incidents %}<br>    &lt;div class=&quot;incident&quot;&gt;{{incident.time}} - {{incident.status}}&lt;/div&gt;<br>    {% endfor %} {% else %} No incidents reported. {% endif %}<br>&lt;/div&gt;<br>{% endblock %}</pre><p>Now it’s time to add the CSS styling! The CSS file is extremely long; for the sake of not overwhelming you with code blocks, you can find it <a href="https://github.com/joshua-mo-143/shuttle-monitoring-template/blob/main/templates/styles.css">here.</a> However, if you’d like to add your own styling, you’re free to do so! We also additionally need to add the CSS file handling route — otherwise, our HTML won’t be able to find it. We can do this like so:</p><pre>// note this assumes your file is at &quot;templates/styles.css&quot;<br>async fn styles() -&gt; impl AxumIntoResponse {<br>    Response::builder()<br>        .status(StatusCode::OK)<br>        .header(&quot;Content-Type&quot;, &quot;text/css&quot;)<br>        .body(include_str!(&quot;../templates/styles.css&quot;).to_owned())<br>        .unwrap()<br>}</pre><p>Then when we add the route to our Router, we need to specify the route as /styles.css.</p><h3>Hooking everything up</h3><p>Now it’s time to hook everything up! All you need to do is to create the AppState, spawn the monitoring request loop as a tokio task and then create your Router:</p><pre>// main.rs<br>#[shuttle_runtime::main]<br>async fn main(#[shuttle_shared_db::Postgres] db: PgPool) -&gt; shuttle_axum::ShuttleAxum {<br>    sqlx::migrate!().run(&amp;db).await.unwrap();<br>    let state = AppState::new(db.clone());<br>    tokio::spawn(async move {<br>        check_websites(db).await;<br>    });<br>    let router = Router::new()<br>        .route(&quot;/&quot;, get(get_websites))<br>        .route(&quot;/websites&quot;, post(create_website))<br>        .route(<br>            &quot;/websites/:alias&quot;,<br>            get(get_website_by_id).delete(delete_website),<br>        )<br>        .route(&quot;/styles.css&quot;, get(styles))<br>        .with_state(state);<br>    Ok(router.into())<br>}</pre><h3>Deploying</h3><p>Now it’s time to deploy! Type in cargo shuttle deploy (add --allow-dirty if on a dirty Git branch) and watch the magic happen. When your program has deployed, it’ll give you the URL of your deployment where you can try it out as well as deployment ID and other details like your database connection (password is hidden until you use the --show-secrets flag).</p><h3>Finishing up</h3><p>Thanks for reading! I hope you have learned a little bit more about Rust by writing an uptime monitoring service.</p><p><em>Originally published at </em><a href="https://www.shuttle.rs/blog/2024/02/08/uptime-monitoring-rust"><em>https://www.shuttle.rs</em></a><em> on February 8, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ced41291c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Shuttle Labs — cutting-edge Rust talks]]></title>
            <link>https://medium.com/@joshmo_dev/introducing-shuttle-labs-cutting-edge-rust-talks-ec5b1c299f50?source=rss-54c5c81fa2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5b1c299f50</guid>
            <category><![CDATA[talks]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Joshua Mo ]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 23:59:37 GMT</pubDate>
            <atom:updated>2024-01-31T00:01:05.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Shuttle Labs — cutting-edge Rust talks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZdy09RrcdedrGUtrLDfEQ.png" /><figcaption>article thumbnail</figcaption></figure><h3>Discussing cutting-edge advancements in the Rust ecosystem</h3><p>If you’re looking to stay ahead of the curve on all things Rust, connect with fellow Rustaceans and expand your skills, we’d love to have you join us at <strong>ShuttleLabs</strong>. Each month we will be hosting a thought leader from the space, diving into the hottest topics and creating an opportunity for discussion that can’t be found anywhere else.</p><h3>Why we decided to start ShuttleLabs</h3><p>Rust is growing faster than its resources and it’s difficult to stay up-to-date on all the advancements in the space. We hope that ShuttleLabs will solve this problem and create an environment for both seasoned and new Rust devs to continually learn, share their perspective, and hear from great contributors in the ecosystem.</p><p>In our first session we will be exploring <strong>Async In Rust, with Stefan Baumgartner!</strong> Async in Rust is a big topic as Rust deals with async at a low level: using futures and executors, as well as being able to programatically create your own async runtime!</p><p>The details of the talk are below:</p><p>Topic: <strong>Async in Rust</strong></p><p>Speaker: <strong>Stefan Baumgartner</strong> (@ddprrt on X)</p><p>Date: <strong>February 6th, 15:00 (UTC)</strong></p><p>Location: <a href="https://discord.gg/shuttle">https://discord.gg/shuttle</a></p><p>If you want to be kept in the loop, <a href="https://shuttlerust.typeform.com/shuttlelabs">sign up here</a> to secure your spot and receive an email ahead of our next session.</p><p>See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5b1c299f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Serde in Rust]]></title>
            <link>https://medium.com/@joshmo_dev/using-serde-in-rust-dc620ce4beff?source=rss-54c5c81fa2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc620ce4beff</guid>
            <category><![CDATA[gui̇de]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Joshua Mo ]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 00:22:18 GMT</pubDate>
            <atom:updated>2024-01-24T00:22:18.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkVU_broQhD1fLCziWu06g.png" /><figcaption>Thumbnail for article</figcaption></figure><p>In this article we’ll be talking about Serde, how you can use it in your Rust application as well as some more advanced tips and tricks.</p><h3>What is serde?</h3><p>The serde Rust crate is used to efficiently serialize and deserialize data in many formats. It does this by providing two traits you can use, aptly named Deserialize and Serialize. Being one of the most well-known crates in the ecosystem, it currently supports (de)serialization to over 20 types.</p><p>To get started, you’ll want to install the crate into your Rust application:</p><pre>cargo add serde</pre><h3>Using serde</h3><h3>Deserializing and Serializing data</h3><p>The simple way to serialize and deserialize data is by adding the serde derive feature. This adds a macro that you can use to implement Deserialize and Serialize automatically - you can do this with the --features flag (-F for short):</p><pre>cargo add serde -F derive</pre><p>Then we can add a macro to any struct or enum that we want to implement Deserialize or Serialize for:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>struct MyStruct {<br>    message: String,<br>    // ... the rest of your fields<br>}</pre><p>This allows us to use any crate with serde support to convert between said formats. As an example, let’s use serde-json to convert to and from JSON format:</p><pre>use serde_json::json;<br>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>struct MyStruct {<br>    message: String,<br>}<br><br>fn to_and_from_json() {<br>    let json = json!({&quot;message&quot;: &quot;Hello world!&quot;});<br>    let my_struct: MyStruct = serde_json::from_str(&amp;json).unwrap();<br>    assert_eq!(my_struct, MyStruct { message: &quot;Hello world!&quot;.to_string());<br>    assert!(serde_json::to_string(my_struct).is_ok());<br>}</pre><p>If you’re interested in using serde-json for your Rust application, we have an article talking about JSON parsing libraries which you can check out <a href="https://www.shuttle.rs/blog/2024/01/18/parsing-json-rust">here.</a></p><p>We can also deserialize and serialize to/from many sources including from a file stream I/O, a JSON byte array and more!</p><h3>Implementing Deserialize and Serialize manually</h3><p>In order to better understand how serde works under the hood, we can also implement Deserialize and Serialize manually. This is quite complicated, but for now we will stick with a simple implementation. Here is a simple implementation for serializing an i32 primitive type:</p><pre>use serde::{Serializer, Serialize};<br><br>impl Serialize for i32 {<br>    fn serialize&lt;S&gt;(&amp;self, serializer: S) -&gt; Result&lt;S::Ok, S::Error&gt;<br>    where<br>        S: Serializer,<br>    {<br>        serializer.serialize_i32(*self)<br>    }<br>}</pre><p>To be able to convert the type, serde internally requires us to use a type that implements Serializer. To implement Serialize for a type that isn’t directly a primitive, we can extend this by serializing into a primitive, then converting into whatever type we want from the primitive. If we want custom serialization for structs, we can also do the same with use of the SerializeStruct trait:</p><pre>use serde::ser::{Serialize, Serializer, SerializeStruct};<br><br>struct Color {<br>    r: u8,<br>    g: u8,<br>    b: u8,<br>}<br><br>impl Serialize for Color {<br>    fn serialize&lt;S&gt;(&amp;self, serializer: S) -&gt; Result&lt;S::Ok, S::Error&gt;<br>    where<br>        S: Serializer,<br>    {<br>        // 3 is the number of fields in the struct.<br>        let mut state = serializer.serialize_struct(&quot;Color&quot;, 3)?;<br>        state.serialize_field(&quot;r&quot;, &amp;self.r)?;<br>        state.serialize_field(&quot;g&quot;, &amp;self.g)?;<br>        state.serialize_field(&quot;b&quot;, &amp;self.b)?;<br>        state.end()<br>    }<br>}</pre><p>Note that to serialize a field, the field type also needs to implement Serialize. If you have a custom type that doesn&#39;t implement Serialize, you will either need to implement Serialize or use a Serialize derive macro (if the struct/enum type holds types that all implement Serialize).</p><p>The Deserialize trait is a little bit different and is a fair bit more complicated to implement. To be able to deserialize to a type, the type itself needs to implement Sized which means that there are a number of types which can’t use this trait (for example &amp;str) because they are unsized types. To deserialize a type, you also need to use a type that implements the Visitor trait.</p><p>The Visitor trait uses the Visitor design pattern in Rust. This means that it encapsulates an algorithm that operates over a collection of same-sized objects. It allows you to write multiple different algorithms for operating over the data, without needing to change any original functionality. You can find out more about this <a href="https://rust-unofficial.github.io/patterns/patterns/behavioural/visitor.html">here.</a></p><p>Below is an example for a MessageVisitor type that attempts to deserialize multiple types to String:</p><pre>use std::fmt;<br><br>use serde::de::{self, Visitor};<br><br>struct MessageVisitor;<br><br>impl&lt;&#39;de&gt; Visitor&lt;&#39;de&gt; for MessageVisitor {<br>    type Value = String;<br><br>    fn expecting(&amp;self, formatter: &amp;mut fmt::Formatter) -&gt; fmt::Result {<br>        formatter.write_str(&quot;A message that can either be deserialized from an i32 or String&quot;)<br>    }<br>    fn visit_string&lt;E&gt;(self, value: String) -&gt; Result&lt;Self::Value, E&gt;<br>    where<br>        E: de::Error,<br>    {<br>        Ok(value)<br>    }<br>    fn visit_str&lt;E&gt;(self, value: &amp;str) -&gt; Result&lt;Self::Value, E&gt;<br>    where<br>        E: de::Error,<br>    {<br>        Ok(value.to_owned())<br>    }<br>    fn visit_i32&lt;E&gt;(self, value: i32) -&gt; Result&lt;Self::Value, E&gt;<br>    where<br>        E: de::Error,<br>    {<br>        Ok(value.to_string())<br>    }<br>}</pre><p>As you can see, the implementation is quite large! However, it also allows us to make the implementation much simpler. By implementing the Visitor trait, we can pass the type that implements it to our Deserialize method and then deserialize JSON into our struct:</p><pre>use serde::{Deserialize, Deserializer};<br><br>impl&lt;&#39;de&gt; Deserialize&lt;&#39;de&gt; for MyStruct {<br>    fn deserialize&lt;D&gt;(deserializer: D) -&gt; Result&lt;Self, D::Error&gt;<br>    where<br>        D: Deserializer&lt;&#39;de&gt;,<br>    {<br>		// note: don&#39;t use unwrap in production!<br>        let message = deserializer.deserialize_string(MessageVisitor).unwrap();<br>        Ok(Self { message })<br>    }<br>}</pre><p>There is also documentation on deserializing structs which you can find <a href="https://serde.rs/deserialize-struct.html">here.</a> However, generally speaking it is recommended that you use the derive feature macros as the manual implementation (as seen on the page itself) is quite large. The implementation involves mostly using a visitor that can visit a map or sequence then iterate through the elements to deserialize it.</p><h3>Using serde attributes</h3><p>When it comes to serde, the crate also has a number of useful attribute macros that we can use on our types to allow things like field renaming when deserializing a field or serializing to a struct. One of the best examples of this would be when you’re interacting with an API written in a language that may have a key that is a reserved keyword in Rust. You can add a #[serde(rename)] attribute macro like so:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>pub struct MyStruct {<br>    #[serde(rename = &quot;type&quot;)]<br>    kind: String<br>}</pre><p>This allows you to get around the issue!</p><p>You can also rename all of your fields to another casing by using the rename_all attribute:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>#[serde(rename_all = &quot;camelCase&quot;)]<br>pub struct MyStruct {<br>    my_message: String<br>}</pre><p>Now when you serialize this struct, my_message should automatically turn into myMessage! Perfect for working with APIs written in other languages or with different conventions.</p><p>If you’d prefer to not wrap fields in Option, you can also implement default values by using #[serde(default)]. This simply allows fields to be filled in with default values instead of automatically erroring out. You can also use #[serde(default = &quot;path&quot;)] to be able to point to functions for providing the automatic default. For example, this struct and function:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>pub struct MyStruct {<br>    #[serde(path = &quot;my_function&quot;)]<br>    my_message: String,<br>}</pre><pre>fn my_function() -&gt; String {<br>    &quot;Hello world!&quot;.to_string()<br>}</pre><p>serde also offers other useful attributes, like being able to deny unknown fields using #[serde(deny_unknown_fields)] on top of the struct. This allows you to make sure that the struct is exactly as-is when serializing and deserializing.</p><h3>Deserializing and Serializing enums</h3><p>Let’s examine this enum type:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>enum MyEnum {<br>    Data { id: String, data: Value },<br>    SomeOtherData { id: i32, name: String }<br>}</pre><p>Note that when converting to and from this enum, it can take two options:</p><ul><li>A String field named id and a JSON value with the key data (this can be a map, a value or anything that the Json value can hold)</li><li>An i32 field named id and a String field named name</li></ul><p>You can then match the enum variant for further processing.</p><p>When the first enum variant is written in JSON, you can see that it should correspond with this:</p><pre>{<br>    &quot;Data&quot;: {<br>        &quot;id&quot;: &quot;your_id_here&quot;,<br>        &quot;data&quot;: { .. }<br>    }<br>}</pre><p>This type of data is “externally tagged” — meaning the data is characterized by the identifier being on the outside of the JSON object. We can add inline tagging so that the identifier is on the inside of the crate — let’s have a look at what this would look like:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>#[serde(tag = &quot;type&quot;)]<br>enum MyEnum {<br>    Data { id: String, data: Value },<br>    SomeOtherData { id: i32, name: String }<br>}</pre><p>Now the JSON representation looks like this:</p><pre>{<br>    &quot;type&quot;: &quot;Data&quot;,<br>    &quot;id&quot;: &quot;your_id_here&quot;,<br>    &quot;data&quot;: { .. }<br>}</pre><p>Interested in reading more? The serde documentation has a page on tagging which you can find <a href="https://serde.rs/enum-representations.html">here.</a></p><h3>Crates that work well with Serde</h3><h3>serde_with</h3><p>serde_with is a crate that provides custom de/serialization helpers to use with serde&#39;s with annotation. Normally, you can define a module for the (de)serializer to use that follows a custom module for custom (de)serialization:</p><pre>#[derive(Deserialize, Serialize)]<br>pub struct MyStruct {<br>    #[serde(with = &quot;my_module&quot;)]<br>    my_message: String<br>}</pre><p>When using serde_with, it works by replacing the with annotation with a new one called serde_as. With this new attribute macro you can do quite a few things:</p><ul><li>De/serializing a type using Display and FromStr traits.</li><li>Support arrays larger than 32 elements.</li><li>Skip serializing empty Option types.</li><li>Deserialize a comma separated list into a Vec&lt;String&gt;.</li></ul><p>To use serde_with, you need to add it to your Cargo.toml either manually or by using the following command:</p><pre>cargo add serde_with</pre><p>Then you need to add serde_as to the type you want to use it for, like so:</p><pre>use serde_with::{serde_as, DisplayFromStr};<br><br>#[serde_as]<br>#[derive(Deserialize, Serialize)]<br>struct MyStruct {<br>    // Serialize with Display, deserialize with FromStr<br>    #[serde_as(as = &quot;DisplayFromStr&quot;)]<br>    my_number: u8,<br>}</pre><p>This struct lets you convert to/from a string but have the type itself in your Rust struct be u8! Pretty useful, right?</p><p>This crate also comes with a <a href="https://docs.rs/serde_with/3.5.0/serde_with/guide/index.html">guide</a> that you can use to fully capitalise on serde_with. Overall, a strong companion crate for serde.</p><h3>serde_bytes</h3><p>serde_bytes is a crate that allows for optimised handling of &amp;[u8] and Vec&lt;u8&gt; types - while serde is capable of dealing these types by itself, some formats can be de/serialized more efficiently. It’s quite simple to use - you just add it to your Cargo.toml and then add it via the #[serde(with = &quot;serde_bytes&quot;)] annotation like so:</p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Deserialize, Serialize)]<br>struct MyStruct {<br>    #[serde(with = &quot;serde_bytes&quot;)]<br>    byte_buf: Vec&lt;u8&gt;,<br>}</pre><p>Overall, an easy to use and simple crate that improves performance without much knowledge required.</p><h3>Finishing up</h3><p>I hope you enjoyed reading about Serde! It’s a pretty powerful Rust crate and forms the backbone of most Rust applications.</p><p>Read more:</p><ul><li>Read more about how you can get started with the Rocket web framework <a href="https://www.shuttle.rs/blog/2023/12/13/using-rocket-rust">here.</a></li><li>Read more about using JSON parsers <a href="https://www.shuttle.rs/blog/2024/01/18/parsing-json-rust">here.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc620ce4beff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>