<?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 Rupert Carr on Medium]]></title>
        <description><![CDATA[Stories by Rupert Carr on Medium]]></description>
        <link>https://medium.com/@rupertcarr?source=rss-21a2a12841d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CZRFG0T1vWSJ-WpGioKKsA.jpeg</url>
            <title>Stories by Rupert Carr on Medium</title>
            <link>https://medium.com/@rupertcarr?source=rss-21a2a12841d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:29:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rupertcarr/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[Implementing a HashMap in Rust]]></title>
            <link>https://medium.com/better-programming/implementing-a-hashmap-in-rust-35d055b5ac2b?source=rss-21a2a12841d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d055b5ac2b</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Rupert Carr]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 16:51:13 GMT</pubDate>
            <atom:updated>2023-01-13T05:16:36.123Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand the data structure through diagrams</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*We_3kT_zWskbX3Uw" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we’re going to help you build your very own HashMap in Rust. We’ll be explaining each step along the way, so don’t worry if you’re new to the language. However, some basic knowledge of Rust is expected for this tutorial — we won’t be covering concepts like mutable references or Rust syntax in detail.</p><p>If you want to skip past the tutorial and step-by-step explanations, feel free to jump straight to the <a href="https://github.com/rupert648/hashmap-rs">project on GitHub</a>. This project also includes some unit tests which, for brevity’s sake, I have skipped past adding in this tutorial.</p><p>Before we dive in, best to discuss our understanding of what a hashmap is.</p><h3>Explaining Hashmaps</h3><p>Let’s begin with arrays, and why they’re great. An array is a collection of data stored in sequential order.</p><p>Each data element in the array is assigned a numerical index, which can be used to access and retrieve the element.</p><p>For example, if we want to retrieve a specific piece of data from an array and we know its index, we can easily use that index to access the element at that position in the array.</p><p>The array provides a starting point or “pointer” for the series of data, and the index tells us how far to move from that starting point to access the desired element.</p><figure><img alt="An image visually showing how an array is accessed" src="https://cdn-images-1.medium.com/max/1024/1*Wai1V1kUJEQb85xHH1Wrpg.png" /></figure><p>This is useful because by knowing the index of a value we can immediately (minus some time taken to perform the addition and multiplication) jump to the in-memory location of an object.</p><p>One limitation of using arrays to store data is that we must know the index of the element to access it.</p><p>This can be inconvenient if we only know the value of the element itself or if we want to use a different type of information, such as a key, to access the element.</p><p>In these cases, a hashmap can be a more suitable data structure. A hashmap is a collection of data that is stored and accessed using keys rather than indices. This allows us to retrieve elements based on their associated key rather than their position in the collection.</p><p>For example, we could use a person’s name as a key to access their phone number in a hashmap. Hashmaps offer more flexibility and power when it comes to storing and accessing data compared to arrays.</p><p>So how does this mythical thing work?</p><p>At their underlying structure, a hashmap is, in essence, an array. However, we are now changing the method of accessing that array. This is where a hash function comes in. A hash function takes a key as input and returns some integer which we can use as an index<strong><em> </em></strong>into that underlying array.</p><p>A simple hash function for converting a string into an integer may look as follows in rust.</p><pre>fn simple_hash(string: &amp;str) -&gt; u32 {<br>    let mut total = 0;<br>    for c in string.chars() {<br>        total += c as u32;<br>    }<br>    total<br>}</pre><p>Once we have the integer value returned by the hash function, we can use the modulus operator to reduce it to a value within the bounds of the array. For example:</p><pre>let index = simple_hash(&quot;hello&quot;) % array_size;</pre><p>This would give us an index within the bounds of the array, allowing us to access the element at that index using the key “hello”.</p><p>A “perfect” or “ideal” hash function would have the following properties:</p><ul><li>It should be deterministic, meaning that it always produces the same output for a given input.</li><li>It should distribute keys uniformly across the range of possible output values so that keys are evenly distributed among the indices in the underlying array.</li><li>It should produce a unique output value for every possible key so that there are no collisions.</li><li>It should be fast to compute so that it does not significantly impact the performance of the hashmap.</li><li>It should be resistant to collision attacks, meaning that it should be difficult for an attacker to craft keys that will produce collisions.</li></ul><p>Keep in mind that it is generally impossible to achieve all of these properties at the same time, especially when dealing with large sets of keys. Therefore, most hash functions aim to balance these properties and trade off some degree of performance or security to achieve a reasonable level of effectiveness.</p><h4>Collisions</h4><p>the truth is, collisions are inevitable when working with hashmaps. Either the hash function produces the same index for two values, or the underlying array is smaller than the number of values it holds. Either way at some point two or more keys may be pointing at the same location in memory, and we want to avoid any unwritten data.</p><p>A common solution to this, and the solution we will be using, is to create a linked list at each index in the array when a collision occurs. Then, when searching for a key/value, we traverse this linked list until we find our key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*p_mJtE1kCRxmcriNDfZQYg.png" /></figure><h3>Implementing the HashMap</h3><p>For our tutorial, we are going to be implementing the four most basic operations of a hashmap.</p><ul><li>HashMap&lt;T, V&gt;.get(key: T)</li><li>HashMap&lt;T, V&gt;.push(key: T, value: V)</li><li>HashMap&lt;T, V&gt;.delete(key: T)</li><li>HashMap&lt;T, V&gt;.clear()</li></ul><p>Note that we can see type annotations here, which allows our implementation to be fully generic and accept any type (with some caveats) for our key and value pair.</p><p>First, initialise a new cargo project, using the --lib flag.</p><pre>cargo init --lib</pre><p>Then, remove the contents of src/lib.rs , and replace it with the following</p><pre>const DEFAULT_MAX_SIZE: u64 = 256;<br><br>pub struct HashMap&lt;T, V&gt; {<br>    curr_size: usize,<br>    arr: [Option&lt;KeyValue&lt;T, V&gt;&gt;; DEFAULT_MAX_SIZE as usize],<br>}<br><br>pub struct KeyValue&lt;T, V&gt; {<br>    key: T,<br>    value: V,<br>    next: Option&lt;Box&lt;KeyValue&lt;T, V&gt;&gt;&gt;,<br>}</pre><p>Here we have declared our two structs for the hashmap.</p><ul><li>The HashMap itself, which maintains a current size, and its underlying array of key/value pairs.</li><li>A KeyValue pair struct, which stores the key and values for the hashmap.</li></ul><p>We set our default max size of the underlying array to be 256.</p><p>Note that the hashmap stores an array of Option&lt;KeyValue&lt;T,V&gt;&gt; . We can use this to check if an element in the array has been initialised or not.</p><p>The KeyValue also has a field next which stores Option&lt;Box&lt;KeyValue&lt;T,V&gt;&gt;&gt; . This refers to an optional next KeyValue in a linked list, in the case of collisions. The Box is a pointer type for heap allocation — allowing us to store generic variables types without knowing their size at compile time.</p><p>Next, we define our four primary public functions.</p><pre>impl&lt;T, V&gt; HashMap&lt;T, V&gt; {<br>    pub fn put(&amp;mut self, key: T, val: V) -&gt; Option&lt;V&gt; {<br>        todo!()<br>    }<br>    pub fn get(&amp;self, key: T) -&gt; Option&lt;V&gt; {<br>        todo!()<br>    }<br>    pub fn remove(&amp;self, key: T) -&gt; Option&lt;V&gt; {<br>        todo!()<br>    }<br>    pub fn clear(&amp;mut self) {<br>        todo!()<br>    }<br>}</pre><p>The implementation of each of these is designed to have the same functionality as the official rust hashmap implementation:</p><ul><li>put inserts a key-value pair into the hashmap. Returns None if the value didn’t exist, or returns the old value if the key was present.</li><li>get gets the value for a given key. Returns the value if it exists, or None otherwise</li><li>remove removes the key-value pair from the map for a given key. Returns the value if that key existed, None otherwise.</li><li>clear clears the hashmap.</li></ul><h4>Implementing Put</h4><p>We’ll start with put since we need this working to check if anything else works!</p><p>We’ll start by first hashing the given key, and calculating a position in the array to insert the value.</p><pre>pub fn put(&amp;mut self, key: T, val: V) -&gt; Option&lt;V&gt; {<br>    let hash_val: u64 = hash_key(key.clone());<br>    let position = hash_val % DEFAULT_MAX_SIZE;<br><br>    None<br>}</pre><p>Then let&#39;s define a hash function — define this <strong><em>outside</em></strong> of your struct implementation</p><pre>fn hash_key&lt;T: Hash&gt;(key: T) -&gt; u64 {<br>    let mut hasher = DefaultHasher::new();<br>    key.hash(&amp;mut hasher);<br>    let hash_val = hasher.finish();<br>    hash_val<br>}</pre><p>Add the following two imports to the top of the file to make your compiler happier, although it will still be throwing up some errors.</p><pre>use std::collections::hash_map::DefaultHasher;<br>use std::hash::{Hash, Hasher};</pre><p>Note, I have decided to simply use the DefaultHasher given to us by rust to hash my keys.</p><p>Your will still be complaining, this is because your type, T does not implement some required traits. We can fix this by adding the following to our implementation signature</p><pre>impl&lt;T: Clone + Hash, V&gt; HashMap&lt;T, V&gt; {</pre><p>This requires our type T to have the clone and hash traits.</p><p>Great — we have successfully hashed our generic key’s value, giving us a valid index into our array. Next, lets use it.</p><pre>pub fn put(&amp;mut self, key: T, val: V) -&gt; Option&lt;V&gt; {<br>    let hash_val: u64 = hash_key(key.clone());<br><br>    let position = hash_val % DEFAULT_MAX_SIZE;<br><br>    match &amp;self.arr[position as usize] {<br>        Some(_) =&gt; self.update_or_link_new_val(key, val, position as usize),<br>        None =&gt; {<br>            self.insert_new_value(key, val, position as usize);<br>            None<br>        }<br>    }<br>}</pre><p>We now inspect the position in the array, using the match clause to see if there is an existing KeyValue in that index. If there isn’t any value there, we insert a new value and return None .</p><p>First, we need a way of creating a new value, lets do that by adding the implementation for KeyValue</p><pre>impl&lt;T, V&gt; KeyValue&lt;T, V&gt; {<br>    pub fn new(key: T, value: V) -&gt; KeyValue&lt;T, V&gt; {<br>        KeyValue {<br>            key,<br>            value,<br>            next: None,<br>        }<br>    }<br>}</pre><p>Now, let&#39;s add insert_new_value to our HashMap implementation</p><pre>fn insert_new_value(&amp;mut self, key: T, val: V, position: usize) {<br>    let new_entry = KeyValue::new(key, val);<br><br>    self.arr[position] = Some(new_entry);<br>    self.curr_size += 1;<br>}</pre><p>Here we simply create a new KeyValue , put it into the array, and increment the array&#39;s size.</p><p>Now we get back to our original match case — what do we do if a value is already present at our index? There are two cases we must handle for the found KeyValue :</p><ul><li>If the key of that KeyValue matches ours, we update its value and return the old value.</li><li>If not, we traverse the linked list until we either find a KeyValue with a matching key, or we insert our new KeyValue pair onto the end of the linked list.</li></ul><p>Let&#39;s look at the implementation of update_or_link_new_val</p><pre>fn update_or_link_new_val(&amp;mut self, key: T, val: V, position: usize) -&gt; Option&lt;V&gt; {<br>    // traverse linked list until either find value (update)<br>    // or stick a new value on the end<br><br>    // can safely unwrap as we&#39;ve already checked this pos exists<br>    let key_val = self.arr[position].as_mut().unwrap();<br>    if key_val.key == key {<br>        let old_val = key_val.value;<br>        key_val.value = val;<br>        // return the old value<br>        return Some(old_val);<br>    }<br><br>    let mut current = key_val;<br>    while current.next.is_some() {<br>        let node = current.next.as_mut().unwrap();<br><br>        if node.key == key {<br>            // update the value<br>            let old_val = node.value;<br>            node.value = val;<br>            return Some(old_val);<br>        }<br><br>        current = node;<br>    }<br><br>    // append the new value to the end of the linked list<br>    let new_key_val = KeyValue::new(key, val);<br><br>    current.next = Some(Box::new(new_key_val));<br>    self.curr_size += 1;<br><br>    None<br>}</pre><p>That&#39;s quite a lot of code to get through, so bare with me.</p><p>Let&#39;s look at the first section:</p><pre>// can safely unwrap as we&#39;ve already checked this pos exists<br>let key_val = self.arr[position].as_mut().unwrap();<br>if key_val.key == key {<br>    let old_val = key_val.value;<br>    key_val.value = val;<br>    // return the old value<br>    return Some(old_val);<br>}</pre><p>Here we grab the key value at that position, and simply check if our keys match. If they do, we update the value, and return the old value.</p><p>Now the next section</p><pre>let mut current = key_val;<br>while current.next.is_some() {<br>    let node = current.next.as_mut().unwrap();<br><br>    if node.key == key {<br>        // update the value<br>        let old_val = node.value;<br>        node.value = val;<br>        return Some(old_val);<br>    }<br><br>    current = node;<br>}<br><br>// append the new value to the end of the linked list<br>let new_key_val = KeyValue::new(key, val);<br><br>current.next = Some(Box::new(new_key_val));<br>self.curr_size += 1;<br><br>None</pre><p>This section iterates through the linked list, using is_some() to check if we’ve reached the end of the linked list. For every existing node we check</p><ul><li>If that node’s key matches ours</li><li>If it does, we update the value, and return the old value held there.</li><li>If not, we move to the next.</li></ul><p>If we reach the end without finding our key, we create a new KeyValue, and set the next attribute of our final KeyValue in the list to our new KeyValue . We then increment the size and return None .</p><p>We now also need to add some more traits to HashMap and in order to ensure that these functions can be satisfied. We add the PartialEq to T and the Copy trait to V . (the PartialEq trait will need importing with use std::cmp::PartialEq; )</p><pre>impl&lt;T: Clone + Hash + PartialEq, V: Copy&gt; HashMap&lt;T, V&gt; {</pre><p>Lovely! That&#39;s put implemented.</p><h4>Implementing Get</h4><p>Now we’ll see if we can actually grab values from our HashMap.</p><p>We’ll start out the same way, by hashing our key to find an index of the array to use.</p><pre>pub fn get(&amp;self, key: T) -&gt; Option&lt;V&gt; {<br>    let hash_val: u64 = hash_key(key.clone());<br>    let position = hash_val % DEFAULT_MAX_SIZE;<br><br>    None<br>}</pre><p>Then, we will do again the same as before and check the value at that index.</p><pre>pub fn get(&amp;self, key: T) -&gt; Option&lt;V&gt; {<br>    let hash_val: u64 = hash_key(key.clone());<br>    let position = hash_val % DEFAULT_MAX_SIZE;<br><br>    match &amp;self.arr[position as usize] {<br>        Some(_) =&gt; self.check_list_for_key(key, position as usize),<br>        None =&gt; None,<br>    }<br>}</pre><p>This time, the case where there is no value is even easier — there is no value to get so we return None.</p><p>If there is a value present, we again will check through that linked list for a key, returning None if we reach the end without finding a value.</p><p>Here is the implementation of check_list_for_key in our HashMap implementation where this is performed.</p><pre>fn check_list_for_key(&amp;self, key: T, position: usize) -&gt; Option&lt;V&gt; {<br>    let mut current = self.arr[position].as_ref().unwrap();<br>    if current.key == key {<br>        return Some(current.value);<br>    }<br><br>    while let Some(node) = current.next.as_ref() {<br>        if node.key == key {<br>            return Some(node.value);<br>        }<br><br>        current = node;<br>    }<br><br>    None<br>}</pre><p>The structure is similar to our implementation of update_or_link_new_val where we first check the first KeyValue then iterate through the linked list until we either find a matching KeyValue or reach the end of the list. Note this time we are using as_ref() rather than as_mut() as we don’t need to mutate any of the values!</p><p>Great, we have both put and get implemented now — but currently we have no way to test them!</p><p>Let&#39;s add a new function to our HashMap implementation to allow us to instantiate a new HashMap.</p><pre>const INIT: Option&lt;KeyValue&lt;T, V&gt;&gt; = None;<br>pub fn new() -&gt; HashMap&lt;T, V&gt; {<br>    HashMap {<br>        curr_size: 0,<br>        arr: [Self::INIT; DEFAULT_MAX_SIZE as usize],<br>    }<br>}</pre><p>We define a const here, with the specified value of None . This gets around requiring the Copy trait on type T as if we were to instantiate the array using the following</p><pre>arr: [None; DEFAULT_MAX_SIZE as usize]</pre><p>this trait would be required. This would mean our HashMap wouldn’t be able to accept String as a valid key type, which would be annoying. Using this const allows us to get around this.</p><p>Now, we can run a test as follows which will pass.</p><pre>#[test]<br>fn test_can_get_item() {<br>    let key = &quot;hello&quot;.to_string();<br>    let value: i32 = 1;<br><br>    let mut my_hash: HashMap&lt;String, i32&gt; = HashMap::new();<br>    my_hash.put(key.clone(), value);<br><br>    let result = my_hash.get(key).unwrap();<br><br>    assert_eq!(result, value)<br>}</pre><p>Nice!</p><h4>Implementing Remove</h4><p>The structure of remove follows a very similar structure to put and get , so we’ll speed through the first part.</p><pre>pub fn remove(&amp;mut self, key: T) -&gt; Option&lt;V&gt; {<br>    let hash_val: u64 = hash_key(key.clone());<br>    let position: u64 = hash_val % DEFAULT_MAX_SIZE;<br><br>    match &amp;self.arr[position as usize] {<br>        Some(_) =&gt; self.check_item_in_list_and_remove(key, position as usize),<br>        None =&gt; None,<br>    }<br>}</pre><p>Again, we hash the key to produce a position, if that position is empty we return None, otherwise we traverse through the linked list looking for that value.</p><p>Let&#39;s look at the implementaiton of check_item_in_list_and_remove</p><pre>fn check_item_in_list_and_remove(&amp;mut self, key: T, position: usize) -&gt; Option&lt;V&gt; {        <br>    let mut current = self.arr[position].as_ref().unwrap();<br>    if current.key == key {<br>        let return_val = current.value;<br>  <br>        // check if there is a next val<br>        // if there is next, update array to point to this val<br>        if let Some(node) = current.next.to_owned() {<br>            self.arr[position] = Some(*node);<br>        } else {<br>            self.arr[position] = None<br>        }<br>  <br>        // return the value the node held<br>        self.curr_size -= 1;<br>        return Some(return_val);<br>    }<br>  <br>    // iterate through until key found<br>    while current.next.is_some() {<br>        let next = current.next.as_mut().unwrap();<br>        if next.key == key {<br>            let return_val = next.value;<br><br>            // check if there is a next val<br>            // if there is next, update array to point to this val<br>            if let Some(next_next) = next.next.to_owned() {<br>                current.next = Some(Box::new(*next_next));<br>            } else {<br>                current.next = None<br>            }<br><br>            // return the value the node held<br>            self.curr_size -= 1;<br>            return Some(return_val);<br>        }<br><br>        // set current equal to the next<br>        current = current.next.as_mut().unwrap();<br>    }<br><br>    None<br>}</pre><p>Now this is a bit more complex — in order to remove a value from a linked list we must do the following</p><ul><li>check if the KeyValue being removed has a next value</li><li>If it does, we set the next value of the <strong><em>previous</em></strong> KeyValue to point to this KeyValue</li><li>If the KeyValue being removed is the <strong><em>first</em></strong> value, we set the value in the array to be the next value, if next exists.</li></ul><p>Let&#39;s look at the first part of this function</p><pre>let mut current = self.arr[position].as_ref().unwrap();<br>if current.key == key {<br>    let return_val = current.value;<br><br>    // check if there is a next val<br>    // if there is next, update array to point to this val<br>    if let Some(node) = current.next.to_owned() {<br>        self.arr[position] = Some(*node);<br>    } else {<br>        self.arr[position] = None<br>    }<br><br>    // return the value the node held<br>    self.curr_size -= 1;<br>    return Some(return_val);<br>}</pre><p>We check if the first node’s key matches our value. If it does, we save the value it held so that we can return it later. We then check if next exists, if it doesn’t, we simply update that position to be None . If it does exist, we set that position to be the address of that node. Hence the use of * .</p><p>We then decrement the size of the HashMap, and return the value.</p><p>Now let&#39;s look at the second bit of code, this looks a bit gruesome, but bare with me.</p><pre>// iterate through until key found<br>while current.next.is_some() {<br>    let next = current.next.as_mut().unwrap();<br>    if next.key == key {<br>        let return_val = next.value;<br><br>        // check if there is a next val<br>        // if there is next, update array to point to this val<br>        if let Some(next_next) = next.next.to_owned() {<br>            current.next = Some(Box::new(*next_next));<br>        } else {<br>            current.next = None<br>        }<br><br>        // return the value the node held<br>        self.curr_size -= 1;<br>        return Some(return_val);<br>    }<br><br>    // set current equal to the next<br>    current = current.next.as_mut().unwrap();<br>}<br><br>None</pre><p>Let&#39;s go through step by step.</p><ul><li>We check if the next KeyValue is not None</li><li>If it isn’t None , we check if its key matches the key we’re looking for.</li><li>If it does, we store the return value to return later.</li><li>We then check if the <strong><em>next </em></strong><strong><em>KeyValue after this is also a value</em></strong></li><li>If it is, we set our <strong><em>current</em></strong> value to point to this “next next” value.</li><li>If there is no “next next” value, we set our <strong><em>current </em></strong>value to point to None</li><li>We then decrement the current size, and return the value.</li></ul><p>This is the basic algorithm for deleting a node in a linked list. If you’re unsure about this, I would recommend going away and researching data structures such as a linked list to understand more.</p><p>If we reach the end of the linked list with no value, we simply return None .</p><p>This requires one other small thing to make the compiler happy; adding the #[derive(Clone)] tag to our KeyValue struct.</p><pre>#[derive(Clone)]<br>pub struct KeyValue&lt;T, V&gt; {<br>    key: T,<br>    value: V,<br>    next: Option&lt;Box&lt;KeyValue&lt;T, V&gt;&gt;&gt;,<br>}</pre><p>And that&#39;s remove implemented!</p><h4>Implementing clear</h4><p>To finish up, we have by far the easiest operation to implement: clear. Lets see how thats done;</p><pre>pub fn clear(&amp;mut self) {<br>    // overwrite the array to yeet everything<br>    self.curr_size -= 0;<br>    self.arr = [Self::INIT; DEFAULT_MAX_SIZE as usize];<br>}</pre><p>We simply set the size to 0, and reinstantiate the array!</p><p>And that&#39;s all! We’ve successfully implemented all the classic functions of a HashMap in rust from scratch!</p><h3>Conclusion</h3><p>Congrats on making it through this tutorial on implementing a hashmap in Rust! By now, you should have a good understanding of how hashmaps work and how to implement one from scratch. You should also be familiar with one possible implementation of the various methods that a hashmap provides, such as put, get, and remove.</p><p>I hope that you found this tutorial helpful and that it has given you the confidence to implement a hashMap in your own Rust projects. Feel free to play around with the code and try out different configurations and methods to get a better understanding of how it all works.</p><p>You can also check out the fully completed code for this tutorial on the GitHub repository <a href="https://github.com/rupert648/hashmap-rs">here</a>, complete with a few unit tests for the code.</p><p>Thanks for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d055b5ac2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/implementing-a-hashmap-in-rust-35d055b5ac2b">Implementing a HashMap in Rust</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying an Argo Workflow on GKE and accessing the Argo UI]]></title>
            <link>https://medium.com/@rupertcarr/deploying-an-argo-workflow-on-gke-and-accessing-the-argo-ui-bf7677e9fd7a?source=rss-21a2a12841d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf7677e9fd7a</guid>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[argo]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[argo-workflows]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Rupert Carr]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 15:31:58 GMT</pubDate>
            <atom:updated>2022-12-07T15:31:58.858Z</atom:updated>
            <content:encoded><![CDATA[<p>Alright, to begin this work through assumes a baseline knowledge of a few things; argo and how a basic workflow is configured, a basic understanding of docker and kubernetes, and some familiarity with Google Cloud.</p><p>Before doing this, I would try and get a workflow up and running locally through minikube. To do this you can follow the official argo getting started <a href="https://argoproj.github.io/argo-workflows/quick-start/">here</a> . Through that it should just be a few minutes until you’ve successfully ran your first workflow.</p><p>However, something simple locally is almost never something simple on the cloud. The first time getting a workflow up and running on GKE I had to jump through a number of hoops to do so, so hopefully this tutorial can speed that process up a bit for yourselves.</p><p>We have a few goals we want to accomplish in this tutorial</p><ul><li>Install Argo onto a Kubernetes cluster hosted on GKE</li><li>Gain access to the Argo UI</li><li>Deploy a basic workflow.</li></ul><h3>The Workflow</h3><p>To keep it simple, we will be deploying the following basic workflow, taken from the getting-started page of the argo workflows site.</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Workflow<br>metadata:<br>  generateName: hello-world-<br>  labels:<br>    workflows.argoproj.io/archive-strategy: &quot;false&quot;<br>spec:<br>  entrypoint: whalesay<br>  templates:<br>  - name: whalesay<br>    container:<br>      image: docker/whalesay:latest<br>      command: [cowsay]<br>      args: [&quot;hello world&quot;]</pre><p>We can put this into a file called hello-world.yaml to use later.</p><h3>Installing Argo onto GKE</h3><h4>Creating a Cluster</h4><p>I am going to start this tutorial from scratch, assuming that you don’t have a cluster created. But I will assume you have both the gcloud and kubectl CLIs installed. If not you can find them <a href="https://cloud.google.com/sdk/docs/install">here</a> and <a href="https://kubernetes.io/docs/tasks/tools/">here</a> respectively.</p><p>To create a cluster, choose a name and run the following command:</p><pre>gcloud container clusters create CLUSTER_NAME --image-type cos</pre><p><strong>IMPORTANT NOTE: </strong>you can specify that you want a cluster to be private with the option --enable-private-nodes . This will have an impact on the install method. See the section <em>Installing Argo onto a private cluster.</em></p><p>Now, configure your local kubectlto point to the new cluster:</p><pre>gcloud container clusters get-credentials CLUSTER_NAME</pre><h4>Installing Argo workflows</h4><p>I am using <strong>Argo v3.4.1 </strong>this tutorial. Hence the following commands may use that version no. The most recent release can be found at <a href="https://github.com/argoproj/argo-workflows/releases">https://github.com/argoproj/argo-workflows/releases</a></p><p>We will first install the Argo CLI to use locally using these commands:</p><pre># Download the binary<br>curl -sLO https://github.com/argoproj/argo-workflows/releases/download/v3.4.1/argo-darwin-amd64.gz<br><br># Unzip<br>gunzip argo-darwin-amd64.gz<br><br># Make binary executable<br>chmod +x argo-darwin-amd64<br><br># Move binary to path<br>mv ./argo-darwin-amd64 /usr/local/bin/argo<br><br># Test installation<br>argo version</pre><p>Create a namespace in the cluster in which we will install argo:</p><pre>kubectl create ns argo</pre><p>For both of our installation steps, we are going to download the argo workflows installation manifest. This will make it much easier to modify and persist changed configuration.</p><p>To download it, use the following link (or change the version number to whatever version you’d like to use)</p><p><a href="https://github.com/argoproj/argo-workflows/releases/download/v3.4.1/install.yaml">https://github.com/argoproj/argo-workflows/releases/download/v3.4.1/install.yaml</a></p><h4>Installing into a public cluster.</h4><p>If you are installing into a public cluster, skip to the section <em>configuring the manifest. </em>After<em> Installing into a private cluster</em></p><h4>Installing into a private cluster.</h4><p>This is a little more tricky. By default nodes within a private cluster don’t have access to resources outside of google cloud. As a result the above manifest we got from the argo github is unable to pull in the images it needs, which are hosted on quay.io . We can see this on lines 1259 and 1314.</p><pre>spec:<br>  containers:<br>  - args:<br>    - server<br>    - --tls-certificate-secret-name=argo-server-tls<br>    env: []<br>    image: quay.io/argoproj/argocli:v3.4.1<br>    name: argo-server</pre><p>Thats okay though! We have two solutions to solve this</p><ul><li>Create an egress which allows our cluster to access the outer internet</li><li>Download the images ourselves, and upload them to GCR so they can be accessed by default.</li></ul><p>I elected to go with the second, as it requires less config!</p><p>First of all, pull the images we need from quay.io</p><pre>docker pull quay.io/argoproj/workflow-controller:v3.4.1<br>docker pull quay.io/argoproj/argocli:v3.4.1</pre><p>Then push the images to GCR</p><pre>gcloud container images add-tag quay.io/argoproj/workflow-controller:v3.4.1 gcr.io/&lt;PROJECT_ID&gt;/workflow-controller:v3.4.2<br>gcloud container images add-tag quay.io/argoproj/argocli:v3.4.1 gcr.io/&lt;PROJECT_ID&gt;/argocli:v3.4.2</pre><p>Change &lt;PROJECT_ID&gt; to match the ID of your google cloud project.</p><p>Now we just have to go into our install manifest and change the images to point towards our new GCR images.</p><pre>containers:<br>  - args:<br>      - server<br>    image: gcr.io/uk-cti-adtech-k8pip-dev/argocli:v3.4.1<br>    name: argo-server</pre><pre>containers:<br>    command:<br>      - workflow-controller<br>    env:<br>      - name: LEADER_ELECTION_IDENTITY<br>        valueFrom:<br>          fieldRef:<br>            apiVersion: v1<br>            fieldPath: metadata.name<br>    image: gcr.io/uk-cti-adtech-k8pip-dev/workflow-controller:v3.4.1</pre><h4>Configuring the Manifest</h4><p>We now only have to configure one line in the manifest, this is necessary for later accessing the UI. In your install.yaml file, add the following environment variable to the argo-server deployment (should be around line 1260):</p><pre>env:<br>  - name: BASE_HREF<br>    value: /argo/</pre><p>So your argo-server deployment should look something as follows.</p><pre>spec:<br>  containers:<br>    - args:<br>        - server<br>      env:<br>        - name: BASE_HREF<br>          value: /argo/<br>      image: gcr.io/uk-cti-adtech-k8pip-dev/argocli:v3.4.2</pre><p>Now install the manifest onto your Kubernetes cluster using the following.</p><pre>kubectl apply -n argo -f install.yaml</pre><p>This will take a few minutes to setup while it spins up all the deployments.</p><h3>Running a workflow</h3><p>Now, fingers crossed, it should be possible to submit your first workflow.</p><p>If not done already, create a file called hello-world.yaml with the contents of the hello world workflow</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Workflow<br>metadata:<br>  generateName: hello-world-<br>  labels:<br>    workflows.argoproj.io/archive-strategy: &quot;false&quot;<br>spec:<br>  entrypoint: whalesay<br>  templates:<br>  - name: whalesay<br>    container:<br>      image: docker/whalesay:latest<br>      command: [cowsay]<br>      args: [&quot;hello world&quot;]</pre><p><strong>NOTE: </strong>if running in a private cluster, you may have the same issue with accessing the docker/whalesay:latest image as before. So you may have to pull this image again and upload it to GCR</p><p>Now, to run the workflow, run the following.</p><pre>argo submit -n argo --watch hello-world.yaml</pre><p>Run the following to get logs, at which point you should be greeted by a friendly whale saying hello.</p><pre>argo logs -n argo @latest</pre><h3>Accessing the UI</h3><p>This is great and all, but you may be familiar with the fact that argo provides a nice UI, from which you can submit and monitor argo workflows.</p><p>Accessing this can be a little complicated, especially on GKE. The following two sections explain two ways of accessing the UI emitted from the argo server.</p><h4>Port Forwarding</h4><p>By far the simplest way to access the UI is to port forward the argo-server by running the following command:</p><pre>kubectl -n argo port-forward svc/argo-server 2746:2746</pre><p>Then, navigate to <a href="https://localhost:2746/">https://localhost:2746</a> and you should be able to see the UI. Instructions for how to login are out of the scope for this tutorial, but can be found <a href="https://argoproj.github.io/argo-workflows/access-token/#token-creation">here</a>.</p><h4>Creating an Ingress</h4><p>This second way requires more initial setup, but allows the UI to be outside accessible on a domain/IP, without having to port forward.</p><p>Currently, the argo-server service is inaccessible from the outside of the cluster. By creating an ingress, we are creating a reverse proxy which can direct outside traffic to the argo server, then return back the response.</p><p>Google Kubernetes already comes with a default ingress installed called gce . However this doesn’t support some of the configuration which make creating this ingress much easier, so as a result we will install nginx.ingress to provide this service.</p><p>To do this you will need the <a href="https://helm.sh/docs/intro/install/">helm CLI installed.</a></p><p>To install NGINX.Ingress onto the cluster, use the following two commands:</p><pre>helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx<br>helm repo update</pre><p>Then deploy nginx-ingress using helm:</p><pre>helm install -n argo nginx-ingress ingress-nginx/ingress-nginx</pre><p>Note that I chose to install this into the argo namespace, although this is not strictly necessary.</p><p>We can verify that the nginx controller deployment and service are up and running by running the command:</p><pre>kubectl get deployment -n argo nginx-ingress-ingress-nginx-controller<br>kubectl get service -n argo nginx-ingress-ingress-nginx-controller</pre><p>Heres the output of the first of those two commands on my cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZJFlTkxvWkvOl2fnMN-9w.png" /></figure><p>We can see the nginx ingress controller deployment alongside the two argo deployments.</p><p>Now we will create a manifest to create an ingress controller. Create a file called ingress.yaml with the following contents</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: argo-server<br>  namespace: argo<br>  annotations:<br>    nginx.ingress.kubernetes.io/rewrite-target: /$2<br>    ingress.kubernetes.io/protocol: https # Traefik<br>    nginx.ingress.kubernetes.io/backend-protocol: https # ingress-nginx<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>    - http:<br>        paths:<br>          - backend:<br>              service:<br>                name: argo-server<br>                port:<br>                  number: 2746<br>            path: /argo(/|$)(.*)<br>            pathType: Prefix</pre><p>Note that we specify ingressClassName to use nginx , specifying that we want the ingress to use our nginx controller we just installed.</p><p>A few things are important in this file</p><ul><li>we point to the argo-server service so that all traffic is routed to this service</li><li>These routes are performed based on if the path attribute is matched. i.e. any routes ending in /argo/*</li><li>The path value /argo(/|$)(.*) contains a regex capture group. This capture group is used in the annotation nginx.ingress.kubernetes.io/rewrite-target: /$2 . This means that a path /argo/* is mapped to /* .</li><li>For example /argo/api/v1 becomes /api/v1</li></ul><p>Now apply this manifest to our cluster using the following:</p><pre>kubectl apply -f client-ingress.yaml</pre><p><strong>NOTE: </strong>I received an error looking similar to the following whilst applying this manifest:</p><pre>internal error occurred: failed calling webhook &quot;validate.nginx.ingress.kubernetes.io&quot;</pre><p>The solution to this error can be found in <a href="https://github.com/kubernetes/ingress-nginx/issues/5401">this github issue</a>.</p><p>Essentially, run the following command:</p><pre>kubectl delete -A ValidatingWebhookConfiguration ingress-nginx-admission</pre><p>Then re-apply the manifest.</p><h4>Viewing the UI</h4><p>You should be all setup! Run the following to see the IP address that your ingress is exposed on.</p><pre>kubectl get ingresses -n argo</pre><p>Then navigate in your browser to the address &lt;ip&gt;/argo.</p><p>Hopefully you have success!</p><p>The combination of all these small interlinked things on gcloud made setting this up take much longer than it perhaps should have, so hopefully this tutorial made your life slightly easier. 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf7677e9fd7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically Scaling a Workflow Step in Argo Workflows]]></title>
            <link>https://medium.com/@rupertcarr/dynamically-scaling-a-workflow-step-in-argo-workflows-1081aafb2929?source=rss-21a2a12841d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1081aafb2929</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[argo-workflows]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[argo]]></category>
            <dc:creator><![CDATA[Rupert Carr]]></dc:creator>
            <pubDate>Sat, 05 Nov 2022 16:20:09 GMT</pubDate>
            <atom:updated>2022-11-05T16:20:20.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Argo</h3><p>From the Argo Site</p><blockquote>Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes</blockquote><p>Argo workflows allows you to define through a configuration file a series of steps to run inside a kubernetes cluster. Argo from this configuration will control the sequencing for this as well as orchestrating any parallel operations you define.</p><p>When managing many parallel running workflows, argo does all the leg work for you. It will spin up containers to handle the steps you define using the kubernetes API. However this wasn’t what I wanted.</p><p>The use case I wanted to achieve for was to dynamically scale a <strong><em>single</em></strong> <strong><em>step</em></strong> in a workflow, whilst keeping other steps static.</p><h3>Why did I need this Use Case?</h3><p>A simplification of my use case provided just two steps.</p><ol><li>A data generation step, which puts the data into a shared database</li><li>A data pulling step, which pulls the data from the database and performs some processing on the data, before dumping it to a storage solution.</li></ol><p>I wanted the data being generated in the first stage to consistently be unique whilst running the node. There are fancy ways to do this whilst running multiple containers but the simplest way to ensure unique data is to just have a single node generating the data.</p><p>The second step is what I wanted to scale — I want to make a decision based upon how much data is generated from the first step to decide how many instances of the second step I created. This would allow me to process the data in parallel. This would make the data processing step much quicker.</p><p><em>Note: A better solution to this issue might be to extract the data production from the workflow, however keeping it inside the workflow itself allowed expandability within my use case as well as the ability to extremely easily orchestrate the whole thing on a CRON job.</em></p><h3>Installation</h3><p>To preface the solution, to demo these steps I am running these steps in a local cluster using <a href="https://minikube.sigs.k8s.io/docs/start/">Minikube</a>. To install minikube follow the instructions on their site, or using homebrew.</p><pre>brew install minikube</pre><p>Run minikube start to spin up your minikube instance, then run the following to install argo.</p><pre>kubectl create namespace argo<br>kubectl apply -n argo -f <a href="https://github.com/argoproj/argo-workflows/releases/download/v">https://github.com/argoproj/argo-workflows/releases/download/v</a>&lt;&lt;ARGO_WORKFLOWS_VERSION&gt;&gt;/install.yaml</pre><p>For the writing of this tutorial, I am using <strong>v3.4.2</strong></p><p>You will also need to install the <a href="https://github.com/argoproj/argo-workflows/releases/tag/v3.4.3">Argo CLI</a></p><h3>The Solution</h3><p>The solution to this problem I found was to utilise the output parameters you are able to pass through the steps in Argo Workflows. We can use these in conjunction with the withParam attribute to run parallel jobs.</p><h4>Output Parameters</h4><p>Argo provides several forms of functionality for passing output parameters between steps.</p><ul><li>Reading the standard output of a container/script</li><li>Taking the value from a specified file</li></ul><p>Reading the standard output is okay for simple scripts, however since many programs will involve regular std output such as logging this may conflict and cause issues, hence creating a temp file to write the value is the easier route. Argo provides in their docs an example on how to do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3220663c026a02b563369d06994551d9/href">https://medium.com/media/3220663c026a02b563369d06994551d9/href</a></iframe><p>We can see that the first step in this workflow writes the value “hello world” to a file /tmp/hello_world.txt , then argo grabs the value written to the file as a parameter called <em>hello-world</em>. Then we use</p><pre>{{steps.generate-parameter.outputs.parameters.hello-param}}</pre><p>to access that parameter in the next step, which uses whalesay to print out the parameter.</p><p>We can submit this workflow using the following command.</p><pre>argo submit -n argo --watch output-parameter-workflow.yaml</pre><p>This will give the following output in the terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_VL3AlVeLLL1vE6DYBw9g.png" /></figure><p>We can view the logs for this workflow to verify the paramater was successfully passed between steps using:</p><pre>argo logs -n argo @latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebc7yTtVAgWBpyhSGvSeNw.png" /></figure><h4>The withParam attribute.</h4><p>We can use these output parameters to define the number of the following steps using the withParam attribute.</p><p>The withParam attribute takes a JSON list as input, and will run the steps in parallel for each value in the list.</p><p>We can use this to our advantage by creating this json list in the previous step, and then using it in the withParam attribute. A simple example of doing this might look as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05708ba01f80831f37ad14a001fd50bf/href">https://medium.com/media/05708ba01f80831f37ad14a001fd50bf/href</a></iframe><p>In this example, in the first step we use a python script to dump a json array to standard output which looks as follows</p><pre>[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]</pre><p>Submitting this workflow using</p><pre>argo submit -n argo --watch loops-param-result.yaml</pre><p>Gives us the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li5T0lShSurJkOTHZcrI9A.png" /></figure><p>We can see that argo coordinates to run one of the “sleep” steps for each of the values spit out in the array, in the brackets we can also see the parameter that each step took.</p><h4>Applying this to our example</h4><p>Coming back to our example, we mentioned that we want the number of data pullers to be generated to be dependent on the amount of data produced in the first step.</p><p>In my use case, I used the number of rows of data produced, divided by a number of rows to handle per db puller, to decide this value.</p><p>For example.</p><ul><li>If our data producer produces <strong>1000</strong> rows of data</li><li>And our data pullers each handle <strong>100</strong> rows of data</li><li>We want to spawn <strong>10</strong> steps of the data puller.</li></ul><p>I also wanted this calculation to be de-coupled away from either of the steps, giving us more control over the operation.</p><p>My solution was as follows</p><ol><li>Have my data generation stage write the number of rows written to a file. Use this file as the output parameter.</li><li>Add an “intermediate” step which uses this output value to produce a JSON List for with withParam attribute</li><li>Take this JSON list and use it in the withParam attribute in the data pulling step.</li></ol><p>For the afore described intermediate step, I use a python script directly in the argo file. This step looks as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f3f298da3e4a73e9eccb21c598ce3f2/href">https://medium.com/media/7f3f298da3e4a73e9eccb21c598ce3f2/href</a></iframe><p>We can see we take the input step as a parameter, calculates the number of the final step we want to produce, then creates a JSON list of that length.</p><p>We can access this in the steps stage using the result tag on outputs , without having to explicitly define it as an output parameter. This access looks as follows.</p><pre>{{steps.numb-sleep-steps.outputs.result}}</pre><p>Now we have produced this json list, we pass it to the final step as we showed in the previous example.</p><h4>Combined Solution</h4><p>Now we combine these steps to produce a final Argo Workflow. This can be seen below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4472f79d1ada8d52ef6b0e3c8c0a53e/href">https://medium.com/media/b4472f79d1ada8d52ef6b0e3c8c0a53e/href</a></iframe><p>Note that the first job we run in the workflow is simply a python script which writes to a file. This could easily be a container which does a similar thing. Note that argo will read files within the local container space.</p><p>So to repeat, this workflow has the following three steps.</p><ol><li>Perform some functionality, write an output number to a file, use this file as an output parameter</li><li>Take this output parameter value (a number), divide it by another number and produce a JSON list of length of the result. This is the output parameter.</li><li>Take this JSON list as input parameter, pass it to the withParam attribute for the step.</li></ol><p>Run this workflow using the following command</p><pre>argo submit -n argo --watch scaling-workflow.yaml</pre><p>Note since we write the value “1000” to the file, then use val_per_sleep = 100 we expect 10 sleep-n-sec steps to be produced. Here is the terminal output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn9QrVIoNWJ4NojmjvYDfw.png" /></figure><p>We can see we get the expected result.</p><p>If we change the value to val_per_sleep = 500 we would expect only 2 workflows to be produced. We can change this in the file and run it again. Giving the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCexh_47YcEJlI0REnp2Xw.png" /></figure><h4>Conclusion</h4><p>So there we go, a way to dynamically scale a step in an Argo Workflow. I would think carefully before deciding if this is something you need, but if you do I think its a neat solution to the problem which takes advantage of configuration attributes available.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1081aafb2929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Deploying a Personal Blog/Portfolio using Docusaurus]]></title>
            <link>https://medium.com/@rupertcarr/creating-and-deploying-a-personal-blog-portfolio-using-docusaurus-4a33f1f4e476?source=rss-21a2a12841d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a33f1f4e476</guid>
            <category><![CDATA[blog-site]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[docusaurus]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[personal-website]]></category>
            <dc:creator><![CDATA[Rupert Carr]]></dc:creator>
            <pubDate>Mon, 03 Oct 2022 13:17:18 GMT</pubDate>
            <atom:updated>2022-10-03T13:17:18.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Docusaurus is the solution from meta for building content based static html sites using nothing more than markdown files. Despite designed around the use-case of building documentation, at its heart Docusaurus is a easy to use content management system, and with its already inbuilt blog feature set it is the perfect candidate to quickly and easily setup a personal website and blog.</p><h3>Setup</h3><p>Setup is as simple as following the <a href="https://docusaurus.io/docs/installation">docusarus setup documentation</a>, and it is quickest to start out with their scaffold project website from which we can expand and adjust. Their documentation, as you would expect from a documentation tool, is fantastic. I strongly suggest opening another tab and browsing this in addition to going through this article, however to save you time I will demonstrate the steps for setting up below.</p><p>First, create the scaffold project website using <strong>npx. </strong>We’ll be adding the --typescript tag to create a typescript project, but this isn’t necessary.</p><pre>npx create-docusaurus@latest my-website classic --typescript</pre><p>And marvellously thats it! You now have a full website, congrats! This generates a folder titled my-website containing the following file structure (truncated below in some places for size on page)</p><pre>my-website<br>├── blog<br>│   ├── 2021-08-26-welcome.md<br>│   ├── 2019-05-28-first-blog-post.md<br>│   └── 2019-05-29-long-blog-post.md<br>│   └── 2019-08-01-mdx-blog-post.mdx<br>│   └── authors.yml<br>├── docs<br>│   ├── tutorial-basics<br>│   │   └── congratulations.md<br>│   │   └── create-a-blog-post.md<br>│   │   └── create-a-document.md<br>│   │   └── create-a-page.md<br>│   │   └── deploy-your-site.md<br>│   │   └── markdown-features.md<br>│   │   └── _category_.json<br>│   ├── tutorial-extras<br>│   ├── intro.md<br>├── src<br>│   ├── components<br>│   │   └── HomePageFeatures<br>│   ├── css<br>│   │   └── custom.css<br>│   └── pages<br>│       ├── index.module.css<br>│       └── index.tsx<br>│       └── markdown-page.md<br>├── static<br>│   └── img<br>├── docusaurus.config.js<br>├── tsconfig.json<br>├── .gitignore<br>├── babel.config.js<br>├── package.json<br>├── README.md<br>├── sidebars.js<br>└── package-lock.json</pre><p>of key note here are the docs and blog directories, as well as the docusaurus.config.js file, in which most of the heavy lifting for converting this into our perfect blog site is done.</p><h3><strong>Running the Development Server</strong></h3><p>Running the following will launch a local development server where you can see your new website!</p><pre>npm start</pre><p>This will default to <a href="http://localhost:3000/">http://localhost:3000</a> which you can open in your browser to see. We can see through doing this that a lot of unneccessary docusaurus boilerplate has been included.</p><h3>Modifying to suit our needs</h3><p>The first thing I wanted to do was to sort out our directory structure. First of all, docs doesn’t really make a lot of sense in our context. Docusaurus unsurprisingly requires this, so the best move is to re-purpose it. Instead I wanted this section to become the “Portfolio” section of our site — it makes sense given that your projects <strong><em>should be documented</em></strong> 😉. To do this we need to make the following adjustments.</p><p>First of all lets rename our docs folder to something more suitable. Since <a href="https://docusaurus.io/docs/migration/manual#customdocspath-docsurl-editurl-enableupdateby-enableupdatetime">version 2.0</a> this is extremely simple. We make the following changes in docusaurus.config.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbe000f7e70bb34c9bcd24802edf20b/href">https://medium.com/media/5dbe000f7e70bb34c9bcd24802edf20b/href</a></iframe><p>routeBasePath changes the routing on the site, meaning if you have some documentation titled myProject the route will now be /portfolio/myProject rather than /docs/myProject .</p><p>path changes where docusaurus searches your project for ‘doc’ markdown files, which it uses to generate the portfolio section.</p><p>Now <strong>to match this change we must rename our </strong><strong>docs folder to </strong><strong>portfolio</strong></p><p>Please note that you can call ‘portfolio’ whatever you want!</p><h3>Adding Projects</h3><p>Now create markdown files within your new folder to populate your site with your projects! Each project can have nested pages by creating sub-folders in the portfolio folder. See the <a href="https://docusaurus.io/docs/docs-introduction">docusaurus documentation</a> for more information about this.</p><h3>Blog</h3><p>One of the main reasons I decided to create a personal site was to host my own blog. A reason docusaurus became my choice for this was due to its out of the box blog support. This supports many features which can enhance your blog — making it much more enjoyable to interact with than simply text. For example tags and reading time.</p><p>Adding a blog to your site is extremely easy — simply add a folder to your root titled blog , this is already done for you in the generated file structure. Then, to create a blog, create a file titled {year}-{month}-{day}-{title}.md . Docusaurus also provides the functionality to provide multiple authors, tags and many other features, all of which can be found <a href="https://docusaurus.io/docs/blog">in their documentation</a>.</p><p>And thats mostly it for the content side of things, once again the docusaurus documentation is unsurprisingly fantastic and completely comprehensive, and will give you access to many other features such as custom pages, themeing and lots else.</p><h3>Deploying the Site</h3><p>Docusaurus is a <em>static site generator. </em>Meaning it generates static files which can simply be served from your favourite static site hosting service. For example, you could simply dump the files inside the build directory into an S3 bucket which would work absolutely fine.</p><p>Sites like <a href="https://www.netlify.com/">Netlify</a> offer a great free tier which gives you pretty much everything you would want for a small blog site. They can also deploy directly from a github repo meaning you can version control your sites content. Simply connect your netlify project to your docusaurus sites github repo, then specify npm run build as the build command and build as the publish directory. This is exactly what I did and it was super simple! Netlify (even on the free tier!) also allows you to connect your own domains. View <a href="https://rupertcarr.uk/">rupertcarr.uk</a> to see mine!</p><h3>Summing Up</h3><p>To wrap up — is docusaurus the optimal tool for deploying your own site? Possibly not — but that said it is incredibly easy to use as a general CMS and therefore I think makes a great option. There may be more tailored tools for the jobs, but I think the feature set they created for this tool can be applied to create a fantastic, simple portfolio site from scratch extremely quickly. And it looks great!</p><p>At the end of the day this was in part a learning exercise for myself to get used to the tool, the experience of which led me to recommend us to use docusaurus to document an internal tool I am working on. But I suggest you yourself go out and examinine and try out other tools as well to make sure you are making the optimal choice for your own use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a33f1f4e476" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Spring Boot API to Railway using Maven and Docker]]></title>
            <link>https://medium.com/@rupertcarr/deploying-a-spring-boot-api-to-railway-using-maven-and-docker-5c75e7428e90?source=rss-21a2a12841d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c75e7428e90</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Rupert Carr]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 17:28:57 GMT</pubDate>
            <atom:updated>2022-09-19T17:28:57.966Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide we will walk through how to deploy a Java Spring Boot API to <a href="https://railway.app/">railway.app</a> , its deceptively simple to do, and with railway’s use of nixpacks the speed of deployment will blow your mind.</p><p>This deployment takes just 5 steps to get from no-code to your very own public API service.</p><ol><li>Create a Springboot application and define some routes</li><li>Push this application to a github repo.</li><li>Create a project on Railway.app from this github repo.</li><li>Create a dockerfile to build and package the application and push it to the repo</li><li>Expose a public domain on Railway.app</li></ol><h3>Getting Started</h3><h4>The Springboot Application</h4><p>The first thing you will need is a spring boot API that you can deploy! If you are just getting started with this, you can follow the official <a href="https://spring.io/guides/gs/spring-boot/">SpringBoot Getting Started Guide</a> to get your first project up and running.</p><p>My directory structure with a project titled “getyourway” looks as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*m7dGC5a-wLzotnPx3g-xVQ.png" /></figure><p>I created a file titled HelloController.java and put in the following code to define one route to /</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef69e3820729278e3d9345b1edaea9e/href">https://medium.com/media/cef69e3820729278e3d9345b1edaea9e/href</a></iframe><p>If we run the application using $ mvn spring-boot:run we can navigate to http://localhost:8080/hello where we can see our response.</p><p>Once done, be sure to <strong>push this project to your own github repository,</strong> so that we can later integrate with railway.</p><h4>Railway</h4><p>To integrate this project with railway you will need to do two things.</p><ul><li>Create a Railway.app account</li><li>Connect Railway.app to your github account</li></ul><p>Railway will walk you through signing up. Once done, railway will greet you with this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1QYzBKAKiTNdK-kGjxWWg.png" /></figure><p>From here we will click <strong>Start a New Project </strong>and then <strong><em>Deploy from a Github Repo.</em></strong></p><p>From this next screen, this is where we can connect and configure railway to work with our github account. So go ahead and click <strong>Configure Github App</strong>.</p><p>This will first ask you to add the app to your github account, then will allow you to configure the account and its permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*0Pg4uVoMfq7yLXO2i-wQwg.png" /></figure><p>Repository access will allow you to choose which repositories Railway can see. I chose to only select certain repositories, in which case <strong>you must select your newly created springboot repository so we can access it.</strong></p><p>Now this is configured, back on Railway we can go ahead and select our github repository. Next click the <strong>Add Variables</strong> option, rather than deploying it right away — we first need to setup our repo to deploy.</p><h3>Configuring SpringBoot to Deploy using Maven</h3><p>The docker file for our application involves two stages to the docker file.</p><ol><li>Building the jar file</li><li>Packaging the application</li></ol><h4>The Dockerfile</h4><p>In the root directory, create a Dockerfile with the following content</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a480d92ad97cc71cdf668d826cc99626/href">https://medium.com/media/a480d92ad97cc71cdf668d826cc99626/href</a></iframe><p><strong>NOTE: </strong>Be sure to change maven and openjdk to use the version of java you are using and generated the spring-boot application with to prevent build errors.</p><p>The build stage uses mvn package to create a jar file of our application from our pom.xml</p><p>The package stage then exposes a port before defining an entrypoint for our package. Don’t forget to change /home/app/target/getyourway-0.0.1-SNAPSHOT.jar to match the name of your application (just the jar filename needs adjusting)</p><p>We expose port 8080, the default launch port for springboot, if you have modified this value at all in the config for your springboot application, change the port value here.</p><h4>Expose port on Railway</h4><p>Before we redeploy, we must let railway know which port our application should listen on. This can be done by setting the environment variable PORT in railway, as can be seen in the image below. Again this should be set to 8080 or your corresponding port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IM_Qm9PqZfk_3mN7FCQkhA.png" /></figure><p>Now this is done, <strong>push your code </strong>to the github repository.</p><p>Immediately Railway will spot this new push and start to redeploy this service.</p><p>Amazingly — thats it! Railway will immediately <strong>identify the Dockerfile</strong> in your repository, and use it to build an image which it uses to run the service.</p><h3>Making it public</h3><p>If we now go to the settings page of our Railway application we can click the <strong>Generate Domain</strong> button underneath <strong><em>Domains </em></strong>(or alternatively add your own domain), this will take a few seconds or minutes but then once your service has adjusted, follow through to this generated domain and go to <a href="https://getyourway-production.up.railway.app/">https://your-generated-project-name.up.railway.app/</a> and you should see “Hello World!” as your result!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c75e7428e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>