<?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 Pab Est Pe on Medium]]></title>
        <description><![CDATA[Stories by Pab Est Pe on Medium]]></description>
        <link>https://medium.com/@pab.est.pe?source=rss-429a77759bd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*opSRs8oiypSu0VAl</url>
            <title>Stories by Pab Est Pe on Medium</title>
            <link>https://medium.com/@pab.est.pe?source=rss-429a77759bd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:42:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pab.est.pe/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[Rust gRPC server with postgres Bonus Part]]></title>
            <link>https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-bonus-part-cb6df91f714e?source=rss-429a77759bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb6df91f714e</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pab Est Pe]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 21:16:30 GMT</pubDate>
            <atom:updated>2024-09-15T21:16:30.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Good evening, everyone. After revisiting the code I wrote in the series (<a href="https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-iv-20a2fcaf5c8d">https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-iv-20a2fcaf5c8d</a>), I realized it could be optimized by leveraging Rust’s powerful ownership and borrowing system. Additionally, I discovered a potential issue due to the use of the unwrap() method when handling requests, which I have also addressed.</p><p>Before we start, all the code can be found in the repository <a href="https://github.com/pestebani/tonic-server/tree/v0.0.5">https://github.com/pestebani/tonic-server/tree/v0.0.5</a></p><h4>Change in Database trait</h4><p>In database trait, we will pass the reference of the object instead of the consuming it. The trait definition (and its implementation in src/database/postgres/mod.rs ) should now look as follows (please note &amp;selfinstead of self) :</p><pre>#[async_trait]<br>pub trait Database {<br>    async fn init_database(&amp;self) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt;;<br>    async fn retrieve_from_id(&amp;self, id: i64) -&gt; Result&lt;AgendaModel, DatabaseError&gt;;<br>    async fn retrieve_all(&amp;self, page: i64, items: i64) -&gt; Result&lt;(Vec&lt;AgendaModel&gt;, i64, i64), DatabaseError&gt;;<br>    async fn create_agenda(&amp;self, agenda: AgendaModel) -&gt; Result&lt;AgendaModel, DatabaseError&gt;;<br>    async fn update_agenda(&amp;self, id: i64, agenda: AgendaModel) -&gt; Result&lt;AgendaModel, DatabaseError&gt;;<br>    async fn delete_agenda(&amp;self, id: i64) -&gt; Result&lt;(), DatabaseError&gt;;<br>}</pre><p>In the original code, each method call would take ownership of the Database instance, meaning we could not use that instance again after calling a method. The updated code allows us to reuse the same Database instance across multiple method calls because we are only borrowing it temporarily. This change also makes it easier to share the Database instance across multiple threads safely using an Arc, as borrowing (&amp;self) is inherently thread-safe compared to moving ownership (self).</p><h4>Change in variable DBLayers</h4><p>The data structure responsible for handling database connections will be an enum. This means the get_db_handler function will return a concrete implementation of the Database trait, rather than a Result. Consequently, any calls to this function should be modified to avoid using the unwrap() method.</p><pre>#[derive(Debug, Clone)]<br>pub enum DBLayers {<br>    Postgres(PostgresDB),<br>}<br><br><br>impl DBLayers {<br>    pub async fn new_db_handler() -&gt; Result&lt;Self, Box&lt;dyn Error&gt;&gt; {<br>        let db_type = env::var(&quot;DATABASE_TYPE&quot;)?;<br>        match db_type.as_str() {<br>            &quot;postgres&quot; =&gt; Ok(DBLayers::Postgres(PostgresDB::new().await?)),<br>            _ =&gt; Err(Box::&lt;dyn Error&gt;::from(format!(&quot;unknown database type {db_type}&quot;))),<br>        }<br>    }<br>    <br>    pub fn get_db_handler(&amp;self) -&gt; &amp;impl Database {<br>        match self {<br>            DBLayers::Postgres(db) =&gt; db,<br>        }<br>    }<br>}</pre><h4>Change in CustomAgendaService</h4><p>The variable database of this structure will be of type Arc&lt;DBLayers&gt; instead of DBLayers . This change will allow us to pass the reference of the memory allocation instead of cloning the whole object saving time and memory.</p><pre>#[derive(Debug)]<br>pub struct CustomAgendaService {<br>    pub(crate) database: Arc&lt;DBLayers&gt;,<br>}</pre><p>On the other hand, within the implementations, we need to modify how we obtain the DBLayers object. Instead of self.database.clone(), we will now use Arc::clone(&amp;self.database). Furthermore, since the get_db_handler function does not return an Option, there is no need to handle the Result. As an illustration, the delete_agenda trait implementation should resemble the following:</p><pre>#[instrument(level = &quot;info&quot;, target = &quot;service::delete_agenda&quot;)]<br>async fn delete_agenda(<br>    &amp;self,<br>    request: Request&lt;DeleteAgendaRequest&gt;,<br>) -&gt; Result&lt;Response&lt;DeleteAgendaResponse&gt;, Status&gt; {<br>    trace_and_handle_error!({<br>        Arc::clone(&amp;self.database)<br>            .get_db_handler()<br>            .delete_agenda(request.into_inner().id)<br>            .await?;<br>        Ok::&lt;Response&lt;DeleteAgendaResponse&gt;, Status&gt;(Response::new(DeleteAgendaResponse {}))<br>    })<br>}</pre><p><strong>Benefits</strong></p><ol><li><strong>Efficiency:</strong> Arcs provide a thread-safe way to share ownership of data. Cloning an Arc is typically much cheaper than cloning the entire underlying object, especially if the object is large or complex.</li><li><strong>Thread Safety:</strong> Because our application involves multiple threads interacting with the Database, using an Arc ensures safe concurrent access. Each thread can have its own Arc pointing to the same Database, and the Arc&#39;s internal reference counting mechanism handles memory management correctly.</li></ol><h4>Change in model module</h4><p>As I mentioned in Part II, handling requests using unwrap() can be risky. If an error occurs, the thread will panic, potentially crashing the entire application. For instance, in the previous implementation, the following request could trigger such a problem:</p><pre># Test creating an agenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: Canceled<br>  Message: stream terminated by RST_STREAM with error code: CANCEL</pre><p>and the following message:</p><pre>thread &#39;tokio-runtime-worker&#39; panicked at src/service/mod.rs:87:84:<br>called `Option::unwrap()` on a `None` value</pre><p>To address this issue, we need to modify the AgendaModel::from_proto implementation as follows:</p><pre>pub fn from_proto(oa: Option&lt;Agenda&gt;) -&gt; Result&lt;Self, ModelError&gt; {<br>    match oa {<br>        Some(ap) =&gt; Ok(AgendaModel{<br>            id: ap.id,<br>            name: ap.name.clone(),<br>            email: ap.email.clone(),<br>            phone: ap.phone.clone(),<br>        }),<br>        None =&gt; Err(ModelError::EmptyInput),<br>    }<br>}</pre><p>and ModelError is defined in the new src/model/error.rs file:</p><pre>use std::error::Error;<br>use std::fmt;<br>use tonic::{Code, Status};<br><br>#[derive(Debug, Clone, PartialEq)]<br>pub enum ModelError{<br>    EmptyInput,<br>    UnknownError{error: String},<br>}<br><br>impl fmt::Display for ModelError {<br>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {<br>        match self {<br>            ModelError::EmptyInput =&gt; write!(f, &quot;missing agenda object in input&quot;),<br>            ModelError::UnknownError{error} =&gt; write!(f, &quot;internal error: {}&quot;, error),<br>        }<br>    }<br>}<br><br><br>// Implement this in order to be able to return an agenda error from any error with &#39;?&#39; operator<br>impl&lt;T&gt; From&lt;T&gt; for ModelError<br>where<br>    T: Error + &#39;static,<br>{<br>    fn from(err: T) -&gt; Self {<br>        ModelError::UnknownError{error: err.to_string()}<br>    }<br>}<br><br><br>// Implement this trait in order to be a tonic response if error<br>impl From&lt;ModelError&gt; for Status {<br>    fn from(err: ModelError) -&gt; Self {<br>        match err {<br>            ModelError::UnknownError {error} =&gt; Status::new(Code::Internal, error),<br>            ModelError::EmptyInput =&gt; Status::new(Code::InvalidArgument, err.to_string()),<br>        }<br>    }<br>}</pre><p>Note that the latest From implementation allows us to directly return a tonic Status error using the ? operator. Therefore, revisiting the service module, we need to adjust where the AgendaModel::from_proto function is called. For example, the create_agenda function should now look like this:</p><pre>#[instrument(level = &quot;info&quot;, target = &quot;service::create_agenda&quot;)]<br>async fn create_agenda(<br>    &amp;self,<br>    request: Request&lt;CreateAgendaRequest&gt;,<br>) -&gt; Result&lt;Response&lt;CreateAgendaResponse&gt;, Status&gt; {<br>    trace_and_handle_error!({<br>        let new_agenda: AgendaModel = Arc::clone(&amp;self.database)<br>            .get_db_handler()<br>            .create_agenda(AgendaModel::from_proto(request.into_inner().agenda)?)<br>            .await?;<br>    <br>        Ok::&lt;Response&lt;CreateAgendaResponse&gt;, Status&gt;(Response::new(CreateAgendaResponse {<br>            agenda: Some(new_agenda.to_proto())<br>        }))<br>    })<br>}</pre><p>Note the change from AgendaModel::from_proto(request.into_inner().agenda.unwrap()) to AgendaModel::from_proto(request.into_inner().agenda)? .</p><p>Now, if we make the same request as before, we should receive the following error (without any thread panic):</p><pre># Test creating an agenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: InvalidArgument<br>  Message: missing agenda object in input</pre><h3>Summary</h3><p>As we heve seen, it is generally best to avoid the unwrap method when handling requests, as it can lead to panics and potential crashes. However, during server initialization, unwrap might be acceptable to prevent an unhealthy application from running.</p><p>Additionally, we explored how Rust’s ownership and borrowing system enables us to create a more efficient server by allowing multiple parts of the code to reference the same database object in memory, eliminating the need to clone the entire database object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb6df91f714e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust gRPC server with postgres PART IV]]></title>
            <link>https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-iv-20a2fcaf5c8d?source=rss-429a77759bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a2fcaf5c8d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Pab Est Pe]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 14:32:08 GMT</pubDate>
            <atom:updated>2024-09-05T14:32:08.018Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the last episode of the series. In this part we will implement logging and distributed traces using OpenTelemetry.</p><p>In the complex landscape of modern software development, where applications are often distributed across multiple services and platforms, gaining insights into their behavior and performance can be a daunting task. OpenTelemetry emerges as a powerful solution to this challenge, offering a vendor-neutral and open-source framework for collecting, processing, and exporting telemetry data such as traces or logs. By providing a standardized approach to observability, OpenTelemetry empowers developers to gain a deeper understanding of their systems, troubleshoot issues more effectively, and ultimately deliver better user experiences.</p><h4>Logs and traces</h4><ul><li><strong>Logs:</strong> Logs serve as the chronicle of events within a system, capturing discrete messages or records at specific points in time. They provide valuable information about system activities, errors, warnings, and other noteworthy occurrences.</li><li><strong>Traces:</strong> Traces offer a more holistic view by tracking the end-to-end journey of a request or transaction as it traverses various components and services within a distributed system. They capture timing information, dependencies, and contextual data, enabling developers to visualize the flow of execution and pinpoint performance bottlenecks or errors.</li></ul><p>Together, logs and traces form a powerful duo in the realm of observability, providing complementary perspectives on system behavior. Logs offer detailed insights into individual events, while traces illuminate the broader context and interrelationships between those events. By leveraging both logs and traces, developers gain a comprehensive understanding of their systems, empowering them to troubleshoot issues, optimize performance, and ensure the smooth operation of their applications.</p><h3>Implementation</h3><p>For this implementation, we’ll utilize the opentelemetryand tracing crates. Please note that we’ll exclusively export Jaeger traces via OTLP and logs to Loki. If you wish to export logs and traces to a different destination, such as those offered by public cloud providers like GCP or AWS, you’ll need to implement that functionality yourself.</p><p>Please, all code is in repository <a href="https://github.com/pestebani/tonic-server/tree/v0.0.4">https://github.com/pestebani/tonic-server/tree/v0.0.4</a></p><h3>Structure of the code</h3><p>In this part, the file structure will be as follows:</p><pre>tonic-server/<br>|_ src/<br>   |_ database/<br>      |_ postgres/<br>         |_ mod.rs<br>      |_ database_object.rs<br>      |_ error.rs<br>      |_ mod.rs<br>   |_ model/<br>      |_ mod.rs<br>   |_ otel/<br>      |_ mod.rs<br>      |_ logger.rs<br>      |_ tracer.rs<br>   |_ proto/<br>      |_ agenda/<br>         |_ v1/<br>            |_ agenda.proto<br>|_ service/<br>      |_ mod.rs<br>   |_ main.rs<br>|_ build.rs<br>|_ Cargo.lock<br>|_ Cargo.toml</pre><p>Note that there are the same files as before, but with folder src/otel.</p><h4>Cargo.toml file</h4><p>We need to add the following dependencies:</p><pre>once_cell = &quot;1.19.0&quot;<br>opentelemetry = { version = &quot;0.24.0&quot;, features = [&quot;metrics&quot;, &quot;logs&quot;] }<br>opentelemetry-otlp = { version=&quot;0.17.0&quot;, features = [&quot;metrics&quot;, &quot;logs&quot;, &quot;grpc-tonic&quot;] }<br>opentelemetry_sdk = { version = &quot;*&quot;, features = [&quot;async-std&quot;, &quot;rt-tokio&quot;] }<br>opentelemetry-stdout = &quot;0.5.0&quot;<br>opentelemetry-semantic-conventions = &quot;0.16.0&quot;<br>tracing = &quot;0.1.40&quot;<br>tracing-opentelemetry = &quot;0.25.0&quot;<br>tracing-loki = &quot;0.2.5&quot;<br>tracing-subscriber = { version = &quot;0.3.18&quot; , features = [&quot;env-filter&quot;]}</pre><h3>otel module</h3><h4>tracer.rs file</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d473868d43c85d89fd027e3e91f18f/href">https://medium.com/media/57d473868d43c85d89fd027e3e91f18f/href</a></iframe><p>This tracer.rs module gives the Rust application the ability to generate and export traces that adhere to the OpenTelemetry standard. It offers flexibility in choosing between sending traces to a centralized collector (for production environments) or simply displaying them on the console (for development/testing). This last kind of tracing is invaluable for gaining insights into the inner workings of the system and troubleshooting any issues that may arise.</p><p>To select between the available options, we need to configure the OTEL_EXPORTER_TRACES environment variable. Setting it to &quot;otlp&quot; will export traces to the endpoint specified by the OTEL_EXPORTER_OTLP_TRACES_ENDPOINT environment variable.</p><h4>logger.rs file</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d106d5da687f2164f9d1232ec6239993/href">https://medium.com/media/d106d5da687f2164f9d1232ec6239993/href</a></iframe><p>The logger.rs module sets up a flexible logging mechanism for the Rust application. It offers the option to send structured logs to Loki for centralized analysis or simply print them to the console during development. The crucial addition of OpenTelemetry integration connects the logs and traces, enabling powerful observability and troubleshooting capabilities.</p><p>To choose between the different logging options, we must configure the OTEL_EXPORTER_LOGS environment variable. If it is set to &quot;loki&quot;, logs will be exported to Loki using the endpoint specified by the OTEL_EXPORTER_OTLP_LOGS_ENDPOINT environment variable.</p><p>To control the level of logging and tracing, you should set the RUST_LOG environment variable. In development environments, setting it to info or debug can be helpful for gaining detailed insights into the application&#39;s behavior. However, in production environments, it&#39;s generally recommended to set it to warn or error to reduce log volume and focus on potential issues.</p><h4>otel/mod.rs file</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98974936db55090b738e80dbd69d2d6/href">https://medium.com/media/a98974936db55090b738e80dbd69d2d6/href</a></iframe><p>This file acts as the orchestrator, bringing together the tracing and logging components. It handles the initialization process, ensuring both systems are correctly set up and interconnected. The shutdown function provides a clean way to wrap up tracing activities when the application finishes.</p><h3>Rest of the application</h3><h4>main.rs file</h4><p>We need to add here the mod otel, and initialize the otel module before starting the server, and stopping it when it receives an stop signal.</p><pre>mod otel;</pre><pre>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    let addr = &quot;[::]:50051&quot;.parse()?;<br>    let agenda_service = service::CustomAgendaService::new().await;<br>    <br>    let _ = init_tracer_and_logger()?;<br><br>    Server::builder()<br>        .add_service(AgendaServiceServer::new(agenda_service))<br>        .serve_with_shutdown(addr, async {<br>            tokio::signal::ctrl_c().await.expect(&quot;failed to install CTRL+C signal handler&quot;);<br>            stop_tracer_and_logger();<br>            time::sleep(Duration::from_secs(1)).await;<br>        })<br>        .await?;<br><br>    Ok(())<br>}</pre><h4>src/service/mod.rs</h4><p>We will create the following macro.</p><pre>macro_rules! trace_and_handle_error {<br>    // Match the block of code within the macro invocation<br>    ({ $($code:tt)* }) =&gt; {{<br>        // Get the current span for tracing<br>        let current_span = tracing::Span::current();<br><br>        // Log the entry into the function<br>        tracing::info!(&quot;Entered function in service module&quot;);<br><br>        // Execute the provided code within an async block<br>        let result = async {<br>            $($code)*<br>        }.await;<br><br>        // Match on the result to handle success and error cases<br>        match &amp;result {<br>            Ok(_) =&gt; {<br>                tracing::info!(&quot;Function executed successfully&quot;);<br>                current_span.record(&quot;success&quot;, &amp;true);<br><br>            },<br><br>            Err(err) if err.code() == Code::Internal =&gt; {<br>                tracing::error!(&quot;Error in function: {}&quot;, err.to_string());<br>                current_span.record(&quot;error&quot;, &amp;format!(&quot;{}&quot;, err.to_string()));<br>            },<br>            Err(err) =&gt; {<br>                tracing::warn!(&quot;Error in function: {}&quot;, err.to_string());<br>                current_span.record(&quot;warn&quot;, &amp;format!(&quot;{}&quot;, err.to_string()));<br>            }<br>        }<br>        result<br>    }};<br>}</pre><p>This macro will contain code blocks for each function, generating an “info” level log before entering a function and another log after its execution. It also intelligently adjusts the trace level based on the response: if it’s a controlled error, the trace is set to “warn”; for an uncontrolled error, it’s set to “error.”</p><p>Additionally, we will employ the tracing::instrument procedural macro before each function to create a corresponding span for detailed tracing. As an example, here’s how the delete_agendafunction from the AgendaServicetrait implementation would look:</p><pre>#[instrument(level = &quot;info&quot;, target = &quot;service::delete_agenda&quot;)]<br>async fn delete_agenda(<br>    &amp;self,<br>    request: Request&lt;DeleteAgendaRequest&gt;,<br>) -&gt; Result&lt;Response&lt;DeleteAgendaResponse&gt;, Status&gt; {<br>    trace_and_handle_error!({<br>        self.database<br>            .clone()<br>            .get_db_handler()<br>            .unwrap()<br>            .delete_agenda(request.into_inner().id)<br>            .await?;<br>        Ok::&lt;Response&lt;DeleteAgendaResponse&gt;, Status&gt;(Response::new(DeleteAgendaResponse {}))<br>    })<br>}</pre><h4>src/database/mod.rs</h4><p>In this module, we will create a macro that can be used by any implementation of the Database trait. This macro functions similarly to the trace_and_handle_error macro, but it specifically handles DatabaseError as an error instead of Status.</p><pre>#[macro_export]<br>macro_rules! trace_and_handle_error_database {<br>    // Match the block of code within the macro invocation<br>    ({ $($code:tt)* }) =&gt; {{<br>        // Get the current span for tracing<br>        let current_span = tracing::Span::current();<br><br>        // Log the entry into the function<br>        tracing::info!(&quot;Entered function in database module&quot;);<br><br>        // Execute the provided code within an async block<br>        let result = async {<br>            $($code)*<br>        }.await;<br><br>        // Match on the result to handle success and error cases<br>        match &amp;result {<br>            Ok(_) =&gt; {<br>                tracing::info!(&quot;Function executed successfully&quot;);<br>                current_span.record(&quot;success&quot;, &amp;true);<br><br>            },<br><br>            Err(DatabaseError::UnknownError{ error: err }) =&gt; {<br>                tracing::error!(&quot;Error in function: {}&quot;, err);<br>                current_span.record(&quot;error&quot;, &amp;format!(&quot;{}&quot;, err));<br>            },<br><br>            Err(err) =&gt; {<br>                tracing::warn!(&quot;Error in function: {}&quot;, err);<br>                current_span.record(&quot;warn&quot;, &amp;format!(&quot;{}&quot;, err));<br>            }<br>        }<br>        result<br>    }};<br>}</pre><h4>src/database/postgres/mod.rs</h4><p>Just as we did in the service module, we’ll employ the tracing::instrument procedural macro to create spans. Additionally, we will utilize the trace_and_handle_error_database macro to generate logs and, if an error occurs, adjust the span level accordingly. Here&#39;s an example of how the delete_agenda function would look:</p><pre>#[instrument(level = &quot;info&quot;)]<br>async fn delete_agenda(self, id: i64) -&gt; Result&lt;(), DatabaseError&gt; {<br>    trace_and_handle_error_database!({<br>    let query = &quot;DELETE from my_table WHERE id = $1&quot;;<br>    let deleted_elements_query: PgQueryResult = sqlx::query(query)<br>        .bind(id)<br>        .execute(&amp;self.pool)<br>        .await?;<br><br>        if deleted_elements_query.rows_affected() &lt; 1 {<br>            Err(DatabaseError::NotFoundError {id})<br>        } else {<br>            Ok(())<br>        }<br>    })<br>}</pre><h4>docker-compose.yaml</h4><p>To run the server with the implemented tracing and logging features, we need to include the following services in our setup:</p><ul><li><strong>Loki:</strong> For aggregating and storing logs.</li><li><strong>Jaeger:</strong> For collecting and visualizing traces.</li><li><strong>Grafana:</strong> For creating dashboards and visualizing both logs and traces.</li></ul><p>We will also need to set the environment variables mentioned in the logging and tracing code:</p><ul><li>RUST_LOG: info</li><li>OTEL_EXPORTER_LOGS: loki</li><li>OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: “http://loki:3100&quot;</li><li>OTEL_EXPORTER_TRACES: otlp</li><li>OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: “http://otel-collector:4317&quot;</li></ul><p>With these in place, the configuration file should look similar to this:</p><pre>services:<br>  postgres:<br>    image: postgres:16.3-alpine3.20<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_DB: postgres<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>    restart: always<br>    ports:<br>      - &quot;5432:5432&quot;<br>  otel-collector:<br>    image: jaegertracing/all-in-one:1.58.1<br>    ports:<br>      - &quot;4317:4317&quot;<br>      - &quot;16686:16686&quot;<br>  loki:<br>    image: grafana/loki:latest<br>    ports:<br>      - &quot;3100:3100&quot;<br>  grafana:<br>    image: grafana/grafana:latest<br>    ports:<br>      - &quot;3000:3000&quot;<br>  tonic-server:<br>    build:<br>        context: .<br>    ports:<br>        - &quot;50051:50051/tcp&quot;<br>    depends_on:<br>      - postgres<br>      - otel-collector<br>      - loki<br>    environment:<br>      DATABASE_TYPE: postgres<br>      DATABASE_URL: &quot;postgres://postgres:postgres@postgres:5432/postgres&quot;<br>      RUST_LOG: info<br>      OTEL_EXPORTER_LOGS: loki<br>      OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: &quot;http://loki:3100&quot;<br>      OTEL_EXPORTER_TRACES: otlp<br>      OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: &quot;http://otel-collector:4317&quot;<br><br>volumes:<br>  postgres_data:<br></pre><h3>Running the server</h3><p>As we did in the previous section, we will use the command docker compose up to run the code. Keep in mind that this might take a while because it needs to build the new image. If it starts up quickly, you might need to delete the image built in the last part because the latest changes are not incorporated.</p><pre># Test connection works<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto [::1]:50051 agenda.v1.AgendaService/Ping<br><br>### OUTOUT<br>{<br>  &quot;response&quot;: &quot;pong&quot;<br>}</pre><p>Now let&#39;s take a look on jaeger user interface in http://localhost:16686 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_X50ChjnctXGTDsY1A16w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48MXGSwyowNDq5pxyMLthw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbewU7IG70Hp-vh1mMD6uA.png" /></figure><p>We can see that ping implementation took around 39 micro-seconds to be completed.</p><p>Let&#39;s try another endpoint.</p><pre>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:1}&#39; [::1]:50051 agenda.v1.AgendaService/GetAgenda</pre><p>Now, if we analyze it in Jaeger, we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnGa6rkgk2XgGBFzE7sa6A.png" /></figure><p>We can see that it has 2 spans embedded. We can also see that the request took 6.85 ms, around 200 times more. On the other hand, looking at the spans, we can see that almost all the time were lost in the database function.</p><h4>See the logs</h4><p>For retrieving the logs, we need to go to grafana http://localhost:3000and configure loki as a datasource. NOTE: the user is admin and the password is also admin .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKAXJxUNO45FkUtXg3Ei9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uc3iELD-MVkMEl_aO2lRFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVTi-2ghrY6g4jYJV_8MWA.png" /></figure><p>In the URL type http://loki:3100 , and then in the botton press Save &amp; test . Finally, in the Exploresection in the menu, we can see the logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrQ8mjhdKW4Az5xsKOYLDg.png" /></figure><h3>Conclussions</h3><p>Thank you for reading! Throughout this journey, we have successfully built a gRPC server using Rust and Postgres, complete with instrumentation for observability.</p><p>If you have the time, I would greatly appreciate any feedback you could provide on these four articles. Please feel free to ask if you have any questions, and I’ll do my best to respond promptly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a2fcaf5c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust gRPC server with postgres PART III]]></title>
            <link>https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-iii-5d67dbaa7496?source=rss-429a77759bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d67dbaa7496</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Pab Est Pe]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 14:31:36 GMT</pubDate>
            <atom:updated>2024-09-05T14:31:36.020Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part of the series, we will complete the postgres module, which will enable us to run all the gRPC services without errors. In order to run the code locally, we use docker-compose.</p><p>As a reminder, all code of this section is available on <a href="https://github.com/pestebani/tonic-server/tree/v0.0.3">https://github.com/pestebani/tonic-server/tree/v0.0.3</a></p><h3>Structure of the code</h3><p>The structure will be the same as before, but adding the filesDockerfile and docker-compose.yaml in the root directory of the project.</p><h3>Third part of the code</h3><h4>Cargo.toml</h4><p>We need to add the libraries sqlx and sqlx-postgres to the dependencies to handle the connection with a postgresql database. We will also need to add the library openssl in order to be able to build the docker (only if running the docker with a scratch image).</p><pre>openssl = { version = &quot;0.10.40&quot;, features = [&quot;vendored&quot;] }<br>sqlx = { version = &quot;0.8.0&quot;, features = [&quot;postgres&quot;, &quot;runtime-tokio-native-tls&quot;] }<br>sqlx-postgres = &quot;0.8.0&quot;</pre><h4>main.rs file</h4><p>Because the image will be running inside a docker container, we need to change the addr value to [::]:50051 to be able to receive requests outside the docker.</p><pre>let addr = &quot;[::]:50051&quot;.parse()?;</pre><h4>postgres module</h4><p>As said in last part, this module provides the concrete implementation for interacting with a PostgreSQL database, translating the abstract Database trait into actual SQL queries and data handling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bff29b436e20f9713ea46a64bff852b/href">https://medium.com/media/2bff29b436e20f9713ea46a64bff852b/href</a></iframe><p>In a real-world scenario, initializing the database should be done in a separate process from server initialization to reduce container startup time. Additionally, a dedicated table should be used to manage database versioning.</p><p><strong>NOTE</strong>: While we could have implemented the From trait instead of creating the convert_postgres_result_to_database_result function, doing so might have resulted in less clear error messages for end-users.</p><h4>Dockerfile</h4><p>A Dockerfile is a script that defines the steps to build a Docker image, which is a self-contained package for running applications in containers. This particular Dockerfile creates a minimal Docker image containing the compiled Rust gRPC server, optimized for deployment and execution in a containerized environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e925e300ce2027cec419fe388457a1/href">https://medium.com/media/59e925e300ce2027cec419fe388457a1/href</a></iframe><h4>docker-compose.yaml</h4><p>The last, but not least, it is time to run the server, but we need a Postgresql database somewhere. For this purpose, the following docker-compose.yaml file orchestrates the deployment of the Rust gRPC server along with a PostgreSQL database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/027f5c121588d249bae113f2e15c3b07/href">https://medium.com/media/027f5c121588d249bae113f2e15c3b07/href</a></iframe><h3>Testing the server</h3><p>Once this file is created, if we go to the project directory and use the command</p><pre>docker compose up</pre><p>The first time the server starts, it might take a few minutes to build the gRPC server. So, let&#39;s make some requests:</p><pre># Test connection works<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto [::1]:50051 agenda.v1.AgendaService/Ping<br><br>### OUTOUT<br>{<br>  &quot;response&quot;: &quot;pong&quot;<br>}</pre><pre># Test creating an agenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;agenda&quot;:{&quot;name&quot;:&quot;name_1&quot;,&quot;email&quot;:&quot;some.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 123456789&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>{<br>  &quot;agenda&quot;: {<br>    &quot;id&quot;: &quot;1&quot;,<br>    &quot;name&quot;: &quot;name_1&quot;,<br>    &quot;email&quot;: &quot;some.email@gmail.com&quot;,<br>    &quot;phone&quot;: &quot;+34 123456789&quot;<br>  }<br>}</pre><pre># Test getting an agenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:1}&#39; [::1]:50051 agenda.v1.AgendaService/GetAgenda<br><br>### OUTOUT<br>{<br>  &quot;agenda&quot;: {<br>    &quot;id&quot;: &quot;1&quot;,<br>    &quot;name&quot;: &quot;name_1&quot;,<br>    &quot;email&quot;: &quot;some.email@gmail.com&quot;,<br>    &quot;phone&quot;: &quot;+34 123456789&quot;<br>  }<br>}</pre><pre># Test creating another agenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;agenda&quot;:{&quot;name&quot;:&quot;name_2&quot;,&quot;email&quot;:&quot;another.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 987654321&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>{<br>  &quot;agenda&quot;: {<br>    &quot;id&quot;: &quot;2&quot;,<br>    &quot;name&quot;: &quot;name_2&quot;,<br>    &quot;email&quot;: &quot;another.email@gmail.com&quot;,<br>    &quot;phone&quot;: &quot;+34 987654321&quot;<br>  }<br>}</pre><pre># Update to an existent name. Should be an error<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:1,&quot;agenda&quot;:{&quot;name&quot;:&quot;name_2&quot;,&quot;email&quot;:&quot;another.new.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 123456789&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/UpdateAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: AlreadyExists<br>  Message: It already exists an entry with name name_2</pre><pre># Update to non-existent name<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:1,&quot;agenda&quot;:{&quot;name&quot;:&quot;new_name_1&quot;,&quot;email&quot;:&quot;another.new.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 123456789&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/UpdateAgenda<br><br>### OUTOUT<br>{<br>  &quot;agenda&quot;: {<br>    &quot;id&quot;: &quot;1&quot;,<br>    &quot;name&quot;: &quot;new_name_1&quot;,<br>    &quot;email&quot;: &quot;another.new.email@gmail.com&quot;,<br>    &quot;phone&quot;: &quot;+34 123456789&quot;<br>  }<br>}</pre><pre># Create an agenda with an existent name. Should be an error<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;agenda&quot;:{&quot;name&quot;:&quot;new_name_1&quot;,&quot;email&quot;:&quot;another.new.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 123456789&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: AlreadyExists<br>  Message: It already exists an entry with name new_name_1</pre><pre># Test creating an agenda like the first one<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;agenda&quot;:{&quot;name&quot;:&quot;name_1&quot;,&quot;email&quot;:&quot;some.email@gmail.com&quot;,&quot;phone&quot;:&quot;+34 123456789&quot;}}&#39; [::1]:50051 agenda.v1.AgendaService/CreateAgenda<br><br>### OUTOUT<br>{<br>  &quot;agenda&quot;: {<br>    &quot;id&quot;: &quot;4&quot;,<br>    &quot;name&quot;: &quot;name_1&quot;,<br>    &quot;email&quot;: &quot;some.email@gmail.com&quot;,<br>    &quot;phone&quot;: &quot;+34 123456789&quot;<br>  }<br>}</pre><pre># Test GetAgendas<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;page&quot;:1,&quot;items&quot;:2}&#39; [::1]:50051 agenda.v1.AgendaService/GetAgendas<br><br>### OUTOUT<br>{<br>  &quot;agendas&quot;: [<br>    {<br>      &quot;id&quot;: &quot;1&quot;,<br>      &quot;name&quot;: &quot;new_name_1&quot;,<br>      &quot;email&quot;: &quot;another.new.email@gmail.com&quot;,<br>      &quot;phone&quot;: &quot;+34 123456789&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;2&quot;,<br>      &quot;name&quot;: &quot;name_2&quot;,<br>      &quot;email&quot;: &quot;another.email@gmail.com&quot;,<br>      &quot;phone&quot;: &quot;+34 987654321&quot;<br>    }<br>  ],<br>  &quot;total&quot;: &quot;3&quot;,<br>  &quot;nextPage&quot;: &quot;2&quot;<br>}</pre><pre># Test DeleteAgenda<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:4}&#39; [::1]:50051 agenda.v1.AgendaService/DeleteAgenda<br><br>### OUTOUT<br>{}</pre><pre># Test DeleteAgenda to the same id. Should be an error<br>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto -d &#39;{&quot;id&quot;:4}&#39; [::1]:50051 agenda.v1.AgendaService/DeleteAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: NotFound<br>  Message: the element with id 4 does not exists</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d67dbaa7496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust gRPC server with postgres PART II]]></title>
            <link>https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-ii-44c03ce9fc31?source=rss-429a77759bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c03ce9fc31</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Pab Est Pe]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 14:31:10 GMT</pubDate>
            <atom:updated>2024-09-05T14:31:10.045Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part of the series, we will create the database module for handling with database operations, but postgres implementation will be done in the next part.</p><p>We will also cretate a model module that will convert the protocol buffers structures into some custom structures to make it easier to handle information.</p><p>Before getting our hands on, let me remind you that all code of this section is available on <a href="https://github.com/pestebani/tonic-server/tree/v0.0.2">https://github.com/pestebani/tonic-server/tree/v0.0.2</a></p><h3>Structure of the code</h3><p>In this second part, the file structure will be as follows:</p><pre>tonic-server/<br>|_ src/<br>   |_ database/<br>      |_ postgres/<br>         |_ mod.rs<br>      |_ database_object.rs<br>      |_ error.rs<br>      |_ mod.rs<br>   |_ model/<br>      |_ mod.rs<br>   |_ proto/<br>      |_ agenda/<br>         |_ v1/<br>            |_ agenda.proto<br>|_ service/<br>      |_ mod.rs<br>   |_ main.rs<br>|_ build.rs<br>|_ Cargo.lock<br>|_ Cargo.toml</pre><p>Note that there are the same files as before, but with folders src/database and src/model .</p><h3>Second part of the code</h3><h4>Model module</h4><p>The src/model/mod.rs module will provide a bridge between the internal data representation (AgendaModel) and the external representation used for gRPC communication (Agenda). This separation allows to keep the application logic decoupled from the specifics of the gRPC protocol, making the code more flexible and maintainable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f66892835c8aaa86d65cef8071db3dfc/href">https://medium.com/media/f66892835c8aaa86d65cef8071db3dfc/href</a></iframe><h4>Database module</h4><p>This module will provide all the necessary functions to handle the connections between the database and the server.</p><h4>Error file</h4><p>The file src/database/error.rs defines a custom error type, DatabaseError, specifically tailored to handle potential errors that may arise when interacting with the database. It also provides mechanisms to convert these errors into user-friendly messages and map them to appropriate gRPC status codes for communication with clients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9e864df2fb6591a86dda32381c593ff/href">https://medium.com/media/a9e864df2fb6591a86dda32381c593ff/href</a></iframe><h4>mod.rs file</h4><p>The src/database/mod.rs file establishes a blueprint for interacting with any database. Any specific database implementation, such as the one inpostgres module, will need to adhere to this trait by providing concrete implementations for these methods. This abstraction allows switching between different database backends without affecting the rest of the application code, promoting modularity and flexibility.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/058e5c55d7ddd05dbf4a1dee0ef95e97/href">https://medium.com/media/058e5c55d7ddd05dbf4a1dee0ef95e97/href</a></iframe><h4>postgres module</h4><p>The src/database/postgres/mod.rs file provides a skeletal implementation of a PostgreSQL database interface for the application. While the core structure is in place, the actual database interaction logic is missing because it will be implemented in the next part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc4746b11a92d273375baec53017eb33/href">https://medium.com/media/fc4746b11a92d273375baec53017eb33/href</a></iframe><h4>Database Object</h4><p>The src/database/database_object.rs file is responsible for managing database connections in the Rust project based on an environment variable (DATABASE_TYPE). It defines a struct DBLayers which can potentially hold different database implementations (only postgres is supported).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76874161e3bc60b69ff84e4986d5f940/href">https://medium.com/media/76874161e3bc60b69ff84e4986d5f940/href</a></iframe><h4>main.rs file</h4><p>In the main file, we need to add the new modules created:</p><pre>mod model;<br>mod database;</pre><h4>Service module</h4><p>Now we are going to implement the service module. In the last part we left it unimplemented because we did not developed the database module yet, so now it is time to implement it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a97e695f64d33a8786ce57976064d7/href">https://medium.com/media/35a97e695f64d33a8786ce57976064d7/href</a></iframe><p><strong>Note:</strong> In a real-world scenario, using the unwrap function when decoding request parameters, such as message.agenda.unwrap(), can be risky. It&#39;s generally safer to use unwrap_or_default or, even better, raise an InvalidArgument error if the parameter is missing. This helps prevent potential panics and provides more informative feedback to the client.</p><h3>Testing the server</h3><p>To run the server, we must set the environment variable DATABASE_TYPE to postgres .</p><pre>export DATABASE_TYPE=postgres<br>cargo run</pre><p>Similar to last part, only the ping service will return a successful response at this point, as we haven’t yet implemented any database functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c03ce9fc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust gRPC server with postgres PART I]]></title>
            <link>https://medium.com/@pab.est.pe/rust-grpc-server-with-postgres-part-i-550d999c2c5f?source=rss-429a77759bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/550d999c2c5f</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pab Est Pe]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 14:30:38 GMT</pubDate>
            <atom:updated>2024-09-05T14:30:38.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! I am excited to share my first Medium article with you all. In this series, I’ll be walking you through a gRPC server demo that I built using Rust and Postgres as Database. All the code for this project can be found in my GitHub repository: <a href="https://github.com/pestebani/tonic-server/tree/master">https://github.com/pestebani/tonic-server/tree/master</a>.</p><h4>A bit about me</h4><p>I am a backend developer with around 6 years of experience. I am starting to write on Medium as a way to solidify my own learning and hopefully help others along the way.</p><p>This project is a bit extensive, so I will be breaking it down into several episodes to make it easier to digest. I hope you find it useful!</p><h3>A Brief Introduction to Rust and gRPC</h3><p>Rust is a modern systems programming language that focuses on safety, concurrency, and performance. Its ownership system and strict compiler guarantee the absence of common errors like null pointers and race conditions, making it an ideal choice for building robust and reliable software.</p><p>On the other hand, gRPC (gRPC Remote Procedure Calls) is a high-performance framework for building web services and APIs. It uses Protocol Buffers as an interface definition language (IDL) to describe the services and messages they exchange, enabling efficient and type-safe communication between different platforms and programming languages.</p><h3><strong>Advantages of Rust and gRPC for Building Web Services</strong></h3><p>The combination of Rust and gRPC offers several advantages for web service development:</p><ul><li><strong>High Performance:</strong> Rust, with its focus on efficiency and lack of garbage collection, allows you to build web services that respond quickly and consume few resources. gRPC, on the other hand, uses HTTP/2 and the binary serialization of Protocol Buffers to optimize communication between the client and server.</li><li><strong>Safety and Reliability:</strong> Rust’s type system and its strict compiler help prevent common errors at compile time, reducing the likelihood of failures in production. gRPC, by using Protocol Buffers, provides an additional layer of data validation, ensuring that the messages exchanged are correct and complete.</li><li><strong>Concurrency:</strong> Rust offers native support for concurrency, making it easy to build web services that can handle multiple requests simultaneously without compromising safety or performance. gRPC, in turn, is designed to work efficiently in concurrent environments.</li><li><strong>Cross-platform Support:</strong> Both Rust and gRPC are compatible with a wide variety of platforms and operating systems, allowing you to build web services that can be deployed in different environments.</li><li><strong>Strong Typing:</strong> The use of Protocol Buffers in gRPC provides strong typing for messages exchanged between the client and server, which facilitates the detection of errors during development and improves code maintainability.</li></ul><p>In summary, Rust and gRPC complement each other to provide a solid and efficient foundation for building modern, high-performance web services.</p><h3>Prerequisites</h3><p>Before diving into the code, let’s make sure everything is set up.</p><ul><li><strong>My setup:</strong> I’m using Ubuntu as operating system and RustRover as IDE.</li><li><strong>Package Installation:</strong> A few packages will need to be installed on Ubuntu. In order to install them, open a terminal and run the following commands.</li></ul><pre># Install Rust<br>curl --proto &#39;=https&#39; --tlsv1.2 -sSf https://sh.rustup.rs | sh<br><br># Install Protocol Buffers compiler<br>sudo apt install protobuf-compiler<br><br># Install build tools<br>sudo apt install build-essential<br><br># Install OpenSSL development libraries<br>sudo apt install libssl-dev</pre><h3>Structure of the code</h3><p>In this first part, this will be the folder and files structure. In case of getting lost, please, refer to <a href="https://github.com/pestebani/tonic-server/tree/v0.0.1">https://github.com/pestebani/tonic-server/tree/v0.0.1</a>:</p><pre>tonic-server/<br>|_ src/<br>   |_ proto/<br>      |_ agenda/<br>         |_ v1/<br>            |_ agenda.proto<br><br>   |_ service/<br>      |_ mod.rs<br><br>   |_ main.rs<br><br>|_ build.rs<br><br>|_ Cargo.lock<br><br>|_ Cargo.toml</pre><h3>First part of the code</h3><p>Once the external dependencies are installed, it is time to start programming the application. In case of getting lost in the code, you can go to my github, and check how the code should look like in this first part.</p><p>The first thing we must do is create a Rust project using cargo with the command cargo new tonic-server.</p><h4>Proto file</h4><p>A .proto file (short for &quot;protocol buffer&quot;) is a text file that defines the structure of messages and services used for communication in gRPC. It acts as a contract between the client and server, specifying the data types and operations that they can exchange. The protoc compiler then uses this .proto file to generate code in various programming languages, which handles the serialization and deserialization of messages, as well as the implementation of the gRPC client and server.</p><p>The file src/proto/agenda/v1/agenda.proto must be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/988b45b4e6d145d771a2a7ce312de5a2/href">https://medium.com/media/988b45b4e6d145d771a2a7ce312de5a2/href</a></iframe><p>This file defines an AgendaService with several RPC methods for managing an agenda. It includes operations for creating, retrieving, updating, and deleting agenda entries, as well as a Ping method for basic health checks. The Agenda message itself is straightforward, containing fields for an ID, name, email, and phone number. The other messages in the file are request and response types for the various RPC methods, carrying the necessary data for each operation.</p><h4>Build.rs file</h4><p>The build.rs file automates the process of generating Rust code from the agenda.proto file whenever there is build the Rust project, ensuring that the Rust code stays in sync with your Protocol Buffer definitions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11c892131eebb5280b5729b272912251/href">https://medium.com/media/11c892131eebb5280b5729b272912251/href</a></iframe><h4>Cargo.toml file</h4><p>The Cargo.toml file serves as the heart of the Rust project, acting as its configuration and manifest file. In this case, the Cargo.tomlfile should be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b06c70f43e31a565627ae2258f72fa4/href">https://medium.com/media/2b06c70f43e31a565627ae2258f72fa4/href</a></iframe><p>Once those files are created, we can run the command cargo build in order to create the rust compiled files. We can take a look those generated files using the command find -iname agenda.v1.rs and opening the file.</p><h4>Service module</h4><p>The src/service/mod.rs module is where the behavior of the gRPC service will be defined, handling incoming requests, processing data, and sending responses back to the client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f51bf044f69e17ee0addb0d22a6aeffa/href">https://medium.com/media/f51bf044f69e17ee0addb0d22a6aeffa/href</a></iframe><p>At this point, the Ping method is the only one implemented, whereas the other methods return an Unimplemented error message.</p><h4>main.rs file</h4><p>The main.rs file serves as the entry point for the Rust application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d8f64326a71654b034365d8b3ed8e30/href">https://medium.com/media/4d8f64326a71654b034365d8b3ed8e30/href</a></iframe><p>This file uses the service created before, and registers it as the handler for the AgendaServiceServer service.</p><h3>Testing the server</h3><p>In order to test the server, I use grpcurl , a cli tool. The binary file can be found at <a href="https://github.com/fullstorydev/grpcurl/releases">https://github.com/fullstorydev/grpcurl/releases</a>.</p><p>For testing the Pingservice (the only one that is implemented), I write in a terminal the following command:</p><pre>grpcurl -plaintext -proto src/proto/agenda/v1/agenda.proto [::1]:50051 agenda.v1.AgendaService/Ping<br><br>### OUTOUT<br>{<br>  &quot;response&quot;: &quot;pong&quot;<br>}</pre><p>On the other hand, if we try to do the same with an unimplemented method, such as DeleteAgenda, I receive an error:</p><pre>grpcurl -plaintext  -proto src/proto/agenda/v1/agenda.proto  -d &#39;{&quot;id&quot;: 123}&#39;  [::1]:50051 agenda.v1.AgendaService/DeleteAgenda<br><br>### OUTOUT<br>ERROR:<br>  Code: Unimplemented<br>  Message: Not yet implemented</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550d999c2c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>