Rust multi module microservices Part 5 - Common
Every workspace can have multiple application crates that can have some common utility functions, constants, models/structs for HTTP Request/Response, Kafka Messages, and much more. For this purpose, we are having the common crate to be used for holding common business domain contexts.
Go ahead and create the above files/folders and we will update the contents as shown below.
Cargo.toml
[package]
name = "common"
version = "0.0.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = {workspace = true}
derive_builder = { workspace = true}
strum = {workspace = true}
apache-avro = {workspace = true}
We add the derive_builder and strum crates for utilities. You can read more about them to check out their capabilities.
src/events/dto/mod.rs
use apache_avro::AvroSchema;
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Builder, Clone, Debug, AvroSchema)]
pub struct CreatedBook {
id: i32,
title: String,
isbn: String,
}
The CreatedBook struct serves as the structure for the Kafka message that we will produce in books_api and consume in books_analytics. Although we use Rust for both producing and consuming, the need for a schema registry to validate the schema might not be as crucial. However, in real-world scenarios, it is highly likely that other microservices will be written in various language-framework combinations, which justifies the need for a schema registry. This registry can prevent messages with non-conforming schemas from being produced or consumed.
src/events/constants.rs
use strum::Display;
#[derive(Display)]
pub enum Topics {
BookCreated,
}
We have created an enumeration of Topics, but feel free to change it to a String or any other data structure that better suits your needs.
src/events/mod.rs
pub mod constants;
pub mod dto;
We register the modules of the events and expose them publically.
src/lib.rs
pub mod events;
At this stage, we have completed the implementation of the common modules and are ready to create the two microservices, books_api and books_analytics, in the upcoming articles.