<?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 Andrej Ocenas on Medium]]></title>
        <description><![CDATA[Stories by Andrej Ocenas on Medium]]></description>
        <link>https://medium.com/@aoc?source=rss-cd7f5448d457------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M2_7vwhj49Io6dr1JaM9UA.jpeg</url>
            <title>Stories by Andrej Ocenas on Medium</title>
            <link>https://medium.com/@aoc?source=rss-cd7f5448d457------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:36:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aoc/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[About clean code]]></title>
            <link>https://medium.com/@aoc/about-clean-code-56a0cc89b48b?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/56a0cc89b48b</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 18:31:37 GMT</pubDate>
            <atom:updated>2020-01-12T18:31:37.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NpGtAufbaLBw4vpR" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today I read Dan Abramov’s <a href="https://overreacted.io/goodbye-clean-code/">article about clean code</a> and as I feel pretty strongly about clean/readable/understandable code I wanted to put my thoughts about that topic on (digital) paper.</p><p>The points in the article are objectively true and probably helpful for lots of people but at the same time, I think it misses an important point.</p><blockquote>The DRY principle is stated as “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”. (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">wikipedia</a>)</blockquote><p>For me, DRY is not about saving words or characters and making your code shorter. Gzip will do that better than you anyway.</p><p>I think the important part is to understand what “Every piece of knowledge” means. For me, it means that first and foremost making your code DRY should convey information, which is that those two things are actually one thing even though they are used or referenced from different places. So DRY is a very important tool to convey crucial information to others.</p><p>It is important to understand that this concept of what is a “piece of knowledge” does not necessarily map one to one to text. Sometimes the same code can represent distinct concepts or two parts of code that are different textually represent the same concept.</p><p>This principle also isn’t on a sliding scale between duplication and no abstraction up to being DRY with too much abstraction. Choosing the appropriate abstraction for what the code does is important but you can make your code DRY with very little abstraction or have lots of duplication while using convoluted and complex abstraction.</p><blockquote>Secondly, nothing is free. My code traded the ability to change requirements for reduced duplication, and it was not a good trade. For example, we later needed many special cases and behaviors for different handles on different shapes. My abstraction would have to become several times more convoluted to afford that, whereas with the original “messy” version such changes stayed easy as cake. (<a href="https://overreacted.io/goodbye-clean-code/">Dan’s article</a>)</blockquote><p>To some, this may suggest that there is a correlation between duplication and the changeability of the code. I think this creates a straw-man argument saying that the only way forward after the refactor is to keep the abstraction even though the underlying concepts change in a way that the abstraction is no longer appropriate.</p><p>I think this is what lots of people get wrong. In my opinion, code that is easiest to change is not one that was written with the change in mind and needs the least amount of textual diff to incorporate the new requirements. The code that is easiest to change is one that is most readable and most accurately represents the system it models at the current time, which makes it easy to understand what needs to change and how.</p><blockquote>The easiest system to change is the one that is easiest to understand.</blockquote><p>So without saying whether the refactor was a good thing or not, the important consideration isn’t about whether it better predicted the future requirements or how much new code it would need to change it. For me, the more important question would be whether it sensibly modelled the current state of the system, whether the code after the refactor was easier to understand than before and by extension easier to change with confidence.</p><p>The answer still may be “No”. Maybe the abstraction was a bit too complex for this case and it was harder to understand than before. Maybe the code that was almost the same did not represent the same “Piece of knowledge” or it did and would actually benefit from making it DRY. Even if it had to be unDRYed later when it no longer represented the system correctly, the change may have been easier even while changing the abstraction.</p><p>So to summarise: Don’t just sling patterns, principles or abstractions willy nilly. Understanding is usually the most important thing. You rise understanding by proper communication, in this context with your code. So when changing code, ask yourself whether your change makes it easier for others to understand the system or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56a0cc89b48b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to type react-redux style HOC in Typescript]]></title>
            <link>https://medium.com/@aoc/how-to-type-react-redux-style-hoc-in-typescript-f21c1e9c1aaa?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21c1e9c1aaa</guid>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 11:41:55 GMT</pubDate>
            <atom:updated>2019-01-06T16:20:16.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMN1Fh_eueVS8bYIpyhLYw.png" /><figcaption>This probably won’t compile</figcaption></figure><p>Even though render props and hooks are all the rage recently, I do not think HOCs as a pattern will go away anytime soon. Typing HOCs though can be a pretty daunting task especially when you go into connect style HOC where you have a HOC factory function, that is configured with function accessing props of the wrapped component.</p><p>Obviously, the best way to find out how to do it is to look at how it was already done. Redux has a good set of <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-redux">declaration in DefinitelyTyped</a> and that was exactly where I looked at. If it was easy to understand what was going on there though I would not decide to write this, so I hope this explanation will help you grasp the concepts faster.</p><p>TLDR: If you just want to see the code, <a href="https://gist.github.com/aocenas/5200570ece4358d0133cfcbdecfe5d53">here it is</a>, otherwise, continue to step by step explanation.</p><p>First, let’s see what we want to do without any typing information in plain JavaScript</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f16291527d2091fe883252f34acb13/href">https://medium.com/media/f7f16291527d2091fe883252f34acb13/href</a></iframe><p>This is a simplification compared to real connect function for sake of clarity of this example. But it contains all important parts that make typing such function hard and it should be easy to see how you can build on top of it and add more functionality later on.</p><p>So, in essence, this is an injector, but a dynamic one. What it injects is dependant on the result of mapProps function. Also what mapProps function should get as an argument is dependant on the WrappedComponent because it will be its props minus whatever we are injecting.</p><p>So lets first type the mapProps function. This should be easy enough:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab41c5d39be2e52544c7bff5c1a35ee/href">https://medium.com/media/1ab41c5d39be2e52544c7bff5c1a35ee/href</a></iframe><p>We do not know the exact type of neither OwnProps nor MappedProps so we need to make them generic parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c9e952fdf5cdbfa6660bd5cf3c8a3f/href">https://medium.com/media/12c9e952fdf5cdbfa6660bd5cf3c8a3f/href</a></iframe><p>Again compared to react-redux typings this is fairly simple. The reason is that in react-redux you also have mapDispatchToProps, mergeProps, and options and there are overloads for various combinations of those parameters as not all are required.</p><p>So what does this first function return? First let’s figure out what is the type of the WrappedComponent. We already have OwnProps and MappedProps defined there and we know that our WrappedComponent will get both so let’s try that first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c17942074b7d65a6dfda5e5860eb8e2/href">https://medium.com/media/5c17942074b7d65a6dfda5e5860eb8e2/href</a></iframe><p>Now it is easy to see what will be the final type as we just subtract MappedProps leaving us with OwnProps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59dbe1ea750454e08e6b30527c9857b9/href">https://medium.com/media/59dbe1ea750454e08e6b30527c9857b9/href</a></iframe><p>This kinda works but this is nowhere near the complexity of react-redux typing. So let’s see how this works and what issues there are with this simple approach.</p><p>First, it does not handle defaultProps in any way. If our WrappedComponent has some defaultProps defined, its props will be defined as non-optional but are not required when using the component. At the same time if we do not do anything special, at the moment mapProps won’t get any defaults so OwnProps are not the same as inside the WrappedComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f83fe621e315d73d99468c75d491cf/href">https://medium.com/media/06f83fe621e315d73d99468c75d491cf/href</a></iframe><p>This is technically correct as the Connected component does not have any defaultProps. If you want to use num as non-optional in mapProps you need to pass it to Connected or you could define it as optional and handle it inside the mapProps.</p><p>One way to handle this is to hoist the defaultProps from WrappedComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e720269754f19cda905f03713fd3dc58/href">https://medium.com/media/e720269754f19cda905f03713fd3dc58/href</a></iframe><p>There are few important changes:</p><ol><li>We extracted the WrappedComponent type into generic parameter &lt;C extends React.ComponentType&lt;MappedProps &amp; OwnProps&gt;&gt; so we can reuse it later.</li><li>The ConnectedComponent type is &lt;React.ComponentType&lt;JSX.LibraryManagedAttributes&lt;C, OwnProps&gt;&gt;. The JSX.LibraryManagedAttributes part is the type that handles defaultProps in a way that it makes them optional in result type.</li><li>We use ConnectedComponent.defaultProps = WrappedComponent.defaultProps as any to hoist our defaults. The any part is unfortunate but necessary here. To be correct we should actually pick only defaults for OwnProps but we do not know at this time what they are. So we are assigning defaults for OwnProps + MappedProps here. A side effect of this is that we will have default values for props that are not defined in the Connected component which is not ideal.</li><li>Our ConnectedComponent has props: any. This is a side effect of using C as a generic parameter instead of exact type and I am not exactly sure why. If anybody has an idea please leave a comment. In any case, you do not know what props you will get anyway so you do not usually need to have type there, you are passing it further down. If you needed some props for internal working of the HOC, you could add another type for internal props and make the ConnectedComponent require also those.</li></ol><p>Mind that this is different from react-redux as it is <a href="https://github.com/reduxjs/react-redux/issues/633">not hoisting your defaultProps</a> but it is using the JSX.LibraryManagedAttributes with a subtle <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30957">issue</a>. I do not thing hoisting the defaultProps is the best approach so I will continue without it but we will keep using the JSX.LibraryManagedAttributes type because even without hoisting the defaultProps it is needed to properly handle defaults in WrappedComponent.</p><p>The second issue this still has is that we are not actually inferring anything from the WrappedComponent. This can be ok for some use-cases but can be tedious because you need to properly define both MappedProps and OwnProps or always type the mapProps arguments when using the HOC which can be awkward when you do not need to use the props there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1c3b55d1836034e416871d0d827c789/href">https://medium.com/media/f1c3b55d1836034e416871d0d827c789/href</a></iframe><p>Even if you do that, you created a function that takes only a special kind of WrappedComponent and so you will get type errors when wrapping the component if it does not match MappedProps and OwnProps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/025a6b5d5070c63af1c9a9e12c1e6531/href">https://medium.com/media/025a6b5d5070c63af1c9a9e12c1e6531/href</a></iframe><p>This additional strictness could be seen as a personal preference but let’s try going further and figure out how to make it bit easier to use.</p><p>So first we need to figure out how to get real props of the WrappedComponent instead of always assuming it will be OwnProps + MappedProps. For that, we will use infer keyword which you can use in TypeScript although only in <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">extend clause of a conditional type</a>. react-redux uses a nice little helper for getting props from a ComponentType:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7b34c39edefb1591c890ed886bfc552/href">https://medium.com/media/b7b34c39edefb1591c890ed886bfc552/href</a></iframe><p>And we will need also a small utility type Omit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51f1d4d6703c9ef0f63d552f61effba/href">https://medium.com/media/a51f1d4d6703c9ef0f63d552f61effba/href</a></iframe><p>So now we can use them instead of OwnProps in WrappedComponent definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8a607c93d633753321116013fb8bfa/href">https://medium.com/media/2f8a607c93d633753321116013fb8bfa/href</a></iframe><p>WrappedComponent now extends React.ComponentType&lt;GetProps&lt;C&gt;&gt; which is kinda obvious but it means it is not strictly tied to what is defined in mapProps as OwnProps anymore.</p><p>As I mentioned, we are still using JSX.LibraryManagedAttributes here even though we are not hoisting defaultProps. The reason is that whatever is left after we remove MappedProps from WrappedComponent props needs to take defaultProps into account. At the same time, we add &amp; OwnProps, so that we still type check what you require in mapProps and make sure it is passed into the ConnectedComponent, without taking defaultProps into account for them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c0d1c19eb6695edc1eacdf9433e065/href">https://medium.com/media/d1c0d1c19eb6695edc1eacdf9433e065/href</a></iframe><p>One thing that can be seen as a drawback is that MappedProps can have keys which are not expected by the WrappedComponent which in some cases can be a sign of a bug or just forgotten code but is in sync with how react-redux works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b466540f508695e7cc94e7477c9a6686/href">https://medium.com/media/b466540f508695e7cc94e7477c9a6686/href</a></iframe><p>So are we done now? What will happen if we inject the right props but of the wrong type? Right now our HOC will let that slide because we just omit our MappedProps keys without any check for the types of the keys.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0c6fbb13ba794e2a12d036e89707cb/href">https://medium.com/media/7b0c6fbb13ba794e2a12d036e89707cb/href</a></iframe><p>In react-redux they also thought about that. They use another helper type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/281256b4f11b2dbd44a748355a41b8ee/href">https://medium.com/media/281256b4f11b2dbd44a748355a41b8ee/href</a></iframe><p>The main point is that in case theDecorationTargetProps cannot accept a type of key from InjectedProps it will return type where the offending key is of type from InjectedProps. This creates a type that needs to match our WrappedComponent props otherwise we would be injecting wrong props into our component. Our generic parameter for WrappedComponent now changes to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7cb3821e47390dc575f78d00ad6f39d/href">https://medium.com/media/e7cb3821e47390dc575f78d00ad6f39d/href</a></iframe><p>So at this moment, we will get a type error when we try to wrap component which cannot handle the type of injected props.</p><p>So now we are done and it looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c40068c8ec31244f723eacf9c8fa7c9/href">https://medium.com/media/8c40068c8ec31244f723eacf9c8fa7c9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aad5c9b53a5a3ccc0df4be134b83b10/href">https://medium.com/media/8aad5c9b53a5a3ccc0df4be134b83b10/href</a></iframe><p>Side note on one difference that can be spotted if you look at the react-redux typing.</p><p>The return type of the final component in react-redux is in essence this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1674bb1204d22faeeb6c5ec15d12bac/href">https://medium.com/media/f1674bb1204d22faeeb6c5ec15d12bac/href</a></iframe><p>With Shared defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea04400d57876931700df30547e8a377/href">https://medium.com/media/ea04400d57876931700df30547e8a377/href</a></iframe><p>This should omit only keys which are assignable to the WrappedComponent. One issue is that even though this returns type where keys that do not match types in WrappedComponent get mapped to never, when used with keyof even never keys are returned and so we remove also non-matching keys from the requirements of the final component which seems like a bug.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389dbcaa42881782d59f49a69b1fcdea/href">https://medium.com/media/389dbcaa42881782d59f49a69b1fcdea/href</a></iframe><p>You could use a modified version of Shared type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633443d43176b9bf5c560da6b3ec0e9e/href">https://medium.com/media/633443d43176b9bf5c560da6b3ec0e9e/href</a></iframe><p>This returns shared keys which types also match directly so your final component would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0e336747e12f1cedbe0ed16ec80e25/href">https://medium.com/media/5b0e336747e12f1cedbe0ed16ec80e25/href</a></iframe><p>But as we are already getting an error from our previous use of Matching type this won’t get used, because we do not allow wrapping of a component that cannot take the proper type of props. You could remove the Matching part from the WrappedComponent definition and keep Shared instead. That would mean you get an error on type mismatch at the place you are using the final ConnectedComponent, saying that you need to supply prop even though it is supplied in mapProps function (due to the mismatch in types of that injected prop). This seems to me as more confusing so I prefer the solution with Matching.</p><p>And now it is really all. Hope this helps and if you find any issue please comment and I will try to respond with something meaningful. Also, this was all done and tested with Typescript 3.2.1 so check your version first if something does not work as advertised here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21c1e9c1aaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring HOC library to React hooks]]></title>
            <link>https://medium.com/@aoc/refactoring-hoc-library-to-react-hooks-6097d2ba5edf?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/6097d2ba5edf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 23:14:46 GMT</pubDate>
            <atom:updated>2018-12-01T12:37:59.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vrI8MZtUEvFKxyT8" /><figcaption>Photo by <a href="https://unsplash.com/@samuelzeller?utm_source=medium&amp;utm_medium=referral">Samuel Zeller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I decided to experiment with how I write React applications. Usually this involves Redux, sometimes Apollo or some boilerplate reducing scaffolding and I like all of these but I always feel like the experience could be better.</p><p>What I wanted to do is something that would have small modular parts I can combine as I needed. I wanted to start simple, just with data fetching, without any global state and just pluck it in later on. I wanted to still use redux underneath so I do not need to reinvent all the tooling around it. I also wanted redux to be still usable in its raw form for more complex state management or as a migration path.</p><p>So I started working on react-sync-tools as a set of HOCs that would meet these vague requirements. It is still work in progress and I can’t say I am fully satisfied with it but at the same time it provides subjectively better interface for some of my small projects, than most of other solutions I tried. Apollo is in some ways similar but sometimes you just can’t or don’t want to use GraphQL and I have other <a href="https://medium.com/@aoc/working-with-apollo-4cc9ad7fddcf">nitpicks with it</a>.</p><p>In the meantime though React introduced Hooks in their 16.7.0 alpha and I realised that with them, the code I was working on could be much simpler and that some parts will probably even disappear. So I got hooked like the rest of the internet and jumped on the opportunity to try them on some non trivial code.</p><h4>Typescript sidenote</h4><p>It is some time since I worked with typescript so doing a small library in it seemed like a nice way to get familiar with it again and see how it progressed. TypeScript can be pretty complicated as exemplified <a href="https://github.com/Microsoft/TypeScript/issues/14833">here</a>. It is also not fun debugging errors like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e994cc13887c2462c98481c7b04a92/href">https://medium.com/media/85e994cc13887c2462c98481c7b04a92/href</a></iframe><p>and sometimes I feel like I need a separate debugger for the type system to understand what is going on.</p><p>Even when you get things right it is still possible that some 3rd party library will cut some corners somewhere and your types won’t survive contact with it.</p><p>When everything is right though it feels pretty good to get errors when you mistype a plain string if it does not match your expected prop type in the wrapped component.</p><h4><a href="https://github.com/aocenas/react-sync-tools">react-sync-tools</a></h4><p>As I mentioned I wanted something modular and that is easy for the simple stuff, while being able to grow easily just by adding components. For me that means I want to be able to do network fetch from a component without hassle for a quick prototyping, before getting into how to store it and just add state management later when needed.</p><p>withActions is a HOC for that, you supply it with an object of Promise returning functions and you will get each wrapped in an object with isLoading, response, error and run properties. This way you do not have to handle cancellation, checking whether component is mounted or local state changes yourself.</p><p>withModel is another HOC to give you access to predefined model which is saved in your redux store. Your wrapped component will get current state and any reducers defined for your model.</p><p>You can easily chain those two so that your actions can call models reducers to store the response or to check beforehand if the action is needed. You can easily compose this into a new HOC and reuse it as needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1b2c15dc59fd3b39c5f4b33f8fbcd0d/href">https://medium.com/media/f1b2c15dc59fd3b39c5f4b33f8fbcd0d/href</a></iframe><p>You can see the code <a href="https://github.com/aocenas/react-sync-tools">here</a>.</p><h4><a href="https://github.com/aocenas/react-sync-tools-hooks">react-sync-tools with hooks</a></h4><p>Obviously hooks are still experimental at the moment and so are all the things I did with them.</p><p>From the start, hooks seem to be a much better fit to what I wanted to do than HOCs (or render props for that matter). They compose much easier. Do you have multiple hooks you use together often? Just wrap them a function. That’s it. People tend to focus on the rule that you can use them only in top level but that haven’t been a problem even when you start composing them. When you think about them as defining a class method it does not seem that strange anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8b17ddac1619b95b4ff50ceb93e381/href">https://medium.com/media/5c8b17ddac1619b95b4ff50ceb93e381/href</a></iframe><p>This simpler API also means it is much easier to type. You go from factory functions creating HOCs, to simple function taking arguments and returning something new.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e9a8a8b2114241cf8c8d78ee70f2d86/href">https://medium.com/media/3e9a8a8b2114241cf8c8d78ee70f2d86/href</a></iframe><p>One thing I was worried about was having to provide both hooks implementation and HOCs or render props components with new libraries. Except for more complex types it is really easy to create HOCs from hooks. For example the withAction HOC based on useAction hook looks like this (with some omissions for clarity):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071ee18a980af87e22f7dee653fc043d/href">https://medium.com/media/071ee18a980af87e22f7dee653fc043d/href</a></iframe><p>You can see the react-sync-tools-hooks repo <a href="https://github.com/aocenas/react-sync-tools-hooks">here</a>.</p><p>There are some caveats with the hooks, that can be confusing at the start.</p><p>Hooks are executed during render, which makes sense. They are simple functions, there is no magic and they are not transpiled to some different code or a class component. They just call some React internals and ask it to store some value, retrieve it or run something at a specified moment. But that also means anything that runs in a hook cannot really affect current render, except for throwing some error or provide value that would change what and how is rendered. That means we do not have useShouldComponentUpdate hook. Even React.memo is not a hook but a decorator (or higher order function).</p><p>There could be some updates as this is <a href="https://github.com/facebook/react/issues/14110">recognised</a> by the React team and there is a discussion going on about it.</p><p>It also means that you are running your hooks on each render. So if your hook is doing something expensive you should make sure you memoize it. Some of the hooks that React provide already use memoization based on array of values that you pass as the last argument to them. If any of the values change, they will recompute and return new value otherwise they return the same one (see for example the <a href="https://reactjs.org/docs/hooks-reference.html#usecallback">useCallback</a>).</p><p>Some libraries already use pattern where there is only one parameter and they require that parameter to not change if you do not want to recompute the hook. For example I used <a href="https://github.com/facebookincubator/redux-react-hook">redux-react-hook</a>, which takes a mapping function which needs be stable between renders otherwise you get infinite rerender loop. That means either creating the mapping function with userCallback or defining it outside of the render function.</p><p>Overall, creating something with hooks was very pleasant experience and even though I was sceptical at first I consider it a step in the right direction from the React team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6097d2ba5edf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Apollo]]></title>
            <link>https://medium.com/@aoc/working-with-apollo-4cc9ad7fddcf?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cc9ad7fddcf</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 11:08:24 GMT</pubDate>
            <atom:updated>2018-10-26T11:08:24.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Re2KOzLscemUs7Eb" /><figcaption>“timelapse photo of total lunar eclipse” by <a href="https://unsplash.com/@jakehills?utm_source=medium&amp;utm_medium=referral">Jake Hills</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my current work we decided to try GraphQL to speed up our development a bit. We were sold by the good people of the internet on productivity benefits and ease of use compared to RESTish APIs.</p><p>After some research, Apollo was picked as library to use both server side and client side and we went on to try rewriting one feature to test the waters. There is lots of tutorials, explanations and enumerations of benefits of either Apollo or GraphQL in general. This will be more critical and will try to describe some issues I encountered while implementing our proof of concept.</p><p>Even though this will probably sound more critical and negative, that is only because decided not to repeat the good parts here only the bad ones. Despite the flaws we still plan to invest more time into Apollo and use it for other features.</p><p>Also some of the issues are real bugs that can be fixed by the time you read this so always check the current state of issues on Github.</p><h4>Server side performance</h4><p>This is a general thing with GraphQL and how you write resolvers and not specific to Apollo but I thought I would mention it.</p><p>In naive implementation, you create a resolver for each node in a query graph which can lead to N+1 queries as each item in a child node is queried separately. For example querying Users and then Articles of each user would mean doing an Articles query for each user.</p><p>This can be mitigated by <a href="https://github.com/facebook/dataloader">dataloader</a> (which you probably want to use by default) but the way it works, you will still do one query for Users and one for Articles.</p><p>99% of time this is fine, GraphQL actually can help with performance because you usually need less http requests from the client but if you have some super optimised queries, you could have hard time porting them to your resolvers.</p><h4>Bugs</h4><p>For a library where lots of components are over 1.0.0 version there seems to be quite a few bugs that I would not expect. <a href="https://github.com/apollographql/apollo-client/issues/3452">This</a> is an open thread listing bugs for a networkPolicy option when doing queries. Most are fixed but for example setting networkPolicy to network-only still renders from cache first in the same way as cache-and-network is behaving. This is still open issue in a 2.4.3 version of the apollo-client.</p><p>So before using Apollo I would recommend checking the current status of open issues. We do not use features like subscriptions or manual cache updates at this moment so I am not sure how stable those features are. We were able to work around all issues for now but we will reevaluate if we find more bugs or if they become blocking.</p><h4>React API</h4><p>For usage with React you can use both higher order component functions or a component with a render prop. I am not a big fan of render prop component in these kind of usages. I rarely need to change the props of the data loading component due to render and if you need to nest multiple mutations it can get ugly pretty fast.</p><pre>&lt;Mutation ...&gt;<br>  {mutate1 =&gt;<br>    &lt;Mutation ...&gt;<br>      {mutate2 =&gt; ...<br>      }<br>    &lt;/Mutation&gt;<br>  }<br>&lt;/Mutation&gt;</pre><p>You can use some helpers to compose the components but at that point it seems like HOC is better way to do that. One problem with that is that mutation HOC does not pass mutation result as a prop and so you can get result only by promise chaining on the provided mutate function. This means your component now needs to be stateful and you need to check mounted state of your component which makes for more error prone code.</p><p>It is trivial to create a custom HOC and fix this but it can surprise you when you first try to use it.</p><h4>Documentation</h4><p>Apollo documentation is not the worst I have seen but could be improved. For example some parameters are explained only in an API reference for the HOC, while there is no link form other parts where the same param is used. There are some omissions mentioned in the Github issues which are long outstanding. As a result I had to go into source code on multiple occasions.</p><p>Again this is not such a big issue but for how mature Apollo looks from the outside, it was surprising.</p><p>As I mentioned we will still continue to use Apollo despite the flaws but my initial enthusiasm was curbed because of them. As with any kind of technology you should always look for stability and maturity of a software. I feel like Apollo looks much more mature on the outside than it actually is so keep that in mind when considering it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cc9ad7fddcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kinesis Firehose to Redshift pipeline with Terraform]]></title>
            <link>https://medium.com/@aoc/kinesis-firehose-to-redshift-pipeline-with-terraform-2261b5afd29d?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/2261b5afd29d</guid>
            <category><![CDATA[kinesis]]></category>
            <category><![CDATA[firehose]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[redshift]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 06:07:44 GMT</pubDate>
            <atom:updated>2019-01-15T20:38:22.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nBYMDywlS4D7cCTX" /><figcaption>“A drone shot of an intersection with an overpasses” by <a href="https://unsplash.com/@ed259?utm_source=medium&amp;utm_medium=referral">Edouard Ki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AWS is a great piece of technology. It can help you build powerful solutions by stacking up pieces like lego bricks. Getting them to stack up right though can be challenging and sometimes you can end up reading about routing tables when you just wanted to get some data into your database.</p><p>This should be a semi complete example of how to create a pipeline with Firehose that pushes data into Redshift from a Node server, including creation of VPC and IAM permissions. There are obvious missing pieces with this setup like better security setup, logging and tighter permissions but it should get you started.</p><p>If you want to jump to the code <a href="https://github.com/aocenas/redshift-data-pipeline-demo">here is the repo</a>. Otherwise I will try to give some explanations and context so it is easier to modify and reuse the code for people not proficient with Terraform and AWS.</p><p><strong>Disclaimer: </strong>This code creates resources, that while running, will be billed to your AWS account.</p><h3>Overview</h3><p>Architecture of this demo is simple: our Node server will receive post request with JSON payload of the data and pushes the data into Firehose. Firehose will store the data into S3 bucket and will trigger COPY operation on Redshift to load the data from S3</p><h3>Terraform config</h3><p><a href="https://www.terraform.io/">Terraform</a> helps you describe and create/modify/destroy your infrastructure. When running terraform apply it will create a plan of execution which will be executed after confirmation. terraform destroy will destroy all resources defined in the configuration files. You should understand that sometimes terraform destroy can timeout or fail to destroy some resources. If you worry about incurring charges, make sure you understand what was created so you can destroy it manually if needed. Particularly, S3 bucket used in this example to store data will not be destroyed by Terraform if it is not empty.</p><h4>Provider</h4><p>We will use <a href="https://www.terraform.io/docs/providers/aws/index.html">AWS Terraform provider</a> for creating the AWS resources:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4c2b7c46e131eeff01421b0ce16cf5/href">https://medium.com/media/0e4c2b7c46e131eeff01421b0ce16cf5/href</a></iframe><p>We specify region and profile here to define where to create the resources and with what credentials. When you setup AWS CLI it will create default profile for you which would be used here if profile is not explicitly specified. When working with multiple AWS accounts (like company account and personal account) I found out it is easier for me to not have default profile so I have to specify profile explicitly.</p><h4>S3 resources</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5c209b92eb91c4d918c52293d32726/href">https://medium.com/media/eb5c209b92eb91c4d918c52293d32726/href</a></iframe><p>We will create S3 bucket where Firehose will store the data. Shipping data first to S3 is necessary in this setup as Redshift does not talk to Firehose directly.</p><p>We will also create an S3 object with some configuration. This will be used as a <a href="https://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html#r_COPY_command_examples-copy-from-json">mapping from the JSON data in S3 files to Redshift columns</a>. This is not necessary in case your JSON data are simple objects with keys equivalent to Redshift table columns.</p><h4>IAM</h4><p>Next we create role and policy so we can access the S3 bucket. We will use single role for both Redshift and Firehose to simplify the setup but otherwise you would probably want separate roles. We also did not setup any logging or encryption so we only add S3 permissions. You can read more about required permissions <a href="https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-s3">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abdab7f31000617c100eef6f5dae17d4/href">https://medium.com/media/abdab7f31000617c100eef6f5dae17d4/href</a></iframe><pre>&quot;Principal&quot;: {<br>  &quot;Service&quot;: [<br>    &quot;firehose.amazonaws.com&quot;,<br>    &quot;redshift.amazonaws.com&quot;<br>  ]      <br>},</pre><p>This part says which services are allowed to assume this role. We have to specify both services here otherwise you would not be able to use the role even if you configured it for the resources.</p><pre>&quot;Action&quot;: [<br>  &quot;s3:AbortMultipartUpload&quot;,<br>  ...<br>],<br>&quot;Resource&quot;: [<br>  &quot;${aws_s3_bucket.s3_bucket.arn}&quot;,<br>  &quot;${aws_s3_bucket.s3_bucket.arn}/*&quot;<br>]</pre><p>Only actions needed by the Firehose and Redshift to access the data are allowed in the policy.</p><h4>VPC</h4><p>This section is kinda optional, depending on whether you have default VPC in your account or not. If you have old account that still allows for <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#differences-ec2-classic-vpc">running instances outside of VPC</a> you probably do not have default VPC and will need to create one for the Redshift cluster. If you have default VPC you can run it there or you can still create separate VPC for this demo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb547c9ad69b7a323d2a44737aeb6d0/href">https://medium.com/media/bdb547c9ad69b7a323d2a44737aeb6d0/href</a></iframe><p>This creates a VPC with one public subnet. We need the subnet to be public because we want to access our Redshift from outside but also because <a href="https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-rs">Firehose needs access to it</a>.</p><p>Then we create a security group that allows all traffic in and out. In real life scenario you would want to allow access only from trusted sources like Firehose or your servers.</p><p>Finally we just create a resource needed for connecting the subnet with Redshift.</p><p>As a side note, this is the only part where I use Terraform modules. Modules are nice way to structure your Terraform config and encapsulate logic into reusable parts with inputs and outputs, similar to putting your code into functions. You can find modules in the <a href="https://registry.terraform.io/">registry</a>. You could probably shorten the config with more modules and my decision where to use modules is mostly arbitrary.</p><h4>Redshift cluster</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27633333bd230e0840ecd9587aafaa3b/href">https://medium.com/media/27633333bd230e0840ecd9587aafaa3b/href</a></iframe><p>We link our subnet, security group and role with the cluster. We need to set publicly_accessible = true so it gets public IP address. Option skip_final_snapshot = true allows us to destroy the cluster faster without any data hanging around afterwards. In production you would probably want it false. Similarly you should not keep passwords in files that should be committed to your VCS. For additional info about how to handle secrets with terraform look in the <a href="https://www.terraform.io/docs/state/sensitive-data.html">docs</a> or <a href="https://tosbourn.com/hiding-secrets-terraform/">here</a> for a bit more comprehensive explanation.</p><p>We also use local-exec provisioner to run sql that will create a table to store the data. This is run only on the creation of the cluster. If you do not have psql locally you can comment it and run the the CREATE TABLE manually.</p><h4>Firehose</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36255a2b7ded1f14521862b8a0794901/href">https://medium.com/media/36255a2b7ded1f14521862b8a0794901/href</a></iframe><p>As mentioned before, we still need to setup S3 destination even when final destination is redshift. Again we need to link IAM role and specify access to the Redshift cluster. We use copy options where we specify the mapping from the JSON to columns. Important thing to note is that by default, Redshift will not understand ISO date format and you need timeformat ‘auto&#39; in the options.</p><p>Firehose creates files in the S3 with time prefix and also a manifest file that is used in the COPY command issued from Redshift. This means that if you delete the manifest file, Firehose will still create new data files but without creating another manifest file and the COPY will not work. Seems like recreating the Firehose or recreating the manifest manually is only way to recover from that.</p><h4>Client</h4><p>Client is fairly standard Node server that uses <a href="https://aws.amazon.com/documentation/sdk-for-javascript/">AWS SDK</a> to push received data into the Firehose. After POSTing to /data endpoint in format { &quot;name&quot;: &quot;test_value&quot;, &quot;value&quot;: 1.0 } you should see it in Redshift. This can take a minute as data is buffered by Firehose and is not delivered real time to the S3. buffer_interval setting controls this behaviour but 60s is minimal value.</p><p>Again, full code can be found <a href="https://github.com/aocenas/redshift-data-pipeline-demo">here</a>. Follow the readme to run the whole demo.</p><p>If you find any problems comment here or create an issue in the repo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2261b5afd29d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Spark on Docker Swarm]]></title>
            <link>https://medium.com/@aoc/running-spark-on-docker-swarm-777b87b5aa3?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/777b87b5aa3</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[swarm]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Sun, 27 Nov 2016 13:14:07 GMT</pubDate>
            <atom:updated>2016-11-27T13:14:07.708Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are like me, playing with neural networks on your Mac Air can seem tedious. So I decided to try to optimize my experimentation by using Spark on AWS. Having some experience with Docker and inspired by this <a href="https://medium.com/@daviws/a-swarm-of-sparks-8f5a4afc72cc#.534b45cvg">article</a>, I decided to try it together with Swarm.</p><p>First thing to note is that there are two versions of Swarm, one is stand alone Swarm that is older, and new Swarm mode built into docker engine. Article I mentioned is written with old Swarm so it will not work with the new Swarm mode. This is something you need to have in mind when searching for Swarm materials.</p><p>TLDR; you can just take a look at <a href="https://github.com/aocenas/spark-docker-swarm">example repo</a>, if you are not interested in Whys and Hows.</p><p>I assume you already have an AWS account and you have configured AWS cli. You also need some VPC and a subnet with some ports opened. For AWS it is now default to use VPC instead of classic mode where all machines were on common network. You also have to create an Internet Gateway and add route 0.0.0.0 -&gt; internet_gateway_id so you can access your instances inside the VPC. Your VPC should have default security group assigned, with all traffic allowed in between instances of the security group and SSH, 80, 8081 ports allowed from outside.</p><p>After this we can start creating some instances. Crate one instance that will serve as our Swarm and Spark master. We will distinguish this with — engine-label role=master .</p><pre>EGION=eu-west-1 # change as needed<br>ZONE=c # change as needed<br>VPC_ID=&lt;your_vpc_id&gt; # you probably do not need this if your VPC is set as default VPC<br>CLUSTER_PREFIX=spark-cluster<br>MASTER_TYPE=m4.large<br>SPARK_IMAGE=gettyimages/spark:2.0.2-hadoop-2.7</pre><pre>DRIVER_OPTIONS=&quot;\<br>--driver amazonec2 \<br>--amazonec2-security-group=default \<br>--amazonec2-vpc-id $VPC_ID \<br>--amazonec2-zone $ZONE \<br>--amazonec2-region $REGION&quot;<br><br>MASTER_OPTIONS=&quot;$DRIVER_OPTIONS \<br>--engine-label role=master \<br>--amazonec2-instance-type=$MASTER_TYPE&quot;<br><br>MASTER_MACHINE_NAME=<strong>$</strong>{CLUSTER_PREFIX}-master<br>docker-machine create $MASTER_OPTIONS $MASTER_MACHINE_NAME</pre><p>Next init the instance as Swarm master.</p><pre># get private ip of the master machine, you need a jq utility json parser<br>MASTER_IP=$(aws ec2 describe-instances — output json | jq -r \<br>“.Reservations[].Instances[] | select(.KeyName==\”$MASTER_MACHINE_NAME\” and .State.Name==\”running\”) | .PrivateIpAddress”)</pre><pre># init the Swarm master<br>docker-machine ssh $MASTER_MACHINE_NAME sudo docker swarm init — advertise-addr $MASTER_IP</pre><pre># get token that we will use to add workers to the Swarm<br>TOKEN=$(docker-machine ssh $MASTER_MACHINE_NAME sudo docker swarm join-token worker -q)</pre><p>Create some workers and join them to the Swarm.</p><pre>WORKER_TYPE=m3.medium<br>SPOT_PRICE=0.067<br>NUM_WORKERS=3</pre><pre>WORKER_OPTIONS=&quot;$DRIVER_OPTIONS \<br>--amazonec2-request-spot-instance \<br>--amazonec2-spot-price=$SPOT_PRICE \<br>--amazonec2-instance-type=$WORKER_TYPE&quot;<br>WORKER_MACHINE_NAME=<strong>$</strong>{CLUSTER_PREFIX}-worker-<br><br><strong>for </strong>INDEX <strong>in $</strong><em>(seq $NUM_WORKERS)<br></em><strong>do<br>    </strong><em>(<br>        docker-machine create $WORKER_OPTIONS $WORKER_MACHINE_NAME$INDEX<br>        docker-machine ssh $WORKER_MACHINE_NAME$INDEX sudo docker swarm join --token $TOKEN $MASTER_IP:2377<br>    ) </em>&amp;<br><strong>done<br></strong><em>wait</em></pre><p>Note for spot price instances, you should make sure that your spot price is above actual spot price seen in <a href="https://aws.amazon.com/ec2/spot/pricing/">https://aws.amazon.com/ec2/spot/pricing/</a>. Otherwise you will have to wait until the price drops. You can put your spot price at normal instance price, you still pay actual spot instance price which is lower than normal but you have higher chance to get one.</p><p>Next we will create a network, our Spark services and one proxy service so we can get into our cluster. New Swarm mode does not work with docker-compose at this time (although you can create a bundle from your compose file and deploy that). With docker-compose you would create links between your services, with Swarm you need to add them to common network. Swarm will then create a virtual ip and balance traffic between containers of a service.</p><pre>docker network create --driver overlay spark-network<br><br>docker service create \<br>--name master \<br>--constraint engine.labels.role==master \<br>--replicas 1 \<br>--network spark-network \<br>${SPARK_IMAGE} \<br>bin/spark-class org.apache.spark.deploy.master.Master<br><br>docker service create \<br>--name worker \<br>--constraint engine.labels.role!=master \<br>--replicas $NUM_WORKERS \<br>--network spark-network \<br>${SPARK_IMAGE} \<br>bin/spark-class org.apache.spark.deploy.worker.Worker spark://master:7077<br><br><em>docker </em>service create \<br>--name proxy \<br>--constraint engine.labels.role==master \<br>--replicas 1 \<br>--publish &quot;80:80&quot; \<br>--publish &quot;8081:8081&quot; \<br>--network spark-network \<br>library/nginx:stable</pre><p>We use engine labels created before to constraint our services to their respective instances. As you can see we do not publish any ports on the Spark services. There is an <a href="https://github.com/docker/docker/issues/24637">issue</a> with this setup, that when you publish some ports, your service will be in the <a href="https://docs.docker.com/engine/swarm/ingress/">ingress network</a> that is used to load balance traffic to containers but at the same time it is inside our spark-network. That mess up the connectivity between workers and master. That is why we have separate service that just proxies traffic into the Swarm.</p><p>For the proxy, you can either create an image with the config or you can exec into the container, replace the nginx.conf and reload nginx.</p><pre>user  nginx;<br>worker_processes  1;<br><br>error_log  /var/log/nginx/error.log warn;<br>pid        /var/run/nginx.pid;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    server {<br>        listen 80;<br><br>        location / {<br>            proxy_pass http://master:8080;<br>        }<br>    }</pre><pre>    server {<br>        listen 8081;<br><br>        location / {<br>            proxy_pass http://worker:8081;<br>        }<br>    }<br>}</pre><p>This is not the most elegant solution, especially because when you navigate to your master UI web page, links are mapped to internal IPs of the containers, which won’t work.</p><p>Last but not least, script to destroy everything afterwards. It will check all docker machines name spark-cluster-* and remove them. This will also terminate them in AWS thanks to the AWS docker machine driver.</p><pre>CLUSTER_PREFIX=spark-cluster<br>docker-machine ls | grep “^${CLUSTER_PREFIX}” | cut -d\ -f1 | xargs docker-machine rm -y</pre><p>If anybody made this work with better solution, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=777b87b5aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Watchman setup]]></title>
            <link>https://medium.com/@aoc/simple-watchman-setup-ab006e97fb1d?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab006e97fb1d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[watchman]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Mon, 23 May 2016 16:37:49 GMT</pubDate>
            <atom:updated>2016-05-23T16:37:49.720Z</atom:updated>
            <content:encoded><![CDATA[<p>My pipeline for building <a href="http://www.whatlib.com/">whatlib</a> is fairly simple but using nodemon for watching and restarting does not cut it. To be honest, Watchman is on the other end of spectrum and for my use case, it’s probably like using a rocket launcher to kill a fly. Next time I would probably go with something like <a href="https://github.com/paulmillr/chokidar">https://github.com/paulmillr/chokidar</a> but I found it only after I already had working Watchman setup (ironically as <a href="http://www.whatlib.com/">whatlib</a> should help you find the right library). Anyway, you have been warned and because Watchman documentation is not the easiest and quickest of reads, this post should serve as a little help.</p><p>All my source files live in src directory, that is javascript, jade and sass files. JS files are transpiled into dist directory by babel. Jade and sass files are just copied into dist without change, to preserve the same relative paths. Sass is later compiled into css by express middleware. This means I have two tasks that I need to do on file change based on file type:</p><ol><li>Transpile js and jsx files into dist with babel.</li><li>Copy jade and sass files into dist without change.</li></ol><p>As I mentioned, I started with nodemon and my package.json scripts looked like this:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;./node_modules/.bin/babel ./src -d ./dist --copy-files&quot;,<br>  &quot;build-watch&quot;: &quot;./node_modules/.bin/nodemon --watch src -e js,jade,jsx,sass --exec npm run build&quot;,</pre><pre>...</pre><pre>},</pre><p>As you can imagine, compiling whole project on each change is rather ineffective. And thus come Watchman.</p><p>After installing Watchman you first need to watch your project. Even though you give watch-project command a directory, it is safer to also add .watchmanconfig in your root project dir. You can find the project path resolution <a href="https://facebook.github.io/watchman/docs/cmd/watch-project.html#what-39-s-a-project-path">here</a>.</p><pre>&gt; cd /your/project/path<br>&gt; watchman watch-project .</pre><p>After this Watchman is watching your project but nothing is triggered after change. We define 2 triggers in separate json files, using <a href="https://facebook.github.io/watchman/docs/cmd/trigger.html#extended-syntax">extended syntax</a>.</p><pre>// babelTrigger.json<br>[<br>  &quot;trigger&quot;,<br>  &quot;./&quot;,<br>  {<br>    &quot;name&quot;: &quot;babel&quot;,<br>    &quot;expression&quot;: [<br>      &quot;anyof&quot;,<br>      [&quot;match&quot;, &quot;src/**/*.js&quot;, &quot;wholename&quot;],<br>      [&quot;match&quot;, &quot;src/**/*.jsx&quot;, &quot;wholename&quot;]<br>    ],<br>    &quot;command&quot;: [&quot;node&quot;, &quot;./babel.js&quot;],<br>    &quot;append_files&quot;: <strong>true<br>  </strong>}<br>]</pre><pre>// copyTrigger.json<br>[<br>  &quot;trigger&quot;,<br>  &quot;./&quot;,<br>  {<br>    &quot;name&quot;: &quot;copy&quot;,<br>    &quot;expression&quot;: [<br>      &quot;anyof&quot;,<br>      [&quot;match&quot;, &quot;src/**/*.jade&quot;, &quot;wholename&quot;],<br>      [&quot;match&quot;, &quot;src/**/*.sass&quot;, &quot;wholename&quot;]<br>    ],<br>    &quot;command&quot;: [&quot;node&quot;, &quot;./copy.js&quot;],<br>    &quot;append_files&quot;: <strong>true<br>  </strong>}<br>]</pre><pre>// to create the triggers<br>&gt; watchman -j &lt; babelTrigger.json<br>&gt; watchman -j &lt; copyTrigger.json</pre><p>Things to note here:</p><ul><li>‘./’ is a root directory for the trigger, other paths will be relative to this.</li><li>‘command’ will be executed by file change specified in ‘expression’</li><li>‘append_files’ means that file names will be appended to the command, not given in stdin. This means my scripts will read them as arguments.</li></ul><p>Any output of your scripts will be piped into Watchers log, which is by default in &lt;PREFIX&gt;/var/run/watchman/&lt;USER&gt;-state for version &gt;3.8. That means that, in case you installed with brew, your log is somewhere like this:</p><pre>/usr/local/Cellar/watchman/4.5.0/var/run/watchman/myusername-state/log</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab006e97fb1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript and Flow]]></title>
            <link>https://medium.com/@aoc/typescript-and-flow-e90e46afd6a0?source=rss-cd7f5448d457------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90e46afd6a0</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Andrej Ocenas]]></dc:creator>
            <pubDate>Sat, 21 May 2016 08:53:02 GMT</pubDate>
            <atom:updated>2016-05-21T08:53:02.625Z</atom:updated>
            <content:encoded><![CDATA[<p>I am a fan of static typing so when building <a href="http://www.whatlib.com/">www.whatlib.com</a> I decided to try first Typescript and then Flow.</p><p>TLDR; I ended up using Flow as it has a bit better documentation and is less invasive when using it for existing project.</p><h4>Typescript</h4><p>But anyway, I started with Typescript as it seemed as a better solution at the start. And it actually is quite easy to convert. As advertised you can just change your .js and .jsx files to .ts and .tsx respectively, change your transpiler to tsc and thats it. In my case my project looks a bit like this:</p><pre>\-root<br>  \-dist<br>  \-src</pre><p>as I was already transpiling everything with babel and running my application from dist, because I want to use the same code/syntax on client and server.</p><p>The real fun begins when you do not want to look at all the compilation errors. My tsconfig.json looked like this:</p><pre>{<br> “compilerOptions”: {<br>   “module”: “commonjs”,<br>   “noImplicitAny”: false,<br>   “preserveConstEnums”: true,<br>   “rootDir”: “./src”,<br>   “sourceMap”: true,<br>   “forceConsistentCasingInFileNames”: true,<br>   “jsx”: “React”,<br>   “moduleResolution”: “node”,<br>   “target”: “es5”<br> },<br> “exclude”: [<br>   “typings/browser.d.ts”,<br>   “typings/browser”,<br>   “node_modules”<br> ]<br>}</pre><p>With noImplicitAny = false you get less type errors but less type safety, but should be easier when you want to ease into it. Bigger issue is third party modules. For those you need to tell TypeScript compiler their definitions. You can do that manually (and you probably will have to anyway in some cases) or use Typings (previously called TSD) which is tool for managing external module definitions.</p><p>This is where I spent most of the time while converting my project. Typings have a notion of different sources of definitions, most used are probably from <a href="http://definitelytyped.org/">http://definitelytyped.org/</a> or directly from NPM packages, where package author can put typings info into package.json. Typings directly from NPM should be more accurate, but most of the time there are only definitions from definitely typed (“dt” source in typings output). To install a definition just do:</p><pre>typings search module_name</pre><pre>// for definitions from NPM<br>typings install module_name --save<br>// for definitions from dt<br>typings install module_name --ambient --save</pre><p>Honestly I could not find good documentation for this but ambient means it loads definitions by default from “dt” source. Save argumen is similar to save in npm, and creates a typings.json where you have list of all installed definitions, presumably so you you do not have to check them into version control, similarly to npm and package.json.</p><p>But then I came to a point where I still had some errors, for example Object.assign was unknown. Reason was that my compile target was ES5 and could be fixed by creating my own definitions but I already lost my patience and went to try Flow.</p><h4>Flow</h4><p>The starting point for this was the same commit as with Typescript. The infrastructure setup is easier, you just need babel plugins, one for syntax and one for striping the type informations. The overall idea of Flow seems to be more geared towards incremental compliance, so I added</p><pre>// @flow</pre><p>comment to some files, it gave me some easily to fix issues. Also there were some files from node_modules which gave some errors so I just added them to Flow ignore list and that was basically it. Much less work than with Typescript. On the other hand, with Flows aggressive type inference, I am not sure if my code is more type safe than with Typescript approach. Probably the opposite, but for me, easier setup and gradual adoption was what I wanted.</p><p>One big positive thing is that for the most part it seems that Typescript and Flow type syntax is identical. I did not try it, but I assume that for the most part you could just switch to Typescript later on and your types from Flow would be picked up right away. You can also add typing info in separate files, defining classes, interfaces or module, which is similar approach as TypeScript definitions for external modules.</p><p>Some caveats:</p><ul><li>I use WebStorm IDE lately which has some Flow support, so it won’t bark on it’s type syntax, but it does not give you any Flow type errors. I ended up using watcher that just outputs Flow info into console window inside WebStore. Not anywhere as nice as it’s Typescript integration but workable.</li><li>With Typescript you probably want to use TSLint, with Flow there are more plugins for ESLint. Also for ESLint you need to change its default parser to babel-eslint.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90e46afd6a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>