<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Haskell Explained</title>
  
  <generator>Styx</generator>
  <updated>2020-09-26T00:00:00Z</updated>
  <id>https://haskell-explained.gitlab.io/blog/feeds/atom.xml</id>
  <link href="https://haskell-explained.gitlab.io/blog/feeds/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="https://haskell-explained.gitlab.io/" rel="alternate"/>
  <author>
  <name>Styx</name>
</author>

  
  
  <entry>
  <id>https://haskell-explained.gitlab.io/blog/posts/2020/09/26/http-apis-with-webgear/index.html</id>
  <title>HTTP APIs with WebGear</title>
  <updated>2020-09-26T00:00:00Z</updated>
  <link href="https://haskell-explained.gitlab.io/blog/posts/2020/09/26/http-apis-with-webgear/index.html" rel="alternate" type="text/html"/>
  <summary type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>I recently released <a href="https://hackage.haskell.org/package/webgear-server">WebGear</a> - a library to build HTTP APIs. While
Haskell has a number of libraries and frameworks for building HTTP API servers, WebGear is somewhat unique in the design
space. I will explain some interesting features of WebGear in this post.</p>

      </div>
    </summary>
  <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>First of all, you should check out the <a href="https://rkaippully.github.io/webgear/guide/introduction/">user guide</a> if you are
not familiar with WebGear. This is a short blog post and I won&#8217;t be covering everything in detail.</p>

<h2 id="haskellforhttpapis">Haskell for HTTP APIs</h2>

<p>Most APIs accept some input from the HTTP request, perform a bunch of validations and operations, and then respond with
some data retrieved from a backend such as a database or other services. Haskell has some unique strengths that makes
this whole process robust.</p>

<p>I strongly believe in making illegal states unrepresentable in the types and techniques like <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">&#8220;parse, don&#8217;t
validate&#8221;</a>. Haskell is well-suited for this
style of programming and WebGear implements some of these ideas in building HTTP APIs.</p>

<h2 id="typesafety">Type Safety</h2>

<p>Haskell&#8217;s type system makes it possible to encode concepts at type level and WebGear makes good use of this. For
example, here is a handler:</p>

<pre><code class="language-haskell">-- Use this handler for a route such as: PUT /api/widget/&lt;widgetId&gt;
putWidgetHandler :: Have [ Method PUT
                         , PathVar &quot;widgetId&quot; Int
                         , JSONRequestBody Widget
                         , BasicAuth
                         ] req
                 =&gt; Handler req Widget
putWidgetHandler = ...
</code></pre>

<p>This handler can only be used with requests with a PUT method and a URL path variable named <code>widgetId</code> with an <code>Int</code>
value. It is a compile time error otherwise, here is an example:</p>

<pre><code class="language-text">• The request doesn't have the trait ‘Method 'PUT’.

  Did you use a wrong trait type?
  For e.g., ‘PathVar &quot;foo&quot; Int’ instead of ‘PathVar &quot;foo&quot; String’?

  Or did you forget to apply an appropriate middleware?
  For e.g. The trait ‘JSONRequestBody Foo’ can be used with ‘jsonRequestBody @Foo’ middleware.
</code></pre>

<p>Middlewares &#8220;parse&#8221; the request and express traits such as HTTP method as a type level list. The trait attributes can be
extracted from the request in a type safe manner:</p>

<pre><code class="language-haskell">type WidgetId = PathVar &quot;widgetId&quot; Int

putWidgetHandler :: Has WidgetId req =&gt; Handler req Widget
putWidgetHandler = Kleisli $ \request -&gt; do
  -- wid has type Int
  let wid = get (Proxy @WidgetId) request
  ...
</code></pre>

<p>You cannot access the widget ID unless you have a <code>Has WidgetId</code> constraint in the type signature. And to satisfy this
 constraint, you must use the <code>pathVar</code> middleware which verifies the presence of such a path variable in the request.</p>

<p>You don&#8217;t need to know a lot of advanced haskell features to use WebGear. Using <code>Has</code> or <code>Have</code> constraints and the
<code>get</code> function with a <code>Proxy</code> is enough to get you going.</p>

<h2 id="composablehandlers">Composable Handlers</h2>

<p>Composition is a key tool to manage complexity. The ability to split code into reusable pieces and combine them at will
is the foundation on which we build all our software. WebGear shines really well in this. Handlers are regular functions
and you can just use function composition.</p>

<p>For example, if you have a number of routes that use the same basic authentication, you can extract that as a common
authentication middleware.</p>

<pre><code class="language-haskell">allRoutes :: Handler req Widget
allRoutes = basicAuth &quot;realm&quot; checkCredentials
            $ getWidget &lt;|&gt; putWidget

getWidget :: Has BasicAuth req =&gt; Handler req Widget
getWidget = ...

putWidget :: Has BasicAuth req =&gt; Handler req Widget
putWidget = ...
</code></pre>

<p>This also shows a prominent difference between WebGear and Servant. Servant uses type level combinators to implement
such functionality. This helps to derive a server, client, documentation etc from the same type definition. But
composition at type level is not as easy to deal with as value level composition. Error messages are often cryptic and
this is a big barrier to entry for newcomers. You also have to resort to techniques like
<a href="https://hackage.haskell.org/package/servant-flatten">servant-flatten</a> to workaround problems caused by nested types.</p>

<p>WebGear on the other hand uses functions which can be composed trivially. The trade-off is that you cannot generate
client and documentation from WebGear middlewares and handlers, they only build a server.</p>

<h2 id="buildingmiddlewares">Building Middlewares</h2>

<p>Often you would want to build your own traits and middlewares. This is straightforward in WebGear.</p>

