<?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 Innocent Anyaele on Medium]]></title>
        <description><![CDATA[Stories by Innocent Anyaele on Medium]]></description>
        <link>https://medium.com/@innocentanyaele?source=rss-e703ae799605------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Fx0MWBAlOZaUwTcQ.jpg</url>
            <title>Stories by Innocent Anyaele on Medium</title>
            <link>https://medium.com/@innocentanyaele?source=rss-e703ae799605------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:34:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@innocentanyaele/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[Build a POSIX compliant shell in C++]]></title>
            <link>https://innocentanyaele.medium.com/build-a-posix-compliant-shell-in-c-f793f66e91ea?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/f793f66e91ea</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 22:50:17 GMT</pubDate>
            <atom:updated>2025-02-02T22:50:17.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0MAcpOKsbyDrqlMPD74DQ.jpeg" /></figure><p>Let’s build a Shell in C++. A POSIX (Portable Operating System Interface) shell is a command-line interface (CLI) designed to be compatible with UNIX-based operating systems. Examples include Bash, Zsh, and others.</p><p>In this walkthrough, we will implement some of the popular commands and features of a basic command line utility in C++. This walkthrough is inspired by the CodeCrafters challenge; <a href="https://app.codecrafters.io/courses/shell/overview"><strong>Build your own Shell</strong></a>.</p><p>Here are some things to note in this walkthrough</p><ul><li>Full code will be added below. This will include all necessary imports.</li></ul><h3><strong>REPL (Read, Evaluation, Print, Loop)</strong></h3><p>We can’t have a shell without accepting input from the user. In this section, we want to set up a system to accept an input from the user, evaluate it, print out the output and repeat. Our <strong>REPL</strong> will contain some advanced functions like autocompleting both <strong>builtin </strong>commands and <strong>system </strong>commands. <strong>Builtin </strong>commands are simply the commands we implement manually such as <strong>echo, type, exit, pwd </strong>and <strong>cd. System </strong>commands are the commands we will direct to the system using the execvp function in C++. We will however need to parse the input to determine what to handle manually and what to direct to the system command.</p><pre>int main() {<br>    cout &lt;&lt; unitbuf;<br>    cerr &lt;&lt; unitbuf;<br><br>    unordered_set&lt;string&gt; validCommands = {&quot;type&quot;, &quot;echo&quot;, &quot;exit&quot;, &quot;pwd&quot;, &quot;cd&quot;};<br><br>    while (true) {<br>        cout &lt;&lt; &quot;$ &quot;;<br>        string input = read_input_with_autocomplete();<br><br>        if (input.empty()) {<br>            continue;<br>        }<br>}</pre><p>Let’s implement our read_input_with_autocomplete .</p><pre>void enable_raw_mode(struct termios &amp;old_term) {<br>    struct termios new_term;<br>    tcgetattr(STDIN_FILENO, &amp;old_term);<br>    new_term = old_term;<br>    new_term.c_lflag &amp;= ~(ICANON | ECHO);<br>    tcsetattr(STDIN_FILENO, TCSANOW, &amp;new_term);<br>}<br><br>void disable_raw_mode(struct termios &amp;old_term) {<br>    tcsetattr(STDIN_FILENO, TCSANOW, &amp;old_term);<br>}<br><br>string longest_common_prefix(const vector&lt;string&gt;&amp; strings) {<br>    if (strings.empty()) return &quot;&quot;;<br><br>    string prefix = strings[0]; <br>    for (size_t i = 1; i &lt; strings.size(); ++i) {<br>        size_t j = 0;<br>        while (j &lt; prefix.size() &amp;&amp; j &lt; strings[i].size() &amp;&amp; prefix[j] == strings[i][j]) {<br>            j++;<br>        }<br>        prefix = prefix.substr(0, j);<br>        if (prefix.empty()) break; <br>    }<br>    return prefix;<br>}<br><br>string read_input_with_autocomplete() {<br>    string input;<br>    struct termios old_term;<br>    enable_raw_mode(old_term);<br><br>    char ch;<br>    bool has_listed_matches = false; <br><br>    while (true) {<br>        ch = getchar();<br><br>        if (ch == &#39;\n&#39;) {<br>            cout &lt;&lt; endl;<br>            break;<br>        } <br>        else if (ch == &#39;\t&#39;) {<br>            if (!input.empty()) {<br>                // Check for built-in commands first<br>                if (input == &quot;ech&quot;) {<br>                    input = &quot;echo &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else if (input == &quot;exi&quot;) {<br>                    input = &quot;exit &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else if (input == &quot;typ&quot;) {<br>                    input = &quot;type &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else {<br>                    string path_env = getenv(&quot;PATH&quot;);<br>                    string path;<br>                    stringstream ss(path_env);<br>                    set&lt;string&gt; unique_matches;<br><br>                    while (!ss.eof()) {<br>                        getline(ss, path, &#39;:&#39;);<br>                        if (filesystem::exists(path)) {<br>                            for (const auto &amp;entry : filesystem::directory_iterator(path)) {<br>                                string filename = entry.path().filename().string();<br>                                if (filename.find(input) == 0 &amp;&amp; access(entry.path().c_str(), X_OK) == 0) {<br>                                    unique_matches.insert(filename);<br>                                }<br>                            }<br>                        }<br>                    }<br><br>                    vector&lt;string&gt; matches(unique_matches.begin(), unique_matches.end()); <br><br>                    if (matches.size() &gt; 1) {<br>                        string lcp = longest_common_prefix(matches);<br><br>                        if (lcp != input) {<br>                            input = lcp;<br>                            cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;  <br>                            has_listed_matches = false;<br>                        } <br>                        else {      <br>                            if (!has_listed_matches) {<br>                                cout &lt;&lt; &quot;\a&quot;; <br>                                has_listed_matches = true;<br>                            } <br>                            else {<br>                                cout &lt;&lt; &quot;\n&quot;;<br>                                for (const auto &amp;match : matches) {<br>                                    cout &lt;&lt; match &lt;&lt; &quot;  &quot;; <br>                                }<br>                                cout &lt;&lt; &quot;\n$ &quot; &lt;&lt; input;<br>                                has_listed_matches = false;  <br>                            }<br>                        }<br>                    } <br>                    else if (matches.size() == 1) {<br>                        input = matches[0] + &quot; &quot;;<br>                        cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                        has_listed_matches = false;<br>                    } <br>                    else {<br>                        cout &lt;&lt; &quot;\a&quot;; <br>                        has_listed_matches = false;<br>                    }<br>                }<br>            }<br>        } <br>        else if (ch == 127 || ch == 8) {<br>            if (!input.empty()) {<br>                cout &lt;&lt; &quot;\b \b&quot;;<br>                input.pop_back();<br>                has_listed_matches = false;<br>            }<br>        } <br>        else {<br>            cout &lt;&lt; ch;<br>            input += ch;<br>            has_listed_matches = false;<br>        }<br>    }<br><br>    disable_raw_mode(old_term);<br>    return input;<br>}</pre><p>We have 4 functions that each play a role in reading and auto completing our input. enable_raw_mode allows accepts a termios (a structure in c used to configure terminal attributes such as input and output mode). In this method, we duplicate our current terminal structure by getting it’s attributes and assigning it to a new terminal structure. We then set attributes for the new terminal structure by disabling canonical mode which disables input buffering since we want to process every character immediately. We also display <strong>echo </strong>since we will handle what input is printed to the screen after the user types it. disable_raw_mode simply reverts our settings back to the old term.</p><p>In our read_input_autocomplete , we handle different cases of input from the user. We break if the user presses enter (\n). If the user presses tab, we take the user’s current input and attempt to autocomplete. We autocomplete for echo , exit and type if they match our set prefixes. We also handle cases for external executable file commands like custom_executable which are not builtin but exist as files in our current directory. In the else statement, we get our current path environment and perform a stream evaluation on it. We process the PATH environment variable, which contains multiple directories separated by colons (:). For each directory, we check if it exists on the system and iterate through its files to find matching commands. For each of these paths, check if they exist on our system, iterate through their directories to get all the file names, and compare the first characters to that our our input. We insert matches in a set to maintain uniqueness and sort the set into a vector of strings. Because we can have multiple matches, we return the longest match. If our users input already matches the longest common prefix, we just return all the list of files with that prefix. Our autocomplete also sends a bell sound with the character \a when no matches are found. We also handle backspace (127) and delete (8) characters to clear the input.</p><h3>pwd, type, cd</h3><p>In this section we will implement 3 builtin commands — pwd to print the current working directory, type to output the type of command for our accepted commands and cd to change directory.</p><p>pwd</p><p>type echo</p><p>type cd</p><p>cd ~</p><p>cd dir_1/dir_2/dir_3</p><pre>string get_path(string command) {<br>    string path_env = getenv(&quot;PATH&quot;);<br>    string path;<br>    stringstream ss(path_env);<br><br>    while (!ss.eof()) {<br>        getline(ss, path, &#39;:&#39;);<br>        string abs_path = path + &quot;/&quot; + command;<br>        if (filesystem::exists(abs_path)) {<br>            return abs_path;<br>        }<br>    }<br>    return &quot;&quot;;<br>}<br><br><br>int main() {<br>    cout &lt;&lt; unitbuf;<br>    cerr &lt;&lt; unitbuf;<br><br>    unordered_set&lt;string&gt; validCommands = {&quot;type&quot;, &quot;echo&quot;, &quot;exit&quot;, &quot;pwd&quot;, &quot;cd&quot;};<br><br>    while (true) {<br>        cout &lt;&lt; &quot;$ &quot;;<br>        string input = read_input_with_autocomplete();<br><br>        if (input.empty()) {<br>            continue;<br>        }<br><br>        string command = input.substr(0, input.find(&quot; &quot;));<br>        string args = input.substr(input.find(&quot; &quot;) + 1);<br><br>        if (command == &quot;exit&quot;) {<br>            return 0;<br>        }<br><br>        else if (command == &quot;pwd&quot;) {<br>            cout &lt;&lt; filesystem::current_path().string() &lt;&lt; &quot;\n&quot;;<br>        }<br><br>        else if (command == &quot;cd&quot;) {<br>            if (args == &quot;~&quot;) {<br>                chdir(getenv(&quot;HOME&quot;));<br>            } else {<br>                if (filesystem::exists(args)) {<br>                    chdir(args.c_str());<br>                } else {<br>                    cout &lt;&lt; &quot;cd: &quot; &lt;&lt; args &lt;&lt; &quot;: No such file or directory\n&quot;;<br>                }<br>            }<br>        }<br>        else if (command == &quot;type&quot;) {<br>            if (validCommands.find(args) != validCommands.end()) {<br>                cout &lt;&lt; args &lt;&lt; &quot; is a shell builtin\n&quot;;<br>            } else {<br>                string path = get_path(args);<br>                if (path.empty()) {<br>                    cout &lt;&lt; args &lt;&lt; &quot;: not found\n&quot;;<br>                } else {<br>                    cout &lt;&lt; args &lt;&lt; &quot; is &quot; &lt;&lt; path &lt;&lt; &quot;\n&quot;;<br>                }<br>            }<br>        }<br><br>}</pre><p>After accepting our input from read_input_with_autocomplete , we check if the input is empty and continue the loop if it is. We spit the input into two parts. The command by finding the first space in the string, and the args which is everything after the space.</p><p>Our first if statement handles the exit command by immediately return 0 to end the <strong>REPL</strong>.</p><p>Our second if statement prints the current working directory using the filesystem::current_path() function.</p><p>In our third if statement, we first handled the argument if it is ~ ; a shortcut for the <strong>HOME </strong>directory and change the directory to <strong>HOME </strong>using the chdir function. If it is not the <strong>HOME </strong>shortcut, we just if the path specified in the argument exists. If so we change the directory to that part.</p><p>In our type condition, we check the argument passed against our unordered set of commands. If we have that in our set we printout that the argument is a builtin command. Now remember we need to handle both builtin and system commands. If the command is not builtin, it could be a path to an executable file.</p><p>$ type valid_command<br>valid_command is /usr/local/bin/valid_command</p><p>For such commands, our get_path function accepts the arguments, streams our <strong>PATH </strong>environement which could be multiple paths seperated by <strong>column,</strong> and for each path it combines our path argument and checks if the file exists. If it exists it returns the absolute path which we print out to the user. If not, then the command is an invalid command.</p><h3>echo</h3><p>Next, we will be implementing our echo shell command. This command is primarily used to display text or variables to the standard output. Our echo command will handle basic text output as well as redirecting output with;</p><ul><li>echo &quot;Hello&quot; &gt; file.txt(redirecting output to file)</li><li>&gt;&gt; (redirecting output to file without overwriting it)</li><li>1&gt; (redirecting standard output to file)</li><li>1&gt;&gt; (redirecting standard output to file without overwriting it)</li><li>2&gt; (redirecting standard error to file)</li><li>2&gt;&gt; (redirecting standard error to file without overwriting it)</li></ul><p>One very important thing to take note about parsing input commands and arguments from users is how to handle special characters and commands in quotes. Here are some basic rules to note</p><ol><li><strong>Backslashes (</strong><strong>\) escape characters (</strong><strong>\, </strong><strong>$, </strong><strong>&quot;, </strong><strong>\n) only inside double quotes.</strong></li><li><strong>Single quotes (</strong><strong>&#39;...&#39;) preserve everything literally, including </strong><strong>\.</strong></li><li><strong>Double quotes (</strong><strong>&quot;...&quot;) group words into a single argument and remove themselves.</strong></li><li><strong>Spaces separate arguments unless inside quotes.</strong></li><li><strong>Multiple spaces outside quotes are ignored.</strong></li><li><strong>Unclosed quotes still return their content but may cause unexpected behavior.</strong></li><li><strong>Quotes do not nest; inner quotes are treated as normal characters.</strong></li><li><strong>Special characters (</strong><strong>$, </strong><strong>\n) behave normally outside quotes but can be escaped inside double quotes.</strong></li></ol><pre>vector&lt;string&gt; parse_args(const string &amp;input) {<br>    vector&lt;string&gt; args;<br>    string arg;<br>    bool in_quotes = false;<br>    char quote_char = &#39;\0&#39;;<br><br>    for (size_t i = 0; i &lt; input.length(); ++i) {<br>        char ch = input[i];<br><br>        if (ch == &#39;\\&#39; &amp;&amp; i + 1 &lt; input.length()) {<br>            char next_ch = input[i + 1];<br>            if (in_quotes) {<br>                if (quote_char == &#39;\&quot;&#39; &amp;&amp;<br>                    (next_ch == &#39;\\&#39; || next_ch == &#39;$&#39; || next_ch == &#39;&quot;&#39; || next_ch == &#39;\n&#39;)) {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                } else {<br>                    arg += ch;<br>                    continue;<br>                }<br>            } else {<br>                if (next_ch == &#39;\\&#39; || next_ch == &#39;$&#39; || next_ch == &#39;&quot;&#39; || next_ch == &#39;\n&#39;) {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                } else {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                }<br>            }<br>        }<br><br>        if (ch == &#39;&quot;&#39; || ch == &#39;\&#39;&#39;) {<br>            if (in_quotes &amp;&amp; ch == quote_char) {<br>                in_quotes = false;<br>                quote_char = &#39;\0&#39;;<br>            } else if (!in_quotes) {<br>                in_quotes = true;<br>                quote_char = ch;<br>            } else {<br>                arg += ch;<br>            }<br>        } else if (ch == &#39; &#39; &amp;&amp; !in_quotes) {<br>            if (!arg.empty()) {<br>                args.push_back(arg);<br>                arg.clear();<br>            }<br>        } else {<br>            arg += ch;<br>        }<br>    }<br><br>    if (!arg.empty()) {<br>        args.push_back(arg);<br>    }<br><br>    return args;<br>}</pre><p>In the parse_args function, we accept a reference to the input variable and parse it according to the rules specified above. The returned args is a revised version of the input that we can work with.</p><p>Let’s implement echo now.</p><pre> else if (command == &quot;echo&quot;) {<br>            vector&lt;string&gt; parsed_args = parse_args(input);<br>            string output;<br>            string redirectFile;<br>            bool hasRedirection = false;<br>            bool isStderrRedirection = false;<br>            bool appendToFile = false;<br><br>            for (size_t i = 1; i &lt; parsed_args.size(); ++i) {<br>                if (parsed_args[i] == &quot;&gt;&quot; || parsed_args[i] == &quot;1&gt;&quot; || parsed_args[i] == &quot;2&gt;&quot; ||<br>                    parsed_args[i] == &quot;&gt;&gt;&quot; || parsed_args[i] == &quot;1&gt;&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;) {<br>                    if (i + 1 &gt;= parsed_args.size()) {<br>                        cerr &lt;&lt; &quot;echo: syntax error near unexpected token &#39;newline&#39;\n&quot;;<br>                        return 1;<br>                    }<br>                    hasRedirection = true;<br>                    isStderrRedirection = (parsed_args[i] == &quot;2&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;);<br>                    appendToFile = (parsed_args[i] == &quot;&gt;&gt;&quot; || parsed_args[i] == &quot;1&gt;&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;);<br>                    redirectFile = parsed_args[i + 1];<br>                    break;<br>                }<br>                if (!output.empty()) {<br>                    output += &quot; &quot;;<br>                }<br>                output += parsed_args[i];<br>            }<br><br>            if (hasRedirection) {<br>                filesystem::path filePath(redirectFile);<br>                filesystem::create_directories(filePath.parent_path());<br>                ofstream fileStream;<br>                ios::openmode mode = appendToFile ? ios::app : ios::trunc;<br>                fileStream.open(redirectFile, mode);<br>                if (!fileStream) {<br>                    cerr &lt;&lt; &quot;echo: cannot open &quot; &lt;&lt; redirectFile &lt;&lt; &quot; for writing\n&quot;;<br>                    return 1;<br>                }<br>                if (isStderrRedirection) {<br>                    cerr &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>                } else {<br>                    fileStream &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>                }<br>                fileStream.close();<br>            } else {<br>                cout &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>            }<br>        }</pre><p>We add a new else if statement inside our main function. In our echo implementation, we first parse our input using the parse_args function which will return a vector of strings from our initial input. We iterate through the elements and look for our redirect characters ; &gt; , &gt;&gt; , 1&gt; , 1&gt;&gt; , 2&gt; , 2&gt;&gt; . If we find any of them, we set a boolean hasRedirection variable to true . If our redirect character is either 2&gt; or 2&gt;&gt; , we need to only redirect the standard error output to the specified file. If our redirect character is &gt;&gt; , 1&gt;&gt; , or 2&gt;&gt; , we set an appendFile boolean to true. redirectFile will be everything specified after the redirect char. If our command hasRedirection we create a filePath using our redirectFile . We also create a directory from the parent path of the file path if it doesn’t exist. We create a fileStream and open our redirectFile in append mode if appendFile is true else in truncate mode which will overwrite existing values. We then write our output to the fileStream . If hasRedirection is false, we simple cout our output.</p><h3>System Commands &amp; Everything Else</h3><p>Everything else that isn’t manually implemented will be handled by the system using the execvp command.</p><pre>else {<br>    vector&lt;string&gt; tokens = parse_args(input);<br>    execute_command(tokens);<br>  }</pre><p>Let’s build our execute command.</p><pre>void execute_command(const vector&lt;string&gt;&amp; tokens) {<br>    if (tokens.empty()) return;<br><br>    string command = tokens[0];<br>    if (get_path(command).empty()) {<br>        cout &lt;&lt; command &lt;&lt; &quot;: command not found&quot; &lt;&lt; endl;<br>        return;<br>    }<br><br>    vector&lt;char*&gt; args;<br>    int fd_out = -1;<br>    bool redirect = false;<br>    bool appendMode = false;<br>    int redirect_type = STDOUT_FILENO;<br>    string redirect_path;<br><br>    for (size_t i = 0; i &lt; tokens.size(); ++i) {<br>        if (tokens[i] == &quot;&gt;&quot; || tokens[i] == &quot;1&gt;&quot; || tokens[i] == &quot;2&gt;&quot; || tokens[i] == &quot;&gt;&gt;&quot; || tokens[i] == &quot;1&gt;&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;) {<br>            if (i + 1 &lt; tokens.size()) {<br>                redirect = true;<br>                redirect_path = tokens[i + 1];<br>                size_t last_slash = redirect_path.find_last_of(&#39;/&#39;);<br>                if (last_slash != string::npos) {<br>                    string dir_path = redirect_path.substr(0, last_slash);<br>                    mkdir(dir_path.c_str(), 0755);<br>                }<br>                appendMode = (tokens[i] == &quot;&gt;&gt;&quot; || tokens[i] == &quot;1&gt;&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;);<br>                fd_out = open(redirect_path.c_str(), O_WRONLY | O_CREAT | (appendMode ? O_APPEND : O_TRUNC), 0644);<br>                if (fd_out == -1) {<br>                    cerr &lt;&lt; &quot;Error: Cannot open file &#39;&quot; &lt;&lt; redirect_path &lt;&lt; &quot;&#39;&quot; &lt;&lt; endl;<br>                    return;<br>                }<br>                if (tokens[i] == &quot;2&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;) {<br>                    redirect_type = STDERR_FILENO;<br>                }<br>                break;<br>            } else {<br>                cerr &lt;&lt; &quot;Syntax error: expected filename after `&quot; &lt;&lt; tokens[i] &lt;&lt; &quot;`&quot; &lt;&lt; endl;<br>                return;<br>            }<br>        } else {<br>            args.push_back(const_cast&lt;char*&gt;(tokens[i].c_str()));<br>        }<br>    }<br><br>    args.push_back(nullptr);<br><br>    pid_t pid = fork();<br>    if (pid == -1) {<br>        perror(&quot;fork&quot;);<br>        return;<br>    }<br><br>    if (pid == 0) {<br>        if (redirect &amp;&amp; fd_out != -1) {<br>            dup2(fd_out, redirect_type);<br>            close(fd_out);<br>        }<br>        execvp(args[0], args.data());<br>        perror(&quot;execvp&quot;);<br>        exit(EXIT_FAILURE);<br>    } else {<br>        int status;<br>        waitpid(pid, &amp;status, 0);<br>    }<br>}<br><br></pre><p>In our execute statement, we accept an already parsed input using the parse_args method which returns a vector of strings. If it’s empty we return. We get the first item in our return vector and use our custom get_path method to validate if that system path exist. Then just like our echo method, we check for redirect characters. If we have redirect characters, we find the last slash in our redirect path and make a directory (if it doesn’t exist) using the substring between the next character after our redirect character and the last slash in the file path. Why we use the last slash is because the text after the last slash would be the file name. If we want to redirect output to the file, we need make the both the parent directory of the file as well as the file exist. We use the open function to open a file description with O_WRONLY (write only), O_CREAT (create the file if it does not already exist), O_APPEND (open in append mode if our append mode boolean is set), O_TRUNC (open in truncated mode if append mode is not set. We also set a boolean redirect_type to STDERR_FILENO (value 2: file descriptor for standard error output). By default it is set to STDOUT_FILENO (value 1: file descriptor for standard output). <a href="https://en.wikipedia.org/wiki/File_descriptor">Learn more about file descriptors here</a>.</p><p>Next, we <strong>fork a child process</strong> using fork().</p><ul><li>If fork() fails (pid == -1), we print an error and return.</li><li>If we are in the <strong>child process</strong> (pid == 0):</li><li>If redirection is enabled and fd_out is valid, we use dup2(fd_out, redirect_type) to <strong>redirect output</strong> (either stdout or stderr) to the file.</li><li>We then close the file descriptor (close(fd_out)) to free system resources.</li><li>The execvp(args[0], args.data()) call replaces the child process with the command specified in args, executing it.</li><li>If execvp fails, we print an error message and exit the child process with EXIT_FAILURE.</li></ul><p>In the <strong>parent process</strong>, we use waitpid(pid, &amp;status, 0) to wait for the child process to complete before continuing execution.</p><p>We have successfully built a functional shell that supports basic commands such as echo, cd, pwd, type, and exit, along with redirection capabilities. Additionally, our shell seamlessly delegates non-builtin commands to the underlying system for execution. With these features in place, our shell provides a solid foundation for further enhancements, such as piping, advanced process management, and improved error handling. 🚀</p><pre>#include &lt;iostream&gt;<br>#include &lt;sstream&gt;<br>#include &lt;filesystem&gt;<br>#include &lt;vector&gt;<br>#include &lt;cstdlib&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;sys/wait.h&gt;<br>#include &lt;unordered_set&gt;<br>#include &lt;string&gt;<br>#include &lt;fstream&gt;<br>#include &lt;fcntl.h&gt;<br>#include &lt;sys/types.h&gt;<br>#include &lt;sys/stat.h&gt;<br>#include &lt;termios.h&gt; <br>#include &lt;set&gt;<br><br>using namespace std;<br><br>string get_path(string command) {<br>    string path_env = getenv(&quot;PATH&quot;);<br>    string path;<br>    stringstream ss(path_env);<br><br>    while (!ss.eof()) {<br>        getline(ss, path, &#39;:&#39;);<br>        string abs_path = path + &quot;/&quot; + command;<br>        if (filesystem::exists(abs_path)) {<br>            return abs_path;<br>        }<br>    }<br>    return &quot;&quot;;<br>}<br><br>vector&lt;string&gt; parse_args(const string &amp;input) {<br>    vector&lt;string&gt; args;<br>    string arg;<br>    bool in_quotes = false;<br>    char quote_char = &#39;\0&#39;;<br><br>    for (size_t i = 0; i &lt; input.length(); ++i) {<br>        char ch = input[i];<br><br>        if (ch == &#39;\\&#39; &amp;&amp; i + 1 &lt; input.length()) {<br>            char next_ch = input[i + 1];<br>            if (in_quotes) {<br>                if (quote_char == &#39;\&quot;&#39; &amp;&amp;<br>                    (next_ch == &#39;\\&#39; || next_ch == &#39;$&#39; || next_ch == &#39;&quot;&#39; || next_ch == &#39;\n&#39;)) {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                } else {<br>                    arg += ch;<br>                    continue;<br>                }<br>            } else {<br>                if (next_ch == &#39;\\&#39; || next_ch == &#39;$&#39; || next_ch == &#39;&quot;&#39; || next_ch == &#39;\n&#39;) {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                } else {<br>                    arg += next_ch;<br>                    ++i;<br>                    continue;<br>                }<br>            }<br>        }<br><br>        if (ch == &#39;&quot;&#39; || ch == &#39;\&#39;&#39;) {<br>            if (in_quotes &amp;&amp; ch == quote_char) {<br>                in_quotes = false;<br>                quote_char = &#39;\0&#39;;<br>            } else if (!in_quotes) {<br>                in_quotes = true;<br>                quote_char = ch;<br>            } else {<br>                arg += ch;<br>            }<br>        } else if (ch == &#39; &#39; &amp;&amp; !in_quotes) {<br>            if (!arg.empty()) {<br>                args.push_back(arg);<br>                arg.clear();<br>            }<br>        } else {<br>            arg += ch;<br>        }<br>    }<br><br>    if (!arg.empty()) {<br>        args.push_back(arg);<br>    }<br><br>    return args;<br>}<br><br>void execute_command(const vector&lt;string&gt;&amp; tokens) {<br>    if (tokens.empty()) return;<br><br>    string command = tokens[0];<br>    if (get_path(command).empty()) {<br>        cout &lt;&lt; command &lt;&lt; &quot;: command not found&quot; &lt;&lt; endl;<br>        return;<br>    }<br><br>    vector&lt;char*&gt; args;<br>    int fd_out = -1;<br>    bool redirect = false;<br>    bool appendMode = false;<br>    int redirect_type = STDOUT_FILENO;<br>    string redirect_path;<br><br>    for (size_t i = 0; i &lt; tokens.size(); ++i) {<br>        if (tokens[i] == &quot;&gt;&quot; || tokens[i] == &quot;1&gt;&quot; || tokens[i] == &quot;2&gt;&quot; || tokens[i] == &quot;&gt;&gt;&quot; || tokens[i] == &quot;1&gt;&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;) {<br>            if (i + 1 &lt; tokens.size()) {<br>                redirect = true;<br>                redirect_path = tokens[i + 1];<br>                size_t last_slash = redirect_path.find_last_of(&#39;/&#39;);<br>                if (last_slash != string::npos) {<br>                    string dir_path = redirect_path.substr(0, last_slash);<br>                    mkdir(dir_path.c_str(), 0755);<br>                }<br>                appendMode = (tokens[i] == &quot;&gt;&gt;&quot; || tokens[i] == &quot;1&gt;&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;);<br>                fd_out = open(redirect_path.c_str(), O_WRONLY | O_CREAT | (appendMode ? O_APPEND : O_TRUNC), 0644);<br>                if (fd_out == -1) {<br>                    cerr &lt;&lt; &quot;Error: Cannot open file &#39;&quot; &lt;&lt; redirect_path &lt;&lt; &quot;&#39;&quot; &lt;&lt; endl;<br>                    return;<br>                }<br>                if (tokens[i] == &quot;2&gt;&quot; || tokens[i] == &quot;2&gt;&gt;&quot;) {<br>                    redirect_type = STDERR_FILENO;<br>                }<br>                break;<br>            } else {<br>                cerr &lt;&lt; &quot;Syntax error: expected filename after `&quot; &lt;&lt; tokens[i] &lt;&lt; &quot;`&quot; &lt;&lt; endl;<br>                return;<br>            }<br>        } else {<br>            args.push_back(const_cast&lt;char*&gt;(tokens[i].c_str()));<br>        }<br>    }<br><br>    args.push_back(nullptr);<br><br>    pid_t pid = fork();<br>    if (pid == -1) {<br>        perror(&quot;fork&quot;);<br>        return;<br>    }<br><br>    if (pid == 0) {<br>        if (redirect &amp;&amp; fd_out != -1) {<br>            dup2(fd_out, redirect_type);<br>            close(fd_out);<br>        }<br>        execvp(args[0], args.data());<br>        perror(&quot;execvp&quot;);<br>        exit(EXIT_FAILURE);<br>    } else {<br>        int status;<br>        waitpid(pid, &amp;status, 0);<br>    }<br>}<br><br><br>string longest_common_prefix(const vector&lt;string&gt;&amp; strings) {<br>    if (strings.empty()) return &quot;&quot;;<br><br>    string prefix = strings[0];<br>    for (size_t i = 1; i &lt; strings.size(); ++i) {<br>        size_t j = 0;<br>        while (j &lt; prefix.size() &amp;&amp; j &lt; strings[i].size() &amp;&amp; prefix[j] == strings[i][j]) {<br>            j++;<br>        }<br>        prefix = prefix.substr(0, j);<br>        if (prefix.empty()) break; <br>    }<br>    return prefix;<br>}<br><br>void enable_raw_mode(struct termios &amp;old_term) {<br>    struct termios new_term;<br>    tcgetattr(STDIN_FILENO, &amp;old_term);<br>    new_term = old_term;<br>    new_term.c_lflag &amp;= ~(ICANON | ECHO);<br>    tcsetattr(STDIN_FILENO, TCSANOW, &amp;new_term);<br>}<br><br>void disable_raw_mode(struct termios &amp;old_term) {<br>    tcsetattr(STDIN_FILENO, TCSANOW, &amp;old_term);<br>}<br><br>string read_input_with_autocomplete() {<br>    string input;<br>    struct termios old_term;<br>    enable_raw_mode(old_term);<br><br>    char ch;<br>    bool has_listed_matches = false; <br><br>    while (true) {<br>        ch = getchar();<br><br>        if (ch == &#39;\n&#39;) {<br>            cout &lt;&lt; endl;<br>            break;<br>        } <br>        else if (ch == &#39;\t&#39;) {<br>            if (!input.empty()) {<br>                if (input == &quot;ech&quot;) {<br>                    input = &quot;echo &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else if (input == &quot;exi&quot;) {<br>                    input = &quot;exit &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else if (input == &quot;typ&quot;) {<br>                    input = &quot;type &quot;;<br>                    cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                } <br>                else {<br>                    string path_env = getenv(&quot;PATH&quot;);<br>                    string path;<br>                    stringstream ss(path_env);<br>                    set&lt;string&gt; unique_matches;<br><br>                    while (!ss.eof()) {<br>                        getline(ss, path, &#39;:&#39;);<br>                        if (filesystem::exists(path)) {<br>                            for (const auto &amp;entry : filesystem::directory_iterator(path)) {<br>                                string filename = entry.path().filename().string();<br>                                if (filename.find(input) == 0 &amp;&amp; access(entry.path().c_str(), X_OK) == 0) {<br>                                    unique_matches.insert(filename);<br>                                }<br>                            }<br>                        }<br>                    }<br><br>                    vector&lt;string&gt; matches(unique_matches.begin(), unique_matches.end()); <br><br>                    if (matches.size() &gt; 1) {<br>                        string lcp = longest_common_prefix(matches);<br><br>                        if (lcp != input) {<br>                            input = lcp;<br>                            cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;  <br>                            has_listed_matches = false;<br>                        } <br>                        else {<br>                            if (!has_listed_matches) {<br>                                cout &lt;&lt; &quot;\a&quot;;<br>                                has_listed_matches = true;<br>                            } <br>                            else {<br>                                cout &lt;&lt; &quot;\n&quot;;<br>                                for (const auto &amp;match : matches) {<br>                                    cout &lt;&lt; match &lt;&lt; &quot;  &quot;;<br>                                }<br>                                cout &lt;&lt; &quot;\n$ &quot; &lt;&lt; input;<br>                                has_listed_matches = false; <br>                            }<br>                        }<br>                    } <br>                    else if (matches.size() == 1) {<br>                        input = matches[0] + &quot; &quot;;<br>                        cout &lt;&lt; &quot;\r$ &quot; &lt;&lt; input;<br>                        has_listed_matches = false;<br>                    } <br>                    else {<br>                        cout &lt;&lt; &quot;\a&quot;;<br>                        has_listed_matches = false;<br>                    }<br>                }<br>            }<br>        } <br>        else if (ch == 127 || ch == 8) {<br>            if (!input.empty()) {<br>                cout &lt;&lt; &quot;\b \b&quot;;<br>                input.pop_back();<br>                has_listed_matches = false;<br>            }<br>        } <br>        else {<br>            cout &lt;&lt; ch;<br>            input += ch;<br>            has_listed_matches = false;<br>        }<br>    }<br><br>    disable_raw_mode(old_term);<br>    return input;<br>}<br><br>int main() {<br>    cout &lt;&lt; unitbuf;<br>    cerr &lt;&lt; unitbuf;<br><br>    unordered_set&lt;string&gt; validCommands = {&quot;type&quot;, &quot;echo&quot;, &quot;exit&quot;, &quot;pwd&quot;, &quot;cd&quot;};<br><br>    while (true) {<br>        cout &lt;&lt; &quot;$ &quot;;<br>        string input = read_input_with_autocomplete();<br><br>        if (input.empty()) {<br>            continue;<br>        }<br><br>        string command = input.substr(0, input.find(&quot; &quot;));<br>        string args = input.substr(input.find(&quot; &quot;) + 1);<br><br>        if (command == &quot;exit&quot;) {<br>            return 0;<br>        }<br>        else if (command == &quot;echo&quot;) {<br>            vector&lt;string&gt; parsed_args = parse_args(input);<br>            string output;<br>            string redirectFile;<br>            bool hasRedirection = false;<br>            bool isStderrRedirection = false;<br>            bool appendToFile = false;<br><br>            for (size_t i = 1; i &lt; parsed_args.size(); ++i) {<br>                if (parsed_args[i] == &quot;&gt;&quot; || parsed_args[i] == &quot;1&gt;&quot; || parsed_args[i] == &quot;2&gt;&quot; ||<br>                    parsed_args[i] == &quot;&gt;&gt;&quot; || parsed_args[i] == &quot;1&gt;&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;) {<br>                    if (i + 1 &gt;= parsed_args.size()) {<br>                        cerr &lt;&lt; &quot;echo: syntax error near unexpected token &#39;newline&#39;\n&quot;;<br>                        return 1;<br>                    }<br>                    hasRedirection = true;<br>                    isStderrRedirection = (parsed_args[i] == &quot;2&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;);<br>                    appendToFile = (parsed_args[i] == &quot;&gt;&gt;&quot; || parsed_args[i] == &quot;1&gt;&gt;&quot; || parsed_args[i] == &quot;2&gt;&gt;&quot;);<br>                    redirectFile = parsed_args[i + 1];<br>                    break;<br>                }<br>                if (!output.empty()) {<br>                    output += &quot; &quot;;<br>                }<br>                output += parsed_args[i];<br>            }<br><br>            if (hasRedirection) {<br>                filesystem::path filePath(redirectFile);<br>                filesystem::create_directories(filePath.parent_path());<br>                ofstream fileStream;<br>                ios::openmode mode = appendToFile ? ios::app : ios::trunc;<br>                fileStream.open(redirectFile, mode);<br>                if (!fileStream) {<br>                    cerr &lt;&lt; &quot;echo: cannot open &quot; &lt;&lt; redirectFile &lt;&lt; &quot; for writing\n&quot;;<br>                    return 1;<br>                }<br>                if (isStderrRedirection) {<br>                    cerr &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>                } else {<br>                    fileStream &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>                }<br>                fileStream.close();<br>            } else {<br>                cout &lt;&lt; output &lt;&lt; &#39;\n&#39;;<br>            }<br>        }<br>        else if (command == &quot;type&quot;) {<br>            if (validCommands.find(args) != validCommands.end()) {<br>                cout &lt;&lt; args &lt;&lt; &quot; is a shell builtin\n&quot;;<br>            } else {<br>                string path = get_path(args);<br>                if (path.empty()) {<br>                    cout &lt;&lt; args &lt;&lt; &quot;: not found\n&quot;;<br>                } else {<br>                    cout &lt;&lt; args &lt;&lt; &quot; is &quot; &lt;&lt; path &lt;&lt; &quot;\n&quot;;<br>                }<br>            }<br>        }<br>        else if (command == &quot;pwd&quot;) {<br>            cout &lt;&lt; filesystem::current_path().string() &lt;&lt; &quot;\n&quot;;<br>        }<br>        else if (command == &quot;cd&quot;) {<br>            if (args == &quot;~&quot;) {<br>                chdir(getenv(&quot;HOME&quot;));<br>            } else {<br>                if (filesystem::exists(args)) {<br>                    chdir(args.c_str());<br>                } else {<br>                    cout &lt;&lt; &quot;cd: &quot; &lt;&lt; args &lt;&lt; &quot;: No such file or directory\n&quot;;<br>                }<br>            }<br>        }<br>        else {<br>            vector&lt;string&gt; tokens = parse_args(input);<br>            execute_command(tokens);<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f793f66e91ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing HTTP Compression (Gzip) in a C HTTP Server: A CodeCrafters Challenge Walkthrough]]></title>
            <link>https://innocentanyaele.medium.com/implementing-http-compression-gzip-in-a-c-http-server-a-codecrafters-challenge-walkthrough-cd9fdf9c30a6?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9fdf9c30a6</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[gzip]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 21:56:25 GMT</pubDate>
            <atom:updated>2025-01-26T21:56:25.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJn52NAei0pD1FW2Yg3-8w.png" /></figure><p>Pointers, low-level, compiled, memory management… Great! Now that we’ve successfully scared away the Python developers, let’s get started!😄</p><p>In this article, we’ll be taking on the popular CodeCrafters challenge <strong>Build your own HTTP server <em>using c.</em></strong> We will focus only on the last section of the challenge which is HTTP Compression. This section includes the exercises <strong>Compression headers</strong>, <strong>Multiple compression schemes, </strong>and <strong>Gzip compression</strong>. My walkthrough will treat all these exercises as one.</p><h3><strong>The Challenge</strong></h3><p>Our server is going to receive a request: curl -v -H &quot;Accept-Encoding: gzip&quot; <a href="http://localhost:4221/echo/abc">http://localhost:4221/echo/abc</a> . We are particularly interested in the Accept-Encoding section of the header through which the request will indicate it’s support for a compression scheme.</p><p>The Accept-Encoding header could have the following formats:</p><ul><li>Accept-Encoding: gzip</li><li>Accept-Encoding: encoding-1, encoding-2, encoding-3</li><li>Accept-Encoding: invalid-encoding-1, gzip, invalid-encoding-2</li></ul><p>We are to only accept gzip encoding and return a compressed body with a Content-Encoding: gzip or return a response without any encoding if gzip is not specified.</p><pre>Request Sample<br><br>&gt; GET /echo/foo HTTP/1.1<br>&gt; Host: localhost:4221<br>&gt; User-Agent: curl/7.81.0<br>&gt; Accept: */*<br>&gt; Accept-Encoding: gzip  // Client specifies it supports the gzip compression scheme.<br><br>Response Sample<br><br>&lt; HTTP/1.1 200 OK<br>&lt; Content-Encoding: gzip    // Server specifies that the response body is compressed with gzip.<br>&lt; Content-Type: text/plain  // Original media type of the body.<br>&lt; Content-Length: 23        // Size of the compressed body.<br>&lt; ...                       // Compressed body.<br></pre><p>This walkthrough assumes you have completed the previous exercises and already have your socket set up to accept connections. We will begin by passing a void pointer to our client file descriptor pointer in the handle_connection function.</p><pre><br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;zlib.h&gt;<br><br>void *handle_connection(void *client_fd_ptr) {<br> int client_fd = *((int *)client_fd_ptr);<br> free(client_fd_ptr); <br><br> if (client_fd == -1) { <br>  return NULL;<br> }<br> printf(&quot;Client connected\n&quot;);<br> <br> char *response_not_found = &quot;HTTP/1.1 404 Not Found\r\n\r\n&quot;;<br><br> char readBuffer[1024];<br> int bytesReceived = recv(client_fd, readBuffer, sizeof(readBuffer), 0);<br><br> if (bytesReceived == -1) {<br>  printf(&quot;Receiving failed: %s \n&quot;, strerror(errno));<br>  close(client_fd);<br>  return NULL;<br> }<br><br> int bytesSent;<br><br>}</pre><p>In this function, we</p><ul><li>Cast our client_fd_ptr pointer which is void into an integer pointer.</li><li>Free the memory that previously allocated for our client_fd_ptr</li><li>Set up a readBufer that will hold our incoming request data</li><li>Initialize a bytesSent variable, which will later be used to check for server response errors</li></ul><p>Next in our handle connection function, we duplicate our readBuffer so we can process the request path.</p><pre> char *reqPath = strdup(readBuffer);<br> reqPath = strtok(reqPath, &quot; &quot;);<br> reqPath = strtok(NULL, &quot; &quot;); <br> printf(&quot;Request path %s \n&quot;, reqPath);</pre><p>Our request path should print out something like /echo/abc .</p><p>Next we check if the request begins with /echo/ and handle accordingly.</p><pre>if (strncmp(reqPath, &quot;/echo/&quot;, 6) == 0) {<br>    reqPath = strtok(reqPath, &quot;/&quot;);  // Extract &quot;echo&quot;<br>    reqPath = strtok(NULL, &quot;/&quot;);    // Extract the content (e.g., &quot;abc&quot;)<br>    printf(&quot;Request content: %s\n&quot;, reqPath);<br><br>    int contentLength = strlen(reqPath);<br><br>    if (strncmp(reqPath, &quot;abc&quot;, 3) == 0) {<br>        int encoded = 0;<br><br>        char *headerLine = strdup(readBuffer);<br>        headerLine = strtok(headerLine, &quot;\r\n&quot;);<br><br>        while (headerLine != NULL) {<br>            if (strncmp(headerLine, &quot;Accept-Encoding&quot;, 15) == 0) {<br>                char *encoding = strtok(headerLine + 15, &quot; &quot;);<br>                while (encoding != NULL) {<br>                    if (strncmp(encoding, &quot;gzip&quot;, 4) == 0) {<br>                        // Compress and respond<br>                    } else {<br>                        encoding = strtok(NULL, &quot; &quot;);<br>                    }<br>                }<br>            }<br>            headerLine = strtok(NULL, &quot;\r\n&quot;);<br>        }<br>    }<br>}<br>else if {<br>  bytesSent = send(client_fd, response_not_found, strlen(response_not_found), 0);<br>}<br><br>if (bytesSent &lt; 0) {<br>        printf(&quot;Sending failed\n&quot;);<br>    } else if (bytesSent == 0) {<br>        printf(&quot;Client closed the connection\n&quot;);<br>    }</pre><p>In the above function we</p><ul><li>Compare the first 6 letters of the request path with our expected path /echo/ . If not echo, we return a no response found.</li><li>Use strtok to extract “echo” by specifying the delimiter “/”. This will return a pointer to the beginning of the substring “echo”, effectively tokenizing the original string.</li><li>Continue to tokenize the reqPath by passing in NULL to the strtok. By passing NULL to strtok, we resume tokenization where the previous call left off, retrieving the next token from the reqPath string and enabling us to process the entire sequence of tokens.</li><li>Check if the first 3 characters of the request path is “abc”. This can be replaced to any string you are expecting in the request. For something more dynamic, you can accept any string which will be compressed later and returned in the response body.</li><li>Instantiate an encoded variable, which we use later to indicate if we encoded a response.</li><li>Duplicate the readBuffer again to process our headlines. By applying the same strtok headerLine, we move the pointer to the next character after the first carriage return \r\n . This will effectively move us to the next section of the header which will be the HTTP/1.1. But we want to keep on going till we find an Accept-Encoding.</li><li>Set up a while loop to keep tokenizing by carriage return \r\nwhile headerLine is not null until we find the Accept-Encoding section.</li><li>Proceed to now tokenize using the “ “ separator to find the supported compression scheme or until we reach a NULL. On each iteration, we check for gzip. Once we find gzip , we do compress our body which we will implement later.</li></ul><p>Let’s proceed to implement the Gzip Compression. We will create a separate function for that. The compress function from the zlib library produces a raw DEFLATE stream, which is just the compressed data without any additional metadata. For this exercise we want to produce the full compressed data so we can later compare and verify by running Gzip command in the cli. So we will implement a more comprehensive method.</p><pre>void gzip_compress(const char *input, size_t inputLength, unsigned char *output, size_t *outputLength) {<br>    z_stream stream = {0};<br>    deflateInit2(&amp;stream, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);<br><br>    stream.next_in = (unsigned char *)input;<br>    stream.avail_in = inputLength;<br><br>    stream.next_out = output;<br>    stream.avail_out = *outputLength;<br><br>    deflate(&amp;stream, Z_FINISH);<br>    *outputLength = stream.total_out;<br><br>    deflateEnd(&amp;stream);<br>}</pre><p>In this function we</p><ul><li>Accept a pointer to the body to compress, the size of the body, a pointer to our output, and the size of our output</li><li>Initialize a z_stream structure to manage the compression process</li><li>Initialize the stream with our gzip headers. Z_BEST_COMPRESSION (Compression level), Z_DEFLATED (specify the DEFLATE compression algorithm), 15 + 16 (Window size 15 bits and +16 enables the gzip header/footer for the metadata), 8 (Memory allocation level) and Z_DEFAULT_STRATEGY (Default compression strategy).</li><li>Pass the headers to the deflateInit2</li><li>Set a pointer to the output buffer (where the compressed data will be written)</li><li>Set the size of the output buffer (number of bytes available for writing)</li><li>Perform the compression. Z_FINISH indicates that this is the final chunk of data to be compressed.</li><li>Update the output length with the total number of bytes written to the output buffer</li><li>Clean up and free resources used by deflateInit2</li></ul><p>The next step is compress the response and send with the appropriate headers.</p><pre>unsigned char compressedBody[1024];<br>uLong compressedLength = sizeof(compressedBody);<br><br>gzip_compress(reqPath, contentLength, compressedBody, &amp;compressedLength);<br><br>char response[2048];<br>int headersLength = snprintf(response, 2048,<br>    &quot;HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Type: text/plain\r\nContent-Length: %lu\r\n\r\n&quot;, <br>    compressedLength);<br>memcpy(response + headersLength, compressedBody, compressedLength);<br><br>bytesSent = send(client_fd, response, headersLength + compressedLength, 0);</pre><p>In this step we</p><ul><li>Assign an unsigned char of 1024 bytes to hold our compressed body</li><li>Compress our response by passing in the request path data, length of the request path, our output, and compressed length</li><li>Assign a response character array of 2048 bytes to construct the HTTP response: We allocate a buffer response of size 2048 bytes to construct the HTTP response. This buffer will hold the HTTP headers and the compressed response body.</li><li>Construct the HTTP response headers with the compressed length: We use snprintf to construct the HTTP response headers, including the Content-Encoding: gzip and Content-Length headers, which specify the length of the compressed response body.</li><li>Copy the compressed body into the response buffer: We use memcpy to copy the compressed response body into the response buffer, immediately following the HTTP headers.</li><li>Send the response to the client: We use the send function to send the constructed HTTP response to the client.</li></ul><p>In the last step we handle the uncomperessed responses. If Gzip is not specified in the Accept-Encoding header, the server sends the response uncompressed.</p><pre>if (encoded == 0) {<br>    char response[512];<br>    sprintf(response, &quot;HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s&quot;, contentLength, reqPath);<br>    printf(&quot;Sending response: %s\n&quot;, response);<br>    bytesSent = send(client_fd, response, strlen(response), 0);<br>}</pre><p>We can also print the contents of our response headers and compressed body for debugging purposes.</p><pre>printf(&quot;Response Headers:\n%.*s&quot;, headersLength, response);<br><br>// Print compressed body as hex<br>printf(&quot;Compressed Body (hex):\n&quot;);<br>for (uLong i = 0; i &lt; compressedLength; i++) {<br>printf(&quot;%02x &quot;, compressedBody[i]);<br>if ((i + 1) % 16 == 0) { // Newline after every 16 bytes<br> printf(&quot;\n&quot;);<br>}<br>}<br>printf(&quot;\n&quot;);</pre><p>Let’s compile and run our code. Don’t forget to link the zlib library.gcc -o server server.c -lz; ./server</p><p>We can test our server with curl with an appropriate request. This should print the appropriate response headers and hex of the compressed body.</p><pre>curl -v -H &quot;Accept-Encoding: invalid-encoding-1, gzip, invalid-encoding-2&quot; http://localhost:4221/echo/abc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*N1cks2H5JIjJuGDkUhWp5g.png" /></figure><p>To verify the compressed data, we can compare it with the output of the gzip command using hexdump.</p><pre>echo -n &quot;abc&quot; | gzip | hexdump -C</pre><p>This should give us a response like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*9Xkvns8mCMt9HzTAYhOTDQ.png" /></figure><p>We have similar compressed data as shown above.</p><p>In this walkthrough, we implemented HTTP compression in a C-based HTTP server, focusing on Gzip compression. We explored parsing the Accept-Encoding header to identify supported compression schemes, compressing response bodies using the zlib library, and sending compressed responses with appropriate headers. I hope this was helpful.</p><p>Complete code below</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;zlib.h&gt;<br><br>void gzip_compress(const char *input, size_t inputLength, unsigned char *output, size_t *outputLength) {<br>    z_stream stream = {0};<br>    deflateInit2(&amp;stream, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);<br><br>    stream.next_in = (unsigned char *)input;<br>    stream.avail_in = inputLength;<br><br>    stream.next_out = output;<br>    stream.avail_out = *outputLength;<br><br>    deflate(&amp;stream, Z_FINISH);<br>    *outputLength = stream.total_out;<br><br>    deflateEnd(&amp;stream);<br>}<br><br>void *handle_connection(void *client_fd_ptr) {<br>    int client_fd = *((int *)client_fd_ptr);<br>    free(client_fd_ptr);<br><br>    if (client_fd == -1) {<br>        return NULL;<br>    }<br>    printf(&quot;Client connected\n&quot;);<br><br>    char *response_not_found = &quot;HTTP/1.1 404 Not Found\r\n\r\n&quot;;<br>    char readBuffer[1024];<br>    int bytesReceived = recv(client_fd, readBuffer, sizeof(readBuffer), 0);<br><br>    if (bytesReceived == -1) {<br>        printf(&quot;Receiving failed: %s\n&quot;, strerror(errno));<br>        close(client_fd);<br>        return NULL;<br>    }<br><br>    int bytesSent;<br>    char *reqPath = strdup(readBuffer);<br>    reqPath = strtok(reqPath, &quot; &quot;);<br>    reqPath = strtok(NULL, &quot; &quot;);<br>    printf(&quot;Request path: %s\n&quot;, reqPath);<br><br>    if (strncmp(reqPath, &quot;/echo/&quot;, 6) == 0) {<br>        reqPath = strtok(reqPath, &quot;/&quot;);<br>        reqPath = strtok(NULL, &quot;/&quot;);<br><br>        int contentLength = strlen(reqPath);<br>        if (strncmp(reqPath, &quot;abc&quot;, 3) == 0) {<br>            int encoded = 0;<br>            char *headerLine = strdup(readBuffer);<br>            headerLine = strtok(headerLine, &quot;\r\n&quot;);<br><br>            while (headerLine != NULL) {<br>                if (strncmp(headerLine, &quot;Accept-Encoding&quot;, 15) == 0) {<br>                    char *encoding = strtok(headerLine + 15, &quot; &quot;);<br>                    while (encoding != NULL) {<br>                        if (strncmp(encoding, &quot;gzip&quot;, 4) == 0) {<br>                            unsigned char compressedBody[1024];<br>                            uLong compressedLength = sizeof(compressedBody);<br><br>                            gzip_compress(reqPath, contentLength, compressedBody, &amp;compressedLength);<br><br>                            char response[2048];<br>                            int headersLength = snprintf(response, 2048,<br>                                &quot;HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Type: text/plain\r\nContent-Length: %lu\r\n\r\n&quot;,<br>                                compressedLength);<br><br>                            memcpy(response + headersLength, compressedBody, compressedLength);<br>                            bytesSent = send(client_fd, response, headersLength + compressedLength, 0);<br><br>                            encoded = 1;<br>                            break;<br>                        }<br>                        encoding = strtok(NULL, &quot; &quot;);<br>                    }<br>                    break;<br>                }<br>                headerLine = strtok(NULL, &quot;\r\n&quot;);<br>            }<br><br>            if (encoded == 0) {<br>                char response[512];<br>                sprintf(response, &quot;HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s&quot;, contentLength, reqPath);<br>                bytesSent = send(client_fd, response, strlen(response), 0);<br>            }<br>        }<br>    } else {<br>        bytesSent = send(client_fd, response_not_found, strlen(response_not_found), 0);<br>    }<br><br>    if (bytesSent &lt; 0) {<br>        printf(&quot;Sending failed\n&quot;);<br>    } else if (bytesSent == 0) {<br>        printf(&quot;Client closed the connection\n&quot;);<br>    }<br>  <br>    free(reqPath);<br><br>    close(client_fd);<br>    return NULL;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9fdf9c30a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fault-Tolerant Systems: Implementing Distributed Message Queues with RabbitMQ]]></title>
            <link>https://blog.devops.dev/fault-tolerant-systems-implementing-distributed-message-queues-with-rabbitmq-c13936674c6c?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13936674c6c</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 09:24:28 GMT</pubDate>
            <atom:updated>2024-08-12T18:19:13.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZUduAKfeNn8sqAC4HZPIg.jpeg" /></figure><p>Fault tolerance is a very integral part of distributed systems. How does your system respond to network issues or server crashes in the middle of processing a request? How do you offload time consuming processes or decouple processing tasks to be handled asynchronously by background workers. By implementing fault tolerance mechanisms your system is able to handle unexpected failures gracefully and ensure operations are completed reliably.</p><p>Message queues are often used to ensure fault tolerance in a system. They coordinate the flow of data between parts of your system. In this writeup, we will have an idea on how to implement message queues using RabbitMQ.</p><p>RabbitMQ is an open-source message broker that uses a combination of queues, exchanges, and bindings to route, store and process messages effectively. Learn More here — <a href="https://www.rabbitmq.com/">RabbitMQ: One broker to queue them all | RabbitMQ</a></p><h4>Prerequisites and Imports</h4><ul><li><a href="https://www.rabbitmq.com/docs/download">Installing RabbitMQ | RabbitMQ</a></li></ul><pre>import asyncio<br>import aio_pika<br>from loguru import logger<br>import json<br>from aio_pika import exceptions<br></pre><h4>Getting our connection</h4><p>Our first step is adding a method to get the connection to our RabbitMQ. We pass in our host localhost, port 5672, username guestand password guest.</p><pre>async def get_connection():<br>    try:<br>        connection = await aio_pika.connect_robust(<br>            host=host,<br>            port=int(port),<br>            login=username,<br>            password=password,<br>            timeout=30,<br>        )<br>        logger.info(&quot;RabbitMQ connection established successfully&quot;)<br>        return connection<br>    except aio_pika.exceptions.AMQPConnectionError as e:<br>        logger.error(f&quot;Failed to connect to RabbitMQ: {e}&quot;)<br>        return None</pre><h4>Getting channel</h4><p>We then add a method to declare a queue where we are going to publish our messages.</p><pre>DLQ_NAME = &quot;&quot; #dead letter queue<br><br>async def get_channel(connection, queue_name=&quot;main-queue&quot;):<br>    if connection is None:<br>        logger.error(&quot;No connection available to get a channel&quot;)<br>        return None<br><br>    try:<br>        channel = await connection.channel()<br><br>        # Declare the DLQ<br>        await channel.declare_queue(DLQ_NAME, durable=True)<br><br>        # Check if the main queue exists<br>        try:<br>            await channel.declare_queue(queue_name, passive=True)<br>            logger.info(f&quot;Queue {queue_name} already exists&quot;)<br>        except exceptions.ChannelClosed as e:<br>            if &quot;NOT_FOUND&quot; in str(e):<br>                logger.info(<br>                    f&quot;Queue {queue_name} does not exist, declaring it with DLQ settings&quot;<br>                )<br>                await channel.declare_queue(<br>                    queue_name,<br>                    durable=True,<br>                    arguments={<br>                        &quot;x-dead-letter-exchange&quot;: &quot;&quot;,<br>                        &quot;x-dead-letter-routing-key&quot;: DLQ_NAME,<br>                    },<br>                )<br>            else:<br>                logger.error(f&quot;Channel closed with error: {e}&quot;)<br>                return None<br>        except exceptions.QueueDoesNotExist:<br>            logger.info(<br>                f&quot;Queue {queue_name} does not exist, declaring it with DLQ settings&quot;<br>            )<br>            await channel.declare_queue(<br>                queue_name,<br>                durable=True,<br>                arguments={<br>                    &quot;x-dead-letter-exchange&quot;: &quot;&quot;,<br>                    &quot;x-dead-letter-routing-key&quot;: DLQ_NAME,<br>                },<br>            )<br><br>        return channel<br>    except exceptions.AMQPChannelError as e:<br>        logger.error(f&quot;Failed to create a channel or declare a queue: {e}&quot;)<br>        return None</pre><p>Our get channel accepts a connection for which we have implemented a method for as well the name of queue.</p><p>We also declare a dead letter queue variable DLQ_NAME. In distributed systems, some message may fail to process due to several reasons such as bugs or invalid data structure. We establish a dead letter queue where these failed messages will be sent to so we can further analyze.</p><p>Our code declares a dead letter queue with durable option set to true ensuring that even when our broker restarts, our queue will survive.</p><p>We then check if our main queue already exists. If it doesn’t exist, we declare it with the specific arguments x-dead-letter-exchange specifying that dead letter messages should be sent to the default exchange and x-dead-letter-routing-key specifying that messages should be routed to the DLQ_NAMEqueue.</p><h4><strong>Publish message</strong></h4><p>In our publish message function, we pass in our message body as well our queue name. This enables us to publish a message body to our queue to be be consumed by the workers.</p><pre>async def publish_message(message_body, queue_name=&quot;main-queue&quot;):<br>    connection = await get_connection()<br>    if connection is None:<br>        logger.error(&quot;No connection available for publishing&quot;)<br>        return<br><br>    try:<br>        async with connection:<br>            channel = await connection.channel()<br>            await channel.default_exchange.publish(<br>                aio_pika.Message(body=message_body.encode()),<br>                routing_key=queue_name,<br>            )<br>            logger.info(f&quot;Sent message to {queue_name}: {message_body}&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Failed to publish message: {e}&quot;)</pre><p>In this function our connection is created using our previous get_connection function and an asynchronous process it started to publish our message, passing in the queue_name as the routing key.</p><h4>Consuming messages</h4><p>Once the message is published to the queue, we need to consume it.</p><pre>async def consume_messages(queue_name):<br>    connection = await get_connection()<br>    channel = await get_channel(connection, queue_name=queue_name)<br><br>    if channel is None:<br>        logger.error(&quot;Failed to get channel&quot;)<br>        return<br><br>    queue = await channel.declare_queue(queue_name, durable=True)<br>    await queue.consume(callback, no_ack=False)<br><br>    logger.info(&quot;Waiting for messages&quot;)<br>    await asyncio.Future()  # Run forever<br><br><br><br>asyncio.create_task(consume_messages())<br>await publish_message(&quot;Hello, world!&quot;, queue_name=&quot;main-queue&quot;)</pre><p>Our consume_messages function establishes a connection to the RabbitMQ channel and declares the queue from which we want to consume messages, setting durable=True to ensure the queue persists across broker restarts. We then consume messages from the queue using queue.consume, passing in a callback function (to be defined later) and setting no_ack=False. This means the queue will not automatically acknowledge a processed message; instead, we handle the acknowledgment manually. Acknowledging a message removes it from the queue, confirming successful processing. If an error occurs during processing, the message can be requeued or sent to a Dead Letter Queue for further analysis.</p><p>We keep the consume_messages function running indefinitely by using await asyncio.Future().</p><p>In the main function, we create an async task to start consuming our messagings in the background and publish an Hello worldmessage to test it out.</p><h4>Callback message</h4><p>In our callback function, we receive the message body from our consume_messages function. If processing the message fails, we want to retry it up to 5 times before rejecting it and moving it to a Dead Letter Queue (DLQ). To avoid overwhelming the system, we implement an exponentially increasing delay between each retry attempt. If the message is successfully processed without any exceptions, we acknowledge it, removing it from the queue. Otherwise, we continue retrying until the maximum retries are reached.</p><p>If the message fails to process due to a JSONDecodeError, indicating that the message body cannot be properly loaded as JSON, retrying would be unnecessary. In such cases, we simply reject the message without requeuing it.</p><pre>MAX_REQUEUE_ATTEMPTS = 5<br><br>async def callback(message: aio_pika.IncomingMessage):<br>    retry_count = 0<br>    max_retries = 5  # Adjust this value based on your needs<br>    backoff_delay = 1  # Initial delay in seconds<br><br>    while retry_count &lt;= max_retries:<br>        try:<br>            # Decode the message body<br>            json_message_body = json.loads(message.body.decode())<br><br>            # Process the message<br>            await process_function(json_message_body)<br><br>            # If successful, acknowledge the message and exit the loop<br>            await message.ack()<br>            return<br><br>        except json.JSONDecodeError as e:<br>            logger.error(f&quot;Failed to decode JSON: {e}&quot;)<br>            await message.reject(requeue=False)<br>            return  # Don&#39;t retry for JSON decode errors<br><br>        except Exception as e:<br>            logger.error(<br>                f&quot;Failed to process message: {e} (Retry {retry_count+1}/{max_retries})&quot;<br>            )<br>            retry_count += 1<br><br>            if retry_count &lt;= max_retries:<br>                await asyncio.sleep(backoff_delay)  # Wait before retrying<br>                backoff_delay *= 2  # Exponential backoff<br>            else:<br>                logger.error(<br>                    &quot;Max retries exceeded. Moving message to dead letter queue.&quot;<br>                )<br>                # Here you would implement the logic to move the message to a dead letter queue<br>                # For example:<br>                # await move_to_dead_letter_queue(message)<br>                await message.reject(requeue=False)<br>                return</pre><p>Remember, even in coding, it’s okay to take a break — sometimes the best solutions come when you step away for a bit. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13936674c6c" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/fault-tolerant-systems-implementing-distributed-message-queues-with-rabbitmq-c13936674c6c">Fault-Tolerant Systems: Implementing Distributed Message Queues with RabbitMQ</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Real-Time Communication: Scaling WebSockets with Redis Pub/Sub]]></title>
            <link>https://blog.devops.dev/distributed-real-time-communication-scaling-websockets-with-redis-pub-sub-9a7db4f81cd0?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7db4f81cd0</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 09:23:13 GMT</pubDate>
            <atom:updated>2024-08-12T18:19:20.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzFJZvrGG0dEJ9u5lmMIPA.jpeg" /></figure><p>How are websockets handled at scale? In a simple websocket implementation, your client connects to the server and the associated websocket is managed and stored in memory — usually in a dictionary. In any subsequent request, you are able to retrieve the associated socket for client Afrom your dictionary and send a message to client Busing their websockets stored in their dictionary.</p><p>But what happens when you have your client load balanced across multiple servers. In a situation where client A is load balanced to server A and client B is load balanced to server B. How does client A send a message via websockets to client B.</p><p>To handle websockets at scale, we can use a redis pub/sub architecture to manage communications across all the instances of our server. Since websockets cannot be directly stored in redis, we can use redis to store the metadata of our websocket connections such as connection IDs, user IDs, etc. but that is something perhaps for another article. In this article, we will be solely focusing on how redis pub/sub feature. We will be using fastapi Websocket library and redis pub/sub for this article.</p><p>Pub/Sub stands for publish/subscribe, a messaging pattern where messages are published to channels without knowing who or what will consume them. In redis pub/sub, the publisher sends the message to a redis channel, where all the instances of our server will be listening for them.</p><h4><strong>How will it work</strong></h4><ul><li>Our server once started will subscribe to a specified channel and listen for messages</li><li>We will maintain a dictionary say web socket dictionary that will hold our unique client id as key and their websocket as values</li><li>When a client connects via a websocket to the server, the server will store their websocket together with their client id in their dictionary</li><li>When client A from server Awants to send a message to client B in server B, server A will publish the message to the channel</li><li>All servers listening to the channel will receive the message</li><li>Each server will check in the web socket dictionary client B unique id exists.</li><li>If it does exist, the server will send the message to the associated websocket of that client B</li></ul><h4>Implementing our redis pub/sub class</h4><p>We first implement our redis pub/sub class. This class is responsible for managing our redis pub/sub service. We setup this class using a Singleton pattern to enable us to have only one instance managing the connection across the application. This way, we can avoid creating redundant connections to Redis.</p><p><a href="https://www.geeksforgeeks.org/singleton-design-pattern/">Singleton Method Design Pattern — GeeksforGeeks</a></p><pre>import asyncio<br>import redis.asyncio as aioredis<br>import json<br>from loguru import logger<br><br><br>class RedisPubSubManager:<br>    _instance = None<br><br>    def __new__(cls, *args, **kwargs):<br>        if not cls._instance:<br>            cls._instance = super(RedisPubSubManager, cls).__new__(cls)<br>        return cls._instance<br><br>    &quot;&quot;&quot;<br>    Initializes the RedisPubSubManager.<br><br>    Args:<br>        host (str): Redis server host.<br>        port (int): Redis server port.<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        redis_host = host<br>        redis_port = port<br>        redis_password = password<br>        self.redis_url = f&quot;redis://:{redis_password}@{redis_host}:{redis_port}&quot;<br>        self.pubsub = None<br>        self.redis_connection = None<br><br><br>    async def _get_redis_connection(self) -&gt; aioredis.Redis:<br>        &quot;&quot;&quot;<br>        Establishes a connection to Redis.<br><br>        Returns:<br>            aioredis.Redis: Redis connection object.<br>        &quot;&quot;&quot;<br>        return aioredis.Redis.from_url(https://medium.com/self.redis_url,%20decode_responses=True)<br><br>    async def connect(self):<br>        &quot;&quot;&quot;<br>        Connects to the Redis server and initializes the pubsub client.<br>        &quot;&quot;&quot;<br>        self.redis_connection = await self._get_redis_connection()<br>        self.pubsub = self.redis_connection.pubsub()<br>        logger.info(f&quot;Connected to Redis at {self.redis_url} with pubsub {self.pubsub}&quot;)<br>        try:<br>            await self.redis_connection.ping()<br>            logger.info(f&quot;successfully pinged redis server&quot;)<br>            # yield self.redis_connection<br>        except Exception as e:<br>            print(f&quot;Failed to connect to Redis: {e}&quot;)<br>            raise  # Re-raise the exception to signal failure<br><br>    async def disconnect(self):<br>        &quot;&quot;&quot;Disconnects from the Redis server and closes resources.&quot;&quot;&quot;<br>        if self.pubsub:<br>            await self.pubsub.close()<br>        if self.redis_connection:<br>            await self.redis_connection.close()<br>            await self.redis_connection.wait_closed()<br><br>    async def publish(self, topic: str, message) -&gt; None:<br>        &quot;&quot;&quot;<br>        Publishes a message to a specific Redis channel.<br><br>        Args:<br>            topic (str): Channel or room ID.<br>            message (str): Message to be published.<br>        &quot;&quot;&quot;<br>        logger.info(f&quot;message being published {message}&quot;)<br>        logger.info(f&quot;topic being published to {topic}&quot;)<br>        await self.redis_connection.publish(topic, message)<br><br>    async def subscribe(self, topic: str) -&gt; aioredis.client.PubSub:<br>        &quot;&quot;&quot;<br>        Subscribes to a Redis channel.<br><br>        Args:<br>            topic (str): Channel or room ID to subscribe to.<br><br>        Returns:<br>            aioredis.client.PubSub: PubSub object for the subscribed channel.<br>        &quot;&quot;&quot;<br>        await self.pubsub.subscribe(topic)<br>        return self.pubsub<br><br>    async def unsubscribe(self, topic: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Unsubscribes from a Redis channel.<br><br>        Args:<br>            topic (str): Channel or room ID to unsubscribe from.<br>        &quot;&quot;&quot;<br>        await self.pubsub.unsubscribe(topic)<br><br>    async def listen(self) -&gt; None:<br>        &quot;&quot;&quot;<br>        Listens for messages on the subscribed channels.<br>        &quot;&quot;&quot;<br>        async for message in self.pubsub.listen():<br>            if message[&quot;type&quot;] == &quot;message&quot;:<br>                print(f&quot;Received message: {message[&#39;data&#39;]}&quot;)<br><br><br># # Example usage<br>async def main():<br>    manager = RedisPubSubManager()<br>    await manager.connect()<br><br>    # Subscribe to a topic<br>    await manager.subscribe(&#39;test-channel&#39;)<br><br>    # Run the listener in the background<br>    asyncio.create_task(manager.listen())<br><br>    # Publish a message<br>    await manager.publish(&#39;test-channel&#39;, &#39;Hello, Redis!&#39;)<br><br>    # Keep the main thread running<br>    await asyncio.sleep(10)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>The _get_redis_connection is responsible for creating the redis connection object.</p><p>The connect method is responsible for initializing the connection to the Redis server and setting up the Pub/Sub client.</p><p>The disconnect method is used to gracefully close the connection to the Redis server and the Pub/Sub client.</p><p>The publish method is used to send (publish) a message to a specific Redis channel (or topic). It logs the message and the topic before publishing, which is useful for debugging and monitoring.</p><p>The subscribe method subscribes to a specified Redis channel (topic). When a subscription is successful, the method returns the PubSub object, which allows the application to start receiving messages from that channel.</p><p>The unsubscribe method allows the application to stop receiving messages from a specified Redis channel.</p><p>The listen method continuously listens for messages on the subscribed channels.</p><p>The example usage at the end of the script shows how to use the RedisPubSubManager class:</p><ul><li><strong>Connecting</strong> to the Redis server.</li><li><strong>Subscribing</strong> to a topic (&#39;test-channel&#39;).</li><li><strong>Listening</strong> for messages on that topic.</li><li><strong>Publishing</strong> a message to the topic.</li></ul><h4>Chat connection manager</h4><p>The ChatConnectionManager class is responsible for managing WebSocket connections and facilitating the communication between clients across multiple servers. It is implemented with a singleton pattern to ensure only one instance is made.</p><pre>import json<br>from typing import Dict<br>from fastapi import WebSocket<br>import asyncio<br>from loguru import logger<br><br>channel = &quot;main_channel&quot;<br><br>class ChatConnectionManager:<br>    _instance = None<br><br>    def __new__(cls, *args, **kwargs):<br>        if not cls._instance:<br>            cls._instance = super(ChatConnectionManager, cls).__new__(cls)<br>        return cls._instance<br><br>    def __init__(self):<br>        self.active_connections: Dict[str, WebSocket] = {}<br>        self.redis_pub_sub_manager = RedisPubSubManager()<br><br>    async def connect(self, client_id: str, websocket: WebSocket):<br>        await websocket.accept()<br>        self.active_connections[client_id] = websocket<br>        logger.info(f&quot;Client {client_id} connected.&quot;)<br><br>    async def handle_web_receive_message(self, message: str, recipient_client_id: str):<br>        data_to_publish = json.dumps({<br>            &quot;action&quot;: &quot;send_message&quot;,<br>            &quot;message&quot;: message,<br>            &quot;client_id&quot;: recipient_client_id<br>        })<br>        await self.redis_pub_sub_manager.publish(channel, data_to_publish)<br>        logger.info(f&quot;Published message to channel {channel} for client {recipient_client_id}.&quot;)<br><br>    async def disconnect(self, client_id: str):<br>        if client_id in self.active_connections:<br>            await self.redis_pub_sub_manager.publish(channel, json.dumps({<br>                &quot;action&quot;: &quot;disconnect&quot;,<br>                &quot;client_id&quot;: client_id<br>            }))<br>            del self.active_connections[client_id]<br>            logger.info(f&quot;Client {client_id} disconnected and removed from active connections.&quot;)<br><br>    async def subscribe_to_chat_channel(self, channel: str):<br>        logger.info(f&quot;Subscribing to chat channel {channel}.&quot;)<br>        websocket_chat_pub_subscriber = await self.redis_pub_sub_manager.subscribe(channel)<br>        task = asyncio.create_task(self._pubsub_data_reader(websocket_chat_pub_subscriber))<br>        return task<br><br>    async def _pubsub_data_reader(self, websocket_chat_pub_subscriber):<br>        try:<br>            async for message in websocket_chat_pub_subscriber.listen():<br>                logger.info(f&quot;Received message from pubsub: {message}&quot;)<br>                await self._handle_pubsub_message(message)<br>        except asyncio.CancelledError:<br>            logger.error(f&quot;Pub/Sub subscriber for {websocket_chat_pub_subscriber} has been cancelled.&quot;)<br>            raise<br><br>    async def _handle_pubsub_message(self, data):<br>        try:<br>            if isinstance(data, str):<br>                try:<br>                    data = json.loads(data)<br>                    logger.info(f&quot;JSON loaded message from pubsub: {data}&quot;)<br>                except json.JSONDecodeError as e:<br>                    logger.error(f&quot;Failed to decode JSON: {e}&quot;)<br>                    return<br><br>            if data and data.get(&quot;channel&quot;) == channel:<br>                message = data.get(&quot;data&quot;)<br>                if isinstance(message, str):<br>                    try:<br>                        message = json.loads(message)<br>                    except json.JSONDecodeError as e:<br>                        logger.error(f&quot;Failed to decode message JSON: {e}&quot;)<br>                        return<br><br>                if isinstance(message, dict):<br>                    action = message.get(&quot;action&quot;)<br>                    logger.info(f&quot;Message action: {action}&quot;)<br><br>                    if action == &quot;send_message&quot;:<br>                        client_id = message.get(&#39;client_id&#39;)<br>                        if client_id in self.active_connections:<br>                            client_socket = self.active_connections[client_id]<br>                            await client_socket.send_text(json.dumps({&quot;message&quot;: message.get(&quot;message&quot;)}))<br>                            logger.info(f&quot;Sent message to client {client_id}.&quot;)<br>                    elif action == &quot;disconnect&quot;:<br>                        logger.info(f&quot;Processing disconnect action for client {message.get(&#39;client_id&#39;)}.&quot;)<br>                        # Implement disconnect handling logic here<br><br>        except Exception as e:<br>            logger.error(f&quot;Failed to handle pubsub message: {e}&quot;)<br>            raise</pre><p>Our active connection dictionary holds the active Websocket connects with the client_id as the key and the websocket as the value.</p><p>The RedisPubSubManager we created earlier is initialized. This will handle operatios such as subscribing to channels and publishing messages.</p><p>When a new WebSocket connection is established, the connect method accepts the connection and stores it in the active connection</p><p>handle_web_receive_message method handles message received from a Websocket client. It formats the message to json includes an action send_message , the message content, and the recipient client ID. The message is then published to the Redis channel, allowing it to be distributed across all server instances.</p><p>When a client disconnects, this diconnectpublishes a action to the Redis channel to be received by all instances of the server. It also removes the client&#39;s WebSocket connection from the active_connections dictionary to free up resources and prevent any further communication with that client.</p><p>subscribe_to_chat_channel<strong> </strong>subscribes the server instance to a specified Redis channel. It creates a background task to continuously listen for incoming messages on that channel using the _pubsub_data_reader method.</p><p>_pubsub_data_reader<strong> </strong>continuously listens for messages from the subscribed Redis channel. When a message is received, it is passed to the _handle_pubsub_message method for processing. If the task is cancelled, an error is logged, and the cancellation is raised.</p><p>_handle_pubsub_message<strong> </strong>processes messages received from the Redis Pub/Sub system. It first checks if the message is a string and attempts to decode it as JSON. If the message is intended for the main_channel, it further processes the content, determining the action (send_message or disconnect).</p><ul><li>send_message: If the action is send_message, the method checks if the recipient client is connected to the current server instance. If they are, the message is sent to the client&#39;s WebSocket.</li><li>disconnect: if the action is disconnect, you can then go ahead to process any relevant actions</li></ul><h4>Setting up the websocket server</h4><p>This WebSocket route allows clients to establish a real-time, bi-directional connection with the server. The route is managed by FastAPI and uses the ChatConnectionManager to handle WebSocket connections, messaging, and disconnections.</p><pre>import json<br>from typing import Optional<br>from dependency_injector.wiring import inject, Provide<br>from fastapi import (<br>    APIRouter,<br>    WebSocket,<br>    Depends,<br>    Query,<br>    WebSocketDisconnect,<br>    HTTPException,<br>)<br>from chat_connection_manager import ChatConnectionManager<br>from loguru import logger<br><br>router = APIRouter()<br><br>chat_connection_manager = ChatConnectionManager()<br><br><br>@router.websocket(&quot;/ws&quot;)<br>async def ws(<br>    websocket: WebSocket,<br>    client_id: str,<br>):<br>    try:<br>        await chat_connection_manager.connect(<br>            client_id,<br>            websocket,<br>        )<br>        while True:<br>            data = await websocket.receive_text()<br>            logger.info(f&quot;Received data: {data}&quot;)<br>            data = json.loads(data)<br>            logger.info(f&quot;parsed json data {data}&quot;)<br>            if data.get(&quot;action&quot;) == &quot;send_message&quot;:<br>                await chat_connection_manager.handle_web_receive_message(<br>                        data, websocket.app.state<br>                    )<br> <br>            if data.get(&quot;action&quot;) == &quot;disconnect&quot;:<br>                  await chat_connection_manager.disconnect(<br>                      client_id,<br>                  )<br><br>    except WebSocketDisconnect:<br>        await chat_connection_manager.disconnect(<br>            client_id<br>        )</pre><p>client_id: str: The client ID is passed as a query parameter when the WebSocket connection is established. This ID uniquely identifies the client and is used to manage the connection within the ChatConnectionManager.</p><p>await chat_connection_manager.connect(client_id, websocket): When a client connects, this method accepts the connection and stores it in the ChatConnectionManager, associating the WebSocket connection with the client_id.</p><p>data = await websocket.receive_text(): This line waits for the client to send a message. Once a message is received, it&#39;s logged and parsed from JSON format.</p><p>await chat_connection_manager.handle_web_receive_message(data, websocket.app.state): If the received message is an action to send a message (&quot;action&quot;: &quot;send_message&quot;), this method handles the message by publishing it to the appropriate channel, leveraging the Redis Pub/Sub mechanism.</p><p>await chat_connection_manager.disconnect(client_id): If the client sends a disconnect action (&quot;action&quot;: &quot;disconnect&quot;), or if the connection is lost (e.g., the client disconnects unexpectedly), the disconnect method is called. This method removes the client from the active connections list and notifies other servers of the disconnection via Redis.</p><p>except WebSocketDisconnect:: This block catches the WebSocketDisconnect exception, which is raised when the client disconnects. The server then gracefully handles the disconnection by calling the disconnect method.</p><p>I hope this was helpful and at least gives you an idea on how websockets can be scaled using redis pub/sub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7db4f81cd0" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/distributed-real-time-communication-scaling-websockets-with-redis-pub-sub-9a7db4f81cd0">Distributed Real-Time Communication: Scaling WebSockets with Redis Pub/Sub</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Cache Performance: Hashing function calls and Implementing Composite Caches with Local…]]></title>
            <link>https://blog.devops.dev/optimizing-cache-performance-hashing-function-calls-and-implementing-composite-caches-with-local-9e1f7a6d7255?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e1f7a6d7255</guid>
            <category><![CDATA[max-size]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lru-cache]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 09:22:12 GMT</pubDate>
            <atom:updated>2024-08-12T18:19:26.338Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Optimizing Cache Performance: Hashing function calls and Implementing Composite Caches with Local Memory and Redis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZtzEJb1VH-KJpOhHCu-Vg.jpeg" /></figure><p>If you have ever worked on the backend of an application that was going to serve users at a large scale, you have probably worried about how to minimize the response time of your server.</p><p>One effective way this is done is by caching frequently accessed data from the database in memory. This can introduce a bit more complexity to your setup as you have to worry about specific data storage formats for each type of request. If you need to, for instance, cache database calls for the user table and the user posts table, you will need to define the respective structures for each.</p><p>An alternative approach involves hashing the function and its parameters to create a unique key, then storing the result in memory with that key as a value. For subsequent calls, the system first checks the cache to see if the function with identical parameters has been executed before. This reduces redundant computations. We will explore how to implement this using a custom LRU (Least Recently Used) cache and Redis cache. Our composite implementation will first check the local memory in our custom LRU cache and return the result if found. If the result is not found, it will then check the Redis cache. If the result is still not found, it will execute the function, store the result in both caches, and return the result for future use.</p><h4>CAP Theorem</h4><p>While implementing our cache, it’s important to consider the CAP Theorem, which states that a system can only achieve two out of three properties: Consistency, Availability, and Partition Tolerance. Our cache will require trading off consistency for availability and will return outdated data if the database changes frequently. We however use use a Time-To-Live (TTL) and max size for our LRU cache, which helps manage data freshness and memory usage but in systems with frequent writes, there’s a risk of returning stale data.</p><h4>Prerequisites and Imports</h4><ul><li><a href="https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/">Install and Setup Redis | Docs</a></li></ul><pre>import redis.asyncio as aioredis<br>import redis<br>from functools import wraps, lru_cache<br>from loguru import logger<br>import pickle<br>import asyncio<br>import time<br>from collections import OrderedDict</pre><h4>Custom LRU Cache</h4><p>The lru cache available by default in the python library doesn’t include a time to live, so we will implement our custom LRU cache with a time to live feature.</p><pre>class LRUCacheTTL:<br>    def __init__(self, maxsize=128, ttl=600):<br>        self.cache = OrderedDict()<br>        self.maxsize = maxsize<br>        self.ttl = ttl<br>        self.lock = asyncio.Lock()<br><br>    def _is_expired(self, entry):<br>        return time.time() - entry[1] &gt; self.ttl<br><br>    async def get(self, key):<br>        async with self.lock:<br>            if key in self.cache:<br>                entry = self.cache[key]<br>                if not self._is_expired(entry):<br>                    self.cache.move_to_end(key)<br>                    return entry[0]<br>                else:<br>                    del self.cache[key]<br>            return None<br><br>    async def set(self, key, value):<br>        async with self.lock:<br>            self.cache[key] = (value, time.time())<br>            if len(self.cache) &gt; self.maxsize:<br>                self.cache.popitem(last=False)<br><br>    def get_sync(self, key):<br>        if key in self.cache:<br>            entry = self.cache[key]<br>            if not self._is_expired(entry):<br>                self.cache.move_to_end(key)<br>                return entry[0]<br>            else:<br>                del self.cache[key]<br>        return None<br><br>    def set_sync(self, key, value):<br>        self.cache[key] = (value, time.time())<br>        if len(self.cache) &gt; self.maxsize:<br>            self.cache.popitem(last=False)</pre><p>Our class initializes an ordered dictto maintain the order of the items based on usage. Our max sizespecifies the max number of items our cache can hold. TTLrefers to the expiration time in seconds for the cache. Lockensures we can access our cache in an asynchronous environment to prevent race conditions.</p><p>We add a helper method _is_expiredto check if a cache entry is expired by comparing the current time with the time the entry was added and return True if this has exceeded our ttl.</p><p>The asynchronous get<strong> </strong>method retrieves a value from the cache. If the cache exists and isn’t expired, it marks it as recently used. If entry has expired, it is deleted, and None is returned. The async with self.lock helps access our cache in a concurrent safe environment.</p><p>The setmethod adds a new key-value pair or updates the existing one. If the max size is exceeded, the least recently which is the first item in the ordered dict is removed.</p><p>The get_syncmethod works similarly to the asynchronous getbut without the async syntax. This is the same with the set_sync<strong>.</strong></p><p><strong>Redis cache</strong></p><p>Next, we implement our async Redis cache decorator. This decorator can be used on an asynchronous function to optimize it’s response time by first checking if the hashed key and results of the function exists in redis and returning it or caching it if it doesn’t exist. We first define our asynchronous and synchronous redis connection.</p><pre>async_redis_client = aioredis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20f&quot;redis://%7Bhost%7D:%7Bport%7D&quot;,%3Cbr%3E%20%20%20%20%20%20%20%20db=db,%3Cbr%3E%20%20%20%20%20%20%20%20password=password,%3Cbr%3E)<br>sync_redis_client = redis.StrictRedis(<br>        host=host, port=port, db=db<br>    )<br><br>def async_redis_cache(ttl=600):<br>    def decorator(func):<br>        @wraps(func)<br>        async def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            logger.info(f&quot;Checking Redis cache for key: {cache_key}&quot;)<br>            cached_result = await async_redis_client.get(cache_key)<br>            if cached_result:<br>                logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                return pickle.loads(cached_result)<br>            logger.info(f&quot;Redis cache miss for key: {cache_key}. Calling the function.&quot;)<br>            result = await func(*args, **kwargs)<br>            await async_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>            logger.info(f&quot;Storing result in Redis cache for key: {cache_key}&quot;)<br>            return result<br><br>        return wrapper<br><br>    return decorator<br><br>def sync_redis_cache(ttl=600):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            logger.info(f&quot;Checking Redis cache for key: {cache_key}&quot;)<br>            cached_result = sync_redis_client.get(cache_key)<br>            if cached_result:<br>                logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                return pickle.loads(cached_result)<br>            logger.info(f&quot;Redis cache miss for key: {cache_key}. Calling the function.&quot;)<br>            result = func(*args, **kwargs)<br>            sync_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>            logger.info(f&quot;Storing result in Redis cache for key: {cache_key}&quot;)<br>            return result<br><br>        return wrapper<br><br>    return decorator</pre><p>The async_redis_cacheaccepts a time to live parameter specifying how long our item should remain. We create a unique cache key of the function name as well as it’s arguments and keyword arguments using pickle.dump which serializes the arguments into a byte stream.</p><p>We then retrieve the item from redis using the cache key. If the item exists, we deserialize the results using picke.load and return it. If not, we call the original function and store the serialized result as a value using pickle.dump with the cache key and time to live. We then return the result.</p><p>We use pickle for serialization because unlike other serialization methods like JSON, pickle can serialize nearly any python object. It also ensures uniqueness to avoid any possibility of cache collisions.</p><p>The sync_redis_cachedoes the same thing but using the synchronous redis client we defined earlier</p><p><strong>NB: </strong>We serialize both the cache key and value in redis because redis accepts only strings.</p><p><strong>Wrapping the LRU cache in a decorator</strong></p><p>We can also wrap the LRU cache in a decorator to be used independently for functions we wanted to cache on the memory.</p><pre>def lru_cache_decorator(maxsize=128, ttl=600):<br>    lru_cache_ttl = LRUCacheTTL(maxsize=maxsize, ttl=ttl)<br><br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            if asyncio.iscoroutinefunction(func):<br><br>                async def async_wrapper(*args, **kwargs):<br>                    logger.info(<br>                        f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    result = await lru_cache_ttl.get(cache_key)<br>                    if result is not None:<br>                        logger.info(<br>                            f&quot;LRU cache hit for function: {func.__name__} with key: {cache_key}&quot;<br>                        )<br>                        return result<br>                    logger.info(<br>                        f&quot;LRU cache miss for function: {func.__name__}. Calling the function.&quot;<br>                    )<br>                    result = await func(*args, **kwargs)<br>                    await lru_cache_ttl.set(cache_key, result)<br>                    return result<br><br>                return async_wrapper(*args, **kwargs)<br>            else:<br>                logger.info(<br>                    f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                )<br>                result = lru_cache_ttl.get_sync(cache_key)<br>                if result is not None:<br>                    logger.info(<br>                        f&quot;LRU cache hit for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    return result<br>                logger.info(<br>                    f&quot;LRU cache miss for function: {func.__name__}. Calling the function.&quot;<br>                )<br>                result = func(*args, **kwargs)<br>                lru_cache_ttl.set_sync(cache_key, result)<br>                return result<br><br>        return wrapper<br><br>    return decorator</pre><p>Our lru cache decorator also creates a cache key using pickle.dumps . Unlike the redis cache that seperate functions for asynchronous and synchronous methods, our lru cache decorator accepts any type of function but checks if that function is a coroutine function. This allows it to handle the different types of functions appropriately.</p><p>It then gets the cache using the cache key and returns the result if it exists. If it doesn’t exist, it calls the function and updates the cache with the result.</p><h4><strong>Composite Cache</strong></h4><p>The final part of our code is the composite cache. The composite cache combines the two cache mechanisms. This approach leverages the speed of in-memory caching for frequent and recent access patterns and redis for persistence and sharing of cache accross processes and machines.</p><pre>def composite_cache(ttl=600, maxsize=128):<br>    def decorator(func):<br>        lru_cached_func = lru_cache_decorator(maxsize=maxsize, ttl=ttl)(func)<br><br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            if asyncio.iscoroutinefunction(func):<br><br>                async def async_wrapper(*args, **kwargs):<br>                    logger.info(<br>                        f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    result = await lru_cached_func(*args, **kwargs)<br>                    if result is not None:<br>                        return result<br>                    logger.info(<br>                        f&quot;LRU cache miss for function: {func.__name__}. Checking Redis cache.&quot;<br>                    )<br>                    cached_result = await async_redis_client.get(cache_key)<br>                    if cached_result:<br>                        logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                        result = pickle.loads(cached_result)<br>                        await lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                        return result<br>                    result = await func(*args, **kwargs)<br>                    await async_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>                    await lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                    return result<br><br>                return async_wrapper(*args, **kwargs)<br>            else:<br>                logger.info(<br>                    f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                )<br>                result = lru_cached_func(*args, **kwargs)<br>                if result is not None:<br>                    return result<br>                logger.info(<br>                    f&quot;LRU cache miss for function: {func.__name__}. Checking Redis cache.&quot;<br>                )<br>                cached_result = sync_redis_client.get(cache_key)<br>                if cached_result:<br>                    logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                    result = pickle.loads(cached_result)<br>                    lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                    return result<br>                result = func(*args, **kwargs)<br>                sync_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>                lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                return result<br><br>        return wrapper<br><br>    return decorator</pre><p>Our composite cache decorator accepts a ttl and maxsize. It then applies the lru_cache_decoratorto the function, passing in the ttl and maxsize. It creates the cache key using pickle dumps. Then checks if the function is a coroutine to handle it appropriately.</p><p>The async_wrapperhandles our caching for asynchronous functions and the sync_wrapperfor synchronous functions. They both first check the lru_cache for an existing result and return it. If no result, they then check redis using the cache_key. If a result is found, the value of the redis cache is deserialized and returned. If no result, the original function is called, and the cache_key and serialized results is stored in redis along with a ttl.</p><h4>Calling our decorators</h4><p>Here is an example usage of our decorators.</p><pre>&quot;&quot;&quot;<br># Example usage:<br># Using composite cache for async function<br>@composite_cache(ttl=600, maxsize=128)<br>async def get_conversation(conversation_service, conversation_id):<br>    return await conversation_service.get_conversation(conversation_id)<br><br># Using composite cache for sync function<br>@composite_cache(ttl=600, maxsize=128)<br>def sync_function(arg1, arg2):<br>    # Function implementation<br>    return result<br><br># Using only LRU cache for async function<br>@lru_cache_decorator(maxsize=128, ttl=600)<br>async def async_function(arg1, arg2):<br>    # Function implementation<br>    return result<br><br># Using only LRU cache for sync function<br>@lru_cache_decorator(maxsize=128, ttl=600)<br>def sync_function(arg1, arg2):<br>    # Function implementation<br>    return result<br>&quot;&quot;&quot;</pre><h4>Full code below</h4><pre>import redis.asyncio as aioredis<br>import redis<br>from functools import wraps, lru_cache<br>from loguru import logger<br>import pickle<br>import asyncio<br>import time<br>from collections import OrderedDict<br><br># Initialize Redis clients<br>async_redis_client = aioredis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20f&quot;redis://%7Bhost%7D:%7Bport%7D&quot;,%3Cbr%3E%20%20%20%20%20%20%20%20db=db,%3Cbr%3E%20%20%20%20%20%20%20%20password=redis_password,%3Cbr%3E)<br>sync_redis_client = redis.StrictRedis(<br>        host=host,<br>        port=port,<br>        db=db,<br>        password=password,<br>    )<br><br><br><br>class LRUCacheTTL:<br>    def __init__(self, maxsize=128, ttl=600):<br>        self.cache = OrderedDict()<br>        self.maxsize = maxsize<br>        self.ttl = ttl<br>        self.lock = asyncio.Lock()<br><br>    def _is_expired(self, entry):<br>        return time.time() - entry[1] &gt; self.ttl<br><br>    async def get(self, key):<br>        async with self.lock:<br>            if key in self.cache:<br>                entry = self.cache[key]<br>                if not self._is_expired(entry):<br>                    self.cache.move_to_end(key)<br>                    return entry[0]<br>                else:<br>                    del self.cache[key]<br>            return None<br><br>    async def set(self, key, value):<br>        async with self.lock:<br>            self.cache[key] = (value, time.time())<br>            if len(self.cache) &gt; self.maxsize:<br>                self.cache.popitem(last=False)<br><br>    def get_sync(self, key):<br>        if key in self.cache:<br>            entry = self.cache[key]<br>            if not self._is_expired(entry):<br>                self.cache.move_to_end(key)<br>                return entry[0]<br>            else:<br>                del self.cache[key]<br>        return None<br><br>    def set_sync(self, key, value):<br>        self.cache[key] = (value, time.time())<br>        if len(self.cache) &gt; self.maxsize:<br>            self.cache.popitem(last=False)<br><br><br>def async_redis_cache(ttl=600):<br>    def decorator(func):<br>        @wraps(func)<br>        async def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            logger.info(f&quot;Checking Redis cache for key: {cache_key}&quot;)<br>            cached_result = await async_redis_client.get(cache_key)<br>            if cached_result:<br>                logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                return pickle.loads(cached_result)<br>            logger.info(f&quot;Redis cache miss for key: {cache_key}. Calling the function.&quot;)<br>            result = await func(*args, **kwargs)<br>            await async_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>            logger.info(f&quot;Storing result in Redis cache for key: {cache_key}&quot;)<br>            return result<br><br>        return wrapper<br><br>    return decorator<br><br><br>def sync_redis_cache(ttl=600):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            logger.info(f&quot;Checking Redis cache for key: {cache_key}&quot;)<br>            cached_result = sync_redis_client.get(cache_key)<br>            if cached_result:<br>                logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                return pickle.loads(cached_result)<br>            logger.info(f&quot;Redis cache miss for key: {cache_key}. Calling the function.&quot;)<br>            result = func(*args, **kwargs)<br>            sync_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>            logger.info(f&quot;Storing result in Redis cache for key: {cache_key}&quot;)<br>            return result<br><br>        return wrapper<br><br>    return decorator<br><br><br>def lru_cache_decorator(maxsize=128, ttl=600):<br>    lru_cache_ttl = LRUCacheTTL(maxsize=maxsize, ttl=ttl)<br><br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            if asyncio.iscoroutinefunction(func):<br><br>                async def async_wrapper(*args, **kwargs):<br>                    logger.info(<br>                        f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    result = await lru_cache_ttl.get(cache_key)<br>                    if result is not None:<br>                        logger.info(<br>                            f&quot;LRU cache hit for function: {func.__name__} with key: {cache_key}&quot;<br>                        )<br>                        return result<br>                    logger.info(<br>                        f&quot;LRU cache miss for function: {func.__name__}. Calling the function.&quot;<br>                    )<br>                    result = await func(*args, **kwargs)<br>                    await lru_cache_ttl.set(cache_key, result)<br>                    return result<br><br>                return async_wrapper(*args, **kwargs)<br>            else:<br>                logger.info(<br>                    f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                )<br>                result = lru_cache_ttl.get_sync(cache_key)<br>                if result is not None:<br>                    logger.info(<br>                        f&quot;LRU cache hit for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    return result<br>                logger.info(<br>                    f&quot;LRU cache miss for function: {func.__name__}. Calling the function.&quot;<br>                )<br>                result = func(*args, **kwargs)<br>                lru_cache_ttl.set_sync(cache_key, result)<br>                return result<br><br>        return wrapper<br><br>    return decorator<br><br><br>def composite_cache(ttl=600, maxsize=128):<br>    def decorator(func):<br>        lru_cached_func = lru_cache_decorator(maxsize=maxsize, ttl=ttl)(func)<br><br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            cache_key = f&quot;{func.__name__}:{pickle.dumps(args)}:{pickle.dumps(kwargs)}&quot;<br>            if asyncio.iscoroutinefunction(func):<br><br>                async def async_wrapper(*args, **kwargs):<br>                    logger.info(<br>                        f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                    )<br>                    result = await lru_cached_func(*args, **kwargs)<br>                    if result is not None:<br>                        return result<br>                    logger.info(<br>                        f&quot;LRU cache miss for function: {func.__name__}. Checking Redis cache.&quot;<br>                    )<br>                    cached_result = await async_redis_client.get(cache_key)<br>                    if cached_result:<br>                        logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                        result = pickle.loads(cached_result)<br>                        await lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                        return result<br>                    result = await func(*args, **kwargs)<br>                    await async_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>                    await lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                    return result<br><br>                return async_wrapper(*args, **kwargs)<br>            else:<br>                logger.info(<br>                    f&quot;Checking LRU cache for function: {func.__name__} with key: {cache_key}&quot;<br>                )<br>                result = lru_cached_func(*args, **kwargs)<br>                if result is not None:<br>                    return result<br>                logger.info(<br>                    f&quot;LRU cache miss for function: {func.__name__}. Checking Redis cache.&quot;<br>                )<br>                cached_result = sync_redis_client.get(cache_key)<br>                if cached_result:<br>                    logger.info(f&quot;Redis cache hit for key: {cache_key}&quot;)<br>                    result = pickle.loads(cached_result)<br>                    lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                    return result<br>                result = func(*args, **kwargs)<br>                sync_redis_client.setex(cache_key, ttl, pickle.dumps(result))<br>                lru_cached_func(*args, **kwargs)  # Populate LRU cache<br>                return result<br><br>        return wrapper<br><br>    return decorator<br><br><br>&quot;&quot;&quot;<br># Example usage:<br># Using composite cache for async function<br>@composite_cache(ttl=600, maxsize=128)<br>async def get_conversation(conversation_service, conversation_id):<br>    return await conversation_service.get_conversation(conversation_id)<br><br># Using composite cache for sync function<br>@composite_cache(ttl=600, maxsize=128)<br>def sync_function(arg1, arg2):<br>    # Function implementation<br>    return result<br><br># Using only LRU cache for async function<br>@lru_cache_decorator(maxsize=128, ttl=600)<br>async def async_function(arg1, arg2):<br>    # Function implementation<br>    return result<br><br># Using only LRU cache for sync function<br>@lru_cache_decorator(maxsize=128, ttl=600)<br>def sync_function(arg1, arg2):<br>    # Function implementation<br>    return result<br>&quot;&quot;&quot;</pre><p>Hope this was a great read!</p><p>When in doubt, take a walk — sometimes the best ideas hit you when you’re away from the screen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e1f7a6d7255" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/optimizing-cache-performance-hashing-function-calls-and-implementing-composite-caches-with-local-9e1f7a6d7255">Optimizing Cache Performance: Hashing function calls and Implementing Composite Caches with Local…</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Querying Gemini with Langchain’s RunnableMap, LLM chain and Gemini API using…]]></title>
            <link>https://blog.devops.dev/querying-gemini-with-langchains-runnablemap-llm-chain-and-gemini-api-using-docarrayinmemorysearch-4ce35d88bfdc?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce35d88bfdc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 06:06:11 GMT</pubDate>
            <atom:updated>2024-02-12T19:00:31.819Z</atom:updated>
            <content:encoded><![CDATA[<h3>Querying Gemini with Langchain’s RunnableMap, LLM chain and Gemini API using DocArrayInMemorySearch as a store and retriever.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNrwAm4dgIPA6w-t1HaIwg.jpeg" /></figure><p>Following Google’s Gemini API release, I decided to update my previous article on Redis + Langchain + OpenAI to work with Gemini. After debugging for hours and swearing to quit programming and move to a small village far away from civilization, I finally fixed my code and ditched the idea. So, here’s my latest article on Querying Gemini with Langchain Runnable maps, LLM chain and also Gemini API using DocArrayInMemorySearch as a store and retriever. It’s a mouthful I know, but I couldn’t figure out a simpler title.</p><p>This will include;</p><ul><li>Setting up our DocArrayInMemorySearch store for our business — Frosty Delights</li><li>Quering the vector with RunnableMap</li><li>Quering the vector with LLM Chain</li><li>Querying directly with Gemini</li></ul><h4><strong>Creating a vector store for Frosty Delights</strong></h4><p>This portion ideally should be done using some sort of storage e.g Redis, Chroma, Pinecone, Postgres. For the sake of simplicity, we will store Frosty Delights vector storage in a variable. If you want to use Redis as a vector store, you can refer to <a href="https://blog.devops.dev/using-redis-as-vector-storage-to-connect-a-website-to-openai-from-building-the-index-to-querying-ad608fd11598">one of my previous articles</a>. For this article, we will use <strong>DocArrayInMemorySearch </strong>provided by langchain as a temporary storage in memory. <a href="https://python.langchain.com/docs/integrations/vectorstores/docarray_in_memory">DocArrayInMemorySearch</a> is a document index provided by Docarray that stores documents in memory. It is a great starting point for small datasets, where you may not want to launch a database server.</p><p>In this section we,</p><ul><li>Initialize a variable to hold our business_data for Frosty delights.</li><li>Split it into an array of shorter texts.</li><li>Initialize a langchain document class for each text in the array</li><li>Create a vector store from the texts using DocArrayInMemorySearch</li></ul><pre># imports<br>from langchain_google_genai import GoogleGenerativeAIEmbeddings<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.schema.document import Document<br>from langchain.vectorstores import DocArrayInMemorySearch<br><br># business data for Frosty Delights<br>business_data = &quot;Welcome to Frosty Delights, your go-to destination for delicious frozen treats! At Frosty Delights, we pride ourselves on serving up the creamiest, most mouthwatering ice cream flavors in town. From classic favorites like chocolate and vanilla to innovative creations like mango habanero and salted caramel swirl, there&#39;s something for everyone to enjoy. Our ice cream is made fresh daily using only the finest ingredients, sourced locally whenever possible. Whether you&#39;re stopping by for a scoop, a sundae, or one of our signature ice cream sandwiches, you&#39;re sure to leave with a smile on your face. Come experience the joy of Frosty Delights today!&quot;<br><br># initialize embeddings with GoogleGenerativeAIEmbeddings<br>embeddings = GoogleGenerativeAIEmbeddings(model=&quot;models/embedding-001&quot;, google_api_key = GOOGLE_API_KEY)<br><br>GOOGLE_API_KEY = &quot;your-google-api-key-here&quot;<br><br>def create_vector_store(data):<br>   # initiliaze RecursiveCharacterTextSplitter class <br>   text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=20)<br>  # spit business data<br>  split_text = text_splitter.split_text(data)<br>  # load each split text into an array of LangChain&#39;s document class<br>   docs = [Document(page_content=x) for x in split_text(data)]<br>   # create the vector storage using DocArrayInMemorySearch<br>   vectorstore = DocArrayInMemorySearch.from_texts(docs, embeddings)<br>   return vectorstore<br><br>vectorstore = create_vector_store(business_data)</pre><h4><strong>Querying with Runnable Map</strong></h4><p>To query Gemini with RunnableMap we;</p><ul><li>Create our prompt template with two variables context (for the relevant context retrieved) and question (query passed into the function)</li><li>Initialize our model with ChatGoogleGenerativeAI passing the gemini-pro model and our Api key.</li><li>Set up our <a href="https://python.langchain.com/docs/modules/data_connection/retrievers/vectorstore">retriever</a> from our previous vector store created. We will use this retriever in our RunnableMap to retrieve relevant contents.</li><li>Build our prompt from the prompt template</li><li>Initialize an <a href="https://python.langchain.com/docs/modules/model_io/output_parsers/">output parser</a>. This is responsible for taking the output of an LLM and transforming it to a more suitable format.</li><li>Initialize and invoke our RunnableMap.</li></ul><p>A RunnableMap, from langchain.schema.runnable, is a way to manipulate data in a chain of runnables. It can be used to transform the output of one runnable to match the input format of the next runnable in a sequence.</p><pre># imports<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain.schema.output_parser import StrOutputParser<br>from langchain.schema.runnable import RunnableMap<br><br># initialize prompt template    <br>prompt_template = &quot;&quot;&quot;<br>    You are an AI assistant for a business that sells ice cream. Your primary goal is to provide support and assistance to customers based on extracted context    <br>    Context : \n {context} \n    <br>    Question: \n {question} \n<br>    Answer:<br>    &quot;&quot;&quot;<br><br># initialize an output parser<br>output_parser = StrOutputParser()<br><br>def runnable_map(question):<br>  # initialize our model<br>  model = ChatGoogleGenerativeAI(model=&quot;gemini-pro&quot;, temperature = 0.7, google_api_key = GOOGLE_API_KEY)<br>  # we set up a retriever from our vectorestore which we will use to get relevant context from our query <br>  retriever = vectorstore.as_retriever()<br>  # create prompt from prompt template<br>  prompt = ChatPromptTemplate.from_template(template)<br>  # initialize the RunnableMap class<br>  chain = RunnableMap({<br>        &quot;context&quot;: lambda x: retriever.get_relevant_documents(x[&quot;question&quot;]),<br>        &quot;question&quot;: lambda x : x[&quot;question&quot;],<br>    }) | prompt | model | output_parser<br># invoke the RunnableMap<br> response = chain.invoke({&quot;question&quot;: question})<br> return response<br><br>runnable_map(&quot;What does Frosty Delights sell?&quot;)</pre><h4>Querying with LLM Chain</h4><p>In this section, we look out how to query Gemini using a simple Langchain LLM. Our process involves</p><ul><li>Creating our prompt from the prompt template</li><li>Setting up our retriever and using it to retrieve relevant documents from our vector store.</li><li>Setting up our LLM Chain</li></ul><pre># imports<br>from langchain.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br><br># prompt_template and model are initialized under &quot;Querying with Runnable Map&quot; section<br><br>def query_llm_chain(question):<br>  # create our prompt and specify the input variables<br>  prompt = PromptTemplate(template=prompt_template, input_variables=[&quot;context&quot;, &quot;question&quot;])<br>  # retrive the relevant documents<br>  retriever = vectorstore.as_retriever()<br>  relevant_docs = retriever.get_relevant_documents(question)<br>  # set up chain<br>  chain = LLMChain(llm = model, prompt=prompt, verbose = True)<br>  # run chain<br>  response = chain({&quot;context&quot;: relevant_docs, &quot;question&quot;: question}, return_only_outputs=True)<br>  print (response)<br>  print (response[&quot;text&quot;])<br>  return response[&quot;text&quot;]<br><br>query_llm_chain(&quot;What does Frosty Delights sell?&quot;)</pre><h4>Querying Directly with Gemini API</h4><p>For this section, after we retrieve the relevant contents with our retriever, we write a separate function to iterate through all the contents and build a string with all the content of the retrieved documents to pass to Gemini API.</p><pre># imports<br>import google.generativeai as genai<br><br># configure gemini key<br>genai.configure(api_key=os.getenv(&#39;GEMINI_API_KEY&#39;) or &quot;YOUR KEY HERE&quot;)<br><br><br># this function takes in our retrieved context which is an array of langchain documents, and builds a string context based from their content<br>def construct_context(docs):<br>    output = &quot;&quot;<br>    for content in docs:<br>        output += f&quot;\n {content.page_content}&quot;<br>    return output<br><br># prompt_template is initialized under &quot;Querying with Runnable Map&quot; section<br><br>def query_gemini_directly(question):<br>   # initializing our model<br>   model = genai.GenerativeModel(&#39;gemini-pro&#39;)<br>   # retrive the relevant documents<br>   retriever = vectorstore.as_retriever()<br>   relevant_docs = retriever.get_relevant_documents(question)<br>   # construct the content text from the retrieved docs<br>   context = construct_context(relevant_docs)<br>   # pass both the question and context into our formatted prompt template<br>   prompt_formatted = prompt.format(context=context, question = question)<br>  response = model.generate_content(prompt_formatted)<br>  return response<br><br>query_gemini_directly(question)</pre><p>Thanks for taking the time to read all through the end. I hope the article was of help to you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce35d88bfdc" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/querying-gemini-with-langchains-runnablemap-llm-chain-and-gemini-api-using-docarrayinmemorysearch-4ce35d88bfdc">Querying Gemini with Langchain’s RunnableMap, LLM chain and Gemini API using…</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Redis as vector storage to connect a Website to OpenAI — From Building the index to Querying…]]></title>
            <link>https://blog.devops.dev/using-redis-as-vector-storage-to-connect-a-website-to-openai-from-building-the-index-to-querying-ad608fd11598?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad608fd11598</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 06:53:23 GMT</pubDate>
            <atom:updated>2023-12-11T13:57:39.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Redis as vector storage to connect a Website to OpenAI — From Building the index to Querying the index</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-koU5xVbZ0t9lp0-7N5New.png" /></figure><p>I’m going to try to be quick with this so you can get back to building your app before OpenAI releases GPT 5 and kills your startup.</p><p>Redis offers vector storage as part of its many database and caching solutions. Vector storage is a way of storing mostly unstructured data. It does this by mapping the data to a sequence of numbers mostly used in machine learning applications allowing a number of operations to be performed on them such as searching, clustering, recommendations, anomaly detection, diversity measurement, classification etc.</p><h3><strong>Setting up Redis</strong></h3><p>Before we break down the steps in building and querying the index,<strong> we need to set up our Redis</strong>. You can install Redis with docker, or set up a Redis database using the Redis cloud.</p><p><a href="https://redis.io/docs/install/">Install Redis or Redis Stack</a></p><p>Now let’s import all the Python libraries we will use for this. We will use langchain as it provides a number of wrappers around OpenAI we can use.</p><pre>import redis<br># langchain imports<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.document_loaders import WebBaseLoader<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores.redis import Redis<br>from langchain.vectorstores.redis.base import check_index_exists<br>from langchain.llms import OpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.memory import ConversationBufferMemory<br>from langchain.chains.question_answering import load_qa_chain<br>from langchain.callbacks import get_openai_callback</pre><h3>Loading the data from the website.</h3><pre>def get_website_data_and_chunks(url):<br>    web_loader = WebBaseLoader(url)<br>    web_data = web_loader.load()<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=20)<br>    docs = text_splitter.split_documents(web_data)<br>    return docs</pre><ul><li>We use the WebBaseLoader provided by langchain to load the data from our URL.</li><li>Next, we use the RecursiveCharacterTextSplitter to split our data into several chunks. These are the chunks that will be returned from the Vector store based on the relevancy to our query. The chunk size refers to the length of each segment into which our text is divided. The chunk overlap is the amount of characters we want to overlap between segments. Selecting a good chunk size and overlap is vital as helps capture contextual information that spans amongst the chunks.</li><li>Our function will return a list of Documents containing the information about each chunk.</li></ul><h3>Building Redis Index</h3><pre>redis_host = &#39;redis://127.0.0.1:6379&#39;<br>embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)<br><br>def build_index(docs, index_name):<br>    rds = Redis.from_documents(docs, embeddings, redis_url = redis_host, index_name = index_name)<br>    print (rds)<br>    print (rds.index_name)<br>    # print (rds.write_schema)<br>    schema = rds.schema<br>    print (schema)<br>    rds.write_schema(&#39;redis_schema.yaml&#39;)</pre><ul><li>In this function, we convert our documents into vectors using OpenAI embeddings. We pass our <strong>documents </strong>from our previous function as well as an <strong>index_name</strong>. This name will be the key we use to retrieve relevant chunks later. We also initialize our redis_host. If you are using Redis in the cloud, your host can take the format, <em>redis://username:password@localhost:6379.</em></li><li>After creating the index, we will retrieve the schema of our data. This schema is important, as we will need to pass it when performing a similarity search from our index. You can save the schema to a yaml file, or into a variable.</li></ul><h3>Retrieving relevant documents</h3><pre>def retrieve_documents(index_name, query, schema):<br>    rds = Redis.from_existing_index(embeddings,index_name=index_name,redis_url = redis_host, schema=schema )<br>    results = rds.similarity_search(query)<br>    # results = rds.similarity_search(query, k=3)<br>    # results = rds.similarity_search_with_relevance_scores(query, k=5)<br>    print (results)<br>    return query_ai(query, results); </pre><ul><li>In this function, we retrieve the relevant documents based on our query. This function takes the <strong>index_name</strong>,<strong> query</strong>,<strong> </strong>and the <strong>schema</strong>. The query for example can be “Tell me about this business”. This query will be converted to vectors using the same OpenAI embeddings we used when creating our index, and we will perform a <strong>vector similarity search </strong>on our vector store, to retrieve the vectors that are similar to this query. That way we can pass both the query and the relevant content into our OpenAI model, to draft an answer for us.</li><li>As indicated in the commented results variable, we can specify a <strong>k </strong>value to return the top k results that are most relevant to our query. We can also use the similaity_search_with_relevance_scores to return the relevance score of each results.</li><li>Lastly, we will pass our <strong>query </strong>and <strong>results </strong>into the <strong>query_ai function </strong>which we will be writing next.</li></ul><h3>Querying the AI</h3><pre>def query_ai(query, results):<br>    memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;, input_key=&quot;human_input&quot;)<br>    template = &quot;&quot;&quot;<br>    You are a bot for a sports business. Given extracted parts of the business information, provide support to the client.<br>    {context}<br>    {chat_history}<br>    Human: {human_input}<br>    AI:&quot;&quot;&quot;<br>    prompt = PromptTemplate(input_variables=[&quot;context&quot;, &quot;chat_history&quot;, &quot;human_input&quot;], template=template)<br>    with get_openai_callback() as cb:<br>        llm = OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0,)<br>        chain = load_qa_chain(llm, chain_type=&quot;stuff&quot;, memory = memory, verbose= True, prompt=prompt)<br>        response = chain({&quot;input_documents&quot;: results, &quot;human_input&quot;: query}, return_only_outputs=True)<br>        print(&#39;callback info&#39;, cb)<br>        print (response)</pre><ul><li>In this function, we first create a <strong>ConversationBufferMemory </strong>which is optional, but this allows us to essentially build a history of previous conversations that we can pass to the AI. See more about ConversationBufferMemory and how to add context here. <a href="https://python.langchain.com/docs/modules/memory/types/buffer">https://python.langchain.com/docs/modules/memory/types/buffer</a> . In our conversation buffer memory, we specify a <strong>memory_key </strong>and <strong>input_key </strong>that will be mapped to our prompt template.</li><li>We then create a template using the PromptTemplate class provided to us by langchain, specifying 3 input variables used in our template; <strong>context, chat_history </strong>and <strong>human_input.</strong></li><li>Using <strong>load_qa_chain</strong> we pass in our llm, memory, and prompt.</li><li>We run the chain and pass in our query, and the results gotten from our Redis vector similarity search.</li><li>We also use an open AI callback to return information about our token usage.</li><li>Finally, we print our response from the AI.</li></ul><h3>Full code</h3><pre>import redis<br># langchain imports<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.document_loaders import WebBaseLoader<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores.redis import Redis<br>from langchain.vectorstores.redis.base import check_index_exists<br>from langchain.llms import OpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.memory import ConversationBufferMemory<br>from langchain.chains.question_answering import load_qa_chain<br>from langchain.callbacks import get_openai_callback<br><br>OPENAI_API_KEY = &#39;your-key-here&#39;<br>embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=20)<br>redis_host = &quot;redis://127.0.0.1:6379&quot;<br><br><br>def get_website_data_and_chunks(url):<br>    web_loader = WebBaseLoader(url)<br>    web_data = web_loader.load()<br>    docs = text_splitter.split_documents(web_data)<br>    return docs<br><br>def build_index(docs, index_name):<br>    rds = Redis.from_documents(docs, embeddings, redis_url = redis_host, index_name = index_name)<br>    print (rds)<br>    print (rds.index_name)<br>    # print (rds.write_schema)<br>    schema = rds.schema<br>    print (schema)<br>    rds.write_schema(&#39;redis_schema.yaml&#39;)<br>    return rds.index_name<br><br>def retrieve_documents(index_name, query, schema):<br>    # schema = &#39;redis_schema.yaml&#39;<br>    rds = Redis.from_existing_index(embeddings,index_name=index_name,redis_url = redis_host, schema=schema )<br>    results = rds.similarity_search(query)<br>    # results = rds.similarity_search(query, k=3)<br>    # results = rds.similarity_search_with_relevance_scores(query, k=5)<br>    print (results)<br>    return query_ai(query, results); <br><br>    <br>def query_ai(query, results):<br>    memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;, input_key=&quot;human_input&quot;)<br>    template = &quot;&quot;&quot;<br>    You are a bot for a sports business. Given extracted parts of the business information, provide support to the client.<br>    {context}<br>    {chat_history}<br>    Human: {human_input}<br>    AI:&quot;&quot;&quot;<br>    prompt = PromptTemplate(input_variables=[&quot;context&quot;, &quot;chat_history&quot;, &quot;human_input&quot;], template=template)<br>    with get_openai_callback() as cb:<br>        llm = OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0,)<br>        chain = load_qa_chain(llm, chain_type=&quot;stuff&quot;, memory = memory, verbose= True, prompt=prompt)<br>        response = chain({&quot;input_documents&quot;: results, &quot;human_input&quot;: query}, return_only_outputs=True)<br>        print(&#39;callback info&#39;, cb)<br>        print (response)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad608fd11598" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/using-redis-as-vector-storage-to-connect-a-website-to-openai-from-building-the-index-to-querying-ad608fd11598">Using Redis as vector storage to connect a Website to OpenAI — From Building the index to Querying…</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why The Bear feels like a warzone?]]></title>
            <link>https://innocentanyaele.medium.com/why-the-bear-feels-like-a-warzone-d71d1479dcef?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71d1479dcef</guid>
            <category><![CDATA[cinema]]></category>
            <category><![CDATA[the-bears]]></category>
            <category><![CDATA[film]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[movıe]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 14:02:52 GMT</pubDate>
            <atom:updated>2023-08-29T14:02:52.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKvCqAxNxTZXGqOYNEqDqg.jpeg" /></figure><p>FX show, The Bear, just like some of their previous masterpieces, delivered us with an authentic yet thrilling experience. Every episode personally gave me that sunken feeling of realism and I found myself questioning some of my life choices.</p><p>The kitchen drama follows a young chef, Carmy, who returns home to run his family’s restaurant, “The Beef”, following the death of his brother. Every episode opens another layer of grief both from Carmy’s past and the present trying to save the dying restaurant. But inside this grief packed series, Christopher Storer manages to create some of the most chaotic scenes that feel like the frontline of battle.</p><p><strong>Spoilers ahead</strong></p><p>I will use the episode, “Review” (Season 1 Episode 8) for my analysis and break down some of the elements in the kitchen nightmare scene (10:40–19:32) that I think contribute to this intense experience.</p><p><strong>Disclaimer </strong>: I have no experience in film making or cinematography and all my opinions are simply what I make of this scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nMDw9nX_YVfJFV3D4iLSdw.gif" /></figure><p><strong>Tension Buildup &amp; Explosion</strong></p><p>The first element is the tension build up that happens before the scene. From the start of the episode, minor disputes slowly build its way through the episode before finally exploding into the 9 minute kitchen nightmare segment. Let’s look at what tension starts before the scene, and where exactly it explodes to understand how that explosion was a key element in creating such an intense scene.</p><p>&gt; Ebraheim opens it up by reading a review of Sydney’s dish by a customer. A decision by Sydney that Carmy wasn’t particularly happy with. The conflict builds on top of it when Sydney brings it up and apologizes. The conflict builds on top of it when Richie comes in and uses that same dish as an opportunity to pick an argument with Richie. Then Carmy blames the whole nightmare on Sydney’s dish (“I told you the dish wasn’t fucking ready”) and the conflict finally explodes in the kitchen nightmare scene when Carmy let’s Sydney have it telling her to fuck off his expo and Sydney finally quitting.</p><p>&gt; Another starts when Tina brings in Louie to be taught by Sydney on a very busy day which finally explodes during the nightmare scene after Sydney goes off on her.</p><p>&gt; Another starts when Marcus decides to focus on making his donuts instead of the cake. This tension developed through the episode when Carmy mentions it, then Sydney, then finally explodes in the kitchen nightmare scene when Carmy loses it on him.</p><p>This build up of tension throughout the episode played a major role in the nightmare scene having all the earlier developing conflicts finally exploding all at once. This is one key element that creates such intensity during some of the chaotic scenes we see in the bear. You will find this same pattern repeat in the episodes across the series.</p><p><strong>Time bound</strong></p><p>Nothing says chaos like working within a short timeline. The pressure of time creates a rush in the process and it’s easy to lose focus. The nightmare scene opens up when Syndey leaves the pre order option on the machine open resulting in millions of orders coming through. They open in 10 minutes and they have to prepare all the meals that keep coming through the machine. This is perhaps the most important element of the scene that makes it intense.</p><p><strong>Music</strong></p><p>This already speaks for itself. It just had to be metal music playing in the background. What else can make this scene chaotic? The pacing of the music timed perfectly with the development of the scene. It started off slow and took off with the developing intensity of the scene. The perfect compliment to the chaos in the scene.</p><p><strong>Close up shot</strong></p><p>This might be a bit of a stretch but I personally felt the close up shot of the characters during this scene, make it a tad more chaotic. Having the camera that close to characters especially during dialogue really left me with no sense of depth. By isolating us from the full view of the surroundings we feel we have less control of the whole scene and this can contribute to the intensity of the scene. Close up shots are typically used in cinema to convey an emotional intimacy between the audience and the character, and aside from the spectacular acting, this shot emphasized the psychological state of each of the characters.</p><p><strong>Continuous dialogues &amp; actions</strong></p><p>The dialogue never stops. It continues throughout the scene eating its way into the next and the next. It doesn’t give you a chance to take a breath and fully analyze the emotional consequences of the words and the actions but layers everything on top of each other. You have the sense of too many things happening at the same time.</p><p><strong>The whirring of the machine</strong></p><p>Behind the metal music and the continuous dialogues, the order machine whirls aggressively throughout the scene. The music and machine dance between each other not even giving us a chance to form a satisfying rhythm to it.</p><p>The nightmare scene ends without a satisfying resolution to all these conflicts leaving the audience anticipating the turnout of these events. Did they make it through the day? What happened to Marcus? Will Sydney come back? Most of these elements can be found in other “chaotic” episodes of the series. Overall it was a brilliant mix of them and I personally can’t wait to see more of this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71d1479dcef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protect pages from unauthorized access — NextJs, Firebase]]></title>
            <link>https://innocentanyaele.medium.com/protect-pages-from-unauthorized-access-nextjs-firebase-45fd9ee732b4?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/45fd9ee732b4</guid>
            <category><![CDATA[sign-in]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[protected-routes]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[authenticity]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 14:03:29 GMT</pubDate>
            <atom:updated>2023-07-13T14:03:29.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Protect pages from unauthorized access — NextJs, Firebase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oT1Uadw9D4wLJU5JJKPe5A.jpeg" /></figure><p>You have signed in your user with firebase and redirected him to a page, but there’s one problem; anyone can access that same page by just searching up the URL in their browser. Here is how you can protect your page to only allow authenticated users.</p><ul><li>Creating your sign in function with firebase.</li></ul><pre>  function signIn() {<br>    signInWithEmailAndPassword(auth, email, password)<br>      .then((response) =&gt; {<br>        localStorage.setItem(&quot;user&quot;, JSON.stringify(response.user.uid));<br>        router.push(&quot;/main/dashboard&quot;);<br>      })<br>      .catch((err) =&gt; {<br>        console.log(err);<br>        setError(&quot;Wrong username or password&quot;);<br>      });<br>  }</pre><ul><li>Create a directory for the page you want to protect.</li></ul><p>In my NextJs project, I want to direct my authenticated users to my <strong>dashboard page</strong> as well as other authenticated pages that I will store in a directory named <strong>main</strong>. In my <strong>main </strong>directory where I will store all my authenticated pages, create a file in the main root called <strong>layout.tsx</strong>. The layout file in NextJs serves as a wrapper for all the pages found in the directory.</p><pre>src<br>  app<br>    main<br>      dashboard<br>        page.tsx<br>    <strong>layout.tsx</strong><br>  page.tsx<br>  global.css</pre><ul><li>Add the code to authenticate and redirect users</li></ul><p>In layout.tsx, create a use effect that checks if an authenticated user exists. If a user is found we can return the dashboard component, it not we redirect him back to the home page or sign in page. We do this by toggling our <strong>isUserValid </strong>state to return the component.</p><pre>&quot;use client&quot;;<br><br>import NavBar from &quot;@/components/navbar/NavBar&quot;;<br>import { Montserrat } from &quot;@next/font/google&quot;;<br><br>import { useAuth } from &quot;@/lib/AuthContext&quot;;<br>import { auth } from &quot;@/lib/firebase&quot;;<br><br>import { redirect, useRouter } from &quot;next/navigation&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function DashboardLayout({<br>  children, // will be a page or nested layout<br>}: {<br>  children: React.ReactNode;<br>}) {<br><br>  const router = useRouter();<br>  const [isUserValid, setIsUserValid] = useState(false);<br><br><br>  useEffect(() =&gt; {<br>    const checkAuth = () =&gt; {<br>      auth.onAuthStateChanged((user) =&gt; {<br>        if (user) {<br>          setIsUserValid(true);<br>          console.log(&quot;This is the logged in user&quot;, user);<br>        } else {<br>          console.log(&quot;no user found&quot;);<br>          router.push(&quot;/&quot;);<br>        }<br>      });<br>    };<br><br>    checkAuth();<br>  }, []);<br><br>  if (isUserValid) {<br>    return (<br>      &lt;div className={`${montserrat.variable} font-sans`}&gt;<br>        {/* Include shared UI here e.g. a header or sidebar */}<br>        &lt;NavBar /&gt;<br>        &lt;div className=&quot;mt-20&quot;&gt;{children}&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>}</pre><p>This should prevent unauthenticated users from accessing the page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45fd9ee732b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Meta Webhooks for Instagram Messaging and respond to message.]]></title>
            <link>https://innocentanyaele.medium.com/setup-meta-webhooks-for-instagram-messaging-and-respond-to-message-4575bc95c7a2?source=rss-e703ae799605------2</link>
            <guid isPermaLink="false">https://medium.com/p/4575bc95c7a2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Innocent Anyaele]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 13:08:36 GMT</pubDate>
            <atom:updated>2023-06-27T13:08:36.292Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll guide you through how to set up Instagram messaging webhooks using the meta developer platform and set up a flask route to respond to Instagram messages.</p><h4>CONFIGURE WEBHOOKS ON META DEVELOPER DASHBOARD</h4><p>There are a few things we need to get out the way first. This article assumes you have a meta developer profile and have created an application in the platform. To use meta webhooks for Instagram messaging. Follow this link to see a more in-depth guide — <a href="https://developers.facebook.com/docs/instagram-api/guides/webhooks/">Webhooks — Instagram Platform (facebook.com)</a></p><ul><li>You need to have the <strong>instagram_manage_messages </strong>permissions with advanced access. You can do this by going to your meta dashboard and requesting for <strong>instagram_manage_messages </strong>advanced access in permissions and features under app review.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAWDuWw3pSMn5mcAVjxwHw.png" /></figure><ul><li>In your meta dashboard under webhooks subscribe to the <strong>messages </strong>option. Click the dropdown, select instagram and subscribe to <strong>messages</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzF9F5whg-2I5_aPZiYSRg.png" /></figure><ul><li>You need to also edit subscription to set up a callback url and token for your webhook. Click on edit subscription. Under callback url put in the url to your site. The url should include the path to your api that will handle the webhook. Under Verify Token, put in a secret variable that will validate your Api.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yKLRcn4ib17UCI0WPN7vw.png" /></figure><ul><li>We now have to enable page subscriptions to connect the Instagram page in the app user’s account. You can enable the subscription with the request below. Page ID takes in the ID of the page you want to connect to. The Access Token takes in the page access token. And the fields take in the fields you want to subscribe to. In our case the field is going to be <strong>messages</strong>.</li></ul><pre>POST /{page-id}/subscribed_apps<br>  ?access_token={access-token}<br>  &amp;fields={fields}</pre><h4>WRITING THE ROUTES IN FLASK</h4><p>In the code,</p><ul><li>We set up a simple route with the URL ‘/webhook/messaging-webhook’ matching what we initially set up in our subscription callback URL.</li><li>We verify the token with a secret token set in our app configuration. This secret token should match what was set while editing the subscription.</li><li>If it is a post subscription we iterate through the data, and get the message, the sender id, as well as the recipient id. We define a function sendCustomerAMessage which we will explain below. This function takes in the Page ID and Page Access token which are all set in the app’s configuration as well as the response and sender_id.</li></ul><pre> @app.route(&#39;/webhook/messaging-webhook&#39;, methods=[&#39;GET&#39;,&#39;POST&#39;])<br>    def messagingWebhook():<br>        if request.method == &#39;GET&#39;:<br>            mode = request.args.get(&#39;hub.mode&#39;)<br>            token = request.args.get(&#39;hub.verify_token&#39;)<br>            challenge = request.args.get(&#39;hub.challenge&#39;)<br><br>            if mode and token:<br>                if mode == &#39;subscribe&#39; and token == app.config[&#39;VERIFY_TOKEN&#39;]:<br>                    return make_response(challenge,200)<br>                else:<br>                    return make_response(&#39;&#39;,403)<br>            else:<br>                return<br>        if request.method == &#39;POST&#39;:<br>            body = request.get_json()<br>            entry = body[&#39;entry&#39;]<br>            <br>            try:<br>                if body[&#39;object&#39;] == &#39;instagram&#39;:<br>                    for output in entry:<br>                        output_message =  output[&#39;messaging&#39;][0]<br>                        sender_id = output_message[&#39;sender&#39;][&#39;id&#39;]<br>                        recipient_id = output_message[&#39;recipient&#39;][&#39;id&#39;]<br>                        message_text = output_message[&#39;message&#39;][&#39;text&#39;]<br><br>                        response = &quot;this is a response&quot;<br>                        sendCustomerAMessage(app.config[&#39;PAGE_ID&#39;],response,app.config[&#39;PAGE_ACCESS_TOKEN&#39;],sender_id)<br>                    return make_response(&#39;EVENT_RECEIVED&#39;, 200)<br>                else:<br>                    return make_response(&#39;&#39;,404)<br>            except Exception as e:<br>                print (e)<br>                return make_response(&#39;&#39;,500)</pre><p>We define the <strong>sendCustomerAMessage </strong>function here.</p><pre>def sendCustomerAMessage(page_id,response,page_token,psid):<br>    new_response = response.replace(&quot;&#39;&quot;,r&quot;\&#39;&quot;)<br>    # print (&#39;this is the new response&#39;, new_response)<br>    url = f&quot;https://graph.facebook.com/v14.0/{page_id}/messages\<br>?recipient={{id:{psid}}}\<br>&amp;message={{text:&#39;{new_response}&#39;}}\<br>&amp;messaging_type=RESPONSE\<br>&amp;access_token={page_token}&quot;<br>    # print (url)<br>    response = requests.post(url)<br>    # print (response.json())<br>    return (response.json())</pre><p>Now that our webhook and code is setup, our server should respond to the messages sent to our instagram page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4575bc95c7a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>