<?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 Christopher Scholz on Medium]]></title>
        <description><![CDATA[Stories by Christopher Scholz on Medium]]></description>
        <link>https://medium.com/@christopher-scholz?source=rss-92a12b8dc23e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*woU40-hZmE6QIW1auWr4mw.png</url>
            <title>Stories by Christopher Scholz on Medium</title>
            <link>https://medium.com/@christopher-scholz?source=rss-92a12b8dc23e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:19:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christopher-scholz/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[How to Setup IAM Database Authentication with IAM Identity Center]]></title>
            <link>https://medium.com/@christopher-scholz/how-to-setup-iam-database-authentication-with-iam-identity-center-e8a24cd1a611?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a24cd1a611</guid>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[iam-identity-center]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 13:53:56 GMT</pubDate>
            <atom:updated>2023-07-22T13:53:56.670Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up individual db user credentials is a pain. It would be a lot nicer and cleaner to use AWS Credentials as db credentials. When using AWS IAM Identity Center and non publiclyavailable databases, this becomes a non trivial task.</p><p>In the following I will explain how to set this up for Amazon RDS MariaDB, Amazon RDS MySQL, Amazon RDS PostgreSQL, and Amazon Redshift.</p><h4>Basic Setup</h4><p>As the first step setup an db user with password, to check whether connection works in general.</p><p>Secure setups will always secure databases by not making them publicly reachable. Therefore test your connection first. Options to reach the db in the private subnet without having any self managed publically available endpoints are AWS VPC Client VPN, AWS SSM ssh session and AWS SSM port forwarding session (this one is my favourite)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16161da878f9c3301fd9c46087214da8/href">https://medium.com/media/16161da878f9c3301fd9c46087214da8/href</a></iframe><p>Setup data transport encryption using SSL. IAM Auth requires using SSL</p><ul><li>For RDS sslmode set to require will work</li><li>For Redshift you ned at least verify-ca</li></ul><p>If you like to set it to verify-full you have to make sure that the host is reachable. For public dbs, vpn connections and ssh this should be not a problem. When using AWS SSM port forwarding session, you need to add the db host to your hosts file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9fd2ed876af62666918405bab6a95dd/href">https://medium.com/media/a9fd2ed876af62666918405bab6a95dd/href</a></iframe><p>This is because, the port forwarding session will attach the db port to <a href="http://localhost/">localhost</a>. Instead of connection to the remote host, you will need to connect to localhost instead with your db client. But localhost is not the db host, therefore verify-full will not work without adding the db host to hosts. This way your client still connects to the db host, but is silently routed via localhost in the background.</p><h4>Individual IAM Identity Center Users : One DB Use</h4><p>For most users setting up a single db user for the IAM Identity Center Group will be enough. Databases allow multiple connection for the same user, therefore this will work.</p><p>Create a user in the database and apply the the database specific options to allow IAM authentication.</p><p><strong>RDS MariaDB and MySQL</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fc564db1f2eeff65fb64729aca0569e/href">https://medium.com/media/5fc564db1f2eeff65fb64729aca0569e/href</a></iframe><p><strong>RDS PostgreSQL</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901551bd2f9b180a825969ee99579c04/href">https://medium.com/media/901551bd2f9b180a825969ee99579c04/href</a></iframe><p><strong>Redshift</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b6975fbec6e61818b522f4532c1c10/href">https://medium.com/media/62b6975fbec6e61818b522f4532c1c10/href</a></iframe><p>Create IAM Policy and attach it to the IAM Identity Center SSO Role for the group</p><p>To find the correct role, look for a role with a path of /aws-reserved/sso.amazonaws.com/&lt;Region&gt; and a name prefix of /AWSReservedSSO_.</p><p><strong>RDS Policy</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52da12cb11d54d155bdd555b90d8c61e/href">https://medium.com/media/52da12cb11d54d155bdd555b90d8c61e/href</a></iframe><p>Be aware, that you need to put the Database Resource ID, not the Database Instance ID into the policy. You can find the Resource ID in the Configuration tab of your RDS Database Instance.</p><p><strong>Redshift Policy</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa1f49fd886946b938531ada5c861f1/href">https://medium.com/media/6fa1f49fd886946b938531ada5c861f1/href</a></iframe><p>As always, you can use also wildcards to be less restrictive. E.g. Allowing to log in to any database, as long as there is a matching username available.</p><ul><li>RDS &quot;arn:aws:rds-db:&lt;Region&gt;:&lt;AccountID&gt;:dbuser:*/&lt;Username&gt;&quot;</li><li>Redshift &quot;arn:aws:redshift:&lt;Region&gt;:&lt;AccountID&gt;:dbname:&lt;ClusterName&gt;/*&quot;</li></ul><p>When you log in to the database you will have to provide a password. The password you can obtain e.g. via the aws cli or programatically via the sdk.</p><p><strong>RDS</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/555a70c22b204ed75d26386150a9af5b/href">https://medium.com/media/555a70c22b204ed75d26386150a9af5b/href</a></iframe><p>You will get a response like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72605c423ebd0003c6ce5365f91cfcaf/href">https://medium.com/media/72605c423ebd0003c6ce5365f91cfcaf/href</a></iframe><p><strong>Redshift</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4d95875474c4708c889ea2297f589bd/href">https://medium.com/media/a4d95875474c4708c889ea2297f589bd/href</a></iframe><p>You will get a response like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53bf629c2461988fb02b2b5a9e5ba25e/href">https://medium.com/media/53bf629c2461988fb02b2b5a9e5ba25e/href</a></iframe><p>Redshift allows differnt methods of User Authentification. To tell which method to use, you have to prefix your username with the specific method. For IAM use IAM:</p><p>Your username will therefore be IAM:&lt;Username&gt; when loggin into Redshift.</p><h4>Individual IAM Identity Center Users : Individual DB Users</h4><p>Until now, every step was quite trivial and fairly good documented by AWS. Problems araise, when trying to setup a policy, which allows access for each AWS IAM Identitfy Center user to a sepecfic db user.</p><p>There several varaibles you can use in policies to make them dynamic to the user. One of these variables is aws:userid. As explained in the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#policy-vars-infotouse">AWS docs</a> when being logged in as a IAM Identity Center User, your aws:userid will be</p><blockquote>role-id<em>:</em>caller-specified-role-name</blockquote><blockquote><em>where </em><em>role-id is the </em><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids"><em>unique id of the role</em></a><em> and the caller-specified-role-name is specified by the </em><a href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_AssumeRole.html#API_AssumeRoleWithWebIdentity_RequestParameters"><em>RoleSessionName parameter</em></a><em> passed to the AssumeRoleWithWebIdentity request.</em></blockquote><p>This means if we create a RDS policy like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f761097a0f412e64dcf2b84926b3d37b/href">https://medium.com/media/f761097a0f412e64dcf2b84926b3d37b/href</a></iframe><p>We now allow each IAM Identity Center User to login to the Database using their aws:userid as a name. This solution has multiple issues:</p><ul><li>The aws:userid will be different for each account and role AWS IAM Identity Center Group for the same user, making the creation of the database role a huge pain.</li><li>This will not work for Redshift, as Redshift only allows a colon in the name to specify the Authentication Provider like IAM:. Creating a user having a name like <em>role-id</em>:<em>caller-specified-role-name</em> will not be accepted, as Redshift thinks it should create an external user with a authentication provider having the name <em>role-id.</em></li></ul><p>To get around this issue we use the knowledge of the aws:userid and create a statement condition to check against the aws:userid instead of using it directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcdcbb219ebbe89d4cf02933d2fee82b/href">https://medium.com/media/dcdcbb219ebbe89d4cf02933d2fee82b/href</a></iframe><p>This statement is only valid for a single AWS IAM Identity Center User, even if its attached to the whole AWS IAM Identity Center Group. Repeating statements for different users will allow us to create AWS IAM Identity Center User specific db users. In order not to write each statement individually you can e.g. when using Terraform use a list to create the statements</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3ccc24c17459a0dedf51b2f3e20f9e5/href">https://medium.com/media/c3ccc24c17459a0dedf51b2f3e20f9e5/href</a></iframe><p>This will create an individual statement for each user. If you have a really long list of users, then make sure to split your policy into multiple, as each policy allows a maximum of 6,144 characters.</p><p>I hope this helps some of you. Please let me know, if you have a better idea in mind, which possibly gets around the individual policy statements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a24cd1a611" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A more general solution to ST_Buffer(SphericalGeography, distance) in Trino]]></title>
            <link>https://medium.com/@christopher-scholz/a-more-general-solution-to-st-buffer-sphericalgeography-distance-in-trino-6cf765f3a3b2?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf765f3a3b2</guid>
            <category><![CDATA[trinos]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 14:01:42 GMT</pubDate>
            <atom:updated>2022-11-07T14:01:42.131Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to implement a projection wrapper to get around the spherical geography limitations of geospatial functions in Trino with clever usage of regular expressions and lambda functions.</strong></p><p>In my <a href="https://www.notion.so/A-more-general-solution-to-ST_Buffer-SphericalGeography-distance-in-Trino-f4eb2a1060d14b9dbee95fab260cc0fe">previous story</a> I created a algorithm to create a buffer around a point of type SphericalGeography in Trino. In this story we will dig into the the second possible solution of the problem. We will use a mercator projection to project our coordinates onto a map, apply ST_Buffer(Geometry, distance) and finally use the inverse of the projection to get the new coordinates. This is a simplified version of the way PostGis solves that problem. The main difference is, that we will not chose from a variety of projections in order to get the least distortion, but just stick with the <a href="https://en.wikipedia.org/wiki/Mercator_projection">mercator projection</a>.</p><p>For a complete problem description head over to the <a href="https://www.notion.so/A-more-general-solution-to-ST_Buffer-SphericalGeography-distance-in-Trino-f4eb2a1060d14b9dbee95fab260cc0fe">previous story</a>.</p><h3>Implementation</h3><p>For our solution we will have to project each pair of longitude and latitude using the mercator projection. After applying the ST_Buffer(Geometry, distance) function we will have to apply the inverse of the projection.</p><p>We could somehow deconstruct every possible SphericalGeography into rows of longitude and latitude, apply our projection and then aggregate it back into a Geometry, but there is an easier way.</p><p>Trino offers very good <a href="https://trino.io/docs/current/functions/regexp.html">regular expression</a> support and even features <a href="https://trino.io/docs/current/functions/lambda.html">lambda expressions</a>. We will use regexp_replace(string, pattern, function) → varchar. It is a normal <a href="https://trino.io/docs/current/functions/regexp.html?highlight=regexp_replace#regexp_replace">regexp_replace</a> function with a twist. Instead of a replacement varchar we provide a lambda function:</p><blockquote><em>Replaces every instance of the substring matched by the regular expression </em><em>pattern in </em><em>string using </em><em>function. The </em><a href="https://trino.io/docs/current/functions/lambda.html"><em>lambda expression</em></a><em> </em><em>function is invoked for each match with the </em><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#cg"><em>capturing groups</em></a><em> passed as an array. Capturing group numbers start at one; there is no group for the entire match (if you need this, surround the entire expression with parenthesis).</em></blockquote><p>We will need to identify every pair of longitude and latitude and then pass them to our lambda function, which will process them individually and then return a new varchar. For our pattern we will use the regular expression ([\-\d.]+) ([\-\d.]+). This regular expression is build from</p><ul><li>two capturing groups which are separated by a space.</li><li>each capturing group is build from [\-\d.]+</li><li>this matches a single character present in the list [\-\d.] between one and unlimited times, as many times as possible, giving back as needed (greedy).</li><li>\- matches the character ”-” literally → sign of the degree</li><li>\d matches a digit (equivalent to [0–9]) → digits of the degree</li><li>. matches the character ”.” literally → decimal point of the degree</li></ul><p>in order to not change our input we would use the following lambda function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e536a5b3a7ecb1f0a0acb6d9cee18c76/href">https://medium.com/media/e536a5b3a7ecb1f0a0acb6d9cee18c76/href</a></iframe><p>As you can see, we can use the array x of which each index corresponds to a capture group. Putting it into our regular expression it will look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0379de179cdf0f1042c9c48b33381521/href">https://medium.com/media/0379de179cdf0f1042c9c48b33381521/href</a></iframe><p>Next step is to actually implement the projection and the inverse.</p><p>The <em>x</em> coordinate for the mercator projection is calculated by <em>x = (<br>π R λ°)/180</em> where <em>λ°</em> is the longitude in degree. The <em>y</em> coordinate for the mercator projection is calculated by <em>y = R ln[tan(45 + φ°/2)]</em> where <em>φ°</em> is the latitude in degree.</p><p>For the inverse projection we have to solve for <em>λ°</em> and <em>φ°</em>.</p><p>The longitude in degree <em>λ°</em> for the inverse mercator projection is calculated by <em>λ° </em>= 180 x / (<em>π R)</em> where <em>x</em> is the x-axis of the map. The latitude in degree <em>φ°</em> for the inverse mercator projection is calculated by <em>φ° = 2 arctan exp y/R - 90</em> where <em>y</em> is the y-axis of the map.</p><p>A full explanation of the formula can be found <a href="https://en.wikipedia.org/wiki/Mercator_projection#Alternative_expressions">here</a>.</p><p>If we would implement those directly in trino <a href="https://trino.io/docs/current/functions/math.html#trigonometric-functions">trigonometric functions</a> we would run into a problem. All trigonometric functions are expressed in radians in Trino. So we need to convert into radians first. Trino also offers functions for this: <a href="https://trino.io/docs/current/functions/math.html#degrees">degrees</a>, <a href="https://trino.io/docs/current/functions/math.html#radians">radians</a>. Also we need to cast x[1] and x[2] as doubles before we can apply any mathematical functions.</p><p>After applying our projection we finally have to convert the double into a varchar again. We will do this after rounding to 8 decimal places. The final SQL for the projection looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdfb0285221460cd13f48f4331c32139/href">https://medium.com/media/cdfb0285221460cd13f48f4331c32139/href</a></iframe><p>The SQL for the inverse projection looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dfb08eaa7d8afe51c5dbbe3fc37d88a/href">https://medium.com/media/7dfb08eaa7d8afe51c5dbbe3fc37d88a/href</a></iframe><p>In between those two projections we can than apply any <a href="https://trino.io/docs/current/functions/geospatial.html">geospatial</a> function which allows Geometry as input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa6de9575ca5035dae193bc970319436/href">https://medium.com/media/aa6de9575ca5035dae193bc970319436/href</a></iframe><p>Finally we can put everything together using some CTEs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd96f9901ed92a4c99533fa6cfeea3ed/href">https://medium.com/media/bd96f9901ed92a4c99533fa6cfeea3ed/href</a></iframe><h4>Test</h4><p>Running our script and then putting our result into <a href="https://www.keene.edu/campus/maps/tool/">https://www.keene.edu/campus/maps/tool/</a> we can see a perfect circle. Our script works.</p><figure><img alt="Circle with 96 segments around Berlin/Germany." src="https://cdn-images-1.medium.com/max/1024/1*cXSR9ybdGCNMjtF6Vou1vw.png" /><figcaption>Plot of the result of the script</figcaption></figure><h3>Conclusion</h3><p>With this easy solution to the original problem we essentially created a wrapper around any function which accepts a single Geometry type. Also it is a very good example how powerful lambda functions in Trino are.</p><p>In a next iteration you could add more possible projections and add a function which chooses the best fitting projection.</p><p>Also we could make this a <a href="https://docs.getdbt.com/docs/build/jinja-macros">dbt macro</a> (if you haven’t tried <a href="https://www.getdbt.com/">dbt</a> yet, then give it a try! I think it is worth for every Data Engineer and Data Analyst to have a look), which would allow us to not having to repeat the code for any other function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf765f3a3b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of hierarchies in Trino using dbt]]></title>
            <link>https://medium.com/@christopher-scholz/analysis-of-hierarchies-in-trino-using-dbt-7f29fcb99ae5?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f29fcb99ae5</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[trinos]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[hierarchy]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 15:50:34 GMT</pubDate>
            <atom:updated>2022-11-04T15:50:34.110Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why large hierarchies with unlimited number of levels can be a nuisance when querying in Trino and how to work around these issues.</strong></p><figure><img alt="Abstract painting of infinite tunnel of statements, which was generated by stable diffusion." src="https://cdn-images-1.medium.com/max/512/1*d5WPLW-qHMhMHvNKXbo8wA.jpeg" /><figcaption>“A distributed recursive query.” — generated art using stable diffusion</figcaption></figure><p>Trino is awesome, just not with recursive CTEs. The problem is summerized in this <a href="https://github.com/trinodb/trino/issues/1122#issuecomment-632402097">issue</a> quite well.<br>Essentially Trino produces a huge <em>UNION</em> statement for which each <em>SELECT</em> does not reference the previous <em>SELECT</em> but instead produces the previous <em>SELECT</em> from scratch and wraps it in another level of the recursive query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b83a5ac7477b3e952eccedc39372505d/href">https://medium.com/media/b83a5ac7477b3e952eccedc39372505d/href</a></iframe><p>produces behind the curtain this code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b73d4da417787d7a6843d6d43fddb881/href">https://medium.com/media/b73d4da417787d7a6843d6d43fddb881/href</a></iframe><p>but this is unnecessary complex. Instead it should have created code like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d4b30636c67953fc7beb1c100966e7d/href">https://medium.com/media/8d4b30636c67953fc7beb1c100966e7d/href</a></iframe><p>But there is no mechanism in Trino which will create temporary tables. Instead we will create a custom dbt materialization, which will do just this. If you haven’t checked out dbt, it will be worth your time.</p><p>Prerequisites: dbt-core^=1.3.0, dbt-trino^=1.3.0</p><p>If you need to learn more about custom materialization, have a look <a href="https://docs.getdbt.com/guides/legacy/creating-new-materializations">here</a>. We will use the standard <a href="https://github.com/starburstdata/dbt-trino/blob/master/dbt/include/trino/macros/materializations/table.sql">dbt_trino.table</a> materialization and modify it.</p><p>The table materialization in dbt-trino has lots of code, but the main parts can be found <a href="https://github.com/starburstdata/dbt-trino/blob/8b83f066eea6f2366f5ec296931b3a09d00a620b/dbt/include/trino/macros/materializations/table.sql#L45-L47">here</a>(<em>on_table_exists = rename</em>) and <a href="https://github.com/starburstdata/dbt-trino/blob/8b83f066eea6f2366f5ec296931b3a09d00a620b/dbt/include/trino/macros/materializations/table.sql#L66-L68">here</a>(<em>on_table_exists = drop</em>). Instead of this we substitute with a call to the macro <em>recursive_create_table_as</em> which implements our logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d240b6c7e6c4579d5e5c7698c40b1b1b/href">https://medium.com/media/d240b6c7e6c4579d5e5c7698c40b1b1b/href</a></iframe><p>Next we need to get around two limitations.</p><ul><li>only one sql model, which we need to split into a anchor and recursive member query</li><li>no do…while loop or for loop break in the dbt jinja2 available (we don’t know how many recursions we need to run beforehand)</li></ul><h4>Split sql model</h4><p>In our model we add some characters __RECURSIVE__, which splits the anchor and the recursive member. In the macro we use a regular expression to split the sql code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597055e5fdab5146d0c82a81f0eee3a8/href">https://medium.com/media/597055e5fdab5146d0c82a81f0eee3a8/href</a></iframe><h4>Loop</h4><p>Instead of using a loop we will also stick to a recursion. We will call our macro initially with <em>depth=0</em>. As long as we the break condition(no new rows) is not met we will call the macro with depth++.</p><p>Instead of creating a new table for each recursion, we will insert the result of each recursion into the main table and add a <em>__depth</em> column to keep track of the depth and query only needed data. After the break condition is met, we remove this column again. In order to add the column we will need to wrap the anchor and recursive member.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b655af38eba0bbf4724b1fe090bf2f7f/href">https://medium.com/media/b655af38eba0bbf4724b1fe090bf2f7f/href</a></iframe><p>Also we need to create a small macro which will insert, instead of create a new table for each recursion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456c07cc7087a722ab54698038adcbf8/href">https://medium.com/media/456c07cc7087a722ab54698038adcbf8/href</a></iframe><h4>Break condition</h4><p>The break condition is met, if the recursive member does not produce any new rows. To check this, we need to query the table with the current depth and check whether there is new data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec8d6a268b599e9c52541d3e22c4b5d/href">https://medium.com/media/aec8d6a268b599e9c52541d3e22c4b5d/href</a></iframe><p>Using a if statement we check whether the returned number is bigger than zero. If not, our break condition is met.</p><h4>Main</h4><p>In our main query we will need to check whether we at the initial <em>depth=0</em> or at <em>depth&gt;0</em>. If <em>depth=0 </em>we use the anchor member after adding the depth column to create a new table. Afterwards we call the macro again with <em>depth=1</em>.</p><p>If <em>depth&gt;0</em>, we use the recursive member. As we only want to query the target table where <em>depth-- </em>we cannot just use <a href="https://docs.getdbt.com/reference/dbt-jinja-functions/this"><em>{{ this }}</em></a> in our model. Instead we will put a custom <em>__THIS__</em> string, which we replace while running our macro.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a209ba79497b74b4e3f668c84757204d/href">https://medium.com/media/a209ba79497b74b4e3f668c84757204d/href</a></iframe><p>Also we add our depth again. After running the modified recursive member and inserting the data into our target table, we check whether there are any new rows. If yes, than we do it all over again, but with <em>depth++</em>. If break condition is met, we remove the <em>__depth</em> column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ba42c758a86d79e90af4eaafc3bcf4/href">https://medium.com/media/85ba42c758a86d79e90af4eaafc3bcf4/href</a></iframe><p>The full materialization can be found <a href="https://github.com/christopherscholz/dbt_trino_recursive_materialization/blob/main/macros/materializations/recursive.sql">here</a>.</p><h3>Example</h3><p>In order to try our recursive materialization we need some data. This will create 10,000,000 rows with 500,000 groups of 20 member linear parent, child relationships.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a777da25f4f56f655984fbf1f8e7951/href">https://medium.com/media/1a777da25f4f56f655984fbf1f8e7951/href</a></iframe><p>If we want to get all parents for each child, we can use our recursive materialization like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81d74b8a4547e6c36fe4862f2904c69a/href">https://medium.com/media/81d74b8a4547e6c36fe4862f2904c69a/href</a></iframe><h3>Conclusion</h3><p>Trino and dbt go great together. Where Trino is limited, we can use some dbt codes to work around this. I still hope that</p><ul><li>temporary tables <a href="https://github.com/trinodb/trino/issues/5686">https://github.com/trinodb/trino/issues/5686</a></li><li>optimized recursive cte <a href="https://github.com/trinodb/trino/issues/1122">https://github.com/trinodb/trino/issues/1122</a></li><li>cte caching <a href="https://github.com/trinodb/trino/issues/5878">https://github.com/trinodb/trino/issues/5878</a></li></ul><p>will be implemented in Trino in the future, which will be even better, but until then we are all set.</p><p>The full code can be found <a href="https://github.com/christopherscholz/dbt_trino_recursive_materialization">here</a> and be used as a dbt <a href="https://docs.getdbt.com/docs/build/packages#git-packages">package</a> using</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/624dd91e9b6323f1482b53533d6dc752/href">https://medium.com/media/624dd91e9b6323f1482b53533d6dc752/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f29fcb99ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce the size of your Node.js docker image by up to 90%]]></title>
            <link>https://blog.devgenius.io/reduce-the-size-of-your-node-js-docker-image-by-up-to-90-53aad23890e2?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/53aad23890e2</guid>
            <category><![CDATA[distroless]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 16:21:41 GMT</pubDate>
            <atom:updated>2022-11-02T11:51:26.100Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Some easy tweaks for your next Node.js docker image, which will reduce the size drastically.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*luTuhYvnbScnF6-a" /><figcaption>Photo by <a href="https://unsplash.com/@siora18?utm_source=medium&amp;utm_medium=referral">Siora Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A typical Node.js image is roughly 350MB in size. Together with your <em>node_modules</em> and <em>src</em> this often exceeds 1 GB. There are many ways how you can reduce the size of your image</p><ul><li>Choose the right base image</li><li>Install production dependencies only</li><li>Use multi stage build</li><li>Copy required files only</li><li>Prune node_modules</li></ul><h3>Example Application</h3><p>Our example application is a the default react app created by npx create-react-app, which is served via express. I have also added eslint as a development dependency. The code for the application can be found here: <a href="https://github.com/christopherscholz/reduce_node_docker_image_size/tree/main/context">https://github.com/christopherscholz/reduce_node_docker_image_size/tree/main/context</a></p><p>In the following, I will not change the application code at all, but only the Dockerfile code.</p><h3>Choose the right base image</h3><p>First of all we can choose from different node docker images when creating our Dockerfile. The most common tag is <em>latest</em>, which is a alias for <em>current</em>, which is an alias for <em>current-bullseye</em> which is an alias for <em>bullseye</em>, which is an alias for <a href="https://hub.docker.com/layers/library/node/19.0.0-bullseye/images/sha256-2b00d259f3b07d8aa694b298a7dcf4655571aea2ab91375b5adb8e5a905d3ee2?context=explore"><em>19.0.0-bullseye</em></a> at the time of writing this story. For all our Dockerfiles we will copy the application, install react package, build react and install the express package. For the <em>bullseye</em> Dockerfile this looks like that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a3b0b18a367dfc9ed7107bc5e1b3318/href">https://medium.com/media/2a3b0b18a367dfc9ed7107bc5e1b3318/href</a></iframe><p>On amd64 this image has the size of 1.4 GB, which will be our starting size.</p><p>Instead of <em>bullseye</em> we also have the option of <em>bullseye-slim</em> and <em>alpine</em>. If we only change the FROM node:19.0.0-bullseye statement of our Dockerfile to FROM <a href="https://hub.docker.com/layers/library/node/19.0.0-bullseye-slim/images/sha256-978417e9dd45a1b7f673077d56fc54cb7bab98f6592f12fe7861d80a4669ad4a?context=explore">19.0.0-bullseye-slim</a> or FROM <a href="https://hub.docker.com/layers/library/node/19.0.0-alpine3.16/images/sha256-e74f32d2a985f4d7d3ced0754bb1c40c68b6c0431043b154cb44127546e94f11?context=explore">19.0.0-alpine3.16</a>, we shrink the image to 652.75 MB (-53.4% overall) or 576.89 MB (-58.8% overall, -11.6% to the previous) respectively.</p><p>This is the biggest and easiest decrease in size, but by far not all we can do.</p><h3>Install production dependencies only</h3><p>In a next step we can make sure not to add the development dependencies while building our docker image. There are multiple ways to do this. I believe the easiest is by setting the environment variable <em>NODE_ENV</em> to <em>production</em>. We can do this by adding the line ENV NODE_ENV=production after FROM 19.0.0-alpine3.16 statement.</p><p>By doing this we effectively remove the <em>eslint </em>package. This shrinks the image to 566.73 MB (-59.5% overall, -1.8% to the previous optimization)</p><h3>Use multi stage build</h3><p>Another way to reduce our image size is using a multi stage build. The idea is to build the application using a <em>builder</em> image and then copy only the needed files to run the application into a runner <em>image</em>.</p><p>In case of our alpine image this could look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2adf7ae18cd7789926136668e4a5d0d2/href">https://medium.com/media/2adf7ae18cd7789926136668e4a5d0d2/href</a></iframe><p>This shrinks the size of the docker image to 178.04 MB (-87.3% overall, -68,6% to the previous optimization).</p><p><em>Alpine</em> is not the smallest base image we can use. A true minimal Linux bundled with a <em>Node.js</em> runtime is <a href="https://github.com/GoogleContainerTools/distroless/blob/main/nodejs/README.md">distroless/nodejs18-debian11</a>. The only way to use it is to use a multi stage build, as we can only COPY files to the image and not RUN any applications, as there is no shell installed. The <em>Node.js</em> runtime is also stripped down to the bare minimum, as it even removes <em>npm</em> and <em>npx</em>. A Dockerfile using the distroless image looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c031ae4191dc45fc135245e1f51f006e/href">https://medium.com/media/c031ae4191dc45fc135245e1f51f006e/href</a></iframe><p>This shrinks the size of the docker image to 162.53 MB (-88.4% overall, -8.7% to the previous optimization).</p><h3>Copy required files only</h3><p>We can further reduce the size of the image by making sure to only COPY relevant files. Having build relevant files in the final docker image is also a common security issue.</p><p>For our application this means switching out COPY --from=builder /app/express /app/express with</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c0241eaf6c86ee541086531c1e36b03/href">https://medium.com/media/5c0241eaf6c86ee541086531c1e36b03/href</a></iframe><p>In our case this only removes two files (.gitignore and package.json), so the size implication is minimal. The new size is 162.41 MB (-88.4% overall, -0.1% to the previous optimization).</p><h3>Prune node_modules</h3><p>Another step we can automate is to prune the node_modules further. E.g. the tool <a href="https://github.com/tj/node-prune">https://github.com/tj/node-prune</a> is an easy way to do this. We only need to download the binary and run it inside the npom package. root. We can do this in one simple statement</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce05d3003e9d33e93317b4d8ffe116c/href">https://medium.com/media/5ce05d3003e9d33e93317b4d8ffe116c/href</a></iframe><p>or if we use a base image with curl instead of wget</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95922c982d20e9eb1d309163da1a1b16/href">https://medium.com/media/95922c982d20e9eb1d309163da1a1b16/href</a></iframe><p>This was our final step to decrease the size of our image. The final size is 161.44 MB (-88.5% overall, -0.6% to the previous optimization). The final Dockerfile looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/199687a79021b73e9d7fc178f26ab94e/href">https://medium.com/media/199687a79021b73e9d7fc178f26ab94e/href</a></iframe><p>We could go deeper here by manually checking files we could remove. A good way to analyze the image is to use the <a href="https://github.com/wagoodman/dive">dive</a> tool.</p><h3>Extra: Speed up builds significantly by choosing a better build order</h3><p>Every statement in your Dockerfile creates a new layer. Layers are cached. If a layer changes all downstream layers also have to be rebuild. So it is very important to structure our Dockerfile in a way that the often updated layers are at the end and nearly static layers are at the beginning of the Dockerfile. If you use this principle smartly, you can significantly reduce your build time.</p><h3>Conclusion</h3><p>We got our docker image from 1.4 GB down to 161.44 MB, which is a decrease of 88.5%.</p><p>There is a lot you can do in order to reduce the size of your node docker image and speed up the build time. The ideas usually apply to other applications as well. E.g. using a distroless image might decrease your next Rust application by a lot.</p><p>I hope you found those ideas interesting and are able to apply them to your next or current project.</p><p>Also a big thanks to the authors of the following stories as those helped me to learn a lot about optimizing docker builds</p><ul><li><a href="https://blog.tarkalabs.com/how-to-reduce-nodejs-docker-image-by-70-e799b3d3396a">How to reduce your Node.js docker image size by 70%</a> by <a href="https://medium.com/u/5c0d85235c3b">Madhava Reddy SV</a></li><li><a href="https://medium.com/trendyol-tech/how-we-reduce-node-docker-image-size-in-3-steps-ff2762b51d5a">How We Reduce Node Docker Image Size In 3 Steps</a> by <a href="https://medium.com/u/18b9b9a2b09e">Soner Çökmen</a></li><li><a href="https://medium.com/inside-sumup/stop-using-alpine-docker-images-fbf122c63010">Stop using Alpine Docker images</a> by <a href="https://medium.com/u/e8ced5abda1">Vitor Falcao</a></li><li><a href="https://tsh.io/blog/reduce-node-modules-for-better-performance/">Honey, I shrunk the node_modules! …and improved app’s performance in the process. On node module size</a> by Adam Polak</li><li><a href="https://tier.engineering/Tips-for-optimising-docker-build">Tips for Optimizing Docker Builds</a> by <a href="https://www.linkedin.com/in/abiodunjames/">James Samuel</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53aad23890e2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/reduce-the-size-of-your-node-js-docker-image-by-up-to-90-53aad23890e2">Reduce the size of your Node.js docker image by up to 90%</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ST_Buffer(SphericalGeography, distance) for a point in Trino]]></title>
            <link>https://medium.com/@christopher-scholz/st-buffer-sphericalgeography-distance-for-a-point-in-trino-9bee4d2f3a7?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bee4d2f3a7</guid>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[trinos]]></category>
            <category><![CDATA[geography]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 14:39:31 GMT</pubDate>
            <atom:updated>2022-10-31T14:46:12.626Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to get around the spherical geography limitations of geospatial functions in Trino with a bit of math and SQL.</strong></p><p>In one of my previous jobs, I had the task of segmenting the beginning and end of hundreds of thousands cab trips based on whether they were within a circle based on the coordinates of a landmark and a maximum distance from that landmark. This sounds like an easy task when using <a href="https://postgis.net/">PostGIS</a>. Add a buffer around the coordinates and then check whether this area contains the other points. This is possible, because PostGIS supports the Geography type for <a href="https://postgis.net/docs/ST_Buffer.html">ST_Buffer</a>. But we didn’t have PostGIS available and used <a href="https://trino.io/">Trino</a> for our analysis instead. Also we wanted to answer this question quickly, without putting too much effort into this analysis, like setting up another PostgreSQL database with the PostGIS extension or writing a <a href="https://trino.io/docs/current/develop/spi-overview.html#plugin">Trino plugin</a>. So, in order not to waste more than one working day, we opted for a pure SQL solution.</p><p>In this story, I explain step by step how we came up with the solution and the problems we encountered.</p><h3>ST_Buffer(Geometry, distance) does not fit</h3><p>Before we dived into the depth of math and SQL we tried to create the the circle by converting the point of type <a href="https://trino.io/docs/current/functions/geospatial.html?highlight=sphericalgeography">SphericalGeography</a> to type <a href="https://trino.io/docs/current/functions/geospatial.html?highlight=geometry">Geometry</a>, applying the <a href="https://trino.io/docs/current/functions/geospatial.html?highlight=st_buffer#ST_Buffer">ST_Buffer(Geometry, distance</a>) function and then converting back to the SphericalGeography type. Already by choosing the distance here, we got stuck. How to translate a distance in meter into a degree? The answer is easy. You can’t.</p><p>The length of one degree longitude varies a lot. At the poles (+-90° latitude) the distance of one degree longitude is 0km, but at the equator (0° latitude) it is 111.32km. Often people forget, that the earth is not a perfect sphere, but rather a ellipsoid. Also the distance of one degree latitude changes. At the pole one degree latitude is roughly 111.694km and at the equator it is 110.574. More about this <a href="https://en.wikipedia.org/wiki/Latitude#Length_of_a_degree_of_latitude">here</a>.</p><p>For our problem this means that we need a degree value to be added for both latitude and longitude to define a point on the circle. Each point on the circle has a different degree value to add for latitude and longitude.</p><p>We can show this quite easily by e.g. adding one degree of buffer around some coordinates and then plotting the result on a map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41473d172f9fe6c4715a80b59696803f/href">https://medium.com/media/41473d172f9fe6c4715a80b59696803f/href</a></iframe><p>Which results in</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4fa415cb8b658b7925a68afd25bdff6/href">https://medium.com/media/b4fa415cb8b658b7925a68afd25bdff6/href</a></iframe><p>Using e.g. <a href="https://www.keene.edu/campus/maps/tool/">https://www.keene.edu/campus/maps/tool/</a> we can plot these points. And we clearly see that this is not a circle at all.</p><figure><img alt="A vertical ellipse made from 96 segments around Berlin/Germany." src="https://cdn-images-1.medium.com/max/849/1*gd0yNJmqerkCQPRf5UXh0Q.png" /><figcaption>Plotted result of ST_Buffer(Geometry, distance) in Trino</figcaption></figure><h3>Finding a solution</h3><p>There are many different solutions to our problem. Two stick out the most.</p><ol><li>Calculate each point on the circle individually from bearing and distance</li><li>Use a map projection, apply the ST_Buffer(Geometry, distance) and finally use the inverse of the projection</li></ol><p>The problem with the second solution is, that these projections are always somehow distorted. On the other hand it is a much more general solution to the problem. This is also <a href="https://postgis.net/docs/ST_Buffer.html">the way PostGIS solves that problem</a>:</p><blockquote><em>For geography, this is a wrapper around the geometry implementation. It determines a planar spatial reference system that best fits the bounding box of the geography object (trying UTM, Lambert Azimuthal Equal Area (LAEA) North/South pole, and finally Mercator ). The buffer is computed in the planar space, and then transformed back to WGS84. This may not produce the desired behavior if the input object is much larger than a UTM zone or crosses the dateline</em></blockquote><p>Our solution is using method one instead, as we only need to implement the ST_Buffer function for a point and not any shape.</p><p>In order to implement the solution we need to</p><ol><li>Split point of type SphericalGeography into latitude and longitude</li><li>Create a list of bearings</li><li>Calculate for each bearing and the common distance a point on the circle</li><li>Aggregate points into a polygon of type SphericalGeography</li></ol><h4>Split point of type SphericalGeography into latitude and longitude</h4><p>In order to split the point of type SphericalGeography into latitude and longitude, we need to get the text representation of it and then use a regular expression to get the two numbers. We can get the text representation by using <a href="https://trino.io/docs/current/functions/geospatial.html?highlight=ST_AsText#ST_AsText">ST_AsText</a>, but we need to convert the point into type Geometry first.</p><p>This can be done using <a href="https://trino.io/docs/current/functions/geospatial.html?highlight=to_geometry#to_geometry">to_geometry</a>. The pattern for the regular expression is [\-\d.]+<em>,</em> which matches a single character present in the list [\-\d.] between one and unlimited times, as many times as possible, giving back as needed (greedy).</p><ul><li>\- matches the character ”-” literally → sign of the degree</li><li>\d matches a digit (equivalent to [0–9]) → digits of the degree</li><li>. matches the character ”.” literally → decimal point of the degree</li></ul><p>For more details: <a href="https://regex101.com/">https://regex101.com/</a></p><p>The function <a href="https://trino.io/docs/current/functions/regexp.html?highlight=regexp_extract_all#regexp_extract_all">regexp_extract_all(string, pattern)</a><em> r</em>eturns the substring(s) matched by the regular expression pattern in string as an array.</p><p>We use a <a href="https://trino.io/docs/current/sql/select.html?highlight=lateral#lateral">lateral join</a> CROSS JOIN LATERAL (which can also be written as , LATERAL) to add the regular expression result to our table, so we do not have to write the expression twice.</p><p>The two array items are then extracted using their index and casted from varchar into a double.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f59281b4b674a8a472c23d84c87f10a7/href">https://medium.com/media/f59281b4b674a8a472c23d84c87f10a7/href</a></iframe><p>As result we get two columns (longitude and latitude) with the corresponding values from the point of type SphericalGeography.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f078f9f375af6e460910f7a54d49b2/href">https://medium.com/media/c6f078f9f375af6e460910f7a54d49b2/href</a></iframe><h4>Create a list of bearings</h4><p>Next we need a list of bearings. Each bearing will later correspond to one point on the circle. We will need to define how many segments our circle should have. For this PostGIS has added the quad_segs parameter, which is the number of line segments used to approximate a quarter circle.</p><p>Using the <a href="https://trino.io/docs/current/functions/array.html?highlight=sequence#sequence">sequence</a> function we can create an array of numbers. Unfortunately the function does not support sequence(double, double, double). Instead we need to use sequence(integer, integer, integer). To make it a bit more useful we multiply by a thousand to get at least three decimals. Later we divide the bearings again by a thousand but cast them to double before.</p><p>For our sequence we add the following parameters</p><ul><li>0° as start</li><li>360° as end</li><li>360° divided by four quadrants times the number of segments per quadrant</li></ul><p>The <a href="https://trino.io/docs/current/sql/select.html?highlight=unnest#unnest">unnest</a> keyword expands an array into a column. Using , before means, that we cross joins the column to the first table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1354545ff6331669b3a757874c9b201/href">https://medium.com/media/c1354545ff6331669b3a757874c9b201/href</a></iframe><p>As result we get one column with four times the number of segments per quadrant plus one rows. E.g. quad_segs=8 results in 32+1=33 rows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c78b1ee078b382b4667cbb5d62aa2196/href">https://medium.com/media/c78b1ee078b382b4667cbb5d62aa2196/href</a></iframe><h4>Calculate for each bearing and the common distance a point on the circle</h4><p>The main step is calculating the points on the circle for each bearing. We can get the formula from <a href="http://www.movable-type.co.uk/scripts/latlong.html">http://www.movable-type.co.uk/scripts/latlong.html</a>. Heavily using the triangular function of trino will get us our solution. Also we have to keep in mind, to convert our degrees into radians and back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd36f5d0f7a7bd700c61066f4683eca6/href">https://medium.com/media/dd36f5d0f7a7bd700c61066f4683eca6/href</a></iframe><p>The result of this is a coordinate which is 100km in 45° from north from the original coordinate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0481cf9df942861b6f627bc8d6b514b2/href">https://medium.com/media/0481cf9df942861b6f627bc8d6b514b2/href</a></iframe><h4>Aggregate points into a polygon of type SphericalGeography</h4><p>As last step we need to aggregate the points into a polygon. For this we use a variety of functions</p><ul><li><a href="https://trino.io/docs/current/functions/math.html?highlight=round#round">round(x, d)</a> → to make sure we don’t get to many decimals, we use the round function, which rounds x to d decimal places.</li><li><a href="https://trino.io/docs/current/functions/conversion.html?highlight=format#format">format(format, args...)</a> → Returns a formatted string using the specified <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Formatter.html#syntax">format string</a> and arguments. As we will concatenate everything together into a geometry string, we cast the latitude and longitude into varchar using %.8f, which corresponds to a decimal number without thousand separator and eight decimals.</li><li><a href="https://trino.io/docs/current/functions/string.html?highlight=replace#replace">replace(string, search, replace)</a> → Replaces all instances of <em>search</em> with replace in string. To make sure we get a dot as a decimal point we need to replace a comma with a dot.</li><li><a href="https://trino.io/docs/current/functions/string.html?highlight=replace#string-operators">||</a> → operator performs concatenation. We need pairs of longitude and latitude for each point in form longitude latitude. Later we concatenate POLYGON (( and )) to the list of points.</li><li><a href="https://trino.io/docs/current/functions/aggregate.html?highlight=array_agg#array_agg">array_agg(x)</a> → Returns an array created from the input x elements. All varchars of longitude and latitude are aggregated into an array</li><li><a href="https://trino.io/docs/current/functions/string.html?highlight=concat_ws#concat_ws">concat_ws(string, array(varchar))</a> → Returns the concatenation of elements in the array using string as a separator. If string is null, then the return value is null. Any null values in the array are skipped. Each longitude latitude varchar are concatenated into a list separated with a comma.</li><li><a href="https://trino.io/docs/current/functions/geospatial.html?highlight=st_geometryfromtext#ST_GeometryFromText">ST_GeometryFromText(varchar)</a> → Returns a Geometry type object from WKT representation. We convert our concatenated polygon from the text representation to a Geometry.</li><li><a href="https://trino.io/docs/current/functions/geospatial.html?highlight=to_spherical_geography#to_spherical_geography">to_spherical_geography(Geometry)</a> → Converts a Geometry object to a SphericalGeography. We convert our polygon of type Geometry into type SphericalGeography.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed11ef92fd1289840d27bbf4c3ad9558/href">https://medium.com/media/ed11ef92fd1289840d27bbf4c3ad9558/href</a></iframe><p>As a result we get an object with a text representation of the polygon.</p><h4>Putting all together</h4><p>As last step we need to put these for steps into one sql script. We heavily use CTEs in order to make our code a little bit cleaner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbcb5e639ddbdf20d58cd4ccb37983a8/href">https://medium.com/media/dbcb5e639ddbdf20d58cd4ccb37983a8/href</a></iframe><h4>Test</h4><p>As test we again use our Point with longitude 13.3777052 and latitude 52.5162682, but this time 100km. Each quadrant of the circle should have 24 segments. This translates into a input CTE of</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0a241ba08c14ca99c212528416adad8/href">https://medium.com/media/c0a241ba08c14ca99c212528416adad8/href</a></iframe><p>The result is a polygon made up of 97 (24*4+1) points. We plot this polygon again using the same tool as in the start. This time we get a perfect circle with a radius of 100km.</p><figure><img alt="A circle made from 96 segments around Berlin/Germany." src="https://cdn-images-1.medium.com/max/846/1*LJJN_8wanIUM-hFB4nIj_Q.png" /><figcaption>Plotted result of our test</figcaption></figure><h3>Conclusion</h3><p>It shows how we can get around limitations by just using some math. It also shows how strong Trino is. Unfortunately we have to repeat this code every time we need it, as we cannot create a scalar function using Trino. We might get around this issue by using a <a href="https://docs.getdbt.com/docs/build/jinja-macros">dbt macro</a> (if you haven’t tried <a href="https://www.getdbt.com/">dbt</a> yet, then give it a try! I think it is worth for every Data Engineer and Data Analyst to have a look) instead, but also here we will probably run into a limitation, as we cannot join on tables using a Geometry or SphericalGeography type for a column. So the only good solution would be extending the geospatial plugin of trino to avoid this hassle.</p><p>This kind of calculation takes a lot of computational power. Therefore we need to make sure to reduce the number of calculations by persisting the results and then query e.g. relationships afterwards using the resulting shapes. Even better would be to not use SphericalGeography, but use method two and project the coordinates onto a map. These computations take far less computational steps and therefore are much faster.</p><p>If you would like to try out my solution an easy way is to use the docker-compose from <a href="https://github.com/starburstdata/dbt-trino">starburstdata/dbt-trino</a>.</p><p>Big thanks to <a href="https://de.linkedin.com/in/ayartalha">Talha Ayar</a>, who iterated with me on my first implementation of the circle around a point of type SphericalGeography problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bee4d2f3a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Website Using Rust, GraphQL, React]]></title>
            <link>https://medium.com/better-programming/building-a-website-using-rust-graphql-react-72f2783f2a30?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/72f2783f2a30</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 12:55:11 GMT</pubDate>
            <atom:updated>2022-10-26T15:11:31.920Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to help you create faster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mv8lB66qz23Eq1Js" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a <a href="https://medium.com/@christopher-scholz/building-a-website-using-rust-grpc-web-react-7412f1596a17">previous article</a>, I explained how I created my personal website using React, gRPC-web, and Rust. In this article, I will change the code to use a GraphQL Interface instead.</p><p>For the server, I’m using <a href="https://rocket.rs/">Rocket</a> web framework and the <a href="https://github.com/graphql-rust/juniper">Juniper</a> library to serve <a href="https://graphql.org/">GraphQL</a>.</p><p>For the client, I’m using <a href="https://reactjs.org/">React</a> and <a href="https://www.apollographql.com/docs/react/">Apollo Client</a> and serving it via <a href="https://expressjs.com/">Express</a>.</p><h3>Server</h3><p>For the server, we will need the following crates:</p><ul><li>rocket=&quot;0.5.0-rc.2”</li><li>juniper={version=&quot;0.15.10&quot;,features=[&quot;uuid&quot;,&quot;chrono&quot;]}</li><li>juniper_rocket=&quot;0.8.2” helps integrating juniper with rocket</li><li>chrono={version=&quot;0.4.22&quot;,features=[&quot;serde&quot;]} used to create timestamps and serialize them to json</li><li>uuid={version=&quot;0.8.2&quot;,features=[&quot;v4&quot;,&quot;serde&quot;]} used to create UUIDs and serialize them to json</li></ul><p>For this example, we will not implement a database but use a <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html">HashMap</a> to store our data. Let’s start by declaring the use of the needed crates and adding a struct for the Database. Our page Object will be called Page, and we will be storing it using a String key called “home”. We will also need to let our fields access our Database. To do this, we need to implement Context for our Database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35ed5d7f284969f19c52f59722de35af/href">https://medium.com/media/35ed5d7f284969f19c52f59722de35af/href</a></iframe><p>Having this, we will first implement our Schema and initialize our Database with the content. The content follows again, like in the gRPC-web app, the <a href="https://editorjs.io/">Editor.js</a> schema.</p><h4>Schema</h4><p>Juniper has macros for defining GraphQL <a href="https://docs.rs/juniper/0.15.10/juniper/attr.graphql_object.html">Objects</a> and <a href="https://docs.rs/juniper/0.15.10/juniper/attr.graphql_interface.html">Interfaces</a>. We will be using them. Juniper allows us to use a <a href="https://graphql-rust.github.io/juniper/master/types/objects/defining_objects.html">struct</a> or an implementation as a GraphQL object. Using an implementation allows us to define our resolvers manually. For example, we could resolve calculated fields. The same can also be applied to GraphQL interfaces.</p><p>Let’s first try a simple struct as a GraphQL Object for our Page. For our blocks, we will use a vector and call our Block BlockValue. This will become clear as soon as we implement our Block Interface, as every Block type needs to be a Block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e0e738b7d2bac1e0d49fe211b5cf94/href">https://medium.com/media/c0e0e738b7d2bac1e0d49fe211b5cf94/href</a></iframe><p>We will also need an implementation, as we want to make it easier to create a new Page. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db943a8011af906627d4dad16df24ddb/href">https://medium.com/media/db943a8011af906627d4dad16df24ddb/href</a></iframe><p>As already mentioned, every Block Type is a Block. Therefore we will implement an interface called Block. This Block should have two standard fields id and type. As type is a reserved name, we will need to rename it and annotate it to be renamed. As we implement three objects for this interface, we will also need to name them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f57b672ea3801fbd2f3a8e7fd1cb0a/href">https://medium.com/media/43f57b672ea3801fbd2f3a8e7fd1cb0a/href</a></iframe><p>As the to_vec() needs the trait Clone, we will have to implement it for the Interface enum, which is generated by the macro graphql_interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ac056f8329abacab3de4a1b61a74074/href">https://medium.com/media/0ac056f8329abacab3de4a1b61a74074/href</a></iframe><p>Now we can implement our three different Block types. I will only show the list type, as the other two are nearly identical. The block_type will be derived using a function and not be stored in our database. We will also add a new function to our ListBlock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771bfa6479a1732b6c225dae26f2aea2/href">https://medium.com/media/771bfa6479a1732b6c225dae26f2aea2/href</a></iframe><p>Next, we will implement the interface and the GraphQL Object. As we use our implementation as our object, we will need to duplicate some code. If you know a better solution, please let me know.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ef26215eee9b330f0759e9f6a2f0b71/href">https://medium.com/media/9ef26215eee9b330f0759e9f6a2f0b71/href</a></iframe><p>The ListData will have a style field that is constrained to two options. We can achieve this by using an enum, and the <a href="https://graphql-rust.github.io/juniper/master/types/enums.html">GraphQLEnum</a> derive macro.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23dc67c78a588c63ac92468f0bf61dc0/href">https://medium.com/media/23dc67c78a588c63ac92468f0bf61dc0/href</a></iframe><p>Finally, we can implement the Query for our Page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f1688bd1bc110e14c348d9e0e6d67ad/href">https://medium.com/media/9f1688bd1bc110e14c348d9e0e6d67ad/href</a></iframe><p>This is then also implemented for the ParagraphBlock and HeaderBlock.</p><h4>Database</h4><p>The Database needs two functions:</p><ul><li>a new function to initialize the db</li><li>the get_page function to get the page-by-page name</li></ul><p>The get_page function returns the page if there is a page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/631578c1508e11800287227eb32b7576/href">https://medium.com/media/631578c1508e11800287227eb32b7576/href</a></iframe><p>For the new function, we will initialize a mutable HashMap and then insert our Pages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5fcc42367c10f41142dd2d168f8b79/href">https://medium.com/media/ed5fcc42367c10f41142dd2d168f8b79/href</a></iframe><p>This was all we needed to implement our Database and Schema.</p><h3>Application</h3><p>For the integration with rocket, we stick with the official <a href="https://github.com/graphql-rust/juniper/blob/master/juniper_rocket/examples/rocket_server.rs">example</a>.</p><p>As this does not include CORS headers, we will need to make some changes. There is the crate <a href="https://docs.rs/rocket_cors/latest/rocket_cors/">rocket_cors</a> to do this, but it’s not currently stable, so we do it manually.</p><p>We will need a few more imports, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b50c873bb0dcfe031e75726bd001769/href">https://medium.com/media/6b50c873bb0dcfe031e75726bd001769/href</a></iframe><p>The idea is to create a Fairing, which will add the CORS headers to every response. Also, we will need to add an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS">HTTP </a><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS">OPTIONS method</a> handler, which is required for CORS. The option handler will not have any logic, as the only thing required is the CORS header in the response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caf40f5fec3d7c18b822dd807fc2b77b/href">https://medium.com/media/caf40f5fec3d7c18b822dd807fc2b77b/href</a></iframe><p>At last, we only need to add the new route and attach our CORS Fairing to our Rocket&lt;Build&gt;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5dc9b302e7ff9b7b8b9729cab7dbf90/href">https://medium.com/media/d5dc9b302e7ff9b7b8b9729cab7dbf90/href</a></iframe><p>The official example also includes a GraphiQL route. So by starting our app, we can already try out our server. Let’s start the server up and head to <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>.</p><pre>cargo run</pre><p>We can query our server like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2688b1f5531987ce7a8e6156e5b021bc/href">https://medium.com/media/2688b1f5531987ce7a8e6156e5b021bc/href</a></iframe><h3>Client</h3><p>The client is the same as in the <a href="https://medium.com/@christopher-scholz/building-a-website-using-rust-grpc-web-react-7412f1596a17">gRPC-web example</a>, so I only explain how to implement the Apollo client.</p><p>We will need to add</p><ul><li>@apollo/client@~3.7.0</li><li>graphql@~16.6.0</li></ul><p>to our package.</p><p>In our index.js file, we will instantiate the apollo client as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70f035ca4ad026142dbca3665b902e13/href">https://medium.com/media/70f035ca4ad026142dbca3665b902e13/href</a></iframe><p>And add the ApolloProvider component as a child of the React component. The rest of the root.render function stays the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7f15571207bd9ef111ac238ef3ea56/href">https://medium.com/media/fe7f15571207bd9ef111ac238ef3ea56/href</a></iframe><p>The Page component will query the server and store the data in a data variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e0cf089f73887937cd20c01d4d53ec/href">https://medium.com/media/a6e0cf089f73887937cd20c01d4d53ec/href</a></iframe><p>The return function will render the blocks the same way as in the gRPC-web example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3a6a49a3d954006487b0b209be2b75a/href">https://medium.com/media/d3a6a49a3d954006487b0b209be2b75a/href</a></iframe><p>This was all. We can now run our client and server and browse to <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a>.</p><pre>docker-compose up --build</pre><h3>Conclusion</h3><p>Juniper is very well documented. If you don’t like Rocket, many other integrations are available. Also, Apollo Client is very well established. Every question you might have will already be answered on Stack Overflow.</p><p>I love how easy everything is to set up and how well it works. As Juniper is using a <a href="https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/">code-first-approach</a> we will have to write quite some code. If you like a <a href="https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/">schema-first-approach</a> instead, there is the <a href="https://github.com/davidpdrsn/juniper-from-schema">juniper-from-schema</a> crate to do just this.</p><p>The full code of the application can be found <a href="https://github.com/christopherscholz/rust_graphql_website">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72f2783f2a30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-a-website-using-rust-graphql-react-72f2783f2a30">Building a Website Using Rust, GraphQL, React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build a Website Using Rust, gRPC-Web, React]]></title>
            <link>https://medium.com/better-programming/building-a-website-using-rust-grpc-web-react-7412f1596a17?source=rss-92a12b8dc23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7412f1596a17</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Christopher Scholz]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 18:24:12 GMT</pubDate>
            <atom:updated>2022-10-26T11:02:33.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to creating your own internet home</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ThSirzaZa8PXa3md" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is how I implemented a small client-server app that serves my personal website using a <a href="https://github.com/grpc/grpc-web">grpc-web</a> interface and what I learned while doing it. The client serves a static page and receives the content via gRPC. The content is structured like <a href="https://editorjs.io/">Editor.js</a>.</p><p>For the server, I’m using Rust and the <a href="https://github.com/hyperium/tonic">Tonic</a> framework. As gRPC is based on <a href="https://en.wikipedia.org/wiki/HTTP/2">http/2</a> a <a href="https://www.envoyproxy.io/">Envoy Proxy</a> is often used to transform the <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">http/1.1</a> into <a href="https://en.wikipedia.org/wiki/HTTP/2">http/2.</a> For this app, I went a different way and used the <a href="https://github.com/hyperium/tonic/tree/master/tonic-web">Tonic-web</a> crate.</p><p>For the client, I’m using <a href="https://reactjs.org/">React</a> and serving it via <a href="https://expressjs.com/">Express</a>.</p><h3>Server</h3><h4>Setup environment</h4><p>To build the app, we need <a href="https://www.rust-lang.org/">Rust</a> and the <a href="https://grpc.io/">Protocol Buffer Compiler</a> (protoc) installed.</p><ul><li>Install Rust: <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a></li><li>Install Protocol Buffer Compiler on Linux and macOS: <a href="https://grpc.io/docs/protoc-installation/">https://grpc.io/docs/protoc-installation/</a> To install it on Windows, you need to download the Binary from <a href="https://github.com/protocolbuffers/protobuf/releases">https://github.com/protocolbuffers/protobuf/releases</a>. extract it somewhere like C:\\Program Files\\protoc and add C:\\Program Files\\protoc\\bin to your <a href="https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/">PATH</a>.</li></ul><h4>Setup package</h4><p>Having set up our development environment, we can start working on our project. Let’s first start a new project directory with the following command:</p><pre>mkdir grpc_app<br>cd grpc_app</pre><p>Using the Rust package manager, we can now create a package.</p><pre>cargo new server<br>cd server</pre><p>For the app interface, we need the following:</p><ul><li><a href="https://github.com/hyperium/tonic/tree/master/tonic-build">Tonic-build</a> (as build dependency), <a href="https://github.com/tokio-rs/prost">Prost</a>, <a href="https://github.com/tokio-rs/prost/tree/master/prost-types">Prost-types</a> crates to generate the Rust code from the <a href="https://developers.google.com/protocol-buffers/docs/proto3">proto3</a> file</li><li><a href="https://tokio.rs/">Tokio</a> crate to run the server async</li></ul><p>The <a href="https://github.com/uuid-rs/uuid">UUID</a> crate is used to create <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)">uuids v4</a>. This is just needed for the app content but not for the general implementation of the interface.</p><p>Let’s add them to our server app, as shown below:</p><pre>cargo add tonic@0.8 tonic-web@0.4<br>cargo add prost@0.11 prost-types@0.11<br>cargo add --features tokio@1.0/macros,tokio@1.0/rt-multi-thread tokio@1.0<br>cargo add --features uuid@1.2/v4 uuid@1.2<br>cargo add --build tonic-build@0.8</pre><p>This should result in a Cargo.toml, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/587ad991dd26b7f630826c7ff325dd6b/href">https://medium.com/media/587ad991dd26b7f630826c7ff325dd6b/href</a></iframe><h4>Create protocol buffer definition</h4><p>As mentioned, we want to create our interface based on the <a href="https://editorjs.io/">Editor.js</a> specification. We will implement the block types Paragraph, Header and List.</p><p>Let’s first create a new file in a proto directory:</p><pre>mkdir proto<br>cd proto<br>touch page.proto</pre><p>First, we need to define the syntax and give the syntax a name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c64179c5d76b369c5d072edb00688f/href">https://medium.com/media/83c64179c5d76b369c5d072edb00688f/href</a></iframe><p>Next, we define our service. The service consists of just one call, receiving and returning a message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfcc98bb266d057bf73634c1cdbc793b/href">https://medium.com/media/bfcc98bb266d057bf73634c1cdbc793b/href</a></iframe><p>We will need to implement those two messages. The PageRequest is just a string, but the PageReply will be our structured <a href="https://editorjs.io/">Editor.js</a>-like response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfc9863e7ba0fed1447ff13141785566/href">https://medium.com/media/bfc9863e7ba0fed1447ff13141785566/href</a></iframe><p>As the PageReply has a timestamp, we will need to import or create an additional type. We will import the one from Google’s <a href="https://developers.google.com/protocol-buffers/docs/reference/csharp/namespace/google/protobuf/well-known-types">well-known types</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6068512e262c8814e6b53d81a518b6bb/href">https://medium.com/media/6068512e262c8814e6b53d81a518b6bb/href</a></iframe><p>We then define our PageReply. To create a list, we use the feature repeated. The block can then be one of Paragraph, Header, and List. For this, we use the feature oneof. A oneof can not be repeated. So we need to create an intermediate message named Block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20c3962e5bcf26f83a67c7b41ee03079/href">https://medium.com/media/20c3962e5bcf26f83a67c7b41ee03079/href</a></iframe><p>Now we can implement the different Block types. For the ListBlock we will need a constraint for the style field. This can be achieved via an enum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c12a0416ef01f11983f18a5ca0cfe25/href">https://medium.com/media/3c12a0416ef01f11983f18a5ca0cfe25/href</a></iframe><p>The full code can be found <a href="https://github.com/christopherscholz/rust_grpc_website/blob/main/server/proto/page.proto">here</a>.</p><h4>Generate proto stub</h4><p>To generate the proto stub, we will need to add a <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html">build script</a> (build.rs) in the main directory of our app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ebc831e075fa23052e529455dbe0960/href">https://medium.com/media/8ebc831e075fa23052e529455dbe0960/href</a></iframe><h4>Implement service</h4><p>To write our app, we edit the src/main.rs file, which was created by cargo new server.</p><p>First, we will declare the use of some modules and publish the generated proto page stub.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d21277635d6e574edb61eefe62803b8/href">https://medium.com/media/0d21277635d6e574edb61eefe62803b8/href</a></iframe><p>Next, we declare our struct and define our Page implementation. We will come to the logic later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c513b6f2a26c505fdf2c4a047588299/href">https://medium.com/media/9c513b6f2a26c505fdf2c4a047588299/href</a></iframe><p>To run our app, we have to add our main function. We use the tokio::main macro to help us with this. Here we also use the tonic_web crate to serve our service on http/1.1 and define the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a> headers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a7fb2c6de36fec6ef2ac7f977a164b/href">https://medium.com/media/69a7fb2c6de36fec6ef2ac7f977a164b/href</a></iframe><p>The logic of our app is based on the input. We will need to define three cases inside our get_page function as follows:</p><ul><li>home</li><li>impressum</li><li>a default case</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8db4b98bbaf4dfac233dcbc2f1d332aa/href">https://medium.com/media/8db4b98bbaf4dfac233dcbc2f1d332aa/href</a></iframe><p>Each match arm is then built by creating our Blocks, e.g., like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec96510071123bf9e7ab7a5f515b8abd/href">https://medium.com/media/ec96510071123bf9e7ab7a5f515b8abd/href</a></iframe><p>The full code can be found <a href="https://github.com/christopherscholz/rust_grpc_website/blob/main/server/src/main.rs">here</a>.</p><h4>Run service</h4><p>We can now run the app with this command:</p><pre>cargo run</pre><p>Because we haven’t yet implemented a client, we test our server via <a href="https://github.com/bloomrpc/bloomrpc">BloomRPC</a>. For this, we can import our page.proto, then set our server to 127.0.01:8000 and switch from gRPC to web. Hitting the green play button will get our response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trvnjiRoEr7bPNzw81I8sw.png" /></figure><h4>Dockerize</h4><p>Every good app needs to be dockerized. We do this by first building it and then copying the binary to a distroless image.</p><p>Let’s create our Dockerfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24fe38e9dc69ed3b490f07b3b608aa9/href">https://medium.com/media/e24fe38e9dc69ed3b490f07b3b608aa9/href</a></iframe><p>As we will also create a docker image for our client later, let’s set up a docker-compose.json in our project main directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ead251ad219995e9876ba80ef1ddf83/href">https://medium.com/media/7ead251ad219995e9876ba80ef1ddf83/href</a></iframe><p>We can then run our Docker Image and test again via BloomRPC.</p><pre>docker-compose up --build</pre><h3>Client</h3><h4>Setup environment</h4><p>Install <a href="https://nodejs.org/en/">Node</a>.</p><p>In addition to the Protocol Buffer Compiler we installed for the server, we also need two plugins that generate the JavaScript proto stub. Unfortunately, the maintenance of the JavaScript implementation of protobuf-javascript is not very good. At the time of writing this, the release binaries were not working, so we need to compile it from the source.</p><p>First, we download the protoc-gen-grpc-web binary from <a href="https://github.com/grpc/grpc-web/releases/tag/1.4.1">https://github.com/grpc/grpc-web/releases/tag/1.4.1</a> and put it next to our protoc binary. Make sure to rename the binary to <a href="https://github.com/grpc/grpc-web/releases/download/1.4.1/protoc-gen-grpc-web-1.4.1-darwin-aarch64">protoc-gen-grpc-web</a>.</p><p>Second, clone the protobuf-javascript repository and reset it to the specified commit.</p><pre>git clone &lt;https://github.com/protocolbuffers/protobuf-javascript&gt; /home/protobuf-javascript<br>git reset --hard 3ff6090f139d71453062fb96c66e9aff801709c2</pre><p>We will need to have bazel installed: <a href="https://docs.bazel.build/versions/main/install.html">https://docs.bazel.build/versions/main/install.html</a></p><p>Then we can load the dependencies and build the binary</p><pre>cd protobuf-javascript<br>npm install<br>npm run build</pre><p>The last thing is to copy the bazel-bin/generator/protoc-gen-js to the same path as the protoc binary.</p><h4>Setup package</h4><p>Now we can create the React app by running the following:</p><pre>npx create-react-app client<br>cd client</pre><p>In addition to the React dependencies, we will also need to add the react-router, grpc-web, and google-protobuf modules.</p><pre>npm install --save google-protobuf@~3.21.2 grpc-web@~1.4.1 react-router-dom@~6.4.2</pre><h4>Generate proto stub</h4><p>We must create our proto-javascript stub to encode/decode serialize/deserialize the grpc data. For this, we can use the protoc binary. Copy the page.proto into a new directory in the client app called proto, then run the following:</p><pre>protoc --proto_path=proto page.proto \\<br>  --grpc-web_out=import_style=commonjs,mode=grpcweb:src \\<br>  --js_out=import_style=commonjs,binary:src</pre><p>This will generate two JavaScript files called page_grpc_web_pb.js and page_pb.js inside the src directory. With big proto files, this will generate quite a lot of code. Instead of generating this static code, you can use a node module like <a href="https://github.com/protobufjs/protobuf.js">protobuf.js</a>.</p><p>The mode is set to grpcweb. Instead, we also could have set it to grpcwebtext. More about the modes <a href="https://github.com/grpc/grpc-web#wire-format-mode">here</a>.</p><p>To support the binary proto format, we added the binary import_style to js_out. More about the options <a href="https://github.com/protocolbuffers/protobuf-javascript#the---js_out-flag">here</a>.</p><p>To make sure this stub is generated every time, we run npm install and add another script to our package.json.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa29052d6547a77f70cdef209912cd4/href">https://medium.com/media/daa29052d6547a77f70cdef209912cd4/href</a></iframe><h4>Implement client</h4><p>Our client will be quite straightforward.</p><p>First, we need a public/index.html</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de40f89c24be022a5ed7c6d599a294ac/href">https://medium.com/media/de40f89c24be022a5ed7c6d599a294ac/href</a></iframe><p>Then we will implement our React app in src/index.js.</p><p>First, import all needed modules and define the React root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d2f62a044d13e0f68b7f293c6209a3f/href">https://medium.com/media/6d2f62a044d13e0f68b7f293c6209a3f/href</a></iframe><p>Inside our React.StrictMode, we will add the React router with three routes</p><ul><li>/ → Page component with property page=home</li><li>/impressum → Page component with property page=impressum</li><li>other → NoPage component</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d17426d49546f04149ad83ae2cb1d5/href">https://medium.com/media/89d17426d49546f04149ad83ae2cb1d5/href</a></iframe><p>The NoPage component is just some HTML without any logic</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/763f2dddb9f8773c69f334e34f7e9dd7/href">https://medium.com/media/763f2dddb9f8773c69f334e34f7e9dd7/href</a></iframe><p>For the Page component, we will need to import our generated JavaScript stub first and create a PageClient object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3796a76536d9d1ad53d2843e46e26ee1/href">https://medium.com/media/3796a76536d9d1ad53d2843e46e26ee1/href</a></iframe><p>Then we can define our component without logic like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b67b56191729397273ddca04c9c868/href">https://medium.com/media/40b67b56191729397273ddca04c9c868/href</a></iframe><p>For the logic, we will create a PageRequest from the page property, call getPage and set the state of the component with generated HTML from PageReply.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc5ab966dc80a4caa7401026d9f780e3/href">https://medium.com/media/bc5ab966dc80a4caa7401026d9f780e3/href</a></iframe><p>We use the response to generate our HTML. As the response includes a list of blocks, we can iterate over them and return the corresponding HTML.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49e5430f4d86ae6713eb42d197f4a43b/href">https://medium.com/media/49e5430f4d86ae6713eb42d197f4a43b/href</a></iframe><p>For my implementation, I have added some styling and a few other static HTML bits and pieces to it.</p><h4>Run client</h4><p>To run our client via the development server, we need to run the React start script. This will also open a new browser window and show the website.</p><pre>npm start</pre><h4>Serve via Express</h4><p>The development server is not the only way to deploy a React app. We can read about some possibilities here: <a href="https://create-react-app.dev/docs/deployment/">https://create-react-app.dev/docs/deployment/</a></p><p>We choose to deploy the app via express. To do this, we create a new nodejs app inside our client app and add the express dependency.</p><pre>npm init express<br>cd express<br>npm install --save express@~4.18.2</pre><p>Then we need an index.js file to serve the React app. Here’s what that looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a57e2811261260b099ec6372890ef0ac/href">https://medium.com/media/a57e2811261260b099ec6372890ef0ac/href</a></iframe><p>This will not work, as we haven’t created the production build yet. We can do this by running the following command in the client directory:</p><pre>npm run build</pre><p>Then we can run the express server using this code:</p><pre>cd express<br>node index.js</pre><h4>Dockerize</h4><p>Like the server app, we dockerize the client.</p><p>This will be a little bit more complicated as we need to create the following:</p><p><strong>builder</strong></p><ul><li>install the protobuf compiler and the two generator plugins</li><li>build our React app</li><li>install express</li></ul><p><strong>runner</strong></p><ul><li>add node user and group</li><li>install nodejs and dum-init</li><li>copy relevant files from builder</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0ba0d392ca2abc4c7bd3e4de818f3a7/href">https://medium.com/media/a0ba0d392ca2abc4c7bd3e4de818f3a7/href</a></iframe><p>Now, add our client to the docker-compose.json in our project main directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ba00094e3e5921686f9004826ede32d/href">https://medium.com/media/3ba00094e3e5921686f9004826ede32d/href</a></iframe><p>After we have put everything together, we run both images and browse to <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a>.</p><pre>docker-compose up --build</pre><h3>Conclusion</h3><p>I had quite some hassle getting the protocol buffer compiler JavaScript plugins to work. But afterward, everything was quite easy to set up. The gRPC-web communication with the server worked without problems and used only roughly 2/3 of the size of a corresponding JSON.</p><p>But the encoding/decoding and serializing/deserializing of the messages takes quite some code, which seems overly complicated for a webapp. <a href="https://github.com/protobufjs/protobuf.js">protobuf.js</a> might be a way around this, but it will also need some code to generate the stubs on the fly.</p><p>I love how easy it is to understand the data’s structure using the proto files. These proto files act as a contract between the client and server.</p><p>I miss the possibility of writing a query like when using GraphQL as it mostly resembles a binary REST-like interface. It definitely would be possible to create a GraphQL-like protocol buffer, but this would be quite a lot of work. For now, I will still keep using GraphQL for Web Client-to-Server communication.</p><p>The full code for the application can be found <a href="https://github.com/christopherscholz/rust_grpc_website">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7412f1596a17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-a-website-using-rust-grpc-web-react-7412f1596a17">How To Build a Website Using Rust, gRPC-Web, React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>