<p>Let us take an example. Many microservices use Correlation IDs to trace a transaction across many services. This is done
by sending a special HTTP header - <code>Correlation-ID</code> - in every request and response. All services include this
correlation ID in their logs. The first request in the transaction obviously will not receive the header and should
generate a random ID instead.</p>

<p>How do we implement this in WebGear? We start by defining a data type for correlation IDs and implement the <code>Trait</code> type
class for it.</p>

<pre><code class="language-haskell">data CorrelationId = CorrelationId ByteString

instance MonadIO m =&gt; Trait CorrelationId Request m where
  type Attribute CorrelationId Request = CorrelationId
  type Absence CorrelationId Request = Void

  toAttribute :: Request -&gt; m (Result CorrelationId Request)
  toAttribute req = do
    let h = requestHeader &quot;Correlation-ID&quot; req
    Found . CorrelationId &lt;$&gt; maybe randomUUID pure h
</code></pre>

<p>The <code>Trait</code> type class has two associated types - <code>Attribute</code> and <code>Absence</code>. <code>Attribute</code> is the type of the trait
attribute and <code>Absence</code> is an error type for the case when correlation ID is missing. In this case, we always have a
correlation ID, either from the request or a randomly generated one. So we use <code>CorrelationId</code> as the <code>Attribute</code> and
<code>Void</code> as <code>Absence</code>.</p>

<p>The <code>toAttribute</code> function returns a <code>CorrelationId</code> either from the <code>Correlation-ID</code> header or generating a random UUID.</p>

<p>Next, let us build a middleware that uses <code>CorrelationId</code>:</p>

<pre><code class="language-haskell">withCorrelationId :: MonadIO m
                  =&gt; RequestMiddleware' m req (CorrelationId : req) a
withCorrelationId handler = Kleisli $ \request -&gt; do
  result &lt;- probe @CorrelationId request
  either absurd runHandler result
  where
    runHandler request = do
      let CorrelationId cid = get (Proxy @CorrelationId) request
      response &lt;- runKleisli handler request
      pure $ setResponseHeader &quot;Correlation-ID&quot; cid response
</code></pre>

<p>The <code>probe</code> function checks the presence of <code>CorrelationId</code> and the result is an <code>Either</code> value with the <code>Left</code>
indicating <code>Absence</code> and the <code>Right</code> indicating an <code>Attribute</code>.</p>

<p>We know that <code>CorrelationId</code> is always present and will not have a <code>Left</code> case indicating absence of the trait. But most
other traits are &#8220;optional&#8221; and have to deal with a case where they are absent from the request. So <code>probe</code> returns an
<code>Either</code> value to indicate this.</p>

<p>The <code>absurd</code> function from <code>Data.Void</code> module is used to handle the <code>Left</code> case that will never occur.</p>

<p>For the positive case where we have a correlation ID, <code>runHandler</code> invokes the <code>handler</code> and then adds the correlation
ID to the response.</p>

<p>We can use this middleware with any of the handlers:</p>

<pre><code class="language-haskell">allRoutes :: Handler req ByteString
allRoutes = withCorrelationId
            $ putWidget &lt;|&gt; deleteWidget

putWidget :: Has CorrelationId req =&gt; Handler req ByteString
putWidget = method @PUT $ Kleisli $ \request -&gt; do
  let cid = get (Proxy @CorrelationId) request
  ...
</code></pre>

<h2 id="summary">Summary</h2>

<p>Hopefully this post has convinced you that WebGear can build type safe APIs without requiring a PhD in type theory. The
user-facing parts of the library is built with care to not require many advanced Haskell concepts. You can find
code, examples, and much more about WebGear in the <a href="https://github.com/rkaippully/webgear/">Github repo</a>.</p>

      </div>
    </content>
</entry>

<entry>
  <id>https://haskell-explained.gitlab.io/blog/posts/2019/08/27/pattern-synonyms/index.html</id>
  <title>PatternSynonyms for expressive code</title>
  <updated>2019-08-27T00:00:00Z</updated>
  <link href="https://haskell-explained.gitlab.io/blog/posts/2019/08/27/pattern-synonyms/index.html" rel="alternate" type="text/html"/>
  <summary type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p><a href="https://downloads.haskell.org/~ghc/8.6.5/docs/html/users_guide/glasgow_exts.html#extension-PatternSynonyms">PatternSynonyms</a>
is a very handy GHC extension to abstract away some implementation details of your data types and present a cleaner
interface to the rest of the code.</p>

      </div>
    </summary>
  <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <h2 id="patterns">Patterns</h2>

<p>Patterns are ubiquitous in Haskell code; it is one of the first things you learn as you get familiar with the
language. Almost every piece of Haskell code will have a pattern match construct in a function definition or case
expression. However, they have some limitations as well.</p>

<p>As an example, let us look at how to represent identifiers:</p>

<pre><code class="language-haskell">import qualified Data.Text as Text
import Data.Text (Text)

newtype Identifier = Identifier { unIdentifier :: Text }
  deriving Eq
</code></pre>

<p>We can construct values of type <code>Identifier</code> with the <code>Identifier</code> data constructor (e.g. <code>Identifier &quot;foo&quot;</code>). You can
deconstruct an identifier in two ways:</p>

<pre><code class="language-haskell">identifierLength1 :: Identifier -&gt; Int
identifierLength1 = Text.length . unIdentifier

identifierLength2 :: Identifier -&gt; Int
identifierLength2 (Identifier s) = Text.length s
</code></pre>

<p>Having both a record field accessor and a pattern matching syntax is very useful. We can pick the best one depending on
the usage.</p>

<h2 id="acuriouscase">A curious case</h2>

