{"title":"Joe Thomas","link":[{"@attributes":{"href":"https:\/\/jsthomas.github.io\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/jsthomas.github.io\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/jsthomas.github.io\/","updated":"2021-10-20T00:00:00-04:00","entry":[{"title":"What I learned publishing an open source package","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/first-opam-package.html","rel":"alternate"}},"published":"2021-10-20T00:00:00-04:00","updated":"2021-10-20T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-10-20:\/first-opam-package.html","summary":"<p>Today I published my first package on OPAM! You can find <code>tidy_email<\/code>\nand its sub-libraries (<code>tidy_email_mailgun<\/code>, <code>tidy_email_sendgrid<\/code>,\nand <code>tidy_email_smtp<\/code>)\n<a href=\"https:\/\/opam.ocaml.org\/packages\/tidy_email\/tidy_email.0.0.1\/\">here<\/a>. This\nwrapped up a goal I wanted to accomplish while at <a href=\"https:\/\/www.recurse.com\/\">Recurse\nCenter<\/a>: Writing a simple (but useful) OCaml\nlibrary and making it available via <code>opam<\/code>.<\/p>\n<p>I chose this project \u2026<\/p>","content":"<p>Today I published my first package on OPAM! You can find <code>tidy_email<\/code>\nand its sub-libraries (<code>tidy_email_mailgun<\/code>, <code>tidy_email_sendgrid<\/code>,\nand <code>tidy_email_smtp<\/code>)\n<a href=\"https:\/\/opam.ocaml.org\/packages\/tidy_email\/tidy_email.0.0.1\/\">here<\/a>. This\nwrapped up a goal I wanted to accomplish while at <a href=\"https:\/\/www.recurse.com\/\">Recurse\nCenter<\/a>: Writing a simple (but useful) OCaml\nlibrary and making it available via <code>opam<\/code>.<\/p>\n<p>I chose this project for several reasons:<\/p>\n<ol>\n<li>I wanted more experience designing small APIs in OCaml.<\/li>\n<li>I thought releasing a small library would help me understand how\n\"open source maintainer\" work differs from paid closed-source\napplication development.<\/li>\n<li>I wanted to learn more about the mechanics\/process of packaging\n   code for OPAM.<\/li>\n<\/ol>\n<p>The rest of this post explains the process I used and which parts\nworked well. Most of this discussion is applicable to general open\nsource development, but some of the tooling-related points are\nspecific to OCaml.<\/p>\n<h1>Picking a Topic<\/h1>\n<p>When I started my batch at RC, I knew that I wanted to publish\n<em>something<\/em>, but hadn't settled on a topic. Contributing to other\nprojects was a valuable source of ideas. After working on a couple of\nissues for the web framework\n<a href=\"https:\/\/github.com\/aantron\/dream\">Dream<\/a>, I wrote a small <a href=\"https:\/\/jsthomas.github.io\/ocaml-email.html\">blog\npost<\/a> showing how to\nbuild a simple email feature with Mailgun. That started a discussion\nwith other Dream contributors about how to simplify the implementation\nof email features.<\/p>\n<p>After a few more conversations, I decided to write an \"adapter\"\nlibrary that creates a consistent interface across different email\nservices. Instead of having to study Mailgun or Sendgrid's REST API\nand worry about the details of making HTTP requests, you can install\n<code>tidy_email<\/code>, provide your API keys, and use a <code>send<\/code> function that\nconsumes a simple email type. The library also makes switching email\nproviders as simple as changing your credentials.<\/p>\n<p>I intentionally kept the scope of the library very small, since this\nallowed me to complete the project in a short time frame\nwhile learning several new skills\/systems.<\/p>\n<h1>Looking at \"Prior Art\"<\/h1>\n<p>Before I started implementing, I researched existing libraries that\ndealt with email. This took time but paid dividends by helping me to\navoid re-inventing existing functionality. I learned more about\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/\"><code>letters<\/code><\/a>, a library for\nsending email via SMTP and supporting libraries like\n<a href=\"https:\/\/github.com\/mirage\/mrmime\"><code>mrmime<\/code><\/a> for parsing and\ngenerating email. Later, I utilized some of these libraries while\nadding an SMTP option to <code>tidy_email<\/code>.<\/p>\n<p>Investigating other work in the OCaml web development space helped me\nto articulate some of the design goals for my library.  I looked at\nthe web framework\n<a href=\"https:\/\/github.com\/oxidizing\/sihl\/tree\/master\/sihl-email\">sihl<\/a>,\nwhich has email among it's many capabilities, and realized I wanted to\nmake a very \"slim\" library that didn't couple sending email with other\ndependencies related to SQL, HTTP, etc.<\/p>\n<h1>Picking a Name<\/h1>\n<p>Naming things is hard! I spent some time looking through OPAM to see\nwhich names were already taken (<code>emile<\/code>, <code>letters<\/code>). Ultimately, I\ndecided on these constraints:<\/p>\n<ul>\n<li>The name needed to be short, easy to search and remember.<\/li>\n<li>Ideally it would have only simple English words in it.<\/li>\n<li>The name should relate to email in an obvious way.<\/li>\n<\/ul>\n<p>I settled on <code>tidy_email<\/code> based on Dream's description as a \"tidy,\nfeature-complete web framework\". The goal of the library would be to\nprovide a \"tidy\" (i.e. well-designed, beginner-friendly) API for\nsending mail, and hopefully appeal to people who also like Dream.<\/p>\n<p>One mistake I made early on was not sticking to a consistent naming\nscheme; I had <code>tidy-email<\/code>, <code>tidy_email<\/code>, and \"tidy email\" in\ndifferent places. Fortunately, github makes it fairly easy to re-name\na repo if you change your mind later; it will even redirect from the\nold repo name to the new one.<\/p>\n<h1>Writing a First Draft<\/h1>\n<p>Even though <code>tidy_email<\/code> is quite simple. It took me some time to set\nall the resources up.<\/p>\n<p>Before I could get an account with Sendgrid, I had to register a\ndomain and create a simple website. I used AWS for this because I was\nalready familiar with it from past jobs. I also needed to register for\nMailgun and create keys for API and SMTP access. At some point, I had\naccumulated enough credentials that I needed to set up password\nmanagement to stay organized.<\/p>\n<p>Once I had access to services, I was able to write a first draft of\nthe library. This turned out to be harder than I expected! I wasted a\nlot of time over-complicating my code with new concepts I had learned\n(functors and higher order modules). Eventually I came to my senses\nand wrote a much simpler implementation.<\/p>\n<p>I found keeping good notes to be quite helpful in this phase. Later, I\nturned these notes into documentation explaining how to set up mail\nservices and some relevant trade-offs when choosing a service (tl;dr:\nMailgun was the easiest, lowest-commitment way to get started).<\/p>\n<h1>Getting Feedback<\/h1>\n<p>My main advice is: Don't go it alone. Having someone (ideally a more\nexperienced maintainer) review early drafts of work was really\nvaluable for staying on track. This helped me:<\/p>\n<ul>\n<li>Understand how new users would think.<\/li>\n<li>Re-order things to make them easier for first-time users to understand.<\/li>\n<li>Remove confusing or superfluous parts of my API.<\/li>\n<li>Leverage github features I wasn't aware of (actions and secrets).<\/li>\n<\/ul>\n<p>I also found it helpful to attend <a href=\"https:\/\/discuss.ocaml.org\/t\/ocaml-cafe-wed-oct-13-1pm-u-s-central\/8610\">OCaml\nCafe<\/a>\n(this is currently meeting on Zoom). A lecture about <code>dune<\/code> given by\nRudi Grinberg showed me some techniques that made managing multiple\n<code>.opam<\/code> files much easier.<\/p>\n<h1>Testing<\/h1>\n<p>I didn't keep a careful count of my hours but I estimate that more\nthan half were spent writing unit and integration tests. Setting these\nup early made it much easier to iterate on my design and accept pull\nrequests. Github actions were pretty straightforward to configure\n(specified with a simple YAML\n<a href=\"https:\/\/github.com\/jsthomas\/tidy_email\/blob\/main\/.github\/workflows\/test.yml\">file<\/a>)\nafter looking at a few examples. I appreciated not having to sign up\nfor yet another service in order to get a simple CI system working.<\/p>\n<p>In <code>tidy_email<\/code>, an \"integration test\" is just a small executable that\ntries to send an email to a mailbox. I used github secrets to add API\nkeys to my project so that integration tests could run securely on an\nPR\/merge that I made. It would've been nice to be able to run\nintegration tests on outside PRs automatically, but there isn't really\na way to do that securely.<\/p>\n<p>Integration tests ended up being very advantageous for shaking out\nproblems that new users are likely to encounter. For example, by\ntesting with (intentionally) invalid SMTP credentials, I\n<a href=\"https:\/\/jsthomas.github.io\/smtp-debugging.html\">learned<\/a> that Mailgun\ncan terminate SMTP connections in a way that is hard for <code>colombe<\/code> to\nhandle. Debugging this example gave me some valuable experience\ndigging into <code>tidy_email<\/code>'s dependencies and helped me file a good bug\nreport to help improve <code>colombe<\/code>.<\/p>\n<h1>Documentation<\/h1>\n<p>I spent more time than expected writing documentation. The main lesson\nI learned is: <em>Don't bury the lede.<\/em> When people look at your repo,\nthey have limited time. Therefore, the first things you should show\nthem are<\/p>\n<ol>\n<li>A simple, one sentence summary of what the library does.<\/li>\n<li>A minimal working example (code) illustrating the library in action.<\/li>\n<\/ol>\n<p>Everything that comes after this introduction should be in the service\nof getting the user set up as painlessly as possible. In my case, that\nmeant adding sign-up links to the relevant services the library\nsupports. I also provided a brief explanation of the trade-offs when\nchoosing a service.<\/p>\n<p><code>tidy_email<\/code> is small enough that I didn't write documentation beyond\na readme, comments in the code, and folders of working examples. I\nthink for a project any larger than this, I would have had to invest\nsome time thinking about how to generate and host a static site with\ndocumentation (e.g. ReadTheDocs).<\/p>\n<h1>Release<\/h1>\n<p>Publishing my code on <a href=\"https:\/\/opam.ocaml.org\/\">opam<\/a> was relatively\npainless. To sum up the process:<\/p>\n<ol>\n<li>I ran <code>dune build<\/code> one final time and verified my opam files were\n   up to date.<\/li>\n<li>I created a \"tag\" for my project (<code>git tag -a 0.0.1 &amp;&amp; git push origin 0.0.1<\/code>).<\/li>\n<li>I ran \"opam publish\", which created a <a href=\"https:\/\/github.com\/ocaml\/opam-repository\/pull\/19816\">pull\n   request<\/a> on\n   <code>ocaml\/opam-repository<\/code>.<\/li>\n<li>~12 hours later my PR passed CI and was approved.<\/li>\n<li>About 6 hours after that, my PR was merged and showed up on <code>opam<\/code>.<\/li>\n<\/ol>\n<p>My <a href=\"https:\/\/github.com\/ocaml\/opam-repository\/pull\/19634\">first\nattempt<\/a> at\npublishing didn't pass CI because of some simple mistakes I made in my\n<code>.opam<\/code> files. Fixing these was relatively straightforward after\nreading the docs and looking at some other repos for reference.<\/p>\n<h1>Final Thoughts<\/h1>\n<p>None of the work involved with releasing <code>tidy_email<\/code> was especially\n<em>hard<\/em>, but there were <em>many<\/em> small tasks to understand. Compared to\npaid application development work, I found that this project had more\n\"admin work\": signing up for services, configuring things, and writing\nprose.<\/p>\n<p>Overall, I found this type of work quite rewarding. It has been fun to\nsee new people discover and star the repo on Github. The project\nmotivated me to learn aspects of email that I would not have otherwise\nexplored. Given how much open source software I use, it feels great\nto make a small contribution to the community.<\/p>","category":{"@attributes":{"term":"OSS, Projects"}}},{"title":"Writing a Simple Browser Game in Elm","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/elm-space-battle.html","rel":"alternate"}},"published":"2021-09-03T00:00:00-04:00","updated":"2021-09-03T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-09-03:\/elm-space-battle.html","summary":"<p>A user experience report from a first time Elm user<\/p>","content":"<p>TL;DR : This week I built a little spaceship game using Elm! You can\nplay the game <a href=\"https:\/\/jsthomas.github.io\/static\/elm-space-battle\/index.html\">here<\/a> (it\nprobably won't work well on mobile or if you have a tiny screen) and\nsee the source code\n<a href=\"https:\/\/github.com\/jsthomas\/elm-space-battle\">here<\/a>.<\/p>\n<p><em>Here's a screenshot:<\/em><\/p>\n<p><img alt=\"A screenshot of my\ngame.\" src=\"https:\/\/jsthomas.github.io\/images\/elm-space-battle\/game_small.png\"><\/p>\n<h1>Context<\/h1>\n<p>This was my last week at Recurse Center; after Labor Day, I head back\nto full time work as a data engineer. One of my main RC projects,\n<a href=\"https:\/\/github.com\/jsthomas\/tidy-email\">tidy-email<\/a>, is waiting on\nsome upstream changes on OPAM before it can be released. In light of\nall this, I decided to work on a short term project this week, and\nlearn a bit of <a href=\"https:\/\/elm-lang.org\/\">Elm<\/a>.<\/p>\n<p>My reasons for learning Elm are twofold. First, I think this\ntechnology is a great example of how to make strongly typed functional\nprogramming accessible to a wider audience. It's worth studying just\nfor the sake of examining how ideas are presented, because I can\nre-use those skills to build user-friendly OCaml projects. Second, the\n\"Elm Architecture\" is widely used in front-end programming and I'd\nlike to fill in some of the gaps in my front-end skill-set.<\/p>\n<h1>Defining the Project<\/h1>\n<p>I wanted this week's project to be small in scope and entertaining, so\nI decided to build a game similar to the 1962 game <em>Spacewar!<\/em>,\nwritten for the PDP-1 at MIT. You can read more about this game\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Spacewar!\">here<\/a> and play an emulated\nversion <a href=\"https:\/\/www.masswerk.at\/spacewar\/\">here<\/a>.<\/p>\n<p><img alt=\"The original spacewar on a DEC\nmonitor.\" src=\"https:\/\/jsthomas.github.io\/images\/elm-space-battle\/Spacewar_screenshot_small.png\"><\/p>\n<p><em>Spacewar!<\/em> features two rocket ships orbiting a star; the objective\nis to destroy the other player's ship by shooting it with a\ntorpedo. The star exerts a gravitational pull on the two rockets,\nwhich complicates the ship's trajectories. A player that gets too\nclose to the star loses. Player's that fly off the screen reappear on\nthe opposite side, just like in Asteroids.<\/p>\n<p>After playing with <em>Spacewar!<\/em> for a bit, I decided on the following\nrules for my game:<\/p>\n<ul>\n<li>The game should be single player instead of two player, with simple\n  AI opponents.<\/li>\n<li>The player's should have a finite number of torpedoes, which\n  replenish as they are used.<\/li>\n<li>The AI opponents should be able to shoot their own torpedoes at the\n  player.<\/li>\n<li>Both the player and torpedoes should be influenced by gravity.<\/li>\n<li>There should be a display at the top of the screen tracking how many\n  torpedoes the player has left and how many enemies they need to\n  destroy.<\/li>\n<li>The player can lose by colliding with the sun, a torpedo, or an\n  enemy.<\/li>\n<\/ul>\n<h1>Getting set up with Elm<\/h1>\n<p>I was quite impressed with how simple it was to get set up with\n<code>elm<\/code>. There is a single executable that handles compiling Elm source\nfiles, downloading dependencies from the internet, and serving an Elm\n<code>repl<\/code>.<\/p>\n<p>I read <a href=\"https:\/\/elmprogramming.com\/\">Beginning Elm<\/a> to get a feel for\nthe language. If you're coming to Elm from another strongly typed\nlanguage like OCaml or Haskell, this guide is a pretty fast read. I\nappreciated that it provided chapters on the Elm architecture and how\nto make requests against a JSON API, so that I could jump right to\nthose topics and start learning what I wanted to know.<\/p>\n<p>I also found the online code editor\n<a href=\"https:\/\/ellie-app.com\/62Dy7vxsBHZa1\">Ellie<\/a> quite helpful for running\nlittle experiments without installing anything, especially as I wanted\nto learn more about the elm-canvas library.<\/p>\n<p>The main Elm documentation\n<a href=\"https:\/\/package.elm-lang.org\/packages\/joakin\/elm-canvas\/4.3.0\/\">page<\/a>\nprovided a concise overview of the graphics package I wanted to\nuse. Overall, I was quite happy with the quality of the documentation,\nthough I did encounter a number of dead links on stack overflow.<\/p>\n<p>I used VSCode with the <code>Elm<\/code> extension for my development work. This\nwas straightforward to install. Syntax and error highlighting worked\nfine. I found the error highlighter to be quite aggressive. Part way\nthrough adding a new function definition, the highlighter would mark\nthe entire source file as a single error, which was distracting. I\ndidn't bother to get live-reloading working because the project was so\nsmall, but this would've been nice to have.<\/p>\n<h1>Thoughts on the Elm Architecture<\/h1>\n<p>The Elm Architecture is worth expanding on a bit, and is summed up by\nthe following diagram in <em>Beginning Elm<\/em>:<\/p>\n<p><img alt=\"Elm architecture diagram\" src=\"https:\/\/jsthomas.github.io\/images\/elm-space-battle\/elm-arch.png\"><\/p>\n<p>The Elm runtime is responsible for handling all side-effects, so that\nElm programmers only need to work with pure functions and immutable\ndata. To define the application, we provide the runtime with a handful\nof important definitions:<\/p>\n<ul>\n<li>A model that defines the state of the game at a moment in time.<\/li>\n<li>An initial model state, to be used when the app loads.<\/li>\n<li>A view function, that explains how to render the model in the browser.<\/li>\n<li>An update rule, that explains how to transform one model into\n  another model based on inputs from the runtime.<\/li>\n<li>Finally, any subscriptions the app needs. In my case, the app\n  subscribes to events from the keyboard and events from a timer, and\n  these events dictate how to update the model.<\/li>\n<\/ul>\n<p>I found that separating effectful code from pure code was very\nconvenient. It greatly simplified reasoning about my game logic. I\nfound that it natural to express different \"game rules\" in terms of\ntransformations on the <code>Model<\/code>, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">removeOldTorpedos<\/span> <span class=\"nf\">:<\/span> <span class=\"kt\">Model<\/span> <span class=\"nf\">-&gt;<\/span> <span class=\"kt\">Model<\/span>\n<span class=\"nv\">removeOldTorpedos<\/span> <span class=\"nv\">model<\/span> <span class=\"nf\">=<\/span>\n    <span class=\"kr\">let<\/span> <span class=\"nv\">torpedoLifetime<\/span> <span class=\"nf\">=<\/span> <span class=\"mi\">60<\/span> <span class=\"nf\">*<\/span> <span class=\"mi\">2<\/span> <span class=\"kr\">in<\/span>  <span class=\"c1\">-- ~ 2 seconds<\/span>\n    <span class=\"kr\">let<\/span> <span class=\"nv\">isLive<\/span> <span class=\"nv\">b<\/span> <span class=\"nf\">=<\/span> <span class=\"nv\">model<\/span><span class=\"nf\">.<\/span><span class=\"nv\">time<\/span> <span class=\"nf\">-<\/span> <span class=\"nv\">b<\/span><span class=\"nf\">.<\/span><span class=\"nv\">created<\/span> <span class=\"nf\">&lt;<\/span> <span class=\"nv\">torpedoLifetime<\/span> <span class=\"kr\">in<\/span>\n    <span class=\"p\">{<\/span><span class=\"nv\">model<\/span> <span class=\"nf\">|<\/span> <span class=\"nv\">torpedos<\/span> <span class=\"nf\">=<\/span> <span class=\"kt\">List<\/span><span class=\"nf\">.<\/span><span class=\"nv\">filter<\/span> <span class=\"nv\">isLive<\/span> <span class=\"nv\">model<\/span><span class=\"nf\">.<\/span><span class=\"nv\">torpedos<\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h1>Developer Experience<\/h1>\n<p>Building a game in Elm was quite pleasant. The compiler's error\nmessages are easy to interpret and the type system enables aggressive\nrefactoring that would have been difficult for me to do in\nJavaScript. I found it quite easy to evolve my design as I worked and\nI didn't need to refer back to <em>Beginning Elm<\/em> or the documentation\nvery often.<\/p>\n<p>Overall I found Elm much easier to understand than rescript. I think\nthis was in part because there are better-established conventions\nabout how to build with Elm, and rescript is newer. I also found Elm's\nsyntax easier to understand coming from OCaml than the JS\/OCaml hybrid\nsyntax in rescript.<\/p>\n<p>I started the project with a very simple goal: Display a static scene\nwith a background of stars, a yellow sun at the center, and two space\nships. From there, I started to add simple physics, the ability to\nrespond to keyboard events, and a simple collision detection\nsystem.<\/p>\n<p>I really enjoyed how the compiler enabled me to explore \"what-if\"\nscenarios, like \"What if I wanted to make the torpedoes change colors\nover time?\". I found myself working in this cycle:<\/p>\n<ul>\n<li>Ask a what-if question.<\/li>\n<li>Change the data model to support that question.<\/li>\n<li>Fix the errors identified by the compiler.<\/li>\n<li>Compile.<\/li>\n<li>Try the game and reflect on whether it was more fun.<\/li>\n<\/ul>\n<p>This tight development loop allowed me to spend most of my time\n\"discovering\" the right definitions for my game rather than fighting\nwith confusing JavaScript bugs. Once I had a canvas and keyboard\ninputs working (which required a bit of research), the game came\ntogether quite quickly.<\/p>\n<h1>Conclusion<\/h1>\n<p>Fundamentally, I think Elm was easy to start using for two reasons:<\/p>\n<ul>\n<li>It cleanly separates pure computations from ones with side effects,\n  via the Elm Architecture.<\/li>\n<li>The Elm team spent time making the tools easy to use and created\n  well-written tutorials explaining the language.<\/li>\n<\/ul>\n<p>This is definitely a tool I'd consider using for future front-end work\nand I'd recommend it to other developers who are interested in\nexploring strongly typed functional programming for the first time.<\/p>\n<h1>Feedback<\/h1>\n<p>If you found this post useful (or conversely, think that the advice\nhere is bad), send me an email. My contact information is listed on\nthe <a href=\"\/\">About<\/a> page.<\/p>","category":{"@attributes":{"term":"FP, Elm"}}},{"title":"Things I learned at ICFP 2021","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/icfp-2021.html","rel":"alternate"}},"published":"2021-08-30T00:00:00-04:00","updated":"2021-08-30T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-08-30:\/icfp-2021.html","summary":"<p>A summary of the sessions I attended at ICFP 2021<\/p>","content":"<p>Last week I attended ICFP for the first time. Due to the pandemic, the\nconference was entirely online. This made it really easy and\ninexpensive to attend (were it in person, I would've had to fly to\nKorea), but also made it harder to meet people and benefit from \"the\nhallway track\".<\/p>\n<p>Despite the circumstances, there were a number of interesting\nsessions. Below is a summary of some of the projects I learned about\nat the conference. Some caveats:<\/p>\n<ul>\n<li>\n<p>ICFP has a lot of parallel tracks. I was focused primarily on ML and\n  OCaml sessions, so I'm sure there were interesting talks that I\n  missed.<\/p>\n<\/li>\n<li>\n<p>I missed some talks due to timezone issues.<\/p>\n<\/li>\n<li>\n<p>I'm approaching the conference as someone who primarily works on the\n  backend of analytics applications, so I wasn't as interested in new\n  results about PL theory.<\/p>\n<\/li>\n<\/ul>\n<p>I think conferences are a great way to hear about new technologies,\nbut for depth you have to study on your own afterwards. As such, this\npost is a bit of a \"listicle\" capturing topics I might want to\ninvestigate later.<\/p>\n<h1>Keynote<\/h1>\n<p>Ravi Chugh gave an interesting keynote about how programming language\ntechniques can be applied to human-computer interaction problems. He\ndemonstrated a 2D graphics editor called Sketch-n-sketch where the\nuser could create an image using a GUI or a programming language, and\nsynchronize between the two.<\/p>\n<p>Before this session, I didn't realize how much research has been done\ninto applying FP\/PL techniques to human\/computer interfaces. It would\nbe interesting to apply similar techniques to a 3D animation system\nlike Blender. When I used to work on animation (long, long ago), I\nwanted GUI capabilities for building individual models in a scene but\nwould have preferred a programming language when rigging characters or\nautomating certain motions. Debugging GUI-based automation was\nno fun at all.<\/p>\n<h1>Historical Talks<\/h1>\n<p>Don Syme gave a talk about the history of F#. This covered the\noriginal motivation for the language, it's interactions with the C#\ncommunity, and the impact of Object Orient Programming's popularity on\nPL research. Xavier Leroy gave a presentation about the history of\nOCaml (this year was the language's 25th anniversary), and also\ncommented on the impact of OO. It was interesting to hear about how\nOCaml was used for teaching programming in Universities and how this\nlanguage related to research in automated theorem proving.<\/p>\n<h1>Research and Industry Talks<\/h1>\n<p>Marten Agren gave a talk about how Standard Chartered uses a strict\nversion of Haskell for their work, and how FP is especially suited to\nscalable inter-operation with spreadsheets. Before this talk, I didn't\nknow that some people use Haskell without lazy evaluation.<\/p>\n<p>Denis Merigoux gave a <a href=\"https:\/\/youtu.be\/jmHwAh_-IOU\">presentation<\/a>\nabout a new DSL called <a href=\"https:\/\/github.com\/CatalaLang\">Catala<\/a> that\nmakes it possible to model laws (e.g. tax law) with code. The compiler\nfor the language is written in OCaml. Naturally, the correctness of\nthese types of systems is quite important; errors mean that essential\nsocial services aren't delivered (e.g. paychecks for government\nworkers). It's interesting to think about other areas where this work\ncould be applied beyond tax law. For example, most utility costs are\nalso a matter of public record and having an open, formally verified\nsystem for calculating those costs would help ensure rate payers are\nbilled fairly.<\/p>\n<h2>Talks about tooling and libraries<\/h2>\n<p>The OCaml workshop featured several exciting talks about improvements\nto the OCaml ecosystem.<\/p>\n<p>Laurent Mazare spoke about how Jane Street makes OCaml libraries\naccessible from within python, with a special focus on Jupyter\nnotebooks. As someone who has worked supporting data scientists in the\npast, this seems like a great way to get the benefits of the Python\ndata science ecosystem while building primarily in a strongly typed\nlanguage. I'm not sure what this work means for projects like Owl that\ntry to provide a similar feature set as Numpy\/SciPy\/Pandas in OCaml.<\/p>\n<p>Di Long Li and Gabriel Radanne presented a new library called\n<a href=\"https:\/\/github.com\/daypack-dev\/timere\"><code>timere<\/code><\/a> that makes it easier\nto work with dates and times. The library simplifies solving\nrecurrence-rule problems like \"tell me which Christmases fall on a\nWednesday from now on\". I think this is a great development,\nespecially if you're building an application that works with time\nseries data from a business domain. Gabriel Radanne also presented\n<a href=\"https:\/\/github.com\/Drup\/dowsing\"><code>dowsing<\/code><\/a> a tool that allows the\nuser to search OCaml codebases using a type signature. This is a bit\nlike <a href=\"https:\/\/hoogle.haskell.org\/\">hoogle<\/a>, but the underlying\ntechniques used to enable search are quite different.<\/p>\n<p>Thomas Leonard gave an impressive talk about applying the new effect\nsystem in multicore OCaml to the <code>angstrom<\/code> library, demonstrating\nperformance on par with Rust. I think it will be exciting to start\nusing effects as they become available in the next year or two.<\/p>\n<p>Two different teams discussed their efforts to improve the state of\nOCaml documentation, so that a site similar to\n<a href=\"https:\/\/hackage.haskell.org\/\">hackage<\/a> could be generated directly\nfrom OPAM. This seems like a great way to lower one of the barriers to\nentry for maintainers and make OCaml documentation more consistent.<\/p>\n<p>Gargi Sharma presented work that a team at Tarides is doing on\n<a href=\"https:\/\/github.com\/ocurrent\/current-bench\"><code>current-bench<\/code><\/a>, a system\nfor analyzing benchmarking data that integrates with OCaml CI\nsystems. Using their tools, one can track trends in benchmark data\nover time and identify builds that improved or degraded\nperformance. This system also provides a nice example of how to build\nan analytics app using FP techniques. They use <code>rescript<\/code> for their\nfrontend, <code>hasura<\/code> to serve analytics results via GraphQL, and an\nOCaml program for ingesting performance data into their database.<\/p>\n<h1>Takeaways<\/h1>\n<p>There was a lot of focus on \"ecosystem tooling\" at the OCaml workshop\nand considerable excitement about the upcoming release of multicore\nOCaml. I didn't hear much about work on the frontend (ReasonML,\nBucklescript, Rescript) or updates about applications of OCaml to\nstatistics\/numerical computing. Possibly this was just a function of\nthe unusual pandemic environment or the nature of a conference with a\nmore academic focus. In any case, I'm excited to dive into some of\nthese new tools, and especially to start getting the benefits of\nimproved documentation and search capabilities for OCaml libraries.<\/p>","category":{"@attributes":{"term":"FP, ICFP"}}},{"title":"Debugging an SMTP Integration in OCaml","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/smtp-debugging.html","rel":"alternate"}},"published":"2021-08-25T00:00:00-04:00","updated":"2021-08-25T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-08-25:\/smtp-debugging.html","summary":"<p>Things I learned while fixing some SMTP problems.<\/p>","content":"<p>For the last few weeks I've been working on a side project to create a\nsmall library called\n<a href=\"https:\/\/github.com\/jsthomas\/tidy-email\"><code>tidy_email<\/code><\/a> that makes it\neasier to send email in OCaml. The repository has some example\nprograms illustrating how to connect to different email services. I\nwanted to make sure that these programs would fail gracefully if\nconfigured with the wrong credentials. But when I ran my example <a href=\"https:\/\/github.com\/jsthomas\/tidy-email\/blob\/main\/smtp\/example\/send.ml\">SMTP\napp<\/a>\nwith an invalid password, I saw this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Send<\/span> <span class=\"nv\">failed<\/span>. <span class=\"nv\">Details<\/span>: <span class=\"nv\">Error<\/span>: <span class=\"nv\">Stack<\/span> <span class=\"nv\">overflow<\/span>\n<\/code><\/pre><\/div>\n\n<p>I expected to see some sort of \"not authorized\" message. Why was\nthis happening? This post summarizes how I debugged this problem.<\/p>\n<h2>Context<\/h2>\n<p>Among email services (like Mailgun, Sendgrid, and Amazon SES) there\nare typically two ways for a web application to send email: make a\nrequest to a REST API or use\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Simple_Mail_Transfer_Protocol\">SMTP<\/a>. REST\nAPIs are convenient because they expose more features. In particular,\nwhen you provide malformed data, the API can respond with a detailed\nexplanation of what the application did incorrectly. On the other\nhand, SMTP is advantageous if you already have a mail server, want to\nintegrate with a legacy system, or can't be bothered to write a custom\nREST API integration.<\/p>\n<p><code>tidy_email<\/code> provides a simple wrapper around other libraries that\nhandle HTTP requests and\/or SMTP. For SMTP, it uses\n<a href=\"https:\/\/github.com\/oxidizing\/letters\"><code>letters<\/code><\/a>, which in turn\ndepends on a library called\n<a href=\"https:\/\/github.com\/mirage\/colombe\/\"><code>colombe<\/code><\/a>. At a high level, what\nI wanted to understand was why <code>letters<\/code> was experiencing a stack\noverflow when provided with bad SMTP credentials.<\/p>\n<p>The specific SMTP server I was testing against was provided by\nMailgun. I had previously had some\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/issues\/35\">difficulties<\/a> with\nthis server; these came about because Mailgun's implementation doesn't\nstrictly adhere to the relevant RFCs, and I thought something similar\nmight be occurring here.<\/p>\n<h2>Gathering Data<\/h2>\n<p>I started by cloning the <code>letters<\/code> and <code>colombe<\/code> repositories from\ngithub. Fortunately, I already had\n<a href=\"https:\/\/github.com\/ocaml\/merlin\/wiki\/emacs-from-scratch#configuring-your-project\"><code>merlin<\/code><\/a>\ninstalled for Emacs. This gave me the ability to jump from a function\ncall in my source code to the function's definition (<code>C-c l<\/code>). It also\nallowed me to quickly look up types (<code>C-c t<\/code>). These hotkeys were\ninvaluable for efficiently working with unfamiliar code.<\/p>\n<p>Before I started digging into the source code, I tried running\n<code>strace<\/code> on my test app. This tool produces a log of all system calls\nmade by the app under test. This results in a <em>lot<\/em> of output; here is\nan excerpt of what I saw:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;220 Mailgun Influx ready\\r\\n&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">26<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a92d460<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">           <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">EAGAIN<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Resource<\/span><span class=\"w\"> <\/span><span class=\"n\">temporarily<\/span><span class=\"w\"> <\/span><span class=\"n\">unavailable<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"k\">write<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;EHLO glenmeretechnologies.com\\r\\n&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">31<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">31<\/span><span class=\"w\"><\/span>\n<span class=\"n\">getpid<\/span><span class=\"p\">()<\/span><span class=\"w\">                                <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">15565<\/span><span class=\"w\"><\/span>\n<span class=\"n\">epoll_wait<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">{EPOLLIN, {u32=5, u64=8589934597}}<\/span><span class=\"o\">]<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">9879<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;250-smtp-out-n02.prod.us-west-2.&quot;<\/span><span class=\"p\">...,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">144<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a92d460<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">           <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">EAGAIN<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Resource<\/span><span class=\"w\"> <\/span><span class=\"n\">temporarily<\/span><span class=\"w\"> <\/span><span class=\"n\">unavailable<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"k\">write<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;STARTTLS\\r\\n&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">)<\/span><span class=\"w\">            <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"w\"><\/span>\n<span class=\"n\">getpid<\/span><span class=\"p\">()<\/span><span class=\"w\">                                <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">15565<\/span><span class=\"w\"><\/span>\n<span class=\"n\">epoll_wait<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">{EPOLLIN, {u32=5, u64=8589934597}}<\/span><span class=\"o\">]<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">9840<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;220 Go ahead\\r\\n&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">       <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">14<\/span><span class=\"w\"><\/span>\n<span class=\"n\">brk<\/span><span class=\"p\">(<\/span><span class=\"mh\">0x56132a954000<\/span><span class=\"p\">)<\/span><span class=\"w\">                     <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a954000<\/span><span class=\"w\"><\/span>\n<span class=\"n\">brk<\/span><span class=\"p\">(<\/span><span class=\"mh\">0x56132a975000<\/span><span class=\"p\">)<\/span><span class=\"w\">                     <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a975000<\/span><span class=\"w\"><\/span>\n<span class=\"n\">brk<\/span><span class=\"p\">(<\/span><span class=\"mh\">0x56132a996000<\/span><span class=\"p\">)<\/span><span class=\"w\">                     <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a996000<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a92d460<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">           <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">EAGAIN<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Resource<\/span><span class=\"w\"> <\/span><span class=\"n\">temporarily<\/span><span class=\"w\"> <\/span><span class=\"n\">unavailable<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"k\">write<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;\\26\\3\\3\\2\\0\\1\\0\\1\\374\\3\\0033y\\374\\354\\246\\200\\2749u\\7\\375P\\226\\273\\37\\342|\\257\\235\\277h&quot;<\/span><span class=\"p\">...,<\/span><span class=\"w\"> <\/span><span class=\"mi\">517<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">517<\/span><span class=\"w\"><\/span>\n<span class=\"n\">getpid<\/span><span class=\"p\">()<\/span><span class=\"w\">                                <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">15565<\/span><span class=\"w\"><\/span>\n<span class=\"n\">epoll_wait<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">{EPOLLIN, {u32=5, u64=8589934597}}<\/span><span class=\"o\">]<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">9796<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;\\26\\3\\3\\0Z\\2\\0\\0V\\3\\3\\22c1v\\234\\367\\0\\322fR\\230\\264\\236;\\314\\f\\23\\234$\\245\\33&quot;<\/span><span class=\"p\">...,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">3389<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mh\">0x56132a92d460<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">           <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">EAGAIN<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Resource<\/span><span class=\"w\"> <\/span><span class=\"n\">temporarily<\/span><span class=\"w\"> <\/span><span class=\"n\">unavailable<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<span class=\"k\">read<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">4096<\/span><span class=\"p\">)<\/span><span class=\"w\">                       <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"w\"><\/span>\n<span class=\"p\">(<\/span><span class=\"k\">last<\/span><span class=\"w\"> <\/span><span class=\"n\">line<\/span><span class=\"w\"> <\/span><span class=\"n\">repeats<\/span><span class=\"w\"> <\/span><span class=\"n\">hundreds<\/span><span class=\"w\"> <\/span><span class=\"k\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">times<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<\/code><\/pre><\/div>\n\n<p>From this output, I was able to glean a couple of things:<\/p>\n<ol>\n<li>\n<p>My app is successfully connecting to <code>smtp.mailgun.org<\/code>, as\n   evidenced by the <code>220 Go ahead<\/code> message.<\/p>\n<\/li>\n<li>\n<p>The hundreds of <code>read<\/code> calls seem related to the stack overflow\n   issue. They suggest some sort of infinite loop or that the app is\n   trying to read data that isn't available for some reason.<\/p>\n<\/li>\n<\/ol>\n<h2>Getting more information about SMTP<\/h2>\n<p>At this point, I decided I needed to learn a little bit about how SMTP\nworks. Fortunately, wikipedia provides a fairly concise\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Simple_Mail_Transfer_Protocol\">overview<\/a>\nwith an example of a successful SMTP session (<code>S<\/code> = Server, <code>C<\/code> = Client):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">220<\/span> <span class=\"n\">smtp<\/span><span class=\"o\">.<\/span><span class=\"na\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span> <span class=\"n\">ESMTP<\/span> <span class=\"n\">Postfix<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">HELO<\/span> <span class=\"n\">relay<\/span><span class=\"o\">.<\/span><span class=\"na\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">250<\/span> <span class=\"n\">smtp<\/span><span class=\"o\">.<\/span><span class=\"na\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">,<\/span> <span class=\"n\">I<\/span> <span class=\"n\">am<\/span> <span class=\"n\">glad<\/span> <span class=\"n\">to<\/span> <span class=\"n\">meet<\/span> <span class=\"n\">you<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">MAIL<\/span> <span class=\"n\">FROM<\/span><span class=\"o\">:&lt;<\/span><span class=\"n\">bob<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">250<\/span> <span class=\"n\">Ok<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">RCPT<\/span> <span class=\"n\">TO<\/span><span class=\"o\">:&lt;<\/span><span class=\"n\">alice<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">250<\/span> <span class=\"n\">Ok<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">RCPT<\/span> <span class=\"n\">TO<\/span><span class=\"o\">:&lt;<\/span><span class=\"n\">theboss<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">250<\/span> <span class=\"n\">Ok<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">DATA<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">354<\/span> <span class=\"n\">End<\/span> <span class=\"n\">data<\/span> <span class=\"k\">with<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">CR<\/span><span class=\"o\">&gt;&lt;<\/span><span class=\"n\">LF<\/span><span class=\"o\">&gt;.&lt;<\/span><span class=\"n\">CR<\/span><span class=\"o\">&gt;&lt;<\/span><span class=\"n\">LF<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">From<\/span><span class=\"o\">:<\/span> <span class=\"s2\">&quot;Bob Example&quot;<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">bob<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">To<\/span><span class=\"o\">:<\/span> <span class=\"n\">Alice<\/span> <span class=\"n\">Example<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">alice<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Cc<\/span><span class=\"o\">:<\/span> <span class=\"n\">theboss<\/span><span class=\"err\">@<\/span><span class=\"n\">example<\/span><span class=\"o\">.<\/span><span class=\"na\">com<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Date<\/span><span class=\"o\">:<\/span> <span class=\"n\">Tue<\/span><span class=\"o\">,<\/span> <span class=\"mi\">15<\/span> <span class=\"n\">Jan<\/span> <span class=\"mi\">2008<\/span> <span class=\"mi\">16<\/span><span class=\"o\">:<\/span><span class=\"mi\">02<\/span><span class=\"o\">:<\/span><span class=\"mi\">43<\/span> <span class=\"o\">-<\/span><span class=\"mi\">0500<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Subject<\/span><span class=\"o\">:<\/span> <span class=\"n\">Test<\/span> <span class=\"n\">message<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Hello<\/span> <span class=\"n\">Alice<\/span><span class=\"o\">.<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">This<\/span> <span class=\"k\">is<\/span> <span class=\"n\">a<\/span> <span class=\"n\">test<\/span> <span class=\"n\">message<\/span> <span class=\"k\">with<\/span> <span class=\"mi\">5<\/span> <span class=\"n\">header<\/span> <span class=\"n\">fields<\/span> <span class=\"n\">and<\/span> <span class=\"mi\">4<\/span> <span class=\"n\">lines<\/span> <span class=\"k\">in<\/span> <span class=\"n\">the<\/span> <span class=\"n\">message<\/span> <span class=\"n\">body<\/span><span class=\"o\">.<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Your<\/span> <span class=\"n\">friend<\/span><span class=\"o\">,<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">Bob<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"o\">.<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">250<\/span> <span class=\"n\">Ok<\/span><span class=\"o\">:<\/span> <span class=\"n\">queued<\/span> <span class=\"k\">as<\/span> <span class=\"mi\">12345<\/span>\n<span class=\"n\">C<\/span><span class=\"o\">:<\/span> <span class=\"n\">QUIT<\/span>\n<span class=\"n\">S<\/span><span class=\"o\">:<\/span> <span class=\"mi\">221<\/span> <span class=\"n\">Bye<\/span>\n<\/code><\/pre><\/div>\n\n<p>Unfortunately, this excerpt doesn't explain much about how a session\nusing STARTTLS should look. Since I saw some successful <code>read<\/code> calls\nin my strace output, with arguments that weren't readable text, I\ninferred that TLS was probably interfering with my ability to easily\nsee what was going on in the session after the first 220 response.<\/p>\n<h2>Getting more data from logs<\/h2>\n<p>I used <code>merlin<\/code> to jump to the <a href=\"https:\/\/github.com\/mirage\/colombe\/blob\/master\/sendmail\/sendmail_with_starttls.ml\">relevant\nparts<\/a>\nof the <code>colombe<\/code> source code and noticed that <code>colombe<\/code> uses the\n<code>Logs<\/code> module. Adding these two lines at the start of my test app\nallowed me to start collecting log output, and see what was going on\nin <code>colombe<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>  <span class=\"nn\">Logs<\/span><span class=\"p\">.<\/span><span class=\"n\">set_reporter<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Logs<\/span><span class=\"p\">.<\/span><span class=\"n\">format_reporter<\/span> <span class=\"bp\">()<\/span><span class=\"o\">);<\/span>\n  <span class=\"nn\">Logs<\/span><span class=\"p\">.<\/span><span class=\"n\">set_level<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Some<\/span> <span class=\"nn\">Logs<\/span><span class=\"p\">.<\/span><span class=\"nc\">Info<\/span><span class=\"o\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>When I took a look at the log output, I saw:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">Return<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"err\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">220<\/span><span class=\"w\"> <\/span><span class=\"n\">Mailgun<\/span><span class=\"w\"> <\/span><span class=\"n\">Influx<\/span><span class=\"w\"> <\/span><span class=\"n\">ready<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"err\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"n\">smtp<\/span><span class=\"o\">-<\/span><span class=\"k\">out<\/span><span class=\"o\">-<\/span><span class=\"n\">n01<\/span><span class=\"p\">.<\/span><span class=\"n\">prod<\/span><span class=\"p\">.<\/span><span class=\"n\">us<\/span><span class=\"o\">-<\/span><span class=\"n\">west<\/span><span class=\"o\">-<\/span><span class=\"mf\">2.<\/span><span class=\"n\">postgun<\/span><span class=\"p\">.<\/span><span class=\"n\">com<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"n\">AUTH<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAIN<\/span><span class=\"w\"> <\/span><span class=\"n\">LOGIN<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"k\">SIZE<\/span><span class=\"w\"> <\/span><span class=\"mi\">52428800<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"mi\">8<\/span><span class=\"n\">BITMIME<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"n\">SMTPUTF8<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"o\">-<\/span><span class=\"n\">PIPELINING<\/span><span class=\"w\"><\/span>\n<span class=\"mi\">250<\/span><span class=\"w\"> <\/span><span class=\"n\">STARTTLS<\/span><span class=\"w\"><\/span>\n<span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">Return<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"err\">:<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">Return<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">WARNING<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"n\">The<\/span><span class=\"w\"> <\/span><span class=\"n\">server<\/span><span class=\"w\"> <\/span><span class=\"n\">send<\/span><span class=\"w\"> <\/span><span class=\"n\">an<\/span><span class=\"w\"> <\/span><span class=\"n\">invalid<\/span><span class=\"w\"> <\/span><span class=\"n\">base64<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"err\">:<\/span><span class=\"w\"> <\/span><span class=\"ss\">&quot;Go ahead&quot;<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"err\">:<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">Return<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"n\">Response<\/span><span class=\"w\"> <\/span><span class=\"mi\">535<\/span><span class=\"w\"> <\/span><span class=\"n\">Authentication<\/span><span class=\"w\"> <\/span><span class=\"n\">failed<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"n\">Quitting<\/span><span class=\"w\"> <\/span><span class=\"k\">connection<\/span><span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">Before<\/span><span class=\"w\"> <\/span><span class=\"n\">recv<\/span><span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<span class=\"nl\">send<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">INFO<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"err\">:<\/span><span class=\"w\"><\/span>\n<span class=\"p\">(<\/span><span class=\"n\">repeats<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">hundreds<\/span><span class=\"w\"> <\/span><span class=\"k\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">times<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"p\">...<\/span><span class=\"w\"><\/span>\n<\/code><\/pre><\/div>\n\n<p>Similar to the <code>strace<\/code> results, I could see many failed reads. But\nthis time I could see they occurred after a <code>535 Authentication\nfailed<\/code> message came back from the server.<\/p>\n<p>During this phase of analysis it was helpful to be able to add my own\nlog points to the source code. In order to do this, though, I needed\nto ensure that my test app would build against my modified version of\n<code>colombe<\/code>, not the published version on <code>opam<\/code>. Within the <code>colombe<\/code>\nrepo, I ran<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>dune build src <span class=\"o\">&amp;&amp;<\/span> dune install colombe <span class=\"o\">&amp;&amp;<\/span> dune build sendmail <span class=\"o\">&amp;&amp;<\/span> dune install sendmail\n<\/code><\/pre><\/div>\n\n<p>This pinned both <code>colombe<\/code> and <code>sendmail<\/code> to my local versions on\ndisk. Because <code>letters<\/code> uses these two libraries, I also needed to go\nto my <code>letters<\/code> repo and run:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>dune build . <span class=\"o\">&amp;&amp;<\/span> dune install letters\n<\/code><\/pre><\/div>\n\n<p>With these two steps taken care of, I could use <code>dune<\/code> to execute my\ntest app and see the custom instrumentation that I'd added to the\nunderlying libraries.<\/p>\n<h2>Reproducing the problem<\/h2>\n<p>At this point, I was pretty confident that <code>colombe<\/code> was having\nproblems immediately after trying to quit the SMTP session by sending\na <code>QUIT<\/code>. After some google searching, I learned that <code>openssl<\/code>\nallows you to run an SMTP session interactively. To test, I ran:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">openssl<\/span> <span class=\"nv\">s_client<\/span> <span class=\"o\">-<\/span><span class=\"k\">connect<\/span> <span class=\"nv\">smtp<\/span>.<span class=\"nv\">mailgun<\/span>.<span class=\"nv\">org<\/span>:<span class=\"mi\">587<\/span> <span class=\"o\">-<\/span><span class=\"nv\">starttls<\/span> <span class=\"nv\">smtp<\/span>\n<\/code><\/pre><\/div>\n\n<p>The first part of the session looked like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>250 STARTTLS\n---\nPost-Handshake New Session Ticket arrived:\nSSL-Session:\n    Protocol  : TLSv1.3\n    Cipher    : TLS_AES_128_GCM_SHA256\n    Session-ID: 7E83FE3CC7D65BE60AF56A2E049C09A27AB33DF834454617B81C0469A32EEC62\n    Session-ID-ctx:\n    Resumption PSK: 4A7C875CECCCA5633D3FF2107857EAF220FF561B782AAC3AC416385612E08AAB\n    PSK identity: None\n    PSK identity hint: None\n    SRP username: None\n    TLS session ticket lifetime hint: 604800 (seconds)\n    TLS session ticket:\n    0000 - 4a 79 8c 03 d5 1e 3f 5d-dc b2 2d b6 38 db 4e 10   Jy....?]..-.8.N.\n    0010 - 91 b6 1d 44 d2 95 c9 50-f3 f9 a7 89 8d 0e b9 7e   ...D...P.......~\n    0020 - f1 d6 52 da 3d 84 f5 ee-58 72 a8 81 1e 0f ad c7   ..R.=...Xr......\n    0030 - c7 76 8f 8c d9 d9 56 8f-f3 72 de 0e bf 17 b0 2f   .v....V..r.....\/\n    0040 - 72 a7 98 cd 92 46 da 45-fc b8 a9 d4 6e 73 71 f5   r....F.E....nsq.\n    0050 - 74 f2 1d eb 83 b3 01 83-77 3f 7a e0 9a 36 4a fe   t.......w?z..6J.\n    0060 - b3 89 3e c7 4c aa 87 eb-6d 46 42 46 73 8f 35 1f   ..&gt;.L...mFBFs.5.\n    0070 - 8c                                                .\n\n    Start Time: 1630180065\n    Timeout   : 7200 (sec)\n    Verify return code: 0 (ok)\n    Extended master secret: no\n    Max Early Data: 0\n---\nread R BLOCK\nEHLO\n250-smtp-out-n02.prod.us-west-2.postgun.com\n250-AUTH PLAIN LOGIN\n250-SIZE 52428800\n250-8BITMIME\n250-SMTPUTF8\n250 PIPELINING\n<\/code><\/pre><\/div>\n\n<p>By running <code>EHLO<\/code>, I was able to see the different operations this\nSMTP server supports. In the output above, we can see that one of\nthose operations is <code>AUTH PLAIN<\/code>. I tried to authenticate with invalid\ncredentials, and saw this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>AUTH PLAIN BADPASSWORD\n501 Invalid response encoding\n535 Authentication failed\nclosed\n<\/code><\/pre><\/div>\n\n<p>This means that after a client provides bad credentials, Mailgun's\nSMTP implementation immediately terminates the connection. But, when\n<code>colombe<\/code> encountered a failure to authenticate, it tried to clean up\nthe session like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">properly_quit_and_fail<\/span> <span class=\"n\">ctx<\/span> <span class=\"n\">err<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Monad<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">*<\/span> <span class=\"o\">_<\/span><span class=\"n\">txts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">send<\/span> <span class=\"n\">ctx<\/span> <span class=\"nn\">Value<\/span><span class=\"p\">.<\/span><span class=\"nc\">Quit<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"k\">fun<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">recv<\/span> <span class=\"n\">ctx<\/span> <span class=\"nn\">Value<\/span><span class=\"p\">.<\/span><span class=\"nc\">PP_221<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nc\">Error<\/span> <span class=\"n\">err<\/span>\n<\/code><\/pre><\/div>\n\n<p>So <code>colombe<\/code> tried to send a <code>QUIT<\/code> message and await a <code>221 Bye<\/code>, but\nthat message never arrived because the server had already closed the\nconnection.<\/p>\n<h2>Fixing the problem<\/h2>\n<p>Once I understood the problem, I realized I could avoid the issue by\nrevising <code>properly_quit_and_fail<\/code> to prevent waiting on a response\nfrom the server. Effectively, this meant changing a <code>let*<\/code> to a <code>let<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">properly_quit_and_fail<\/span> <span class=\"n\">ctx<\/span> <span class=\"n\">err<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Monad<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"o\">_<\/span><span class=\"n\">txts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">send<\/span> <span class=\"n\">ctx<\/span> <span class=\"nn\">Value<\/span><span class=\"p\">.<\/span><span class=\"nc\">Quit<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"k\">fun<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">recv<\/span> <span class=\"n\">ctx<\/span> <span class=\"nn\">Value<\/span><span class=\"p\">.<\/span><span class=\"nc\">PP_221<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nc\">Error<\/span> <span class=\"n\">err<\/span>\n<\/code><\/pre><\/div>\n\n<p>I also filed this\n<a href=\"https:\/\/github.com\/mirage\/colombe\/issues\/46\">issue<\/a>, which prompted\none of the maintainers to\n<a href=\"https:\/\/github.com\/mirage\/colombe\/pull\/47\">refactor<\/a> how connections\nare managed, with a much more thorough solution than what I had\ndone. (Many thanks to Calascibetta Romain for fixing my issue so\nquickly!) Once merged, other <code>colombe<\/code> users shouldn't encounter the\nstack overflow issues I described here.<\/p>\n<h2>Final Thoughts<\/h2>\n<p>This was an interesting bug to investigate because it covered a number\nof unfamiliar topics. I didn't know much about SMTP when I started,\nand I learned a couple useful facts while debugging:<\/p>\n<ul>\n<li>SMTP sessions consist of a handful of commands that are fairly easy\n  to understand.<\/li>\n<li>OpenSSL's tooling makes it easy to test SMTP by hand.<\/li>\n<li>Even very commonly used mail services like Mailgun may not work\n  exactly the way you expect from reading RFCs or other documentation!<\/li>\n<\/ul>\n<p>I also learned some useful techniques I can reuse the next time I need\nto debug OCaml problems:<\/p>\n<ul>\n<li>When writing test apps, enable logging (at info level) from the\n  beginning!<\/li>\n<li>Use <code>dune install<\/code> to add instrumentation and temporary bug fixes to\n  libraries.<\/li>\n<li>Developer tooling like <code>merlin<\/code> is very helpful for efficiently\n  navigating unfamiliar code.<\/li>\n<\/ul>\n<h2>Feedback<\/h2>\n<p>If you found this post useful (or conversely, found an error), send me\nan email. I'm interested in adding more tutorial resources to the\nOCaml ecosystem and would happy to hear suggestions about how to make\nthese resources better. My contact information is listed on the\n<a href=\"\/\">About<\/a> page.<\/p>","category":{"@attributes":{"term":"OCaml, SMTP, Debugging"}}},{"title":"How to send emails from Dream","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-email.html","rel":"alternate"}},"published":"2021-07-23T00:00:00-04:00","updated":"2021-07-23T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-23:\/ocaml-email.html","summary":"<p>How to build an email queue system for a Dream web server.<\/p>","content":"<p>I recently <a href=\"https:\/\/github.com\/aantron\/dream\/issues\/138\">learned<\/a> the\nOCaml ecosystem has most of the libraries needed to build email\nfeatures, but I wasn't able to find an example that brings all of\nthose pieces together. I wanted a simple example I could easily adapt\nto build common account verification and password recovery workflows\nin the Dream web framework. This post is my attempt to solve that\nproblem and explain what I learned in the process. The accompanying\ncode can be found\n<a href=\"https:\/\/github.com\/jsthomas\/dream-email-example\">here<\/a>.<\/p>\n<h2>Defining the problem<\/h2>\n<p>As an application developer, my main concerns when\nsending mail are:<\/p>\n<ol>\n<li>Trying to ensure the address I'm sending to is valid.<\/li>\n<li>Handling the email synthesis process asynchronously, so it doesn't\n   block the web server from handling requests quickly.<\/li>\n<li>Transmitting the email content (SMTP or a REST API call)<\/li>\n<li>Monitoring that the applications messages aren't getting\n   blocked\/dropped for some reason.<\/li>\n<\/ol>\n<p>To test how easily I could satisfy these requirements, I built a web\napp that lets the user send an arbitary email.<\/p>\n<p><img alt=\"A screenshot of the email form.\" src=\"https:\/\/jsthomas.github.io\/images\/ocaml-email\/screenshot.png\"><\/p>\n<p>The app has two parts:<\/p>\n<ul>\n<li>A server process responsible for showing the form above and\n  validating user inputs.<\/li>\n<li>A \"worker\" process responsible for sending mail. The worker gets its\n  tasks from a queue populated by the server.<\/li>\n<\/ul>\n<h2>Validating Email Addresses<\/h2>\n<p>I decided to utilize the library\n<a href=\"https:\/\/github.com\/dinosaure\/emile\"><code>emile<\/code><\/a> for address\nvalidation. An email address might be invalid for reasons outside of\nthe application's control (like the domain going way), but <code>emile<\/code> at\nleast provides a way to check a given string conforms to 5(!) RFCs\nrelevant to parsing email addresses. Check out the\n<a href=\"https:\/\/github.com\/dinosaure\/emile\/blob\/master\/test\/test.ml#L34\">tests<\/a>\nto see the impressive diversity of valid email addresses on the web.<\/p>\n<p>The library provides several different predicates for checking\naddresses. I utilized <code>Emile.of_string<\/code>, which generates a simple\nresult type, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">form_post<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">match<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">form<\/span> <span class=\"n\">request<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Ok<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;address&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">address<\/span><span class=\"o\">;<\/span> <span class=\"s2\">&quot;message&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">message<\/span><span class=\"o\">;<\/span> <span class=\"s2\">&quot;subject&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">subject<\/span> <span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Emile<\/span><span class=\"p\">.<\/span><span class=\"n\">of_string<\/span> <span class=\"n\">address<\/span> <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">alert<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">sprintf<\/span> <span class=\"s2\">&quot;Sent an email to %s.&quot;<\/span> <span class=\"n\">address<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">sprintf<\/span> <span class=\"s2\">&quot;%s is not a valid email address.&quot;<\/span> <span class=\"n\">address<\/span>\n      <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">queue_req<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">queue_email<\/span> <span class=\"n\">address<\/span> <span class=\"n\">subject<\/span> <span class=\"n\">message<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n    <span class=\"k\">in<\/span>\n    <span class=\"n\">queue_req<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"o\">(<\/span><span class=\"k\">fun<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n        <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">html<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Template<\/span><span class=\"p\">.<\/span><span class=\"n\">show_form<\/span> <span class=\"o\">~<\/span><span class=\"n\">alert<\/span> <span class=\"n\">request<\/span><span class=\"o\">))<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Bad_Request<\/span>\n<\/code><\/pre><\/div>\n\n<p>This way, if a user provides an invalid address, the form displays a simple\nwarning message and won't queue any email tasks.<\/p>\n<h2>Queuing Tasks with RabbitMQ<\/h2>\n<p>The second issue I needed to address is handling the email send\nprocess with a background worker (<code>queue_email<\/code> in the code excerpt\nabove). Sending an email can be a slow process, especially if you need\nto make additional database queries or render images to produce a\ncustomized email. That shouldn't block the web server from quickly\nresponding to the user's requests. Instead, the server should record\nthe email task in a <em>queue<\/em>, to be handled by a background worker that\nisn't as sensitive to latency.<\/p>\n<p>There are several different technologies that can be used to solve\nthis problem, for example <a href=\"https:\/\/www.rabbitmq.com\/\">RabbitMQ<\/a>,\n<a href=\"https:\/\/redislabs.com\/ebook\/part-2-core-concepts\/chapter-6-application-components-in-redis\/6-4-task-queues\/6-4-1-first-in-first-out-queues\/\">Redis<\/a>\nand <a href=\"https:\/\/aws.amazon.com\/sqs\/\">SQS<\/a>. I decided to use RabbitMQ\nbecause I didn't want to tie my implementation to one cloud provider\nand RabbitMQ is supported by\n<a href=\"https:\/\/github.com\/andersfugmann\/amqp-client\">amqp-client<\/a> on\nOPAM. This isn't the only way to go: for Redis and SQS, you might have\nsuccess with the packages\n<a href=\"https:\/\/opam.ocaml.org\/packages\/redis\/\">redis<\/a> or\n<a href=\"https:\/\/opam.ocaml.org\/packages\/aws-sqs\/\">aws-sqs<\/a>, respectively.<\/p>\n<p>The worker and server process share a common function for establishing\na connection to RabbitMQ:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">connection<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Connection<\/span><span class=\"p\">.<\/span><span class=\"n\">connect<\/span> <span class=\"o\">~<\/span><span class=\"n\">id<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;dream&quot;<\/span> <span class=\"s2\">&quot;localhost&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Connection<\/span><span class=\"p\">.<\/span><span class=\"n\">open_channel<\/span> <span class=\"o\">~<\/span><span class=\"n\">id<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;email&quot;<\/span> <span class=\"nn\">Channel<\/span><span class=\"p\">.<\/span><span class=\"n\">no_confirm<\/span> <span class=\"n\">connection<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">declare<\/span> <span class=\"n\">channel<\/span> <span class=\"o\">~<\/span><span class=\"n\">arguments<\/span><span class=\"o\">:[<\/span><span class=\"nn\">Rpc<\/span><span class=\"p\">.<\/span><span class=\"nn\">Server<\/span><span class=\"p\">.<\/span><span class=\"n\">queue_argument<\/span><span class=\"o\">]<\/span> <span class=\"s2\">&quot;email&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"o\">(<\/span><span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span><span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>I was initially little confused about why I needed a \"channel\" when I\nalready had a connection to the broker. Both the worker and the server\nconnect to the RabbitMQ Broker via TCP. It's common for clients to\nneed several connections to the broker, but it's costly to have many\nTCP connections. RabbitMQ lets us avoid this cost with channels, which\nare like \"lightweight connections that share a single TCP\nconnection\", according to these <a href=\"https:\/\/www.rabbitmq.com\/channels.html\">docs<\/a>.<\/p>\n<p>I created this function to submit messages to the queue:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">address<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">subject<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">text<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span> <span class=\"o\">[@@<\/span><span class=\"n\">deriving<\/span> <span class=\"n\">yojson<\/span><span class=\"o\">]<\/span>\n\n<span class=\"k\">let<\/span> <span class=\"n\">queue_email<\/span> <span class=\"n\">address<\/span> <span class=\"n\">subject<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span><span class=\"n\">address<\/span><span class=\"o\">;<\/span> <span class=\"n\">subject<\/span><span class=\"o\">;<\/span> <span class=\"n\">text<\/span><span class=\"o\">}<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"n\">email<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"n\">yojson_of_email<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">publish<\/span> <span class=\"n\">channel<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Message<\/span><span class=\"p\">.<\/span><span class=\"n\">make<\/span> <span class=\"n\">text<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here the server writes the address, subject, and text into a record\ntype that can be serialized to JSON before being pushed into the queue.<\/p>\n<p>The worker process, <code>queue_worker<\/code>, is fairly simple to define:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">handle_message<\/span> <span class=\"o\">(<\/span><span class=\"n\">m<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Message<\/span><span class=\"p\">.<\/span><span class=\"n\">t<\/span><span class=\"o\">)<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"n\">snd<\/span> <span class=\"n\">m<\/span><span class=\"o\">.<\/span><span class=\"n\">message<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">text<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"n\">email_of_yojson<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Received invalid email record from RabbitMQ: %s&quot;<\/span> <span class=\"n\">text<\/span><span class=\"o\">;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">email<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">e<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">send_email<\/span> <span class=\"n\">e<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">queue_worker<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Starting Queue Worker<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">;<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">handle<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"o\">~<\/span><span class=\"n\">no_ack<\/span><span class=\"o\">:<\/span><span class=\"bp\">true<\/span> <span class=\"n\">channel<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"k\">fun<\/span> <span class=\"n\">message<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">task<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">message<\/span> <span class=\"k\">with<\/span>\n      <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">m<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"n\">handle_message<\/span> <span class=\"n\">m<\/span>\n      <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;No new tasks, waiting.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Lwt_unix<\/span><span class=\"p\">.<\/span><span class=\"n\">sleep<\/span> <span class=\"mi\">5<\/span><span class=\"o\">.<\/span>\n    <span class=\"k\">in<\/span>\n    <span class=\"n\">task<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"n\">handle<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"n\">handle<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>The worker consists of an infinite loop. When the worker wakes and\nfinds tasks in the queue, it uses <code>yojson<\/code> to deserialize the\nmessages and passes them to <code>send_email<\/code>. If no work is available,\nthe worker just sleeps for 5 seconds.<\/p>\n<h2>Sending Email with <code>cohttp<\/code> and Mailgun<\/h2>\n<p>In order to send mail, I set up a trial\n<a href=\"https:\/\/documentation.mailgun.com\/en\/latest\/quickstart-sending.html#send-via-smtp\">Mailgun<\/a>\naccount. I selected this provider for several reasons:<\/p>\n<ul>\n<li>Mailgun has a generous free tier (5000 emails).<\/li>\n<li>A new account also comes with a \"sandbox\" domain, so I didn't have\n  to deal with registering a domain.<\/li>\n<li>Mailgun supports both a REST API and SMTP, allowing me to try\n  different integrations.<\/li>\n<li>Mailgun provides dashboards for tracking messages sent over time as\n  well as emails that were rejected (bounced, marked as spam, etc.).<\/li>\n<\/ul>\n<p>Mailgun's API allowed me to send an email by sending a POST with an API key and form\ndata, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">send_email<\/span> <span class=\"o\">(<\/span><span class=\"n\">e<\/span><span class=\"o\">:<\/span> <span class=\"n\">email<\/span><span class=\"o\">)<\/span> <span class=\"o\">=<\/span>\n   <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Cohttp<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Cohttp_lwt_unix<\/span> <span class=\"k\">in<\/span>\n\n   <span class=\"k\">let<\/span> <span class=\"n\">api_key<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_API_KEY&quot;<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">sender<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SEND_ADDRESS&quot;<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">api_base<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_API_BASE&quot;<\/span> <span class=\"k\">in<\/span>\n\n   <span class=\"k\">let<\/span> <span class=\"n\">params<\/span> <span class=\"o\">=<\/span> <span class=\"o\">[<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;from&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">sender<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;to&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">address<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;subject&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">subject<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;text&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">text<\/span><span class=\"o\">])<\/span>\n   <span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">cred<\/span> <span class=\"o\">=<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Basic<\/span> <span class=\"o\">(<\/span><span class=\"s2\">&quot;api&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">api_key<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">uri<\/span> <span class=\"o\">=<\/span> <span class=\"n\">api_base<\/span> <span class=\"o\">^<\/span> <span class=\"s2\">&quot;\/messages&quot;<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Uri<\/span><span class=\"p\">.<\/span><span class=\"n\">of_string<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">headers<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Header<\/span><span class=\"p\">.<\/span><span class=\"n\">add_authorization<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Header<\/span><span class=\"p\">.<\/span><span class=\"n\">init<\/span> <span class=\"bp\">()<\/span><span class=\"o\">)<\/span> <span class=\"n\">cred<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span>\n     <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Initiating email send to %s.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">address<\/span><span class=\"o\">;<\/span>\n     <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">gettimeofday<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">resp<\/span><span class=\"o\">,<\/span> <span class=\"n\">rbody<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Client<\/span><span class=\"p\">.<\/span><span class=\"n\">post_form<\/span> <span class=\"n\">uri<\/span> <span class=\"o\">~<\/span><span class=\"n\">params<\/span> <span class=\"o\">~<\/span><span class=\"n\">headers<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">gettimeofday<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">rbody_str<\/span> <span class=\"o\">=<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Cohttp_lwt<\/span><span class=\"p\">.<\/span><span class=\"nn\">Body<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">rbody<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;API Response Status: %d.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Code<\/span><span class=\"p\">.<\/span><span class=\"n\">code_of_status<\/span> <span class=\"n\">resp<\/span><span class=\"o\">.<\/span><span class=\"n\">status<\/span><span class=\"o\">);<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;API Response body %s.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"n\">rbody_str<\/span><span class=\"o\">;<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Time to send an email: %.2fs<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"n\">finish<\/span> <span class=\"o\">-.<\/span> <span class=\"n\">start<\/span><span class=\"o\">);<\/span>\n   <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>The endpoint replies with either 200 and a JSON body like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">{<\/span>\n  <span class=\"nt\">&quot;id&quot;<\/span><span class=\"p\">:<\/span> <span class=\"nt\">&quot;&lt;some mailgun email address here&gt;&quot;<\/span>\n  <span class=\"nt\">&quot;message&quot;<\/span><span class=\"p\">:<\/span> <span class=\"s2\">&quot;Queued. Thank you.&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>or else a 400 and an explanation of why the request was rejected. In\nmy tests, a successful API request typically took between 0.5 and 1\nseconds. For comparison, the webserver can serve the email form in\nless than 200 microseconds, so the performance benefits to shifting\nemail tasks to a background queue are nontrivial.<\/p>\n<h2>Sending email with SMTP<\/h2>\n<p>Mailgun supports SMTP but they recommend using their API, especially\nfor sending large amounts of mail at once. I used\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/\">letters<\/a> to test their SMTP\nsupport with this script:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">body<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nc\">Plain<\/span> <span class=\"o\">{|<\/span><span class=\"nc\">This<\/span> <span class=\"n\">is<\/span> <span class=\"n\">a<\/span> <span class=\"n\">test<\/span> <span class=\"n\">email<\/span> <span class=\"n\">body<\/span><span class=\"o\">.|}<\/span>\n\n<span class=\"k\">let<\/span> <span class=\"n\">send_email<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">config<\/span> <span class=\"o\">=<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nn\">Config<\/span><span class=\"p\">.<\/span><span class=\"n\">make<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">username<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_USER&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">password<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_PASSWORD&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">hostname<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;smtp.mailgun.org&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">with_starttls<\/span><span class=\"o\">:<\/span><span class=\"bp\">true<\/span><span class=\"o\">)<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">sender<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_SENDER&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">recipients<\/span> <span class=\"o\">=<\/span> <span class=\"o\">[<\/span><span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nc\">To<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;EMAIL_ADDRESS&quot;<\/span><span class=\"o\">)]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">subject<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;Test email from mailgun.&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">mail<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"n\">build_email<\/span> <span class=\"o\">~<\/span><span class=\"n\">from<\/span><span class=\"o\">:<\/span><span class=\"n\">sender<\/span> <span class=\"o\">~<\/span><span class=\"n\">recipients<\/span> <span class=\"o\">~<\/span><span class=\"n\">subject<\/span> <span class=\"o\">~<\/span><span class=\"n\">body<\/span> <span class=\"k\">in<\/span>\n\n  <span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">record_backtrace<\/span> <span class=\"bp\">true<\/span><span class=\"o\">;<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">mail<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"n\">message<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"o\">(<\/span><span class=\"k\">try<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span>\n       <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"n\">send<\/span> <span class=\"o\">~<\/span><span class=\"n\">config<\/span> <span class=\"o\">~<\/span><span class=\"n\">sender<\/span> <span class=\"o\">~<\/span><span class=\"n\">recipients<\/span> <span class=\"o\">~<\/span><span class=\"n\">message<\/span>\n    <span class=\"k\">with<\/span>\n      <span class=\"n\">e<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Error. %s<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">e<\/span><span class=\"o\">);<\/span>\n      <span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">print_backtrace<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span>\n      <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n   <span class=\"o\">)<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Message synthesis failed.&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Lwt_main<\/span><span class=\"p\">.<\/span><span class=\"n\">run<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">send_email<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>I ran into some\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/issues\/35\">difficulties<\/a> because\nMailgun does not consistently follow RFC 4954 (thanks to Calascibetta\nRomain for figuring out the problem and creating a\n<a href=\"https:\/\/github.com\/mirage\/colombe\/pull\/41\">patch<\/a>). Once I applied\nthe patch, I was able to send mail successfully.<\/p>\n<p>I haven't fully explored the tradeoffs of using SMTP versus an\nAPI. The main goal of my experiements was to confirm that if I needed\nto integrate with a specific SMTP server, I knew how to do so.<\/p>\n<h2>Discussion<\/h2>\n<p>This example focused on email, but task queues and background workers\ncan be used to implement other important pieces of functionality for\nweb applications. For example, I've utilized\n<a href=\"https:\/\/docs.celeryproject.org\/en\/stable\/getting-started\/introduction.html\">celery<\/a>\nin the past to generate weekly reports and schedule recurring ETL\njobs. This exercise was a nice opportunity to see how one would\nconstruct a system similar to <code>celery<\/code> in OCaml. It also provides a\nsimple illustration of how we can utilize queues to facilitate\nhorizontal scaling. If the volume of email requests grows too big for\none machine, we can put the web server and the worker on separate\ninstances or have multiple worker instances consuming from the email\nqueue.<\/p>\n<p>I didn't cover error handling in this example, but that's clearly an\nimportant piece of functionality to include when building a production\nemail system. At a minimum, it would be useful to add a retry\nmechanism in the event that Mailgun is unavailable.<\/p>\n<h2>References<\/h2>\n<p>I found the resources below helpful for working on this project:<\/p>\n<ul>\n<li>The <code>amqp-client<\/code>\n  <a href=\"https:\/\/andersfugmann.github.io\/amqp-client\/amqp-client-lwt\/index.html\">documentation<\/a>,\n  especially the\n  <a href=\"https:\/\/github.com\/andersfugmann\/amqp-client\/tree\/master\/examples\">examples<\/a>\n  were helpful for setting up with RabbitMQ.<\/li>\n<li>The <a href=\"https:\/\/github.com\/mirage\/ocaml-cohttp#client-tutorial\">client\n  tutorial<\/a>\n  was helpful for getting started with <code>cohttp<\/code>. Later, I utilized\n  <a href=\"https:\/\/mirage.github.io\/ocaml-cohttp\/cohttp-lwt-unix\/Cohttp_lwt_unix\/Client\/index.html\">this\n  section<\/a>\n  of the docs to understand that I needed to use <code>post_form<\/code> instead\n  of <code>post<\/code> when interacting with Mailgun's API.<\/li>\n<\/ul>\n<h2>Feedback<\/h2>\n<p>If you ended up looking through the source code for this example, let\nme know how what you thought! I'm interested in adding more tutorial\nresources to the OCaml ecosystem, so feel free to post a PR or issue\nto\n<a href=\"https:\/\/github.com\/jsthomas\/dream-email-example\">dream-email-example<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Writing a REST API with Dream","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-dream-api.html","rel":"alternate"}},"published":"2021-07-12T00:00:00-04:00","updated":"2021-07-12T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-12:\/ocaml-dream-api.html","summary":"<p>Writing a REST API in Dream<\/p>","content":"<p>In the last few weeks I've been building a simple REST API using the\n<a href=\"https:\/\/aantron.github.io\/dream\/\">Dream<\/a> web framework. Writing APIs\nhas been one major component of my paid programming work and I wanted\nto compare and contrast the experience of writing an API in a strongly\ntyped functional programming language with the same workflow in a\ndynamically typed language like Python.<\/p>\n<p>You can find the source code for this project\n<a href=\"https:\/\/github.com\/jsthomas\/sensors\">here<\/a>. Hopefully, this repo will\nbe a useful resource for anyone who wants to look at a slightly larger\nexample application that uses Dream. Though I'm still a beginner, I\nwas surprised how easy it was to complete familiar tasks in this\nframework. I'm optimistic about the future of web programming in\nOCaml!<\/p>\n<p>This post provides a sort of \"experience report\" for working with\nDream, Yojson, and Caqti. Obviously, these types of reports are highly\nsubjective and you should run your own experiments too!  I'll be\ncomparing with my experience in working with\n<a href=\"https:\/\/trypyramid.com\/\">Pyramid<\/a> and\n<a href=\"https:\/\/www.sqlalchemy.org\/\">SQLAlchemy<\/a>, since those are the Python\nprojects I've used most.<\/p>\n<p>Finally, it's important to point out that Dream is in alpha (version\n<code>1.0.0~alpha2<\/code> as of this writing). This is an early version!\nComparisons with frameworks like Pyramid or Flask are in some sense\napples-and-oranges, because those projects have had a long time (and\nmany engineering hours) to mature. Ultimately, the point of this post\n(and the repo that goes with it) isn't to make make value judgements\n(\"framework X is good, Y is bad\"), but rather to understand how to\ntranslate concepts from one workflow to another.<\/p>\n<h2>Problem Definition<\/h2>\n<p>I decided to build a API for managing time series data. My\nrequirements for the project were as follows:<\/p>\n<ul>\n<li>The API will allow creating, reading, and deleting \"sensors\". A\n  sensor is an abstract IoT device that measures a floating point\n  quantity at a specific cadence (for example a weather station\n  measuring average hourly windspeed).<\/li>\n<li>Every sensor gets an API key that allows it to upload (POST) data to\n  an endpoint.<\/li>\n<li>A GET endpoint will allow users to retrieve the data a sensor\n  generated between two dates.<\/li>\n<li>The API sends and receives data formatted as JSON and must be backed\n  by a PostgreSQL database.<\/li>\n<li>The API should have <code>login\/logout<\/code> endpoints for a (not yet built)\n  frontend to use.<\/li>\n<li>Finally, a user should only be allowed to access sensor data that\n  belongs to them.<\/li>\n<\/ul>\n<p>I chose these requirements because they cover a number of different\nread\/write operations that require data formatting\/parsing and\ntracking relationships between four different entities (users, keys,\nsensors, and readings).<\/p>\n<h2>Dependencies and Setup<\/h2>\n<p>For this build, I needed three core dependencies:<\/p>\n<ol>\n<li>A server to handle web requests (Dream).<\/li>\n<li>Support for parsing and synthesizing JSON records.<\/li>\n<li>A library for integrating with PostgreSQL.<\/li>\n<\/ol>\n<p>After a bit of research, I settled on\n<a href=\"https:\/\/opam.ocaml.org\/packages\/yojson\/\">Yojson<\/a> and\n<a href=\"https:\/\/opam.ocaml.org\/packages\/caqti\/\">Caqti<\/a> for (2) and (3)\nrespectively. Both of these are fairly standard and appear in the\nexcellent corpus of\n<a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\">examples<\/a> that\naccompany Dream. Since I had previously written an\n<a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\/w-docker-postgres\">example<\/a>\nof how to use Dream with a dockerized PostrgreSQL container, I used\nthat as a starting point.<\/p>\n<p>It's useful to have a way to run (and re-run) ad-hoc requests against\nthe API during development. I used <a href=\"https:\/\/insomnia.rest\/\">Insomnia<\/a>\nfor this, but other tools like <code>curl<\/code> would work too.<\/p>\n<h2>Adding an endpoint<\/h2>\n<p>To give a sense of my development workflow, I want to walk through my\nprocess for adding a simple endpoint, <code>\/api\/login<\/code>. Inside the router,\nthat endpoint looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/login&quot;<\/span> <span class=\"n\">login<\/span><span class=\"o\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>In this excerpt <code>login<\/code> is a \"handler\". Handlers are responsible for\ntranslating requests into responses; this is captured in their <a href=\"https:\/\/aantron.github.io\/dream\/#type-handler\">type\nsignature<\/a>.<\/p>\n<p>Conceptually, the <code>login<\/code> handler needs to do three things:<\/p>\n<ol>\n<li>Receive a JSON body and confirm it's formatted as expected.<\/li>\n<li>Look up the relevant user\/password combination in the database.<\/li>\n<li>Load the relevant session information if the credentials are valid.<\/li>\n<\/ol>\n<p>For the first part, the endpoint needs to receive a JSON payload that\nlooks like <code>{\"username\": \"...\", \"password\": \"...\"}<\/code>. To describe that\npayload, I introduced a simple record type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">login_doc<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">username<\/span> <span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">password<\/span> <span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span> <span class=\"o\">[@@<\/span><span class=\"n\">deriving<\/span> <span class=\"n\">yojson<\/span><span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Adding <code>[@@deriving yojson]<\/code> means the compiler can generate functions\nto convert these records to and from JSON. In this case those\nfunctions are called <code>login_doc_of_yojson<\/code> and <code>yojson_of_login_doc<\/code>.<\/p>\n<p>My <code>login<\/code> handler looked roughly like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">json_receiver<\/span> <span class=\"n\">json_parser<\/span> <span class=\"n\">handler<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">body<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">body<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">body<\/span>\n      <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span>\n      <span class=\"o\">|&gt;<\/span> <span class=\"n\">json_parser<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">doc<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">handler<\/span> <span class=\"n\">doc<\/span> <span class=\"n\">request<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"o\">{<\/span> <span class=\"n\">error<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;Received invalid JSON input.&quot;<\/span> <span class=\"o\">}<\/span>\n    <span class=\"o\">|&gt;<\/span> <span class=\"n\">yojson_of_error_doc<\/span>\n    <span class=\"o\">|&gt;<\/span> <span class=\"n\">json_response<\/span> <span class=\"o\">~<\/span><span class=\"n\">status<\/span><span class=\"o\">:<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Bad_Request<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">login<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">login_base<\/span> <span class=\"n\">login_doc<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_id<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql<\/span> <span class=\"n\">request<\/span>\n        <span class=\"o\">(<\/span><span class=\"nn\">Models<\/span><span class=\"p\">.<\/span><span class=\"nn\">User<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"n\">login_doc<\/span><span class=\"o\">.<\/span><span class=\"n\">username<\/span> <span class=\"n\">login_doc<\/span><span class=\"o\">.<\/span><span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">match<\/span> <span class=\"n\">user_id<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">id<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">invalidate_session<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">put_session<\/span> <span class=\"s2\">&quot;user&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Int<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">id<\/span><span class=\"o\">)<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">OK<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Forbidden<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"n\">json_receiver<\/span> <span class=\"n\">login_doc_of_yojson<\/span> <span class=\"n\">login_base<\/span>\n<\/code><\/pre><\/div>\n\n<p>If a user uploads an invalid JSON body, this will cause\n<code>login_doc_of_yojson<\/code> to throw an exception. By default, this produces\na 500 server error response. To handle this situation more gracefully,\nI introduced <code>json_receiver<\/code>. If the parser passed to <code>json_receiver<\/code>\nsucceeds on the request body, the results are passed to the inner\nhandler. Otherwise, the server responds with a <code>400 Bad\nRequest<\/code>. Re-using <code>json_receiver<\/code> across my endpoints allows me to\navoid introducing a<code>try\/with<\/code> block any time time I need to handle\nJSON input.<\/p>\n<p>I decided to manage models in a separate library, <code>Models<\/code>. The\nbuild tool, <code>dune<\/code>, made this easy to do; I just needed separate\n<code>dune<\/code> files for the <code>server\/model<\/code> and <code>server\/bin<\/code> folders. I like\nthis design because it simplifies re-use of the database portion of my\nproject. For example, if I later needed to build a CLI admin tool,\nthat tool could utilize my existing queries without being exposed to\nAPI concerns.<\/p>\n<p>Inside <code>User<\/code>, the <code>get<\/code> query function is defined as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">get<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">query<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">R<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"o\">(<\/span><span class=\"n\">tup2<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span><span class=\"o\">)<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">int<\/span>\n      <span class=\"s2\">&quot;SELECT id FROM app_user WHERE username = ? and password = ?&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">fun<\/span> <span class=\"n\">username<\/span> <span class=\"n\">password<\/span> <span class=\"o\">(<\/span><span class=\"k\">module<\/span> <span class=\"nc\">Db<\/span> <span class=\"o\">:<\/span> <span class=\"nc\">DB<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_or_error<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Db<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"n\">query<\/span> <span class=\"o\">(<\/span><span class=\"n\">username<\/span><span class=\"o\">,<\/span> <span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"nn\">Caqti_lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">or_fail<\/span> <span class=\"n\">user_or_error<\/span>\n<\/code><\/pre><\/div>\n\n<p>Caqti allows us to define a function that consumes our query\nparameters (the username and password) along with a database\nconnection, and produces a promise that will resolve with the results\nof the query. In this case, the types encode that the function\nproduces an <code>int option<\/code> containing the user's primary key if the\ncredentials are valid. (Note that it's not a good idea to store\npasswords in plain text like this; this is just for illustrative\npurposes.)<\/p>\n<p>Session management, the final item that the endpoint needs to address,\nis handled by Dream. The framework allows sessions to be stored in\ncookies, memory, or the database; I opted for database sessions\nbecause I had used similar session backends in the past. Sessions\nallow us to store pairs key\/value strings across requests. I used the\nsession just to store the logged-in user's ID, so that the API has\neasy access in later database queries.<\/p>\n<h2>Thoughts on the Dream Router<\/h2>\n<p>The final router for my server looked like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">run<\/span> <span class=\"o\">~<\/span><span class=\"n\">interface<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;0.0.0.0&quot;<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">logger<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql_pool<\/span> <span class=\"s2\">&quot;postgresql:\/\/sensors@127.0.0.1\/sensors&quot;<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql_sessions<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">router<\/span> <span class=\"o\">[<\/span>\n    <span class=\"c\">(* More endpoints here ... *)<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"s2\">&quot;\/version&quot;<\/span> <span class=\"n\">version<\/span><span class=\"o\">;<\/span>\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/login&quot;<\/span> <span class=\"n\">login<\/span><span class=\"o\">;<\/span>\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/logout&quot;<\/span> <span class=\"n\">logout<\/span><span class=\"o\">;<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">scope<\/span> <span class=\"s2\">&quot;\/api&quot;<\/span> <span class=\"o\">[<\/span><span class=\"n\">login_required<\/span><span class=\"o\">]<\/span> <span class=\"o\">[<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"s2\">&quot;\/user\/:user_id&quot;<\/span> <span class=\"n\">user<\/span><span class=\"o\">;<\/span>\n      <span class=\"c\">(* More endpoints here... *)<\/span>\n    <span class=\"o\">];<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">scope<\/span> <span class=\"s2\">&quot;\/sensor&quot;<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">[<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/upload&quot;<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">api_key_required<\/span> <span class=\"n\">sensor_upload<\/span><span class=\"o\">;<\/span>\n    <span class=\"o\">]<\/span>\n  <span class=\"o\">]<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">not_found<\/span>\n<\/code><\/pre><\/div>\n\n<p>I really appreciate how Dream makes it possible to get a concise\noverview of the API; in some Pyramid projects, I found this wasn't\nalways possible. In fact, in Pyramid I sometimes struggled with subtle\nrouting bugs that were not obvious until run time. Having the compiler\nvalidate the router in Dream was a welcome change.<\/p>\n<p>At the moment, Pyramid makes it somewhat easier to handle\naccess\/permissions concerns compared to Dream. Working in Pyramid, it\nwas relatively common for the routes to manage some amount of\nparameter validation and permissions. For example, given a path\n<code>\/user\/123\/article\/abc456<\/code>, the route (or \"resources\" in Pyramid\nterminology) would be responsible for:<\/p>\n<ul>\n<li>Extracting the user and article IDs (<code>123<\/code> and <code>abc456<\/code>).<\/li>\n<li>Determining those records actually exist in the database, and\n  passing them to the view\/handler in a context record.<\/li>\n<li>Validating that the requester has permissions to operate on those\nUser and Article records.<\/li>\n<\/ul>\n<p>This is discussed a bit more in the Pyramid Docs under <a href=\"https:\/\/docs.pylonsproject.org\/projects\/pyramid\/en\/latest\/narr\/traversal.html\">URL\ntraversal<\/a>.\nEffectively, Pyramid resources mean that handler\/view code downstream\ncan focus on updating database records and\/or rendering HTML\/JSON\nwithout worrying about permissions concerns.<\/p>\n<p>I didn't want to build a permissions system for my API so instead I\nincorporated User IDs into my function signatures in <code>Model<\/code> and used\ninner joins to model permissions. For example, here is an example of a\nquery that fetches the metadata for all sensors belonging to a\nparticular user:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">SELECT<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">name<\/span><span class=\"p\">,<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">description<\/span><span class=\"p\">,<\/span> <span class=\"n\">k<\/span><span class=\"p\">.<\/span><span class=\"n\">uuid<\/span>\n<span class=\"k\">FROM<\/span> <span class=\"n\">sensor<\/span> <span class=\"n\">s<\/span>\n<span class=\"k\">INNER<\/span> <span class=\"k\">JOIN<\/span> <span class=\"n\">user_sensor<\/span> <span class=\"n\">us<\/span>\n <span class=\"k\">ON<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">sensor<\/span> <span class=\"o\">=<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">id<\/span> <span class=\"k\">AND<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">app_user<\/span> <span class=\"o\">=<\/span> <span class=\"err\">$<\/span><span class=\"mi\">1<\/span> <span class=\"k\">AND<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">sensor<\/span> <span class=\"o\">=<\/span> <span class=\"err\">$<\/span><span class=\"mi\">2<\/span>\n<span class=\"k\">INNER<\/span> <span class=\"k\">JOIN<\/span> <span class=\"n\">api_key<\/span> <span class=\"n\">k<\/span>\n <span class=\"k\">ON<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">api_key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">k<\/span><span class=\"p\">.<\/span><span class=\"n\">id<\/span>\n<\/code><\/pre><\/div>\n\n<p>By joining against <code>user_sensor<\/code>, I ensure that a user only gets data\nfor the sensors they own.<\/p>\n<p>I should point out that Dream allows us to use a custom router,\nhowever! The project has <a href=\"https:\/\/github.com\/aantron\/dream\/issues\/122\">an\nissue<\/a> for more elaborate\nrouting and Ulrik Strid has introduced\n<a href=\"https:\/\/github.com\/ulrikstrid\/dream-routes\">dream-routes<\/a>, which\nallows additional type information to be encoded in routes. So,\nwriting a more sophisticated router that behaves like Pyramid's\nresource system is certainly possible.<\/p>\n<h2>Comparing Caqti and SQLAlchemy<\/h2>\n<p>As a web programmer, especially one working on an analytics project,\nit's important to get comfortable working with the database library\nyou've chosen for your project. Indeed, a significant portion of this\nproject consisted of familiarizing myself with <code>Caqti<\/code>.<\/p>\n<p>Caqti is a bit different from SQLAlchemy. With SQLAlchemy, you\ntypically define one class for each table. Then, using SQLAlchemy's\nmetaprogramming features, those classes are used to define\nqueries. For comparison, here are equivalent queries against the user\ntable:<\/p>\n<p><strong>Caqti<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">get<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">query<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">R<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"o\">(<\/span><span class=\"n\">tup2<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span><span class=\"o\">)<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">int<\/span>\n      <span class=\"s2\">&quot;SELECT id FROM app_user WHERE username = ? and password = ?&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">fun<\/span> <span class=\"n\">username<\/span> <span class=\"n\">password<\/span> <span class=\"o\">(<\/span><span class=\"k\">module<\/span> <span class=\"nc\">Db<\/span> <span class=\"o\">:<\/span> <span class=\"nc\">DB<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_or_error<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Db<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"n\">query<\/span> <span class=\"o\">(<\/span><span class=\"n\">username<\/span><span class=\"o\">,<\/span> <span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"nn\">Caqti_lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">or_fail<\/span> <span class=\"n\">user_or_error<\/span>\n<\/code><\/pre><\/div>\n\n<p><strong>SQLAlchemy<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">db<\/span><span class=\"o\">.<\/span><span class=\"n\">session<\/span><span class=\"o\">.<\/span><span class=\"n\">query<\/span><span class=\"p\">(<\/span><span class=\"n\">User<\/span><span class=\"p\">)<\/span> \\\n    <span class=\"o\">.<\/span><span class=\"n\">filter<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">User<\/span><span class=\"o\">.<\/span><span class=\"n\">username<\/span> <span class=\"o\">==<\/span> <span class=\"n\">username<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">User<\/span><span class=\"o\">.<\/span><span class=\"n\">password<\/span> <span class=\"o\">==<\/span> <span class=\"n\">password<\/span>\n    <span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">one_or_none<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Working with Caqti, a mistake in the syntax of a SQL query won't be\ndiscovered until runtime. I made fewer mistakes like this with\nSQLAlchemy because most queries are written in Python and can be\nlinted by the IDE. Another recurring point of confusion for me with\nCaqti had to do with matching the function on the <code>Caqti_request<\/code>\n(<code>R.find_opt<\/code> above) with the function invoked in <code>Db<\/code>\n(<code>Db.find_opt<\/code>); this is how we indicate that the query produces zero,\none, zero\/one, or multiple rows. If the two don't agree, the program\nwon't compile; initially I struggled to understand what this\ncompiler error meant:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Error<\/span><span class=\"o\">:<\/span> <span class=\"n\">The<\/span> <span class=\"kd\">function<\/span> <span class=\"n\">applied<\/span> <span class=\"n\">to<\/span> <span class=\"k\">this<\/span> <span class=\"n\">argument<\/span> <span class=\"n\">has<\/span> <span class=\"n\">type<\/span>\n         <span class=\"o\">?<\/span><span class=\"n\">env<\/span><span class=\"o\">:(<\/span><span class=\"n\">Caqti_driver_info<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">string<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">Caqti_query<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n         <span class=\"o\">?<\/span><span class=\"n\">oneshot<\/span><span class=\"o\">:<\/span><span class=\"n\">bool<\/span> <span class=\"o\">-&gt;<\/span>\n         <span class=\"o\">(<\/span><span class=\"err\">&#39;<\/span><span class=\"n\">a<\/span><span class=\"o\">,<\/span> <span class=\"n\">unit<\/span><span class=\"o\">,<\/span> <span class=\"o\">[&lt;<\/span> <span class=\"err\">`<\/span><span class=\"n\">Many<\/span> <span class=\"o\">|<\/span> <span class=\"err\">`<\/span><span class=\"n\">One<\/span> <span class=\"o\">|<\/span> <span class=\"err\">`<\/span><span class=\"n\">Zero<\/span> <span class=\"o\">&gt;<\/span> <span class=\"err\">`<\/span><span class=\"n\">Zero<\/span> <span class=\"o\">])<\/span> <span class=\"n\">Caqti_request<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span>\n<span class=\"n\">This<\/span> <span class=\"n\">argument<\/span> <span class=\"n\">cannot<\/span> <span class=\"n\">be<\/span> <span class=\"n\">applied<\/span> <span class=\"n\">without<\/span> <span class=\"n\">label<\/span>\n<\/code><\/pre><\/div>\n\n<p>Using Caqti became easier as I became accustomed to thinking in terms of\nprepared queries. About halfway through the project I realized I\nneeded to switch from SQLite to PostgreSQL, and changing databases was\nfairly painless because Caqti supports both.<\/p>\n<p>I also made use of Caqti's features for dealing with custom column\ntypes. Caqti does not have built-in support for JSON columns, but\nadding a custom column type to handle this was straightforward:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">type<\/span><span class=\"w\"> <\/span><span class=\"n\">readings<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nc\">float<\/span><span class=\"w\"> <\/span><span class=\"k\">option<\/span><span class=\"w\"> <\/span><span class=\"k\">array<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">@@deriving yojson<\/span><span class=\"o\">]<\/span><span class=\"w\"><\/span>\n\n<span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">sql_readings<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">encode<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nl\">a<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">readings<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Ok<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">yojson_of_readings<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"n\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"ow\">in<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">decode<\/span><span class=\"w\"> <\/span><span class=\"nc\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Ok<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nc\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"n\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">readings_of_yojson<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"ow\">in<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">T<\/span><span class=\"p\">.(<\/span><span class=\"n\">custom<\/span><span class=\"w\"> <\/span><span class=\"o\">~<\/span><span class=\"n\">encode<\/span><span class=\"w\"> <\/span><span class=\"o\">~<\/span><span class=\"n\">decode<\/span><span class=\"w\"> <\/span><span class=\"n\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<\/code><\/pre><\/div>\n\n<p>In my case, the JSON that I needed to store consisted of arrays of\nfloating point numbers, so building the custom type was simply a\nmatter of connecting Yojson and Caqti in the right way.<\/p>\n<h2>Discussion<\/h2>\n<p>Ever since I started building web applications in Python, I've thought\nof an API server as a big function that transforms requests into\nresponses, with any nontrivial state residing in databases or services\nlike S3. Dream provides a modern web framework that matches my mental\nmodel for how a web server should work.<\/p>\n<p>Web programming in OCaml \"feels\" a bit different than working in\nPython. In Python it's possible to get something running quickly, but\nit's also easy to forget corner cases and introduce defects that have\nto be addressed later in the application's lifecycle. An OCaml project\nrequires some up-front investment, but this investment pays off later\nin several ways. First, fast feedback from the compiler (together with\neditor integrations like <code>merlin<\/code> and <code>tuareg<\/code>) helped me to identify\nissues earlier. <code>Yojson<\/code> made it simple to enforce that JSON requests\nand responses adhered to a fixed schema, and helped me process inputs\nmore systematically. OCaml made refactoring safe and easy, so that I\ncould confidently adapt my design as I introduced new requirements. In\nthe right context, I think the advantages of using OCaml could\nsignificantly reduce the total lifecycle costs of maintaining many web\napplications without reducing the pace of new development.<\/p>\n<h2>References<\/h2>\n<p>I found the resources below helpful for working on this project:<\/p>\n<ul>\n<li>The Dream <a href=\"https:\/\/aantron.github.io\/dream\/\">API docs<\/a> set a high\n  standard for readability and helped me quickly get up to speed with\n  the framework.<\/li>\n<li>This <a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\">section<\/a>\n  of the Dream repo has excellent examples, both for working with the\n  framework and deploying it.<\/li>\n<li>I referred to Bobby Priambodo's <a href=\"https:\/\/medium.com\/@bobbypriambodo\/interfacing-ocaml-and-postgresql-with-caqti-a92515bdaa11\">blog\n  posts<\/a>\n  about interfacing Caqti and PostgreSQL as I wrote the models in my project.<\/li>\n<li>The Caqti\n  <a href=\"https:\/\/paurkedal.github.io\/ocaml-caqti\/index.html\">docs<\/a>,\n  especially for <code>Caqti_type<\/code> and <code>Caqti_request<\/code> were helpful as I\n  was writing queries.<\/li>\n<li>There is also an\n  <a href=\"https:\/\/github.com\/paurkedal\/ocaml-caqti\/blob\/master\/tests\/bikereg.ml\">example<\/a>\n  in the Caqti repo that is worth looking through.<\/li>\n<li>The README on\n  <a href=\"https:\/\/github.com\/janestreet\/ppx_yojson_conv\">ppx_yojson_conv<\/a> had\n  helpful examples that I referred to while writing my own\n  JSON-related types.<\/li>\n<\/ul>\n<h2>Feedback<\/h2>\n<p>If you ended up looking through the source code for my API, let me\nknow how what you thought! I'm interested in adding more tutorial\nresources to the OCaml ecosystem, so feel free to post a PR or issue\nto\n<a href=\"https:\/\/github.com\/jsthomas\/sensors\">sensors<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Let's write a shell in OCaml!","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-shell.html","rel":"alternate"}},"published":"2021-07-01T00:00:00-04:00","updated":"2021-07-01T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-01:\/ocaml-shell.html","summary":"<p>A user experience report about writing a simple shell in OCaml<\/p>","content":"<p>This Summer I'm studying OCaml and systems programming at the <a href=\"https:\/\/www.recurse.com\/\">Recurse\nCenter<\/a>. Currently I'm reading the\ndelightful book <a href=\"https:\/\/pages.cs.wisc.edu\/~remzi\/OSTEP\/\"><em>Operating Systems: Three Easy\nPieces<\/em><\/a> by Remzi\nArpaci-Dusseau and Andrea Arpaci-Dusseau. Besides great exposition,\nthe book includes several interesting projects, one of which is to\n<a href=\"https:\/\/github.com\/remzi-arpacidusseau\/ostep-projects\/tree\/master\/processes-shell\">write a\nshell<\/a>.<\/p>\n<p>The project materials, a set of shell scripts that define tests, are\nlanguage agnostic. I believe the authors intended for students to use\nC, but I worked through the exercise in OCaml; you can find the final\nresult <a href=\"https:\/\/github.com\/jsthomas\/simple-ocaml-shell\">in this\nrepo<\/a>. This blog post\nis a short experience report; if you're interested in working on a\nbeginner OCaml project, hopefully it provides some useful scaffolding\nfor your studies.<\/p>\n<h2>Shell features<\/h2>\n<p>The shell I built (<code>osh<\/code>) has a somewhat limited feature set. It:<\/p>\n<ul>\n<li>\n<p>Allows several commands to be run in parallel (e.g. <code>program1 arg1 &amp;\n  program2 arg2 arg3<\/code>)<\/p>\n<\/li>\n<li>\n<p>Supports simple output redirection (e.g. <code>echo \"hello\" &gt;\n  hello.txt<\/code>). Both <code>stdout<\/code> and <code>stderr<\/code> go to the same file.<\/p>\n<\/li>\n<li>\n<p>Has three builtin functions, <code>cd<\/code>, <code>exit<\/code>, and <code>path<\/code>. <code>path<\/code> allows\n  you to define a list of directories to search for executables; we\n  need this because environment variables aren't supported.<\/p>\n<\/li>\n<\/ul>\n<p>Other niceties, like tab completion and pipes, aren't supported. To\nfacilitate testing, the shell can run in a batch mode (<code>osh &lt;my file\nof commands&gt;<\/code>) as well as an interactive mode. A final simplifying\nassumption is that <code>osh<\/code> only provides a basic error message when\ninputs are malformed.<\/p>\n<h2>Concepts<\/h2>\n<p>There are three main topics I studied while working on this project:<\/p>\n<ol>\n<li>\n<p>The <code>Unix<\/code> module, especially <code>fork<\/code> and\n    <code>execv<\/code>. <a href=\"https:\/\/ocaml.github.io\/ocamlunix\/ocamlunix.html\">This\n    page<\/a>, from\n    Xavier Leroy and Didier R\u00e9my, was helpful for getting up to\n    speed. The man-pages were also useful.<\/p>\n<\/li>\n<li>\n<p>The <a href=\"https:\/\/ocaml.org\/api\/Stream.html\"><code>Stream<\/code><\/a> module. Streams\n   in OCaml are roughly analogous to generators in Python; they\n   allowed me to use a single type (a <code>string Stream.t<\/code>) to represent\n   commands coming from an interactive session or a batch file.<\/p>\n<\/li>\n<li>\n<p>The <a href=\"https:\/\/github.com\/inhabitedtype\/angstrom\">Angstrom<\/a>\n   parser-combinator library. I used this library to determine whether\n   a given line of user input is well formed.<\/p>\n<\/li>\n<\/ol>\n<p>I suspect you could implement the parser without Angstrom, if you\nreally wanted to. I wanted to learn more about this library, and this\nproject seemed like a good place to try it out.<\/p>\n<p>Although I previously worked through some simple monadic parser\nexercises in Haskell, I struggled the most with Angstrom. Reading one\nof the main <a href=\"https:\/\/github.com\/inhabitedtype\/angstrom\/blob\/master\/lib\/angstrom.mli\">mli\nfiles<\/a>\nseemed to be the best way to get an overview of the combinators the\nlibrary provides. I also spent a fair amount of time experimenting in\n<code>utop<\/code> as I put my parser together.<\/p>\n<h2>Steps<\/h2>\n<p>Here is a rough outline for how I built my shell.<\/p>\n<p>First, I defined a main function that would fetch a line of text from\n<code>stdin<\/code> and echo it back to the user. Then I added the ability to\nrepresent either interactive or batch input with a <code>Stream<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">prompt_stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">f<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;osh&gt; &quot;<\/span><span class=\"o\">;<\/span>\n    <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">read_line<\/span> <span class=\"bp\">()<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">from<\/span> <span class=\"n\">f<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">file_stream<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">in_channel<\/span> <span class=\"o\">=<\/span> <span class=\"n\">open_in<\/span> <span class=\"n\">filename<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">f<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">input_line<\/span> <span class=\"n\">in_channel<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"nc\">End_of_file<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"n\">close_in<\/span> <span class=\"n\">in_channel<\/span><span class=\"o\">;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">from<\/span> <span class=\"n\">f<\/span>\n<\/code><\/pre><\/div>\n\n<p>It's useful to do this part as early as possible, since batch input\nallows you to run the tests.<\/p>\n<p>Once I could get <code>osh<\/code> to fail all 22 test cases, I started adding the\nsimpler built-in commands <code>cd<\/code> and <code>exit<\/code>. (Note <code>.\/test-osh.sh -c<\/code>\nwill run all 22 tests, without stopping at the first one that fails.)<\/p>\n<p>My first version of <code>main<\/code> just treated user input as <code>string list<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">String<\/span><span class=\"p\">.<\/span><span class=\"n\">split_on_char<\/span> <span class=\"sc\">&#39; &#39;<\/span> <span class=\"n\">text<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">process<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"n\">text<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span>  <span class=\"c\">(* Empty lines should just be treated as no-ops. *)<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;&quot;<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;exit&quot;<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">exit<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;cd&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">x<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">chdir<\/span> <span class=\"n\">x<\/span>\n    <span class=\"o\">|<\/span> <span class=\"s2\">&quot;cd&quot;<\/span><span class=\"o\">::<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span>\n    <span class=\"o\">|<\/span> <span class=\"n\">x<\/span><span class=\"o\">::<\/span><span class=\"n\">xs<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">match<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">fork<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">with<\/span>\n      <span class=\"o\">|<\/span> <span class=\"mi\">0<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Child *)<\/span>\n        <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">execv<\/span> <span class=\"n\">x<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Array<\/span><span class=\"p\">.<\/span><span class=\"n\">of_list<\/span> <span class=\"n\">xs<\/span><span class=\"o\">)<\/span>\n      <span class=\"o\">|<\/span> <span class=\"n\">child_pid<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Parent *)<\/span>\n        <span class=\"k\">let<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">waitpid<\/span> <span class=\"bp\">[]<\/span> <span class=\"n\">child_pid<\/span>\n        <span class=\"k\">in<\/span> <span class=\"bp\">()<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">iter<\/span> <span class=\"n\">process<\/span> <span class=\"n\">stream<\/span>\n<\/code><\/pre><\/div>\n\n<p>This worked well enough for running simple commands like <code>\/usr\/bin\/ls\n-lah<\/code>. In order to get output redirection and <code>&amp;<\/code> to work, I needed to\nupgrade the program's parsing capabilities. I switched from\nrepresenting user input with a <code>string list<\/code> to a variant type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">exec<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">executable<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">arguments<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span> <span class=\"kt\">list<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">output<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">option<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span>\n\n<span class=\"k\">type<\/span> <span class=\"n\">line<\/span> <span class=\"o\">=<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">NoOp<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">ChangeDirectory<\/span> <span class=\"k\">of<\/span> <span class=\"kt\">string<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">PathChange<\/span> <span class=\"k\">of<\/span> <span class=\"kt\">string<\/span> <span class=\"kt\">list<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Executable<\/span> <span class=\"k\">of<\/span> <span class=\"n\">exec<\/span> <span class=\"kt\">list<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Quit<\/span>\n<\/code><\/pre><\/div>\n\n<p>I found the OCaml compiler (and its emacs integrations, <code>merlin<\/code> and\n<code>tuareg<\/code>) very helpful for refactoring. When I revised my types to\nmake them better reflect the data I wanted to model, type errors\nidentified all of the places I needed to update. At this point, I\nintroduced an Angstrom parser and re-implemented support for <code>cd<\/code>,\n<code>exit<\/code>, and <code>path<\/code>. That allowed me to get familiar with the parser\ncombinators <code>*&gt;<\/code>, <code>many<\/code>, and <code>choice<\/code>, before attempting the more\ncomplicated parsers needed to support <code>&amp;<\/code> and <code>&gt;<\/code>.<\/p>\n<p>The type system protected me from a number of silly mistakes, but it\nwasn't a silver bullet. I spent an hour confused about why one of my\nparsers would go into an infinite loop before realizing I needed to\nuse <code>many1<\/code> instead of <code>many<\/code>. I think this is the sort of mistake I\nwould learn to avoid if I spent more time working with Angstrom.<\/p>\n<h2>Discussion<\/h2>\n<p>As I worked through this project, I started to appreciate how OCaml\nchooses \"good defaults\" for my code (especially immutable data)\nwithout forbidding me from working in an imperative mode when I need\nto.<\/p>\n<p>For example, I found that the function responsible for running a child\nprocess was most natural to express with imperative language features:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">run_executable<\/span> <span class=\"n\">path<\/span> <span class=\"o\">{<\/span><span class=\"n\">executable<\/span><span class=\"o\">;<\/span> <span class=\"n\">arguments<\/span><span class=\"o\">;<\/span> <span class=\"n\">output<\/span><span class=\"o\">}<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">full_paths<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">map<\/span> <span class=\"o\">(<\/span><span class=\"k\">fun<\/span> <span class=\"n\">p<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">p<\/span> <span class=\"o\">^<\/span> <span class=\"s2\">&quot;\/&quot;<\/span> <span class=\"o\">^<\/span> <span class=\"n\">executable<\/span><span class=\"o\">)<\/span> <span class=\"n\">path<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">executables<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">append<\/span> <span class=\"n\">full_paths<\/span> <span class=\"o\">[<\/span><span class=\"n\">executable<\/span><span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">present<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">filter<\/span> <span class=\"n\">executable_present<\/span> <span class=\"n\">executables<\/span> <span class=\"k\">in<\/span>\n\n  <span class=\"k\">match<\/span> <span class=\"n\">present<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span><span class=\"o\">;<\/span> <span class=\"nc\">None<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">x<\/span> <span class=\"o\">::<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">match<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">fork<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"mi\">0<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Child *)<\/span>\n       <span class=\"k\">let<\/span> <span class=\"n\">out<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">output<\/span> <span class=\"k\">with<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">openfile<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">[<\/span><span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_TRUNC<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_WRONLY<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_CREAT<\/span> <span class=\"o\">]<\/span> <span class=\"mo\">0o640<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stdout<\/span>\n       <span class=\"k\">in<\/span>\n       <span class=\"k\">let<\/span> <span class=\"n\">err<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">output<\/span> <span class=\"k\">with<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stderr<\/span>\n         <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">out<\/span>\n       <span class=\"k\">in<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">dup2<\/span> <span class=\"n\">out<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stdout<\/span><span class=\"o\">;<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">dup2<\/span> <span class=\"n\">err<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stderr<\/span><span class=\"o\">;<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">execv<\/span> <span class=\"n\">x<\/span> <span class=\"o\">@@<\/span> <span class=\"nn\">Array<\/span><span class=\"p\">.<\/span><span class=\"n\">of_list<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">executable<\/span><span class=\"o\">::<\/span><span class=\"n\">arguments<\/span><span class=\"o\">;<\/span>\n    <span class=\"o\">|<\/span> <span class=\"n\">child_pid<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Parent *)<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"n\">child_pid<\/span>\n<\/code><\/pre><\/div>\n\n<p>Writing this way made it easy for me to switch between C and OCaml; in\nboth languages, we follow a pattern of calling <code>fork<\/code>, then <code>execv<\/code> in\nthe child process. The fact that I can easily re-use my knowledge of\nthe UNIX APIs across different programming languages is one of the\nmain reasons I'm excited to learn more systems programming concepts!<\/p>\n<p>Variants and pattern matching are features I miss when working in\nlanguages like Python. These features make it so easy to look at a\nfunction like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">path<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ref<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;\/bin&quot;<\/span><span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">process<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">match<\/span> <span class=\"nn\">Parser<\/span><span class=\"p\">.<\/span><span class=\"n\">parse_line<\/span> <span class=\"n\">text<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">NoOp<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">()<\/span> <span class=\"c\">(* Empty lines should just be treated as no-ops. *)<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Quit<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">exit<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">ChangeDirectory<\/span> <span class=\"n\">x<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">change_directory<\/span> <span class=\"n\">x<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">PathChange<\/span> <span class=\"n\">paths<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">cwd<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">getcwd<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n      <span class=\"n\">path<\/span> <span class=\"o\">:=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">map<\/span> <span class=\"o\">(<\/span><span class=\"n\">amend_path<\/span> <span class=\"n\">cwd<\/span><span class=\"o\">)<\/span> <span class=\"n\">paths<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Executable<\/span> <span class=\"n\">execs<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">run_executables<\/span> <span class=\"o\">!<\/span><span class=\"n\">path<\/span> <span class=\"n\">execs<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">iter<\/span> <span class=\"n\">process<\/span> <span class=\"n\">stream<\/span>\n<\/code><\/pre><\/div>\n\n<p>and quickly understand all of the different commands <code>osh<\/code> supports.<\/p>\n<p>Although it took me some time to get up and running with Angstrom, I\nstrongly prefer working with parser combinators to writing an\nimperative parser (as I've had to do in Python and Java). Angstrom\nmakes it easy to build up small parsers and test them in isolation\nbefore composing them into the larger parser you really need. If I\nplanned to develop a shell with more features, I would probably break\n<code>Parser<\/code> out into its own file with separate unit tests.<\/p>\n<h2>Feedback<\/h2>\n<p>If you give this project a try, let me know how it turned out! I'm\ninterested in adding more tutorial resources to the OCaml ecosystem,\nso feel free to post a PR or issue to\n<a href=\"https:\/\/github.com\/jsthomas\/simple-ocaml-shell\">simple-ocaml-shell<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"How I Contribute to Open Source Projects","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/oss-how-why.html","rel":"alternate"}},"published":"2021-06-27T00:00:00-04:00","updated":"2021-06-27T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-06-27:\/oss-how-why.html","summary":"<p>A short explanation of my open source process.<\/p>","content":"<p>Contributing to public projects is one of the most fulfilling aspects\nof my software development practice. It allows me to make new\nprofessional connections and gain exposure to challenges I would never\nencounter on the job. But it <em>is<\/em> effortful, especially after a full\nday of paid work. Over time, I've developed (mostly by trial and\nerror) a process that makes it easier for me to fit open source work\ninto my schedule and make this extra effort worthwhile.<\/p>\n<p>Earlier in my career I wanted to contribute to public projects but\ndidn't know how to begin. In this post, I tried to provide a concise\nsummary of the advice I wish I'd received long ago.<\/p>\n<h2>Why contribute?<\/h2>\n<p>Like most engineers, my paid work has been on years-long,\nclosed-source projects driven by deadlines and business\nrequirements. In that context, it's normal to build with the most\nstandard components possible. If your Django app needs flash messages,\nyou probably want to use the <a href=\"https:\/\/docs.djangoproject.com\/en\/3.2\/ref\/contrib\/messages\/\">messages\nframework<\/a>,\nrather than rolling your own solution; there just isn't much business\nvalue in writing something new. As a result, there are some design\nproblems you don't get to spend much time thinking about while doing paid\nwork.<\/p>\n<p>Working on OSS projects lets me to grow my skills beyond boundaries\nimposed by business concerns. For instance, working on <a href=\"https:\/\/github.com\/aantron\/dream\/issues\/43\">this\nissue<\/a> let me build a\nflash message system for a new web framework,\n<a href=\"https:\/\/aantron.github.io\/dream\/\">Dream<\/a>. Within the structure of\nthat project, I had an opportunity to study how Rails, Django, and\nPhoenix implement flash messages. Discussing the merits of these\ndifferent approaches with more experienced engineers helped me become\na better designer.<\/p>\n<p>I've also found that OSS projects are an effective way to practice the\ninvestigative skills I use on the first few months of a new job. When\nI join an organization, I have to get up to speed on new codebases\n(sometimes in a language I haven't used before).  Working on an\nunfamiliar open source project simulates these conditions, without the\naccompanying pressures of a new job.<\/p>\n<h2>How do I find new projects to work on?<\/h2>\n<p>Conferences focused on a specific programming language or family of\ntechnologies are a great way to meet maintainers. When I attended\n<a href=\"http:\/\/www.composeconference.org\/2017\/\">Compose 2017<\/a>, a\nserendipitous conversation in between sessions led to a 3-4 month\nperiod of making contributions to\n<a href=\"https:\/\/github.com\/ocsigen\/lwt\/\">lwt<\/a>, learning a lot more about\nOCaml, and this <a href=\"https:\/\/jsthomas.github.io\/map-comparison.html\">blog\npost<\/a>.<\/p>\n<p>Conferences <em>can<\/em> be a bit of a gamble. The costs of travel, lodging,\nand fees are significant. Most conferences will post their talks\nlater. Watching these is a great way to stay informed. This Strange\nLoop <a href=\"https:\/\/youtu.be\/gCWtkvDQ2ZI\">talk<\/a>, for instance, gave me a\ngood overview of the Unison programming language, which eventually\nallowed me to contribute this\n<a href=\"https:\/\/github.com\/unisonweb\/unison\/pull\/1639\">change<\/a>. This approach\nis much more efficient for finding projects that spark your interest,\nsince you can watch talks at 2x speed and skip ones that aren't\nuseful.<\/p>\n<h2>Evaluating whether a project is a good fit<\/h2>\n<p>Once I've found a project (usually on github) that I think is\ninteresting, there are a few things I check before deciding whether to\ncontribute.<\/p>\n<p>First, I look at whether the project has recent commits. If the most\nrecent commit is more than a few months old, that might mean the\nproject is abandoned. Since I'm interested in being a contributor\nrather than a maintainer, working on these repos is usually not a good\nuse of time.<\/p>\n<p>The second thing I look at are the project's pull requests. If there\nare many old, open pull requests (ones that don't have any comments),\nthis is another sign that the project might be abandoned. Looking\nthrough closed PRs, or PRs with a lot of comments, typically gives me\nsome idea of how contributors and maintainers interact. The\nmaintainers I've interacted with have been friendly and welcoming; I\navoid projects where that isn't the norm.<\/p>\n<p>Next, I'll take a look at the project's issue list. If users and\nmaintainers write clearly, it's much easier for me to make progress on\nan issue without having to ask too many questions. Issues with links\nto relevant code, minimal working examples, and repro steps are all\ngood signs.<\/p>\n<p>I also look to see whether the project has Travis or Circle CI set up,\nsince that means I can get quick feedback on a PR without talking to\nanyone. The CI systems is also helpful as a model for setting up my\ndevelopment environment; often I will look through the CI\nconfiguration in order to run my unit tests with the exact same\ndatabases\/dependencies\/settings.<\/p>\n<p>Finally, I'll take a more in-depth look at the codebase itself. At\nthis point, I'm just trying to answer basic questions, like:<\/p>\n<ul>\n<li>How is the source tree organized?<\/li>\n<li>Do most of the functions\/classes\/modules have comprehensible names?<\/li>\n<li>Where are the tests? Where would I add new tests?<\/li>\n<li>Are there comments?<\/li>\n<\/ul>\n<h2>Finding a task<\/h2>\n<p>Once I'm confident that I want to participate, my next step is to\nchoose an open issue to work on. Ones that are marked \"good first\nissue\" or \"beginner\" are great for a first contribution, and I'll\noften start with those.<\/p>\n<p>I try to keep the scope of my first contribution small. For example,\n<a href=\"https:\/\/github.com\/arenadotio\/pgx\/issues\/97\">this issue<\/a> on the OCaml\nlibrary <code>pgx<\/code> asked for someone to add support for a different\ndate-time library (in this case <code>ptime<\/code>) because not everyone can use\nJane Street's <code>Core<\/code> library. This was an ideal first issue because I\ncould use the existing <code>Core<\/code> implementation as a model for what I\nneeded to build.<\/p>\n<p>If an issue is a little bit old, it's a good idea to leave a note\nasking whether the maintainer is still interested in having it\naddressed. For example, I was interested in working on this\n<a href=\"https:\/\/github.com\/aantron\/dream\/issues\/43\">issue<\/a>, but it was a\nmonth old. Rather than jumping into an implementation that might go to\nwaste, I left a comment expressing interest and offering some design\nideas. Replies in that thread allowed me to create this <a href=\"https:\/\/github.com\/aantron\/dream\/pull\/62\">pull\nrequest<\/a>, confident in the\nknowledge that someone would want to use my work.<\/p>\n<p>Once I've picked out task, it's (finally) time to implement a\nsolution. If I can get as far as implementing some unit tests and\ngetting most of them to pass, I post a comment on the issue indicating\nthat I'm working on a pull request. Personally, I consider it best\npractice to <em>only<\/em> post one of these comments if I'm very confident\nthat I'll have a PR ready in the next few days. Conversely, no-one\nwants to duplicate effort, so it's courteous to indicate that you're\npreparing a PR.<\/p>\n<h2>Pull request and review<\/h2>\n<p>Since pull requests take time to review, I try to perform at least one\nround of self-review before opening a PR. Generally, I won't open a PR\nunless I have fairly good test coverage for my work and the tests (and\nlint steps) are passing. At a paid position, it's easy to have a\nmeeting or use slack to discuss a change. Public projects tend to be\nmore asynchronous, so it's important to read instructions carefully,\nwrite clearly, and address obvious issues on your own.<\/p>\n<p>When I write a description for my PR, I include a link to the issue it\naddresses, usually in the first sentence. If the change adds new types\nor functions, I include a summary of that as well. If there are design\ndetails I'm unsure of, I flag these with comments so that the\nreviewer(s) can discuss them with me.<\/p>\n<p>The code review process on a public project can be a little different\nfrom code review inside a company. At some jobs, I've observed an\nunspoken rule that PRs need to be more or less correct on the first or\nsecond try, otherwise you'll be considered ineffective. My sense is\nthat the review process on public projects is much more\niterative. Sometimes it isn't possible to gather all of the necessary\nrequirements until a first PR is drafted and people have something to\nreact to. It can take several rounds of revision before all of the\ninterested parties agree that the design is right.<\/p>\n<p>This <a href=\"https:\/\/github.com\/aantron\/dream\/pull\/62\">PR<\/a> for instance,\nrequired several tries to find a flash message implementation that fit\nwith the philosophy of the project. These situations are an\nopportunity to practice discussing (and justifying) your design\ndecisions with other technical-minded people. I think the key to\nsuccess with public reviews is to read reviewer's comments carefully,\nmake an effort to understand their goals, and then fit your changes to\nsupport those goals.<\/p>\n<h2>General suggestions<\/h2>\n<p>If you plan on making OSS contributions long term, I'd suggest having\nboth a schedule and dedicated hardware for your work. Working after\ndinner from 6 to 8 PM weeknights helps me get into a productive\nmindset quickly. Time-boxing my work also helps me avoid exhausting my\ninterest in a project by putting in too many consecutive hours. Using\nan inexpensive, second-hand laptop for my public projects makes it\neasy for me to suspend my work when I'm done for the night and then\nstart the next day exactly where I left off, without having to set up\nmy browser\/editor\/terminals again.<\/p>","category":{"@attributes":{"term":"OSS, Projects"}}},{"title":"Microbenchmarking Implementations of Map in OCaml","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/map-comparison.html","rel":"alternate"}},"published":"2017-06-06T00:00:00-04:00","updated":"2017-06-06T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2017-06-06:\/map-comparison.html","summary":"<p>A comparison of different implementations of map in OCaml<\/p>","content":"<p><code>Map<\/code> is one of the first higher-order functions I remember\nencountering when I learned some rudimentary functional programming\ntopics as an undergraduate. More recently I began learning OCaml. The\n<code>map<\/code>\n<a href=\"https:\/\/github.com\/ocaml\/ocaml\/blob\/2691c40f2ff9bc34912db39bc1f17045c9241473\/stdlib\/list.ml#L80-L82\">implementation<\/a>\nI found in the standard library was the textbook definition I was\nexpecting<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"o\">=<\/span> <span class=\"k\">function<\/span>\n   <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">[]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">a<\/span><span class=\"o\">::<\/span><span class=\"n\">l<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"k\">let<\/span> <span class=\"n\">r<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">a<\/span> <span class=\"k\">in<\/span> <span class=\"n\">r<\/span> <span class=\"o\">::<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"n\">l<\/span>\n<\/code><\/pre><\/div>\n\n<p>but I was surprised to learn there are actually several\nimplementations of <code>map<\/code> in the OCaml ecosystem. I wanted to know more\nabout these different implementations and their performance\ncharacteristics. This article summarizes what I learned.<\/p>\n<p>Part of my motivation to write this post arose from\n<a href=\"https:\/\/github.com\/ocsigen\/lwt\/pull\/347\">this discussion<\/a> of a pull\nrequest that proposes the default <code>map<\/code> implementation in <code>lwt<\/code> should\nbe tail recursive. After reading all of the comments, I wanted to\ndevelop experiments that would convince me whether this was a good\nidea.<\/p>\n<h1>Introduction<\/h1>\n<p>Since I'll introduce several versions of <code>map<\/code>, I'll refer to the\nimplementation above as <code>stdlib<\/code>. An important aspect of this version\nis that it isn't <em>tail recursive<\/em>. A tail recursive function uses\nrecursion in a specific way; it only calls itself as the final\noperation in the function. In OCaml, tail recursive functions get the\nbenefit of tail-call optimization so that they only use one frame on\nthe stack. In contrast, the <code>stdlib<\/code> implementation takes space on the\nstack proportional to the length of the input list. For long enough\nlists, this causes a stack overflow.<\/p>\n<p>We can make a basic tail-recursive version of <code>map<\/code> by composing two\nstandard library functions that are tail recursive: <code>List.rev_map<\/code>\n(which creates the output of <code>map<\/code>, but in reversed order) and\n<code>List.rev<\/code> which reverses lists. I'll call this naive implementation\n<code>ntr<\/code> (naive tail recursive). Compared to <code>stdlib<\/code>, <code>ntr<\/code> allocates\ntwice as much space on the heap (one list for the output of\n<code>List.rev_map<\/code>, and a second equally long list for <code>List.rev<\/code>) and\nspends additional time performing a list traversal. The benefit is\nthat with this implementation, calling <code>map<\/code> on a long list won't\nresult in a stack overflow.<\/p>\n<p>As we'll see later in the Results section, the naive tail recursive\nimplementation is, overall, slower than the <code>stdlib<\/code>\nimplementation. However, there are some optimizations we can apply to\nimprove the performance of both versions.<\/p>\n<p>The first trick I call \"unrolling\". Similar to\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Loop_unrolling\">loop unrolling in procedural languages<\/a>,\nthe idea is to use cases to <code>map<\/code> on groups of list elements so fewer\nfunction calls are needed to complete the work. For example, an\nunrolled version of <code>stdlib<\/code> looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"n\">l<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">l<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">[]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"n\">x1<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"o\">[<\/span><span class=\"n\">f1<\/span><span class=\"o\">]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"n\">x1<\/span><span class=\"o\">;<\/span> <span class=\"n\">x2<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x2<\/span> <span class=\"k\">in<\/span>\n    <span class=\"o\">[<\/span><span class=\"n\">f1<\/span><span class=\"o\">;<\/span> <span class=\"n\">f2<\/span><span class=\"o\">]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">x1<\/span> <span class=\"o\">::<\/span> <span class=\"n\">x2<\/span> <span class=\"o\">::<\/span> <span class=\"n\">x3<\/span> <span class=\"o\">::<\/span> <span class=\"n\">tl<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x2<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f3<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x3<\/span> <span class=\"k\">in<\/span>\n    <span class=\"n\">f1<\/span> <span class=\"o\">::<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">::<\/span> <span class=\"n\">f3<\/span> <span class=\"o\">::<\/span> <span class=\"n\">map<\/span> <span class=\"n\">tl<\/span>\n<\/code><\/pre><\/div>\n\n<p>We get to choose how many elements to unroll (here I picked 3); some\nprofiling is needed to decide the most appropriate number.<\/p>\n<p>The second trick I call \"hybridizing\". The <code>stdlib<\/code> version is faster,\nbut isn't safe for long lists. The tail recursive implementation is\nslow, but safe for all lists. When we \"hybridize\" the two, we use the\nfaster version up to some fixed number of elements (e.g. 1000), and\nthen switch to the safe version for the remainder of the list.<\/p>\n<p>These two optimizations are useful for understanding the\nimplementations of <code>map<\/code> we find in other libraries. For example, both\n<a href=\"https:\/\/github.com\/janestreet\/base\/blob\/f10483e957206dc6b656a28ffec667d8b068c149\/src\/list.ml#L311-L345\"><code>base<\/code><\/a>\nand\n<a href=\"https:\/\/github.com\/c-cube\/ocaml-containers\/blob\/d659ba677e3dbd95430f59b3794ac2f2a5677d61\/src\/core\/CCList.ml#L20-L37\"><code>containers<\/code><\/a>\nuse an unrolled <code>stdlib<\/code>-style <code>map<\/code>, hybridized with an\n<code>ntr<\/code>-style <code>map<\/code>.<\/p>\n<p>Looking at <code>ntr<\/code>, one might ask: Is it strictly necessary to use\nadditional heap space to get the implementation to be tail recursive?\nThe answer is no. The <code>batteries<\/code> package\n<a href=\"https:\/\/github.com\/ocaml-batteries-team\/batteries-included\/blob\/c10c65a203a7590b15b9a370f66e8c2884817428\/src\/batList.mlv#L163-L173\">implements <code>map<\/code><\/a>\nso that the work is done by a single tail recursive function, creating\none new list on the heap. To achieve this, the implementation uses\nmutable state and casting to avoid a second list traversal\n(specifically,\n<a href=\"https:\/\/github.com\/ocaml-batteries-team\/batteries-included\/blob\/c10c65a203a7590b15b9a370f66e8c2884817428\/src\/batList.mlv#L69\">here<\/a>).<\/p>\n<p>As with any optimization, one makes tradeoffs between elegance,\nperformance, and the language features one considers acceptable to\nuse. I wanted to know:<\/p>\n<ul>\n<li>\n<p>Which version is the fastest in practice?<\/p>\n<\/li>\n<li>\n<p>How much speed does one lose using the safer tail recursive version?<\/p>\n<\/li>\n<\/ul>\n<p>Both <code>base<\/code> and <code>containers<\/code> decided to hybridize with an <code>ntr<\/code>-style\n<code>map<\/code> for safety. But the <code>batteries<\/code> implementation is also robust to\nstack overflow. That led to one final question:<\/p>\n<ul>\n<li>How fast is an unrolled <code>stdlib<\/code>-style <code>map<\/code> hybridized with a\n  <code>batteries<\/code>-style <code>map<\/code>?<\/li>\n<\/ul>\n<h1>Experimental Setup<\/h1>\n<p>In 2014, Jane Street introduced a\n<a href=\"https:\/\/github.com\/janestreet\/core_bench\">library<\/a> for\nmicrobenchmarking called <code>core_bench<\/code>. As they explain\n<a href=\"https:\/\/blogs.janestreet.com\/core_bench-micro-benchmarking-for-ocaml\/\">on their blog<\/a>,\n<code>core_bench<\/code> is intended to measure the performance of small pieces of\nOCaml code. This library helps developers to better understand the\ncost of individual operations, like <code>map<\/code>.<\/p>\n<p>There are a couple benefits to measuring <code>map<\/code> implementations with\n<code>core_bench<\/code>.<\/p>\n<ol>\n<li>\n<p>The library makes it easy to track both time and use of the heap.<\/p>\n<\/li>\n<li>\n<p>Once you specify your test, <code>core_bench<\/code> automatically provides\n   many <a href=\"https:\/\/github.com\/janestreet\/core_bench\/wiki\/Getting-Started-with-Core_bench\">command line\n   options<\/a>\n   to help you present your test data in different ways.<\/p>\n<\/li>\n<li>\n<p>The library uses statistical techniques (bootstrapping and linear\n   regression) to reduce many runs worth of data to a small number of\n   meaningful performance metrics that account for the amortized cost\n   of garbage collection and error introduced by system activity.<\/p>\n<\/li>\n<\/ol>\n<p>I wrote\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/maptest.ml\">this program<\/a>\nto compare performance between the six implementations I described\nabove. The program includes the batteries-hybrid I described above,\nwhich I'll refer to as <code>batt-hybr<\/code>. Other test details:<\/p>\n<ul>\n<li>I tested each algorithm against lists of lengths <span class=\"math\">\\(N=10^2, 10^3,\n  10^4\\)<\/span> and <span class=\"math\">\\(10^5\\)<\/span>. On my system, <span class=\"math\">\\(N=10^5\\)<\/span> was the highest power of 10\n  for which the <code>stdlib<\/code> implementation did not fail due to a stack\n  overflow.<\/li>\n<li>Each list consisted of integer elements (all 0), and the function\n  mapped onto the list simply added one to each element.<\/li>\n<li>I ran these tests on a Lenovo X220, Intel Core i5-2520M CPU (2.50GHz \u00d7\n  4 cores), with 4GB RAM.<\/li>\n<li>I used the OCaml 4.03.0 compiler, and compiled to native code\n  without using <code>flambda<\/code>. (<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/makefile\">This\n  makefile<\/a>\n  gives the full specifications.)<\/li>\n<\/ul>\n<h1>Results<\/h1>\n<p>For each list size, <code>core_bench<\/code> produces a table with several metrics besides time:<\/p>\n<ul>\n<li><code>mWd<\/code> : Words allocated on the minor heap.<\/li>\n<li><code>mjWd<\/code> : Words allocated on the major heap.<\/li>\n<li><code>Prom<\/code> : Words promoted from minor to major heap.<\/li>\n<\/ul>\n<p>The library also allows us to produce 95% confidence intervals and\n<span class=\"math\">\\(R^2\\)<\/span> values for the time estimates.<\/p>\n<p><strong>Map Benchmark, N = 100<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     1.00 \u2502 741.20ns \u2502 -0.23% +0.22% \u2502 609.01w \u2502    0.53w \u2502    0.53w \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502 439.55ns \u2502 -0.64% +0.67% \u2502 304.03w \u2502    0.17w \u2502    0.17w \u2502     59.30% \u2502\n\u2502 batteries  \u2502     1.00 \u2502 581.65ns \u2502 -0.14% +0.16% \u2502 309.01w \u2502    0.35w \u2502    0.35w \u2502     78.47% \u2502\n\u2502 base       \u2502     1.00 \u2502 438.63ns \u2502 -0.19% +0.20% \u2502 304.03w \u2502    0.16w \u2502    0.16w \u2502     59.18% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502 610.45ns \u2502 -0.10% +0.11% \u2502 304.01w \u2502    0.17w \u2502    0.17w \u2502     82.36% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502 426.76ns \u2502 -0.15% +0.17% \u2502 304.03w \u2502    0.17w \u2502    0.17w \u2502     57.58% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 1000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     1.00 \u2502   8.84us \u2502 -0.14% +0.15% \u2502  6.01kw \u2502   52.08w \u2502   52.08w \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502   5.07us \u2502 -0.13% +0.15% \u2502  3.00kw \u2502   17.23w \u2502   17.23w \u2502     57.34% \u2502\n\u2502 batteries  \u2502     1.00 \u2502   6.57us \u2502 -0.14% +0.14% \u2502  3.01kw \u2502   34.71w \u2502   34.71w \u2502     74.32% \u2502\n\u2502 base       \u2502     1.00 \u2502   4.99us \u2502 -0.20% +0.24% \u2502  3.00kw \u2502   17.08w \u2502   17.08w \u2502     56.44% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502   6.84us \u2502 -0.10% +0.10% \u2502  3.00kw \u2502   17.22w \u2502   17.22w \u2502     77.34% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502   4.96us \u2502 -0.13% +0.13% \u2502  3.00kw \u2502   17.07w \u2502   17.07w \u2502     56.10% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 10,000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     0.99 \u2502 203.11us \u2502 -0.45% +0.53% \u2502 60.01kw \u2502   5.40kw \u2502   5.40kw \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502 144.95us \u2502 -0.50% +0.60% \u2502 48.01kw \u2502   3.04kw \u2502   3.04kw \u2502     71.37% \u2502\n\u2502 batteries  \u2502     1.00 \u2502 136.87us \u2502 -0.51% +0.63% \u2502 30.01kw \u2502   3.64kw \u2502   3.64kw \u2502     67.39% \u2502\n\u2502 base       \u2502     1.00 \u2502 130.85us \u2502 -0.34% +0.39% \u2502 44.98kw \u2502   2.66kw \u2502   2.66kw \u2502     64.42% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502 118.70us \u2502 -0.30% +0.29% \u2502 30.00kw \u2502   1.80kw \u2502   1.80kw \u2502     58.44% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502 106.91us \u2502 -0.42% +0.52% \u2502 30.01kw \u2502   2.22kw \u2502   2.22kw \u2502     52.64% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 100,000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502  mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     0.98 \u2502  10.27ms \u2502 -2.39% +2.32% \u2502 600.02kw \u2502 411.83kw \u2502 411.83kw \u2502     94.33% \u2502\n\u2502 containers \u2502     0.99 \u2502  10.62ms \u2502 -2.19% +1.83% \u2502 588.02kw \u2502 404.91kw \u2502 404.91kw \u2502     97.61% \u2502\n\u2502 batteries  \u2502     1.00 \u2502   7.19ms \u2502 -0.78% +0.79% \u2502 300.02kw \u2502 300.35kw \u2502 300.35kw \u2502     66.02% \u2502\n\u2502 base       \u2502     0.99 \u2502  10.88ms \u2502 -1.54% +1.41% \u2502 584.99kw \u2502 397.60kw \u2502 397.60kw \u2502    100.00% \u2502\n\u2502 stdlib     \u2502     0.99 \u2502   6.33ms \u2502 -1.08% +1.07% \u2502 300.01kw \u2502 171.73kw \u2502 171.73kw \u2502     58.18% \u2502\n\u2502 batt-hybr  \u2502     0.93 \u2502   6.09ms \u2502 -4.30% +4.63% \u2502 300.02kw \u2502 285.46kw \u2502 285.46kw \u2502     55.93% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p>A few things I noticed about the data:<\/p>\n<ul>\n<li>\n<p>The tail recursive implementation is slow, but not always the\n  slowest. In the <span class=\"math\">\\(N=10^5\\)<\/span> case, <code>ntr<\/code>,<code>base<\/code>, and <code>containers<\/code> show\n  similar performance; this makes sense given they have the same\n  behavior after a prefix of the list.<\/p>\n<\/li>\n<li>\n<p>For short lists, <code>base<\/code>, <code>containers<\/code>, and <code>batt-hybr<\/code> are fastest,\n  likely because of unrolling.<\/p>\n<\/li>\n<li>\n<p>We can see from the <code>mWd<\/code> and <code>mjWd<\/code> columns that <code>ntr<\/code> uses the\n  most heap space, as we would expect.<\/p>\n<\/li>\n<li>\n<p>As we increase the size of the list, <code>stdlib<\/code> gets faster relative\n  to <code>ntr<\/code>; I suspect this can be attributed to the cost of garbage\n  collection.<\/p>\n<\/li>\n<li>\n<p>Overall, <code>batt-hybr<\/code> appears to have the best performance (though in\n  the <span class=\"math\">\\(N=10^5\\)<\/span> case, the confidence interval is large enough that we\n  can't conclude <code>batt-hybr<\/code> is faster than <code>stdlib<\/code>, and the <span class=\"math\">\\(R^2\\)<\/span>\n  value is a bit low).<\/p>\n<\/li>\n<\/ul>\n<h1>Conclusions<\/h1>\n<p>The data above suggest three main findings:<\/p>\n<ol>\n<li>\n<p>The stack-based standard library implementation of <code>map<\/code> is faster\n   than the naive tail recursive implementation, taking about 60-80%\n   of the time to do the same work depending on the size of the list.<\/p>\n<\/li>\n<li>\n<p>There are clear benefits to both unrolling and\n   hybridizing. Hybridizing lets us take an implementation that\n   performs well on long lists (<code>batteries<\/code>), and make it even better\n   by combining it with one that's fast on short lists, to produce\n   <code>batt-hybr<\/code>.<\/p>\n<\/li>\n<li>\n<p>Overall, the data show we don't have to give up safety (resistance\n   to stack overflow) to get better performance. A tail recursive\n   implementation can be quite competitive, albeit more complex.<\/p>\n<\/li>\n<\/ol>\n<h1>Discussion<\/h1>\n<p>A follow up question to this analysis, in the context of the\ndiscussion of <code>Lwt_list.map_p<\/code> is: \"How significant is the cost of\n<code>map<\/code> compared to other operations?\" To partially address this, I\nwrote\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/bufftest.ml\">another program<\/a>\nthat measures how long it takes to write 4096 bytes to a Unix pipe\nusing <code>Lwt_unix.write<\/code>, and then read it back using <code>Lwt_unix.read<\/code>. Using\n<code>core_bench<\/code>, I found:<\/p>\n<p><strong>Unix Pipe Read\/Write Benchmark<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502    1.00 \u2502 893.33ns \u2502 -0.16% +0.18% \u2502  56.00w \u2502    100.00% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p>It seems reasonable to estimate that <code>Lwt_list.map_p<\/code> would primarily\nbe applied to IO operations like the ones in this experiment. In that\ncase, the data suggest the cost per element of applying the slowest\n<code>map<\/code> implementation (<code>ntr<\/code>) is about 0.82% of the cost of one 4KB\nread\/write operation on a unix pipe. In the context of <code>Lwt<\/code>, it seems\nreasonable to conclude the implementation of <code>map<\/code> isn't a significant\nconcern; the real cost is performing IO. In light of that, it seems\npreferable to use an implementation that cannot cause a stack\noverflow.<\/p>\n<p>A second question that might be asked about this analysis is: \"Was it\nnecessary to introduce the added complexity of <code>core_bench<\/code> to measure\nthe performance of <code>map<\/code>?\" For example, one might set up a performance\ntest with just successive calls to <code>Time.now<\/code> or\n<code>Unix.gettimeofday<\/code>. In an earlier draft of this article, I tried such\nan\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/profile.ml\">approach<\/a>,\nproducing some misleading data. In that test, I did a full garbage\ncollection in between runs (applications of <code>map<\/code>), which suppressed\nthat (nontrivial) cost and made the tail recursive implementation\nappear quite fast. <code>core_bench<\/code> does a much better job incorporating\nthe cost of garbage collection by varying the number of test runs\nperformed in a row and then establishing a trend (with linear\nregression) that reflects the amortized cost of garbage collection per\nrun.<\/p>\n<p>One interesting finding did arise from my earlier tests: for short\nlists, allocating memory on the heap actually appears to be faster\nthan creating frames on the stack. Since the tests perform a full\ngarbage collection between test runs, the timings show only the cost\nof allocating space on the heap. This produced data like the\nfollowing:<\/p>\n<p><strong>Summary Statistics, <span class=\"math\">\\(N=10^3\\)<\/span> Garbage Collected Map Benchmark Times (\u03bcs)<\/strong><\/p>\n<table class=\"dataframe\">\n  <thead>\n    <tr>\n      <th><\/th>\n      <th>Std. Lib.<\/th>\n      <th>NTR<\/th>\n      <th>Base<\/th>\n      <th>Batteries<\/th>\n      <th>Containers<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <th>Mean<\/th>\n      <td>27.18<\/td>\n      <td>27.21<\/td>\n      <td>11.23<\/td>\n      <td>19.03<\/td>\n      <td>13.06<\/td>\n    <\/tr>\n    <tr>\n      <th>Min<\/th>\n      <td>15.97<\/td>\n      <td>14.07<\/td>\n      <td>6.91<\/td>\n      <td>9.06<\/td>\n      <td>7.87<\/td>\n    <\/tr>\n    <tr>\n      <th>25%<\/th>\n      <td>18.84<\/td>\n      <td>17.88<\/td>\n      <td>7.15<\/td>\n      <td>10.97<\/td>\n      <td>10.01<\/td>\n    <\/tr>\n    <tr>\n      <th>50%<\/th>\n      <td>20.03<\/td>\n      <td>19.07<\/td>\n      <td>8.11<\/td>\n      <td>15.50<\/td>\n      <td>10.01<\/td>\n    <\/tr>\n    <tr>\n      <th>75%<\/th>\n      <td>23.13<\/td>\n      <td>22.17<\/td>\n      <td>12.87<\/td>\n      <td>18.84<\/td>\n      <td>10.97<\/td>\n    <\/tr>\n    <tr>\n      <th>Max<\/th>\n      <td>849.01<\/td>\n      <td>576.02<\/td>\n      <td>379.80<\/td>\n      <td>622.03<\/td>\n      <td>434.88<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><strong>Summary Statistics, <span class=\"math\">\\(N=10^4\\)<\/span> Garbage Collected Map Benchmark Times (\u03bcs)<\/strong><\/p>\n<table class=\"dataframe\">\n  <thead>\n    <tr>\n      <th><\/th>\n      <th>Std. Lib.<\/th>\n      <th>NTR<\/th>\n      <th>Base<\/th>\n      <th>Batteries<\/th>\n      <th>Containers<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <th>Mean<\/th>\n      <td>230.23<\/td>\n      <td>216.60<\/td>\n      <td>141.39<\/td>\n      <td>144.59<\/td>\n      <td>161.56<\/td>\n    <\/tr>\n    <tr>\n      <th>Min<\/th>\n      <td>77.01<\/td>\n      <td>73.91<\/td>\n      <td>61.04<\/td>\n      <td>54.84<\/td>\n      <td>63.18<\/td>\n    <\/tr>\n    <tr>\n      <th>25%<\/th>\n      <td>97.04<\/td>\n      <td>86.07<\/td>\n      <td>67.95<\/td>\n      <td>58.89<\/td>\n      <td>70.81<\/td>\n    <\/tr>\n    <tr>\n      <th>50%<\/th>\n      <td>121.95<\/td>\n      <td>99.90<\/td>\n      <td>75.10<\/td>\n      <td>61.99<\/td>\n      <td>77.01<\/td>\n    <\/tr>\n    <tr>\n      <th>75%<\/th>\n      <td>193.83<\/td>\n      <td>284.91<\/td>\n      <td>148.59<\/td>\n      <td>118.26<\/td>\n      <td>175.24<\/td>\n    <\/tr>\n    <tr>\n      <th>Max<\/th>\n      <td>12719.87<\/td>\n      <td>2753.97<\/td>\n      <td>2960.21<\/td>\n      <td>3616.09<\/td>\n      <td>13603.93<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p>When we ignore the time spent on garbage collection, we see that <code>ntr<\/code>\nis surprisingly competitive, especially in comparison with <code>stdlib<\/code>;\nthe difference between the two implementations, of course, is that\n<code>ntr<\/code> allocates more memory on the heap while <code>stdlib<\/code> creates more\nstack frames.<\/p>\n<h2>Notes<\/h2>\n<p>Thanks to <a href=\"https:\/\/github.com\/aantron\">Anton Bachin<\/a> and\n<a href=\"https:\/\/github.com\/c-cube\/\">Simon Cruanes<\/a> for reading drafts of this\npost.<\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Refactoring Python Code","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/mgptree-refactor.html","rel":"alternate"}},"published":"2017-05-01T00:00:00-04:00","updated":"2017-05-01T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2017-05-01:\/mgptree-refactor.html","summary":"<p>Refactoring some python code from many years ago.<\/p>","content":"<p>Recently, a friend from grad-school asked me about an\n<a href=\"https:\/\/github.com\/jsthomas\/mgptree\">experimental python data visualization tool<\/a>\nI wrote in 2012. Since the code had rotted (to the point that it no\nlonger worked), and my understanding of python has changed quite a bit\nsince I originally wrote it, I thought this would be a good\nopportunity to write about my current processes for debugging and refactoring.<\/p>\n<h2>What's this supposed to do again?<\/h2>\n<p>The premise of the program is pretty simple:<\/p>\n<ol>\n<li>\n<p>The\n   <a href=\"https:\/\/www.genealogy.math.ndsu.nodak.edu\/\">Mathematics Genealogy Project (MGP)<\/a>\n   lets us search for advisor-advisee relationships between names.<\/p>\n<\/li>\n<li>\n<p>We want to take a list of names <span class=\"math\">\\(L\\)<\/span> and an integer <span class=\"math\">\\(n\\)<\/span>, and look up\n   <span class=\"math\">\\(n\\)<\/span> generations of mathematicians, starting from <span class=\"math\">\\(L\\)<\/span>.<\/p>\n<\/li>\n<li>\n<p>Then, we want to render the digraph of advisee-advisor\n   relationships using the <a href=\"http:\/\/graphviz.org\/\"><code>graphviz<\/code><\/a> program\n   <code>dot<\/code>.<\/p>\n<\/li>\n<\/ol>\n<p>Looking at this code it's surprising some of the things I did and\ndidn't know:<\/p>\n<ol>\n<li>\n<p>Prior to 2014, I wasn't in the habit of using virtual environments\n   and <code>pip<\/code>. For this project, that's not really a big deal because\n   there aren't a lot of dependencies.<\/p>\n<\/li>\n<li>\n<p>I wasn't aware of <code>pylint<\/code>. Today, I find that <code>pylint<\/code> makes it a\n   lot easier to write clean python and refactor existing code.<\/p>\n<\/li>\n<\/ol>\n<p>Some things that haven't changed:<\/p>\n<ol>\n<li>\n<p>I still think graphviz is really great. It makes plotting directed\n   graphs <em>so<\/em> easy, and it's easy to decorate them with a lot of\n   metadata.<\/p>\n<\/li>\n<li>\n<p><code>argparse<\/code> makes it easy to write a command line interface that\n   works just like other familiar unix tools. I especially like that\n   adds <code>-h<\/code> options for displaying help, which are invaluable when\n   building a more extensive CLI tool.<\/p>\n<\/li>\n<\/ol>\n<h2>Phase 1: Cleaning up lint issues.<\/h2>\n<p>Whenever I'm starting on unfamiliar python code, I like to begin with\n<code>pylint<\/code>'s suggestions.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">```<\/span>\n<span class=\"o\">...<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">384<\/span><span class=\"p\">,<\/span> <span class=\"mi\">4<\/span><span class=\"p\">:<\/span> <span class=\"n\">Invalid<\/span> <span class=\"n\">method<\/span> <span class=\"n\">name<\/span> <span class=\"s2\">&quot;extractPersonalData&quot;<\/span> <span class=\"p\">(<\/span><span class=\"n\">invalid<\/span><span class=\"o\">-<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">384<\/span><span class=\"p\">,<\/span> <span class=\"mi\">4<\/span><span class=\"p\">:<\/span> <span class=\"n\">Missing<\/span> <span class=\"n\">method<\/span> <span class=\"n\">docstring<\/span> <span class=\"p\">(<\/span><span class=\"n\">missing<\/span><span class=\"o\">-<\/span><span class=\"n\">docstring<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">391<\/span><span class=\"p\">,<\/span><span class=\"mi\">11<\/span><span class=\"p\">:<\/span> <span class=\"n\">Do<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">use<\/span> <span class=\"err\">`<\/span><span class=\"n\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">SEQUENCE<\/span><span class=\"p\">)<\/span><span class=\"err\">`<\/span> <span class=\"k\">as<\/span> <span class=\"n\">condition<\/span> <span class=\"n\">value<\/span> <span class=\"p\">(<\/span><span class=\"n\">len<\/span><span class=\"o\">-<\/span><span class=\"k\">as<\/span><span class=\"o\">-<\/span><span class=\"n\">condition<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">395<\/span><span class=\"p\">,<\/span><span class=\"mi\">11<\/span><span class=\"p\">:<\/span> <span class=\"n\">Do<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">use<\/span> <span class=\"err\">`<\/span><span class=\"n\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">SEQUENCE<\/span><span class=\"p\">)<\/span><span class=\"err\">`<\/span> <span class=\"k\">as<\/span> <span class=\"n\">condition<\/span> <span class=\"n\">value<\/span> <span class=\"p\">(<\/span><span class=\"n\">len<\/span><span class=\"o\">-<\/span><span class=\"k\">as<\/span><span class=\"o\">-<\/span><span class=\"n\">condition<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">399<\/span><span class=\"p\">,<\/span><span class=\"mi\">11<\/span><span class=\"p\">:<\/span> <span class=\"n\">Do<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">use<\/span> <span class=\"err\">`<\/span><span class=\"n\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">SEQUENCE<\/span><span class=\"p\">)<\/span><span class=\"err\">`<\/span> <span class=\"k\">as<\/span> <span class=\"n\">condition<\/span> <span class=\"n\">value<\/span> <span class=\"p\">(<\/span><span class=\"n\">len<\/span><span class=\"o\">-<\/span><span class=\"k\">as<\/span><span class=\"o\">-<\/span><span class=\"n\">condition<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">402<\/span><span class=\"p\">,<\/span> <span class=\"mi\">4<\/span><span class=\"p\">:<\/span> <span class=\"n\">Missing<\/span> <span class=\"n\">method<\/span> <span class=\"n\">docstring<\/span> <span class=\"p\">(<\/span><span class=\"n\">missing<\/span><span class=\"o\">-<\/span><span class=\"n\">docstring<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">C<\/span><span class=\"p\">:<\/span><span class=\"mi\">405<\/span><span class=\"p\">,<\/span> <span class=\"mi\">4<\/span><span class=\"p\">:<\/span> <span class=\"n\">Missing<\/span> <span class=\"n\">method<\/span> <span class=\"n\">docstring<\/span> <span class=\"p\">(<\/span><span class=\"n\">missing<\/span><span class=\"o\">-<\/span><span class=\"n\">docstring<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">W<\/span><span class=\"p\">:<\/span><span class=\"mi\">408<\/span><span class=\"p\">,<\/span><span class=\"mi\">12<\/span><span class=\"p\">:<\/span> <span class=\"n\">Unused<\/span> <span class=\"n\">variable<\/span> <span class=\"s1\">&#39;name&#39;<\/span> <span class=\"p\">(<\/span><span class=\"n\">unused<\/span><span class=\"o\">-<\/span><span class=\"n\">variable<\/span><span class=\"p\">)<\/span>\n\n<span class=\"o\">---------------------------------------------------------------------<\/span>\n<span class=\"n\">Your<\/span> <span class=\"n\">code<\/span> <span class=\"n\">has<\/span> <span class=\"n\">been<\/span> <span class=\"n\">rated<\/span> <span class=\"n\">at<\/span> <span class=\"o\">-<\/span><span class=\"mf\">1.83<\/span><span class=\"o\">\/<\/span><span class=\"mi\">10<\/span>\n<span class=\"err\">```<\/span>\n<\/code><\/pre><\/div>\n\n<p>Pylint scored my original code -1.83\/10. D'oh. It turns out one of the\nthings I wasn't following in 2012 was PEP8, which means I had a lot of\nformatting\/whitespace issues. Fixing these, my score rose to\n6.94\/10.<\/p>\n<p>One thing that I really like about <code>pylint<\/code> is how it dramatically\nsimplifies finding unused variables in my code. Sometimes, I even use\nthis to help me refactor more systematically: First I change whatever\nlines I planned to simplify, then I let <code>pylint<\/code> confirm that I can\nget rid of the variables I'd planned to eliminate. It turns out I had\nfour unused variables in 430 lines of code, all easy to fix.<\/p>\n<p>Another convention I wasn't following in 2012 is the use of\ndocstrings. Instead, I was writing big block comments, like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">################################################################################<\/span>\n<span class=\"c1\"># Procedure: validate_scrape<\/span>\n<span class=\"c1\">#<\/span>\n<span class=\"c1\"># Input: Parser and options objects from optparse<\/span>\n<span class=\"c1\">#<\/span>\n<span class=\"c1\"># Output: A list of well-formed name tuples.<\/span>\n<span class=\"c1\">#<\/span>\n<span class=\"c1\"># Effects: Checks the options object to confirm the inputs are well formed.<\/span>\n<span class=\"c1\">#<\/span>\n<span class=\"c1\">################################################################################<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now that I work with jupyter and ipython more often, I have a better\nappreciation for docstrings. It's really helpful to be able to do\n<code>function_i_dont_remember ?<\/code> at a REPL and immediately pull up\ndocumentation without context switching.<\/p>\n<h2>Phase 2: Cleaning up the output.<\/h2>\n<p>After fixing documentation, the next issue I wanted to improve was the\nscript's lack of logging. For some reason, I'd thought it would be a\ngood idea to send everything directly to <code>stdout<\/code> or <code>stderr<\/code>. I even\nadded a <code>verbose<\/code> command line flag, and then introduced conditionals\nin my code, like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">if<\/span> <span class=\"n\">OPTIONS<\/span><span class=\"o\">.<\/span><span class=\"n\">verbose_on<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">sys<\/span><span class=\"o\">.<\/span><span class=\"n\">stdout<\/span><span class=\"o\">.<\/span><span class=\"n\">write<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Searching MGP for <\/span><span class=\"si\">%s<\/span><span class=\"s2\">, <\/span><span class=\"si\">%s<\/span><span class=\"s2\">, <\/span><span class=\"si\">%s<\/span><span class=\"s2\">.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">%<\/span> <span class=\"p\">(<\/span><span class=\"n\">last<\/span><span class=\"p\">,<\/span> <span class=\"n\">first<\/span><span class=\"p\">,<\/span> <span class=\"n\">middle<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>To simplify this, I introduced the <code>logging<\/code> package with a simple\nconfiguration:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">logging<\/span><span class=\"o\">.<\/span><span class=\"n\">basicConfig<\/span><span class=\"p\">(<\/span><span class=\"n\">level<\/span><span class=\"o\">=<\/span><span class=\"n\">logging<\/span><span class=\"o\">.<\/span><span class=\"n\">INFO<\/span><span class=\"p\">,<\/span>\n                    <span class=\"nb\">format<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;<\/span><span class=\"si\">%(asctime)s<\/span><span class=\"s1\"> <\/span><span class=\"si\">%(message)s<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">,<\/span>\n                    <span class=\"n\">datefmt<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;%m\/<\/span><span class=\"si\">%d<\/span><span class=\"s1\">\/%Y %I:%M:%S %p&#39;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>which let me write logs at several different levels whose visibility\ncan be adjusted in the configuration.<\/p>\n<h2>Phase 3: Fixing bugs.<\/h2>\n<p>At this point, I'd resolved most of the obvious issues I wanted to\nfix, and narrowed down <code>pylint<\/code>'s suggestions to four issues, two of\nwhich were TODOs I'd notice while addressing other issues:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>************* Module mgptree\nW: 58, 0: TODO: Refactor options to be either completely global or not. (fixme)\nW:158, 0: TODO: Consider refactor here. (fixme)\nW: 36, 4: Using the global statement (global-statement)\nR:208, 0: Too many instance attributes (8\/7) (too-many-instance-attributes)\n\n--------------------------------------------------------------------\nYour code has been rated at 9.77\/10\n<\/code><\/pre><\/div>\n\n<p>Fixing the whitespace\/formatting issues turned out to be a good way to\nre-familiarize myself with the code before attempting to fix the\nfunctional issues.<\/p>\n<p>After running <code>mgptree<\/code> on a couple simple examples and looking at the\nlogs, I realized that the main functional issue was in the function\n<code>fetch_id_num<\/code>. This function is supposed to take a tuple of names\n(first, middle, and last) and determine the ID number of the\nmathematician with that name in the MGP service (if the lookup fails\nor returns multiple answers, we return <code>None<\/code>). The function is\nsupposed to do this by using <code>requests<\/code> to make a POST to the URL\nassociated with the PHP script that handles users' searches on the MGP\nsite, and then scraping the resulting reply.<\/p>\n<p>Looking at the MGP website, it didn't appear to be very different from\nwhat I remembered seeing in 2012, so I was puzzled why my scraping\ncode had stopped working. After running my function a few times in an\n<code>ipython<\/code> shell, I realized my main error was my URL. Like a lot of\nwebsites, the math genealogy has moved to HTTPS since 2012. Fixing\nthat and one other formatting change in the pages' <code>&lt;title&gt;<\/code> section\nand my scraping code was working properly again.<\/p>\n<h2>Wrapping Up<\/h2>\n<p>Overall, the improvements I made to my script were pretty trivial,\nbut they illustrate some practices that I think are really helpful for\nincreasing one's personal productivity:<\/p>\n<ol>\n<li>\n<p><em>Restoring an Invariant<\/em>: When I don't know what to do next (or\n   where to start), I find <code>pylint<\/code> and <code>nosetests<\/code> are great\n   guides. Both tools specify an invariant (no lint errors above a\n   certain level, all unit tests passing, etc.) that should be\n   maintained whenever code gets committed. If the invariant isn't\n   satisfied, the next steps are clear: Investigate why, and fix it.<\/p>\n<\/li>\n<li>\n<p><em>One Thing a Time:<\/em> Even though my changes were simple, I made a\n   total of 8 commits to get my code back in working order. Each one\n   focusses on a single issue I wanted to improve in the code\n   (i.e. remove all whitespace lint errors). I find it can be really\n   easy to start \"improving\" two or three issues at the same time, and\n   then do a poor job on all of them (or get stuck). For me, following\n   the rule of one issue per commit has been a great way to stay\n   organized and break larger problems into manageable pieces.<\/p>\n<\/li>\n<\/ol>\n<p>I can see a couple of areas I might want to improve in the future. It\nwould be nice to to store scraped data in an <code>sqlite<\/code> database, which\nmight simplify computing other graph-based presentations of the\ndataset (for example, finding all of the students descended from a\nparticular mathematician). It might also be cool to convert this to a\ndjango or flask app, so that people unfamiliar with the command line\ncan generate their own graphs.<\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":{"@attributes":{"term":"Python, Projects, Refactoring"}}},{"title":"A Mathematics Geneaology Project Visualizer","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/math-genealogy-visualizer.html","rel":"alternate"}},"published":"2014-04-02T00:00:00-04:00","updated":"2014-04-02T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2014-04-02:\/math-genealogy-visualizer.html","summary":"<p>A program to visualize data from the Mathematics Geneaology Project<\/p>","content":"<p>The\n<a href=\"http:\/\/genealogy.math.ndsu.nodak.edu\/\">Mathematics Geneaology Project<\/a>\n(MGP) is a publicly searchable database that records advisor-advisee\nrelations between mathematicians. Their website is interesting,\nparticularly if you're interested in the history of\nmathematics. Unfortunately, their website is also mostly text-based;\nthere isn't a way to visualize the relationships between large groups\nof people.<\/p>\n<p>I've created a tool that produces a directed graph displaying the\nadvisor-advisee relations stored in the MGP database. I created this\ntool in 2012 in order to learn about how to process data from the web\nusing python.<\/p>\n<h2>Example Output<\/h2>\n<p>After reading the steps below, you should be able to produce a picture\nlike the one below.<\/p>\n<p><img alt=\"A genealogical tree\" src=\"https:\/\/jsthomas.github.io\/images\/mgptree\/gauss.png\"><\/p>\n<p>Naturally, the real purpose of the tool is to make much bigger graphs\nthan this!<\/p>\n<h2>Download<\/h2>\n<p>You will need the following:<\/p>\n<ol>\n<li>\n<p>A copy of my python script which you can <a href=\"https:\/\/github.com\/jsthomas\/mgptree\">download here<\/a>.<\/p>\n<\/li>\n<li>\n<p>An installation of <a href=\"http:\/\/www.graphviz.org\/\">graphviz<\/a> (this\nprogram takes care of the actual graph drawing).<\/p>\n<\/li>\n<li>\n<p>Basic knowledge of the command line.<\/p>\n<\/li>\n<\/ol>\n<p>On an Ubuntu machine, these dependencies (<code>graphviz<\/code> and <code>requests<\/code>)\ncan be installed via:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$ sudo apt install virtualenv graphviz\n$ virtualenv venv\n$ venv\/bin\/activate\n<span class=\"o\">(<\/span>venv<span class=\"o\">)<\/span> $ pip install requirements.txt\n<\/code><\/pre><\/div>\n\n<h2>Usage Example<\/h2>\n<p>The easiest way to learn how to use this tool is by way of an\nexample. Place the <code>mgptree<\/code> script in a convenient folder (the\nprogram generates a number of files). Change the permissions on the\nscript so that you can execute it.<\/p>\n<p>Let's say we want to generate a tree for Gau\u00df and Fourier, going back\n5 generations. The first step is to prepare a file of names for our\nsearch:<\/p>\n<p>So, we create a unicode text file:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Gau\u00df, Carl, Friedrich\nFourier, Jean-Baptiste, Joseph\n<\/code><\/pre><\/div>\n\n<p>I'll call the file <code>gf.txt<\/code>. Now we need to get some data from the\nweb. We do this as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>(venv) $ python mgptree.py -g 5 -s -i gf.txt -o gf.mgp\nSaved 25 records to file gf.mgp.\n<\/code><\/pre><\/div>\n\n<p>The <code>-s<\/code> option indicates we want to \"scrape\" data from the MGP\nwebsite. The <code>-g<\/code> option indicates how many generations backward we\nwant to search. The <code>-i<\/code> denotes our input file, the <code>-o gf.mgp<\/code>\nindicates that we want to save our results in a database named\n<code>gf.mgp<\/code>.<\/p>\n<p>Now we need to graph the data, so we type the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>(venv) $ python mgptree.py -p -i gf.mgp -o gf.dot\n(venv) $ dot -Tpng gf.dot -o gf.png\n<\/code><\/pre><\/div>\n\n<p>In the first line, the <code>-p<\/code> indicates we are now in \"plotting mode\"\nwhere we want to convert the input database <code>gf.mgp<\/code> to a textual\nformat, which we'll save as <code>gf.dot<\/code>. The next line hands the textual\ndata to the graphviz program <code>dot<\/code>, which converts it to a PNG image\nfile named <code>gf.png<\/code>. (Many other file formats are available.)<\/p>\n<p><img alt=\"Genealogical trees of Gauss and Fourier\" src=\"https:\/\/jsthomas.github.io\/images\/mgptree\/gf.png\"><\/p>\n<p>Creating the intermediate database <code>gf.mgp<\/code> allows us to work with the\ndata offline, without having to query the web while we are figuring\nout how we want to plot the data.  For example, suppose we only want\nto present two generations of the data we just downloaded. Then we'd\ntype<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>(venv) $ python mgptree.py -p -g2 -i gf.mgp -o gf_tiny.dot\n(venv) $ dot -Tpng gf_tiny.dot -o gf_tiny.png\n<\/code><\/pre><\/div>\n\n<p>and we wouldn't have to retrieve any information from the web. The\nresult, <code>gf_tiny.png<\/code> looks like this:<\/p>\n<p><img alt=\"A small genealogical tree of Gauss and Fourier.\" src=\"https:\/\/jsthomas.github.io\/images\/mgptree\/gf_tiny.png\"><\/p>\n<p>This feature can be pretty useful if you're trying to work with very\nlarge sets of data and don't know how much information you want to\npresent.<\/p>\n<h2>Usage Tips<\/h2>\n<ol>\n<li>\n<p>The Math Geneaology Project has some \"holes\" in its data. This seems\nto be particularly true for mathematicians who didn't get their degree\nin Europe or the US. If you or your advisor aren't listed, add your\ndata to their website\n<a href=\"http:\/\/genealogy.math.ndsu.nodak.edu\/submit.php\">here<\/a> to help fill\nin the gaps!<\/p>\n<\/li>\n<li>\n<p>The number of requests to the MGP's database can grow to be quite\nlarge if you search back 10 or more generations. In particular, it's\nprobably not a good idea to try to generate a tree for a large number\nof people <em>and<\/em> many generations.<\/p>\n<\/li>\n<li>\n<p>Accurately matching name data isn't easy. For example, the\nmathematician Felix Klein is really named Christian Felix Klein. If\nyour searches don't succeed, check to make sure you've got your name\ndata right. This is particularly true for names with accents and\numlauts.<\/p>\n<\/li>\n<\/ol>\n<h2>Making Pretty Graphs<\/h2>\n<p>Because my script produces an intermediate <code>.dot<\/code> file, it is possible\nfor you to edit that file to add additional information or decorations\nto the graph. Don't like the font I chose? Change the <code>font=Courier<\/code>\nentry in the <code>.dot<\/code> file. Want to adjust a few nodes so that\nsignificant mathematicians have special node colors? Search for their\nnames in the <code>.dot<\/code> file, then add the metadata\n<code>color=[your color here]<\/code> to their nodes. The documentation for\ngraphviz is very useful for tasks like this.<\/p>","category":{"@attributes":{"term":"Python, Projects"}}},{"title":"A Camera-Based Virtual Keyboard System","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/vkeyboard.html","rel":"alternate"}},"published":"2013-12-10T00:00:00-05:00","updated":"2013-12-10T00:00:00-05:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2013-12-10:\/vkeyboard.html","summary":"<p>A brief summary of my term project for ECE 532<\/p>","content":"<p>In the Fall of 2013, I developed a camera-based keyboard system as my\nterm project for an image analysis course. This page provides a brief\nsummary of my project.<\/p>\n<p>In my system, a webcam looks down on a user's hands, which rest on a\npaper keyboard template. My program collects images from the webcam to\ndetermine when and where the user touches the keyboard template. When\nthe user touches a key, my program produces the corresponding letter\nas output.<\/p>\n<p>Virtual keyboards are still actively researched in computer science\nand electrical engineering. The system I implemented uses techniques\npublished in [1]-[3] between 2010 and 2013. Camera-based virtual\nkeyboards require a number of interesting image analysis techniques to\nimplement. They are particularly of interest in mobile applications\nand in areas where one would like to avoid the cost of a physical\nkeyboard (for example, projects providing computers to people in the\ndeveloping world).<\/p>\n<h1>Processing Steps<\/h1>\n<p>The virtual keyboard system I implemented needed to solve three main\nproblems:<\/p>\n<ol>\n<li>\n<p>Detect the locations of the user's fingertips.<\/p>\n<\/li>\n<li>\n<p>Detect whether any fingertips are in contact with the tabletop.<\/p>\n<\/li>\n<li>\n<p>When a fingertip touches the tabletop, determine which key was\npressed on the keyboard.<\/p>\n<\/li>\n<\/ol>\n<p>The first problem can be solved by segmenting an input image <span class=\"math\">\\(I\\)<\/span> into\ntwo regions: one representing the hands and another representing the\nbackground. For each connected component of the hand region, we can\nextract a contour <span class=\"math\">\\(\\gamma\\)<\/span> that traverses the boundary\ncounterclockwise. Places where <span class=\"math\">\\(\\gamma\\)<\/span> has high curvature (the\nplaces where <span class=\"math\">\\(\\gamma\\)<\/span> bends the most sharply) typically correspond to\nfingertips.<\/p>\n<p><img alt=\"Virtual keyboard processing steps.\" src=\"https:\/\/jsthomas.github.io\/images\/vkeyboard\/kb_processing.png\"><\/p>\n<p>I addressed the second problem using a technique called <em>shadow\nanalysis<\/em>, which is discussed in [1]. With this technique, we perform\nanother segmentation on <span class=\"math\">\\(I\\)<\/span>, to locate the regions in the image that\nrepresent the shadows of the user's hands. Then, we examine small\nneighborhoods near the user's fingertips. If the proportion of\nshadow-pixels in a given neighborhood is above a certain threshold, we\ninfer that the corresponding fingertip is not in contact with the\ntabletop (because it has a shadow). Otherwise, we declare that\nfingertip to be touching the keyboard.<\/p>\n<p>The last problem is solved by making some assumptions about the\ngeometry of the keyboard and imaging system. I assumed that the\nkeyboard template displays four easily identifiable control points\narranged in a rectangle, and that the front edge of the control\nrectangle is parallel to the <span class=\"math\">\\(x\\)<\/span>-axis of the camera's coordinate\nsystem. With these additional assumptions, it isn't too hard to invert\nthe perspective projection and recover the keyboard-space coordinates\nof each keypress from the image-space coordinates of the fingertips.<\/p>\n<h1>Results<\/h1>\n<p>After implementing my virtual keyboard system in python, I analyzed\nits performance under different lighting and usage conditions. My\ntests suggest that a camera-based user interface that uses shadow\nanalysis will work best under conditions where one has fine control\nover the lighting conditions and the user does not need to enter very\nmuch data at one time. For example, a camera-based user interface\nwould work well in an interactive museum exhibit, but it might not be\na very good tool for word processing in a dark coffee shop. Currently,\ncamera-based keyboards cannot provide the speed and accuracy\nachievable on physical keyboards (but for that matter, neither do\ntouchscreen keyboards).<\/p>\n<h1>Downloads<\/h1>\n<p>Below are links to the paper and code I wrote for the term project. I\nused the code within <a href=\"http:\/\/ipython.org\/\">ipython<\/a> to conduct my\nexperiments, and used the <a href=\"http:\/\/opencv.org\/\">OpenCV<\/a> project to get\ndata from the camera. OpenCV's support for python is still under\ndevelopment, so if you examine my code you may have to adapt it to\nwork with your particular hardware and copy of OpenCV.<\/p>\n<ul>\n<li>\n<p>Paper:\n  <a href=\"https:\/\/jsthomas.github.io\/docs\/vkeyboard\/vkeyboard.pdf\">A Camera Based Virtual Keyboard with Touch Detection by Shadow Analysis<\/a><\/p>\n<\/li>\n<li>\n<p>Project Code: <a href=\"https:\/\/jsthomas.github.io\/docs\/vkeyboard\/vkeyboard.zip\">vkeyboard.zip<\/a><\/p>\n<\/li>\n<\/ul>\n<h2>References<\/h2>\n<ol>\n<li>\n<p>Y. Adajania, J. Gosalia, A. Kanade, H. Mehta, and N. Shekokar. Virtual\nkeyboard using shadow analysis. In Emerging Trends in Engineering and\nTechnology (ICETET), 2010 3rd International Conference on, page 163 to\n165, 2010.<\/p>\n<\/li>\n<li>\n<p>E. Posner, N. Starzicki, and E. Katz. A single camera based floating virtual\nkeyboard with improved touch detection. In Electrical Electronics Engineers\nin Israel (IEEEI), 2012 IEEE 27th Convention of, page 1 to 5, 2012.<\/p>\n<\/li>\n<li>\n<p>M. Hagara and J. Pucik. Fingertip detection for virtual keyboard\nbased on camera. In Radioelektronika (RADIOELEKTRONIKA), 2013 23rd\nInternational Conference, page 356 to 360, 2013.<\/p>\n<\/li>\n<\/ol>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":{"@attributes":{"term":"Python"}}}]}