This page looks best with JavaScript enabled

Hexagonal in Rust

 ·  ☕ 2 min read  ·  ✍️ t1

Hexagonal architecture, also known as the Ports and Adapters pattern, is a software design approach that focuses on the separation of concerns between the business logic of a system and the technical implementation details of how that logic is exposed and consumed. In this architecture, the core business logic is isolated in the “inner hexagon” and is independent of the various ways it can be accessed, such as through a web API, a command-line interface, or a graphical user interface. This allows the business logic to be tested and maintained without being impacted by changes in the technical implementation.

To demonstrate the use of hexagonal architecture in a cloud-native microservice, let’s consider a simple example of a service that retrieves tweets from Twitter and categorizes them based on a set of predefined keywords. In this example, the business logic for categorizing tweets is isolated in the inner hexagon and is independent of the technical implementation details of how the tweets are retrieved from Twitter.

Here is a simplified version of the code in Rust to implement this service using hexagonal architecture:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Define the core business logic for categorizing tweets
trait TweetCategorizer {
    fn categorize(&self, tweet: &str) -> Option<String>;
}

struct KeywordTweetCategorizer {
    keywords: Vec<String>,
}

impl TweetCategorizer for KeywordTweetCategorizer {
    fn categorize(&self, tweet: &str) -> Option<String> {
        for keyword in &self.keywords {
            if tweet.contains(keyword) {
                return Some(keyword.clone());
            }
        }
        None
    }
}

// Define the technical implementation for retrieving tweets from Twitter
trait TwitterClient {
    fn get_tweets(&self, query: &str) -> Vec<String>;
}

struct HttpTwitterClient {
    // Implementation details go here...
}

impl TwitterClient for HttpTwitterClient {
    fn get_tweets(&self, query: &str) -> Vec<String> {
        // Retrieve tweets from Twitter using HTTP requests...
    }
}

// Define the public API for the microservice
struct TweetCategorizationService<T: TwitterClient, C: TweetCategorizer> {
    twitter_client: T,
    tweet_categorizer: C,
}
Share on

t1
WRITTEN BY
t1
Dev