<p>How would you implement case-insensitive identifiers? In such a case, <code>Identifier &quot;foo&quot;</code> and <code>Identifier &quot;Foo&quot;</code> are
considered equal. We must retain the original case in the data type though. Many other use cases - such as displaying
the identifier with the original input case - require that.</p>

<p>Well, it turns out not too complicated. We can do this:</p>

<pre><code class="language-haskell">import Data.Function(on)

newtype Identifier = Identifier { unIdentifier :: Text }

instance Eq Identifier where
  (==) = (==) `on` (Text.toCaseFold . unIdentifier)
</code></pre>

<p>This is as expressive as the previous implementation. We still have the same data constructor and pattern matching at
the usage sites. It has one serious drawback though - performance. <code>Text.toCaseFold</code> is evaluated for each equality
check which makes this a slow operation.</p>

<h2 id="aperformancefix">A performance fix</h2>

<p>Here is one way to solve the performance problem:</p>

<pre><code class="language-haskell">data Identifier = Identifier
  { unIdentifier :: Text
  , folded       :: Text
  }

makeIdentifier :: Text -&gt; Identifier
makeIdentifier s = Identifier
  { unIdentifier = s
  , folded       = Text.toCaseFold s
  }

instance Eq Identifier where
 (==) = (==) `on` folded
</code></pre>

<p>This moves the expensive <code>Text.toCaseFold</code> to record construction so that we don&#8217;t pay a penalty on each <code>==</code>
evaluation. This covers the common use case where the identifier is constructed once and then the equality check is
performed many times on it. In fact, this is the implementation used by the <a href="https://www.stackage.org/package/case-insensitive">case-insensitive
package</a>.</p>

<p>However, we lost the nice symmetric data constructor and pattern match we had in the previous solution. We want to hide
the internal details of <code>Identifier</code> record from the usage sites. So we are forced to provide a smart constructor
<code>makeIdentifier</code> instead and hide the <code>Identifier</code> data constructor. This also means we cannot pattern match on the
<code>Identifier</code> data constructor anymore. The only way to deconstruct an identifier is via the <code>unIdentifier</code> function
which is less expressive than the previous solution.</p>

<h2 id="patternsynonymstotherescue">PatternSynonyms to the rescue</h2>

<p>This is where pattern synonyms come in. We can use a pattern synonym to define this &#8220;missing&#8221; pattern. Here is the
syntax:</p>

