<?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 Tiago Duarte on Medium]]></title>
        <description><![CDATA[Stories by Tiago Duarte on Medium]]></description>
        <link>https://medium.com/@tiago_55824?source=rss-592c00e7aacc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YCu5ktPGp3fLzIFm.</url>
            <title>Stories by Tiago Duarte on Medium</title>
            <link>https://medium.com/@tiago_55824?source=rss-592c00e7aacc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:56:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiago_55824/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[Dangers of using an Object in ReactJS Hooks]]></title>
            <link>https://medium.com/@tiago_55824/dangers-of-using-an-object-in-reactjs-hooks-9e42079d65f?source=rss-592c00e7aacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e42079d65f</guid>
            <category><![CDATA[react-ho]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tiago Duarte]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 09:03:24 GMT</pubDate>
            <atom:updated>2020-12-07T10:23:22.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dangers of using Objects in useState &amp; useEffect ReactJS Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iQPbQ4J37BFhLE-5bmGCA.jpeg" /><figcaption>Dangers of using Objects in useState &amp; useEffect ReactJS Hooks</figcaption></figure><p>Hooks have been around for almost two years now. They we’re added in <a href="https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019">React v16.8.0</a>, and let you use state and other React features without writing a class.</p><p>In this article we won’t be going into much detail about what a hook is, its syntax, and so on and so forth. For that, you can visit the React <a href="https://reactjs.org/docs/hooks-intro.html">documentation page</a> where we think that the React team did a great job 👍🏾 and we couldn’t explain it better.</p><h3>(Un)known problem of using objects in useState / useEffect hooks</h3><p>What brings us here is a problem / bug 🐞 we faced when we first started using hooks, that can easily go unnoticed.</p><p>Let’s look at the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1389a9440e48e4f690925d6143b8d51e/href">https://medium.com/media/1389a9440e48e4f690925d6143b8d51e/href</a></iframe><p>We prepared <a href="https://codepen.io/tmpduarte/pen/yLJWdwm">this codepen</a> with the example, feel free to visit and play around with it.</p><p>In our example we have:</p><ul><li>a count state hook that stores a plain number</li><li>an objectCount state hook that stores an object that contains the count property inside</li><li>an &quot;Increase normal count&quot; button that updates the count state. You can validate this by seeing that the counter updates right after pressing the button</li><li>a &quot;Broken increase of the object count&quot; button that tries to update the objectCount, but fails miserably 🙀. You might be thinking <em>“naaaaaahhh, that should work…”.</em> Go ahead and try it out on <a href="https://codepen.io/tmpduarte/pen/yLJWdwm">codepen</a></li><li>a &quot;Functioning increase of the object count&quot; button that properly updates the objectCount state</li></ul><h4>Why pressing the &quot;Broken increase of the object count&quot; button doesn’t immediately increase the object count?</h4><p>When a user presses the button, we increase the count property inside the objectCount object, and then call setObjectCount(objectCount). <br>The problem with this is that the useState hook uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">strict equality comparison</a> to determine if it should trigger a re-render and doesn’t check if the properties of the object actually changed. <br>In other words, the hook compares (===) the “old” and “new” state and concludes that the object hasn’t changed, and won’t trigger a re-render, causing the object count label to stay the same😭.</p><h3>Possible Solutions</h3><h4>Create and pass a shallow copy to setObjectCount</h4><p>The &quot;Functioning increase of the object count&quot; button fixes the issue by creating and passing a shallow copy of the objectCount to the setter function. <br>It basically keeps the same object properties but creates a new object reference so that the hook strict equality comparison determines that the state changes, and immediately triggers a re-render.</p><h4>Do not use an object as state</h4><p>Another solution would be to simply not use objects in an useState hook. <br>You could use the useState hook per each property of the object. In theory, this would be the ideal scenario, but doing this might be daunting and time-consuming.<br>You might have your reasons to directly store an object as state. In our case, we were retrieving data from an API and decided to store the object retrieved 🤭.</p><h4>Use the <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a> hook</h4><p>If you are familiar with Redux you already know how this works as it is very similar.<br>useReducer accepts a reducer of type (state, action) =&gt; newState, and returns the current state paired with a dispatch method. <br>This is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.</p><h4>Use <a href="https://immutable-js.github.io/immutable-js/">immutable.js</a></h4><p>As per the documentation:</p><blockquote><a href="http://en.wikipedia.org/wiki/Immutable_object">Immutable</a> data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic. <a href="http://en.wikipedia.org/wiki/Persistent_data_structure">Persistent</a> data presents a mutative API which does not update the data in-place, but instead always yields new updated data.</blockquote><p>In practical terms, when using immutable.js, every object change would actually create a new object. In our example, this would cause the state hook to trigger a re-render.</p><blockquote>⚠️ Keep in mind that the same problem and solutions applies to the (optional) list of dependencies of the <a href="https://reactjs.org/docs/hooks-effect.html">useEffect</a> hook ⚠️</blockquote><h3>Time saver</h3><p>When this problem happened to me and <a href="https://medium.com/u/8379066bec55">Rui Sousa</a>, we spent, I would say, a couple of hours hunting down the problem. So we felt like sharing this tip in hopes that it saves you debug time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*X6SJhbaSXP0FtqXDN5aYzw.gif" /><figcaption>Fixing bugs</figcaption></figure><p>If you have a suggestion or a different solution than the ones listed, go ahead and leave us a comment 💬. We are very friendly, we promise 😇.</p><h3>References</h3><ul><li><a href="https://reactjs.org/docs/hooks-overview.html">Hooks at a Glance</a></li><li><a href="https://reactjs.org/docs/hooks-state.html">Using the State Hook</a></li><li><a href="https://reactjs.org/docs/hooks-effect.html">Using the Effect Hook</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">MDN — Equality comparisons and sameness</a></li><li><a href="https://medium.com/@manjuladube/understanding-deep-and-shallow-copy-in-javascript-13438bad941c">Understanding Deep and Shallow Copy in Javascript</a></li><li><a href="https://dribbble.com/raquel-pontes">Raquel Pontes</a> didn’t allow me to use the original cover illustration 😢, so I will leave it here for future reference:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biyEpipo9ZbzGan-Km3ZDg.png" /><figcaption>Original cover illustration</figcaption></figure><h3>Thank you for reading!</h3><p>Thank you so much for reading and if you enjoyed this article make sure to hit that 👏👏 button. It means a lot to us! Also<strong> don’t forget to follow </strong><a href="https://coletiv.com/"><strong>Coletiv</strong></a><strong> on </strong><a href="https://medium.com/coletiv-stories"><strong>Medium</strong></a><strong>, </strong><a href="https://twitter.com/coletivstudio"><strong>Twitter</strong></a><strong>, and </strong><a href="https://www.linkedin.com/company/coletiv/"><strong>LinkedIn</strong></a> as we keep posting more and more interesting articles on multiple technologies.</p><p>In case you don’t know, Coletiv is a software development studio from Porto specialized in Elixir, iOS, and Android app development. But we do all kinds of stuff. We take care of UX/UI design, web development, and even security for you.</p><p>So,<a href="https://coletiv.com/contact"><strong> let’s craft something together?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e42079d65f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical Debt and Unplanned Work on Software Development]]></title>
            <link>https://medium.com/@tiago_55824/technical-debt-and-unplanned-work-on-software-development-8a2398e5f49a?source=rss-592c00e7aacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2398e5f49a</guid>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[tech-debt]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[work-improvement]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Tiago Duarte]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 08:33:00 GMT</pubDate>
            <atom:updated>2020-09-25T08:33:00.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6T4E-OmYSuRsYMaDC5MAg.png" /><figcaption>Technical Debt and Unplanned Work on Software Development</figcaption></figure><p>If you have ever been part of a software development project, chances are that you have experienced the consequences of <a href="https://insights.sei.cmu.edu/sei_blog/2015/07/a-field-study-of-technical-debt.html">technical debt</a>.</p><p><strong>Technical debt is a concept in software development that reflects the implied cost of additional rework caused by choosing an easy (limited) solution now, instead of using a better approach that would take longer.<br>In other words, technical debt conceptualises the tradeoff between the short-term benefits of rapid delivery and long-term value.</strong></p><p>Taking shortcuts to expedite the delivery of features in the short term incurs technical debt.<br>Similar to monetary <a href="https://en.wikipedia.org/wiki/Debt">debt</a>, if technical debt is not repaid, it can accumulate “interest”, making it harder to implement changes. This causes additional cost and rework over the software lifecycle. <br>Understanding and managing technical debt is an important goal for many teams, and <a href="http://www.coletiv.com/">Coletiv</a> is no exception.</p><p>Technical debt can cause many side effects and unplanned work is one of them. Before digging into the relation between both topics. lets distinguish between planned and unplanned work.<br>Planned work is what was planned on being done. Usually, very detailed and specific tasks, that take into account the resources available (e.g.: time).<br>Unplanned work is what prevents you from doing the actual work you have planned to do.</p><p>In this article we are going to approach the relation between technical debt and unplanned work, as well as giving some possible solutions to tackle and reduce technical debt.</p><h3>Technical Debt and Unplanned Work</h3><p><strong>A big problem with technical debt, is that it will ensure that the only work that gets done is unplanned work.</strong> <br>You might be thinking how can this be true? <br>Have you questioned yourself how many times does a proof of concept ended up in production, and you have to interrupt what you planned to do because it isn’t working anymore?<br>How many times a quick and dirty code patch 🔨 ends up not being refactored, causing failures in the system and you end up pausing everything you were doing to fix it?<br>In the end, these quick and dirty fixes led to unplanned work that forced you to stop everything you have planned to do!</p><p><strong>Unplanned work has another side effect. When you spend all of your time firefighting 🚒, there is little time or energy left for planning. <br></strong>When all you do is react, there’s not enough time to do the hard mental work of figuring out whether you can accept new work. So, more projects are crammed onto the plate, which means more multitasking, more escalations from poor code, which means more shortcuts. Around and around we go, sucked into the capacity death spiral ☠️.</p><h3>How do we tackle Technical Debt? 🤔</h3><p>In order to reduce the amount of unplanned work that your team has to deal with, we need to tackle the root problem that caused it in the first place: technical debt.</p><h4><strong>Preventive Work</strong></h4><p>We strongly suggest our teams to dedicate a certain percentage of effort to preventive work. And by preventive work we mean: refactoring, creating proper documentation, reducing code complexity, reduce compile times or whatever task that helps increase the code quality, the speed and the happiness of the development team.<br>Properly elevating preventive work is at the heart of programs like <a href="https://www.leanproduction.com/tpm.html">Total Productive Maintenance</a> (TPM), which has been embraced by the Lean Community. TPM insists that we do whatever it takes to assure machine availability by elevating maintenance. <strong>Improving daily work is even more important than doing daily work.</strong></p><blockquote>It almost doesn’t matter what you improve, as long as you’re improving something. Why? Because if you are not improving, entropy guarantees that you are actually getting worse, which ensures that there is no path to zero errors.</blockquote><p>You might be thinking “yes! yes! all your code is bullet proof and you never take shortcuts and… 🗣”. Don’t get me wrong, sometimes we trade quality for velocity, and that’s fine! As long as the team documents all the shortcuts taken, creates follow up tasks and understands that they will have to pay the technical debt back in the near future.</p><h4><strong>Throw less at the problem</strong></h4><p>From our experience, when a product tries to do too many things, technical debt tends to be created.<br>When a project isn’t working, the natural inclination is to throw more at the problem. More people, time, features and money. All that ends up making the problem bigger. The right way to go is the opposite direction: cut back.</p><blockquote>Being able to take needless work out of the system is more important than being able to put more work into the system.</blockquote><h3>Good and Bad Technical Debt</h3><p>While technical debt can have terrible consequences, it is not always as menacing as it may sound. You can look at it as part of an overall investment strategy, a strategic software design choice.</p><blockquote>If you find yourself spending all your time dealing with debt or you reach the point where you cannot repay it, you have incurred bad debt. When you borrow or leverage time and effort that you can and will repay in the future, you may have incurred good debt.</blockquote><p>If the software product is successful, this strategy can provide you with greater returns than if you had remained debt free. In addition, you might also have the option to simply walk away from your debt if the software is not successful. This dual nature of technical debt — both good and bad — makes it confusing for many project stakeholders.<br>We should never take on technical debt on purpose, and we should pay it back as soon as we know how. Also you should always consider doing less, or at least make a pause and analyse if a certain feature is actually so important for the overall goal you are trying to achieve.</p><h3>References</h3><ul><li><a href="https://insights.sei.cmu.edu/sei_blog/2015/07/a-field-study-of-technical-debt.html">A Field Study of Technical Debt</a></li><li><a href="https://insights.sei.cmu.edu/sei_blog/2019/05/managing-the-consequences-of-technical-debt-5-stories-from-the-field.html">Managing the Consequences of Technical Debt: 5 Stories from the Field</a></li><li><a href="https://www.goodreads.com/book/show/17255186-the-phoenix-project">The Phoenix Project: A Novel About IT, DevOps, and Helping Your Business Win</a></li><li><a href="https://basecamp.com/books/rework">Rework</a></li><li><a href="https://web.archive.org/web/20151111011323/http://ronjeffries.com/articles/015-11/tech-debt/">Technical Debt — Bad metaphor or worst metaphor?</a></li><li>[Wikipedia] <a href="https://en.wikipedia.org/wiki/Technical_debt">Technical Debt</a></li></ul><h3>Thank you for reading!</h3><p>Thank you so much for reading and if you enjoyed this article make sure to hit that 👏👏 button. It means a lot to us! Also<strong> don’t forget to follow </strong><a href="https://coletiv.com/"><strong>Coletiv</strong></a><strong> on </strong><a href="https://medium.com/coletiv-stories"><strong>Medium</strong></a><strong>, </strong><a href="https://twitter.com/coletivstudio"><strong>Twitter</strong></a><strong>, and </strong><a href="https://www.linkedin.com/company/coletiv/"><strong>LinkedIn</strong></a> as we keep posting more and more interesting articles on multiple technologies.</p><p>In case you don’t know, Coletiv is a software development studio from Porto specialized in Elixir, iOS, and Android app development. But we do all kinds of stuff. We take care of UX/UI design, web development, and even security for you.</p><p>So,<a href="https://coletiv.com/contact"><strong> let’s craft something together?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2398e5f49a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Google Maps with Phoenix LiveView]]></title>
            <link>https://medium.com/@tiago_55824/how-to-use-google-maps-with-phoenix-liveview-dbd55771e897?source=rss-592c00e7aacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd55771e897</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[liveview]]></category>
            <category><![CDATA[phoenix-liveview]]></category>
            <dc:creator><![CDATA[Tiago Duarte]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 08:01:01 GMT</pubDate>
            <atom:updated>2020-08-03T08:01:01.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQDl4viYwvZHxfJM0bjn2Q.png" /><figcaption>How to use Google Maps with Phoenix LiveView</figcaption></figure><p>Howdy dear reader 🖖🏽, hope you are safe and healthy during these troubled times. <br>During the past 3 years, we have developed a <a href="https://coletiv.com/showcase/">few projects</a> using the <a href="https://github.com/phoenixframework/phoenix">Phoenix Framework</a> for <a href="https://elixir-lang.org/">Elixir</a>. And as soon as <a href="https://github.com/phoenixframework/phoenix_live_view">LiveView</a> was announced, we could not wait to use it!</p><p>We have been building a platform where using LiveView made a lot of sense, since we wanted some of our features to use an interface that could be updated in real-time. For example, we wanted administrators of the platform to be able to see, on a map, the sightings that the users of the app were reporting on certain places, as they happen. Let’s call it a live map.</p><h3>Understanding the technology 🤓</h3><p>Before digging into the problem, let’s take a look at the technologies we are using. We are assuming that you are familiar with Elixir and Phoenix.</p><h4><a href="https://github.com/phoenixframework/phoenix_live_view">Phoenix LiveView</a></h4><p>According to the <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html">documentation</a>:</p><blockquote>LiveView provides rich, real-time user experiences with server-rendered HTML.</blockquote><blockquote>The LiveView programming model is declarative: instead of saying “once event X happens, change Y on the page”, events in LiveView are regular messages which may cause changes to its state. <br>Once the state changes, LiveView will re-render the relevant parts of its HTML template and push it to the browser, (…) LiveView does the hard work of tracking changes and sending the relevant diffs to the browser.</blockquote><h4><a href="https://developers.google.com/maps/documentation/javascript/tutorial">Google Maps for javascript</a></h4><p>Once again according to the documentation:</p><blockquote>The Maps JavaScript API lets you customise maps with your own content and imagery for display on web pages and mobile devices.</blockquote><p>For you to get up and running, and have a page that displays a map centered in Sydney, you just need to do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40191df083b245cedc083d3774449b9b/href">https://medium.com/media/40191df083b245cedc083d3774449b9b/href</a></iframe><h3>Challenge 🤔</h3><p>In our live map, we will need a bit more than just showing a static map. We will need the map to also show markers, indicating where the users are reporting the sightings. <br>Also, the markers need to show up as soon as users report them 🤯. You might be thinking: “well we have LiveView so it should be easy”. Let’s try it out and see for ourselves.</p><h3>Solution 💡</h3><p>We have prepared a <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps">repository</a> that you can use and jump to specific parts of the article, to avoid doing the boilerplate for yourself.</p><h4>a) Initial Setup</h4><p>The <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/d5c6604105b4d1991be9a1c2f9868f32d592fc8e">initial setup</a> contains the LiveView automatically generated project. <br>We opted to use the --no-ecto option when generating the project as we won’t be needing <a href="https://hexdocs.pm/ecto/getting-started.html">Ecto</a>.</p><h4>b) Adding the map to a LiveView page</h4><p>We <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/cabca20064505d73160f35dedfbbaf869cc6334d">simply added</a> the HTML+ CSS+ JS code described in the section above for the Google Map to show up.<br>Please don’t forget to add <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/cabca20064505d73160f35dedfbbaf869cc6334d#diff-2e26140b5356a39bd65f5573433641f6R56">here</a> your <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">Google Maps API key</a> to the project if you want to see it working.</p><p>If you now run the project (mix phx.server), you will see that the map shows for a brief moment, disappearing right after. Where did the map go? 🤔</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKKOMG9EB7VqBq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKKOMG9EB7VqBq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKKOMG9EB7VqBq%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/64e5896bf7b223e8837e26f52eab2334/href">https://medium.com/media/64e5896bf7b223e8837e26f52eab2334/href</a></iframe><h4>c) Keeping the map on the LiveView page</h4><p>To understand our problem, we first need to understand the <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-life-cycle">life-cycle of a LiveView</a>:</p><blockquote>A LiveView begins as a regular HTTP request and HTML response, and then upgrades to a stateful view on client connect, guaranteeing a regular HTML page even if JavaScript is disabled. Any time a stateful view changes or updates its socket assigns, it is automatically re-rendered and the updates are pushed to the client.<br>(…)<br>After rendering the static page, LiveView connects from the client to the server where stateful views are spawned to push rendered updates to the browser, and receive client events via phx- bindings. Just like the first rendering, <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:mount/3">mount/3</a> is invoked with params, session, and socket state, where mount assigns values for rendering.</blockquote><p>If you want to go deeper into the topic, <a href="https://www.youtube.com/watch?v=te9sp2IblLs">this video</a> explains very well how the inners of LiveView works.</p><p>In our case, what is happening is that:</p><ol><li>There is an initial page render</li><li>The google maps script is loaded and calls our initMap function</li><li>The initMap function initialises the map. Which causes the div with the id=&quot;map&quot; to be filled with all the necessary markup to represent the map</li><li>At the same time, the webpage connects to the LiveView on the server. And as the documentation states: “Just like the first rendering, <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:mount/3"><em>mount/3</em></a> is invoked with params, session, and socket state, where mount assigns values for rendering.”</li><li>The LiveView (JavaScript) on the browser side, then does the diffing of what should the HTML be and what it is now</li><li>And, surprise, surprise 🎁 ! The current HTML contains the map markdown, which wasn’t there when the page initially rendered, and it also wasn’t added by the LiveView. As such the LiveView on the client-side reverts that change 😭</li></ol><p>The good part is that the creators of LiveView thought about these cases and give you the possibility to <a href="https://hexdocs.pm/phoenix_live_view/dom-patching.html">control the patching mechanism</a>:</p><blockquote>A container can be marked with phx-update, allowing the DOM patch operations to avoid updating or removing portions of the LiveView, or to append or prepend the updates rather than replacing the existing contents. This is useful for client-side interop with existing libraries that do their own DOM operations. <br>(…)<br>The “ignore” behaviour is frequently used when you need to integrate with another JS library.</blockquote><p>In practical terms, <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/fcbcb05cc96760ad95e9937d8e68a37151302dca">we only need to add</a> a phx-update=&quot;ignore&quot; to the map container, to inform LiveView that the contents of that container are controlled by us. <br>You should now see the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*Ne53UG08FeTzr50iD1-PVw.png" /><figcaption>Google Map rendered in a LiveView page</figcaption></figure><h4>d) How to dynamically push elements to the map from the server</h4><p>Only the last step is missing: <strong>sightings need to show up as soon as users report them</strong>. <br>In order to simulate a sighting being reported by a user, stored in the database and then broadcasted to other users, <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/82418240307cb9cba01cc0535a27d795f27c658d">we added a button</a> to randomly generate one. This button sends an event to the server as if a user actually reported a sighting. The LiveView then takes care of informing the browser that we have a new sighting.</p><p>The end result should something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OH0jFhHi_ReiUNeJ0qRANQ.gif" /><figcaption>Adding server side generated markers to the live map</figcaption></figure><p>To sum up the important parts, <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/82418240307cb9cba01cc0535a27d795f27c658d">what we did</a> was:</p><p><strong>d.1) Create a </strong><a href="https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks"><strong>javascript hook</strong></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/888bdfb08fe3a72ab941c9ddb64af193/href">https://medium.com/media/888bdfb08fe3a72ab941c9ddb64af193/href</a></iframe><p>We are making use of the newly added handleEvent / pushEvent feature of hooks. This method is available since <a href="https://github.com/phoenixframework/phoenix_live_view/blob/master/CHANGELOG.md#0140-2020-07-07">LiveView version 0.14</a>:</p><blockquote>The hook can push events to the LiveView by using the pushEvent function and receive a reply from the server via a {:reply, map, socket} return value. The reply payload will be passed to the optional pushEvent response callback.</blockquote><blockquote>Communication with the hook from the server can be done by reading data attributes on the hook element, or by using push_event on the server and handleEvent on the client.</blockquote><p><strong>d.2) Use the javascript hook on the map markup</strong></p><p>In order to use / attach the newly created hook we just had to do the following:</p><pre>&lt;section class=&quot;row&quot; phx-update=&quot;ignore&quot; phx-hook=&quot;MapSightingsHandler&quot;&gt;</pre><p>As soon as the element is mounted and the LiveView Genserver pushes an event with the name new_sighting , the handleEvent callback is triggered and a map marker is added.</p><p><strong>d.3) Update the LiveView Genserver to push the events / sightings</strong></p><p>The server part that actually receives orders to create a random sighting, via an event sent by a phx-click=”add_random_sighting” on a <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/f8d922cc9d266030e8b2730a5737e9813ce031c5#diff-2e26140b5356a39bd65f5573433641f6R5">button</a> for the sake of simulation, and pushes the event to the browser’s socket:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27963395d095faa203d41308ab5319a9/href">https://medium.com/media/27963395d095faa203d41308ab5319a9/href</a></iframe><p>If you apply all the <a href="https://github.com/coletiv/blog-phoenix-live-view-google-maps/commit/f8d922cc9d266030e8b2730a5737e9813ce031c5">changes</a> and run the code you should now be able to randomly create markers on your map.</p><h3>Improvements 👆🏾</h3><p>We had to cut some corners for the sake of keeping the article focused on topic. <br>There are a few points that we will probably address in another article:</p><p><strong>How to display on the map the already stored sightings?<br></strong>One might think “this seems very easy, on the first mount we could send / schedule a pushEvent!”. <br>The problem here is that the Google Map script might be rendered before or after we call that pushEvent. Meaning that if the script is loaded after, the handleEvent function that creates markers won’t have access to the map and as such it will fail and won’t render the markers!</p><p><strong>Properly store and broadcast sightings creation, updates and deletions?<br></strong>We only handle sightings additions and we don’t even store them on a database nor broadcast it to all users. <br>How would one receive a new sighting, store it in a database and then broadcast this information to all users?</p><p><strong>How to better structure the code?<br></strong>In order to keep the article focused, once again we decided to go for the shortest solution and focus on the technology itself. <br>For instance, we are exposing the map object to the hook by adding it directly to the window. Please don’t do this in production!</p><p>Feel free to tackle the problems mentioned and do pull requests with your suggested solutions. We will be very happy to learn from you as well! 👩🏾‍🎓</p><h3>Conclusion</h3><p>We are very happy with the solutions and results we are achieving with LiveView. Please keep in mind that, as with any other tool, it has its own <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-use-cases">use cases</a> and you should first understand the problem you have at hand before committing to it.</p><p>The biggest downside we still have with LiveView is the code structuring / organisation. We haven’t yet found a structure that we feel 100% confident with, so we are continuing to iterate until we get there.<br>The community is already working on solutions for this, and there are already libraries like <a href="https://github.com/msaraiva/surface">surface</a> that address this issue. Surface is on our “test / research / learning” list and we will certainly give it a try.</p><p>Also LiveView is still in an alpha stage. We have to keep upgrading the dependency quite often, as new releases with breaking changes are made available. The bright side of this is that it keeps getting better with every new release! 🥇</p><h3>Thank you for reading!</h3><p>Thank you so much for reading and if you enjoyed this article make sure to hit that 👏👏 button. It means a lot to us! Also<strong> don’t forget to follow </strong><a href="https://coletiv.com/"><strong>Coletiv</strong></a><strong> on </strong><a href="https://medium.com/coletiv-stories"><strong>Medium</strong></a><strong>, </strong><a href="https://twitter.com/coletivstudio"><strong>Twitter</strong></a><strong>, and </strong><a href="https://www.linkedin.com/company/coletiv/"><strong>LinkedIn</strong></a> as we keep posting more and more interesting articles on multiple technologies.</p><p>In case you don’t know, Coletiv is a software development studio from Porto specialized in Elixir, iOS, and Android app development. But we do all kinds of stuff. We take care of UX/UI design, web development, and even security for you.</p><p>So,<a href="https://coletiv.com/contact"><strong> let’s craft something together?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd55771e897" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using WebSockets With Cookie-Based Authentication]]></title>
            <link>https://medium.com/@tiago_55824/using-websockets-with-cookie-based-authentication-7e4bb9262898?source=rss-592c00e7aacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4bb9262898</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Tiago Duarte]]></dc:creator>
            <pubDate>Mon, 11 May 2020 08:01:01 GMT</pubDate>
            <atom:updated>2020-05-11T08:01:01.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Although only my name appears as the owner of this article it was created together with my old friend 👴🏽 <a href="https://medium.com/u/ad910a0210e8">Nuno Marinho</a> and, as usual, with lots of inputs from the whole <a href="http://www.coletiv.com/">Coletiv</a> team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*In6SHekqQRfuFYzcbwgbqQ.jpeg" /><figcaption>Using WebSockets With Cookie-Based Authentication</figcaption></figure><p>Before diving into the details of the problem lets first have a small recap about these two topics: WebSockets and cookie-based authentication.</p><p><strong>WebSockets</strong></p><p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">MDN web docs</a>:</p><blockquote>The <strong>WebSocket API</strong> is an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.</blockquote><p>Long days are gone since webpages were just a mixture of text and hyperlinks. Feeling nostalgic? 👵🏼 You can check <a href="http://info.cern.ch/hypertext/WWW/TheProject.html">here</a> the first webpage ever built.<br>With the evolution of the world wide web, and computers &amp; smartphones in general, we started seeing richer experiences. <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX">Ajax</a> came into play and webpages started to interact with servers without the need for a full reload. <br>Well, evolution never stops 🤘🏽! And we are once again seeing webpages morphing <a href="https://en.wikipedia.org/wiki/Real-time_web">into (near) real-time</a> experiences. <br>WebSockets, by keeping a two-way communication channel, allow servers to continuously push information/content into the webpage without the need for expensive mechanisms like <a href="https://www.pubnub.com/blog/http-long-polling/">long-polling</a>.</p><p>As a side note, these concepts also apply to mobile applications as well. It is just that it is funnier to look at the early infancy of the web and compare it to its current status.</p><p><strong>Cookie-based authentication</strong></p><p>Cookie-based authentication has been the default, battle-tested method for handling user authentication for a long time.<br>Cookie-based authentication is <strong>stateful</strong>. This means that a record or session is kept both server (optional) and client-side. <br>The server can, optionally, keep track of active sessions. While on the front-end a cookie is created that holds a session identifier, thus the name cookie-based authentication.</p><p>Let’s look at the flow of traditional cookie-based authentication:</p><ol><li>A user enters their login credentials</li><li>The server verifies the credentials are correct and creates a session which is then stored (e.g.: database)</li><li>A cookie with the session ID is placed in the user’s browser</li><li>On subsequent requests, the session ID is verified against the database and if valid, the request is processed</li><li>Once a user logs out of the app, the session is destroyed both client-side and server-side</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*sKpe4bHuMZUKwLYEVkBFfQ.png" /><figcaption>Cookie-based authentication flow</figcaption></figure><p><strong><em>Source:</em></strong><em> </em><a href="https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide"><em>Dzone</em></a></p><h3>Problem: How do we authenticate Elixir GraphQL subscriptions? 🤔</h3><p>In a new Elixir based backend we are working on, we created a <a href="https://graphql.org/">GraphQL</a> based API and used a cookie-based authentication. <br>Nothing new up to this point and everything was going according to plan until we decided to provide a richer experience to the user by having the server push data directly to the page. As we were using GraphQL, <a href="https://www.howtographql.com/graphql-js/7-subscriptions/">subscriptions</a> were the obvious choice.</p><p>According to the <a href="https://www.howtographql.com/graphql-js/7-subscriptions/">documentation</a>:</p><blockquote>Subscriptions are a GraphQL feature that allows a server to send data to its clients when a specific <em>event</em> happens. Subscriptions are usually implemented with WebSockets. In that setup, the server maintains a steady connection to its subscribed client.</blockquote><p>GraphQL subscriptions on their own are quite easy to implement. But, in our case, the subscription could only be done if the user was authenticated, which was something we haven’t done before.</p><p>Like most developers, we started looking for solutions first on the <a href="https://www.apollographql.com/docs/react/data/subscriptions/">Apollo docs</a>, then on the <a href="https://pragprog.com/book/wwgraphql/craft-graphql-apis-in-elixir-with-absinthe">Craft GraphQL APIs in Elixir with Absinthe book</a>.<br>Problem was that both cases, as well as most of the articles on the web, were pointing towards <a href="https://jwt.io/introduction">token-based auth</a>. Or so we thought 🤦🏼‍♂️, as we were blindly 🙈 looking for explanations on how to do it using cookie-based authentication.</p><h3>Solution 💡</h3><p>We were missing something basic: <strong>Secure WebSockets (WSS) use a different protocol than regular based connections which use HTTPS</strong>.</p><p>Although, in theory, one could use cookies, as all WebSocket connections start with an HTTP request (with an upgrade header on it), and the cookies for the domain you are connecting to, will be sent with that initial HTTP request to open the WebSocket. It is not recommended as WebSockets <em>are not restrained by the </em><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy"><em>same-origin policy</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*okpDjFWS838s_oVoEAMUEQ.png" /><figcaption>Lifetime of a WebSocket connection</figcaption></figure><p>Using cookies could actually leave users vulnerable to <a href="https://owasp.org/www-community/attacks/xss/">cross-site scripting attacks</a> (xss). <br>There is a very good article on <a href="https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html">Cross-Site WebSocket Hijacking (CSWSH)</a> that lead us to a solution:</p><blockquote>As you’ve already noticed, securing an application against <strong>Cross-Site WebSocket Hijacking</strong> attacks can be performed using two countermeasures:</blockquote><blockquote>1. Check the Origin header of the WebSocket handshake request on the server, since that header was designed to protect the server against attacker-initiated cross-site connections of victim browsers!</blockquote><blockquote>2. Use session-individual random tokens (like CSRF-Tokens) on the handshake request and verify them on the server.</blockquote><p>Actually, this is exactly what <a href="https://github.com/phoenixframework/phoenix_live_view">Phoenix Live View</a> does. <br>When using live view there is an initial webpage render that contains a &lt;meta&gt; tag with the a csrf token. We then read the token via javascript, and send it via params to create the WebSocket connection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60b890c9a9530400f1e3b070693e9c9/href">https://medium.com/media/b60b890c9a9530400f1e3b070693e9c9/href</a></iframe><h4><a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions"><strong>Possible implementation</strong></a></h4><p>So to prove our concept of <em>“how to authenticate subscriptions in a cookie-based authentication system”,</em> we created a <a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions">small based backend elixir project</a>.<br>The project is very simple, it contains a user table and all the necessary endpoints (<em>login, logout, register, and me</em>) to perform user registration and authentication via API using cookies with Absinthe GraphQL.</p><p>We won’t get into the details on how to fully setup and configure subscriptions on a project, you can follow the <a href="https://hexdocs.pm/absinthe/subscriptions.html">official Absinthe subscription documentation</a> for that.<br>Besides the usual setup we did the following:</p><p><strong>1. </strong><a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions/blob/master/lib/phoenix_absinthe_authenticated_subscriptions_graphql/accounts/types.ex"><strong>Create a subscription</strong></a><strong> that expects the </strong><strong>user_count:#{user_id} as a topic that we want to subscribe to:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3772f1965b2f0014a7ef413354526371/href">https://medium.com/media/3772f1965b2f0014a7ef413354526371/href</a></iframe><p><strong>2. </strong><a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions/blob/master/lib/phoenix_absinthe_authenticated_subscriptions_graphql/accounts/resolver.ex"><strong>Change <em>me</em> endpoint</strong></a><strong>, to allows the user to get a </strong><strong>token containing his </strong><strong>user_idthat will allow us to authenticate the subscription and make sure a user can only subscribe to its own data:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef9588cbac1b3d92c2549d6741422fdb/href">https://medium.com/media/ef9588cbac1b3d92c2549d6741422fdb/href</a></iframe><p><strong>3. </strong><a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions/blob/master/lib/phoenix_absinthe_authenticated_subscriptions_web/channels/user_socket.ex"><strong>Create a handle connect function</strong></a><strong> on the socket. The function expects a token to be sent, validates that the </strong><strong>user_id contained inside the token belongs to the current user so that the current user can only subscribe to data from himself:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcd858106ec1c24933474946f440540/href">https://medium.com/media/fbcd858106ec1c24933474946f440540/href</a></iframe><p><strong>4. For the sake of this example and to test our solution, we </strong><a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions/blob/master/lib/phoenix_absinthe_authenticated_subscriptions/processes/worker.ex"><strong>created a Worker</strong></a><strong> that every 10 seconds publishes to all user topic possibles a random number:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9d364ba9693b214ccea2a1dcb5e990/href">https://medium.com/media/df9d364ba9693b214ccea2a1dcb5e990/href</a></iframe><p><strong>To test the solution</strong> you can follow the <a href="https://github.com/coletiv/phoenix_absinthe_authenticated_subscriptions">readme</a>:</p><ol><li>Install the dependencies with mix deps.get</li><li>Create and migrate the database with mix ecto.setup</li><li>Start the Phoenix server with iex -S mix phx.server</li><li>Open the <a href="http://localhost:4000/v1/graphiq">GraphiQL Interface</a> and import <a href="https://gist.github.com/marinho10/cdb0814eea1ad1aba9b8faa2048d67aa">this workspace</a>.</li><li>Run the mutation - accountsLogin</li><li>Run the query - accountsMe and copy the token returned</li><li>Change the ws url token on subscription - accountsUserCount and run the query</li><li>Verify accountsUserCount value changing every 10 seconds on the result panel</li></ol><h3>Final notes</h3><p>The problem with the csrf token solution is that the token gets sent as a query string value when the WebSocket handshake takes place. <br>We are not worried about man-in-the-middle attacks as the connection is made securely by using wss. <br>The problem is that query string values are often stored in log files on servers and that potentially means we have a log file full of authentication tokens that can be reused, which is a security risk. <br><strong>Please do not forget to check your loggers and take measures so that they do not store these parameters or even these requests at all.</strong></p><h3>Sources</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">The WebSocket API</a></li><li><a href="https://tools.ietf.org/html/rfc6455">Websocket rfc</a></li><li><a href="https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide">Cookies vs. Tokens: The Definitive Guide</a></li><li><a href="https://elixirforum.com/t/accessing-cookies-in-phoenix-socket-connect/4731">Accessing cookies in Phoenix.Socket connect</a></li><li><a href="https://www.wearesauce.io/developer-blog/2018/5/13/websocket-security-with-phoenix-channels">WebSocket Security With Phoenix Channels</a></li><li><a href="https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html">Cross-Site WebSocket Hijacking (CSWSH)</a></li></ul><h3>Thank you for reading!</h3><p>Thank you so much for reading and if you enjoyed this article make sure to hit that 👏👏 button. It means a lot to us! Also<strong> don’t forget to follow </strong><a href="https://coletiv.com/"><strong>Coletiv</strong></a><strong> on </strong><a href="https://medium.com/coletiv-stories"><strong>Medium</strong></a><strong>, </strong><a href="https://twitter.com/coletivstudio"><strong>Twitter</strong></a><strong>, and </strong><a href="https://www.linkedin.com/company/coletiv/"><strong>LinkedIn</strong></a> as we keep posting more and more interesting articles on multiple technologies.</p><p>In case you don’t know, Coletiv is a software development studio from Porto specialized in Elixir, iOS, and Android app development. But we do all kinds of stuff. We take care of UX/UI design, web development, and even security for you.</p><p>So,<a href="https://coletiv.com/contact"><strong> let’s craft something together?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4bb9262898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we scrapped and aggregated data from multiple sources using OTP]]></title>
            <link>https://medium.com/@tiago_55824/how-we-scrapped-and-aggregated-data-from-multiple-sources-using-otp-beccdb90f5f3?source=rss-592c00e7aacc------2</link>
            <guid isPermaLink="false">https://medium.com/p/beccdb90f5f3</guid>
            <category><![CDATA[genserver]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[post]]></category>
            <dc:creator><![CDATA[Tiago Duarte]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 08:01:01 GMT</pubDate>
            <atom:updated>2019-03-22T11:45:21.490Z</atom:updated>
            <content:encoded><![CDATA[<p>Just like in the documentary series “<a href="https://www.imdb.com/title/tt1224381/">Big, Bigger, Biggest</a>” we are going to show the different versions we developed on a real project, alongside the pitfalls and breakthroughs of each version, to increasingly scrape and aggregate bigger amounts of data from multiple sources and feed that data into a comprehensive dashboard.</p><h3>Challenge</h3><p>Earlier this year we were challenged by <a href="https://www.backercamp.com/">Backercamp</a> with a very interesting project, very different from the usual <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> based applications.<br>To give you some context Backercamp’s<em> </em>mission is to help creators of any kind — from new startups to established companies — bring products to market through crowdfunding platforms like <a href="https://www.kickstarter.com/">Kickstarter</a> or <a href="https://www.indiegogo.com/">Indiegogo</a>. Their aim is to bring performance and efficiency to crowdfunding by combining custom made software and their dedicated service.</p><blockquote>Being a performance driven business, Backercamp faced a problem <strong>“how do we track and report to creators the progress and success of our work so that we increase both transparency and trust?”</strong></blockquote><p>One of the many ways Backercamp increases the sales of the creator’s product is by using online advertisement on social networks like <a href="https://www.facebook.com/">Facebook</a>.<br>When it comes to online advertisement, one of the most used metrics to track success is the so-called <a href="https://en.ryte.com/wiki/ROAS">RoAS</a>, an acronym for “Return on Advertising Spend”. <strong>The RoAS tracks the income a creator gets back from every unit of currency (e.g. euro or dollar) invested in advertisement.</strong></p><p>After many successfully backed projects under their belt and with all the experience accumulated from talking with creators regarding the problem faced, they came up with the idea of creating a dashboard for each backer. <br>The dashboard would display aggregated data coming from both the crowdfunding platform and the advertisement platform, this would allow the live report and tracking of many metrics, including the aforementioned RoAS.</p><p>In technical terms, this meant that we would need to constantly fetch and aggregate data from sources that we don’t control and in some cases didn’t even have an <a href="https://en.wikipedia.org/wiki/Open_API">open API</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pzc01FRfLsECI-wlJ4obQ.png" /></figure><p>We had never done such a project, so we went to the blackboard and started scribbling down possible solutions. Before we could reach any conclusions we had to get our heads back again into the Elixir documentation so that we could better understand the <a href="http://erlang.org/doc/design_principles/des_princ.html">OTP design principles</a>, namely <a href="https://hexdocs.pm/elixir/Supervisor.html">Supervisors</a> and <a href="https://hexdocs.pm/elixir/GenServer.html">Genservers</a>. <br>Here are some of the resources we explored:</p><ul><li><a href="http://erlang.org/doc/design_principles/des_princ.html">OTP design principles</a></li><li><a href="https://elixir-lang.org/getting-started/mix-otp/genserver.html">Genserver</a> — from the official Elixir website</li><li><a href="https://elixir-lang.org/getting-started/mix-otp/dynamic-supervisor.html">Dynamic supervisors</a> — from the Elixir website</li><li><a href="https://pragprog.com/book/lhelph/functional-web-development-with-elixir-otp-and-phoenix">Functional Web Development with Elixir, OTP, and Phoenix book</a> by <a href="https://twitter.com/lance_halvorsen">Lance Halvorsen</a></li><li><a href="https://www.manning.com/books/elixir-in-action">Elixir in Action</a> book by <a href="https://twitter.com/sasajuric">Saša Jurić</a></li></ul><h3>V1 Source oriented approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yk_UdzHUqX3YpBcOYNEgxw.png" /><figcaption>V1 Solution — Source oriented approach</figcaption></figure><p>Our initial approach was to scrape each source (e.g. Kickstarter) on its own GenServer.<br>Each GenServer would, every 4 hours, fetch all the projects from the database and, project by project, fetch the correspondent source data.</p><h4>Problems</h4><p><strong>What happened when fetching the data for a project fails causing the GenServer to crash?</strong><br>With this approach the GenServer would die, then because the <a href="https://hexdocs.pm/elixir/Supervisor.html#module-restart-values-restart">Supervision strategy</a> was set up as being :permanent, the Supervisor would restart again the GenServer and it would try to sequentially scrape again all the projects. Because the code did not change the same error would happen again, causing again the GenServer to crash re-starting the process over and over.</p><p>Being noobs and going against the mantra “let it crash” from the <a href="https://www.youtube.com/watch?v=4ZIPijEqrNI">Zen of Erlang</a>, we tried to handle all the errors. <strong>Problem was that we were depending on external services, which meant we could not fully control the data and errors we were receiving</strong> so this was a dead end.</p><p><strong>Duration of the scrapes was growing and growing<br></strong>As soon as we added more projects to the platform and because the scrappes were sequential, the sources of data started to block us by retrieving <a href="https://developers.facebook.com/docs/graph-api/advanced/rate-limiting/">rate limit errors</a>. <br><strong>Once again, we didn’t take the time to step back from the problem and threw more code into it.</strong> We decided to use the <a href="https://github.com/safwank/ElixirRetry">ElixirRetry</a> dependency that provides an <a href="https://en.wikipedia.org/wiki/Exponential_backoff">Exponential backoff</a> algorithm. <br>We shot ourselves in the foot, this heavily increased the amount of time it took for each scrape to complete, having the risk to not even complete all the scrapes in the time window of 4 hours we had.</p><p><strong>What if we wanted to manually scrape a single project?<br></strong>At a certain point we wanted to allow the admin users to trigger scrapes for a single project so that they could update the data shown in the dashboard, but with the current solution, we could only scrape all projects at once.</p><p>This was the final nail in the coffin of the current solution and so we decided to get back to the drawing board.</p><h3>V2 Project-oriented solution, a genserver per each project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VryShCrJPZ03DWrTmgD5mA.png" /><figcaption>V2 Project oriented solution, a genserver per each project</figcaption></figure><p>Luckily by the time we were drawing alternatives to our initial version, the <a href="https://hexdocs.pm/elixir/DynamicSupervisor.html">DynamicSupervisor</a> was released on <a href="https://elixir-lang.org/blog/2018/01/17/elixir-v1-6-0-released/#dynamic-supervisor">Elixir v1.6</a>.</p><p>Making use of this new capability we decided to create a project-oriented solution where each project has a Genserver responsible for scraping the data at every 4 hours. This allowed us to segregate the damages of a crash when scraping a project if the Genserver crashed it would not affect other projects. <br>The solution also allowed us to parallelize and distribute the scrapes throughout the 4-hour window, which completely reduced the number of rate limit errors being thrown by our sources of data. And finally, we were able to manually trigger scrapes on a single project.</p><p>Let’s take a look at 2 of our most common use cases: adding a new project and archiving a project. For simplification purposes, we abstracted many components that play a role in the whole flow (e.g. views, controllers, context, …).</p><p><strong>Adding a new project<br></strong>When an admin adds a new project, the dynamic supervisor starts a new child process passing it the project_idthat the process will be responsible for. The process immediately stores a new key-value pair on the <a href="https://elixir-lang.org/getting-started/mix-otp/ets.html">Erlang Term Storage</a> (ETS) with the key being the project_id and the value being its Process ID (PID) and triggers an initial scrape.<br>This data stored on ETS will be later used when the admin user archives a project or triggers a scrape for a single project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJ4ahkxgstObsszHXlLUSg.png" /><figcaption>Add project flow</figcaption></figure><p><strong>Archiving a project<br></strong>When an admin archives a project the flow is basically the reverse of adding a new project: the application retrieves the PID responsible for the project, the Dynamic Supervisor then deletes the entry for the ETS and using the retrieved PID terminates the child project responsible for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahEPN8yC0ZVkClstW-GGVg.png" /><figcaption>Archive project flow</figcaption></figure><p><strong>Triggering a scrape on a single project<br></strong>The mechanism for scrapping a single project is similar: the admin triggers a scrape, the application retrieves the PID responsible for the project, the Dynamic Supervisor then using the retrieved PID sends a message (:scrappe_project) to the child project responsible for the project.</p><p>The code responsible for the Supervisor and Project Worker can be seen as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc8b65c4f09d616159f3d69d27149ffc/href">https://medium.com/media/cc8b65c4f09d616159f3d69d27149ffc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c208446e556fec12d4775aef96479c/href">https://medium.com/media/23c208446e556fec12d4775aef96479c/href</a></iframe><h4>Problems</h4><p><strong>How can we get rid of the start worker?</strong><br>When the application starts we need to immediately start all project workers under the supervision of the Scrape Supervisor. <br>At the beginning, we tried to start the project workers on the init method of the Supervisor, but we would get the following error:</p><pre>[info] Application Backercamp exited: Backercamp.Application.start(:normal, []) returned an error: shutdown: failed to start child: Backercamp.Scrapper.Supervisor<br>    ** (EXIT) exited in: GenServer.call(Backercamp.Scrapper.Supervisor, {:start_child, {{Backercamp.Scrapper.ProjectWorker, :start_link, [%{project_id: 30}]}, :transient, 5000, :worker, [Backercamp.Scrapper.ProjectWorker]}}, :infinity)<br>        ** (EXIT) process attempted to call itself</pre><p>To solve this problem we created a Genserver that is started after the Supervisor and whose only responsibility is to start all the project workers.</p><p><strong>Would it be possible to simplify the current archival mechanism?<br></strong>In order to manually archive a project we resorted to using ETS to store the project_id and the respective PID responsible for scrapping its data, would there be a simpler way of doing this feature?</p><p><strong>Different data from the same source requires different scrape frequency<br></strong>Project requirements evolve over time and so it happened in our case. <br>Users were asking for certain data points to be updated more often, but with the current solution, it would not be possible. We can only get all the data at once for a certain project, we can’t tell the system to get just a single point of data for all projects. <br>This was when we, once again, had to improve the current solution. This time the change was not so drastic and we ended up mixing the ideas from the previous 2 versions.</p><h3>V3 A mix between the previous solutions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKuxRLEJpeRiFGzL0R3vJg.png" /><figcaption>V3 A mix between the previous solutions</figcaption></figure><p>Picking up on the initial idea of having a source worker per each platform, we simply added a source worker responsible for fetching the data point needed with a much higher frequency (every 5 minutes).<br>If this worker fails no big problems arise as the regular scrapers will still work independently.</p><h3>What will the future hold?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUv2GgD9SMYwKTpiJa837g.png" /><figcaption>Snapshot of the dashboard with fake data</figcaption></figure><p>At the time of writing, we don’t have big drawbacks from the current solution and the feedback from our dashboard users has been great. But from our experience we know that projects evolve, more features are added and current ones are changed which may lead to newer versions of the current architecture.</p><p>Also, we are still learning and experimenting a lot with the Elixir / Phoenix ecosystem which keeps giving us new ideas and improvements to our projects. <br>Lately, we have been using <a href="https://hexdocs.pm/phoenix/channels.html">channels</a> a lot and are moving more and more towards a near-real-time experience to the users. Our end goal is to provide a fully reactive dashboard that shows data with a delay that can be measured in seconds. We know it is a big aim but we also know how important data is for the decisions our users make, some of them bet their life on their creations and it is always a pleasure and also a responsibility to provide them with the best tool we can.</p><p>If you are launching a product on Kickstarter or Indiegogo you should definitely talk with <a href="https://www.backercamp.com/">Backercamp</a>, they will provide all the help you need!</p><h4>Thank you for reading!</h4><p>Thank you so much for reading and if you enjoyed this article make sure to hit that 👏👏 button. It means a lot to us! Also<strong> don’t forget to follow </strong><a href="https://coletiv.com/"><strong>Coletiv</strong></a><strong> on </strong><a href="https://medium.com/coletiv-stories"><strong>Medium</strong></a><strong>, </strong><a href="https://twitter.com/coletivstudio"><strong>Twitter</strong></a><strong>, and </strong><a href="https://www.linkedin.com/company/coletiv/"><strong>LinkedIn</strong></a> as we keep posting more and more interesting articles on multiple technologies.</p><p>In case you don’t know, Coletiv is a software development studio from Porto specialized in Elixir, iOS, and Android app development. But we do all kinds of stuff. We take care of UX/UI design, web development, and even security for you.</p><p>So,<a href="https://coletiv.com/contact"><strong> let’s craft something together?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beccdb90f5f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>