<pre><code class="language-haskell">{-# LANGUAGE PatternSynonyms #-}

data Identifier = MkIdentifier
  { unIdentifier :: Text
  , folded       :: Text
  }

instance Eq Identifier where
 (==) = (==) `on` folded

pattern Identifier :: Text -&gt; Identifier
pattern Identifier s &lt;- MkIdentifier s _ where
  Identifier s = MkIdentifier s (Text.toCaseFold s)
</code></pre>

<p>There are two components to this pattern synonym. First, we define how to use <code>Identifier</code> in pattern matches. The
part:</p>

<pre><code class="language-haskell">pattern Identifier s &lt;- MkIdentifier s _
</code></pre>

<p>tells GHC to replace a pattern match on <code>Identifier s</code> with <code>MkIdentifier s _</code>. For e.g., a case expression
like this:</p>

<pre><code class="language-haskell">case ident of
  Identifier s -&gt; ...
</code></pre>

<p>gets translated to:</p>

<pre><code class="language-haskell">case ident of
  MkIdentifier s _ -&gt; ...
</code></pre>

<p>The second part:</p>

<pre><code class="language-haskell">Identifier s = MkIdentifier s (Text.toCaseFold s)
</code></pre>

<p>tells GHC to replace all occurrences of <code>Identifier s</code> in expressions with the corresponding <code>MkIdentifier s
(Text.toCaseFold s)</code> expression. For e.g., a let expression like this:</p>

<pre><code class="language-haskell">let ident = Identifier s
in ...
</code></pre>

<p>gets translated to:</p>

<pre><code class="language-haskell">let ident = MkIdentifier s (Text.toCaseFold s)
in ...
</code></pre>

<p>Here is how the complete solution:</p>

<pre><code class="language-haskell">module Identifiers
  ( Identifier
  , pattern Identifier
  ) where

import           Data.Text (Text)
import qualified Data.Text as Text
import           Data.Function (on)

data Identifier = MkIdentifier
  { unIdentifier :: Text
  , folded       :: Text
  }

instance Eq Identifier where
 (==) = (==) `on` folded

pattern Identifier :: Text -&gt; Identifier
pattern Identifier s &lt;- MkIdentifier s _ where
  Identifier s = MkIdentifier s (Text.toCaseFold s)
</code></pre>

<p>The <code>MkIdentifier</code> data constructor and all its internal implementation details are hidden away but the usage sites
still can use the nice <code>Identifier s</code> patterns for data construction and pattern matching. Clearly, this is a good
improvement from the previous solution and retains all the performance benefits of it.</p>

<p>Note that there are other ways to declare pattern synonyms. See <a href="https://downloads.haskell.org/~ghc/8.6.5/docs/html/users_guide/glasgow_exts.html#extension-PatternSynonyms">GHC
documentation</a>
for more details. You might also be interested in the
<a href="https://www.stackage.org/haddock/nightly-2019-08-26/containers-0.6.0.1/Data-Sequence.html#t:Seq">Data.Sequence</a> module
that makes good use of pattern synonyms along with the ViewPatterns extension.</p>

      </div>
    </content>
</entry>

<entry>
  <id>https://haskell-explained.gitlab.io/blog/posts/2019/07/31/polysemy-is-cool-part-2/index.html</id>
  <title>Polysemy is fun! - Part 2</title>
  <updated>2019-07-31T00:00:00Z</updated>
  <link href="https://haskell-explained.gitlab.io/blog/posts/2019/07/31/polysemy-is-cool-part-2/index.html" rel="alternate" type="text/html"/>
  <summary type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>Continuing from <a href="/blog/posts/2019/07/28/polysemy-is-cool-part-1/index.html">part1</a>, we figure out how to interpret effects in
<a href="https://github.com/polysemy-research/polysemy">polysemy</a>.</p>

      </div>
    </summary>
  <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>If you have not already gone through the previous post, please do so for context. All the code discussed in this post is
available at <a href="https://gitlab.com/rkaippully/polysemy-password-manager/tree/part2">https://gitlab.com/rkaippully/polysemy-password-manager/tree/part2</a>.</p>

<h2 id="runningeffects">Running Effects</h2>

<p>So far we have seen how to define an effect as a data type and how to embed such effect values in the <code>Sem</code> monad. But
those effects were not &#8220;doing&#8221; anything. It&#8217;s all nice to have a good looking program, but what is the point if it does
not do something? How do we run the code so that we have a real password manager?</p>

<p>It is not hard to run effects. Remember me saying that the <code>r</code> in <code>Sem r a</code> is a list of effects? We pick the first
effect from that list and find a function that can handle that effect and eliminate it from the list. For example, if we
have a program of type <code>Sem [e1, e2] a</code>, we must find a function that will interpret the <code>e1</code> effect. Applying that
function will consume the <code>e1</code> effect and give us a value of type <code>Sem [e2] a</code>. Repeat this with an interpreter for <code>e2</code>
and you get a <code>Sem [] a</code>. This is a value with no effects. You can use the
<a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy.html#v:run"><code>run</code></a> function to get the value out of
it.</p>

<p>Let us see how this works in practice.</p>

<h2 id="interpretingcryptohash">Interpreting CryptoHash</h2>

<p>The first step is to define an interpreter for the <code>CryptoHash</code> effect that we defined. We&#8217;ll use the
<a href="https://en.wikipedia.org/wiki/Bcrypt">BCrypt</a> algorithm to manipulate password hashes as defined in the <a href="https://hackage.haskell.org/package/cryptonite-0.25/docs/Crypto-KDF-BCrypt.html">cryptonite
library</a>. The <code>hashPassword</code> and
<code>validatePassword</code> functions in cryptonite seem to correspond to the <code>MakeHash</code> and <code>ValidateHash</code> data constructors of
<code>CryptoHash</code>.</p>

<p>There is a function named
<a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy.html#v:interpret">interpret</a> in polysemy that lets
you handle an effect such as <code>CryptoHash</code>.</p>

<p>In the first round, we&#8217;ll implement <code>ValidateHash</code>.</p>

<pre><code class="language-haskell">runCryptoHashAsState :: Sem (CryptoHash : r) a -&gt; Sem r a
runCryptoHashAsState = interpret $ \case
  ValidateHash password hash -&gt; return (validatePassword password hash)
</code></pre>

<p>As you can see, <code>interpret</code> takes a function as its only parameter. This function has to transform a <code>CryptoHash m x</code>
value into a <code>Sem r x</code> value.</p>

<p>Also, pay close attention to the type signature <code>Sem (CryptoHash : r) a -&gt; Sem r a</code>. You might recall that the first
type parameter to <code>Sem</code> is a type-level list of effects. Here <code>(CryptoHash : r)</code> is a list of effects with <code>CryptoHash</code>
at its head and <code>r</code> as the tail - the remaining effects. After running the <code>interpret</code> function we eliminate the
<code>CryptoHash</code> effect from the type (because it has been interpreted) and return a <code>Sem r a</code>.</p>

<p>Interpreting <code>ValidateHash</code> is straightforward. We just delegate the call to <code>validatePassword</code> and lift the result into
<code>Sem r</code> monad.</p>

<h2 id="effectdependencies">Effect Dependencies</h2>

<p>Interpreting <code>MakeHash</code> via <code>hashPassword</code> is trickier. The type signature of <code>hashPassword</code> is <code>MonadRandom m =&gt; Int -&gt;
Password -&gt; m PasswordHash</code>. We need to run the hashing in a monad that allows random number generation. One choice is
to run it in <code>IO</code> monad. But that will cause our <code>Sem r</code> to be polluted with IO. This will allow some other piece of
code in this monad to run arbitrary IO actions. Let us avoid it if we can.</p>

<p>Another choice is to use a <a href="https://hackage.haskell.org/package/cryptonite-0.25/docs/Crypto-Random.html#t:MonadPseudoRandom">pseudo-random number
generator</a> with a
deterministic random number generator (DRG) initialized by a seed value. If we have access to such a DRG, we can use
<a href="https://hackage.haskell.org/package/cryptonite-0.25/docs/Crypto-Random.html#v:withDRG"><code>withDRG</code></a> function to run
<code>hashPassword</code> in a <code>MonadRandom</code> context. But every time we use a DRG, its internal state gets updated and we get a new
DRG value. So we need a mechanism to store this updated DRG and pass it to the next <code>MakeHash</code> usage.</p>

<p>This is where <a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy-State.html#t:State"><code>State</code></a> effect
comes in. We can use it to retrieve the current value of DRG. Then we invoke <code>withDRG</code> to generate a password hash. This
invocation will also return an updated DRG which we&#8217;ll save back into the State effect.</p>

<p>The code looks like this:</p>

<pre><code class="language-haskell">MakeHash password -&gt; do
  drg &lt;- get
  let (h, drg') = withDRG drg (hashPassword 10 password)
  put drg'
  return h
</code></pre>

<p>We managed to interpret the <code>CryptoHash</code> effect but that requires a <code>State</code> effect. We express this in the type
signature of <code>runCryptoHashAsState</code> function:</p>

<pre><code class="language-haskell">runCryptoHashAsState :: (DRG gen, Member (State gen) r)
                     =&gt; Sem (CryptoHash : r) a
                     -&gt; Sem r a
runCryptoHashAsState = interpret $ \case
  ValidateHash password hash -&gt; return (validatePassword password hash)
  MakeHash password          -&gt; do
    drg &lt;- get
    let (hash, drg') = withDRG drg (hashPassword 10 password)
    put drg'
    return hash
</code></pre>

<p>The constraint <code>Member (State gen) r</code> indicates that the <code>State gen</code> effect must be present in the list of effects
<code>r</code>. We need to find an interpreter for <code>State gen</code>, but let us leave that for later.</p>

<p>Let us go to the next effect we have - <code>KVStore</code>.</p>

<h2 id="interpretingkvstore">Interpreting KVStore</h2>

<p>Let us use an <a href="https://www.sqlite.org">SQLite database</a> to store the password hashes. We will assume we have a table
named <code>passwords</code> with two columns <code>username</code> and <code>hash</code> to store the data. Interpreting a <code>KVStore</code> with this table is
easy:</p>

<pre><code class="language-haskell">runKVStoreAsSQLite :: Member (Embed IO) r
                   =&gt; Sem (KVStore Username PasswordHash : r) a
                   -&gt; Sem (Input Connection : r) a
runKVStoreAsSQLite = reinterpret $ \case
  LookupKV username -&gt; do
    conn &lt;- input
    hashes &lt;- embed (queryNamed conn
                      &quot;SELECT hash FROM passwords WHERE username = :username&quot;
                      [&quot;:username&quot; := username])
    return (fromOnly &lt;$&gt; listToMaybe hashes)
  UpdateKV username maybeHash -&gt; do
    let (query, params) =
      case maybeHash of
        Just hash -&gt; ( &quot;INSERT INTO passwords (username, hash) &quot; &lt;&gt;
                       &quot;VALUES (:username, :hash) &quot; &lt;&gt;
                       &quot;ON CONFLICT (username) DO UPDATE SET hash = excluded.hash&quot;
                     , [&quot;:username&quot; := username, &quot;:hash&quot; := hash] )
        Nothing   -&gt; ( &quot;DELETE FROM passwords WHERE username = :username&quot;
                     , [&quot;:username&quot; := username] )
    conn &lt;- input
    embed (executeNamed conn query params)
</code></pre>

<p>The structure of this handler is similar to the previous one for <code>CryptoHash</code>. But there are some important differences.</p>

<p>First, we make use of the
<a href="https://hackage.haskell.org/package/sqlite-simple-0.4.16.0/docs/Database-SQLite-Simple.html">sqlite-simple</a> package for
the DB operations. Actions provided by this library run in the IO monad. We have to somehow incorporate that into our
interpretation. Polysemy allows embedding arbitrary monadic actions into the <code>Sem</code> monad via the <code>Embed</code> constraint. The
<code>Member (Embed IO) r</code> constraint indicates that we have embedded <code>IO</code> monadic actions in the <code>Sem</code> monad. In the code,
we can use the <code>embed</code> function to &#8220;lift&#8221; an <code>IO</code> operation into the <code>Sem</code> monad. This is analogous to <code>liftIO</code> in monad
transformers.</p>

<p>Second, we need a database connection to execute our operations. In the case of <code>CryptoHash</code>, a <code>State</code> effect was used
because of the need to get and update the DRG. In this case, the DB connection is just an input. Hence, we make use of
<a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy-Input.html#t:Input"><code>Input</code></a> effect instead. We use
the <a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy-Input.html#v:input"><code>input</code></a> function to get a
connection and use it for DB operations.</p>

<p>Third, we are using the function <code>reinterpret</code> here instead of <code>interpret</code>. There is a subtle but important difference -
<code>interpret</code> handles and eliminates an effect, while <code>reinterpret</code> merely translates one effect to another. The
<code>runCryptoHashAsState</code> handler converted a <code>Sem (CryptoHash : r) a</code> value into a <code>Sem r a</code> value; the <code>CryptoHash</code>
effect was eliminated. But <code>runKVStoreAsSQLite</code> handler converts a <code>Sem (KVStore Username PasswordHash : r)</code> value into
a <code>Sem (Input Connection : r) a</code> value. The <code>KVStore</code> effect just got reencoded as an <code>Input</code> effect.</p>

<p>But <code>runCryptoHashAsState</code> had a dependency on <code>State</code> effect and that was expressed as a type constraint. How is that
different from <code>reinterpret</code> reencoding the <code>KVStore</code> effect? </p>

<p>There are two differences. The <code>Member (State gen) r</code> constraint merely says <code>State gen</code> is one of the effects in
<code>r</code>. It can be located anywhere in the list <code>r</code> which means that this effect can be handled in an arbitrary order. The
handlers for <code>CryptoHash</code> and <code>State gen</code> are only loosely related to each other. But when <code>reinterpret</code> reencodes an
effect into another one, the new effect is added at the head of the effect list and has to be handled next. Typically,
the handlers for <code>KVStore Username PasswordHash</code> and <code>Input Connection</code> will get invoked in that order. This shows that
they are logically related; both these effects together represent the storage system for the data.</p>

<p>It is also crucial to note that there is a one-to-one correspondence between the two effects in <code>reinterpret</code>. Every
time a <code>KVStore</code> effect is handled by <code>runKVStoreAsSQLite</code> handler, a <em>new</em> <code>Input Connection</code> effect is added to the
list of effects. If our program had two separate key-value stores, it will need two separate connection inputs as
well. This makes sense because we don&#8217;t want the data in those two stores mixed up. But there is no such one-to-one
correspondence in the <code>Member</code> constraint introduced by <code>runCryptoHashAsState</code>. If we had two CryptoHash handlers, one
using bcrypt and another using scrypt, the same DRG can be shared for both. So only one handler for <code>State gen</code> is
necessary for any number of <code>CryptoHash</code> handlers.</p>

<h2 id="finalsteps">Final Steps</h2>

<p>With all this, we are ready for a complete implementation of our operations. Here is how to implement <code>addUser</code>:</p>

<pre><code class="language-haskell">runAddUser :: Username -&gt; Password -&gt; IO ()
runAddUser username password = do
  drg &lt;- getSystemDRG
  withConnection dbFile $ \conn -&gt;
    {-
       Handle effects one by one. The comments on each line indicates
       the list of effects yet to be handled at that point.
    -}
    addUser username password  -- [CryptoHash, KVStore Username Password]
      &amp; runCryptoHashAsState   -- [KVStore Username Password, State gen]
      &amp; runKVStoreAsSQLite     -- [Input Connection, State gen, Embed IO]
      &amp; runInputConst conn     -- [State gen, Embed IO]
      &amp; evalState drg          -- [Embed IO]
      &amp; runM
</code></pre>

<p>We get a DRG and a DB connection through the IO monad. Then we start handling the effects in <code>addUser username
password</code>. Notice how some effect handlers (such as <code>runCryptoHashAsState</code>) adds new effects to the &#8220;pending&#8221;
list. Eventually, we are left with a <code>Sem [Embed IO] a</code> value. The <code>runM</code> function can convert that to an <code>IO a</code> value.</p>

<p>Some of the handlers are defined in polysemy library itself - you can find the definitions of <code>runInputConst</code> and
<code>evalState</code> <a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy-Input.html#v:runInputConst">here</a> and
<a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy-State.html#v:evalState">here</a> respectively.</p>

<p>The <code>validatePassword</code> implementation is along similar lines and is left as an exercise for you.</p>

<h2 id="testingeffects">Testing Effects</h2>

<p>Polysemy also helps us in writing tests for our effects. We can provide alternate effect handlers in the test code and
test our effects for correctness and coverage.</p>

<p>below is such an implementation. Note that this code is pure and does not require the IO monad.</p>

<pre><code class="language-haskell">runAddUser :: DRG gen
           =&gt; gen
           -&gt; Map Username PasswordHash
           -&gt; Username
           -&gt; Password
           -&gt; Map Username PasswordHash
runAddUser drg m username password =
  addUser username password  -- [CryptoHash, KVStore Username Password]
    &amp; runCryptoHashAsState   -- [KVStore Username Password, State gen]
    &amp; runKVStorePurely m     -- [State gen]
    &amp; evalState drg          -- []
    &amp; run
    &amp; fst
</code></pre>

<p>This function takes a map of user names and hashes, performs the add operation, and returns the resultant map. A test
can validate that the output map contains expected entries.</p>

<p>For a more interesting example, see <a href="https://gitlab.com/rkaippully/polysemy-password-manager/blob/part2/test/Spec.hs">https://gitlab.com/rkaippully/polysemy-password-manager/blob/part2/test/Spec.hs</a></p>

<h2 id="summary">Summary</h2>

<p>That was a whirlwind tour of implementing effect handlers. Obviously, there is a lot more functionality in polysemy. The
library documentation is quite detailed and informative. Go check it out!</p>

      </div>
    </content>
</entry>

<entry>
  <id>https://haskell-explained.gitlab.io/blog/posts/2019/07/28/polysemy-is-cool-part-1/index.html</id>
  <title>Polysemy is fun! - Part 1</title>
  <updated>2019-07-28T00:00:00Z</updated>
  <link href="https://haskell-explained.gitlab.io/blog/posts/2019/07/28/polysemy-is-cool-part-1/index.html" rel="alternate" type="text/html"/>
  <summary type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>This post is an introduction to <a href="https://github.com/polysemy-research/polysemy">polysemy</a> - a new &#8220;effects&#8221; library that
can be used in place of monad transformers. We&#8217;ll build a real-world application to understand how to use it to
structure your code.</p>

      </div>
    </summary>
  <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <h2 id="context">Context</h2>

<p>There have been a lot of discussions about free/freer monads and extensible effects in the Haskell community for quite a
while now. There is plenty of information about these subjects out there but I could not find a good getting started
guide for a practical application. I had a good grasp of how to use monad transformers and mtl; I was naturally
curious about a practical application of effects.</p>

<p>I found <a href="https://github.com/KerfuffleV2/haskell-polysemy-test/">this example code</a> after some searching around. This
guided me in the right direction and gave me the confidence to rewrite one of my
<a href="https://github.com/rkaippully/gamgee">tools</a> using polysemy. After a few days of struggle with compiler errors, I
managed to rewrite the app completely and also added enough tests. The entire experience was very rewarding and I
learned a lot from it. At the same time, I could have done this a lot quicker if there was some sort of a beginners
tutorial. What better way to fill that gap than by writing one myself now that I have some idea about the topic?</p>

<p>So here we are building a real-world application, at least as real-world as it can get in a blog post. Enjoy the ride!</p>

<p>My goal is not to show you how free/freer monads work under the hood or how they compare against alternatives. There are
other articles available discussing those topics. I&#8217;ll focus on the usage of polysemy instead.</p>

<p>All the code discussed in this post is available at
<a href="https://gitlab.com/rkaippully/polysemy-password-manager/tree/part1">https://gitlab.com/rkaippully/polysemy-password-manager/tree/part1</a>.</p>

<h2 id="thepasswordmanager">The password manager</h2>

<p>Your boss asks you to build a password manager for securely storing usernames and passwords. You discuss the
requirements in detail with your boss. He wants to add a username and password to the password store and also check if a
given username and password combination is valid. Pretty standard stuff, so you get cracking.</p>

<p>You quickly write a spec in pseudo-code and show it to your boss for confirmation. He says that seems right-ish. And you
are ready to go!</p>

<pre><code class="language-haskell">addUser username password = do
    hashedPassword &lt;- makeHash password
    insertInStore username hashedPassword

validatePassword username password = do
    hashInStore &lt;- lookupInStore username
    case hashInStore of
      Just h  -&gt; validateHash password h
      Nothing -&gt; return False   -- user not found
</code></pre>

<p>The spec is straightforward. To add a user, you hash the password and insert the username and the hash to some
kind of storage. To validate a password, you first retrieve the hash for the user and then validate that the given
password matches the hash.</p>

<p>Of course, this is not real Haskell code and won&#8217;t even compile if you try to. We haven&#8217;t specified how to generate a
hash from a password or how to store and retrieve the data. But the intention is to specify the high-level idea and
leave the lower level details for later implementation.</p>

<p>But what if I told you that you can use this spec (with very minor tweaks) as your <em>real</em> application code? That&#8217;d be
very handy! After all, the spec is very concise and makes it so easy to convey ideas with others. Adding implementation
details will clutter it up.</p>

<p>Polysemy lets you use such clutter-free code as your real implementation. We will see how that is done very soon. But
first, let us set up a project.</p>

<h2 id="settingupaproject">Setting up a project</h2>

<p>Polysemy is not present in a stackage LTS snapshot at the time of writing this. So I use:</p>

<pre><code class="language-shell">$ stack new polysemy-password-manager --resolver nightly-2019-07-27
</code></pre>

<p>Polysemy recommends <a href="https://github.com/polysemy-research/polysemy/blob/f2ca91d57d02f8668d0204ec994a717b206e7575/README.md#necessary-language-extensions">various language extensions and
settings</a>,
Let us enable all that. You can see my configuration
<a href="https://gitlab.com/rkaippully/polysemy-password-manager/blob/part1/package.yaml">here</a>.</p>

<p>The project settings are ready, let us get back to work!</p>

<h2 id="whatareeffects">What are effects?</h2>

<figure>
<img src="/images/effects-everywhere.png" alt="" title="Effects everywhere!" />
</figure>

<p>For our purposes, an effect is anything that is outside the contours of a pure function. Typically, they are modeled as
monads. For example, you might have optional values (Maybe), short-circuiting on errors (Either), read-only environment
(Reader), logging (Writer), etc. While all these monads are useful, you almost always want to use more than one of them
in your programs. For example, I want to read a configuration file and pass it as a read-only environment to my
application code (aka Reader) <em>and</em> I want the application to do logging (aka Writer).</p>

<p>Unfortunately, monads do not compose in general. There is no general way to pick any two arbitrary monads and combine
them to produce a composed monad. There are many solutions to this problem. Monad transformers are probably the most
popular one in Haskell community. A composable effects library such as polysemy is another one.</p>

<p>If you examine the spec above, you&#8217;ll notice that it uses two effects. I&#8217;ll call them CryptoHash and KeyValueStore
respectively. The CryptoHash effect handles the makeHash and validateHash operations while the KeyValueStore effect
handles insertInStore and lookupInStore.</p>

<h2 id="thecryptohasheffect">The CryptoHash effect</h2>

<p>Generating a hash from an input is usually a pure function. But a good hashing scheme will also add a randomly generated
salt to avoid <a href="https://en.wikipedia.org/wiki/Rainbow_table">rainbow table attacks</a>. This makes it an effectful
computation.</p>

<p>Let us see how to model this effect in polysemy.</p>

<pre><code class="language-haskell">-- A few type definitions to get started
newtype Username = Username ByteString
newtype Password = Password ByteString
newtype PasswordHash = PasswordHash ByteString

data CryptoHash m a where
  -- | Generates a hash from a password
  MakeHash :: Password -&gt; CryptoHash m PasswordHash
  -- | Check if a password matches a hash
  ValidateHash :: Password -&gt; PasswordHash -&gt; CryptoHash m Bool

makeHash :: Member CryptoHash r =&gt; Password -&gt; Sem r PasswordHash
makeHash x = send (MakeHash x :: CryptoHash (Sem r) PasswordHash)

validateHash :: Member CryptoHash r =&gt; Password -&gt; PasswordHash -&gt; Sem r Bool
validateHash password hash = send (ValidateHash password hash :: CryptoHash (Sem r) Bool)
</code></pre>

<p>There is quite a bit of stuff going on here. Let&#8217;s analyze it line by line.</p>

<p>First, we define a new data type named <code>CryptoHash</code> for our effect as a
<a href="https://downloads.haskell.org/~ghc/8.6.5/docs/html/users_guide/glasgow_exts.html#ghc-flag--XGADTs">GADT</a>. It takes two
type parameters - <code>m</code> and <code>a</code>. The first one <code>m</code> represents a monad and <code>a</code> represents the return value of the
operations. We also have two data constructors <code>MakeHash</code> and <code>ValidateHash</code> that correspond to the operations we had in
the spec.</p>

<p>Note that <code>CryptoHash</code> is not a monad. It is just a regular data type. So we cannot use <code>MakeHash</code> and <code>ValidateHash</code>
directly as monadic values in our code. </p>

<p>This is where the functions <code>makeHash</code> and <code>validateHash</code> come in. They convert a value of type <code>CryptoHash (Sem r) a</code>
to a value of type <code>Sem r a</code> using the <code>send</code> function from polysemy<a href="#fn:1" id="fnref:1" title="see footnote" class="footnote">[1]</a>. <code>Sem r</code> is a monad. So we can use that
value in a monadic style.</p>

<p>You are probably confused now. What exactly is this <code>Sem</code> monad? What does the <code>Member CryptoHash r</code> constraint in the
type signatures mean?</p>

<h2 id="thesemmonad">The Sem monad</h2>

<p>With polysemy, you write all your code in one monad - the <code>Sem</code> monad - regardless of the effects you deal with. The
type parameter <code>r</code> in <code>Sem r a</code> is a type-level list of effects. For example, in our application we could use <code>Sem
[CryptoHash, KeyValueStore k v] a</code> or <code>Sem [KeyValueStore k v, CryptoHash] a</code>. We are only interested to check whether
the <code>CryptoHash</code> effect is present in the list <code>r</code> so that we can make use of it. We don&#8217;t care about its exact position
on the list or whether there are other effects on the list. So instead of specifying a hardcoded list of effects such as
<code>Sem [CryptoHash, KeyValueStore k v] a</code>, we use <code>Member CryptoHash r =&gt; Sem r a</code> to indicate that we have some unknown
list of effects <code>r</code> and we require <code>CryptoHash</code> to be present in that list.</p>

<p>In case you are working with multiple effects you can use the <code>Members</code> constraint to avoid repetition. For example,
<code>Members [CryptoHash, KeyValueStore k v] r =&gt; Sem r a</code> is same as <code>(Member CryptoHash r, Member (KeyValueStore k v) r)
=&gt; Sem r a</code>. It says r is some list of effects and both <code>CryptoHash</code> and <code>KeyValueStore k v</code> effects are present in that
list.</p>

<p><code>Sem</code> monad is defined <a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy.html#t:Sem">here</a> as <code>data
Sem r a</code> and <code>Sem r</code> is a monad. We can use it with the do notation just like any other monad. More importantly, we can
work on multiple effects with just this one monad. Let us see how.</p>

<h2 id="thekeyvaluestoreeffect">The KeyValueStore effect</h2>

<p>The second effect we wanted was <code>KeyValueStore</code>. Unlike <code>CryptoHash</code> we do not have to define it. Polysemy comes with a
standard set of effects in the polysemy package and some additional ones in the polysemy-zoo package. <code>KVStore</code> is one
of them. We can use
<a href="https://hackage.haskell.org/package/polysemy-zoo-0.5.0.1/docs/Polysemy-KVStore.html#v:writeKV"><code>writeKV</code></a> in place of
<code>insertInStore</code> and
<a href="https://hackage.haskell.org/package/polysemy-zoo-0.5.0.1/docs/Polysemy-KVStore.html#v:lookupKV"><code>lookupKV</code></a> in place of
<code>lookupInStore</code>.</p>

<h2 id="writingoperationswithpolysemy">Writing operations with Polysemy</h2>

<p>So here is how we can rewrite the spec into valid Haskell code with polysemy.</p>

<pre><code class="language-haskell">addUser :: Members [CryptoHash, KVStore Username PasswordHash] r
        =&gt; Username
        -&gt; Password
        -&gt; Sem r ()
addUser username password = do
    hashedPassword &lt;- makeHash password
    writeKV username hashedPassword

validatePassword :: Members [CryptoHash, KVStore Username PasswordHash] r
                 =&gt; Username
                 -&gt; Password
                 -&gt; Sem r Bool
validatePassword username password = do
    hashInStore &lt;- lookupKV username
    case hashInStore of
      Just h  -&gt; validateHash password h
      Nothing -&gt; return False
</code></pre>

<p>This is the &#8220;business logic&#8221; of our application. Notice how close it is to the original spec. This is very useful for
analyzing, refactoring, and reasoning about the core of your application in general.</p>

<p><code>Sem</code> monad lets you compose multiple monadic effects in a type-safe manner. <code>Members</code> constraint in the type signature
specifies the effects being used in the code and you can rest assured that the code is not making use of an effect not
mentioned in the constraints.</p>

<p>The implementation details are intentionally kept out of this code. We have not specified where and how we&#8217;ll store the
data because the <code>KVStore</code> effect does not define it. Similarly, we have not chosen the password hashing algorithm
because <code>CryptoHash</code> does not specify one. All such implementation decisions (interpretations in polysemy-speak) can be
done at a later stage. This also allows you to choose different implementations in different contexts. For example, we
may choose to use a database to store the data in a real application. But an in-memory dictionary might be sufficient
for testing the application.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Hopefully, this was a useful introduction of how to use polysemy to build the core parts of an application. I will
explain how to write implementations of effects in the <a href="/blog/posts/2019/07/31/polysemy-is-cool-part-2/index.html">next part</a>
of this series.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>Writing functions such as <code>makeHash</code> and <code>validateHash</code> by hand is tedious. Polysemy has a TemplateHaskell
function <a href="https://hackage.haskell.org/package/polysemy-1.0.0.0/docs/Polysemy.html#v:makeSem">makeSem</a> to
autogenerate them and it is recommended to use it. <a href="#fnref:1" title="return to article" class="reversefootnote">&#160;&#8617;</a></p>
</li>

</ol>
</div>


      </div>
    </content>
</entry>

</feed>
