<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><atom:link href="https://yogthos.net/" rel="self" type="application/rss+xml"/><title>(iterate think thoughts)</title><link>https://yogthos.net/</link><description>Dmitri's blog about programming, Clojure, and software development</description><lastBuildDate>Wed, 25 Feb 2026 23:44:05 +0000</lastBuildDate><generator>clj-rss</generator><item><guid>https://yogthos.net/posts/2026-02-25-ai-at-scale.html</guid><link>https://yogthos.net/posts/2026-02-25-ai-at-scale.html</link><title>Managing Complexity with Mycelium</title><description>&lt;p&gt;Software architecture is at root a creature of human frailty. The sacred cow of clean code and the holy grail of design patterns are understood to be, at least in practical terms, little more than tricks to help people keep their sanity along the way. Human cognitive capacity is strictly limited, and we're still figuring out ways to reliably build machines significantly more complex than can be held in a single mind. Current attempts to offload coding tasks to language models are hitting the same wall. These models can be brilliant, but only up to a point. They’ll effortlessly compose a flawless function, but when challenged to manage a project with a thousand such moving parts, they quickly lose the plot. This problem is commonly known as context rot, but it might equally well be called a coding architecture failure.&lt;/p&gt;&lt;p&gt;If one hands an LLM a big pile of mutable state and loosely defined relationships, a solution that doesn’t actually work will be hallucinated inevitably, and when it does work, it will do so largely by accident. This comes about because there are just too many moving parts, and the ground truth cannot be kept track of. Humans are known to have exactly the same problem. Enormous amounts of time are spent chasing down bugs that exist because some distant part of the app decided to tweak a variable it didn’t own. Shared mutable state quickly leads to an overwhelming information flow, generating invisible threads between components that make it nearly impossible to know the scope of the change being made. Seemingly innocuous code changes end up mutating state in unintended ways that lead to unexpected consequences.&lt;/p&gt;&lt;p&gt;We solve difficult problems by dividing them into smaller, more manageable ones, and then composing them together. Successful architecture requires separable components, each with a function that is easy to grasp, and creating interfaces between them to abstract over their internal details and present to the outside world only their functional aspects. We must discover the boundaries between components, separate external effects from internal implementation details, and arrange for each component to control its own context. Then, and only then, can we be sure that we will always be working in a clear context that we can fit in our heads.&lt;/p&gt;&lt;p&gt;We naturally long for layers of organization. Hierarchies permit us to construct separate, self-contained units which can then be connected together to make larger structures. It's a powerful kind of architecture, one that facilitates writing large projects by abstracting over the complexity of the constituent parts. In working on a given component, we have to know all its details. But in using it, we only need to know what it does, which is entirely reflected in its API surface. The internal complexity is encapsulated within the API boundary. These are building blocks that give us a stable base upon which to build higher-level abstractions. Several such components can be assembled into a bigger block, where the connections between subcomponents become its internal complexity. The composite component becomes a new layer, providing its own API, which can be used by still higher-level abstractions. If what I'm describing sounds familiar, it is because that's exactly the way in which software libraries work. A library is simply a model of a class of problems, and when we encounter these types of problems, we can use it as an off-the-shelf building block.&lt;/p&gt;&lt;p&gt;A complex system has to be resilient and adaptable. But if every component is hooked directly into every other, there’s no way you can anticipate what a change in any one place will do. There are no boundaries to stop the chaos. Anything that works at scale relies on stable subassemblies. Herbert Simon described it long ago in a parable of two watchmakers. The first built his watches one piece at a time. He had to keep the entire complexity of the watch in his mind as he did his work, for any interruption would undo his progress and send the component pieces clattering to the floor. He worked on a flat plane of complexity, having to think through the workings of the entire watch just to insert a single gear. The other watchmaker did well because he first constructed small, stable modules which he was able to click together. So if he was interrupted, only a small amount of work was lost. He never had to think through more than a few components at a time. The system was resilient because it was built as a hierarchy of subunits, each able to stand on its own merit, and so the watchmaker had to consider a small context rather than the stupefying complexity of the whole.&lt;/p&gt;&lt;p&gt;Practically any large system can so be divided into smaller, nested subsystems, which communicate with one another as they go about their business. The intimate workings of other subsystems need hardly be known, which permits these modules to form. Individual components are not encumbered by what’s going on at other places where events are transpiring at different paces and according to a different set of circumstances. This is how hierarchies help in managing the complexity of a system. Each subsystem can evolve on its own. A malfunction in one region can be quarantined; it need not bring down the entire enterprise. A useful way to think of hierarchies is to treat them as connective tissue between the various subsystems of the program, as a principal means of control, providing the architecture and the infrastructure that coordinates the internal functioning of the individual parts of the system.&lt;/p&gt;&lt;p&gt;In contrast, in software development, practitioners are often confronted by the opposite scenario. Large software projects degenerate into a tangled web in which every function depends on a global state or a shared database connection. Humans have difficulty working with such systems because they can’t reason about their pieces independently. If a feature requires more information than can be kept in one’s head at once, guesses and assumptions begin to proliferate.&lt;/p&gt;&lt;p&gt;Just as humans need clear boundaries to maintain sanity, coding agents are even more vulnerable to cognitive saturation. There’s no intuition in a large language model that can tune out the noise. Everything is placed into its context window. If a piece of code is a labyrinth of obscure dependencies, the agent has to parse through it all to make a single modification. Eventually, the context becomes so cluttered that the purpose of the task gets lost in the entropy. The model starts hallucinating because of its inability to distinguish between the logic it’s supposed to refactor and the three hundred other things it’s presented with.&lt;/p&gt;&lt;h3 id="where&amp;#95;we&amp;#95;are&amp;#95;at"&gt;Where We Are At&lt;/h3&gt;&lt;p&gt;To understand how we might solve this for both humans and machines, let's first examine the tools we've already developed for managing complexity. The software industry has spent decades working out how to decompose code into manageable pieces. A very powerful set of tools for this purpose is already available. At the inter-process scale, there are microservices, which provide a physical boundary between programs. And at the intra-program level, there are techniques such as message passing, pure functions, and immutable data.&lt;/p&gt;&lt;p&gt;The functional style is particularly good at taming global state. Here, functions are the smallest building blocks, and pure functions can be considered on their own. The idea here is to build systems from separate, single-purpose parts, by using isolation, composition, and clear contracts inside the application's own logic. Code becomes a pipeline focused on the data flow. A program takes one piece of data as input, and produces another as output, pumping it through a sequence of pure functions. Since data is immutable, it is transparent and inert, having no hidden states or secret side effects. This is how stable contracts are formed. Once the transformations have been specified, the interface is a contract you can trust.&lt;/p&gt;&lt;p&gt;When you design applications in this way, the overall architecture looks like a network of railway lines, with the input data package needing to get from point A to point B. The package might pass through many different stations on the way to its destination, each one inspecting the package to decide where to route it next. An HTTP handler takes the payload, parses the request, determines the content type, and forwards it on toward an authentication handler. The authentication handler might inspect permissions in payload metadata to determine where to send it next, and so on. Eventually, the package arrives at its intended destination where the data gets serialized, stored, or presented to the user.&lt;/p&gt;&lt;p&gt;But even with all these great functional tools, we still tend to tangle two rather different kinds of code together. We mix code that cares what the data means and the code that cares how it travels from one component to another. Traditional software design structures embed the routing implicitly in the function call graph. For example, our authentication handler will have the logic to select the next function to invoke within its implementation. The control logic and its internal implementation details, thus, end up being intertwined in an ad hoc manner, resulting in a significant coupling problem. If you wish to alter the flow of your application, you must sift through voluminous amounts of incidental code describing the internal minutiae of component implementations.&lt;/p&gt;&lt;p&gt;An effective solution to this problem is to use inversion of control by removing routing logic from the functions and elevating it to first-class citizenship in the design. Why is a state machine the natural fit for this, rather than an event bus or dependency injection? Event buses scatter routing logic to the winds with components shouting into the void, making the overall flow impossible to trace. Implicit callbacks hide the flow inside the implementation. State machines, on the other hand, make routing declarative and visible in one place. They force the separation of &lt;em&gt;what to do&lt;/em&gt; from &lt;em&gt;how to do it&lt;/em&gt;.&lt;/p&gt;&lt;h3 id="introducing&amp;#95;mycelium"&gt;Introducing Mycelium&lt;/h3&gt;&lt;p&gt;I’ve spent a great deal of time considering how to construct a system where distinct components are clearly separated by design, with clear boundaries between semantics of the code and the implementation details. This is the basic conceptual orientation of &lt;a href='https://github.com/yogthos/mycelium/'&gt;Mycelium&lt;/a&gt;, which treats the program as a recursive ecosystem of workflows, solving the very routing problem described above.&lt;/p&gt;&lt;p&gt;Clojure provides the tools for writing pure functions, but falls short of giving us guidance on how to orchestrate them when writing large applications. I initially developed &lt;a href='https://github.com/yogthos/maestro'&gt;Maestro&lt;/a&gt; to provide a clear organizational framework, separating side-effectful concerns from pure calculation, and structuring workflows as graphs where the nodes represent computations of state, and the edges represent transitions between them. The nodes are distinct, context-free blocks, responsible for specific tasks, linked by a thin coordinating layer controlling the flow of data between them. The state itself is represented as a map that's passed from one node to another.&lt;/p&gt;&lt;p&gt;The business logic for each node lives inside a Mycelium component called a cell. Since cells are completely unaware of one another, they are inherently isolated. Each one can be viewed as a miniature self-contained application. It knows how to do its specific job and adheres to a strict lifecycle. It takes a state map, loads the data, runs the logic, and computes a new state as its output. All they can access are the IO resources, and a map containing the input state.&lt;/p&gt;&lt;p&gt;Maestro is responsible for arranging these transitions, so that the decisions are pure, and their effects are encapsulated. When a component needs to move itself from one state to another, it does not simply reach in and take what it needs. Instead, it updates the state map, and delegates to Maestro to orchestrate the transition. Again, this keeps the code responsible for deciding what will happen next separate and distinct from the private parts of the individual cells.&lt;/p&gt;&lt;p&gt;Each cell is additionally wrapped in a &lt;a href='https://github.com/metosin/malli'&gt;Malli&lt;/a&gt; schema, which gives the cell a protocol to abide by. You can’t simply hope that the LLM will understand your intentions when they’re expressed in plain English. What you need is a formal contract to determine whether the implementation is correct. Malli enables us to specify precisely what a cell is entitled to receive and what it can produce as its output. It's a flexible way to encode deep, structural invariants representing the interface of the cell.&lt;/p&gt;&lt;p&gt;An agent tasked with constructing a handler for a particular node operates within the constraints of a contract, enforced by the schema, both during development and at runtime. Crucially, the agent doesn't need to scour the codebase to discover the relevant cell; the orchestration layer (acting as a Conductor) assigns the specific cell ID and its schema directly to the agent. It operates within a tightly bounded context provided to it. If the code produced by the agent does not adhere to the contract, if the output is even slightly off, the system will reject it providing meaningful feedback on what went wrong.&lt;/p&gt;&lt;p&gt;Think, for a minute, about what this does for the scope creep problem. The schema defines the boundary of the cell letting the agent know exactly what keys are in the map, what the data types are, and what the constraints are. Since the components do not interact directly, the agent has a well-defined, perfectly sized context that it needs to understand.&lt;/p&gt;&lt;p&gt;We now have a self-correcting loop. The primary agent, the Conductor, designs the workflow in EDN. A fleet of smaller, specialized agents do the individual tasks. If one of them makes an error, it is detected by the Malli contract before it can propagate forward to the next node in the graph. The specific validation failure is known at the point where it arose, and its scope is limited to the node that produced it.&lt;/p&gt;&lt;h3 id="the&amp;#95;state&amp;#95;machine&amp;#95;graph&amp;#95;as&amp;#95;a&amp;#95;contract"&gt;The State Machine Graph as a Contract&lt;/h3&gt;&lt;p&gt;Treating an application's high-level behavior as a state machine graph provides us with a master blueprint. It allows us to determine what the intent of a particular workflow is by reading a declarative schema describing the states and the transitions between the cells. A human can review and approve a data flow diagram, which specifies the semantics of each cell, and the rules guiding the flow of data across them. The details of how each cell functions are abstracted behind its API, and managed by the agent responsible for implementing its functionality. Hence, the orchestrator only needs to concern itself with the routing aspect of the application and ensuring that the schemas of nodes sharing an edge are compatible.&lt;/p&gt;&lt;p&gt;The orchestration layer is in charge of directing the work, and executing the branching logic. Its sole concern is to examine the results from each node to decide on the next branch to take according to the EDN specification.&lt;/p&gt;&lt;p&gt;Because the intercellular connections form a directed graph, and since motion is governed by payload state, with the routing logic separated from the cell code, you can, in principle, determine the entire decision tree of the application just by examining the EDN spec. Instead of having to dig through conditional branches buried in thousands of lines of implementation code, you have a declarative map of possibilities.&lt;/p&gt;&lt;h3 id="how&amp;#95;this&amp;#95;works&amp;#95;in&amp;#95;practice"&gt;How This Works in Practice&lt;/h3&gt;&lt;p&gt;You can glimpse the way in which Mycelium binds these ideas together by examining a snippet from the &lt;a href='https://github.com/yogthos/mycelium/tree/main/examples/user_onboarding'&gt;user-onboarding&lt;/a&gt; demo. The workflow definition is the point of departure. We start by defining a cell and its strict contract:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;;; A cell contract for session validation
{:id       :auth/validate-session
   :doc      &amp;quot;Check credentials against the session store&amp;quot;
   :schema   {:input  &amp;#91;:map
                        &amp;#91;:user-id :string&amp;#93;
                        &amp;#91;:auth-token :string&amp;#93;&amp;#93;
              :output {:authorized   &amp;#91;:map
                                       &amp;#91;:session-valid :boolean&amp;#93;
                                       &amp;#91;:user-id :string&amp;#93;&amp;#93;
                       :unauthorized &amp;#91;:map
                                       &amp;#91;:session-valid :boolean&amp;#93;
                                       &amp;#91;:error-type :keyword&amp;#93;
                                       &amp;#91;:error-message :string&amp;#93;&amp;#93;}}
   :requires &amp;#91;:db&amp;#93;}

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This map represents a stable building block. There is no ambiguity in a declarative specification. A cell is defined by the shape of its input and output, along with its resource requirements. The routing logic is extracted entirely into separate &lt;code&gt;:edges&lt;/code&gt; and &lt;code&gt;:dispatches&lt;/code&gt; keys in the workflow.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt; :edges
 {:validate-session {:authorized   :fetch-profile
                     :unauthorized :error}}

 :dispatches
 {:validate-session &amp;#91;&amp;#91;:authorized   &amp;#40;fn &amp;#91;data&amp;#93; &amp;#40;:session-valid data&amp;#41;&amp;#41;&amp;#93;
                     &amp;#91;:unauthorized &amp;#40;fn &amp;#91;data&amp;#93; &amp;#40;not &amp;#40;:session-valid data&amp;#41;&amp;#41;&amp;#41;&amp;#93;&amp;#93;}

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The edges shown in the snippet represent the possible transitions. The dispatches constitute a list of node identifiers, each with an associated decision function that examines the state and determines whether it should be processed by the identifier in question. Dispatches are processed on a first come, first served basis; that is, the state will be routed to the first matching identifier found.&lt;/p&gt;&lt;p&gt;Next, we have the cell associated with the spec, which is responsible for performing the actual work. Following &lt;a href='https://github.com/weavejester/integrant'&gt;Integrant&lt;/a&gt; philosophy, the cells are defined as a collection of multimethods.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod cell/cell-spec :user/fetch-profile &amp;#91;&amp;#95;&amp;#93;
  {:id      :user/fetch-profile
   :doc     &amp;quot;Fetch user profile from database&amp;quot;
   :handler &amp;#40;fn &amp;#91;{:keys &amp;#91;db&amp;#93;} data&amp;#93;
              &amp;#40;if-let &amp;#91;user &amp;#40;db/get-user db &amp;#40;:user-id data&amp;#41;&amp;#41;&amp;#93;                
                &amp;#40;assoc data :profile &amp;#40;select-keys user &amp;#91;:name :email&amp;#93;&amp;#41;&amp;#41;
                &amp;#40;assoc data
                       :error-type    :not-found
                       :error-message &amp;#40;str &amp;quot;User not found: &amp;quot; &amp;#40;:user-id data&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;}&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note how the &lt;code&gt;:user/fetch-profile&lt;/code&gt; handler doesn’t need to know where the data came from, nor does it decide where to send it. All it receives is the current state. The cell does its work and then returns an updated map. The orchestration layer evaluates the &lt;code&gt;dispatches&lt;/code&gt; against this new data to select the next &lt;code&gt;edge&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Long before a user ever makes a request, the workflow goes through a rigorous validation phase at compile time. During startup, the engine verifies that every cell exists in the registry, that every transition has a valid destination, and that all the input and output schemas chain together with no discontinuities. This is the moment where the blueprint becomes an active, executable process.&lt;/p&gt;&lt;p&gt;When a request (like &lt;code&gt;POST /api/onboarding&lt;/code&gt;) actually arrives, the HTTP routing library recognizes the endpoint and shoves it onward to an onboarding handler. This handler summons the pre-compiled workflow engine, giving it the database connection and the raw request. As the state machine proceeds through its transitions, the Malli schemas are serving as sentinels.&lt;/p&gt;&lt;h3 id="reliability,&amp;#95;debugging,&amp;#95;and&amp;#95;testing"&gt;Reliability, Debugging, and Testing&lt;/h3&gt;&lt;p&gt;The &lt;strong&gt;State Map&lt;/strong&gt; acts as the single source of truth throughout this lifecycle. Every transformation is explicit in the return value, and there are no side channels modifying the state. Like a messenger, it travels through the system, carrying on its person all the data that has been gathered up to this point, as well as associated metadata.&lt;/p&gt;&lt;p&gt;Because the state map keeps a &lt;code&gt;:mycelium/trace&lt;/code&gt; of every transition, you get unparalleled observability. If a workflow fails, you don’t just get a stack trace telling you where in the codebase the crash happened; you get the full history at the moment of failure. You can see the inputs, the previous steps, and the exact data that caused the routing logic to stumble. For the coding agent, it’s as if there’s a black box flight recorder on every single run.&lt;/p&gt;&lt;p&gt;Such level of observability fundamentally transforms how we test applications. Testing in often seen as a thoroughly distasteful chore, so much so that you will often find people spending more time with mocks and dependency injection than actually writing tests.&lt;/p&gt;&lt;p&gt;Mycelium treats each fragment of logic as a pure update of a data structure. Testing reduces to a straightforward exercise in data juggling. You don’t have to mock up a database to test how a particular system handles a User Not Found scenario; you simply feed the component a state map lacking the &lt;code&gt;:user&lt;/code&gt; key and see what output it produces.&lt;/p&gt;&lt;p&gt;Because every workflow node is contractually bound by its Malli schema, you can take the &lt;code&gt;:validate-user-data&lt;/code&gt; handler, feed it a map of bad data, and check that it sets an &lt;code&gt;:invalid&lt;/code&gt; key on the state map. You’re not testing the whole onboarding flow; you’re testing one specific cell.&lt;/p&gt;&lt;p&gt;In Mycelium, logical integration tests can be performed trivially, simply by executing the workflow with a mock resource map. Resources like the database are passed in separately, so a real Postgres connection can be exchanged for a mock in the test suite. The difference is entirely irrelevant to the workflow.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;;; A logical integration test
&amp;#40;deftest onboarding-workflow-test
  &amp;#40;let &amp;#91;ds       &amp;#40;create-test-db!&amp;#41;
        compiled &amp;#40;wf/compile-workflow onboarding-manifest&amp;#41;
        result   &amp;#40;fsm/run compiled
                         {:db ds}
                         {:data {:http-request
                                 {:body {&amp;quot;email&amp;quot; &amp;quot;test@example.com&amp;quot;}}}}&amp;#41;&amp;#93;
    &amp;#40;is &amp;#40;some? &amp;#40;:profile result&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;is &amp;#40;= &amp;quot;test@example.com&amp;quot; &amp;#40;get-in result &amp;#91;:profile :email&amp;#93;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Because of the trace history, your test assertions become incredibly descriptive. You aren't just checking if the final result is &lt;code&gt;200 OK&lt;/code&gt;. You are able to check that the system moved from &lt;code&gt;:start&lt;/code&gt; to &lt;code&gt;:validate-session&lt;/code&gt; to &lt;code&gt;:fetch-profile&lt;/code&gt; in the exact order you expected. You get the confidence of a full system test by simply passing mock resources to your workflow, and verifying that transitions happen in correct order.&lt;/p&gt;&lt;h3 id="layered&amp;#95;abstraction&amp;#95;and&amp;#95;infinite&amp;#95;scale"&gt;Layered Abstraction and Infinite Scale&lt;/h3&gt;&lt;p&gt;The entire design is naturally recursive. A complete system implemented as a network of cells can itself be viewed as a single cell, which offers up an interface and can then be slotted into a yet-larger state machine network. You might have a simple network handling user login, which becomes a component in a medium-scale network managing the payment process, which itself becomes a component in a large-scale network implementing a complete online emporium. Scaling becomes a matter of arranging components on a graph rather than increased coupling within the codebase.&lt;/p&gt;&lt;p&gt;But of course, there must be clear boundaries set for such a system. The most promising way to define components and graphs draws on functional programming and formal methods. For example, Malli-driven schemas provide a means of establishing checkpoints that the LLM agent cannot bypass. The agent must fulfill the contract by adhering to all the constraints and requirements.&lt;/p&gt;&lt;p&gt;Once the high-level design is in place, these contracts can be issued to the agents in charge of the nodes in the graph. You no longer need an exceptionally capable agent that's able to comprehend a massive context and keep track of the interconnections across a sprawling application. The job description of the agent in charge of the flow of control is likewise dramatically circumscribed. The internal details of the cells can be ignored, with attention paid only to the graph itself. If the graph grows too complex, it, too, can be divided into separate, independent subgraphs. In this architecture, the context never needs to become unmanageably large.&lt;/p&gt;&lt;h3 id="the&amp;#95;agent&amp;#95;synergy"&gt;The Agent Synergy&lt;/h3&gt;&lt;p&gt;Historically, this kind of design has been hard to sell. Workflow engines and state-graph systems are not without their proponents, but they haven’t exactly swept the world. The basic problem is that they require a lot of additional ceremony. While wiring functions together by hand permits the programmer to forge ahead in a straight line, forcing yourself to step back, design a state graph, worry about the transition logic among disparate files, and code the glue just feels too onerous. Most programmers would much rather just bang out an &lt;code&gt;if&lt;/code&gt; statement and keep going.&lt;/p&gt;&lt;p&gt;But the picture changes completely when we introduce coding agents. A large language model lacks ego and has no difficulty writing boilerplate code. It does not find itself bored by ceremony, nor frustrated by the need for upfront structural planning. In fact, language models thrive on it. What is a tedious tax for a human developer serves as an explicit, unambiguous map for an agent. By embracing this structure, the agent secures the very boundaries it needs to stay coherent.&lt;/p&gt;&lt;p&gt;Divorcing data flow from data transformation resolves the problem of LLM context overload in an elegant and general way. A strategic agent, in the form of the Conductor, coordinates the flow in the orchestration layer, plotting the tracks. Meanwhile, individual handler agents are responsible for writing, refining, and documenting their particular domain which is just a station on the railway. They do so within a safe, bounded context, avoiding the thicket of intractable problems posed by runaway cognitive saturation.&lt;/p&gt;&lt;p&gt;Imagine a future in which coding agents assemble software systems by integrating and adapting existing workflows that have been approved by human oversight. We no longer have to suffer the frustration of constructing complex machines built out of opaque and unreliable components. We can rely on standardized and tested building blocks, following a clear and verifiable assembly plan, so that the resulting system is guaranteed by its very design to be correct, adaptable, and observable.&lt;/p&gt;</description><pubDate>Wed, 25 Feb 2026 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2026-01-16-lattice-mcp.html</guid><link>https://yogthos.net/posts/2026-01-16-lattice-mcp.html</link><title>Stop Round-Tripping Your Codebase: How to Cut LLM Token Usage by 80% Using Recursive Document Analysis</title><description>&lt;p&gt;When you employ AI agents such as Claude, there’s a significant volume problem for document study. Reading one file of 1000 lines consumes about 10,000 tokens. Token consumption incurs costs and time penalties. Codebases with dozens or hundreds of files, a common case for real world projects, can easily exceed 100,000 tokens in size when the whole thing must be considered. The agent must read and comprehend, and be able to determine the interrelationships among these files. And, particularly, when the task requires multiple passes over the same documents, perhaps one pass to divine the structure and one to mine the details, costs multiply rapidly.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Matryoshka&lt;/strong&gt; is a tool for document analysis that achieves over 80% token savings while enabling interactive and exploratory analysis. The key insight of the tool is to save tokens by caching past analysis results, and reusing them, so you do not have to process the same document lines again. These ideas come from recent research, and retrieval-augmented generation, with a focus on efficiency. We'll see how Matryoshka unifies these ideas into one system that maintains a persistent analytical state. Finally, we'll take a look at some real-world results analyzing the &lt;a href='https://git.sr.ht/~foosoft/anki-connect'&gt;anki-connect&lt;/a&gt; codebase.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="the&amp;#95;problem:&amp;#95;context&amp;#95;rot&amp;#95;and&amp;#95;token&amp;#95;costs"&gt;The Problem: Context Rot and Token Costs&lt;/h2&gt;&lt;p&gt;A common task is to analyze a codebase to answers a question such as “What is the API surface of this project?” Such work includes identifying and cataloguing all the entry points exposed by the codebase.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Traditional approach:&lt;/strong&gt;&lt;/p&gt;&lt;ol&gt;&lt;li&gt;1. Read all source files into context (~95,000 tokens for a medium project)&lt;/li&gt;&lt;li&gt;2. The LLM analyzes the entire codebase’s structure and component relationships&lt;/li&gt;&lt;li&gt;3. For follow-up questions, the full context is round-tripped every turn&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;This creates two problems:&lt;/p&gt;&lt;h3 id="token&amp;#95;costs&amp;#95;compound"&gt;Token Costs Compound&lt;/h3&gt;&lt;p&gt;Every time, the entire context has to go to the API. In a 10-turn conversation about a codebase of 7,000 lines, almost a million tokens might be processed by the system. Most of those tokens are the same document contents being dutifully resent, over and over. The same core code is sent with every new question. This redundant transaction is a massive waste. It forces the model to process the same blocks of text repeatedly, rather than concentrating its capabilities on what’s actually novel.&lt;/p&gt;&lt;h3 id="context&amp;#95;rot&amp;#95;degrades&amp;#95;quality"&gt;Context Rot Degrades Quality&lt;/h3&gt;&lt;p&gt;As described in the &lt;a href='https://arxiv.org/abs/2505.11409'&gt;Recursive Language Models&lt;/a&gt; paper, even the most capable models exhibit a phenomenon called context degradation, in which their performance declines with increasing input length. This deterioration is task-dependent. It’s connected to task complexity. In information-dense contexts, where the correct output requires the synthesis of facts presented in widely dispersed locations in the prompt, this degradation may take an especially precipitous form. Such a steep decline can occur even for relatively modest context lengths, and is understood to reflect a failure of the model to maintain the threads of connection between large numbers of informational fragments long before it reaches its maximum token capacity.&lt;/p&gt;&lt;p&gt;The authors argue that we should not be inserting prompts into the models, since this clutters their memory and compromises their performance. Instead, documents should be considered as &lt;strong&gt;external environments&lt;/strong&gt; with which the LLM can interact by querying, navigating through structured sections, and retrieving specific information on an as-needed basis. This approach treats the document as a separate knowledge base, an arrangement that frees up the model from having to know everything.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="prior&amp;#95;work:&amp;#95;two&amp;#95;key&amp;#95;insights"&gt;Prior Work: Two Key Insights&lt;/h2&gt;&lt;p&gt;Matryoshka builds on two research directions:&lt;/p&gt;&lt;h3 id="recursive&amp;#95;language&amp;#95;models&amp;#95;(rlm)"&gt;Recursive Language Models (RLM)&lt;/h3&gt;&lt;p&gt;The RLM paper introduces a new methodology that treats documents as external state to which step-by-step queries can be issued, without the necessity of loading them entirely. Symbolic operations, search, filter, aggregate, are actively issued against this state, and only the specific, relevant results are returned, maintaining a small context window while permitting analysis of arbitrarily large documents.&lt;/p&gt;&lt;p&gt;Key point is that the documents stay outside the model, and only the search results enter the context. This separation of concerns ensures that the model never sees complete files, instead, a search is initiated to retrieve the information.&lt;/p&gt;&lt;h3 id="barliman:&amp;#95;synthesis&amp;#95;from&amp;#95;examples"&gt;Barliman: Synthesis from Examples&lt;/h3&gt;&lt;p&gt;&lt;a href='https://github.com/webyrd/Barliman'&gt;Barliman&lt;/a&gt;, a tool developed by William Byrd and Greg Rosenblatt, shows that it is possible to use program synthesis without asking for precise code specifications. Instead, input/output examples are used, and a solver engine is used as a relational programming system in the spirit of &lt;a href='http://minikanren.org/'&gt;miniKanren&lt;/a&gt;. Barliman uses such a system to synthesize functions that satisfy the constraints specified. The system interprets the examples as if they were relational rules, and the synthesis engine tries to satisfy them. This approach makes it possible to describe what is desired for concrete test cases.&lt;/p&gt;&lt;p&gt;The approach is to simply show examples of the kind of behavior one wishes the system to exhibit, letting it derive the implmentation on its own. Thus, the emphasis shifts from writing long and detailed step-by-step recipes for behavior to simply portraying, in a declarative fashion, what the desired goal is.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="matryoshka:&amp;#95;combining&amp;#95;the&amp;#95;insights"&gt;Matryoshka: Combining the Insights&lt;/h2&gt;&lt;p&gt;Matryoshka incorporates these insights into a functioning system for LLM agents. A practical tool is provided that enables agents to decompose challenging tasks into a sequence of smaller and more manageable objectives.&lt;/p&gt;&lt;h3 id="1.&amp;#95;nucleus:&amp;#95;a&amp;#95;declarative&amp;#95;query&amp;#95;language"&gt;1. Nucleus: A Declarative Query Language&lt;/h3&gt;&lt;p&gt;Instead of issuing commands, the LLM describes &lt;strong&gt;what&lt;/strong&gt; it wants, using &lt;a href='https://github.com/michaelwhitford/nucleus'&gt;Nucleus&lt;/a&gt;, a simple S-expression query language. This changes the focus from describing each step to specifying the desired outcome.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;grep &amp;quot;class &amp;quot;&amp;#41;           ; Find all class definitions
&amp;#40;count RESULTS&amp;#41;           ; Count them
&amp;#40;map RESULTS &amp;#40;lambda x    ; Extract class names
  &amp;#40;match x &amp;quot;class &amp;#40;\\w+&amp;#41;&amp;quot; 1&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We observe that the declarative interface retains its robustness even when the LLM employs different vocabulary or sentence structures. This robustness originates from the system’s commitment to elucidating the underlying intent of a request, independent of superficial linguistic variations.&lt;/p&gt;&lt;h3 id="2.&amp;#95;pointer-based&amp;#95;state"&gt;2. Pointer-Based State&lt;/h3&gt;&lt;p&gt;The key new insight is that we can separate the results from the context. Results are now stored in the REPL state, rather than in the context.&lt;/p&gt;&lt;p&gt;When Claude runs &lt;code&gt;&amp;#40;grep &amp;quot;def &amp;quot;&amp;#41;&lt;/code&gt; and gets 150 matches:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Traditional tools&lt;/strong&gt;: All 150 lines are fed into context, and round-tripped every turn&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Matryoshka&lt;/strong&gt;: Binds matches to &lt;code&gt;RESULTS&lt;/code&gt; in the REPL, returning only "Found 150 results"&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The variable &lt;code&gt;RESULTS&lt;/code&gt; is bound to the actual value in the REPL. This binding acts as a pointer, revealing the location of the data within the server's memory. Subsequent operations, queries, for example, or updates, use this reference to access the data. But the data itself never actually enters the conversation:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Turn 1: &amp;#40;grep &amp;quot;def &amp;quot;&amp;#41;         → Server stores 150 matches as RESULTS
                              → Context gets: &amp;quot;Found 150 results&amp;quot;

Turn 2: &amp;#40;count RESULTS&amp;#41;       → Server counts its local RESULTS
                              → Context gets: &amp;quot;150&amp;quot;

Turn 3: &amp;#40;filter RESULTS ...&amp;#41;  → Server filters locally
                              → Context gets: &amp;quot;Filtered to 42 results&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The LLM never sees the 150 function definitions, just the aggregated answers from these functions.&lt;/p&gt;&lt;h3 id="3.&amp;#95;synthesis&amp;#95;from&amp;#95;examples"&gt;3. Synthesis from Examples&lt;/h3&gt;&lt;p&gt;When queries need custom parsing, Matryoshka synthesizes functions from examples:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;synthesize&amp;#95;extractor
  &amp;quot;$1,250.00&amp;quot; 1250.00
  &amp;quot;€500&amp;quot; 500
  &amp;quot;$89.99&amp;quot; 89.99&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The synthesizer learns the pattern directly from examples, obtaining numerical values straight from the currency strings and entirely circumventing the need to construct manual regex.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="the&amp;#95;lifecycle"&gt;The Lifecycle&lt;/h2&gt;&lt;p&gt;A typical Matryoshka session:&lt;/p&gt;&lt;h3 id="1.&amp;#95;load&amp;#95;document"&gt;1. Load Document&lt;/h3&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;load &amp;quot;./plugin/&amp;#95;&amp;#95;init&amp;#95;&amp;#95;.py&amp;quot;&amp;#41;
→ &amp;quot;Loaded: 2,244 lines, 71.5 KB&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The document is parsed and stored server-side. Only metadata enters the context.&lt;/p&gt;&lt;h3 id="2.&amp;#95;query&amp;#95;incrementally"&gt;2. Query Incrementally&lt;/h3&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;grep &amp;quot;@util.api&amp;quot;&amp;#41;
→ &amp;quot;Found 122 results, bound to RESULTS&amp;quot;
   &amp;#91;402&amp;#93; @util.api&amp;#40;&amp;#41;
   &amp;#91;407&amp;#93; @util.api&amp;#40;&amp;#41;
   ... &amp;#40;showing first 20&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Each query returns a preview plus the count. Full data stays on server.&lt;/p&gt;&lt;h3 id="3.&amp;#95;chain&amp;#95;operations"&gt;3. Chain Operations&lt;/h3&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;count RESULTS&amp;#41;           → 122
&amp;#40;filter RESULTS ...&amp;#41;      → &amp;quot;Filtered to 45 results&amp;quot;
&amp;#40;map RESULTS ...&amp;#41;         → Transforms bound to RESULTS
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Operations chain through the &lt;code&gt;RESULTS&lt;/code&gt; binding. Each step refines without re-querying.&lt;/p&gt;&lt;h3 id="4.&amp;#95;close&amp;#95;session"&gt;4. Close Session&lt;/h3&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;close&amp;#41;
→ &amp;quot;Session closed, memory freed&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Sessions auto-expire after 10 minutes of inactivity.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="how&amp;#95;agents&amp;#95;discover&amp;#95;and&amp;#95;use&amp;#95;matryoshka"&gt;How Agents Discover and Use Matryoshka&lt;/h2&gt;&lt;p&gt;Matryoshka integrates with LLM agents via the &lt;a href='https://modelcontextprotocol.io/'&gt;Model Context Protocol (MCP)&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="tool&amp;#95;discovery"&gt;Tool Discovery&lt;/h3&gt;&lt;p&gt;When Claude Code starts, it launches Matryoshka as an MCP server and receives a tool manifest:&lt;/p&gt;&lt;pre&gt;&lt;code class="json"&gt;{
  &amp;quot;tools&amp;quot;: &amp;#91;
    {
      &amp;quot;name&amp;quot;: &amp;quot;lattice&amp;#95;load&amp;quot;,
      &amp;quot;description&amp;quot;: &amp;quot;Load a document for analysis...&amp;quot;
    },
    {
      &amp;quot;name&amp;quot;: &amp;quot;lattice&amp;#95;query&amp;quot;,
      &amp;quot;description&amp;quot;: &amp;quot;Execute a Nucleus query...&amp;quot;
    },
    {
      &amp;quot;name&amp;quot;: &amp;quot;lattice&amp;#95;help&amp;quot;,
      &amp;quot;description&amp;quot;: &amp;quot;Get Nucleus command reference...&amp;quot;
    }
  &amp;#93;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Claude sees the available tools and their descriptions. When a user asks to analyze a file, Claude decides which tools to use based on the task.&lt;/p&gt;&lt;h3 id="guided&amp;#95;discovery"&gt;Guided Discovery&lt;/h3&gt;&lt;p&gt;The &lt;code&gt;lattice&amp;#95;help&lt;/code&gt; tool returns a command reference, teaching the LLM the query language on-demand:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;; Search commands
&amp;#40;grep &amp;quot;pattern&amp;quot;&amp;#41;              ; Regex search
&amp;#40;fuzzy&amp;#95;search &amp;quot;query&amp;quot; 10&amp;#41;     ; Fuzzy match, top N
&amp;#40;lines 10 20&amp;#41;                 ; Get line range

; Aggregation
&amp;#40;count RESULTS&amp;#41;               ; Count items
&amp;#40;sum RESULTS&amp;#41;                 ; Sum numeric values

; Transformation
&amp;#40;map RESULTS fn&amp;#41;              ; Transform each item
&amp;#40;filter RESULTS pred&amp;#41;         ; Keep matching items
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The agent learns capabilities incrementally rather than needing upfront training.&lt;/p&gt;&lt;h3 id="session&amp;#95;flow"&gt;Session Flow&lt;/h3&gt;&lt;pre&gt;&lt;code&gt;User: &amp;quot;How many API endpoints does anki-connect have?&amp;quot;

Claude: &amp;#91;Calls lattice&amp;#95;load&amp;#40;&amp;quot;plugin/&amp;#95;&amp;#95;init&amp;#95;&amp;#95;.py&amp;quot;&amp;#41;&amp;#93;
        → &amp;quot;Loaded: 2,244 lines&amp;quot;

Claude: &amp;#91;Calls lattice&amp;#95;query&amp;#40;'&amp;#40;grep &amp;quot;@util.api&amp;quot;&amp;#41;'&amp;#41;&amp;#93;
        → &amp;quot;Found 122 results&amp;quot;

Claude: &amp;#91;Calls lattice&amp;#95;query&amp;#40;'&amp;#40;count RESULTS&amp;#41;'&amp;#41;&amp;#93;
        → &amp;quot;122&amp;quot;

Claude: &amp;quot;The anki-connect plugin exposes 122 API endpoints,
         decorated with @util.api&amp;#40;&amp;#41;.&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Each tool invocation maintains its own state within the conversation. So, for example, when a document is loaded, that content is retained in memory. Similarly, the results of any query that is executed are saved and available for later use.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;h2 id="real-world&amp;#95;example:&amp;#95;analyzing&amp;#95;anki-connect"&gt;Real-World Example: Analyzing anki-connect&lt;/h2&gt;&lt;p&gt;Let's walk through a complete analysis of the &lt;a href='https://git.sr.ht/~foosoft/anki-connect'&gt;anki-connect&lt;/a&gt; Anki plugin. Here we have a real-world codebase with 7,770 lines across 17 files.&lt;/p&gt;&lt;h3 id="the&amp;#95;task"&gt;The Task&lt;/h3&gt;&lt;p&gt;"Analyze the anki-connect codebase: find all classes, count API endpoints, extract configuration defaults, and document the architecture."&lt;/p&gt;&lt;h3 id="the&amp;#95;workflow"&gt;The Workflow&lt;/h3&gt;&lt;p&gt;The agent uses Matryoshka's &lt;a href='https://github.com/yogthos/Matryoshka/blob/4a2143851eed8245d7a314694a2ba9eb6ab80466/src/lattice-mcp-server.ts#L97'&gt;prompt hints&lt;/a&gt; to accomplish the following workflow:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;1. &lt;strong&gt;Discover files&lt;/strong&gt; with Glob&lt;/li&gt;&lt;li&gt;2. &lt;strong&gt;Read small files directly&lt;/strong&gt; (&lt;300 lines)&lt;/li&gt;&lt;li&gt;3. &lt;strong&gt;Use Matryoshka for large files&lt;/strong&gt; (&gt;500 lines)&lt;/li&gt;&lt;li&gt;4. &lt;strong&gt;Aggregate across all files&lt;/strong&gt;&lt;h2&gt;&lt;/h2&gt;&lt;/li&gt;&lt;/ol&gt;&lt;h3 id="step&amp;#95;1:&amp;#95;file&amp;#95;discovery"&gt;Step 1: File Discovery&lt;/h3&gt;&lt;pre&gt;&lt;code&gt;Glob &amp;#42;&amp;#42;/&amp;#42;.py → 15 Python files
Glob &amp;#42;&amp;#42;/&amp;#42;.md → 2 markdown files

File sizes:
  plugin/&amp;#95;&amp;#95;init&amp;#95;&amp;#95;.py    2,244 lines  → Matryoshka
  plugin/edit.py          458 lines  → Read directly
  plugin/web.py           301 lines  → Read directly
  plugin/util.py          107 lines  → Read directly
  README.md             4,660 lines  → Matryoshka
  tests/&amp;#42;.py           11 files      → Skip &amp;#40;tests&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h2&gt;&lt;/h2&gt;&lt;h3 id="step&amp;#95;2:&amp;#95;read&amp;#95;small&amp;#95;files"&gt;Step 2: Read Small Files&lt;/h3&gt;&lt;p&gt;Reading &lt;code&gt;util.py&lt;/code&gt; (107 lines) reveals configuration defaults:&lt;/p&gt;&lt;pre&gt;&lt;code class="python"&gt;DEFAULT&amp;#95;CONFIG = {
    'apiKey': None,
    'apiLogPath': None,
    'apiPollInterval': 25,
    'apiVersion': 6,
    'webBacklog': 5,
    'webBindAddress': '127.0.0.1',
    'webBindPort': 8765,
    'webCorsOrigin': None,
    'webCorsOriginList': &amp;#91;'http://localhost'&amp;#93;,
    'ignoreOriginList': &amp;#91;&amp;#93;,
    'webTimeout': 10000,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Reading &lt;code&gt;web.py&lt;/code&gt; (301 lines) reveals the server architecture:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;- Classes: &lt;code&gt;WebRequest&lt;/code&gt;, &lt;code&gt;WebClient&lt;/code&gt;, &lt;code&gt;WebServer&lt;/code&gt;&lt;/li&gt;&lt;li&gt;- JSON-RPC style API with jsonschema validation&lt;/li&gt;&lt;li&gt;- CORS support with configurable origins&lt;h2&gt;&lt;/h2&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="step&amp;#95;3:&amp;#95;query&amp;#95;large&amp;#95;files&amp;#95;with&amp;#95;matryoshka"&gt;Step 3: Query Large Files with Matryoshka&lt;/h3&gt;&lt;pre&gt;&lt;code class="clojure"&gt;; Load the main plugin file
&amp;#40;load &amp;quot;plugin/&amp;#95;&amp;#95;init&amp;#95;&amp;#95;.py&amp;quot;&amp;#41;
→ &amp;quot;Loaded: 2,244 lines, 71.5 KB&amp;quot;

; Find all classes
&amp;#40;grep &amp;quot;&amp;#94;class &amp;quot;&amp;#41;
→ &amp;quot;Found 1 result: &amp;#91;65&amp;#93; class AnkiConnect:&amp;quot;

; Count methods
&amp;#40;grep &amp;quot;def \\w+\\&amp;#40;self&amp;quot;&amp;#41;
→ &amp;quot;Found 148 results&amp;quot;

; Count API endpoints
&amp;#40;grep &amp;quot;@util.api&amp;quot;&amp;#41;
→ &amp;quot;Found 122 results&amp;quot;

; Load README for documentation
&amp;#40;load &amp;quot;README.md&amp;quot;&amp;#41;
→ &amp;quot;Loaded: 4,660 lines, 107.2 KB&amp;quot;

; Find documented action categories
&amp;#40;grep &amp;quot;&amp;#94;### &amp;quot;&amp;#41;
→ &amp;quot;Found 13 sections&amp;quot;
   &amp;#91;176&amp;#93; ### Card Actions
   &amp;#91;784&amp;#93; ### Deck Actions
   &amp;#91;1231&amp;#93; ### Graphical Actions
   ...
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="complete&amp;#95;findings"&gt;Complete Findings&lt;/h3&gt;&lt;p&gt;&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Metric&lt;/th&gt; &lt;th&gt;Value&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Total files&lt;/td&gt; &lt;td&gt;17 (15 .py + 2 .md)&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Total lines&lt;/td&gt; &lt;td&gt;7,770&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Classes&lt;/td&gt; &lt;td&gt;8 (1 main + 3 web + 4 edit)&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Instance methods&lt;/td&gt; &lt;td&gt;148&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;API endpoints&lt;/td&gt; &lt;td&gt;122&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Config settings&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Imports&lt;/td&gt; &lt;td&gt;48&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Documentation sections&lt;/td&gt; &lt;td&gt;8 categories, 120 endpoints&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;&lt;/p&gt;&lt;h3 id="token&amp;#95;usage&amp;#95;comparison"&gt;Token Usage Comparison&lt;/h3&gt;&lt;p&gt;&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Approach&lt;/th&gt; &lt;th&gt;Lines Processed&lt;/th&gt; &lt;th&gt;Tokens Used&lt;/th&gt; &lt;th&gt;Coverage&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Read everything&lt;/td&gt; &lt;td&gt;7,770&lt;/td&gt; &lt;td&gt;~95,000&lt;/td&gt; &lt;td&gt;100%&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Matryoshka only&lt;/td&gt; &lt;td&gt;6,904&lt;/td&gt; &lt;td&gt;~6,500&lt;/td&gt; &lt;td&gt;65%&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Hybrid&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;7,770&lt;/td&gt; &lt;td&gt;&lt;strong&gt;~17,000&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;100%&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;&lt;/p&gt;&lt;p&gt;The hybrid method achieves a &lt;strong&gt;82% savings&lt;/strong&gt; in tokens while retaining 100% of the original coverage. This approach combines two different strategies, one for compressing redundant information and one for preserving unique insights.&lt;/p&gt;&lt;p&gt;The pure Matryoshka approach ends up missing details from small files (configuration defaults, web server classes), because Claude only uses the tool to query large ones. The hybrid workflow does direct, full-content reads on small files, while leveraging Matryoshka to analyze bigger files, in a kind of divide-and-conquer strategy. All that's needed is to provide the agent an explicit hint on the strategy to use.&lt;/p&gt;&lt;h3 id="why&amp;#95;hybrid&amp;#95;works"&gt;Why Hybrid Works&lt;/h3&gt;&lt;p&gt;Small files (&lt;300 lines) contain critical details:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;- &lt;code&gt;util.py&lt;/code&gt;: All configuration defaults, the API decorator implementation&lt;/li&gt;&lt;li&gt;- &lt;code&gt;web.py&lt;/code&gt;: Server architecture, CORS handling, request schema&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;These fit comfortably in context, and there's no need to do anything different. Matryoshka adds value for:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;- &lt;code&gt;&amp;#95;&amp;#95;init&amp;#95;&amp;#95;.py&lt;/code&gt; (2,244 lines): Query specific patterns without loading everything&lt;/li&gt;&lt;li&gt;- &lt;code&gt;README.md&lt;/code&gt; (4,660 lines): Search documentation sections on demand&lt;h2&gt;&lt;/h2&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h2 id="architecture"&gt;Architecture&lt;/h2&gt;&lt;pre&gt;&lt;code&gt;┌─────────────────────────────────────────────────────────┐
│                     Adapters                            │
│  ┌──────────┐  ┌──────────┐  ┌───────────────────────┐  │
│  │   Pipe   │  │   HTTP   │  │   MCP Server          │  │
│  └────┬─────┘  └────┬─────┘  └───────────┬───────────┘  │
│       │             │                    │              │
│       └─────────────┴────────────────────┘               │
│                          │                              │
│                ┌─────────┴─────────┐                    │
│                │   LatticeTool     │                    │
│                │   &amp;#40;Stateful&amp;#41;      │                    │
│                │   • Document      │                    │
│                │   • Bindings      │                    │
│                │   • Session       │                    │
│                └─────────┬─────────┘                    │
│                          │                              │
│                ┌─────────┴─────────┐                    │
│                │  NucleusEngine    │                    │
│                │  • Parser         │                    │
│                │  • Type Checker   │                    │
│                │  • Evaluator      │                    │
│                └─────────┬─────────┘                    │
│                          │                              │
│                ┌─────────┴─────────┐                    │
│                │    Synthesis      │                    │
│                │  • Regex          │                    │
│                │  • Extractors     │                    │
│                │  • miniKanren     │                    │
│                └───────────────────┘                    │
└─────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;&lt;h2&gt;&lt;/h2&gt;&lt;h2 id="getting&amp;#95;started"&gt;Getting Started&lt;/h2&gt;&lt;p&gt;Install from npm:&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;npm install matryoshka-rlm
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="as&amp;#95;mcp&amp;#95;server&amp;#95;(claude&amp;#95;code&amp;#95;/&amp;#95;claude&amp;#95;desktop)"&gt;As MCP Server (Claude Code / Claude Desktop)&lt;/h3&gt;&lt;p&gt;Add to your Claude configuration:&lt;/p&gt;&lt;pre&gt;&lt;code class="json"&gt;{
  &amp;quot;mcpServers&amp;quot;: {
    &amp;quot;lattice&amp;quot;: {
      &amp;quot;command&amp;quot;: &amp;quot;npx&amp;quot;,
      &amp;quot;args&amp;quot;: &amp;#91;&amp;quot;lattice-mcp&amp;quot;&amp;#93;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="programmatic&amp;#95;use"&gt;Programmatic Use&lt;/h3&gt;&lt;pre&gt;&lt;code class="typescript"&gt;import { NucleusEngine } from &amp;quot;matryoshka-rlm&amp;quot;;

const engine = new NucleusEngine&amp;#40;&amp;#41;;
await engine.loadFile&amp;#40;&amp;quot;./document.txt&amp;quot;&amp;#41;;

const result = engine.execute&amp;#40;'&amp;#40;grep &amp;quot;pattern&amp;quot;&amp;#41;'&amp;#41;;
console.log&amp;#40;result.value&amp;#41;; // Array of matches
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="interactive&amp;#95;repl"&gt;Interactive REPL&lt;/h3&gt;&lt;pre&gt;&lt;code class="bash"&gt;npx lattice-repl
lattice&amp;gt; :load ./data.txt
lattice&amp;gt; &amp;#40;grep &amp;quot;ERROR&amp;quot;&amp;#41;
lattice&amp;gt; &amp;#40;count RESULTS&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h2&gt;&lt;/h2&gt;&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;&lt;p&gt;Matryoshka embodies the principle, emerging from RLM research, that documents are to be treated as external environments rather than as contexts to be parsed. This principle alters the fundamental character of the model’s engagement, no longer a passive reader but an active agent, navigating through and interrogating a document to extract specific information, somewhat as a programmer would browse through code. Combined with Barliman-style synthesis, in which a solution is built up in a series of small, well-defined steps, and pointer-based state management, it achieves:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;- &lt;strong&gt;82% token savings&lt;/strong&gt; on real-world codebase analysis&lt;/li&gt;&lt;li&gt;- &lt;strong&gt;100% coverage&lt;/strong&gt; when combined with direct reads for small files&lt;/li&gt;&lt;li&gt;- &lt;strong&gt;Incremental exploration&lt;/strong&gt; where each query builds on previous results&lt;/li&gt;&lt;li&gt;- &lt;strong&gt;No context rot&lt;/strong&gt; because documents stay outside the model&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;We observe that variable bindings such as &lt;code&gt;RESULTS&lt;/code&gt; refer to REPL state rather than holding data directly in model context. As we formulate and submit queries, what is sent to the server are mere pointers, placeholders indicating where the actual computation should occur. It is the server that executes the substantive computational tasks, returning only the distilled results.&lt;/p&gt;&lt;p&gt;The tool is open source: &lt;a href='https://github.com/yogthos/Matryoshka'&gt;https://github.com/yogthos/Matryoshka&lt;/a&gt;&lt;/p&gt;</description><pubDate>Fri, 16 Jan 2026 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2026-01-12-recursive-language-model.html</guid><link>https://yogthos.net/posts/2026-01-12-recursive-language-model.html</link><title>Grounding LLMs with Recursive Code Execution</title><description>&lt;p&gt;Despite context windows expanding to millions of tokens, LLMs still struggle with the fundamental task of precision. When you ask an LLM to "analyze this report," it often glances at the text and simply hallucinates a plausible-sounding answer based on probability.&lt;/p&gt;&lt;p&gt;A good example of the problem can be seen when asking a model to sum sales figures from a financial report. Left to its own devices, it will likely not bother reading the whole document and simply give you a made-up answer. This is especially a problem with smaller models that you can run locally.&lt;/p&gt;&lt;p&gt;The standard approach to dealing with this problem is to use Retrieval Augmented Generation (RAG), which relies on semantic similarity (embeddings). If you ask for "sales figures," a Vector DB retrieves chunks of text that sound like sales figures. However, semantic similarity is fuzzy and limited in functionality. Embeddings can't count, so you can't ask questions like "count the number of times X happens." They also can't handle information scattered across a bunch of unrelated lines in a document. Furthermore, they don't distinguish between concepts like "Projected Sales" and "Actual Sales" when they appear in similar contexts.&lt;/p&gt;&lt;p&gt;It would be nice to have a system that treats text as a dataset to be queried rather than a prompt to be completed. This is where the &lt;a href='https://arxiv.org/abs/2512.24601'&gt;Recursive Language Model paper&lt;/a&gt; comes in. The core idea here is that instead of having the model operate directly on the document, it uses a programmatic interface to interact with it via a REPL. The model acts as a programmer writing code to explore the document, interpreting execution results, and only then formulating an answer based on them.&lt;/p&gt;&lt;p&gt;The core insight is that code execution provides grounding for the model. When an LLM guesses a number by trying to understand the document, it might be right, or it might be wrong. It has no way to know. When it writes &lt;code&gt;regex.match&amp;#40;&amp;#41;&lt;/code&gt; and the computer returns &lt;code&gt;&amp;#91;'$2,340,000'&amp;#93;&lt;/code&gt;, that result is a hard fact. What the model needs to understand is how to form a query—a general task it's likely good at—instead of trying to solve a domain-specific problem it has no direct training on.&lt;/p&gt;&lt;p&gt;Allowing an LLM to write and run code directly on your system would obviously be a security nightmare, so the implementation uses &lt;code&gt;isolated-vm&lt;/code&gt; to create a secure sandbox for it to play in. The model cannot hallucinate &lt;code&gt;rm -rf /&lt;/code&gt; or &lt;code&gt;curl&lt;/code&gt; a random URL. Having a sandbox also prevents infinite loops or memory leaks. And since the document is immutable, the model can read it but cannot alter the source truth.&lt;/p&gt;&lt;p&gt;The process works as follows:&lt;/p&gt;&lt;p&gt;&lt;ol&gt; &lt;li&gt;1. The document is loaded into a secure, isolated Node.js environment as a read-only &lt;code&gt;context&lt;/code&gt; variable.&lt;/li&gt; &lt;li&gt;2. The model is given exploration tools: &lt;code&gt;text&amp;#95;stats&amp;#40;&amp;#41;&lt;/code&gt;, &lt;code&gt;fuzzy&amp;#95;search&amp;#40;&amp;#41;&lt;/code&gt;, and &lt;code&gt;slice&amp;#40;&amp;#41;&lt;/code&gt;.&lt;/li&gt; &lt;li&gt;3. The Loop: &lt;ul&gt; &lt;li&gt;&lt;span&gt;&amp;#8195;&lt;/span&gt;• The model writes TypeScript to probe the text.&lt;/li&gt; &lt;li&gt;&lt;span&gt;&amp;#8195;&lt;/span&gt;• The Sandbox executes it and returns the output.&lt;/li&gt; &lt;li&gt;&lt;span&gt;&amp;#8195;&lt;/span&gt;• The model reads the result and refines its next step.&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;4. The loop iterates until the model has enough proven data to answer &lt;code&gt;FINAL&amp;#40;&amp;quot;...&amp;quot;&amp;#41;&lt;/code&gt;.&lt;/li&gt; &lt;/ol&gt;&lt;/p&gt;&lt;p&gt;&lt;img src="/img/rlm/rlm.jpg" alt="RLM execution model" width="600" /&gt;&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;p&gt;The system can work entirely locally using something like Ollama with Qwen-Coder, or with hosted models like DeepSeek, which are much smarter by default. It also works as an MCP that you can plug in and let your agent use to solve problems.&lt;/p&gt;&lt;p&gt;Finally, I used Universal Tool Calling Protocol (UTCP) patterns from &lt;a href='https://github.com/universal-tool-calling-protocol/code-mode'&gt;code-mode&lt;/a&gt; to generate strict TypeScript interfaces. This provides the LLM with a strict contract such as:&lt;/p&gt;&lt;pre&gt;&lt;code class="typescript"&gt;// The LLM sees exactly this signature in its system prompt
declare function fuzzy&amp;#95;search&amp;#40;query: string, limit?: number&amp;#41;: Array&amp;lt;{
  line: string;
  lineNum: number;
  score: number; // 0 to 1 confidence
}&amp;gt;;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One problem is that LLMs tend to be messy coders; they forget semicolons, use hallucinated imports, etc. The way around that is to add a self-healing layer. If the sandbox throws a syntax error, a lightweight intermediate step attempts to fix imports and syntax before re-running. This keeps the reasoning chain alive and minimizes round trips to the model.&lt;/p&gt;&lt;p&gt;As a demo to test out the concept, I made a &lt;a href='https://github.com/yogthos/Matryoshka/blob/main/test-fixtures/scattered-data.txt'&gt;document&lt;/a&gt; containing a bunch of scattered data, with 5 distinct sales figures hidden inside 4,700 characters of Lorem Ipsum filler and unrelated business jargon.&lt;/p&gt;&lt;p&gt;Predictably, feeding the text into a standard context window and asking for the total promptly resulted in a hallucinated total of $480,490. It just grabbed numbers that looked like currency from unrelated sections, mashed them together, and called it a day.&lt;/p&gt;&lt;p&gt;Running the same query through RLM was a completely different story. The model took 4 iterations to converge on the actual solution. Instead of trying to guess, it started writing code to explore the document. It first checked the file size:&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;const stats = text&amp;#95;stats&amp;#40;&amp;#41;;
console.log&amp;#40;`Document length: ${stats.length}, Lines: ${stats.lineCount}`&amp;#41;;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, it used fuzzy search to locate relevant lines, ignoring the noise:&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;const matches = fuzzy&amp;#95;search&amp;#40;&amp;quot;SALES&amp;#95;DATA&amp;quot;&amp;#41;;
console.log&amp;#40;matches&amp;#41;;
// Output: &amp;#91;
//   { line: &amp;quot;SALES&amp;#95;DATA&amp;#95;NORTH: $2,340,000&amp;quot;, ... },
//   { line: &amp;quot;SALES&amp;#95;DATA&amp;#95;SOUTH: $3,120,000&amp;quot;, ... }
// &amp;#93;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And finally, it wrote a regex to parse the strings into integers and summed them programmatically to get the correct result:&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;// ...regex parsing logic...
console.log&amp;#40;&amp;quot;Calculated Total:&amp;quot;, total&amp;#41;; // Output: 13000000

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Only after the code output confirmed the math did the model verify the answer.&lt;/p&gt;&lt;p&gt;The key difference is that the traditional approach asks the model "what does this document say," while the recursive coding approach asks it to "write a program to find out what this document says." The logic is now expressed using actual code, and the role of the LLM is to write the code and read the results as opposed to working with the document directly.&lt;/p&gt;&lt;p&gt;As with all things, there is a trade-off here: the RLM approach is slower since it takes multiple turns and can generate more tokens as a result. However, if the document you're working on is itself large, then you will actually save context tokens by not loading it directly.&lt;/p&gt;&lt;h4 id="mcp&amp;#95;integration"&gt;MCP Integration&lt;/h4&gt;&lt;h2&gt;&lt;/h2&gt;&lt;p&gt;The project also &lt;a href='https://www.npmjs.com/package/matryoshka-rlm'&gt;includes an MCP&lt;/a&gt; (Model Context Protocol) server, making it available as a tool for coding agents like &lt;a href='https://github.com/charmbracelet/crush'&gt;Crush&lt;/a&gt;. Once configured, you can ask the agent to analyze documents that would otherwise exceed its context window or require precise data extraction.&lt;/p&gt;&lt;p&gt;The server exposes an &lt;code&gt;analyze&amp;#95;document&lt;/code&gt; tool that takes a query and file path. The tool can then use the RLM approach to explore documents by writing code, executing it in the sandbox, and iterating until it finds the answer.&lt;/p&gt;&lt;p&gt;This creates an interesting dynamic where you agent writes the high-level query, the RLM's backing model (which can be a local Ollama instance) does the iterative code exploration, and the verified results come back to your agent. The grounding problem is solved at the tool level, so the agent can trust the results it receives.&lt;h2&gt;&lt;/h2&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;The implementation is available at &lt;a href='https://github.com/yogthos/Matryoshka'&gt;https://github.com/yogthos/Matryoshka&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;</description><pubDate>Mon, 12 Jan 2026 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2025-12-11-edge-aware-pixelation.html</guid><link>https://yogthos.net/posts/2025-12-11-edge-aware-pixelation.html</link><title>Edge-Aware Pixelation for Better Pixel Art</title><description>&lt;p&gt;Pixelation is everywhere these days, from retro game aesthetics to modern design trends. But if you've ever tried to create pixel art from a photograph, you've probably noticed that the results often look a bit off. Edges get jagged, important features get distorted, and the whole image tends to lose its character.&lt;/p&gt;&lt;p&gt;Most pixelation algorithms rely on the same approach of downscaling the image, then upscaling it back. While this is fast and cheap to implement, it treats every part of the image the same way forcing a rigid grid that cuts indiscriminately across edges, faces, and fine details.&lt;/p&gt;&lt;p&gt;In this post, we'll take a look at a strategy of using edge-aware pixelation. The idea here is to use an algorithm that adapts to the structure of the image rather than forcing a uniform grid onto it. We'll look at how it works, why it tends to produce better results, and the trade-offs involved.&lt;/p&gt;&lt;h3 id="the&amp;#95;traditional&amp;#95;approach"&gt;The Traditional Approach&lt;/h3&gt;&lt;p&gt;Let's start by looking at what most pixelation libraries do under the hood. The most common approach uses standard image scaling with smoothing.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;// Pseudo-code for traditional pixelation
const downscaled = scaleDown&amp;#40;image, pixelSize&amp;#41;; // Uses bilinear/bicubic
const pixelated = scaleUp&amp;#40;downscaled, originalSize&amp;#41;; // Nearest-neighbor
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;While this works, there are a few obvious problems. Smoothing filters tend to blur important edges before downsampling, and the pixel grid doesn't care about the image content. This often leads to artifacts where edges get "chopped" across pixel boundaries, creating jagged lines. You also end up losing fine features like eyes or text.&lt;/p&gt;&lt;p&gt;Some approaches try to improve on this using median color sampling instead of averaging.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;// Sample colors in each block, pick median
const blockColor = median&amp;#40;colorsInBlock&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This avoids some of the blurring, but it still suffers from the same fixed grid issue. It ignores the image structure and can create harsh transitions between blocks.&lt;/p&gt;&lt;p&gt;Basically, all these methods force a uniform grid onto the image without considering its content. The result is usually pixel blocks that cut across important features. For example, if we use the following &lt;a href='https://commons.wikimedia.org/wiki/File:CANADAMIKE.jpg'&gt;image from wikimedia&lt;/a&gt; as the input.&lt;/p&gt;&lt;p&gt;&lt;img src="/img/pixelation/CANADAMIKE.jpg" alt="stock portrait" /&gt;&lt;/p&gt;&lt;p&gt;The result ends up looking something like the following when using a naive pixelation algorithm:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/pixelation/pixelated-naive.png" alt="Naive pixelation" /&gt;&lt;/p&gt;&lt;h3 id="edge-aware&amp;#95;adaptive&amp;#95;grid"&gt;Edge-Aware Adaptive Grid&lt;/h3&gt;&lt;p&gt;Instead of forcing a rigid grid, we can let the grid adapt to the image. This is the core idea behind edge-aware pixelation. We can treat pixelation as an optimization problem with four main stages.&lt;/p&gt;&lt;h4 id="1&amp;#46;&amp;#95;edge&amp;#95;detection"&gt;1&amp;#46; Edge Detection&lt;/h4&gt;&lt;p&gt;First, we need to understand where the important features are in the image.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;// Sobel operators detect gradient magnitude and direction
const gradient = calculateGradient&amp;#40;image&amp;#41;;
const edges = applyNonMaximumSuppression&amp;#40;gradient&amp;#41;;
const edgeMap = thresholdEdges&amp;#40;edges, sharpness&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We use Sobel operators to compute the gradient magnitude, and then apply non-maximum suppression to thin the edges to a single-pixel width. Finally, we use percentile-based thresholding to adapt to the edge distribution of the specific image. Since this can be computationally expensive, using WebGL can provide a significant speedup here.&lt;/p&gt;&lt;p&gt;This gives us an edge map where bright pixels represent edges and dark pixels represent smooth regions.&lt;/p&gt;&lt;p&gt;&lt;img src="/img/pixelation/edges.png" alt="Sobel edges" /&gt;&lt;/p&gt;&lt;h4 id="2&amp;#46;&amp;#95;grid&amp;#95;initialization"&gt;2&amp;#46; Grid Initialization&lt;/h4&gt;&lt;p&gt;Next, we start with a regular grid matching the target pixel size.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;const grid = createUniformGrid&amp;#40;width, height, pixelSize&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Unlike traditional methods, the grid is just a starting point. Each cell is defined by four corner points which we can move around.&lt;/p&gt;&lt;p&gt;&lt;img src="/img/pixelation/grid.png" alt="Initial grid" /&gt;&lt;/p&gt;&lt;h4 id="3&amp;#46;&amp;#95;grid&amp;#95;optimization"&gt;3&amp;#46; Grid Optimization&lt;/h4&gt;&lt;p&gt;This is where the actual work happens. We iteratively move the grid corners to align the cell boundaries with the detected edges.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;for &amp;#40;let iteration = 0; iteration &amp;lt; numIterations; iteration++&amp;#41; {
  for &amp;#40;each corner in grid&amp;#41; {
    // Search nearby positions
    const candidates = searchNeighborhood&amp;#40;corner, stepSize&amp;#41;;

    // Evaluate how well each position aligns edges
    for &amp;#40;const candidate of candidates&amp;#41; {
      const score = evaluateEdgeAlignment&amp;#40;candidate, edgeMap&amp;#41;;
      if &amp;#40;score &amp;gt; bestScore&amp;#41; {
        bestPosition = candidate;
      }
    }

    // Move corner toward best position &amp;#40;with damping&amp;#41;
    corner.moveToward&amp;#40;bestPosition, damping&amp;#41;;
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For each corner, we test multiple positions in a local neighborhood and evaluate the alignment by sampling edge strength along the grid edges. We want to find positions where the grid boundaries follow the edges continuously. We also use damping to prevent over-optimization and maintain stability.&lt;/p&gt;&lt;p&gt;The result is a grid that bends and adapts to align with the natural structure of the image.&lt;/p&gt;&lt;p&gt;&lt;img src="/img/pixelation/optimized-grid.png" alt="Optimized grid" /&gt;&lt;/p&gt;&lt;h4 id="4&amp;#46;&amp;#95;color&amp;#95;assignment"&gt;4&amp;#46; Color Assignment&lt;/h4&gt;&lt;p&gt;Finally, we need to assign colors to our optimized cells.&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;for &amp;#40;each cell in grid&amp;#41; {
  const pixels = samplePixelsInCell&amp;#40;cell&amp;#41;;

  // Blend between average &amp;#40;soft&amp;#41; and median &amp;#40;crisp&amp;#41; based on edge presence
  if &amp;#40;cell.hasEdges&amp;#41; {
    color = blend&amp;#40;average&amp;#40;pixels&amp;#41;, median&amp;#40;pixels&amp;#41;, sharpness&amp;#41;;
  } else {
    color = average&amp;#40;pixels&amp;#41;; // Smooth regions use average
  }

  renderCell&amp;#40;cell, color&amp;#41;;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here we can use a blending strategy. For smooth regions, we use the average color for natural blending. For edge regions, we can blend between average and median based on the desired sharpness. This lets us tune the aesthetic from soft, blended edges to crisp, high-contrast ones. Looking at the two methods side by side, we can see how much smoother the resulting image is:&lt;/p&gt;&lt;p&gt;&lt;table border="0"&gt; &lt;tr&gt;&lt;th&gt;Edge detection&lt;/th&gt;&lt;th&gt;Naive&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;img src="/img/pixelation/pixelated-edges.png" alt="Edge detected pixelation" /&gt;&lt;/td&gt;&lt;td&gt;&lt;img src="/img/pixelation/pixelated-naive.png" alt="Naive pixelation" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&lt;/p&gt;&lt;h3 id="discussion"&gt;Discussion&lt;/h3&gt;&lt;p&gt;There are several advantages to this approach. The most obvious is edge preservation. Traditional methods create jagged artifacts because pixel boundaries cut across edges. By aligning the grid boundaries with the edges, we can preserve continuity and create smoother transitions.&lt;/p&gt;&lt;p&gt;This also means we don't get those choppy edges on outlines, and we can preserve fine details like facial features or text much better. The algorithm effectively has some semantic awareness of what's important in the image.&lt;/p&gt;&lt;p&gt;However, there are trade-offs to consider. The adaptive grid and color blending can produce softer edges compared to traditional methods. If you're looking for extremely crisp, high-contrast pixel art with hard edges, like what you'd see in retro games, traditional downsampling might actually be a better fit.&lt;/p&gt;&lt;p&gt;You also get less contrast in some cases. The color blending can reduce the overall "punchiness" compared to median sampling.&lt;/p&gt;&lt;p&gt;Performance is another factor. Edge-aware pixelation is computationally more intensive. You have to handle edge detection, iterative grid optimization, and spatial hashing for rendering. While WebGL optimizations make it practical taking 100-500ms on most images, simple downsampling will always be faster.&lt;/p&gt;&lt;p&gt;I've found that edge-aware pixelation works best for photographs, portraits, and complex scenes where preserving structure is important. It's less ideal for abstract art or images where a uniform grid is desired for stylistic reasons.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;By detecting edges and optimizing alignment, edge-aware pixelation produces pixel art that does a good job of preserving the essence of the original while still achieving low-resolution aesthetic.&lt;/p&gt;&lt;p&gt;If you're interested in trying this out live &lt;a href='https://yogthos.net/pixel-mosaic.html'&gt;here&lt;/a&gt;, and all the code is available as an open source library called &lt;a href='https://github.com/yogthos/pixel-mosaic'&gt;Pixel Mosaic&lt;/a&gt; that implements both traditional and edge-aware pixelation.&lt;/p&gt;&lt;p&gt;I hope this gives you some ideas for your own image processing projects. Sometimes the simple method is enough, but for complex images, the extra effort of edge-aware processing can be well worth it.&lt;/p&gt;</description><pubDate>Thu, 11 Dec 2025 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2023-06-10-disagreement.html</guid><link>https://yogthos.net/posts/2023-06-10-disagreement.html</link><title>Role of Debate in Problem Solving</title><description>&lt;p&gt;Throughout my career, I have come to appreciate the vital role of open debate in the successful execution of projects. Curiously, arguments and disagreements often carry negative connotations, yet they serve as indispensable tools for fostering a shared comprehension of the problems at hand.&lt;/p&gt;&lt;p&gt;Individuals frequently shy away from engaging in arguments due to personal insecurities that hinder the expression of contrary opinions. Moreover, the fear of causing offense through disagreement serves as a deterrent, preventing many from sharing crucial insights with their teams. When these valuable insights remain private, teams are susceptible to investing significant time and effort in constructing solutions that are fundamentally flawed.&lt;/p&gt;&lt;p&gt;Open debate, encompassing the nature of the problem being addressed and the proposed solutions, stands as a pivotal factor in establishing a well-functioning team. It is crucial to recognize that disagreements generally arise from individuals approaching the problem from different perspectives. One developer may ponder a specific set of trade-offs, while another contemplates a different set.&lt;/p&gt;&lt;p&gt;Each developer possesses only a partial view of the overall picture, rendering the solution proposed by the other developer seemingly incorrect from their respective vantage points. The path to comprehending the complete picture involves engaging in dialogue to grasp the trade-offs considered by each person. Once this pivotal step is taken, it becomes possible to arrive at a solution that addresses the concerns of all involved.&lt;/p&gt;&lt;p&gt;The ultimate objective is not necessarily to discover the optimal solution, but rather to consciously select a set of trade-offs that everyone finds agreeable. By doing so, we ensure that all team members possess a shared understanding of the problem at hand and the rationale behind adopting a specific approach to tackle it.&lt;/p&gt;&lt;p&gt;It is vital to recognize that the ability to engage in frank discussions is a gradual process. Engaging in activities such as pair programming, where developers collaborate closely and solve problems together, can facilitate the development of comfort and familiarity. As individuals grow more acquainted with one another, the prospect of openly disagreeing becomes more natural and effortless.&lt;/p&gt;&lt;p&gt;Finally, I highly recommend watching a &lt;a href='https://www.youtube.com/watch?v=fTtnx1AAJ-c'&gt;recent talk&lt;/a&gt; from Rich Hickey discussing this in more detail.&lt;/p&gt;</description><pubDate>Sat, 10 Jun 2023 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2023-05-12-nbb-resume.html</guid><link>https://yogthos.net/posts/2023-05-12-nbb-resume.html</link><title>Making a Resume with Node.js Babashka (nbb)</title><description>&lt;p&gt;I recently had to update my resume and decided that I might as well have some fun with it while I do it. One thing that I've always found frustrating using an editor like OpenOffice is that it conflates the tasks of formatting and editing content. I don't want to have to worry about look and feel when I'm thinking about the content of the resume, and vice versa.&lt;/p&gt;&lt;p&gt;The obvious solution is to create a template for how the resume should look, and then populate it with the relevant data. Of course, there are already off the shelf tools such as &lt;a href='https://jsonresume.org/'&gt;JSON Resume&lt;/a&gt; that do this, but what fun is there in using an existing tool when you can build one that does exactly what you want. Let's take a look at what's involved in making a similar tool with Clojure and &lt;a href='https://github.com/babashka/nbb'&gt;nbb&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I decided to create a Hiccup template that would represent the layout of the HTML document and then to put the contents of the resume in a separate EDN file. Then all I'd need to do would be to walk over the template, inject the data, and render HTML which could then be converted to a PDF document.&lt;/p&gt;&lt;h3 id="specification"&gt;Specification&lt;/h3&gt;&lt;p&gt;Generally, I find it's helpful to start by defining what the API will look like first, and then figure out what the best way to implement it is. This way there is less of a chance that implementation details will bleed into the API. In this scenario the API will be the format of the EDN file and the Hiccup template.&lt;/p&gt;&lt;p&gt;The EDN is just a data structure that's used to organize the data in the resume. I based mine on the &lt;a href='https://jsonresume.org/schema/'&gt;schema&lt;/a&gt; that JSON Resume uses. The schema contains sections such as &lt;code&gt;:basics&lt;/code&gt;, &lt;code&gt;:work&lt;/code&gt;, &lt;code&gt;:education&lt;/code&gt;, and so on. For example, the &lt;code&gt;:basics&lt;/code&gt; section might look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:basics {:name &amp;quot;John Doe&amp;quot;
          :label &amp;quot;Programmer&amp;quot;
          :image &amp;quot;profile.jpg&amp;quot;
          :email &amp;quot;john@gmail.com&amp;quot;          
          :summary &amp;quot;A summary of John Doe…&amp;quot;}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This data then needs to be fed into the Hiccup template that might look like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:html
 &amp;#91;:body
  &amp;#91;:header#header
   &amp;#91;:div.container
    &amp;#91;:div.row 
     &amp;#91;:div.col-sm-9.col-sm-push-3
      &amp;#91;:h1 :data/basics.name&amp;#93;
      &amp;#91;:h2 :data/basics.label&amp;#93;&amp;#93;&amp;#93;&amp;#93;&amp;#93;
  &amp;#91;:page/image {:src   :data/basics.image
                :width &amp;quot;60px&amp;quot;}&amp;#93;
  &amp;#91;:div &amp;#91;:strong &amp;quot;Email&amp;quot;&amp;#93; &amp;#91;:td &amp;#91;:span.email :data/basics.email&amp;#93;&amp;#93;&amp;#93;
  &amp;#91;:section#about.row
   &amp;#91;:aside.col-sm-3
    &amp;#91;:h3 &amp;quot;About&amp;quot;&amp;#93;&amp;#93;
   &amp;#91;:div.col-sm-9
    &amp;#91;:p :data/basics.summary&amp;#93;&amp;#93;&amp;#93;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I decided to use namespaced keys to specify the dynamic elements in the template. This provides a clean way to differentiate them from the static Hiccup tags and hint at the type of key. For example, keys namespaced with &lt;code&gt;data&lt;/code&gt; indicate that they're paths that should be looked up within the EDN document. The &lt;code&gt;:data/basics.name&lt;/code&gt; keyword translates into &lt;code&gt;&amp;#40;get-in data &amp;#91;:basics :name&amp;#93;&amp;#41;&lt;/code&gt; when the template is parsed.&lt;/p&gt;&lt;p&gt;Another example is using &lt;code&gt;page&lt;/code&gt; namespace to indicate a tag that needs to be processed in a special way. The &lt;code&gt;:page/image&lt;/code&gt; tag above will create an &lt;code&gt;:img&lt;/code&gt; tag with the image at the path specified using &lt;code&gt;:data/basics.image&lt;/code&gt; injected as a base 64 string. This trick provides a flexible way to specify dynamic behaviors in the template.&lt;/p&gt;&lt;p&gt;Finally, I wanted to handle evaluation of forms in order to handle things like iteration within the template. In the snippet below, &lt;code&gt;for&lt;/code&gt; macro is called on the data found under the &lt;code&gt;projects&lt;/code&gt; key in order to create a list of projects:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:section#projects.row
    &amp;#91;:aside.col-sm-3
     &amp;#91;:h3 &amp;quot;Projects&amp;quot;&amp;#93;&amp;#93;
    &amp;#91;:div.col-sm-9
     &amp;#91;:div.row
      &amp;#40;for &amp;#91;{:keys &amp;#91;name summary url&amp;#93;} :data/projects&amp;#93;
        &amp;#91;:div.col-sm-12
         &amp;#91;:h4.strike-through
          &amp;#91;:span name&amp;#93;&amp;#93;
         &amp;#91;:div summary&amp;#93;
         &amp;#91;:div
          &amp;#91;:a {:href url} url&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#93;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Examples above cover all the functionality I expect to need for making a nice looking resume. Let's take a look at what's involved in putting it all together.&lt;/p&gt;&lt;h3 id="implementation"&gt;Implementation&lt;/h3&gt;&lt;p&gt;Conveniently, &lt;code&gt;nbb&lt;/code&gt; provides support for starting up nREPL by running &lt;code&gt;nbb nrepl-server :port 1337&lt;/code&gt;. This facilitates interactive development that Clojure developers know and love. First thing I decided to do after getting the REPL fired up was to make a little Hiccup parser borrowing the relevant bits from the original implementation:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn normalize-body &amp;#91;body&amp;#93;
  &amp;#40;if &amp;#40;coll? body&amp;#41; &amp;#40;apply str &amp;#40;doall body&amp;#41;&amp;#41; &amp;#40;str body&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn as-str  
  &amp;#91;&amp;amp; xs&amp;#93;
  &amp;#40;apply str &amp;#40;map normalize-body xs&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn escape-html  
  &amp;#91;text&amp;#93;
  &amp;#40;-&amp;gt; &amp;#40;as-str text&amp;#41;
      &amp;#40;string/replace #&amp;quot;&amp;amp;&amp;quot; &amp;quot;&amp;amp;amp;&amp;quot;&amp;#41;
      &amp;#40;string/replace #&amp;quot;&amp;lt;&amp;quot; &amp;quot;&amp;amp;lt;&amp;quot;&amp;#41;
      &amp;#40;string/replace #&amp;quot;&amp;gt;&amp;quot; &amp;quot;&amp;amp;gt;&amp;quot;&amp;#41;
      &amp;#40;string/replace #&amp;quot;'&amp;quot; &amp;quot;&amp;amp;apos;&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn xml-attribute &amp;#91;id value&amp;#93;
  &amp;#40;str &amp;quot; &amp;quot; &amp;#40;as-str &amp;#40;name id&amp;#41;&amp;#41; &amp;quot;=\&amp;quot;&amp;quot; &amp;#40;escape-html value&amp;#41; &amp;quot;\&amp;quot;&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn render-attribute &amp;#91;&amp;#91;name value&amp;#93;&amp;#93;
  &amp;#40;cond
    &amp;#40;true? value&amp;#41; &amp;#40;xml-attribute name name&amp;#41;
    &amp;#40;not value&amp;#41; &amp;quot;&amp;quot;
    :else &amp;#40;xml-attribute name value&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn render-attr-map &amp;#91;attrs&amp;#93;
  &amp;#40;apply str &amp;#40;sort &amp;#40;map render-attribute attrs&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn merge-attributes &amp;#91;{:keys &amp;#91;id class&amp;#93;} map-attrs&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; map-attrs
       &amp;#40;merge &amp;#40;when id {:id id}&amp;#41;&amp;#41;
       &amp;#40;merge-with #&amp;#40;if %1 &amp;#40;str %1 &amp;quot; &amp;quot; %2&amp;#41; %2&amp;#41; &amp;#40;when class {:class class}&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn normalize-element &amp;#91;&amp;#91;tag &amp;amp; content&amp;#93;&amp;#93;
  &amp;#40;let &amp;#91;re-tag    #&amp;quot;&amp;#40;&amp;#91;&amp;#94;\s\.#&amp;#93;+&amp;#41;&amp;#40;?:#&amp;#40;&amp;#91;&amp;#94;\s\.#&amp;#93;+&amp;#41;&amp;#41;?&amp;#40;?:\.&amp;#40;&amp;#91;&amp;#94;\s#&amp;#93;+&amp;#41;&amp;#41;?&amp;quot;
        &amp;#91;&amp;#95; tag id class&amp;#93; &amp;#40;re-matches re-tag &amp;#40;as-str &amp;#40;name tag&amp;#41;&amp;#41;&amp;#41;
        tag-attrs {:id    id
                   :class &amp;#40;when class &amp;#40;string/replace class #&amp;quot;\.&amp;quot; &amp;quot; &amp;quot;&amp;#41;&amp;#41;}
        map-attrs &amp;#40;first content&amp;#41;&amp;#93;
    &amp;#40;if &amp;#40;map? map-attrs&amp;#41;
      &amp;#91;tag &amp;#40;merge-attributes tag-attrs map-attrs&amp;#41; &amp;#40;next content&amp;#41;&amp;#93;
      &amp;#91;tag tag-attrs content&amp;#93;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn render-element &amp;#91;&amp;#91;tag attrs &amp;amp; content&amp;#93;&amp;#93;
  &amp;#40;str &amp;quot;&amp;lt;&amp;quot; &amp;#40;name tag&amp;#41; &amp;#40;render-attr-map attrs&amp;#41; &amp;quot;&amp;gt;&amp;quot; &amp;#40;as-str &amp;#40;flatten content&amp;#41;&amp;#41; &amp;quot;&amp;lt;/&amp;quot; &amp;#40;name tag&amp;#41; &amp;quot;&amp;gt;&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn render-hiccup &amp;#91;hiccup&amp;#93;
  &amp;#40;postwalk
   &amp;#40;fn &amp;#91;node&amp;#93;
     &amp;#40;if &amp;#40;and &amp;#40;not &amp;#40;map-entry? node&amp;#41;&amp;#41; &amp;#40;vector? node&amp;#41;&amp;#41;
       &amp;#40;-&amp;gt; node normalize-element render-element&amp;#41;
       node&amp;#41;&amp;#41;
   hiccup&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, I wrote a template parser that would walk the Hiccup template and inject relevant data into it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def path-sep &amp;#40;.-sep path&amp;#41;&amp;#41;

&amp;#40;defn image? &amp;#91;node&amp;#93;
  &amp;#40;and &amp;#40;vector? node&amp;#41; &amp;#40;= :page/image &amp;#40;first node&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn css? &amp;#91;node&amp;#93;
  &amp;#40;and &amp;#40;vector? node&amp;#41; &amp;#40;= :page/css &amp;#40;first node&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn data-node? &amp;#91;node&amp;#93;
  &amp;#40;and &amp;#40;keyword? node&amp;#41; &amp;#40;= &amp;quot;data&amp;quot; &amp;#40;namespace node&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn eval-forms &amp;#91;template&amp;#93;
  &amp;#40;prewalk
   &amp;#40;fn &amp;#91;node&amp;#93;
     &amp;#40;if &amp;#40;list? node&amp;#41;
       &amp;#40;eval node&amp;#41;
       node&amp;#41;&amp;#41;
   template&amp;#41;&amp;#41;

&amp;#40;defn slurp &amp;#91;filename &amp;amp; {:keys &amp;#91;encoding&amp;#93;}&amp;#93;
  &amp;#40;.toString
   &amp;#40;if encoding
     &amp;#40;fs/readFileSync filename encoding&amp;#41;
     &amp;#40;fs/readFileSync filename&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn spit &amp;#91;filename data &amp;amp; {:keys &amp;#91;encoding mode flag&amp;#93;
                             :or   {encoding &amp;quot;utf8&amp;quot;
                                    mode     &amp;quot;0o666&amp;quot;
                                    flag     &amp;quot;w&amp;quot;}}&amp;#93;
  &amp;#40;let &amp;#91;data &amp;#40;if &amp;#40;string? data&amp;#41; data &amp;#40;str data&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;fs/writeFileSync filename data encoding mode flag&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn inject-css &amp;#91;theme ref&amp;#93;
  &amp;#91;:style
   {:type &amp;quot;text/css&amp;quot;}
   &amp;#40;slurp &amp;#40;str theme path-sep ref&amp;#41;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;defn image-&amp;gt;b64 &amp;#91;file-path {:keys &amp;#91;theme&amp;#93;}&amp;#93;
  &amp;#40;when file-path
    &amp;#40;let &amp;#91;format    &amp;#40;last &amp;#40;string/split file-path #&amp;quot;\.&amp;quot;&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;str
       &amp;quot;data:image/&amp;quot; format &amp;quot;;base64, &amp;quot;
       &amp;#40;-&amp;gt; &amp;#40;path/resolve &amp;#40;str theme path-sep file-path&amp;#41;&amp;#41;
           &amp;#40;fs/readFileSync&amp;#41;
           &amp;#40;.toString &amp;quot;base64&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn inject-image &amp;#91;&amp;#91;&amp;#95; path&amp;#93; opts&amp;#93;
  &amp;#91;:img {:src &amp;#40;image-&amp;gt;b64 path opts&amp;#41;}&amp;#93;&amp;#41;

&amp;#40;defn parse-path &amp;#91;path&amp;#93;
  &amp;#40;mapv keyword &amp;#40;string/split path #&amp;quot;\.&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn parse-template &amp;#91;{:keys &amp;#91;theme template data&amp;#93; :as opts}&amp;#93;
  &amp;#40;eval-forms
   &amp;#40;postwalk
    &amp;#40;fn &amp;#91;node&amp;#93;
      &amp;#40;cond
        &amp;#40;css? node&amp;#41;
        &amp;#40;map &amp;#40;partial inject-css theme&amp;#41; &amp;#40;rest node&amp;#41;&amp;#41;
        &amp;#40;image? node&amp;#41;
        &amp;#40;inject-image node opts&amp;#41;
        &amp;#40;data-node? node&amp;#41;
        &amp;#40;get-in data &amp;#40;parse-path &amp;#40;name node&amp;#41;&amp;#41;&amp;#41;
        :else node&amp;#41;&amp;#41;
    template&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, &lt;code&gt;postwalk&lt;/code&gt; is used to navigate the template. Each node is inspected and then handled using the appropriate function based on its type. After all the data is injected in the template, the result is passed to &lt;code&gt;eval-forms&lt;/code&gt; to evaluate any code such as the &lt;code&gt;for&lt;/code&gt; macro we saw above.&lt;/p&gt;&lt;p&gt;With these pieces above in place, I can now generate a nice looking HTML page with the resume content. The last interesting bit is to convert the resulting HTML into a PDF document. The easiest way I found was to use puppeteer in headless mode to render the page and write it out as a PDF:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn write-pdf &amp;#91;{:keys &amp;#91;browser pending target pdf-opts&amp;#93;} html&amp;#93;
  &amp;#40;-&amp;gt; browser
      &amp;#40;.then #&amp;#40;.newPage %&amp;#41;&amp;#41;
      &amp;#40;.then
       &amp;#40;fn &amp;#91;page &amp;#95;&amp;#93; 
         &amp;#40;-&amp;gt; &amp;#40;.setContent page html&amp;#41;
             &amp;#40;.then #&amp;#40;.emulateMediaType page &amp;quot;screen&amp;quot;&amp;#41;&amp;#41;
             &amp;#40;.then &amp;#40;fn &amp;#91;&amp;#95; &amp;#95;&amp;#93;
                      &amp;#40;-&amp;gt; &amp;#40;.pdf page &amp;#40;clj-&amp;gt;js &amp;#40;merge {:path target} pdf-opts&amp;#41;&amp;#41;&amp;#41;
                          &amp;#40;.then
                           &amp;#40;fn &amp;#91;&amp;#95;&amp;#93; &amp;#40;reset! pending false&amp;#41;&amp;#41;&amp;#41;
                          &amp;#40;.catch #&amp;#40;js/console.error &amp;#40;.-message %&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
             &amp;#40;.catch #&amp;#40;js/console.error &amp;#40;.-message %&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The entire code for this ended up weighing in at around 200 lines, and I'm pretty happy with the result. Being able to solve these kinds of tasks in a few lines of code is what makes Clojure such a productive language for me. Incidentally, &lt;a href='https://github.com/yogthos/resume/blob/build/resume.pdf'&gt;here's&lt;/a&gt; a link to my resume, and I am currently open to collaboration or employment opportunities.&lt;/p&gt;&lt;p&gt;The entire project is available &lt;a href='https://github.com/yogthos/resume'&gt;here&lt;/a&gt; for reference.&lt;/p&gt;</description><pubDate>Fri, 12 May 2023 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2022-12-18-StructuringClojureApplications.html</guid><link>https://yogthos.net/posts/2022-12-18-StructuringClojureApplications.html</link><title>Structuring Clojure Applications</title><description>&lt;p&gt;This post will take a look at a strategy for structuring Clojure applications that I've found useful in my projects.&lt;/p&gt;&lt;p&gt;While the idea of writing applications in a pure functional style is appealing, it's not always clear how to separate side effects from pure compuation in practice. Variations of &lt;a href='https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html'&gt;Clean Architecture&lt;/a&gt; approach are often suggested as a way to accomplish this goal. This style dictates that IO should be handled in the outer layer that wraps pure computation core of the application.&lt;/p&gt;&lt;p&gt;While this notion is appealing, it only works in cases where the totality of the data that will be operated on is known up front. Unfortunately, it's impossible to know ahead of time what data will be needed in most real world applications. In many cases additional data needs to load conditionally based on the type of input and the current state of processing.&lt;/p&gt;&lt;p&gt;What we can do, however, is break up our application into small components that can be reasoned about in isolation. Such components can then be composed together to accomplish tasks of increased complexity. I like to think of this as a Lego model of software development. Each component can be viewed as a Lego block, and we can compose these Lego block in many different ways as we solve different problems.&lt;/p&gt;&lt;p&gt;The problem being solved can be expressed in terms of a workflow represented by a graph where the nodes compute the state, and the edges represent transitions between the states. Each time we enter a node in this graph, we look at the input, decide what additional data we may need, run the computation, and transition to the next state. Each node in the graph is a Lego block that accomplishes a particular task. These nodes are then connected by a layer of code governs the data flow.&lt;/p&gt;&lt;p&gt;One approach to implement the above architecture is to use a map to describe overall state, then pass it through multimethods that each operate on a particular type of state and produce a new one. Each multimethod takes the state map as a parameter, does some operations on it, and then returns a new map that gets passed to the next multimethod. If you're thinking that this sounds a like a state machine then you're very much correct.&lt;/p&gt;&lt;h3 id="implemention"&gt;Implemention&lt;/h3&gt;&lt;p&gt;Let's take a look at a concrete example of what this looks like in practice. Say we have a workflow where one user would like to send an email money transfer to another user using our system. There are a few cases we might want to handle here.&lt;/p&gt;&lt;p&gt;There's the happy path scenario where both users are in the system. In this case we simply withdraw the amount from the payor account and deposit it into the payee account.&lt;/p&gt;&lt;p&gt;Another scenario could be that the payor does not have the sufficient funds to do the transaction. In this case we may want to suspend the transaction until the user adds more funds.&lt;/p&gt;&lt;p&gt;Finally, the user receiving the funds may not be in the system, and they need to be invited before they can accept the transfer.&lt;/p&gt;&lt;p&gt;We can start by defining a few helper functions that represent interactions with external resources.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def store &amp;#40;atom {:workflows {&amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                              {:id &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                               :from   {:email &amp;quot;bob@foo.bar&amp;quot;}
                               :to     {:email &amp;quot;alice@bar.baz&amp;quot;}
                               :amount 200
                               :action :transfer}}
                  :users {&amp;quot;bob@foo.bar&amp;quot; {:funds 100}
                          &amp;quot;alice@bar.baz&amp;quot; {:funds 10}}}&amp;#41;&amp;#41;

&amp;#40;defn persist &amp;#91;store {:keys &amp;#91;id&amp;#93; :as state}&amp;#93;
  &amp;#40;swap! store assoc-in &amp;#91;:workflows id&amp;#93; state&amp;#41;&amp;#41;

&amp;#40;defn query &amp;#91;store email&amp;#93;
  &amp;#40;get-in @store &amp;#91;:users email&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn load-state &amp;#91;store workflow-id&amp;#93;
  &amp;#40;get-in @store &amp;#91;:workflows workflow-id&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn send-invite &amp;#91;email&amp;#93;
  &amp;#40;println &amp;quot;sending invite to&amp;quot; email&amp;#41;&amp;#41;

&amp;#40;defn notify-user &amp;#91;email message&amp;#93;
  &amp;#40;println &amp;quot;notifying&amp;quot; email message&amp;#41;&amp;#41;

&amp;#40;defn send-transfer &amp;#91;store from to amount&amp;#93;
  &amp;#40;println &amp;quot;transfering from&amp;quot; from &amp;quot;to&amp;quot; to amount&amp;#41;
  &amp;#40;swap! store
         #&amp;#40;-&amp;gt; %
             &amp;#40;update-in &amp;#91;:users from :funds&amp;#93; - amount&amp;#41;
             &amp;#40;update-in &amp;#91;:users to :funds&amp;#93; + amount&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll create a map to represent the initial state of the workfow.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:id &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
 :from   {:email &amp;quot;bob@foo.bar&amp;quot;}
 :to     {:email &amp;quot;alice@bar.baz&amp;quot;}
 :amount 200
 :action :transfer}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The map will contain a unique id, some initial data that represents user input, and an &lt;code&gt;:action&lt;/code&gt; key indicating what action should be applied to the current state of the workflow.&lt;/p&gt;&lt;p&gt;Let's define a multimethod that will dispatch the approprate action handler based on the value of the &lt;code&gt;:action&lt;/code&gt; key. The multimethod will accept a map of resources as the first argument. The resources represent any code that deals with IO side effects such as database connections. The map representing the state of the workflow will be passed in as the second argument.  &lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmulti handle-action &amp;#40;fn &amp;#91;&amp;#95;resources {:keys &amp;#91;action&amp;#93;}&amp;#93; action&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now define a handler for the &lt;code&gt;:transfer&lt;/code&gt; operation. This multimethod will hydrate some additional data about the users from the datastore, take the appropriate action, and return a new state with the updated &lt;code&gt;:action&lt;/code&gt; key to indicate the next step in the workflow.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod handle-action :transfer &amp;#91;{:keys &amp;#91;store&amp;#93;} {:keys &amp;#91;from to amount&amp;#93; :as state}&amp;#93;
   &amp;#40;let &amp;#91;from-info &amp;#40;query store &amp;#40;:email from&amp;#41;&amp;#41;
         to-info   &amp;#40;query store &amp;#40;:email to&amp;#41;&amp;#41;
         available-funds &amp;#40;:funds from-info&amp;#41;
         state     &amp;#40;-&amp;gt; state
                       &amp;#40;update :from merge from-info&amp;#41;
                       &amp;#40;update :to merge to-info&amp;#41;&amp;#41;&amp;#93; 
     &amp;#40;cond
       &amp;#40;nil? to-info&amp;#41;
       &amp;#40;assoc state :action :invite&amp;#41; 
       &amp;#40;&amp;gt;= available-funds amount&amp;#41;
       &amp;#40;do
         &amp;#40;send-transfer store &amp;#40;:email from&amp;#41; &amp;#40;:email to&amp;#41; amount&amp;#41;
         &amp;#40;assoc state :action :done&amp;#41;&amp;#41;
       &amp;#40;&amp;lt; available-funds amount&amp;#41;
       &amp;#40;assoc state :action :notify-missing-funds&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's add the handlers for &lt;code&gt;:invite&lt;/code&gt; and &lt;code&gt;:notify-missing-funds&lt;/code&gt; actions.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod handle-action :notify-missing-funds &amp;#91;{:keys &amp;#91;store&amp;#93;} {:keys &amp;#91;from&amp;#93; :as state}&amp;#93; 
  &amp;#40;notify-user &amp;#40;:email from&amp;#41; &amp;quot;missing funds&amp;quot;&amp;#41;
  &amp;#40;persist store &amp;#40;assoc state :action :transfer&amp;#41;&amp;#41;
  {:action :await}&amp;#41;

&amp;#40;defmethod handle-action :invite &amp;#91;{:keys &amp;#91;store&amp;#93;} {:keys &amp;#91;to&amp;#93; :as state}&amp;#93;
  &amp;#40;send-invite to&amp;#41;
  &amp;#40;persist store &amp;#40;assoc state :action :transfer&amp;#41;&amp;#41;
  {:action :await}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that &lt;code&gt;:invite&lt;/code&gt; and &lt;code&gt;:notify-missing-funds&lt;/code&gt; actions persist the state and return the &lt;code&gt;:await&lt;/code&gt; action when they complete. We'll use this behavior to indicate that the workflow is blocked on an external action and needs to be suspended.&lt;/p&gt;&lt;p&gt;Finally, we'll add a function that executes the state machine. This function will accept a map containing the resources along with a workflow id. It will load the current state and execute it by dispatching the multimethod defined above.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn run-workflow
  &amp;#91;{:keys &amp;#91;store&amp;#93; :as resources} workflow-id&amp;#93;
  &amp;#40;loop &amp;#91;state &amp;#40;load-state store workflow-id&amp;#41;&amp;#93; 
    &amp;#40;condp = &amp;#40;-&amp;gt; state :action&amp;#41;
      :done state
      :await :workflow-suspended
      &amp;#40;let &amp;#91;state &amp;#40;handle-action resources state&amp;#41;&amp;#93;
        &amp;#40;recur state&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For simplicity's sake let's use an atom as our mock data store.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def store &amp;#40;atom {:workflows {&amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                              {:id &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                               :from   {:email &amp;quot;bob@foo.bar&amp;quot;}
                               :to     {:email &amp;quot;alice@bar.baz&amp;quot;}
                               :amount 200
                               :action :transfer}}
                  :users {&amp;quot;bob@foo.bar&amp;quot; {:funds 100}
                          &amp;quot;alice@bar.baz&amp;quot; {:funds 10}}}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now try running this workflow in the REPL. If we run it with the initial state, then we should see that the workflow was suspended because there were insufficient funds to transfer.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;=&amp;gt; &amp;#40;run-workflow {:store store} &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;&amp;#41;

notifying bob@foo.bar missing funds
:workflow-suspended
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The workflow tries to notify the user of the missing funds and returns. Let's add more funds to the account trying to send the transfer.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;=&amp;gt; &amp;#40;swap! store assoc-in &amp;#91;:users &amp;quot;bob@foo.bar&amp;quot; :funds&amp;#93; 300&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The workflow restarts where it left off and completes the transfer successfully.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;=&amp;gt; &amp;#40;run-workflow {:store store} &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;&amp;#41;

transfering from bob@foo.bar to alice@bar.baz 200
{:id &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;,
 :from {:email &amp;quot;bob@foo.bar&amp;quot;, :funds 300},
 :to {:email &amp;quot;alice@bar.baz&amp;quot;, :funds 10},
 :amount 200,
 :action :done}
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="formalizing&amp;#95;side&amp;#95;effects"&gt;Formalizing Side Effects&lt;/h3&gt;&lt;p&gt;We can make one futher improvement over the implementation above by formalizing resource providers using protocols. Doing so will make it clear what the external dependecies are and facilitate mocking. Let's create &lt;code&gt;Notify&lt;/code&gt; and &lt;code&gt;DataStore&lt;/code&gt; protocols that look as follows.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defprotocol Notify
  &amp;#40;send-invite &amp;#91;email&amp;#93;&amp;#41;
  &amp;#40;notify-user &amp;#91;email message&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defprotocol DataStore
  &amp;#40;persist &amp;#91;&amp;#95; state&amp;#93;&amp;#41;
  &amp;#40;query &amp;#91;&amp;#95; email&amp;#93;&amp;#41;
  &amp;#40;add-funds &amp;#91;&amp;#95; email amount&amp;#93;&amp;#41;
  &amp;#40;load-state &amp;#91;&amp;#95; workflow-id&amp;#93;&amp;#41;
  &amp;#40;send-transfer &amp;#91;&amp;#95; from to amount&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, let's add a couple of records that implement these protocols.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defrecord MockNotify &amp;#91;&amp;#93;
  Notify
  &amp;#40;send-invite &amp;#91;&amp;#95; email&amp;#93;
    &amp;#40;println &amp;quot;sending invite to&amp;quot; email&amp;#41;&amp;#41;
  &amp;#40;notify-user &amp;#91;&amp;#95; email message&amp;#93;
    &amp;#40;println &amp;quot;notifying&amp;quot; email message&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defrecord AtomDataStore &amp;#91;store&amp;#93;
  DataStore
  &amp;#40;persist &amp;#91;&amp;#95; {:keys &amp;#91;id&amp;#93; :as state}&amp;#93;
    &amp;#40;swap! store assoc-in &amp;#91;:workflows id&amp;#93; state&amp;#41;&amp;#41;
  &amp;#40;query &amp;#91;&amp;#95;  email&amp;#93;
    &amp;#40;get-in @store &amp;#91;:users email&amp;#93;&amp;#41;&amp;#41;
  &amp;#40;add-funds &amp;#91;&amp;#95; email amount&amp;#93;
    &amp;#40;swap! store assoc-in &amp;#91;:users &amp;quot;bob@foo.bar&amp;quot; :funds&amp;#93; 300&amp;#41;&amp;#41;
  &amp;#40;load-state &amp;#91;&amp;#95; workflow-id&amp;#93;
    &amp;#40;println &amp;quot;hi&amp;quot;&amp;#41;
    &amp;#40;get-in @store &amp;#91;:workflows workflow-id&amp;#93;&amp;#41;&amp;#41;
  &amp;#40;send-transfer &amp;#91;&amp;#95; from to amount&amp;#93;
    &amp;#40;println &amp;quot;transfering from&amp;quot; from &amp;quot;to&amp;quot; to amount&amp;#41;
    &amp;#40;swap! store
           #&amp;#40;-&amp;gt; %
                &amp;#40;update-in &amp;#91;:users from :funds&amp;#93; - amount&amp;#41;
                &amp;#40;update-in &amp;#91;:users to :funds&amp;#93; + amount&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll also need to modify our multimethods to use &lt;code&gt;Notify&lt;/code&gt; protocol instead of simply calling the functions we defined earlier.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod handle-action :notify-missing-funds &amp;#91;{:keys &amp;#91;store notify&amp;#93;} {:keys &amp;#91;from&amp;#93; :as state}&amp;#93;
  &amp;#40;notify-user notify &amp;#40;:email from&amp;#41; &amp;quot;missing funds&amp;quot;&amp;#41;
  &amp;#40;persist store &amp;#40;assoc state :action :transfer&amp;#41;&amp;#41;
  {:action :await}&amp;#41;

&amp;#40;defmethod handle-action :invite &amp;#91;{:keys &amp;#91;store notify&amp;#93;} {:keys &amp;#91;to&amp;#93; :as state}&amp;#93;
  &amp;#40;send-invite notify to&amp;#41;
  &amp;#40;persist store &amp;#40;assoc state :action :transfer&amp;#41;&amp;#41;
  {:action :await}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we'll instantiate the records and passing them to our &lt;code&gt;run-workflow&lt;/code&gt; function.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def store &amp;#40;-&amp;gt;AtomDataStore &amp;#40;atom {:workflows {&amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                                                {:id &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;
                                                :from   {:email &amp;quot;bob@foo.bar&amp;quot;}
                                                :to     {:email &amp;quot;alice@bar.baz&amp;quot;}
                                                :amount 200
                                                :action :transfer}}
                                    :users {&amp;quot;bob@foo.bar&amp;quot; {:funds 100}
                                            &amp;quot;alice@bar.baz&amp;quot; {:funds 10}}}&amp;#41;&amp;#41;&amp;#41;
&amp;#40;def notify &amp;#40;-&amp;gt;MockNotify&amp;#41;&amp;#41;

&amp;#40;run-workflow {:store store
               :notify notify} 
              &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;&amp;#41;

&amp;#40;add-funds store &amp;quot;bob@foo.bar&amp;quot; 100&amp;#41;

&amp;#40;run-workflow {:store store
               :notify notify} 
              &amp;quot;33a19b1f-c7d1-45d8-9864-0ea17e01a26d&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="discussion"&gt;Discussion&lt;/h3&gt;&lt;p&gt;There are several aspects of the above approach that I've found to be particularly useful when building applications.&lt;/p&gt;&lt;p&gt;Each multimethod can be treated as a small program that can be reasoned about and tested independently. These multimethods can easily be structured using Clean Architecture style keepng IO at the edges.&lt;/p&gt;&lt;p&gt;Passing resources in as an explicit parameter allows decoupling IO from computation. This design lends itself well to testing since resources, such as the data store, are passed in explicitly. We can pass in a map of mock resources when running tests without any changes to the rest of the code. In fact, we can start developing against mock resources and ensure that the workflow logic works as intended before having to worry about connecting to databases or other systems.&lt;/p&gt;&lt;p&gt;Using a map to track the state of the execution makes it easy to inspect it. We can log this map to see what operation we're doing, what the data looks like, and so on. The state can also be easily serialized, allowing us to suspend and resume computation as needed. This is particularly useful in cases when the workflow needs to be suspended pending some external action as we saw earlier.&lt;/p&gt;&lt;p&gt;This design also plays well with Integrant which can be used to manage the system map containing stateful resources.&lt;/p&gt;&lt;p&gt;Most importantly, this type of architecture creates reusable components without implicit coupling. Each multimethod can be used indepenently of the others, and composed into different workflows. This gives us composable Lego blocks that we can use to build larger structures.&lt;/p&gt;</description><pubDate>Sun, 18 Dec 2022 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2022-11-26-nREPL-system-interaction.html</guid><link>https://yogthos.net/posts/2022-11-26-nREPL-system-interaction.html</link><title>Using nREPL as System Interface</title><description>&lt;p&gt;Clojure REPL is a powerful tool for developing programs interactively. Connecting the editor to the REPL allows us to get instant feedback on the code we're writing and have confidence that it works as intended as we're developing the application. However, the REPL isn't inherently limited to application development. It provides us with an interface to the language, and the language in turn be used as an interface to the host system. Let's take a look at how we can use &lt;a href='https://book.babashka.org/'&gt;Babashka&lt;/a&gt; along with &lt;a href='https://osquery.readthedocs.io/en/stable/introduction/using-osqueryi/'&gt;Osquery&lt;/a&gt; to inspect the state of the host.&lt;/p&gt;&lt;p&gt;Osquery is a handy tool that allows using SQL commands in order to leverage a relational data-model to describe a device. Different aspects of the system are mapped to relational tables using the following &lt;a href='https://www.osquery.io/schema/5.5.1/'&gt;schema&lt;/a&gt;. The tables give us access to files, ports, mounts, and many other aspects of the system. One aspect of Osqeury that's particularly useful to us is that it's able to return results in JSON format that we can parse into EDN and work with as structured data in the REPL.&lt;/p&gt;&lt;p&gt;To see how this works we'll start the nREPL server by running &lt;code&gt;bb --nrepl-server&lt;/code&gt;. The REPL will start on port &lt;code&gt;1667&lt;/code&gt; by default, we can also set a custom port by providing port number as the second argument to &lt;code&gt;bb&lt;/code&gt;. Once the REPL is running we can connect any nREPL compatible editor such as Calva or Emacs.&lt;/p&gt;&lt;p&gt;Let's create a file called &lt;code&gt;osquery.clj&lt;/code&gt; and open it in the editor and add some code to drive Osquery. First thing we'll need to do is to require the namespaces for interacting with the shell and parsing JSON:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;require '&amp;#91;clojure.java.shell :refer &amp;#91;sh&amp;#93;&amp;#93;
         '&amp;#91;cheshire.core :as json&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll define the &lt;code&gt;osquery&lt;/code&gt; function that will take a SQL query as text, execute &lt;code&gt;osqueryi&lt;/code&gt; command and return its result as EDN:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn osquery &amp;#91;query&amp;#93;
  &amp;#40;let &amp;#91;{:keys &amp;#91;exit out err&amp;#93;} &amp;#40;sh &amp;quot;osqueryi&amp;quot; &amp;quot;--json&amp;quot; query&amp;#41;&amp;#93;
    &amp;#40;if &amp;#40;zero? exit&amp;#41;
      &amp;#40;json/decode out true&amp;#41;
      &amp;#40;throw &amp;#40;Exception. err&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And we're now ready to try to query some information about the system. Let's run a query to see all the routes where destination is &lt;code&gt;::1&lt;/code&gt;&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;osquery &amp;quot;select &amp;#42; from routes where destination = '::1'&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We should get back a list of routes that looks something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;{:hopcount &amp;quot;0&amp;quot;,
  :interface &amp;quot;lo0&amp;quot;,
  :mtu &amp;quot;16384&amp;quot;,
  :type &amp;quot;local&amp;quot;,
  :source &amp;quot;&amp;quot;,
  :gateway &amp;quot;::1&amp;quot;,
  :netmask &amp;quot;128&amp;quot;,
  :flags &amp;quot;2098181&amp;quot;,
  :destination &amp;quot;::1&amp;quot;,
  :metric &amp;quot;0&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The result is just a plain Clojure data structure we can trivially manipulate using full power of Clojure. &lt;/p&gt;&lt;p&gt;We can even go a step further using &lt;a href='https://github.com/seancorfield/honeysql'&gt;HoneySQL&lt;/a&gt; library that will allow us to make structured queries. We'll need to require &lt;code&gt;deps&lt;/code&gt; and pull in the library as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;require '&amp;#91;babashka.deps :as deps&amp;#93;&amp;#41;

&amp;#40;deps/add-deps '{:deps {com.github.seancorfield/honeysql {:mvn/version &amp;quot;2.2.861&amp;quot;}}}&amp;#41;

&amp;#40;require '&amp;#91;honey.sql :as hsql&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we'll update our &lt;code&gt;osquery&lt;/code&gt; function as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn osquery &amp;#91;query&amp;#93;
  &amp;#40;let &amp;#91;{:keys &amp;#91;exit out err&amp;#93;} &amp;#40;apply sh &amp;quot;osqueryi&amp;quot; &amp;quot;--json&amp;quot; &amp;#40;hsql/format query {:inline true}&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;if &amp;#40;zero? exit&amp;#41;
      &amp;#40;json/decode out true&amp;#41; 
      &amp;#40;throw &amp;#40;Exception. err&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With the changes above we can now write our queries in EDN:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;osquery {:select &amp;#91;:&amp;#42;&amp;#93; :from &amp;#91;:routes&amp;#93; :where &amp;#91;:= :destination &amp;quot;::1&amp;quot;&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I hope this little example illustrates how the REPL can be used as a powerful OS interaction tool as well as a programming tool and inspires you to use the REPL in new and exciting ways. Babashka in particular is a great tool for such REPL driven interaction due to fast startup and wide range of useful libraries that let us access databases, HTTP servers, and other resources. This makes Babashka an excellent tool for doing devops.&lt;/p&gt;</description><pubDate>Sat, 26 Nov 2022 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2022-01-08-IntroducingKit.html</guid><link>https://yogthos.net/posts/2022-01-08-IntroducingKit.html</link><title>Introducing Kit Framework</title><description>&lt;p&gt;&lt;a href='https://kit-clj.github.io/'&gt;Kit&lt;/a&gt; is a Clojure web framework building on experience from Luminus while embracing latest tools and best practices that emerged over the years. Kit shares the same goals as Luminus while aiming to address its deficiencies. Before we dive into Kit, let's take a moment to establish some background. Kit was created as a collaboration between &lt;a href='https://nikperic.com/'&gt;Nik&lt;/a&gt;, &lt;a href='http://www.danboykis.com/'&gt;Dan&lt;/a&gt;, and myself. The project leverages our collective experience developing web applications using Clojure. Nik provides his own rationale for the project &lt;a href='https://nikperic.com/2022/01/08/why-kit.html'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h2 id="background"&gt;Background&lt;/h2&gt;&lt;p&gt;My original motivation behind Luminus was to provide a frictionless beginner experience for Clojure web development. Clojure community favors structuring applications by leveraging composable libraries. This approach affords gives the developer full control over the structure of their project making it easy for experienced Clojure users to build lean applications that contain only the necessary components.&lt;/p&gt;&lt;p&gt;Unfortunately, having to know what libraries and tools to use and how to put them together effectively creates a significant barrier for Clojure beginners. This is one of the major problems addressed by frameworks where such decisions are made by the maintainers of the framework.&lt;/p&gt;&lt;p&gt;Frameworks allow users to focus on the business logic of their application while aiming to handle all the cross-cutting concerns. Downside of this approach is that the framework has to accommodate for many different types of projects. Users of the framework end up inheriting the complexity of the entire framework regardless of the actual needs of their project.&lt;/p&gt;&lt;p&gt;Luminus provides a middle ground between these approaches using project templates. The template makes all the decisions regarding the libraries that are used and the structure of the project. Using such a template allows users to create a skeleton project that works out of the box. However, the user is free to modify the code in the project any way they see fit without being locked into the decisions made by the maintainers of the framework.&lt;/p&gt;&lt;p&gt;Just like a traditional framework, Luminus provides a curated stack of libraries that are known to be maintained and to work well together. This stack is coupled with a documentation site that illustrates how to accomplish common tasks such as HTML templating, routing, and database access.&lt;/p&gt;&lt;p&gt;One major deficiency of Luminus is that it's based around Leiningen templates. Any template features that the user wants to use in their project have to be known at project creation time. For example, if you created a barebones project and then later decided that you wanted to add ClojureScript support, then all the wiring would have to be done manually.&lt;/p&gt;&lt;p&gt;Another problem with baking all the features directly into the template is the resulting maintenance overhead. Any features supported by Luminus have to be maintained in the official repository. As the number of supported features grows so does the maintenance burden.&lt;/p&gt;&lt;p&gt;With all that in mind, let's take a look at what Kit does differently and what improvements it introduces over Luminus.&lt;/p&gt;&lt;h2 id="kit&amp;#95;stack"&gt;Kit Stack&lt;/h2&gt;&lt;p&gt;Kit stack is similar to Luminus with a few notable changes. Let's see what they are and explore the rationale behind them.&lt;/p&gt;&lt;p&gt;Kit uses &lt;a href='https://github.com/weavejester/integrant'&gt;Integrant&lt;/a&gt; to manage stateful components in the project. While &lt;a href='https://github.com/tolitius/mount'&gt;Mount&lt;/a&gt; is a great library for managing stateful components, it doesn't lend itself well towards creating modules since the component is described as code within the project. On the other hand, Integrant uses an EDN configuration file for managing state making it easy to package component configuration in the modules. Integrant also follows data oriented approach favored by Clojure community where the entire system of components and their relationships is described as a map. This makes it easy to see what all the resources and their relationships in the project are at a glance.&lt;/p&gt;&lt;p&gt;Another major change is that tools.deps along with tools.build are used for managing project lifecycle in favor of Leiningen. While Leiningen is a fine tool, it's clear that the community is moving towards using official tooling and Kit embraces this decision. Using official tools also means that there is one less tool to install, making for a smoother beginner experience.&lt;/p&gt;&lt;p&gt;Aside from these changes, the stack and project structure will be familiar to existing Luminus users. Ring is used as the HTTP server abstraction, Reitit being used for routing, Selmer for HTML templating, Migratus for migrations, and HugSQL for managing SQL queries.&lt;/p&gt;&lt;p&gt;With that out of the way, let's take look at the most exciting aspect of the framework which is its module system.&lt;/p&gt;&lt;h2 id="kit&amp;#95;modules"&gt;Kit Modules&lt;/h2&gt;&lt;p&gt;Kit modules are templates that can be applied to an existing project using &lt;a href='https://github.com/kit-clj/kit/tree/master/libs/kit-generator'&gt;kit-generator&lt;/a&gt; library. Modules are managed using git repositories, and official modules can be found &lt;a href='https://github.com/kit-clj/modules'&gt;here&lt;/a&gt;. Let's take a brief look at what a module repository looks like.&lt;/p&gt;&lt;p&gt;A module repository must contain a &lt;code&gt;modules.edn&lt;/code&gt; file describing the modules that are provided. For example, here are the official modules provided by Kit:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:name &amp;quot;kit-modules&amp;quot;
 :modules
 {:kit/html
  {:path &amp;quot;html&amp;quot;
   :doc &amp;quot;adds support for HTML templating using Selmer&amp;quot;}
  :kit/sqlite
  {:path &amp;quot;sqlite&amp;quot;
   :doc &amp;quot;adds support for SQLite embedded database&amp;quot;}
  :kit/cljs
  {:path &amp;quot;cljs&amp;quot;
   :doc &amp;quot;adds support for cljs using shadow-cljs&amp;quot;}}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As we can see above, the official repository contains three modules. Let's take a look at the &lt;a href='https://github.com/kit-clj/modules/tree/master/html'&gt;&lt;code&gt;:kit/html&lt;/code&gt;&lt;/a&gt; module to see how it works. This module contains a &lt;code&gt;config.edn&lt;/code&gt; file and a folder called &lt;code&gt;assets&lt;/code&gt;. Let's take a look at the configuration for the module:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:default
 {:require-restart? true
  :actions
  {:assets           &amp;#91;&amp;#91;&amp;quot;assets/home.html&amp;quot;    &amp;quot;resources/html/home.html&amp;quot;&amp;#93;
                      &amp;#91;&amp;quot;assets/error.html&amp;quot;    &amp;quot;resources/html/error.html&amp;quot;&amp;#93;
                      &amp;#91;&amp;quot;assets/css/screen.css&amp;quot;    &amp;quot;resources/public/css/screen.css&amp;quot;&amp;#93;
                      &amp;#91;&amp;quot;assets/img/kit.png&amp;quot; &amp;quot;resources/public/img/kit.png&amp;quot;&amp;#93;
                      &amp;#91;&amp;quot;assets/src/pages.clj&amp;quot;    &amp;quot;src/clj/&amp;lt;&amp;lt;sanitized&amp;gt;&amp;gt;/web/routes/pages.clj&amp;quot;&amp;#93;
                      &amp;#91;&amp;quot;assets/src/layout.clj&amp;quot;   &amp;quot;src/clj/&amp;lt;&amp;lt;sanitized&amp;gt;&amp;gt;/web/pages/layout.clj&amp;quot;&amp;#93;&amp;#93;
   :injections       &amp;#91;{:type   :edn
                       :path   &amp;quot;resources/system.edn&amp;quot;
                       :target &amp;#91;&amp;#93;
                       :action :merge
                       :value  {:reitit.routes/pages
                          {:base-path &amp;quot;&amp;quot;
                             :env       #ig/ref :system/env}}}
                      {:type   :edn
                       :path   &amp;quot;deps.edn&amp;quot;
                       :target &amp;#91;:deps&amp;#93;
                       :action :merge
                       :value  {selmer/selmer {:mvn/version &amp;quot;1.12.49&amp;quot;}
                                luminus/ring-ttl-session {:mvn/version &amp;quot;0.3.3&amp;quot;}}}
                      {:type   :clj
                       :path   &amp;quot;src/clj/&amp;lt;&amp;lt;sanitized&amp;gt;&amp;gt;/core.clj&amp;quot;
                       :action :append-requires
                       :value  &amp;#91;&amp;quot;&amp;#91;&amp;lt;&amp;lt;ns-name&amp;gt;&amp;gt;.web.routes.pages&amp;#93;&amp;quot;&amp;#93;}&amp;#93;}}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the module has a &lt;code&gt;:default&lt;/code&gt; profile. Kit module profiles allow providing variations of a module with different configurations. For example, a database module could have different profiles for different types of databases. In case of HTML, we only need a single profile.&lt;/p&gt;&lt;p&gt;The&lt;code&gt;:require-restart?&lt;/code&gt; key specifies that the runtime needs to be restarted for changes to take effect. This is necessary for modules that add Maven dependencies necessitating JVM restarts to be loaded.&lt;/p&gt;&lt;p&gt;Next, the module specifies the actions that will be performed. The first action called &lt;code&gt;:assets&lt;/code&gt; specifies new assets that will be added to the project. These are template files that will be read from the &lt;code&gt;assets&lt;/code&gt; folder and injected in the project. Assets are akin to traditional Leiningen templates.&lt;/p&gt;&lt;p&gt;The other configuration action is called &lt;code&gt;:injections&lt;/code&gt; and specifies code that will be injected into existing files within the project. In order to provide support for rendering HTML templates, the module must update Integrant system configuration by adding a reference for new routes to &lt;code&gt;system.edn&lt;/code&gt;, add new dependencies to &lt;code&gt;deps.edn&lt;/code&gt;, and finally require the namespace that contains the routes for the pages in the core namespace of the project.&lt;/p&gt;&lt;h1 id="trying&amp;#95;things&amp;#95;out"&gt;Trying Things Out&lt;/h1&gt;&lt;p&gt;Let's create a new Kit project and see how this all works in practice. Kit uses &lt;a href='https://github.com/seancorfield/clj-new'&gt;clj-new&lt;/a&gt; templates for instantiating the project, make sure you have it &lt;a href='https://kit-clj.github.io/docs/guestbook.html#installing_a_build_tool'&gt;installed locally&lt;/a&gt; to follow along. Let's create a project called &lt;code&gt;guestbook&lt;/code&gt; by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;clojure -X:new :template io.github.kit-clj :name kit/guestbook
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the project is created, you can start the REPL by running &lt;code&gt;clj -M:dev -M:repl&lt;/code&gt;, alternatively if you have &lt;code&gt;make&lt;/code&gt; installed just run &lt;code&gt;make repl&lt;/code&gt; instead. Once the REPL starts, you can run &lt;code&gt;&amp;#40;go&amp;#41;&lt;/code&gt; to start the HTTP server.&lt;/p&gt;&lt;p&gt;Default project provides a minimal configuration with a health status API located at &lt;code&gt;http://localhost:3000/api/health&lt;/code&gt;. Let's see how we can add support for rendering HTML pages using Selmer by installing the official HTML module.&lt;/p&gt;&lt;h2 id="adding&amp;#95;modules"&gt;Adding Modules&lt;/h2&gt;&lt;p&gt;Kit projects use a configuration file called &lt;code&gt;kit.edn&lt;/code&gt; that specifies some metadata about the project and allows the user to reference module repositories. Default configuration will look something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:full-name &amp;quot;kit/guestbook&amp;quot;
 :ns-name   &amp;quot;kit.guestbook&amp;quot;
 :sanitized &amp;quot;kit/guestbook&amp;quot;
 :name      &amp;quot;guestbook&amp;quot;
 :modules   {:root         &amp;quot;modules&amp;quot;
             :repositories &amp;#91;{:url  &amp;quot;git@github.com:kit-clj/modules.git&amp;quot;
                             :tag  &amp;quot;master&amp;quot;
                             :name &amp;quot;kit-modules&amp;quot;}&amp;#93;}}
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id="repl&amp;#95;driven&amp;#95;workflow"&gt;REPL driven workflow&lt;/h2&gt;&lt;p&gt;Kit embraces the REPL and the generator library is aliased in the &lt;code&gt;user&lt;/code&gt; namespace as &lt;code&gt;kit&lt;/code&gt;. Let's see how we can us it to install HTML module in the project. First, we'd need to sync our module repositories. This is done by running the following command in the REPL:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;user=&amp;gt; &amp;#40;kit/sync-modules&amp;#41;
2021-11-30 11:42:41,010 &amp;#91;main&amp;#93; DEBUG org.eclipse.jgit.util.FS - readpipe &amp;#91;git, --version&amp;#93;,/usr/local/bin
2021-11-30 11:42:41,030 &amp;#91;main&amp;#93; DEBUG org.eclipse.jgit.util.FS - readpipe may return 'git version 2.33.1'
2021-11-30 11:42:41,030 &amp;#91;main&amp;#93; DEBUG org.eclipse.jgit.util.FS - remaining output:
...
2021-11-30 11:42:41,769 &amp;#91;main&amp;#93; DEBUG o.e.jgit.transport.PacketLineOut - git&amp;gt; 0000
2021-11-30 11:42:41,769 &amp;#91;main&amp;#93; DEBUG o.e.jgit.transport.PacketLineOut - git&amp;gt; done

2021-11-30 11:42:41,835 &amp;#91;main&amp;#93; DEBUG o.e.jgit.transport.PacketLineIn - git&amp;lt; NAK
nil
user=&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the modules are synchronized, we can list the available modules by running &lt;code&gt;kit/list-modules&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;user=&amp;gt; &amp;#40;kit/list-modules&amp;#41;
:kit/html - adds support for HTML templating using Selmer
:kit/sqlite - adds support for SQLite embedded database
:kit/cljs - adds support for cljs using shadow-cljs
nil
user=&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the three modules specified in the official modules repository are now available for use. Let's install the HTML module by running &lt;code&gt;kit/install-module&lt;/code&gt; function and passing it the keyword specifying the module name:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;user=&amp;gt; &amp;#40;kit/install-module :kit/html&amp;#41;
updating file: resources/system.edn
updating file: deps.edn
updating file: src/clj/kit/guestbook/core.clj
applying
 action: :append-requires
 value: &amp;#91;&amp;quot;&amp;#91;kit.guestbook.web.routes.pages&amp;#93;&amp;quot;&amp;#93;
:kit/html installed successfully!
restart required!
nil
user=&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's restart the REPL and run &lt;code&gt;&amp;#40;go&amp;#41;&lt;/code&gt; command again to start the application. We should now be able to navigate to &lt;code&gt;http://localhost:3000&lt;/code&gt; and see the default HTML page provided by the module.&lt;/p&gt;&lt;p&gt;Generator aims to be idempotent, and will err on the side of safety in case of conflicts. For example, if we attempt to install &lt;code&gt;:kit/html&lt;/code&gt; module a second time then we'll see he following output:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;user=&amp;gt; &amp;#40;kit/install-module :kit/html&amp;#41;
:kit/html requires following modules: nil
module :kit/html is already installed!
nil
user=&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Generator lets us know that the module already exists and there is nothing to be done.&lt;/p&gt;&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;&lt;p&gt;I hope this post convinced you that Kit approach is an improvement over Luminus for both users and developers. With Kit, you no longer have to know what features you're going to be using up front. New functionality can now be added gradually as you discover the need for it. You're no longer restricted to using official modules either. Anyone can make a repository with their own modules that template common functionality that they need and use these along side or even in place of the official modules. For example, if you wanted to use Hiccup instead of Selmer, then you could trivially add support for that yourself based on the example above.&lt;/p&gt;&lt;p&gt;Kit was created by Dmitri Sotnikov, Nikola Peric, and Dan Boykis. We hope that this project will make it easier for Clojure developers to make web applications going forward. Get in touch with us on Clojurians slack at #kit-clj, we're excited to hear community feedback, ideas and suggestions for the project.&lt;/p&gt;</description><pubDate>Sat, 08 Jan 2022 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2020-04-08-advantages-of-data-oriented-programming.html</guid><link>https://yogthos.net/posts/2020-04-08-advantages-of-data-oriented-programming.html</link><title>Advantages of Data Oriented Programming</title><description>&lt;p&gt;One of the biggest advantages I've found working with Clojure is its data oriented nature. Ultimately, all that code is doing is transform data. A program starts with one piece of data as the input and produces another as its output. Mainstream languages attempt to abstract over that using object oriented semantics. While practical value of such abstraction is not entirely clear, there are some tangible problems associated with this approach. Let's take a look at some drawbacks to structuring programs using OO style.&lt;/p&gt;&lt;p&gt;Traditionally, an object can be thought of as a type of a state machine that contains some data fields representing its internal state and provides some methods for manipulating it. An object represents the smallest compositional unit in OO, and a program is structured as a graphs of such objects that interact with one another by manipulating each others state.&lt;/p&gt;&lt;p&gt;The first problem we have is that each object is an ad hoc DSL. When a developer designs an object they define its API in form of methods and come up with the behaviors the object will have. This makes each object unique, and knowing how one object behaves tells you nothing regarding how the next object might behave. Rich Hickey illustrates this point in detail in his &lt;a href='https://www.youtube.com/watch?v=aSEQfqNYNAc'&gt;Clojure, Made Simple&lt;/a&gt; talk. The more objects you define the more behaviors you have to keep in your head. Thus, cognitive overhead grows proportionally with the size of the program.&lt;/p&gt;&lt;p&gt;Any mutable objects present in the program require the developer to know the state of the objects in order to know how the program will behave. A program that is structured as a graph of interdependent state machines quickly becomes impossible to reason about. The problem stems from objects being implicitly connected via references to each other resulting in shared mutable state. This leads to lack or referential transparency and makes it impossible to do local reasoning about the code. In order to tell what a piece of code is doing you also have to track down all the code that shares references with the code you're reading.&lt;/p&gt;&lt;p&gt;This is one reason why sophisticated debugging tools are needed to work with code effectively in object oriented languages. The only way to tell what's happening in a large program is to run it in a debugger, try to put it in a particular state and then inspect it. Unfortunately, this approach is just a heuristic since there may be many different paths that get you to a particular state, and it's impossible to guarantee that you've covered them all.&lt;/p&gt;&lt;p&gt;Another notable problem with objects is that there is no standard way for serializing them creating additional pain at program boundaries. For example, we can't just take an object graph on from a web server and send it to the client. We must write custom serializers for every object adding complexity and boilerplate to our programs. A related problem occurs when composing libraries that define their own classes leading to prevalence of wrapper and adapter patterns.&lt;/p&gt;&lt;p&gt;All these problems disappear in a data oriented language like Clojure. Modern FP style embraces the fact that programs can be viewed as data transformation pipelines where input data is passed through a series of pure functions to transform it into desired output. Such functions can be reasoned about in isolation without having to consider the rest of the program. Plain data doesn't have any hidden behaviors or state that you have to worry about. Immutable data is both transparent and inert while objects are opaque and stateful.&lt;/p&gt;&lt;p&gt;As a concrete example, Pedestal HTTP server &lt;a href='https://www.youtube.com/watch?v=0if71HOyVjY'&gt;has around 18,000 lines of code, and 96% of it is pure functions&lt;/a&gt;. All the IO and side effects are encapsulated in the remaining 4% of the code. This has been a common scenario for the vast majority of Clojure programs I've worked on.&lt;/p&gt;&lt;p&gt;Cognitive overhead associated with reasoning about code is localized as opposed to being directly influenced by the size of the application as often happens with OO. Each function can be thought of as an small individual program, and we simply pipe these programs together to solve bigger problems. Incidentally, this is the exact same approach as advocated by Ken Thompson in &lt;a href='https://en.wikipedia.org/wiki/Unix_philosophy'&gt;Unix philosophy&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Data can also be passed across program boundaries since it's directly serializable. A Clojure web server can send its output directly to the client, and client code can operate on this data without any additional ceremony. I've discussed some of the practical benefits that stem from having standard serialization semantics in &lt;a href='https://www.youtube.com/watch?v=IekPZpfbdaI'&gt;this&lt;/a&gt; presentation.&lt;/p&gt;&lt;p&gt;Another advantage of separating data from logic is code reuse. A pure function that transforms one piece of data into another can be used in any context. A common set of functions from the standard library can be used to manipulate data regardless where it comes from. Once you learn a few common patterns for transforming data, you can apply these patterns everywhere.&lt;/p&gt;&lt;p&gt;I strongly suspect that data driven APIs are a major reason why Clojure libraries tend to be so stable. When a library is simply transforming data then it's possible to get to a state where it's truly done. Once the API consisting of all the supported transformations has been defined and tested, then the API is complete. The only times the library has to be revisited is when use cases missed by tests are discovered or new features are added. This tends to happen early on during library lifecycle, and hence mature libraries need little attention from their maintainers.&lt;/p&gt;&lt;p&gt;Of course, this is not to say that large software cannot be written effectively using OO languages. Clearly plenty of great software has been produced using these techniques. However, the fact that complex applications can be written in a particular fashion is hardly interesting of itself. Given enough dedication and ingenuity it's possible to write complex software in any language. It's more useful to consider how different approaches impact development style in different languages.&lt;/p&gt;</description><pubDate>Wed, 08 Apr 2020 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2019-01-19-LuminusOnDokku.html</guid><link>https://yogthos.net/posts/2019-01-19-LuminusOnDokku.html</link><title>Running Luminus on Dokku</title><description>&lt;p&gt;Luminus provides a great way to get up and running with a Clojure web application. However, building your app is only half the work. Once you've got your app working, the next step is to host it somewhere so that the users can access it.&lt;/p&gt;&lt;p&gt;Cloud platforms, such as AWS, are a popular choice for deploying large scale solutions. On the other hand, VPS services like Digital Ocean and Linode provide a more economical alternative for small scale applications. The downside of running your own VPS is that managing it can be labor intensive. This is where &lt;a href='http://dokku.viewdocs.io/dokku/'&gt;Dokku&lt;/a&gt; comes in. It's a private PaaS modelled on Heroku that you can use to provision a VPS.&lt;/p&gt;&lt;p&gt;Let's take a look at what's involved in provisioning a Digital Ocean droplet with Dokku and deploying a Luminus web app to it.&lt;/p&gt;&lt;h3 id="set&amp;#95;up&amp;#95;the&amp;#95;server"&gt;Set up the server&lt;/h3&gt;&lt;p&gt;Let's create a droplet with Ubuntu LTS (18.0.4 at the time of writing) and SSH into it. We'll need to add new APT repositories before we install Dokku.  &lt;/p&gt;&lt;ol&gt;&lt;li&gt;add the universe repository &lt;code&gt;sudo add-apt-repository universe&lt;/code&gt;&lt;/li&gt;&lt;li&gt;add the key &lt;code&gt;wget -nv -O - https://packagecloud.io/dokku/dokku/gpgkey | apt-key add -&lt;/code&gt;&lt;/li&gt;&lt;li&gt;add the Dokku repo &lt;code&gt;echo &amp;quot;deb https://packagecloud.io/dokku/dokku/ubuntu/ bionic main&amp;quot; &amp;gt; /etc/apt/sources.list.d/dokku.list&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Once the repositories are added, we'll need to update the dependencies and install Dokku.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;update dependencies &lt;code&gt;sudo apt-get update &amp;amp;&amp;amp; sudo apt-get upgrade&lt;/code&gt;&lt;/li&gt;&lt;li&gt;install dokku &lt;code&gt;apt-get install dokku&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Once Dokku is installed, we'll create an application and a Postgres database instance.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;create the app &lt;code&gt;dokku apps:create myapp&lt;/code&gt;&lt;/li&gt;&lt;li&gt;install &lt;a href='https://github.com/dokku/dokku-postgres'&gt;dokku-postgres plugin&lt;/a&gt; &lt;code&gt;sudo dokku plugin:install https://github.com/dokku/dokku-postgres.git&lt;/code&gt;&lt;/li&gt;&lt;li&gt;create the db &lt;code&gt;dokku postgres:create mydb&lt;/code&gt;&lt;/li&gt;&lt;li&gt;link the db to the app &lt;code&gt;dokku postgres:link mydb myapp&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;We're now ready to deploy the app.&lt;/p&gt;&lt;h3 id="create&amp;#95;a&amp;#95;new&amp;#95;luminus&amp;#95;application"&gt;Create a new Luminus application&lt;/h3&gt;&lt;p&gt;Let's create a Luminus application on your local machine.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;lein new luminus myapp +postgres&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;cd myapp&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Let's update the app to run migrations on startup by updating the &lt;code&gt;myapp.core/start-app&lt;/code&gt; function to run the migrations.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn start-app &amp;#91;args&amp;#93;
  &amp;#40;doseq &amp;#91;component &amp;#40;-&amp;gt; args
                        &amp;#40;parse-opts cli-options&amp;#41;
                        mount/start-with-args
                        :started&amp;#41;&amp;#93;
    &amp;#40;log/info component &amp;quot;started&amp;quot;&amp;#41;&amp;#41;

  ;;run migrations  
  &amp;#40;migrations/migrate &amp;#91;&amp;quot;migrate&amp;quot;&amp;#93; &amp;#40;select-keys env &amp;#91;:database-url&amp;#93;&amp;#41;&amp;#41;

  &amp;#40;.addShutdownHook &amp;#40;Runtime/getRuntime&amp;#41; &amp;#40;Thread. stop-app&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we need to update &lt;code&gt;env/prod/resources/logback.xml&lt;/code&gt; to use &lt;code&gt;STDOUT&lt;/code&gt; for the logs:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot;?&amp;gt;
&amp;lt;configuration&amp;gt;
    &amp;lt;statusListener class=&amp;quot;ch.qos.logback.core.status.NopStatusListener&amp;quot; /&amp;gt;
    &amp;lt;appender name=&amp;quot;STDOUT&amp;quot; class=&amp;quot;ch.qos.logback.core.ConsoleAppender&amp;quot;&amp;gt;
        &amp;lt;!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --&amp;gt;
        &amp;lt;encoder&amp;gt;
            &amp;lt;charset&amp;gt;UTF-8&amp;lt;/charset&amp;gt;
            &amp;lt;pattern&amp;gt;%date{ISO8601} &amp;#91;%thread&amp;#93; %-5level %logger{36} - %msg %n&amp;lt;/pattern&amp;gt;
        &amp;lt;/encoder&amp;gt;
    &amp;lt;/appender&amp;gt;
    &amp;lt;logger name=&amp;quot;org.apache.http&amp;quot; level=&amp;quot;warn&amp;quot; /&amp;gt;
    &amp;lt;logger name=&amp;quot;org.xnio.nio&amp;quot; level=&amp;quot;warn&amp;quot; /&amp;gt;
    &amp;lt;logger name=&amp;quot;com.zaxxer.hikari&amp;quot; level=&amp;quot;warn&amp;quot; /&amp;gt;
    &amp;lt;root level=&amp;quot;INFO&amp;quot;&amp;gt;
        &amp;lt;appender-ref ref=&amp;quot;STDOUT&amp;quot; /&amp;gt;
    &amp;lt;/root&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="deploy&amp;#95;the&amp;#95;application&amp;#95;to&amp;#95;dokku"&gt;Deploy the application to Dokku&lt;/h3&gt;&lt;p&gt;We're now ready to deploy the app. First, we'll need to create a Git repo and add the app contents to it.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;git init&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;git add .gitignore Procfile project.clj README.md src/&amp;#42; env/&amp;#42; test/&amp;#42; resources/&amp;#42;&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;git commit -a -m &amp;quot;initial commit&amp;quot;&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Note that you do not want to check in &lt;code&gt;Dockerfile&lt;/code&gt; that's generated by the template. Dokku will use it as the preferred strategy for creating the container.&lt;/p&gt;&lt;p&gt;Next, we'll add the remote for the Dokku repository on the server and push the project to the remote. Dokku will automatically build the project once it's pushed, and deploy the application when the build is successful.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;git remote add dokku dokku@&amp;lt;server name&amp;gt;:myapp&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;git push dokku master&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;The app will be pushed to the server where it will be compiled and run. If everything went well you should see output that looks something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;...
-----&amp;gt; Building with Leiningen
       Running: lein uberjar
       Compiling sample.app
       2019-01-18 01:10:30.857:INFO::main: Logging initialized @6674ms to org.eclipse.jetty.util.log.StdErrLog
       Created /tmp/build/target/myapp-1.0.1.jar
       Created /tmp/build/target/myapp.jar
...
=====&amp;gt; web=1
...
-----&amp;gt; Waiting for 10 seconds ...
-----&amp;gt; Default container check successful!
-----&amp;gt; Running post-deploy
-----&amp;gt; Configuring myapp.&amp;lt;server name&amp;gt;...&amp;#40;using built-in template&amp;#41;
-----&amp;gt; Creating http nginx.conf
-----&amp;gt; Running nginx-pre-reload
       Reloading nginx
-----&amp;gt; Setting config vars
       DOKKU&amp;#95;APP&amp;#95;RESTORE:  1
=====&amp;gt; 8dc31ac11011111117f71e4311111ca5962cf316411d5f0125e87bbac26
=====&amp;gt; Application deployed:
       http://myapp.&amp;lt;server name&amp;gt;

To http://&amp;lt;server name&amp;gt;:myapp
   6dcab39..1c0c8b7  master -&amp;gt; master
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can check the status of the application in the logs by running &lt;code&gt;dokku logs myapp&lt;/code&gt; command on the server. The output should looks something like the following.&lt;/p&gt;&lt;pre&gt;&lt;code class="Setting JAVA_TOOL_OPTIONS defaults based on dyno size. Custom settings will override them."&gt;Picked up JAVA&amp;#95;TOOL&amp;#95;OPTIONS: -Xmx300m -Xss512k -XX:CICompilerCount=2 -Dfile.encoding=UTF-8
2019-01-19 19:09:48,258 &amp;#91;main&amp;#93; INFO  myapp.env -
-=&amp;#91;myapp started successfully&amp;#93;=-
2019-01-19 19:09:50,490 &amp;#91;main&amp;#93; INFO  luminus.http-server - starting HTTP server on port 5000
2019-01-19 19:09:50,628 &amp;#91;main&amp;#93; INFO  org.xnio - XNIO version 3.3.6.Final
2019-01-19 19:09:51,236 &amp;#91;main&amp;#93; INFO  org.projectodd.wunderboss.web.Web - Registered web context /
2019-01-19 19:09:51,242 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.config/env started
2019-01-19 19:09:51,243 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.db.core/&amp;#42;db&amp;#42; started
2019-01-19 19:09:51,243 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.handler/init-app started
2019-01-19 19:09:51,244 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.handler/app started
2019-01-19 19:09:51,249 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.core/http-server started
2019-01-19 19:09:51,249 &amp;#91;main&amp;#93; INFO  myapp.core - #'myapp.core/repl-server started
2019-01-19 19:09:51,250 &amp;#91;main&amp;#93; INFO  myapp.core - running migrations
2019-01-19 19:09:51,257 &amp;#91;main&amp;#93; INFO  migratus.core - Starting migrations
2019-01-19 19:09:51,418 &amp;#91;main&amp;#93; INFO  migratus.database - creating migration table 'schema&amp;#95;migrations'
2019-01-19 19:09:51,992 &amp;#91;main&amp;#93; INFO  migratus.core - Running up for &amp;#91;20190118214013&amp;#93;
2019-01-19 19:09:51,997 &amp;#91;main&amp;#93; INFO  migratus.core - Up 20190118214013-add-users-table
2019-01-19 19:09:52,099 &amp;#91;main&amp;#93; INFO  migratus.core - Ending migrations
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You should now be able to check your application in the browser by navigating to &lt;code&gt;http://&amp;lt;server name&amp;gt;&lt;/code&gt;.&lt;/p&gt;&lt;h3 id="troubleshooting&amp;#95;the&amp;#95;database"&gt;Troubleshooting the database&lt;/h3&gt;&lt;p&gt;The startup logs for the application indicate that it was able to connect to the database and run the migrations successfully. Let's confirm this is the case by connecting a &lt;code&gt;psql&lt;/code&gt; shell to the database container on the server.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;dokku postgres:connect mydb
mydb=# \d
               List of relations
 Schema |       Name        | Type  |  Owner
--------+-------------------+-------+----------
 public | schema&amp;#95;migrations | table | postgres
 public | users             | table | postgres
&amp;#40;2 rows&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the database contains the &lt;code&gt;schema&amp;#95;migrations&lt;/code&gt; table and the &lt;code&gt;users&lt;/code&gt; table that were created when the app migrations ran.&lt;/p&gt;&lt;p&gt;Sometimes it might be useful to connect a more advanced client such as &lt;a href='https://dbeaver.io/'&gt;DBeaver&lt;/a&gt;. This can done by exposing the database on the server using the following command.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;sudo dokku postgres:expose mydb 5000
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll enter the container for the application to get the database connection details.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;dokku enter myapp web
echo $DATABASE&amp;#95;URL
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;DATABASE&amp;#95;URL&lt;/code&gt; environment variable in the container will contain the connection string that looks as follows.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;postgres://postgres:&amp;lt;password&amp;gt;@dokku-postgres-mydb:5432/mydb
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now map the port to the local machine using SSH, and connect to the database as if it was running on the local machine using the connection settings above.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;ssh -L 5432:localhost:5000 &amp;lt;server name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="set&amp;#95;up&amp;#95;https&amp;#95;using&amp;#95;let's&amp;#95;encrypt"&gt;Set up HTTPS using Let's Encrypt&lt;/h3&gt;&lt;p&gt;As the last step we'll set up HTTPS for the application using &lt;a href='https://github.com/dokku/dokku-letsencrypt'&gt;dokku-letsencrypt&lt;/a&gt; plugin. We'll set the app to run on the root domain on the server.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;add the root domain to the app &lt;code&gt;dokku domains:add myapp &amp;lt;server name&amp;gt;&lt;/code&gt;&lt;/li&gt;&lt;li&gt;remove the subdomain from the app &lt;code&gt;dokku domains:remove myapp myapp.&amp;lt;server name&amp;gt;&lt;/code&gt;&lt;/li&gt;&lt;li&gt;install the plugin &lt;code&gt;sudo dokku plugin:install https://github.com/dokku/dokku-letsencrypt.git&lt;/code&gt;&lt;/li&gt;&lt;li&gt;set the email for renewal warnings &lt;code&gt;dokku config:set --no-restart myapp DOKKU&amp;#95;LETSENCRYPT&amp;#95;EMAIL=&amp;lt;your email&amp;gt;&lt;/code&gt;&lt;/li&gt;&lt;li&gt;add HTTPS to the app &lt;code&gt;sudo dokku letsencrypt myapp&lt;/code&gt;&lt;/li&gt;&lt;li&gt;set up auto-renew for the certificate &lt;code&gt;dokku letsencrypt:auto-renew&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;That's all there is to it. The application is now deployed to the droplet, it's hooked up to the database, and it's using Let's Encrypt SSL/TLS Certificates.&lt;/p&gt;&lt;p&gt;Any further updates to the application simply involve committing the changes to the local Git repo and pushing them to the server as we did with our initial deploy.&lt;/p&gt;&lt;p&gt;I recommend taking look at the &lt;a href='http://dokku.viewdocs.io/dokku/getting-started/installation/'&gt;official documentation&lt;/a&gt; on the Dokku site for more information about Dokku. I think it provides an excellent solution for running your VPS. If you're evaluating different options for deploying your Clojure apps give Dokku a look.&lt;/p&gt;</description><pubDate>Sat, 19 Jan 2019 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2018-01-12-ClojureScriptErrorPropagation.html</guid><link>https://yogthos.net/posts/2018-01-12-ClojureScriptErrorPropagation.html</link><title>Capturing ClojureScript Errors on the Server</title><description>&lt;p&gt;Logging errors is an important aspect of writing real-world applications. When something goes wrong at runtime it's very helpful to have a log detailing what went wrong in order to fix the problem. This is a straightforward process when we're working on the backend code. We can catch the exception and log it along with the stack trace. However, we need to get a bit more creative in order to handle client-side errors.&lt;/p&gt;&lt;p&gt;In this post we'll take a look at propagating errors from a &lt;a href='http://reagent-project.github.io/'&gt;Reagent&lt;/a&gt; based app back to the server. A naive implementation might look something like the following. We'll write a function that accepts an event containing the error, then send the error message along with the stack trace to the server:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn report-error! &amp;#91;event&amp;#93;
  &amp;#40;let &amp;#91;error &amp;#40;.-error event&amp;#41;
        message &amp;#40;.-message error&amp;#41;
        stacktrace &amp;#40;.-stack error&amp;#41;&amp;#93;    
    &amp;#40;ajax/POST &amp;quot;/error&amp;quot;
               {:headers
                {&amp;quot;x-csrf-token&amp;quot;
                 &amp;#40;.-value &amp;#40;js/document.getElementById &amp;quot;&amp;#95;&amp;#95;anti-forgery-token&amp;quot;&amp;#41;&amp;#41;}
                :params
                {:message     message
                 :stacktrace stacktrace}}&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll set the &lt;code&gt;report-error!&lt;/code&gt; function as the global &lt;code&gt;error&lt;/code&gt; event listener:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;.addEventListener js/window &amp;quot;error&amp;quot; report-error!&amp;#41;
  &amp;#40;reagent/render &amp;#91;home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;home-page&lt;/code&gt; function will render a button that will throw an error when it's clicked:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;:div&amp;gt;h2 &amp;quot;Error Test&amp;quot;
   &amp;#91;:div&amp;gt;button
    {:on-click #&amp;#40;throw &amp;#40;js/Error. &amp;quot;I'm an error&amp;quot;&amp;#41;&amp;#41;}
    &amp;quot;throw an error&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If we pop up the console in the browser we should see something like the following there:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Uncaught Error: I'm an error
    at app.core.home&amp;#95;page &amp;#40;core.cljs:25&amp;#41;
    at Object.ReactErrorUtils.invokeGuardedCallback &amp;#40;react-dom.inc.js:9073&amp;#41;
    at executeDispatch &amp;#40;react-dom.inc.js:3031&amp;#41;
    at Object.executeDispatchesInOrder &amp;#40;react-dom.inc.js:3054&amp;#41;
    at executeDispatchesAndRelease &amp;#40;react-dom.inc.js:2456&amp;#41;
    at executeDispatchesAndReleaseTopLevel &amp;#40;react-dom.inc.js:2467&amp;#41;
    at Array.forEach &amp;#40;&amp;lt;anonymous&amp;gt;&amp;#41;
    at forEachAccumulated &amp;#40;react-dom.inc.js:15515&amp;#41;
    at Object.processEventQueue &amp;#40;react-dom.inc.js:2670&amp;#41;
    at runEventQueueInBatch &amp;#40;react-dom.inc.js:9097&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This gives us the namespace and the line number in the ClojureScript source that caused the error. However, if we print the message that we received on the server it will look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt; Error: I'm an error
    at app.core.home&amp;#95;page &amp;#40;http://localhost:3000/js/out/app/core.js:51:8&amp;#41;
    at Object.ReactErrorUtils.invokeGuardedCallback &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:9073:16&amp;#41;
    at executeDispatch &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:3031:21&amp;#41;
    at Object.executeDispatchesInOrder &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:3054:5&amp;#41;
    at executeDispatchesAndRelease &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:2456:22&amp;#41;
    at executeDispatchesAndReleaseTopLevel &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:2467:10&amp;#41;
    at Array.forEach &amp;#40;&amp;lt;anonymous&amp;gt;&amp;#41;
    at forEachAccumulated &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:15515:9&amp;#41;
    at Object.processEventQueue &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:2670:7&amp;#41;
    at runEventQueueInBatch &amp;#40;http://localhost:3000/js/out/cljsjs/react-dom/development/react-dom.inc.js:9097:18&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The stack trace is there, but it's no longer source mapped. So we'll know what namespace caused the error, but not the line in question. In order to get a source mapped stack trace we'll have to use a library such as &lt;a href='https://github.com/stacktracejs/stacktrace.js'&gt;stacktrace.js&lt;/a&gt;. Unfortunately, we won't be able to use the new &lt;code&gt;:npm-deps&lt;/code&gt; option in the ClojureScript compiler. This works as expected when &lt;code&gt;:optimizations&lt;/code&gt; are set to &lt;code&gt;:none&lt;/code&gt;, but fails to provide us with the source mapped stack trace in the &lt;code&gt;:advanced&lt;/code&gt; mode.&lt;/p&gt;&lt;p&gt;Instead, we'll use the &lt;a href='https://www.webjars.org/'&gt;WebJars&lt;/a&gt; dependency along with the &lt;a href='https://github.com/weavejester/ring-webjars'&gt;ring-webjars&lt;/a&gt; middleware:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:dependencies
&amp;#91;...
 &amp;#91;ring-webjars &amp;quot;0.2.0&amp;quot;&amp;#93;
 &amp;#91;org.webjars.bower/stacktrace-js &amp;quot;2.0.0&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The middleware uses the &lt;code&gt;/assets/&amp;lt;webjar&amp;gt;/&amp;lt;asset path&amp;gt;&lt;/code&gt; pattern to load the resources packaged in WebJars dependencies. Here's how this would look for loading the stacktrace-js resource. &lt;/p&gt;&lt;p&gt;We'll require the middleware:  &lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns app.handler
 &amp;#40;:require
  ...
  &amp;#91;ring.middleware.webjars :refer &amp;#91;wrap-webjars&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Wrap the Ring handler with it:  &lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt; &amp;#40;defn -main &amp;#91;&amp;#93;
  &amp;#40;run-jetty
   &amp;#40;-&amp;gt; handler
       &amp;#40;wrap-webjars&amp;#41;
       &amp;#40;wrap-defaults site-defaults&amp;#41;&amp;#41;
   {:port 3000 :join? false}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;stacktrace.min.js&lt;/code&gt; file packaged in the &lt;code&gt;org.webjars.bower/stacktrace-js&lt;/code&gt; dependency will be available as a resource at the following path &lt;code&gt;/assets/stacktrace-js/dist/stacktrace.min.js&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defroutes handler
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93;
    &amp;#40;html5
      &amp;#91;:head
       &amp;#91;:meta {:charset &amp;quot;utf-8&amp;quot;}&amp;#93;
       &amp;#40;anti-forgery-field&amp;#41;&amp;#93;
      &amp;#91;:body
       &amp;#91;:div#app&amp;#93;
        &amp;#40;include-js &amp;quot;/assets/stacktrace-js/dist/stacktrace.min.js&amp;quot;
                    &amp;quot;/js/app.js&amp;quot;&amp;#41;&amp;#93;&amp;#41;&amp;#41;
  
  &amp;#40;POST &amp;quot;/error&amp;quot; {:keys &amp;#91;body&amp;#93;}
    &amp;#40;let &amp;#91;{:keys &amp;#91;message stacktrace&amp;#93;}
          &amp;#40;-&amp;gt; body
              &amp;#40;transit/reader :json&amp;#41;
              &amp;#40;transit/read&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;println &amp;quot;Client error:&amp;quot; message &amp;quot;\n&amp;quot; stacktrace&amp;#41;&amp;#41;
    &amp;quot;ok&amp;quot;&amp;#41;
  
  &amp;#40;resources &amp;quot;/&amp;quot;&amp;#41;
  &amp;#40;not-found &amp;quot;Not Found&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt; &lt;br /&gt;&lt;p&gt;Finally, the ClojureScript compiler configuration will look as follows:  &lt;/p&gt; &lt;pre&gt;&lt;code class="clojure"&gt;{:output-dir &amp;quot;target/cljsbuild/public/js&amp;quot;
 :output-to  &amp;quot;target/cljsbuild/public/js/app.js&amp;quot;
 :source-map &amp;quot;target/cljsbuild/public/js/app.js.map&amp;quot;
 :optimizations :advanced
 :infer-externs true
 :closure-warnings {:externs-validation :off
                    :non-standard-jsdoc :off}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We need to specify the name of the source map file when using the advanced optimization, tell the compiler to infer the externs, and optionally suppress the warnings.&lt;/p&gt;&lt;p&gt;The new version of the &lt;code&gt;report-error!&lt;/code&gt; function will look similar to the original, except that we'll now be passing the error to the &lt;code&gt;StackTrace.fromError&lt;/code&gt; function. This function returns a promise containing the source mapped stack trace that we'll be sending to the server:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn report-error! &amp;#91;event&amp;#93;
  &amp;#40;let &amp;#91;error &amp;#40;.-error event&amp;#41;&amp;#93;
    &amp;#40;-&amp;gt; &amp;#40;js/StackTrace.fromError error&amp;#41;
        &amp;#40;.then
         &amp;#40;fn &amp;#91;stacktrace&amp;#93;
           &amp;#40;ajax/POST &amp;quot;/error&amp;quot;
                      {:headers
                       {&amp;quot;x-csrf-token&amp;quot;
                        &amp;#40;.-value &amp;#40;js/document.getElementById &amp;quot;&amp;#95;&amp;#95;anti-forgery-token&amp;quot;&amp;#41;&amp;#41;}
                       :params
                       {:message    &amp;#40;.-message error&amp;#41;
                        :stacktrace &amp;#40;-&amp;gt;&amp;gt; stacktrace
                                          &amp;#40;mapv #&amp;#40;.toString %&amp;#41;&amp;#41;
                                          &amp;#40;string/join &amp;quot;\n &amp;quot;&amp;#41;&amp;#41;}}&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;This time around we should see the source mapped error on the server with all the information that we need:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;I'm an error
 Error&amp;#40;&amp;#41;@http://localhost:3000/js/app/core.cljs:27:23
 mountComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:40:5631
 focusDOMComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:38:22373
 focusDOMComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:38:22588
 focusDOMComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:38:18970
 focusDOMComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:38:19096
 didPutListener&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:41:12120
 focusDOMComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:38:20154
 mountComponent&amp;#40;&amp;#41;@http://localhost:3000/js/app.js:40:5880
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the error occurred on line 27 of the &lt;code&gt;app.core&lt;/code&gt; namespace which is indeed where the code that throws the exception resides. The full listing for the example is available on &lt;a href='https://github.com/yogthos/clojurescript-error-reporting-example'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;While the example in this post illustrates bare bones exception handling, we can do more interesting things in a real world application. For example, &lt;a href='https://github.com/Day8/re-frame'&gt;re-frame&lt;/a&gt; based application could send the entire state of the re-frame database at the time of the error to the server. This allows us to put the application in the exact state that caused the error when debugging the problem.&lt;/p&gt;</description><pubDate>Fri, 12 Jan 2018 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2017-10-03-MovingForwardByLettingGo.html</guid><link>https://yogthos.net/posts/2017-10-03-MovingForwardByLettingGo.html</link><title>Moving Forward by Letting Go</title><description>&lt;p&gt;Lisps are famous for having powerful metaprogramming facilities derived from their homoiconic nature. Core language consists of a small set of built in primitives, and the rest is implemented using macros and functions in the standard library.&lt;/p&gt;&lt;p&gt;Since these same tools are available to the users, anybody can easily extend the language to add semantics for their problem domain. This is the aspect of macros that's discussed most often.&lt;/p&gt;&lt;p&gt;While this is certainly the case, Clojure community tends to discourage using macros if they can be avoided. The rationale behind this being that macros introduce additional complexity, and Clojure values simplicity. I generally agree with this sentiment, and I find that I tend to use macros sparingly myself. However, saying that macros shouldn’t be overused is not the same as saying they shouldn’t be used at all.&lt;/p&gt;&lt;p&gt;One place where macros work well is library APIs. Libraries that express a particular domain can create a DSL in their API that cleanly maps to that domain. &lt;a href='https://github.com/weavejester/compojure'&gt;Compojure&lt;/a&gt;, &lt;a href='https://github.com/nathanmarz/specter'&gt;Specter&lt;/a&gt;, and &lt;a href='http://www.clara-rules.org/'&gt;Clara Rules&lt;/a&gt; are great examples of effective macro use. Such libraries are a powerful demonstration of users extending semantics of the language.&lt;/p&gt;&lt;p&gt;Since most ideas can be expressed via libraries, it becomes possible to experiment with different approaches to solving problems without modifying the core language. Extending the language through libraries has the advantage of keeping these extensions contained. It also lets them fade away when you no longer use them.&lt;/p&gt;&lt;p&gt;Clojure has been around for a decade now, and the core language hasn't changed much in that time. Some new features have been added, most notably reducers and transducers, but overall the language has stayed small and focused. In fact, I've even seen concerns that Clojure is stagnating because features aren't being added at the rate of other languages.&lt;/p&gt;&lt;p&gt;The idea of using libraries to add features is used by the Clojure core team as well. Consider the example of the &lt;a href='https://github.com/clojure/core.async'&gt;core.async&lt;/a&gt; library that brings Go channel semantics and the CSP programming model to Clojure.&lt;/p&gt;&lt;p&gt;Perhaps, in time a better idea will come along, and core.async library will become deprecated. At that point developers would stop using the library and move on to use whatever happens to replace it.&lt;/p&gt;&lt;p&gt;Meanwhile, existing projects will not be affected as they can continue using the library. The community will move on, and most people won't have to learn about core.async semantics. This cycle may happen many times with many different ideas, without any baggage being accumulate by the language itself.&lt;/p&gt;&lt;p&gt;Unfortunately, mainstream languages are designed in a way where it's not practical to add new features without updating the language specification to accommodate them. Popular languages such as Java, Python, and JavaScript have accumulated a lot of complexity over the years.&lt;/p&gt;&lt;p&gt;As usage patterns change, new features are being added, while existing features become deprecated. Removing features is difficult since many projects in the wild end up relying on them, so they're typically left in place.&lt;/p&gt;&lt;p&gt;Having lots of features in a language can seem like a positive at first glance, but in practice, features often turn into &lt;a href='http://yogthos.net/posts/2013-08-18-Why-I-m-Productive-in-Clojure.html'&gt;a mental burden&lt;/a&gt; for the developer. Eventually languages become too large to understand fully, and developers settle on a subset of the features considered to be the current best practice. &lt;/p&gt;&lt;p&gt;In my opinion, this is the real power of homoiconicity. A language that can be extended in user space can evolve without accumulating baggage. New ideas can be implemented as libraries, and later discarded when better ideas come along. The end result is a small and focused language that doesn't sacrifice flexibility.&lt;/p&gt;</description><pubDate>Tue, 03 Oct 2017 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2017-03-26-ReagentReactView.html</guid><link>https://yogthos.net/posts/2017-03-26-ReagentReactView.html</link><title>Comparing Reagent to React.js and Vue.js for dynamic tabular data</title><description>&lt;p&gt;I recently ran across a &lt;a href='https://engineering.footballradar.com/a-fairer-vue-of-react-comparing-react-to-vue-for-dynamic-tabular-data-part-2/?utm_content=buffer0e901'&gt;comparison of React.js to Vue.js for rendering dynamic tabular data&lt;/a&gt;, and I got curious to see how &lt;a href='https://github.com/reagent-project/reagent'&gt;Reagent&lt;/a&gt; would stack up against them.&lt;/p&gt;&lt;p&gt;The benchmark simulates a view of football games represented by a table. Each row in the table represents the state of a particular game. The game states are updated once a second triggering UI repaints.&lt;/p&gt;&lt;p&gt;I structured the application similarly to the way that React.js version was structured in the original benchmark. The application has a &lt;code&gt;football.data&lt;/code&gt; namespace to handle the business logic, and a &lt;code&gt;football.core&lt;/code&gt; namespace to render the view.&lt;/p&gt;&lt;h3 id="implementing&amp;#95;the&amp;#95;business&amp;#95;logic"&gt;Implementing the Business Logic&lt;/h3&gt;&lt;p&gt;Let's start by implementing the business logic in the &lt;code&gt;football.data&lt;/code&gt; namespace. First, we'll need to provide a container to hold the state of the games. To do that we'll create a Reagent atom called &lt;code&gt;games&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns football.data
  &amp;#40;:require &amp;#91;reagent.core :as reagent&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defonce games &amp;#40;reagent/atom nil&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll add a function to generate the fake players:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn generate-fake-player &amp;#91;&amp;#93;
  {:name               &amp;#40;-&amp;gt; js/faker .-name &amp;#40;.findName&amp;#41;&amp;#41;
   :effort-level       &amp;#40;rand-int 10&amp;#41;
   :invited-next-week? &amp;#40;&amp;gt; &amp;#40;rand&amp;#41; 0.5&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You can see that we're using JavaScript interop to leverage the &lt;a href='https://github.com/marak/Faker.js/'&gt;Faker.js&lt;/a&gt; library for generating the player names. One nice aspect of working with ClojureScript is that JavaScript interop tends to be seamless as seen in the code above.&lt;/p&gt;&lt;p&gt;Now that we have a way to generate the players, let's add a function to generate fake games:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn generate-fake-game &amp;#91;&amp;#93;
  {:id                 &amp;#40;-&amp;gt; js/faker .-random &amp;#40;.uuid&amp;#41;&amp;#41;
   :clock              0
   :score              {:home 0 :away 0}
   :teams              {:home &amp;#40;-&amp;gt; js/faker .-address &amp;#40;.city&amp;#41;&amp;#41;
                        :away &amp;#40;-&amp;gt; js/faker .-address &amp;#40;.city&amp;#41;&amp;#41;}
   :outrageous-tackles 0
   :cards              {:yellow 0 :read 0}
   :players            &amp;#40;mapv generate-fake-player &amp;#40;range 4&amp;#41;&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With the functions to generate the players and the games in place, we'll now add a function to generate a set of initial game states:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn generate-games &amp;#91;game-count&amp;#93;
  &amp;#40;reset! games &amp;#40;mapv generate-fake-game &amp;#40;range game-count&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The next step is to write the functions to update the games and players to simulate the progression of the games. This code translates pretty much directly from the JavaScript version:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn maybe-update &amp;#91;game prob path f&amp;#93;
  &amp;#40;if &amp;#40;&amp;lt; &amp;#40;rand-int 100&amp;#41; prob&amp;#41;
    &amp;#40;update-in game path f&amp;#41;
    game&amp;#41;&amp;#41;

&amp;#40;defn update-rand-player &amp;#91;game idx&amp;#93;
  &amp;#40;-&amp;gt; game
      &amp;#40;assoc-in &amp;#91;:players idx :effort-level&amp;#93; &amp;#40;rand-int 10&amp;#41;&amp;#41;
      &amp;#40;assoc-in &amp;#91;:players idx :invited-next-week?&amp;#93; &amp;#40;&amp;gt; &amp;#40;rand&amp;#41; 0.5&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn update-game &amp;#91;game&amp;#93;
  &amp;#40;-&amp;gt; game
      &amp;#40;update :clock inc&amp;#41;
      &amp;#40;maybe-update 5 &amp;#91;:score :home&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 5 &amp;#91;:score :away&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 8 &amp;#91;:cards :yellow&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 2 &amp;#91;:cards :red&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 10 &amp;#91;:outrageous-tackles&amp;#93; inc&amp;#41;
      &amp;#40;update-rand-player &amp;#40;rand-int 4&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The last thing we need to do is to add the functions to update the game states at a specified interval. The original code uses &lt;a href='https://github.com/Reactive-Extensions/RxJS'&gt;Rx.js&lt;/a&gt; to accomplish this, but it's just as easy to do using the &lt;code&gt;setTimeout&lt;/code&gt; function with Reagent:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn update-game-at-interval &amp;#91;interval idx&amp;#93;
  &amp;#40;swap! games update idx update-game&amp;#41;
  &amp;#40;js/setTimeout update-game-at-interval interval interval idx&amp;#41;&amp;#41;

&amp;#40;def event-interval 1000&amp;#41;

&amp;#40;defn update-games &amp;#91;game-count&amp;#93;
  &amp;#40;dotimes &amp;#91;i game-count&amp;#93;
    &amp;#40;swap! games update i update-game&amp;#41;
    &amp;#40;js/setTimeout #&amp;#40;update-game-at-interval event-interval i&amp;#41;
                   &amp;#40;&amp;#42; i event-interval&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;update-games&lt;/code&gt; function updates the state of each game, then sets up a timeout for the recurring updates using the &lt;code&gt;update-game-at-interval&lt;/code&gt; function.&lt;/p&gt;&lt;h3 id="implementing&amp;#95;the&amp;#95;view"&gt;Implementing the View&lt;/h3&gt;&lt;p&gt;We're now ready to write the view portion of the application. We'll start by referencing the &lt;code&gt;football.data&lt;/code&gt; namespace in the &lt;code&gt;football.core&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns football.core
  &amp;#40;:require
    &amp;#91;football.data :as data&amp;#93;
    &amp;#91;reagent.core :as reagent&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll write the components to display the players and the games:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn player-component &amp;#91;{:keys &amp;#91;name invited-next-week? effort-level&amp;#93;}&amp;#93;
  &amp;#91;:td
   &amp;#91;:div.player
    &amp;#91;:p.player&amp;#95;&amp;#95;name
     &amp;#91;:span name&amp;#93;
     &amp;#91;:span.u-small &amp;#40;if invited-next-week? &amp;quot;Doing well&amp;quot; &amp;quot;Not coming again&amp;quot;&amp;#41;&amp;#93;&amp;#93;
    &amp;#91;:div {:class-name &amp;#40;str &amp;quot;player&amp;#95;&amp;#95;effort &amp;quot;
                            &amp;#40;if &amp;#40;&amp;lt; effort-level 5&amp;#41;
                              &amp;quot;player&amp;#95;&amp;#95;effort--low&amp;quot;
                              &amp;quot;player&amp;#95;&amp;#95;effort--high&amp;quot;&amp;#41;&amp;#41;}&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn game-component &amp;#91;game&amp;#93;
  &amp;#91;:tr
   &amp;#91;:td.u-center &amp;#40;:clock game&amp;#41;&amp;#93;
   &amp;#91;:td.u-center &amp;#40;-&amp;gt; game :score :home&amp;#41; &amp;quot;-&amp;quot; &amp;#40;-&amp;gt; game :score :away&amp;#41;&amp;#93;
   &amp;#91;:td.cell--teams &amp;#40;-&amp;gt; game :teams :home&amp;#41; &amp;quot;-&amp;quot; &amp;#40;-&amp;gt; game :teams :away&amp;#41;&amp;#93;
   &amp;#91;:td.u-center &amp;#40;:outrageous-tackles game&amp;#41;&amp;#93;
   &amp;#91;:td
    &amp;#91;:div.cards
     &amp;#91;:div.cards&amp;#95;&amp;#95;card.cards&amp;#95;&amp;#95;card--yellow &amp;#40;-&amp;gt; game :cards :yellow&amp;#41;&amp;#93;
     &amp;#91;:div.cards&amp;#95;&amp;#95;card.cards&amp;#95;&amp;#95;card--red &amp;#40;-&amp;gt; game :cards :red&amp;#41;&amp;#93;&amp;#93;&amp;#93;
   &amp;#40;for &amp;#91;player &amp;#40;:players game&amp;#41;&amp;#93;
     &amp;#94;{:key player}
     &amp;#91;player-component player&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;defn games-component &amp;#91;&amp;#93;
  &amp;#91;:tbody
   &amp;#40;for &amp;#91;game @data/games&amp;#93;
     &amp;#94;{:key game}
     &amp;#91;game-component game&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;defn games-table-component &amp;#91;&amp;#93;
  &amp;#91;:table
   &amp;#91;:thead
    &amp;#91;:tr
     &amp;#91;:th {:width &amp;quot;50px&amp;quot;} &amp;quot;Clock&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;50px&amp;quot;} &amp;quot;Score&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;200px&amp;quot;} &amp;quot;Teams&amp;quot;&amp;#93;
     &amp;#91;:th &amp;quot;Outrageous Tackles&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;Cards&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;Players&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;&amp;#93;&amp;#93;
   &amp;#91;games-component&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You can see that HTML elements in Reagent components are represented using Clojure vectors and maps. Since s-expressions cleanly map to HTML, there's no need to use an additional DSL for that. You'll also notice that components can be nested within one another same way as plain HTML elements.&lt;/p&gt;&lt;p&gt;Noe thing to note is that the &lt;code&gt;games-component&lt;/code&gt; dereferences the &lt;code&gt;data/games&lt;/code&gt; atom using the &lt;code&gt;@&lt;/code&gt; notation. Dereferencing simply means that we'd like to view the current state of a mutable variable.&lt;/p&gt;&lt;p&gt;Reagent atoms are reactive, and listeners are created when the atoms are dereferenced. Whenever the state of the atom changes, any components that are observing the atom will be notified of the change.&lt;/p&gt;&lt;p&gt;In our case, changes in the state of the &lt;code&gt;games&lt;/code&gt; atom will trigger the &lt;code&gt;games-component&lt;/code&gt; function to be evaluated. The function will pass the current state of the games down to its child components, and this will trigger any necessary repaints in the UI.&lt;/p&gt;&lt;p&gt;Finally, we have a bit of code to create the root component represented by the &lt;code&gt;home-page&lt;/code&gt; function, and initialize the application:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;games-table-component&amp;#93;&amp;#41;

&amp;#40;defn mount-root &amp;#91;&amp;#93;
  &amp;#40;reagent/render &amp;#91;home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;def game-count 50&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;data/generate-games game-count&amp;#41;
  &amp;#40;data/update-games game-count&amp;#41;
  &amp;#40;mount-root&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We now have a naive implementation of the benchmark using Reagent. The entire project is &lt;a href='https://github.com/yogthos/ReagentPerf'&gt;available on GitHub&lt;/a&gt;. Next, let's take a look at how it performs.&lt;/p&gt;&lt;h3 id="profiling&amp;#95;with&amp;#95;chrome"&gt;Profiling with Chrome&lt;/h3&gt;&lt;p&gt;When we profile the app in Chrome, we'll see the following results:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/reagent-perf/reagent.png" alt="Reagent Results" /&gt;&lt;/p&gt;&lt;p&gt;Here are the results for React.js and Vue.js running in the same environment for comparison:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/reagent-perf/react.png" alt="React.js Results" /&gt;&lt;/p&gt;&lt;p&gt;&lt;img src="/img/reagent-perf/vue.png" alt="Vue.js Results" /&gt;&lt;/p&gt;&lt;p&gt;As you can see, the naive Reagent version spends about double the time scripting compared to React.js, and about four times as long rendering.&lt;/p&gt;&lt;p&gt;The reason is that we're dereferencing the &lt;code&gt;games&lt;/code&gt; atom at top level. This forces the top level component to be reevaluated whenever the sate of any game changes.&lt;/p&gt;&lt;p&gt;Reagent provides a mechanism for dealing with this problem in the form of cursors. A cursor allows subscribing to changes at a specified path within the atom. A component that dereferences a cursor will only be updated when the data the cursor points to changes. This allows us to granularly control what components will be repainted when a particular piece of data changes in the &lt;code&gt;games&lt;/code&gt; atom. Let's update the view logic as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn player-component &amp;#91;player&amp;#93;
  &amp;#91;:td
   &amp;#91;:div.player
    &amp;#91;:p.player&amp;#95;&amp;#95;name
     &amp;#91;:span &amp;#40;:name @player&amp;#41;&amp;#93;
     &amp;#91;:span.u-small
      &amp;#40;if &amp;#40;:invited-next-week? @player&amp;#41;
        &amp;quot;Doing well&amp;quot; &amp;quot;Not coming again&amp;quot;&amp;#41;&amp;#93;&amp;#93;
    &amp;#91;:div {:class-name &amp;#40;str &amp;quot;player&amp;#95;&amp;#95;effort &amp;quot;
                            &amp;#40;if &amp;#40;&amp;lt; &amp;#40;:effort-level @player&amp;#41; 5&amp;#41;
                              &amp;quot;player&amp;#95;&amp;#95;effort--low&amp;quot;
                              &amp;quot;player&amp;#95;&amp;#95;effort--high&amp;quot;&amp;#41;&amp;#41;}&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn game-component &amp;#91;game&amp;#93;
  &amp;#91;:tr
   &amp;#91;:td.u-center &amp;#40;:clock @game&amp;#41;&amp;#93;
   &amp;#91;:td.u-center &amp;#40;-&amp;gt; @game :score :home&amp;#41; &amp;quot;-&amp;quot; &amp;#40;-&amp;gt; @game :score :away&amp;#41;&amp;#93;
   &amp;#91;:td.cell--teams &amp;#40;-&amp;gt; @game :teams :home&amp;#41; &amp;quot;-&amp;quot; &amp;#40;-&amp;gt; @game :teams :away&amp;#41;&amp;#93;
   &amp;#91;:td.u-center &amp;#40;:outrageous-tackles @game&amp;#41;&amp;#93;
   &amp;#91;:td
    &amp;#91;:div.cards
     &amp;#91;:div.cards&amp;#95;&amp;#95;card.cards&amp;#95;&amp;#95;card--yellow &amp;#40;-&amp;gt; @game :cards :yellow&amp;#41;&amp;#93;
     &amp;#91;:div.cards&amp;#95;&amp;#95;card.cards&amp;#95;&amp;#95;card--red &amp;#40;-&amp;gt; @game :cards :red&amp;#41;&amp;#93;&amp;#93;&amp;#93;
   &amp;#40;for &amp;#91;idx &amp;#40;range &amp;#40;count &amp;#40;:players @game&amp;#41;&amp;#41;&amp;#41;&amp;#93;
     &amp;#94;{:key idx}
     &amp;#91;player-component &amp;#40;reagent/cursor game &amp;#91;:players idx&amp;#93;&amp;#41;&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;def game-count 50&amp;#41;

&amp;#40;defn games-component &amp;#91;&amp;#93;
  &amp;#91;:tbody
   &amp;#40;for &amp;#91;idx &amp;#40;range game-count&amp;#41;&amp;#93;
     &amp;#94;{:key idx}
     &amp;#91;game-component &amp;#40;reagent/cursor data/games &amp;#91;idx&amp;#93;&amp;#41;&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;defn games-table-component &amp;#91;&amp;#93;
  &amp;#91;:table
   &amp;#91;:thead
    &amp;#91;:tr
     &amp;#91;:th {:width &amp;quot;50px&amp;quot;} &amp;quot;Clock&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;50px&amp;quot;} &amp;quot;Score&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;200px&amp;quot;} &amp;quot;Teams&amp;quot;&amp;#93;
     &amp;#91;:th &amp;quot;Outrageous Tackles&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;Cards&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;Players&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;
     &amp;#91;:th {:width &amp;quot;100px&amp;quot;} &amp;quot;&amp;quot;&amp;#93;&amp;#93;&amp;#93;
   &amp;#91;games-component&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;games-table-component&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above version creates a cursor for each game in the &lt;code&gt;games-components&lt;/code&gt;. The &lt;code&gt;game-component&lt;/code&gt; in turn creates a cursor for each player. This way only the components that actually need updating end up being rendered as the state of the games is updated. Let's profile the application again to see how much impact this has on its performance:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/reagent-perf/reagent-cursor.png" alt="Reagent Results" /&gt;&lt;/p&gt;&lt;p&gt;The performance of the Reagent code using cursors now looks similar to that of the Vue.js implementation. You can see the entire source for the updated version &lt;a href='https://github.com/yogthos/ReagentPerf/tree/reagent-cursors'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;In this post we saw that ClojureScript with Reagent provides a compelling alternative to JavaScript offerings such as React.js and Vue.js.&lt;/p&gt;&lt;p&gt;Reagent allows writing succinct solutions that perform as well as those implemented using native JavaScript libraries. It also provides us with tools to intuitively reason about what parts of the view are going to be updated.&lt;/p&gt;&lt;p&gt;Likewise, we get many benefits by simply switching from using JavaScript to ClojureScript.&lt;/p&gt;&lt;p&gt;For example, We already saw that we didn't need any additional syntax, such as JSX, to represent HTML elements. Since HTML templates are represented using regular data structures, they follows the same rules as any other code. This allows us to transform them just like we would any other data in our project.&lt;/p&gt;&lt;p&gt;In general, I find ClojureScript to be much more consistent and less noisy than equivalent JavaScript code. Consider the implementation of the &lt;code&gt;updateGame&lt;/code&gt; function in the original JavaScript version:&lt;/p&gt;&lt;pre&gt;&lt;code class="javascript"&gt;function updateGame&amp;#40;game&amp;#41; {
    game = game.update&amp;#40;&amp;quot;clock&amp;quot;, &amp;#40;sec&amp;#41; =&amp;gt; sec + 1&amp;#41;;

    game = maybeUpdate&amp;#40;5, game, &amp;#40;&amp;#41; =&amp;gt; game.updateIn&amp;#40;&amp;#91;&amp;quot;score&amp;quot;, &amp;quot;home&amp;quot;&amp;#93;, &amp;#40;s&amp;#41; =&amp;gt; s + 1&amp;#41;&amp;#41;;
    game = maybeUpdate&amp;#40;5, game, &amp;#40;&amp;#41; =&amp;gt; game.updateIn&amp;#40;&amp;#91;&amp;quot;score&amp;quot;, &amp;quot;away&amp;quot;&amp;#93;, &amp;#40;s&amp;#41; =&amp;gt; s + 1&amp;#41;&amp;#41;;
    
    game = maybeUpdate&amp;#40;8, game, &amp;#40;&amp;#41; =&amp;gt; game.updateIn&amp;#40;&amp;#91;&amp;quot;cards&amp;quot;, &amp;quot;yellow&amp;quot;&amp;#93;, &amp;#40;s&amp;#41; =&amp;gt; s + 1&amp;#41;&amp;#41;;
    game = maybeUpdate&amp;#40;2, game, &amp;#40;&amp;#41; =&amp;gt; game.updateIn&amp;#40;&amp;#91;&amp;quot;cards&amp;quot;, &amp;quot;red&amp;quot;&amp;#93;, &amp;#40;s&amp;#41; =&amp;gt; s + 1&amp;#41;&amp;#41;;

    game = maybeUpdate&amp;#40;10, game, &amp;#40;&amp;#41; =&amp;gt; game.update&amp;#40;&amp;quot;outrageousTackles&amp;quot;, &amp;#40;t&amp;#41; =&amp;gt; t + 1&amp;#41;&amp;#41;;

    const randomPlayerIndex = randomNum&amp;#40;0, 4&amp;#41;;
    const effortLevel = randomNum&amp;#40;&amp;#41;;
    const invitedNextWeek = faker.random.boolean&amp;#40;&amp;#41;;

    game = game.updateIn&amp;#40;&amp;#91;&amp;quot;players&amp;quot;, randomPlayerIndex&amp;#93;, &amp;#40;player&amp;#41; =&amp;gt; {
        return player.set&amp;#40;&amp;quot;effortLevel&amp;quot;, effortLevel&amp;#41;.set&amp;#40;&amp;quot;invitedNextWeek&amp;quot;, invitedNextWeek&amp;#41;;
    }&amp;#41;;

    return game;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Compare it with the equivalent ClojureScript code:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn update-rand-player &amp;#91;game idx&amp;#93;
  &amp;#40;-&amp;gt; game
      &amp;#40;assoc-in &amp;#91;:players idx :effort-level&amp;#93; &amp;#40;rand-int 10&amp;#41;&amp;#41;
      &amp;#40;assoc-in &amp;#91;:players idx :invited-next-week?&amp;#93; &amp;#40;&amp;gt; &amp;#40;rand&amp;#41; 0.5&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn update-game &amp;#91;game&amp;#93;
  &amp;#40;-&amp;gt; game
      &amp;#40;update :clock inc&amp;#41;
      &amp;#40;maybe-update 5 &amp;#91;:score :home&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 5 &amp;#91;:score :away&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 8 &amp;#91;:cards :yellow&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 2 &amp;#91;:cards :red&amp;#93; inc&amp;#41;
      &amp;#40;maybe-update 10 &amp;#91;:outrageous-tackles&amp;#93; inc&amp;#41;
      &amp;#40;update-rand-player &amp;#40;rand-int 4&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;ClojureScript version has a lot less syntactic noise, and I find this has direct impact on my ability to reason about the code. The more quirks there are, the more likely I am to misread the intent. Noisy syntax results in situations where code looks like it's doing one thing, while it's actually doing something subtly different.&lt;/p&gt;&lt;p&gt;Another advantage is that ClojureScript is backed by immutable data structures by default. My experience is that immutability is crucial for writing large maintainable projects, as it allows safely reasoning about parts of the code in isolation.&lt;/p&gt;&lt;p&gt;Since immutability is pervasive as opposed to opt-in, it allows for tooling to be designed with it in mind. For example, &lt;a href='https://github.com/bhauman/lein-figwheel'&gt;Figwheel&lt;/a&gt; plugin relies on this property to provide live hot reloading in the browser.&lt;/p&gt;&lt;p&gt;Finally, ClojureScript compiler can do many optimizations, such as &lt;a href='http://swannodette.github.io/2015/01/06/the-false-promise-of-javascript-microlibs'&gt;dead code elimination&lt;/a&gt;, that are difficult to do with JavaScript. I highly recommend the &lt;a href='https://www.youtube.com/watch?v=cH4ZJAKZHjQ'&gt;Now What?&lt;/a&gt; talk by David Nolen that goes into more details regarding this.&lt;/p&gt;&lt;p&gt;Overall, I'm pleased to see that ClojureScript and Reagent perform so well when stacked up against native JavaScript libraries. It's hard to overstate the fact that a ClojureScript library built on top of React.js can outperform React.js itself.&lt;/p&gt;</description><pubDate>Sun, 26 Mar 2017 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-12-26-MacchiatoDebugging.html</guid><link>https://yogthos.net/posts/2016-12-26-MacchiatoDebugging.html</link><title>Using Chrome DevTools with Macchiato</title><description>&lt;p&gt;Chrome DevTools provide a lot of useful features for debugging and profiling applications in the browser. As it happens, you can to connect DevTools to a Node.js process as well. Let's take a look at debugging the &lt;a href='https://github.com/macchiato-framework/examples/tree/master/guestbook'&gt;guestbook project&lt;/a&gt; from the examples repository.&lt;/p&gt;&lt;p&gt;You'll first have to start Figwheel to compile the project by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein build
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the project is compiled, you have to start Node with the &lt;code&gt;--inspect&lt;/code&gt; flag:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;$ node --inspect target/out/guestbook.js

Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/bundled/inspector.html?experiments=true&amp;amp;v8only=true&amp;amp;ws=127.0.0.1:9229/0dbaef2a-996f-4229-8a52-6c4e50d0bf18
INFO &amp;#91;guestbook.core:19&amp;#93; - guestbook started on 127.0.0.1 : 3000
Figwheel: trying to open cljs reload socket
Figwheel: socket connection established
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You'll see that there's a URL printed in the console when the app starts. Copy this URL and open it in Chrome to connect DevTools to your Node process. At this point you can use all the tools the same way you would with an application running in the browser. You can debug ClojureScript files, profile the process, and so on.&lt;/p&gt;&lt;h4 id="gotchas"&gt;Gotchas&lt;/h4&gt;&lt;p&gt;Unfortunately, there's a &lt;a href='http://dev.clojure.org/jira/browse/CLJS-1864'&gt;small bug&lt;/a&gt; in the ClojureScript compiler that prevents timestamped source maps from working with Node. The problem is that that the compiler assumes that ClojureScript is running in browser and appends &lt;code&gt;?timestamp&lt;/code&gt; at the end of the file name as if it was a URL. Since Node is looking for actual files on disk, it fails to find the source map.&lt;/p&gt;&lt;p&gt;Currently, the workaround for this is to set &lt;code&gt;:source-map-timestamp false&lt;/code&gt; in the compiler options. However, since Node caches the source maps, you have to restart the process any time you make a change in the code to get accurate line numbers.&lt;/p&gt;&lt;p&gt;The good news is that restarts happen instantaneously, and you can automate this process using Node supervisor as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;npm install supervisor -g
supervisor --inspect target/out/guestbook.js
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's all there is to it.&lt;/p&gt;</description><pubDate>Mon, 26 Dec 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-12-20-MacchiatoModules.html</guid><link>https://yogthos.net/posts/2016-12-20-MacchiatoModules.html</link><title>Macchiato Modules</title><description> &lt;p&gt;As I discussed in the last &lt;a href='http://yogthos.net/posts/2016-12-17-MacchiatoProgress.html'&gt;post&lt;/a&gt;, Ring middleware stack closely resembles modules in a framework. However, one notable difference is that middleware functions aren't directly aware of one another. When the handler is passed to a middleware function, that function has no way of knowing what other middleware might have been wrapped around the handler by the time it got to it.&lt;/p&gt;&lt;p&gt;Conversely, these functions can't know what middleware will be wrapped after that they may depend on. Since middleware that was wrapped last will be invoked first, inner middleware ends up being dependent on the outer middleware.&lt;/p&gt;&lt;p&gt;This presents a number of problems. We can end up with multiple copies of the same middleware wrapped around the handler, middleware could be wrapped in the wrong order, or required middleware might be missing altogether. All of the above cases can lead to unpredictable behaviors, and can be difficult to debug.&lt;/p&gt;&lt;p&gt;One way to mitigate the problem is by creating a default middleware stack, such as seen in the &lt;a href='https://github.com/ring-clojure/ring-defaults'&gt;ring-defaults&lt;/a&gt; library. This takes care of ensuring that all the core middleware is wrapped correctly, but doesn't help with middleware libraries added by the user. Another approach is to wrap the Ring stack in a higher level abstraction as seen with &lt;a href='https://github.com/weavejester/integrant'&gt;Integrant&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The solution I came up with for Macchiato is to use metadata attached to the handler to track the middleware that's been applied to it. This metadata can be used to inform how the middleware is loaded, and address the problems outlined above.&lt;/p&gt;&lt;p&gt;Let's take a look at an example of how this works in practice. Let's say we have the default handler such as:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn handler &amp;#91;req res raise&amp;#93;
  &amp;#40;res {:body &amp;#40;str &amp;#40;-&amp;gt; req :params :name&amp;#41;&amp;#41;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then, let's say we have two pieces of middleware we wish to wrap the handler with. The first will parse the request params, and the second will keywordize the params. The second middleware function depends on the first in order to work.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn parse-params &amp;#91;req&amp;#93;
  ;;parses request parameters into a map
  &amp;#41;

&amp;#40;defn wrap-params &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req res raise&amp;#93;
    &amp;#40;handler &amp;#40;parse-params req&amp;#41; res raise&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn keywordize-params &amp;#91;params&amp;#93;
  ;;keywordizes the params
  &amp;#41;
          
&amp;#40;defn wrap-keyword-params &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req res raise&amp;#93;
    &amp;#40;handler &amp;#40;update req :params keywordize-params&amp;#41; res raise&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We have to make sure that the middleware is chained as follows to get keywordized params:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def wrapped-handler &amp;#40;-&amp;gt; handler
                         wrap-keyword-params
                         wrap-params&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, it's not possible to deduce that this actually happened given the resulting handler function. Let's see how we can use metadata to address this problem. We'll update the &lt;code&gt;wrap-params&lt;/code&gt; and the &lt;code&gt;wrap-keyword-params&lt;/code&gt; functions as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn
  &amp;#94;{:macchiato/middleware
    {:id :wrap-params}}    
  wrap-params &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req res raise&amp;#93;
    &amp;#40;handler &amp;#40;parse-params req&amp;#41; res raise&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn
 &amp;#94;{:macchiato/middleware
   {:id :wrap-keyword-params
    :required &amp;#91;:wrap-params&amp;#93;}}
  wrap-keyword-params &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req res raise&amp;#93;
    &amp;#40;handler &amp;#40;update req :params keywordize-params&amp;#41; res raise&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;:id&lt;/code&gt; key in the metadata is meant to specify the specific type of middleware as opposed to a concrete implementation. If two pieces of middleware happen to implement the same functionality they should use the same &lt;code&gt;:id&lt;/code&gt;. &lt;/p&gt;&lt;p&gt;The &lt;code&gt;:required&lt;/code&gt; key specifies the keys for the &lt;code&gt;:id&lt;/code&gt;s that the particular middleware function depends on. In this case, &lt;code&gt;wrap-keyword-params&lt;/code&gt; requires &lt;code&gt;wrap-params&lt;/code&gt; to be present.&lt;/p&gt;&lt;p&gt;Next, we can write the code that will update the handler metadata each time it's wrapped with a middleware function.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn update-middleware-meta &amp;#91;handler handler-middleware middleware-meta&amp;#93;
  &amp;#40;with-meta
    handler
    {:macchiato/middleware
     &amp;#40;conj handler-middleware middleware-meta&amp;#41;}&amp;#41;&amp;#41;

&amp;#40;defn loaded? &amp;#91;middleware {:keys &amp;#91;id&amp;#93;}&amp;#93;
  &amp;#40;some #{id} &amp;#40;map :id middleware&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn- middleware-from-handler &amp;#91;handler&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; handler meta :macchiato/middleware &amp;#40;remove nil?&amp;#41; vec&amp;#41;&amp;#41;

&amp;#40;defn wrap
  &amp;#40;&amp;#91;handler middleware-fn&amp;#93;
   &amp;#40;wrap handler middleware-fn nil&amp;#41;&amp;#41;
  &amp;#40;&amp;#91;handler middleware-fn opts&amp;#93;
   &amp;#40;let &amp;#91;handler-middleware &amp;#40;middleware-from-handler handler&amp;#41;
         middleware-meta    &amp;#40;-&amp;gt; middleware-fn meta :macchiato/middleware&amp;#41;&amp;#93;
     &amp;#40;if &amp;#40;loaded? handler-middleware middleware-meta&amp;#41;
       handler
       &amp;#40;update-middleware-meta
         &amp;#40;if opts
           &amp;#40;middleware-fn handler opts&amp;#41;
           &amp;#40;middleware-fn handler&amp;#41;&amp;#41;
         handler-middleware
         middleware-meta&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;wrap&lt;/code&gt; function uses the &lt;code&gt;:macchiato/middleware&lt;/code&gt; metadata key to get the currently applied middleware. When a middleware function with the same &lt;code&gt;:id&lt;/code&gt; is already present, then the original handler is returned. Otherwise, the handler is wrapped with the middleware and its metadata is updated.&lt;/p&gt;&lt;p&gt;Let's update the original code that wrapped the handler to use the &lt;code&gt;wrap&lt;/code&gt; function:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def wrapped-handler &amp;#40;-&amp;gt; handler
                         &amp;#40;wrap #'wrap-keyword-params&amp;#41;
                         &amp;#40;wrap #'wrap-params&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now use the &lt;code&gt;meta&lt;/code&gt; function to access the metadata that was generated for the handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;meta wrapped-handler&amp;#41;

{:macchiato/middleware
 &amp;#91;{:id :wrap-params}
  {:id :wrap-keyword-params
   :required &amp;#91;:wrap-params&amp;#93;}&amp;#93;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This tells us exactly what middleware has been applied to the handler and in what order, allowing us to validate that the middleware chain. This is accomplished as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn validate &amp;#91;handler-middleware
   {:keys &amp;#91;id required&amp;#93; :as middleware-meta}&amp;#93;
  &amp;#40;when &amp;#40;not-empty &amp;#40;difference &amp;#40;set required&amp;#41;
                               &amp;#40;set &amp;#40;map :id handler-middleware&amp;#41;&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;throw &amp;#40;js/Error. &amp;#40;str id &amp;quot; is missing required middleware: &amp;quot; required&amp;#41;&amp;#41;&amp;#41;&amp;#41;
  middleware-meta&amp;#41;
  
&amp;#40;defn validate-handler &amp;#91;handler&amp;#93;
  &amp;#40;let &amp;#91;middleware &amp;#40;middleware-from-handler handler&amp;#41;&amp;#93;
    &amp;#40;loop &amp;#91;&amp;#91;middleware-meta &amp;amp; handler-middleware&amp;#93; middleware&amp;#93;
      &amp;#40;when middleware-meta
        &amp;#40;validate handler-middleware middleware-meta&amp;#41;
        &amp;#40;recur handler-middleware&amp;#41;&amp;#41;&amp;#41;
    handler&amp;#41;&amp;#41;  
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With the above code in place we're now able to ensure that middleware functions are not loaded more than once, and that the order of middleware is correct.&lt;/p&gt;&lt;p&gt;Finally, Macchiato provides the &lt;code&gt;macchiato.middleware/wrap-middleware&lt;/code&gt; convenience function that allows wrapping multiple middleware functions around the handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;m/wrap-middleware
  handler
  #'wrap-anti-forgery
  &amp;#91;#'wrap-session {:store &amp;#40;mem/memory-store&amp;#41;}&amp;#93;
  #'wrap-nested-params
  #'wrap-keyword-params
  #'wrap-params&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I think that the approach of using metadata provides an elegant view into the state of the middleware chain, while allowing Macchiato to stay compliant with Ring middleware semantics.&lt;/p&gt;&lt;p&gt;Another advantage of using metadata is that it makes the mechanism user extensible. If you're using a piece of middleware that doesn't have the metadata you need, you can always set it yourself.&lt;/p&gt;&lt;p&gt;The latest release of Macchiato has all the core middleware tagged with the appropriate metadata, and &lt;a href='https://github.com/macchiato-framework/macchiato-defaults'&gt;macchiato-defaults&lt;/a&gt; generates a handler that has the &lt;code&gt;:macchiato/middleware&lt;/code&gt; key pointing to the vector of the middleware that was applied.&lt;/p&gt;</description><pubDate>Tue, 20 Dec 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-12-17-MacchiatoProgress.html</guid><link>https://yogthos.net/posts/2016-12-17-MacchiatoProgress.html</link><title>Frameworks, Foundations, and Macchiato</title><description>&lt;p&gt;I've been making steady progress on Macchiato in the past weeks. This post will discuss some of my thought process and design decisions I settled on during this time.&lt;/p&gt;&lt;p&gt;One of the core questions is what problem the project aims to solve, and how it aims to do that.&lt;/p&gt;&lt;p&gt;The goal for Macchiato is to provide a way to build Node web applications using CojureScript. Ultimately, I'd like to produce something that's immediately usable and works well out of the box. The best way to accomplish that is to leverage the existing work in this domain.&lt;/p&gt;&lt;p&gt;The Ring stack is the most popular platform for developing Clojure applications on the JVM, and rightfully so in my opinion. It does an excellent job of abstracting the HTTP protocol, and provides a simple and intuitive API to the user.&lt;/p&gt;&lt;p&gt;Ring added async handler support in version 1.6, making it possible to implement compatible HTTP handlers on top of Node. This in turn allowed to port the core middleware stack to Macchiato.&lt;/p&gt;&lt;p&gt;As I was porting &lt;a href='https://github.com/ring-clojure/ring/tree/master/ring-core/'&gt;ring-core&lt;/a&gt; on Node, I've come to realize that Ring middleware libraries have a lot in common with framework modules.&lt;/p&gt;&lt;p&gt;These libraries are meant to be used together in a standard way, they're designed to compose, and they're often built on top of each other.&lt;/p&gt;&lt;p&gt;However, the Ring stack acts as a foundation rather than a framework. To understand this idea, let's first look at the traditional framework approach.&lt;/p&gt;&lt;h3 id="frameworks"&gt;Frameworks&lt;/h3&gt;&lt;p&gt;The core problem the frameworks attempt to solve is to provide a standard way to build software where the user can focus on writing the code that's relevant to their application. Meanwhile, the framework attempts to take care of all the incidental details around it.&lt;/p&gt;&lt;p&gt;The way traditional frameworks, such as Spring, accomplish this is through inversion of control. However, since the connections are no longer expressed directly in code, it makes it difficult to navigate them clouding the logic of the application.&lt;/p&gt;&lt;p&gt;Another problem with this approach is that the framework necessarily has to make a lot of decisions up front. Yet, a general purpose framework also has to be flexible enough to accommodate many types of application.&lt;/p&gt;&lt;p&gt;A framework typically turns into an exercise in designing a solution without knowing the problem. My experience is that it's not an effective way to write software in practice.&lt;/p&gt;&lt;p&gt;However, I think that the problem the frameworks attempt to solve is real. Having to artisanally handcraft each application from ground up is tedious and error prone.&lt;/p&gt;&lt;h3 id="foundations"&gt;Foundations&lt;/h3&gt;&lt;p&gt;A better way to approach this problem is by addressing the known common needs. The key insight of Ring is that majority of reusable work is centred around processing the incoming HTTP requests and outgoing responses.&lt;/p&gt;&lt;p&gt;Ring provides a simple core that different middleware can be attached to in order to extend its functionality. We can add middleware that facilitates authentication, sessions, and so on. &lt;a href='https://github.com/funcool/buddy'&gt;Buddy&lt;/a&gt;, &lt;a href='https://github.com/metosin/compojure-api'&gt;compojure-api&lt;/a&gt;, and &lt;a href='https://github.com/ptaoussanis/sente'&gt;Sente&lt;/a&gt; are all great examples of this approach in practice.&lt;/p&gt;&lt;p&gt;One of the downsides of the library approach is that libraries aren't aware of one another, and the user has to glue them together. However, Ring middleware stack is not just a set of random libraries. Since Ring defines what the request and response must look like, it informs the design of libraries built on top of it. &lt;/p&gt;&lt;p&gt;The Ring stack is a mature and battle tested foundation for building the rest of the application on top of. At the same time, it doesn't attempt to guess the problems that are specific to your application. You're free to solve them in a way that makes sense to you.&lt;/p&gt;&lt;h3 id="macchiato"&gt;Macchiato&lt;/h3&gt;&lt;p&gt;Macchiato implements Ring 1.6 async handlers on top of the &lt;code&gt;ClientRequest&lt;/code&gt; and the &lt;code&gt;ServerResponse&lt;/code&gt; classes exposed by the Node HTTP module. Using the same API provides a consistent experience developing web applications on both platforms, and facilitates code reuse between them.&lt;/p&gt;&lt;p&gt;One immediate benefit of making Macchiato compatible with Ring was the ability to leverage its test harness. As I port the middleware to Node, I'm able to verify that it still behaves the same as the original. Going forward, it will be possible to write cljc middleware that targets both Ring and Macchiato.&lt;/p&gt;&lt;p&gt;Alongside the creation of the core libraries, I've been working on the template that packages everything together for the user. This template is informed by my experience working on Luminus and uses many of the same patterns and structure. If you're already familiar with Luminus, then you'll feel right at home with Macchiato.&lt;/p&gt;&lt;p&gt;As I noted in the last &lt;a href='http://yogthos.net/posts/2016-11-30-Macchiato.html'&gt;post&lt;/a&gt;, Macchiato development experience is very similar to working with Clojure on the JVM, and Chrome devtools along with &lt;a href='https://github.com/binaryage/dirac'&gt;Dirac&lt;/a&gt; look promising for debugging and profiling apps.&lt;/p&gt;&lt;p&gt;Meanwhile, the project has already garnered interest from the community. &lt;a href='https://numergent.com/opensource/'&gt;Ricardo J. Méndez&lt;/a&gt; has been working on creating a &lt;a href='https://github.com/macchiato-framework/macchiato-sql'&gt;HugSQL style database access library&lt;/a&gt;, and &lt;a href='https://github.com/niwinz'&gt;Andrey Antukh&lt;/a&gt;, has been working on the &lt;a href='https://github.com/funcool/dost'&gt;dost&lt;/a&gt; crypto library.&lt;/p&gt;&lt;p&gt;It's great to see such prominent members of the community take interest in the project in the early stages. My hope is that as Macchiato matures we'll see many more supporting libraries built around it.&lt;/p&gt;&lt;p&gt;There's now a &lt;code&gt;#macchiato&lt;/code&gt; channel on Clojurians slack. Feel free to drop by and discuss problems and ideas.&lt;/p&gt;&lt;p&gt;If you're looking to contribute to an open source project, Macchiato is a great opportunity. The project is still in the early days and there are many low hanging fruit. The project needs more tests, libraries, and documentation. This is a great time to make an impact on its future direction.&lt;/p&gt;</description><pubDate>Sat, 17 Dec 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-11-30-Macchiato.html</guid><link>https://yogthos.net/posts/2016-11-30-Macchiato.html</link><title>Macchiato: ClojureScript Arrives on the Server</title><description> &lt;p&gt; I recently started the &lt;a href='https://github.com/macchiato-framework'&gt;Macchiato&lt;/a&gt; project to provide a platform for building ClojureScript based apps on top Node.js.   &lt;/p&gt;&lt;p&gt;First, let's look at some of the reasons for running ClojureScript on the server. The JVM is an excellent platform, it's mature, performant, and has a large ecosystem around it. This makes it a solid choice for a wide range of applications.&lt;/p&gt;&lt;p&gt;However, there are situations where the JVM might not be a good fit. It's a complex piece of technology that requires experience to use effectively. It has a fairly large footprint even from small applications. The startup times can be problematic, especially when it comes to loading Clojure runtime.&lt;/p&gt;&lt;p&gt;Meanwhile, Node.js also happens to be a popular platform with a large ecosystem around it. It requires far less resources for certain types of applications, has very fast startup times, and its ecosystem is familiar to many JavaScript developers.&lt;/p&gt;&lt;p&gt;Another appeal for Node based servers comes from building full stack ClojureScript single-page applications, since using Node on the server facilitates server-side rendering for any React based libraries.&lt;/p&gt;&lt;p&gt;While there are a few existing experiments using ClojureScript on Node, such as &lt;a href='https://github.com/whamtet/dogfort'&gt;Dog Fort&lt;/a&gt;, none of these appear to be actively maintained. Since ClojureScript and its ecosystem have evolved in the meantime, I wanted to create a fresh stack using the latest tools and best practices.&lt;/p&gt;&lt;h3 id="overview"&gt;Overview&lt;/h3&gt;&lt;p&gt;My goal for Macchiato is to provide a stack modeled on Ring based around the existing Node ecosystem, and a development environment similar to what's available for Clojure on the JVM.&lt;/p&gt;&lt;h4 id="the&amp;#95;stack"&gt;The Stack&lt;/h4&gt;&lt;p&gt;I think it makes sense to embrace the Node ecosystem and leverage the existing modules whenever possible. For example, Ring style cookies map directly to the &lt;a href='https://www.npmjs.com/package/cookies'&gt;cookies&lt;/a&gt; NPM module. Conversely, there are a number of excellent ClojureScript libraries available as well, such as &lt;a href='https://github.com/ptaoussanis/timbre'&gt;Timbre&lt;/a&gt;,  &lt;a href='https://github.com/juxt/bidi/'&gt;Bidi&lt;/a&gt;, and &lt;a href='https://github.com/tolitius/mount'&gt;Mount&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I used a Ring inspired model where I created &lt;a href='https://github.com/macchiato-framework/macchiato-core/blob/master/src/macchiato/http.cljs'&gt;wrappers around Node HTTP request and response objects&lt;/a&gt;. This allowed adapting parts of Ring, such as its session store implementation, with minimal changes.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;ClientRequest&lt;/code&gt; object is translated to a Clojure map, and the response map is written to the &lt;code&gt;ServerResponse&lt;/code&gt; object. The request handler is implemented as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defprotocol IHTTPResponseWriter
  &amp;#40;-write-response &amp;#91;data res&amp;#93; &amp;quot;Write data to a http.ServerResponse&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn response &amp;#91;req res opts&amp;#93;
  &amp;#40;fn &amp;#91;{:keys &amp;#91;cookies headers body status&amp;#93;}&amp;#93;
    &amp;#40;cookies/set-cookies cookies req res &amp;#40;:cookies opts&amp;#41;&amp;#41;
    &amp;#40;.writeHead res status &amp;#40;clj-&amp;gt;js headers&amp;#41;&amp;#41;
    &amp;#40;when &amp;#40;-write-response body res&amp;#41;
      &amp;#40;.end res&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn handler &amp;#91;handler-fn &amp;amp; &amp;#91;opts&amp;#93;&amp;#93;
  &amp;#40;let &amp;#91;opts &amp;#40;or opts {}&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;req res&amp;#93;
      &amp;#40;handler-fn &amp;#40;req-&amp;gt;map req res opts&amp;#41; &amp;#40;response req res opts&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;handler&lt;/code&gt; accepts a &lt;code&gt;handler-fn&lt;/code&gt; function that's passed the request map produced by the &lt;code&gt;req-&amp;gt;map&lt;/code&gt; helper. The &lt;code&gt;handler-fn&lt;/code&gt; is expected to return a request handler function that will be used to generate the response. This function should accept the request map and the &lt;code&gt;response&lt;/code&gt; call back function that writes the response map to the &lt;code&gt;ServerResponse&lt;/code&gt; object. The &lt;code&gt;IHTTPResponseWriter&lt;/code&gt; protocol is used to serialize different kinds of responses.&lt;/p&gt;&lt;h4 id="concurrent&amp;#95;request&amp;#95;handling"&gt;Concurrent Request Handling&lt;/h4&gt;&lt;p&gt;JVM servers commonly use a listener thread for accepting client requests, the connections are then passed on to a thread pool of request handlers. This allows the listener to continue accepting connections while the requests are being processed.&lt;/p&gt;&lt;p&gt;Since Node is single threaded, long running request handlers block the server until they finish. While async operations can be used to handle IO in the background, any business logic will end up preventing the server from accepting new connections while it's running.&lt;/p&gt;&lt;p&gt;One way around this is to use the cluster module that spins up a single listening process that forks child processes and dispatches the requests to them. Setting this up is pretty straight forward: &lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defstate env :start &amp;#40;config/env&amp;#41;&amp;#41;

&amp;#40;defstate http :start &amp;#40;js/require &amp;quot;http&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn app &amp;#91;&amp;#93;
  &amp;#40;mount/start&amp;#41;
  &amp;#40;let &amp;#91;host &amp;#40;or &amp;#40;:host env&amp;#41; &amp;quot;127.0.0.1&amp;quot;&amp;#41;
        port &amp;#40;or &amp;#40;some-&amp;gt; env :port js/parseInt&amp;#41; 3000&amp;#41;&amp;#93;
    &amp;#40;-&amp;gt; @http
        &amp;#40;.createServer
          &amp;#40;handler
            router
            {:cookies {:signed? true}
             :session {:store &amp;#40;mem/memory-store&amp;#41;}}&amp;#41;&amp;#41;
        &amp;#40;.listen port host #&amp;#40;info &amp;quot;{{name}} started on&amp;quot; host &amp;quot;:&amp;quot; port&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn start-workers &amp;#91;os cluster&amp;#93;
  &amp;#40;dotimes &amp;#91;&amp;#95; &amp;#40;-&amp;gt; os .cpus .-length&amp;#41;&amp;#93;
    &amp;#40;.fork cluster&amp;#41;&amp;#41;
  &amp;#40;.on cluster &amp;quot;exit&amp;quot;
       &amp;#40;fn &amp;#91;worker code signal&amp;#93;
         &amp;#40;info &amp;quot;worker terminated&amp;quot; &amp;#40;-&amp;gt; worker .-process .-pid&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn main &amp;#91;&amp;amp; args&amp;#93;
  &amp;#40;let &amp;#91;os      &amp;#40;js/require &amp;quot;os&amp;quot;&amp;#41;
        cluster &amp;#40;js/require &amp;quot;cluster&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;if &amp;#40;.-isMaster cluster&amp;#41;
      &amp;#40;start-workers os cluster&amp;#41;
      &amp;#40;app&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, it's worth noting that unlike threads, processes don't share memory. So, each child that gets spun up will require its own copy of the memory space.&lt;/p&gt;&lt;h4 id="the&amp;#95;template"&gt;The Template&lt;/h4&gt;&lt;p&gt;I setup a &lt;a href='https://github.com/macchiato-framework/macchiato-template'&gt;template&lt;/a&gt; that creates a minimal app with some reasonable defaults. This template is published to Clojars, and you can try it out yourself by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new macchiato myapp
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The template is setup similarly to Luminus. The source code for the project is found in the &lt;code&gt;src&lt;/code&gt; folder, and the &lt;code&gt;env&lt;/code&gt; folder contains code that's specific for dev and prod environments.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;project.clj&lt;/code&gt; contains &lt;code&gt;dev&lt;/code&gt; and &lt;code&gt;release&lt;/code&gt; profiles for working with the app in development mode and packaging it for production use. The app can be started in development mode by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein build
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will clean the project, download NPM modules, and start the Figwheel compiler. Once Figwheel compiles the sources, you can run the app with Node in another terminal as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;node target/out/myapp.js
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The app should now be available at &lt;code&gt;http://localhost:3000&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Figwheel also starts the nREPL at &lt;code&gt;localhost:7000&lt;/code&gt;. You can connect to it from the editor and run &lt;code&gt;&amp;#40;cljs&amp;#41;&lt;/code&gt; to load the ClojureScript REPL.&lt;/p&gt;&lt;p&gt;Packaging the app for production is accomplished by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein package
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will print out &lt;code&gt;package.json&lt;/code&gt; for the app and generate the release artifact called &lt;code&gt;target/release/myapp.js&lt;/code&gt;.&lt;/p&gt;&lt;h3 id="looking&amp;#95;forward"&gt;Looking Forward&lt;/h3&gt;&lt;p&gt;Overall, I think that ClojureScript on top of Node is ready for prime time. It opens up server-side Clojure development to a large community of JavaScript developers, and extends the reach of Clojure to any platform that supports Node.&lt;/p&gt;&lt;p&gt;While the initial results are very promising, there is still much work to be done in order to provide a solid stack such as Luminus. If you think this project is interesting, feel free to ping me via email or on the Clojurians slack. I would love to collaborate on making Macchiato into a solid choice for developing Node based applications.&lt;/p&gt;</description><pubDate>Wed, 30 Nov 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-11-05-LuminusPostgresNotifications.html</guid><link>https://yogthos.net/posts/2016-11-05-LuminusPostgresNotifications.html</link><title>PostgreSQL Async Notifications in Luminus</title><description>&lt;p&gt;There are many situations where the application needs to react to changes in the data. The simplest way to handle this requirement is to keep state in the server session. Unfortunately, this makes it difficult to scale applications horizontally, and can incur additional memory requirements.&lt;/p&gt;&lt;p&gt;A common solution to this problem is to use an external queue service that each instance of the application subscribes to. However, this adds a new component to the architecture that needs to be maintained.&lt;/p&gt;&lt;p&gt;A less known option is to use Postgres &lt;a href='https://www.postgresql.org/docs/9.5/static/sql-notify.html'&gt;NOTIFY&lt;/a&gt; command to send push notifications from the database. This allows multiple instances of the application can subscribe directly to the database to listen for events.&lt;/p&gt;&lt;p&gt;This post will walk you through configuring a Luminus app to listen for Postgres notification, and broadcast them to the connected clients over a WebSocket.&lt;/p&gt;&lt;p&gt;&lt;em&gt;prerequisites:&lt;/em&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='http://www.azul.com/downloads/zulu/'&gt;JDK&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='http://leiningen.org/'&gt;Leiningen&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://www.postgresql.org/'&gt;PostgreSQL&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Let's start by creating a new project for our app:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus pg-feed-demo +postgres +re-frame
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="the&amp;#95;database"&gt;The database&lt;/h3&gt;&lt;p&gt;The first step is to create a schema for the app, and set the connection URL in the &lt;code&gt;profiles.clj&lt;/code&gt;, e.g:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:profiles/dev
 {:env
  {:database-url
   &amp;quot;jdbc:pgsql://localhost:5432/feeds&amp;#95;dev?user=feeds&amp;amp;password=feeds&amp;quot;}}
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="migrations"&gt;Migrations&lt;/h4&gt;&lt;p&gt;Once the schema is ready, we can write a migrations script that creates a table called &lt;code&gt;events&lt;/code&gt;, and sets up a notification trigger on it. Let's run the following command in the project root folder to create the migration files:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein migratus create events-table
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, add the following script as the &lt;code&gt;up&lt;/code&gt; migration:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;CREATE TABLE events
&amp;#40;id SERIAL PRIMARY KEY,
 event TEXT&amp;#41;;
--;;
CREATE FUNCTION notify&amp;#95;trigger&amp;#40;&amp;#41; RETURNS trigger AS $$
DECLARE
BEGIN
 -- TG&amp;#95;TABLE&amp;#95;NAME - name of the table that was triggered
 -- TG&amp;#95;OP - name of the trigger operation
 -- NEW - the new value in the row
 IF TG&amp;#95;OP = 'INSERT' or TG&amp;#95;OP = 'UPDATE' THEN
   execute 'NOTIFY '
   || TG&amp;#95;TABLE&amp;#95;NAME
   || ', '''
   || TG&amp;#95;OP
   || ' '
   || NEW
   || '''';
 ELSE
   execute 'NOTIFY '
   || TG&amp;#95;TABLE&amp;#95;NAME
   || ', '''
   || TG&amp;#95;OP
   || '''';
 END IF;
 return new;
END;
$$ LANGUAGE plpgsql;
--;;
CREATE TRIGGER event&amp;#95;trigger
AFTER INSERT or UPDATE or DELETE ON events
FOR EACH ROW EXECUTE PROCEDURE notify&amp;#95;trigger&amp;#40;&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The&lt;code&gt;notify&amp;#95;trigger&lt;/code&gt; function will broadcast a notification with the table name, the operation, and the parameters when available. The &lt;code&gt;event&amp;#95;trigger&lt;/code&gt; will run it whenever &lt;code&gt;insert&lt;/code&gt;, &lt;code&gt;update&lt;/code&gt;, or &lt;code&gt;delete&lt;/code&gt; operations are performed on the &lt;code&gt;messages&lt;/code&gt; table.&lt;/p&gt;&lt;p&gt;We'll also add the &lt;code&gt;down&lt;/code&gt; migration for posterity:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;DROP FUNCTION notify&amp;#95;trigger&amp;#40;&amp;#41; CASCADE;
DROP TABLE events;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now run migrations as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein run migrate
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="queries"&gt;Queries&lt;/h4&gt;&lt;p&gt;Let's open the &lt;code&gt;resources/sql/queries.sql&lt;/code&gt; file and replace the default queries with the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- :name event! :! :n
-- :doc insert a new event
INSERT INTO events &amp;#40;event&amp;#41; VALUES &amp;#40;:event&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="the&amp;#95;server"&gt;The server&lt;/h3&gt;&lt;p&gt;Unfortunately, the official Postgres JDBC driver cannot receive asynchronous notifications, and uses polling to check if any notifications were issued. Instead, we'll use the &lt;a href='http://impossibl.github.io/pgjdbc-ng/'&gt;pgjdbc-ng&lt;/a&gt; driver that provides support for many Postgres specific features, including async notifications. Let's update our app to use this driver instead by swapping the dependency in &lt;code&gt;project.clj&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;;&amp;#91;org.postgresql/postgresql &amp;quot;9.4.1211&amp;quot;&amp;#93;
&amp;#91;com.impossibl.pgjdbc-ng/pgjdbc-ng &amp;quot;0.6&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;                        &lt;br /&gt;&lt;h4 id="notification&amp;#95;listener"&gt;Notification listener&lt;/h4&gt;&lt;p&gt;Let's open up the &lt;code&gt;pg-feed-demo.db.core&lt;/code&gt; namespace and update it to fit our purposes. Since we're no longer using the official Postgres driver, we'll need to update the namespace declaration to remove any references to it. We'll also add the import for the &lt;code&gt;PGNotificationListener&lt;/code&gt; class that will be used to add listeners to the connection. To keep things simple, we'll also remove any protocol extensions declared there. The resulting namespace should look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns pg-feed-demo.db.core
  &amp;#40;:require
    &amp;#91;cheshire.core :refer &amp;#91;generate-string parse-string&amp;#93;&amp;#93;
    &amp;#91;clojure.java.jdbc :as jdbc&amp;#93;
    &amp;#91;conman.core :as conman&amp;#93;
    &amp;#91;pg-feed-demo.config :refer &amp;#91;env&amp;#93;&amp;#93;
    &amp;#91;mount.core :refer &amp;#91;defstate&amp;#93;&amp;#93;&amp;#41;
  &amp;#40;:import
    com.impossibl.postgres.api.jdbc.PGNotificationListener&amp;#41;&amp;#41;

&amp;#40;defstate &amp;#94;:dynamic &amp;#42;db&amp;#42;
  :start &amp;#40;conman/connect! {:jdbc-url &amp;#40;env :database-url&amp;#41;}&amp;#41;
  :stop &amp;#40;conman/disconnect! &amp;#42;db&amp;#42;&amp;#41;&amp;#41;

&amp;#40;conman/bind-connection &amp;#42;db&amp;#42; &amp;quot;sql/queries.sql&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In order to add a notification listener, we first have to create a connection. Let's create a &lt;a href='https://github.com/tolitius/mount'&gt;Mount&lt;/a&gt; &lt;code&gt;defstate&lt;/code&gt; called &lt;code&gt;notifications-connection&lt;/code&gt; to hold it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defstate notifications-connection
  :start &amp;#40;jdbc/get-connection {:connection-uri &amp;#40;env :database-url&amp;#41;}&amp;#41;
  :stop &amp;#40;.close notifications-connection&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll add functions that will allow us to add and remove listeners for a given connection:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn add-listener &amp;#91;conn id listener-fn&amp;#93;
  &amp;#40;let &amp;#91;listener &amp;#40;proxy &amp;#91;PGNotificationListener&amp;#93; &amp;#91;&amp;#93;
                   &amp;#40;notification &amp;#91;chan-id channel message&amp;#93;
                     &amp;#40;listener-fn chan-id channel message&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;.addNotificationListener conn listener&amp;#41;
    &amp;#40;jdbc/db-do-commands
      {:connection notifications-connection}
      &amp;#40;str &amp;quot;LISTEN &amp;quot; &amp;#40;name id&amp;#41;&amp;#41;&amp;#41;
    listener&amp;#41;&amp;#41;

&amp;#40;defn remove-listener &amp;#91;conn listener&amp;#93;
  &amp;#40;.removeNotificationListener conn listener&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's start the application by running &lt;code&gt;lein run&lt;/code&gt; in the terminal. Once it starts, the nREPL will become available at &lt;code&gt;localhost:7000&lt;/code&gt;. When the REPL is connected, run the following code in it to start the database connection and register a listener:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;require :reload 'pg-feed-demo.db.core&amp;#41;
&amp;#40;in-ns 'pg-feed-demo.db.core&amp;#41;

&amp;#40;mount.core/start
  #'&amp;#42;db&amp;#42;
  #'notifications-connection&amp;#41;
                  
&amp;#40;add-listener
  notifications-connection
  &amp;quot;events&amp;quot;
  &amp;#40;fn &amp;#91;&amp;amp; args&amp;#93;
    &amp;#40;apply println &amp;quot;got message:&amp;quot; args&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now test that adding a new message produces the notification:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;event! {:event &amp;quot;hello world&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One the function runs, we should see something like the following printed in the terminal as the message is added to the database:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;got message: 32427 messages INSERT &amp;#40;0,&amp;quot;hello world&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="websocket&amp;#95;connection"&gt;WebSocket connection&lt;/h4&gt;&lt;p&gt;We're now ready to setup the WebSocket connection that will be used to push notifications to the clients. We'll update the &lt;code&gt;pg-feed-demo.routes.home&lt;/code&gt;namespace to look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns pg-feed-demo.routes.home
  &amp;#40;:require &amp;#91;pg-feed-demo.layout :as layout&amp;#93;
            &amp;#91;compojure.core :refer &amp;#91;defroutes GET&amp;#93;&amp;#93;
            &amp;#91;pg-feed-demo.db.core :as db&amp;#93;
            &amp;#91;mount.core :refer &amp;#91;defstate&amp;#93;&amp;#93;
            &amp;#91;immutant.web.async :as async&amp;#93;
            &amp;#91;clojure.tools.logging :as log&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defstate channels
  :start &amp;#40;atom #{}&amp;#41;&amp;#41;

&amp;#40;defstate &amp;#94;{:on-reload :noop} event-listener
  :start &amp;#40;db/add-listener
           db/notifications-connection
           :events
           &amp;#40;fn &amp;#91;&amp;#95; &amp;#95; message&amp;#93;
             &amp;#40;doseq &amp;#91;channel @channels&amp;#93;
               &amp;#40;async/send! channel message&amp;#41;&amp;#41;&amp;#41;&amp;#41;
  :stop &amp;#40;db/remove-listener
          db/notifications-connection
          event-listener&amp;#41;&amp;#41;

&amp;#40;defn persist-event! &amp;#91;&amp;#95; event&amp;#93;
  &amp;#40;db/event! {:event event}&amp;#41;&amp;#41;

&amp;#40;defn connect! &amp;#91;channel&amp;#93;
  &amp;#40;log/info &amp;quot;channel open&amp;quot;&amp;#41;
  &amp;#40;swap! channels conj channel&amp;#41;&amp;#41;

&amp;#40;defn disconnect! &amp;#91;channel {:keys &amp;#91;code reason&amp;#93;}&amp;#93;
  &amp;#40;log/info &amp;quot;close code:&amp;quot; code &amp;quot;reason:&amp;quot; reason&amp;#41;
  &amp;#40;swap! channels #&amp;#40;remove #{channel} %&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#40;layout/render &amp;quot;home.html&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defroutes home-routes
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93;
    &amp;#40;home-page&amp;#41;&amp;#41;
  &amp;#40;GET &amp;quot;/events&amp;quot; request
    &amp;#40;async/as-channel
      request
      {:on-open    connect!
       :on-close   disconnect!
       :on-message persist-event}&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;channels&lt;/code&gt; state will contain a set of all the channels for the currently connected clients.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;event-listener&lt;/code&gt; will create a new listener that's triggered when events are stored in the database. The handler function will broadcast each event to all the connected clients. Note that we need &lt;code&gt;&amp;#94;{:on-reload :noop}&lt;/code&gt; metadata on the listener to prevent it being registered multiple times in case the namespace is reloaded during development.&lt;/p&gt;&lt;p&gt;Whenever the server receives a message from a client, the message will be persisted to the database by the &lt;code&gt;persist-event!&lt;/code&gt; function.&lt;/p&gt;&lt;p&gt;Finally, we'll create the &lt;code&gt;/events&lt;/code&gt; route that will be used to manage WebSocket communication with the clients.&lt;/p&gt;&lt;h3 id="the&amp;#95;client"&gt;The client&lt;/h3&gt;&lt;p&gt;The client will need to track the currently available messages, allow the user to send new messages to the server, and update the available messages based on server WebSocket notifications.&lt;/p&gt;&lt;p&gt;Let's run Figwheel to start the ClojureScript compiler before we start working on the client-side code by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein figwheel
&lt;/code&gt;&lt;/pre&gt;Once Figwheel compiler starts, navigate to &lt;a href='http://localhost:3000'&gt;http://localhost:3000&lt;/a&gt; in the browser to load the client-side of the application.&lt;h4 id="re-frame&amp;#95;events"&gt;Re-frame events&lt;/h4&gt;&lt;p&gt;We'll start by adding a handler for adding messages in the &lt;code&gt;pg-feed-demo.handlers&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;reg-event-db
  :event
  &amp;#40;fn &amp;#91;db &amp;#91;&amp;#95; event&amp;#93;&amp;#93;
    &amp;#40;update db :events &amp;#40;fnil conj &amp;#91;&amp;#93;&amp;#41; event&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll add a corresponding subscription to see the current messages in the &lt;code&gt;pg-feed-demo.subscriptions&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;reg-sub
  :events
  &amp;#40;fn &amp;#91;db &amp;#95;&amp;#93;
    &amp;#40;:events db&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="websocket&amp;#95;connection"&gt;WebSocket connection&lt;/h4&gt;&lt;p&gt;We can now add a &lt;code&gt;pg-feed-demo.ws&lt;/code&gt; namespace to manage the client-side of the WebSocket connection:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns pg-feed-demo.ws&amp;#41;

&amp;#40;defonce ws-chan &amp;#40;atom nil&amp;#41;&amp;#41;

&amp;#40;defn send
  &amp;#91;message&amp;#93;
  &amp;#40;if @ws-chan
    &amp;#40;.send @ws-chan message&amp;#41;
    &amp;#40;throw &amp;#40;js/Error. &amp;quot;Websocket is not available!&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn connect-ws &amp;#91;url handler&amp;#93;
  &amp;#40;if-let &amp;#91;chan &amp;#40;js/WebSocket. url&amp;#41;&amp;#93;
    &amp;#40;do
      &amp;#40;set! &amp;#40;.-onmessage chan&amp;#41; #&amp;#40;-&amp;gt; % .-data handler&amp;#41;&amp;#41;
      &amp;#40;reset! ws-chan chan&amp;#41;&amp;#41;
    &amp;#40;throw &amp;#40;js/Error. &amp;quot;Websocket connection failed!&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="user&amp;#95;interface"&gt;User interface&lt;/h4&gt;&lt;p&gt;Finally, we'll update the &lt;code&gt;pg-feed-demo.core&lt;/code&gt; namespace to list incoming events and allow the user to generate an event. To do that, We'll update the namespace to look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns pg-feed-demo.core
  &amp;#40;:require &amp;#91;reagent.core :as r&amp;#93;
            &amp;#91;re-frame.core :as rf&amp;#93;
            &amp;#91;pg-feed-demo.handlers&amp;#93;
            &amp;#91;pg-feed-demo.subscriptions&amp;#93;
            &amp;#91;pg-feed-demo.ws :as ws&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;:div.container
   &amp;#91;:div.navbar&amp;#93;
   &amp;#91;:div.row&amp;gt;div.col-sm-12&amp;gt;div.card
    &amp;#91;:div.card-header&amp;gt;h4 &amp;quot;Events&amp;quot;&amp;#93;
    &amp;#91;:div.card-block&amp;gt;ul
     &amp;#40;for &amp;#91;event @&amp;#40;rf/subscribe &amp;#91;:events&amp;#93;&amp;#41;&amp;#93;
       &amp;#94;{:key event}
       &amp;#91;:li event&amp;#93;&amp;#41;&amp;#93;&amp;#93;
   &amp;#91;:hr&amp;#93;
   &amp;#91;:div.row&amp;gt;div.col-sm-12&amp;gt;span.btn-primary.input-group-addon
    {:on-click #&amp;#40;ws/send &amp;#40;str &amp;quot;user event &amp;quot; &amp;#40;js/Date.&amp;#41;&amp;#41;&amp;#41;}
    &amp;quot;generate event&amp;quot;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn mount-components &amp;#91;&amp;#93;
  &amp;#40;r/render &amp;#91;#'home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;rf/dispatch-sync &amp;#91;:initialize-db&amp;#93;&amp;#41;
  &amp;#40;ws/connect-ws
    &amp;#40;str &amp;quot;ws://&amp;quot; &amp;#40;.-host js/location&amp;#41; &amp;quot;/events&amp;quot;&amp;#41;
    #&amp;#40;rf/dispatch &amp;#91;:event %&amp;#93;&amp;#41;&amp;#41;
  &amp;#40;mount-components&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's all there is to it. We should now be able to send events to the server and see the notifications in the browser. We should also be able to generate events by running queries directly in the database, or in another instance of the application.&lt;/p&gt;&lt;p&gt;The complete source for the project is available &lt;a href='https://github.com/yogthos/pg-feed-demo'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 05 Nov 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-10-15-AtomWithLuminus.html</guid><link>https://yogthos.net/posts/2016-10-15-AtomWithLuminus.html</link><title>Configuring Atom for Luminus</title><description>&lt;p&gt;There are many editors and IDEs available for Clojure today. The most popular ones are Emacs with &lt;a href='https://github.com/clojure-emacs/cider'&gt;CIDER&lt;/a&gt; and IntelliJ with &lt;a href='https://cursive-ide.com/'&gt;Cursive&lt;/a&gt;. While both of these options provide excellent development environments, they also require a bit of learning to become productive in.&lt;/p&gt;&lt;p&gt;Good news is that you don't have to learn a complex environment to get started. This post will walk you through the steps of configuring &lt;a href='https://atom.io/'&gt;Atom editor&lt;/a&gt; editor to work with a &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; project. We'll see how to configure Atom for editing Clojure code and how to connect it to the remote REPL started by the Luminus app for interactive development.&lt;/p&gt;&lt;h3 id="prerequisites"&gt;Prerequisites&lt;/h3&gt;&lt;p&gt;You'll need the following installed to follow along with this post:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='http://www.azul.com/downloads/zulu/'&gt;OpenJDK&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='http://leiningen.org/'&gt;Leiningen&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://atom.io/'&gt;Atom&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="configuring&amp;#95;atom"&gt;Configuring Atom&lt;/h3&gt;&lt;p&gt;Let's take a look at the bare minimum Atom configuration for working with Clojure. Once you're up and running, you may with to look &lt;a href='https://gist.github.com/jasongilman/d1f70507bed021b48625'&gt;here&lt;/a&gt; for a more advanced configuration. We'll start by installing the following packages:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='https://atom.io/packages/parinfer'&gt;parinfer&lt;/a&gt; or &lt;a href='https://atom.io/packages/lisp-paredit'&gt;lisp-paredit&lt;/a&gt; package for structural editing&lt;/li&gt;&lt;li&gt;&lt;a href='https://atom.io/packages/proto-repl'&gt;proto-repl&lt;/a&gt; to connect to a Clojure REPL&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="structural&amp;#95;editing"&gt;Structural Editing&lt;/h3&gt;&lt;p&gt;A structural editor understands the structure of Clojure code and provides shortcuts for manipulating s-expressions instead of lines of text. It also eliminates the need to manually balance the parens. This takes a bit of getting used to, but it will make working with Clojure a lot more pleasant in the long run.&lt;/p&gt;&lt;h4 id="parinfer"&gt;Parinfer&lt;/h4&gt;&lt;p&gt;The &lt;code&gt;parinfer&lt;/code&gt; mode will attempt to automatically infer the necessary parens based on the indentation. This mode has a gentle learning curve and attempts to get our of your way as much as possible. You can read more about how it works &lt;a href='https://shaunlebron.github.io/parinfer/#introduction'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h4 id="paredit"&gt;Paredit&lt;/h4&gt;&lt;p&gt;The &lt;code&gt;paredit&lt;/code&gt; mode takes a bit more getting used to, but provides you with precise control over code structure. Whenever you add a peren, a matching closing paren will be inserted automatically. Paredit will also prevent you you from deleting parens unless you have an empty pair. &lt;/p&gt;&lt;p&gt;The package also provides a handy &lt;code&gt;ctrl-w&lt;/code&gt; shortcut that will extend the selection by s-expression. This is the recommended way to select code as you don't have to manually match the start and end of an expression when selecting.&lt;/p&gt;&lt;h3 id="the&amp;#95;repl"&gt;The REPL&lt;/h3&gt;&lt;p&gt;The REPL is an essential tool for working with Clojure. When integrated with the editor, it allows running any code that you write directly in the application.&lt;/p&gt;&lt;h4 id="connecting&amp;#95;the&amp;#95;repl"&gt;Connecting the REPL&lt;/h4&gt;&lt;p&gt;We'll create a new Luminus project with SQLite database support by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus myapp +sqlite&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the project is created, we can go to the project folder and run the migrations:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;cd myapp 
lein run migrate
&lt;/code&gt;&lt;/pre&gt;We're now ready to start the app in development mode:  &lt;br /&gt;&lt;pre&gt;&lt;code&gt;lein run&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The app will start the nREPL server on &lt;code&gt;localhost:7000&lt;/code&gt; once it loads. Let's open the project in Atom and connect to the nREPL instance.&lt;/p&gt;&lt;p&gt;The default keybinding for connecting to the nREPL is &lt;code&gt;ctrl-alt-, y&lt;/code&gt; on Windows/Linux and &lt;code&gt;cmd-alt-, y&lt;/code&gt; on OS X. This should pop up a dialog asking for the host and the port.&lt;/p&gt;&lt;p&gt;&lt;img src="/img/atom/atom-nrepl.png" alt="" /&gt;&lt;/p&gt;&lt;p&gt;Enter &lt;code&gt;7000&lt;/code&gt; as the port and hit &lt;code&gt;enter&lt;/code&gt;. If everything went well the REPL should now be connected to your project.&lt;/p&gt;&lt;p&gt;Once the REPL is connected we can try to evaluate some code in it. For example, let's check what namespace we're currently in by typing &lt;code&gt;&amp;#42;ns&amp;#42;&lt;/code&gt; in the REPL and then hitting &lt;code&gt;shift-enter&lt;/code&gt;. The result should look something like the following:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/atom/atom-repl-ns.png" alt="" /&gt;&lt;/p&gt;&lt;p&gt;Let's navigate to the &lt;code&gt;myapp.routes.home&lt;/code&gt; namespace and try to run some of the database query functions from there. We'll first need to require the database namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns myapp.routes.home
  &amp;#40;:require &amp;#91;myapp.layout :as layout&amp;#93;
            &amp;#91;compojure.core :refer &amp;#91;defroutes GET&amp;#93;&amp;#93;
            &amp;#91;ring.util.http-response :as response&amp;#93;
            &amp;#91;clojure.java.io :as io&amp;#93;
            ;; add a reference to the db namespace
            &amp;#91;myapp.db.core :as db&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once we've done that, we'll need to reload &lt;code&gt;myapp.routes.home&lt;/code&gt; namespace. To do that we'll need to send the code from the editor to the REPL for evaluation.&lt;/p&gt;&lt;p&gt;There are a few commands for doing this. I recommend starting by using the &lt;code&gt;ctrl-alt-, B&lt;/code&gt; shortcut that sends the top-level block of code to the REPL for execution. Place the cursor inside the &lt;code&gt;ns&lt;/code&gt; declaration and hit &lt;code&gt;ctrl-alt-, B&lt;/code&gt; to send it to the REPL. We can see that the REPL displays the code that was sent to it along with the result:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/atom/send-to-repl.png" alt="" /&gt;&lt;/p&gt;&lt;p&gt;Now that we have the &lt;code&gt;db&lt;/code&gt; namespace required, we can start the database connection state by typing the following command in the REPL:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;mount.core/start #'db/&amp;#42;db&amp;#42;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The result should look as follows:&lt;/p&gt;&lt;p&gt;&lt;img src="/img/atom/atom-start-db.png" alt="" /&gt;&lt;/p&gt;&lt;p&gt;With the database is started, let's add a user to it by running the following code in the REPL:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;db/create-user!
 {:id &amp;quot;foo&amp;quot;
  :first&amp;#95;name &amp;quot;Bob&amp;quot;
  :last&amp;#95;name &amp;quot;Bobberton&amp;quot;
  :email &amp;quot;bob@foo.bar&amp;quot;
  :pass &amp;quot;secret&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can also test that the user was added successfully by running:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;db/get-user {:id &amp;quot;foo&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the user record exists in the database:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:id &amp;quot;foo&amp;quot;
 :admin nil
 :is&amp;#95;active nil
 :last&amp;#95;login nil
 :first&amp;#95;name &amp;quot;Bob&amp;quot;
 :last&amp;#95;name &amp;quot;Bobberton&amp;quot;
 :email &amp;quot;bob@foo.bar&amp;quot;
 :pass &amp;quot;secret&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, the code that we run in the REPL executes in the context of the application and has access to all the resources and the application state. Let's take a closer look at how this helps us during development.&lt;/p&gt;&lt;p&gt;You might have noticed that the records we get back from the database use the &lt;code&gt;&amp;#95;&lt;/code&gt; character as word separator. Meanwhile, idiomatic Clojure code uses the &lt;code&gt;-&lt;/code&gt; character. Let's write a couple of functions to transform the key names in the results.&lt;/p&gt;&lt;p&gt;A Clojure map represents its entities as vectors containing key-value pairs. We'll start by writing a function to rename underscores to dashes in map entries:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn clojurize &amp;#91;&amp;#91;k v&amp;#93;&amp;#93;
  &amp;#91;&amp;#40;-&amp;gt; k name &amp;#40;.replaceAll &amp;quot;&amp;#95;&amp;quot; &amp;quot;-&amp;quot;&amp;#41; keyword&amp;#41; v&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll load the function in the namespace by placing the cursor anywhere inside it and hitting &lt;code&gt;ctrl-alt-, B&lt;/code&gt; to load it. Let's run this function in the REPL to see that it works:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;clojurize &amp;#91;:first&amp;#95;name &amp;quot;Bob&amp;quot;&amp;#93;&amp;#41;
=&amp;gt;&amp;#91;:first-name &amp;quot;Bob&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the result is what we expect. Next, let's write a function to rename the keys in a map:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn clojurize-keys &amp;#91;m&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; m &amp;#40;map clojurize&amp;#41; &amp;#40;into {}&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll load the new function and test that this works as expected in the REPL:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;clojurize-keys &amp;#40;db/get-user {:id &amp;quot;foo&amp;quot;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We see that the result is the translated map that we want:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:id &amp;quot;foo&amp;quot;
 :admin nil
 :is-active nil
 :last-login nil
 :first-name &amp;quot;Bob&amp;quot;
 :last-name &amp;quot;Bobberton&amp;quot;
 :email &amp;quot;bob@foo.bar&amp;quot;
 :pass &amp;quot;secret&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now that we have a nicely formatted result, let's add a route to query it in the browser:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defroutes home-routes
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93; &amp;#40;home-page&amp;#41;&amp;#41;
  &amp;#40;GET &amp;quot;/user/:id&amp;quot; &amp;#91;id&amp;#93;
       &amp;#40;-&amp;gt; &amp;#40;db/get-user {:id id}&amp;#41;
           &amp;#40;clojurize-keys&amp;#41;
           &amp;#40;response/ok&amp;#41;&amp;#41;&amp;#41;
  &amp;#40;GET &amp;quot;/about&amp;quot; &amp;#91;&amp;#93; &amp;#40;about-page&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now navigate to &lt;code&gt;http://localhost:3000/user/foo&lt;/code&gt; and see the user data.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;That's all there is to it. While this setup is fairly minimal, it will let you play with a lot of Clojure features without having to spend practically any time learning and configuring an editor. &lt;/p&gt;</description><pubDate>Sat, 15 Oct 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-09-25-ReagentComponents.html</guid><link>https://yogthos.net/posts/2016-09-25-ReagentComponents.html</link><title>Reusable Components</title><description>&lt;p&gt;One of the projects my team works is a clinical documentation platform. The goal of the project is to facilitate the implementation of different kinds of workflows for the clinics at our hospital.&lt;/p&gt;&lt;h2 id="requirements"&gt;Requirements&lt;/h2&gt;&lt;p&gt;One major requirement for the platform is support for multiple concurrent users working on the same document. For example, both a physician and a pharmacist may have to enter the prescribed medications for a patient. Both users have to be able to complete their work concurrently and to be aware of the changes made by the other.&lt;/p&gt;&lt;p&gt;Another requirement is to visualize the data differently depending on the discipline. Patient lab results may need to be shown as a table in one place, but as a trending chart in another. A physician may call a piece of data by one name, while the pharmacist calls it by another.&lt;/p&gt;&lt;p&gt;In other words, the data model needs to have different views associated with it. Furthermore, some information may not be shown in a particular view at all, but it would still need to be updated when a field in the view changes.&lt;/p&gt;&lt;p&gt;Consider an example where you're collecting patient height and weight, then the BMI is calculated based on that. The user may only be interested in seeing height and weight in their workflow, but once that data changes the BMI still needs to be recalculated even if it's not displayed in that view.&lt;/p&gt;&lt;p&gt;Finally, we have a large data model based on the &lt;a href='https://www.hl7.org/fhir/'&gt;Hl7 FHIR&lt;/a&gt; standard. This standard specifies resources for describing different kinds clinical data, such as patient demographics, medications, allergies and so on. An example of a resource definition can be seen in the &lt;a href='https://www.hl7.org/fhir/resourcelist.html'&gt;Resources&lt;/a&gt; section.&lt;/p&gt;&lt;h2 id="architecture"&gt;Architecture&lt;/h2&gt;&lt;p&gt;The concurrent user requirement means that the changes made by different users have to be kept in sync. Meanwhile, business rules have to be applied transactionally for each change.&lt;/p&gt;&lt;p&gt;The easiest way to address the above requirements is to keep the master document on the server. Any time a client makes a change, a request is sent to the server over a WebSocket. The server updates the field in the document and runs the business rules. It will then notify the clients viewing a particular document of all the fields that were updated in the transaction.&lt;/p&gt;&lt;p&gt;The clients simply reflect the state of the document managed by the server and never make local updates to the model. This ensures that all the changes are handled centrally, and that the business rules are applied regardless of what is displayed on the client.&lt;/p&gt;&lt;p&gt;The second problem is the creation of views for the data. Since we have many distinct fields, but only a small number of types of fields, it made sense for us to create widgets to represent specific data types. The widgets are bound to the fields in the data model using the path as a unique identifier.&lt;/p&gt;&lt;p&gt;Let's take a look at a &lt;a href='https://github.com/yogthos/components-example'&gt;sample project&lt;/a&gt; that illustrates the above architecture to see how this works in practice.&lt;/p&gt;&lt;h2 id="server-side&amp;#95;state&amp;#95;management"&gt;Server-Side State Management&lt;/h2&gt;&lt;p&gt;We'll start by examining the server-side implementation of the architecture starting with the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/clj/components_example/document.clj'&gt;components-example.document&lt;/a&gt; namespace. The server in our example keeps its state in a &lt;code&gt;ref&lt;/code&gt;, and updates it transactionally whenever it receives an update from the client.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defonce document &amp;#40;ref {}&amp;#41;&amp;#41;

&amp;#40;defn bmi &amp;#91;weight height&amp;#93;
  &amp;#40;when &amp;#40;and weight height &amp;#40;pos? height&amp;#41;&amp;#41;
    &amp;#40;/ weight &amp;#40;&amp;#42; height height&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn bmi-rule &amp;#91;doc&amp;#93;
  &amp;#40;let &amp;#91;weight &amp;#40;get-in doc &amp;#91;:vitals :weight&amp;#93;&amp;#41;
        height &amp;#40;get-in doc &amp;#91;:vitals :height&amp;#93;&amp;#41;&amp;#93;
    &amp;#91;{:path  &amp;#91;:vitals :bmi&amp;#93;
      :value &amp;#40;bmi weight height&amp;#41;}&amp;#93;&amp;#41;&amp;#41;

&amp;#40;def rules
  {&amp;#91;:vitals :weight&amp;#93; bmi-rule
   &amp;#91;:vitals :height&amp;#93; bmi-rule}&amp;#41;

&amp;#40;defn run-rules &amp;#91;doc {:keys &amp;#91;path&amp;#93;}&amp;#93;
  &amp;#40;when-let &amp;#91;rule &amp;#40;rules path&amp;#41;&amp;#93;
    &amp;#40;rule doc&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn update-document! &amp;#91;{:keys &amp;#91;path value&amp;#93; :as path-value}&amp;#93;
  &amp;#40;dosync
    &amp;#40;let &amp;#91;current-document &amp;#40;alter document assoc-in path value&amp;#41;
          updated-paths    &amp;#40;run-rules current-document path-value&amp;#41;&amp;#93;
      &amp;#40;doseq &amp;#91;{:keys &amp;#91;path value&amp;#93;} updated-paths&amp;#93;
        &amp;#40;alter document assoc-in path value&amp;#41;&amp;#41;
      &amp;#40;into &amp;#91;path-value&amp;#93; updated-paths&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note the use of the &lt;code&gt;dosync&lt;/code&gt; block in the &lt;code&gt;update-document!&lt;/code&gt; function to update the document and run the business rules as a transaction.&lt;/p&gt;&lt;p&gt;Each rule can in turn create additional changes in the document. A vector of updated &lt;code&gt;path-value&lt;/code&gt; pairs is returned as the result of the update. Our setup has a single rule that calculates the BMI. This rule is triggered whenever the weight or height fields are changed.&lt;/p&gt;&lt;p&gt;While the example keeps the document in memory, there's nothing stopping us from keeping it in the database and running the updates using a transaction against it. This is especially easy to do with PostgreSQL as it supports working with individual JSON fields directly.&lt;/p&gt;&lt;h2 id="client-server&amp;#95;communication"&gt;Client-Server Communication&lt;/h2&gt;&lt;p&gt;When the client loads, it establishes a WebSocket connection with the server. This connection is used to notify the server of the user actions and to push the changes back to the clients.&lt;/p&gt;&lt;p&gt;Server side of the connection can be found in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/clj/components_example/routes/ws.clj'&gt;components-example.routes.ws&lt;/a&gt; namespace. The part that's of most interest to us is the &lt;code&gt;handle-message&lt;/code&gt; multimethod that's keyed on the &lt;code&gt;:document/update&lt;/code&gt; event:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod handle-message :document/update &amp;#91;{:keys &amp;#91;?data&amp;#93;}&amp;#93;
  &amp;#40;let &amp;#91;updated-paths &amp;#40;update-document! ?data&amp;#41;&amp;#93;
    &amp;#40;doseq &amp;#91;uid &amp;#40;-&amp;gt; @socket :connected-uids deref :any&amp;#41;&amp;#93;
      &amp;#40;&amp;#40;:send-fn @socket&amp;#41; uid &amp;#91;:document/update updated-paths&amp;#93;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The multimethod calls the &lt;code&gt;update-document!&lt;/code&gt; function we just saw and then notifies the connected clients with its result.&lt;/p&gt;&lt;p&gt;Conversely, the client portion of the WebSocket connection is found in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/ws.cljs'&gt;components-example.ws&lt;/a&gt; namespace. Here we have the &lt;code&gt;update-value&lt;/code&gt; function that sends the update event to the server, and the &lt;code&gt;handle-message&lt;/code&gt; multimethod that handles incoming update messages:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn update-value &amp;#91;path-value&amp;#93;
  &amp;#40;&amp;#40;:send-fn @socket&amp;#41; &amp;#91;:document/update path-value&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defmethod handle-message :document/update &amp;#91;&amp;#91;&amp;#95; updated-paths&amp;#93;&amp;#93;
  &amp;#40;doseq &amp;#91;{:keys &amp;#91;path value&amp;#93;} updated-paths&amp;#93;
    &amp;#40;dispatch &amp;#91;:set-doc-value path value&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The multimethod dispatches a re-frame event for each path/value pair in the message. Let's take a look at the re-frame handlers and subscriptions next.&lt;/p&gt;&lt;h2 id="client-side&amp;#95;state&amp;#95;management"&gt;Client-Side State Management&lt;/h2&gt;&lt;p&gt;Re-frame handlers are found in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/handlers.cljs'&gt;components-example.handlers&lt;/a&gt; namespace, where the document state is updated using the following handlers:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;reg-event-db
  :set-doc-value
  &amp;#40;fn &amp;#91;db &amp;#91;&amp;#95; path value&amp;#93;&amp;#93;
    &amp;#40;assoc-in db &amp;#40;into &amp;#91;:document&amp;#93; path&amp;#41; value&amp;#41;&amp;#41;&amp;#41;

&amp;#40;reg-event-db
  :save
  &amp;#40;fn &amp;#91;db &amp;#91;&amp;#95; path value&amp;#93;&amp;#93;
    &amp;#40;ws/update-value {:path path :value value}&amp;#41;
    db&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;:save&lt;/code&gt; event creates a WebSocket call to notify the server of the change. Meanwhile, the &lt;code&gt;:set-doc-value&lt;/code&gt; event is used to update the client state with the set of changes. This event will be triggered by a WebSocket message from the server, whenever the master document is updated.&lt;/p&gt;&lt;p&gt;We also need to have a corresponding subscription to view the state of the document. This subscription is found in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/subscriptions.cljs'&gt;components-example.subscriptions&lt;/a&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;reg-sub
  :document
  &amp;#40;fn &amp;#91;db &amp;#91;&amp;#95; path&amp;#93;&amp;#93;
    &amp;#40;let &amp;#91;doc &amp;#40;:document db&amp;#41;&amp;#93;
      &amp;#40;if path &amp;#40;get-in doc path&amp;#41; doc&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, let's take a look at how the UI components are defined and associated with the data model.&lt;/p&gt;&lt;h2 id="application&amp;#95;components"&gt;Application Components&lt;/h2&gt;&lt;p&gt;The UI for the application consists of widgets representing individual data types. When a widget is instantiated it's associated with a particular path in the document. The widgets are found in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/widgets.cljs'&gt;components-example.widgets&lt;/a&gt; namespace.&lt;/p&gt;&lt;p&gt;The set of all valid paths is contained in the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljc/components_example/model.cljc'&gt;components-example.model&lt;/a&gt; namespace. This namespace is written using CLJC, and provides a single schema for both the client and the server portions of the application.&lt;/p&gt;&lt;p&gt;The widgets are associated with the model using the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/model_view.cljs'&gt;components-example.model-view&lt;/a&gt; namespace. Each of the paths found in the model can have multiple views associated with it. In our example, we have the form for entering the data and a preview for displaying it.&lt;/p&gt;&lt;p&gt;Finally, we have the &lt;a href='https://github.com/yogthos/components-example/blob/master/src/cljs/components_example/view.cljs'&gt;components-example.view&lt;/a&gt; namespace that provides the layout for the page. This namespace instantiates the widgets defined in the &lt;code&gt;model-view&lt;/code&gt; namespace and lays them out as needed for a particular page in the application.&lt;/p&gt;&lt;p&gt;Let's explore each of these namespaces in detail below.&lt;/p&gt;&lt;h3 id="model"&gt;Model&lt;/h3&gt;&lt;p&gt;The data model in our application consists of a map that's keyed on the element path where each key points to the type of data found in that element. Let's take a look at a simple demographics model below:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def Name
  {:first s/Str
   :last  s/Str}&amp;#41;

&amp;#40;def demographics
  {&amp;#91;:demographics :mrn&amp;#93;
   s/Str
   
   &amp;#91;:demographics :name&amp;#93;
   Name

   &amp;#91;:demographics :name :dob&amp;#93;
   #?&amp;#40;:clj java.util.Date
      :cljs js/Date&amp;#41;

   &amp;#91;:demographics :address :province&amp;#93;
   &amp;#40;s/enum &amp;quot;AB&amp;quot; &amp;quot;BC&amp;quot; &amp;quot;MB&amp;quot; &amp;quot;NB&amp;quot; &amp;quot;NL&amp;quot; &amp;quot;NS&amp;quot; &amp;quot;NT&amp;quot; &amp;quot;NU&amp;quot; &amp;quot;ON&amp;quot; &amp;quot;PE&amp;quot; &amp;quot;QC&amp;quot; &amp;quot;SK&amp;quot; &amp;quot;YT&amp;quot;&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can see that the demographics model contains the name, the date of birth, and the province for the patient.&lt;/p&gt;&lt;p&gt;The paths can point to any type of data structure. For example, the &lt;code&gt;&amp;#91;:demographics :name&amp;#93;&lt;/code&gt; path points to a map containing the first and the last name.&lt;/p&gt;&lt;p&gt;Meanwhile, the &lt;code&gt;&amp;#91;:demographics :name :dob&amp;#93;&lt;/code&gt; path leverages CLJC to provide different validators for Clojure and ClojureScript.&lt;/p&gt;&lt;h3 id="widgets"&gt;Widgets&lt;/h3&gt;&lt;p&gt;Now, let's take a look at the approach we took to map the FHIR data model to the UI in the application.&lt;/p&gt;&lt;p&gt;At the lowest level we have widgets that represent a particular type of element. These would include text fields, datepickers, dropdowns, tables, and so on. The way we chose to represent the widgets was to use multimethods. The widgets are initialized using a map containing the &lt;code&gt;:type&lt;/code&gt; key:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmulti widget :type&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Given the multimethod definition above, a text input widget might look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod widget :text-input &amp;#91;{:keys &amp;#91;label path&amp;#93;}&amp;#93;
  &amp;#40;r/with-let &amp;#91;value    &amp;#40;r/atom nil&amp;#41;
               focused? &amp;#40;r/atom false&amp;#41;&amp;#93;
    &amp;#91;:div.form-group
     &amp;#91;:label label&amp;#93;
     &amp;#91;:input.form-control
      {:type      :text
       :on-focus  #&amp;#40;do
                    &amp;#40;reset! value @&amp;#40;rf/subscribe &amp;#91;:document path&amp;#93;&amp;#41;&amp;#41;
                    &amp;#40;reset! focused? true&amp;#41;&amp;#41;
       :on-blur   #&amp;#40;do
                    &amp;#40;rf/dispatch
                      &amp;#91;:save path @value&amp;#93;&amp;#41;
                    &amp;#40;reset! focused? false&amp;#41;&amp;#41;
       :value     &amp;#40;if @focused? @value @&amp;#40;subscribe-doc path&amp;#41;&amp;#41;
       :on-change #&amp;#40;reset! value &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;}&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The text input widget subscribes to the given path in the document as its value. Since we don't want to generate unnecessary WebSocket events while the user is typing, the input keeps a local state while it's focused.&lt;/p&gt;&lt;p&gt;When the user focuses the input, its local state is set to the current document state, and when the focus is lost, the update event is generated with the new value.&lt;/p&gt;&lt;p&gt;Each widget is a reusable component that is associated with a path in the document to create a concrete instance:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;widget {:type :text-input
         :lable &amp;quot;first name&amp;quot;
         :path &amp;#91;:patient :name :first&amp;#93;}&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Since the widgets are mapped to the data elements via the path when instantiated, they can easily be composed into larger components. For example, we'll create a patient name component using two &lt;code&gt;:text-input&lt;/code&gt; widgets:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod widget :name &amp;#91;{:keys &amp;#91;first-name last-name path&amp;#93;}&amp;#93;
  &amp;#91;:div
   &amp;#91;widget {:label first-name
            :type :text-input
            :path &amp;#40;conj path :first&amp;#41;}&amp;#93;
   &amp;#91;widget {:label last-name
            :type :text-input
            :path &amp;#40;conj path :last&amp;#41;}&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Composite widgets provide us with the ability to describe complex data elements that are common among different resources.&lt;/p&gt;&lt;h3 id="model-view"&gt;Model-View&lt;/h3&gt;&lt;p&gt;The widgets are associated with the concrete paths using a model-view map. This map is keyed on the same paths as the model map, but points to widget declarations instead of the types. We can represent the MRN and name fields as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def demographics-form
  {&amp;#91;:demographics :mrn&amp;#93;
   {:label &amp;quot;medical record number&amp;quot;
    :type  :text-input}
    
   &amp;#91;:demographics :name&amp;#93;
   {:first-name &amp;quot;first name&amp;quot;
    :last-name  &amp;quot;last name&amp;quot;
    :type       :name}}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The model/view map contains a set of UI elements for representing the data model. Note that this approach allows us to create multiple view definitions for any particular data element.&lt;/p&gt;&lt;p&gt;This is useful as we may wish to present the data differently depending on the use case. For example, some users may manipulate the data, while others will simply want to view it.&lt;/p&gt;&lt;h3 id="view"&gt;View&lt;/h3&gt;&lt;p&gt;This brings us to the view portion of the architecture. The view aggregates the widgets defined in the model-view map into a particular layout. The demographics view could look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-widget &amp;#91;view path&amp;#93;
  &amp;#40;let &amp;#91;opts &amp;#40;view path&amp;#41;&amp;#93;
    &amp;#91;widget &amp;#40;assoc opts :path path&amp;#41;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn form-row &amp;#91;view path&amp;#93;
  &amp;#91;:div.row&amp;gt;div.col-md-12
   &amp;#40;create-widget view path&amp;#41;&amp;#93;&amp;#41;
   
&amp;#40;defn demographics &amp;#91;view&amp;#93;
  &amp;#91;:div
   &amp;#40;form-row demographics-form &amp;#91;:demographics :mrn&amp;#93;&amp;#41;
   &amp;#40;form-row demographics-form &amp;#91;:demographics :name&amp;#93;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here we use a &lt;code&gt;create-widget&lt;/code&gt; helper function that looks up the options for a widget in the view and instantiate it with the given path.&lt;/p&gt;&lt;p&gt;The widgets are then wrapped in the layout tags in the &lt;code&gt;form-row&lt;/code&gt; and inserted in the the &lt;code&gt;div&lt;/code&gt; that represents the demographics view.&lt;/p&gt;&lt;p&gt;Once the widgets are defined, it becomes trivial to create different kinds of interfaces using them. This is perfect for our use case where we have a large common data model with many different views into it.&lt;/p&gt;&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;&lt;p&gt;I hope this provides a bit of an insight into building large UIs with reusable components using Reagent and re-frame. My team has found that this approach scales very nicely and allows us to quickly build different kinds of UIs against a common data model.&lt;/p&gt;</description><pubDate>Sun, 25 Sep 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-09-06-Static-Typing-WebSockets.html</guid><link>https://yogthos.net/posts/2016-09-06-Static-Typing-WebSockets.html</link><title>Static Typing vs WebSockets</title><description> &lt;p&gt;A &lt;a href='https://hashrocket.com/blog/posts/websocket-shootout'&gt;recent post&lt;/a&gt; compared WebSocket server performance in Clojure, C++, Elixir, Go, NodeJS, and Ruby. Chris Allen wrote a &lt;a href='http://bitemyapp.com//posts/2016-09-03-websocket-shootout-haskell.html'&gt;nice follow-up post&lt;/a&gt; where he implemented the benchmark using Haskell.&lt;/p&gt;&lt;p&gt;The initial results looked extremely favorable for Haskell. However, it turned out that the Haskell implementation failed to deliver messages reliably, &lt;a href='https://github.com/hashrocket/websocket-shootout/pull/14'&gt;dropping 98% of the messages it received&lt;/a&gt;. What's interesting is that this is exactly the kind of behavior we would expect Haskell type system to prevent from happening. So, how did the fact that messages were being dropped slip by completely undetected?&lt;/p&gt;&lt;h4 id="update"&gt;update&lt;/h4&gt;&lt;p&gt;As a couple of people helpfully pointed out, the problem was not in fact caused by using unsafe functions. It's simply a type of error that would not be caught by the Haskell type system in general.&lt;/p&gt;&lt;p&gt;While the problems I outline with the unsafe operations are still present, it's clearly possible for serious problems to slip by even when you're not using them.&lt;/p&gt;&lt;p&gt;If anything, I think this bolsters the argument for the importance of a mature ecosystem and specification testing.&lt;/p&gt;&lt;p&gt;&lt;hr&gt;&lt;/p&gt;&lt;h3 id="type&amp;#95;system&amp;#95;escape&amp;#95;hatches"&gt;Type system escape hatches&lt;/h3&gt;&lt;p&gt;Haskell provides escape hatches from its type system, and these are often used in practice to achieve reasonable performance. When we look at code in the &lt;a href='https://github.com/jberryman/unagi-chan'&gt;unagi-chan&lt;/a&gt; library used in the Haskell implementation, we can see that it uses &lt;code&gt;unsafeInterleaveIO&lt;/code&gt; to get the channel contents.&lt;/p&gt;&lt;p&gt;This is an example of an escape hatch that bypasses the type checker entirely. While Haskell is conceptually a pure language, the internal GHC implementation is imperative in nature. GHC runtime evaluates impure functions that produce side effects making the order of evaluation important. Functions like &lt;code&gt;unsafeInterleaveIO&lt;/code&gt; expose the impure runtime to the user, and open the gate for all the types of errors we're familiar with from imperative languages.&lt;/p&gt;&lt;p&gt;The way GHC implements Haskell inherently precludes safety guarantees by its type system. The purity is effectively an honor system, and cannot be proved by the compiler. In other words, once we use a library that happens to use unsafe operations any guarantees that we get from the type system go out of the window.&lt;/p&gt;&lt;h3 id="types&amp;#95;are&amp;#95;not&amp;#95;a&amp;#95;specification"&gt;Types are not a specification&lt;/h3&gt;&lt;p&gt;While Haskell type system can help ensure that our code is self-consistent, it clearly can't provide any guarantees regarding the behavior of third party code. Since most real world applications tend to rely on many third party libraries, it means that unless we know what each library is doing we can't ever be certain that our code will work as expected.&lt;/p&gt;&lt;p&gt;The developer can't possibly be expected to audit every library they use in their project to ensure that it behaves safely. Since most applications rely on large amounts of third party code, availability of mature and reliable libraries is a major factor when it comes to building robust applications.&lt;/p&gt;&lt;p&gt;While the benchmark in this example is trivial, it's a good example of real world problems many projects have to deal with. Most applications have to interact with the external resources such as queues, databases, and other services. Therefore, we need mature and tested libraries in order to accomplish these tasks effectively.&lt;/p&gt;&lt;p&gt;I think this is one of the major reasons why hosted languages have been gaining popularity in recent years. When the language relies on a mature ecosystem, such as the JVM, it inherits a lot of battle tested code along with it.&lt;/p&gt;&lt;p&gt;However, this problem exists in every language. Ultimately, we need to know what the code is doing, and clearly types don't provide us with enough information to really be sure the code is doing what was intended.&lt;/p&gt;&lt;h3 id="achieving&amp;#95;correctness"&gt;Achieving correctness&lt;/h3&gt;&lt;p&gt;The only way to know that the code is doing what was intended is to have a specification, and test the code against it. This is true pretty much for any language in use today. Tests allow us to validate complex properties that are difficult or even impossible to encode using most type systems.&lt;/p&gt;&lt;p&gt;Consider the trivial case of validating a user generated password. We need to check its length, combinations of characters it contains, and whether it matches the retyped password. All most type systems can tell us is that we have to pass the function a couple of strings and it will return a boolean.&lt;/p&gt;&lt;p&gt;To check any of the properties that prove that the function does what was intended, we need to come up with a specification and test the code against it. While the tests do not provide an exhaustive proof of correctness, they provide proof that the code satisfies the intended use cases.&lt;/p&gt;&lt;p&gt;An argument can be made that types save time in finding bugs when the tests fail. However, my experience is that it's often trivial to track down the actual problem once you're aware of it.&lt;/p&gt;&lt;p&gt;I think this is where the trade-off between static and dynamic languages lies. The former forces us to describe the types up front, and makes it easier to track down potential errors. Meanwhile, the latter approach allows us to skip this step at the cost of potentially having to do more work to find bugs later.&lt;/p&gt;&lt;p&gt;To the best of my knowledge nobody knows whether one approach is strictly more efficient than the other.  The overall amount of work appears to be comparable with both approaches. However, the nature of work is different, therefore each approach appeals to a different mindset.&lt;/p&gt;&lt;p&gt;One interesting approach is to generate types from tests &lt;a href='https://github.com/typedclojure/auto-annotation'&gt;as seen in recent version of Typed Clojure&lt;/a&gt;. Using tests to drive type generation has the potential to offer the best of both worlds. We can work with a dynamic language, and offload the work of figuring out the type relationships to a library. As long as we're diligent about writing tests, we get the types for free.&lt;/p&gt;&lt;p&gt;Another powerful tool for writing robust code is the REPL. When it's integrated with the editor, testing code as you write it becomes very natural. It's quite common for me to test functions as I develop them, then extract the REPL session into a test suite for the feature I'm working on.&lt;/p&gt;&lt;h3 id="takeaways"&gt;Takeaways&lt;/h3&gt;&lt;p&gt;Even a strong type system, such as one found in Haskell, provides a very weak specification in practice. Just because the code compiles doesn't mean it's actually doing what was intended.&lt;/p&gt;&lt;p&gt;The type system does not help debugging many real world problems. The code in this benchmark worked as expected under small load, and started exhibiting errors when it was stress tested.&lt;/p&gt;&lt;p&gt;The ecosystem around the language is an important factor when it comes to productivity. When we use mature and battle tested libraries, we're much less likely to be surprised by their behavior.&lt;/p&gt;&lt;p&gt;Tests are ultimately the only practical way to provide a specification for the application. Behaviors that are easily tested can be difficult or impossible to encode using a type system.&lt;/p&gt;</description><pubDate>Tue, 06 Sep 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-07-23-WebDevWithClojure2.html</guid><link>https://yogthos.net/posts/2016-07-23-WebDevWithClojure2.html</link><title>Web Development with Clojure, Second Edition</title><description> &lt;p&gt;I'm glad to announce that the &lt;a href='https://pragprog.com/book/dswdcloj2/web-development-with-clojure-second-edition'&gt;second edition of Web Development with Clojure&lt;/a&gt; is finally finished. The book took longer to put together than I anticipated, and I ended up missing the original release target by a few months.&lt;/p&gt;&lt;p&gt;However, all the delays resulted in a much better book in the end. Having a long beta period allowed me to collect a lot of feedback from the readers and address any concerns that came up. This process helped ensure that the material is clear and easy to follow, while keeping a good pace. I discussed the specifics of what the book covers an earlier post &lt;a href='http://yogthos.net/posts/2016-01-01-ClojureWebDev2.html'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;It's my sincere hope that the book will provide the readers with a smooth path into the wonderful world of Clojure web development.&lt;/p&gt;</description><pubDate>Sat, 23 Jul 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-07-15-JavaSSLWorkaround.html</guid><link>https://yogthos.net/posts/2016-07-15-JavaSSLWorkaround.html</link><title>Working around the Java SSL trust store</title><description>&lt;p&gt;The Java standard library provides a rich networking API. For example, the &lt;code&gt;java.net.URL&lt;/code&gt; class provides a simple way to access resources using a URL location pattern. We can do fun stuff like this using it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;-&amp;gt; &amp;quot;https://gist.githubusercontent.com/yogthos/f432e5ba0bb9d70dc479/raw/768050c7fae45767b277a2ce834f4d4f00158887/names.clj&amp;quot;
    &amp;#40;java.net.URL.&amp;#41;
    &amp;#40;slurp&amp;#41;
    &amp;#40;load-string&amp;#41;&amp;#41;

&amp;#40;gen-name 11 6&amp;#41;    
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Unfortunately, the SSL certificates bundled with the default Java runtime aren't comprehensive. For example, the &lt;a href='https://http.cat/'&gt;https://http.cat/&lt;/a&gt; site has a valid certificate that's not part of the default Java trust store.&lt;/p&gt;&lt;p&gt;Let's write a function to read an image from the site using &lt;code&gt;java.net.URL&lt;/code&gt;, then save it to a file to see what happens.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn read-image &amp;#91;url&amp;#93;
  &amp;#40;let &amp;#91;conn &amp;#40;.openConnection &amp;#40;java.net.URL. url&amp;#41;&amp;#41;&amp;#93;    
    &amp;#40;.getInputStream conn&amp;#41;&amp;#41;&amp;#41;
    
&amp;#40;clojure.java.io/copy
  &amp;#40;read-image &amp;quot;https://http.cat/200&amp;quot;&amp;#41;
  &amp;#40;java.io.FileOutputStream. &amp;quot;200.jpg&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we try to access the resource, we end up with a security exception because the default trust store does not contain the right certificate.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
...
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One way we could work around this problem would be to add the certificate to the local store. This is the proper solution that should be used in the vast majority of cases.&lt;/p&gt;&lt;p&gt;However, there are situations where this approach isn't possible. I've run into many situations working in the enterprise where SSL was misconfigured, and the application would need to connect to an intranet service over such a connection. At the same time I had no control over the deployment environment and wasn't able to manage the keystore there.&lt;/p&gt;&lt;p&gt;An alternative approach is to replace the default certificate check for a specific connection with a custom one. Let's take a look at how this can be accomplished.&lt;/p&gt;&lt;p&gt;We'll first have to create a proxy &lt;code&gt;TrustManager&lt;/code&gt;, then use it to create a socket factory for our connection as seen in the following code:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn set-socket-factory &amp;#91;conn&amp;#93;
  &amp;#40;let &amp;#91;cert-manager &amp;#40;make-array X509TrustManager 1&amp;#41;
        sc           &amp;#40;SSLContext/getInstance &amp;quot;SSL&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;aset cert-manager 0
          &amp;#40;proxy &amp;#91;X509TrustManager&amp;#93;&amp;#91;&amp;#93;
            &amp;#40;getAcceptedIssuers &amp;#91;&amp;#93;&amp;#41;
            &amp;#40;checkClientTrusted &amp;#91;&amp;#95; &amp;#95;&amp;#93;&amp;#41;
            &amp;#40;checkServerTrusted &amp;#91;&amp;#95; &amp;#95;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;.init sc nil cert-manager &amp;#40;java.security.SecureRandom.&amp;#41;&amp;#41;
    &amp;#40;.setSSLSocketFactory conn &amp;#40;.getSocketFactory sc&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The custom socket factory will use the &lt;code&gt;X509TrustManager&lt;/code&gt; proxy that we provide and rely on it for validation. We can simply return &lt;code&gt;nil&lt;/code&gt; from each of the validation methods to skip the certificate validation.&lt;/p&gt;&lt;p&gt;Note that while we're skipping validation entirely in the above example, we'd likely want to supply a custom validator that validates against an actual certificate in practice.&lt;/p&gt;&lt;p&gt;Next, let's update the &lt;code&gt;read-image&lt;/code&gt; function to set the custom socket factory for the connection before trying to read from it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn read-image &amp;#91;url&amp;#93;
  &amp;#40;let &amp;#91;conn &amp;#40;.openConnection &amp;#40;java.net.URL. url&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;set-socket-factory conn&amp;#41;
    &amp;#40;.getInputStream conn&amp;#41;&amp;#41;&amp;#41;

&amp;#40;clojure.java.io/copy
  &amp;#40;read-image &amp;quot;https://http.cat/200&amp;quot;&amp;#41;
  &amp;#40;java.io.FileOutputStream. &amp;quot;200.jpg&amp;quot;&amp;#41;&amp;#41;    
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We should now have a &lt;code&gt;200.jpg&lt;/code&gt; file on our file system with the following content:&lt;/p&gt;&lt;p&gt;&lt;img src="https://http.cat/200" alt="cat" /&gt;&lt;/p&gt;&lt;p&gt;That's all there is to it. We can now enjoy consuming cat HTTP status pictures using the &lt;code&gt;java.net.URL&lt;/code&gt; and even make some silly &lt;a href='https://github.com/yogthos/ring-http-cat-status'&gt;Ring middleware&lt;/a&gt; using it. :)&lt;/p&gt;</description><pubDate>Fri, 15 Jul 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-06-06-WorkingWithHoplon.html</guid><link>https://yogthos.net/posts/2016-06-06-WorkingWithHoplon.html</link><title>Consider Hoplon</title><description>&lt;p&gt;A &lt;a href='https://dl.dropboxusercontent.com/u/12379861/micha_on_hoplon_vs_react/index.html'&gt;recent discussion of Hoplon vs React&lt;/a&gt; has been making rounds. While I don't necessarily agree that using React is as difficult as Micha makes it sound, I do think that Hoplon provides an interesting alternative to React that has a number of benefits.&lt;/p&gt;&lt;p&gt;The main selling point for Hoplon is that it's simple. Hoplon doesn't use a virtual DOM, and thus it doesn't have a component lifecycle. One major benefit of this approach is in making it natural to use with existing Js libraries that expect to work with the browser DOM.&lt;/p&gt;&lt;p&gt;An example of this would be something like using a &lt;a href='https://github.com/cljsjs/packages/tree/master/jquery-daterange-picker'&gt;jQuery date picker widget&lt;/a&gt;. With Reagent, we'd have to use the lifecycle hooks, and make sure that the component is mounted in the browser DOM before the library is called. Conversely, we may need to consider the case of the component updating separately. While, it's not difficult to reason about in most cases, it does introduce some mental overhead. Using the same date picker in Hoplon can be seen &lt;a href='https://github.com/hoplon/jquery.daterangepicker/blob/master/src/hoplon/jquery/daterangepicker.cljs.hl'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;However, while I found the idea of Hoplon interesting, I've never gave it a serious look due to the fact that it looked to be a monolithic stack. When you read Hoplon documentation, it's easy to get the impression that it has to be used with Boot, you have to use special &lt;code&gt;.hl&lt;/code&gt; files to define ClojureScript, and you're expected to work with its server implementation.&lt;/p&gt;&lt;p&gt;This all can be appealing if you're looking for a full-stack solution where decisions have been made for you, but it's a bit of a deterrent for somebody who already has a preferred workflow and uses other tools such as Figwheel and Leiningen.&lt;/p&gt;&lt;p&gt;After having a discussion with Micha &lt;a href='https://www.reddit.com/r/Clojure/comments/4mi64q/hoplon_vs_react/'&gt;on Reddit&lt;/a&gt;, I realized that this wasn't the case and decided to give Hoplon another shot.&lt;/p&gt;&lt;h3 id="the&amp;#95;setup"&gt;The Setup&lt;/h3&gt;&lt;p&gt;I used the &lt;a href='https://github.com/reagent-project/reagent-template'&gt;reagent-template&lt;/a&gt; that I maintain as the base for he project by running the following command in the terminal:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new reagent hoplon-app
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, I updated the dependencies in &lt;code&gt;project.clj&lt;/code&gt; to remove the references to Reagent, and add the Hoplon dependency instead:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;  :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.8.0&amp;quot;&amp;#93;
                 &amp;#91;ring-server &amp;quot;0.4.0&amp;quot;&amp;#93;
                 &amp;#91;hoplon &amp;quot;6.0.0-alpha15&amp;quot;&amp;#93;
                 &amp;#91;ring &amp;quot;1.4.0&amp;quot;&amp;#93;
                 &amp;#91;ring/ring-defaults &amp;quot;0.2.0&amp;quot;&amp;#93;
                 &amp;#91;compojure &amp;quot;1.5.0&amp;quot;&amp;#93;
                 &amp;#91;hiccup &amp;quot;1.0.5&amp;quot;&amp;#93;
                 &amp;#91;yogthos/config &amp;quot;0.8&amp;quot;&amp;#93;
                 &amp;#91;org.clojure/clojurescript &amp;quot;1.9.36&amp;quot;
                  :scope &amp;quot;provided&amp;quot;&amp;#93;
                 &amp;#91;secretary &amp;quot;1.2.3&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's all the changes I had to do in order to switch to using Hoplon in the project.&lt;/p&gt;&lt;p&gt;The next step was to open up the ClojureScript source in the &lt;code&gt;src/cljs/hoplon&amp;#95;app/core.cljs&lt;/code&gt; file and replace the references to Reagent with Hoplon:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns hoplon-app.core
  &amp;#40;:require
    &amp;#91;hoplon.core
     :as h
     :include-macros true&amp;#93;
    &amp;#91;javelin.core
     :refer &amp;#91;cell&amp;#93;
     :refer-macros &amp;#91;cell= dosync&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;h/defelem home &amp;#91;&amp;#93;
  &amp;#40;h/div
    :id &amp;quot;app&amp;quot;
    &amp;#40;h/h3 &amp;quot;Welcome to Hoplon&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn mount-root &amp;#91;&amp;#93;
  &amp;#40;js/jQuery #&amp;#40;.replaceWith &amp;#40;js/jQuery &amp;quot;#app&amp;quot;&amp;#41; &amp;#40;home&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;mount-root&amp;#41;&amp;#41;    
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;At this point I could start Figwheel and see the page load in the browser by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein figwheel
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see the main difference so far is that we mount the Hoplon DOM using plain jQuery call, and the elements are defined using Hoplon helper macros.&lt;/p&gt;&lt;p&gt;Let's see how we can add a bit of state to our Hoplon app. Hoplon state management is handled by the &lt;a href='https://github.com/hoplon/javelin'&gt;Javelin&lt;/a&gt; library. It uses a similar concept to the Reagent atom where we can define cells, and then whenever the state of the cells changes any elements that are looking at its value will be notified.&lt;/p&gt;&lt;p&gt;We'll create a simple to-do list to illustrate how this works. First, we need to create a cell to hold the data. We'll add the following code at the top of the namespace to do that:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def todo-items &amp;#40;cell &amp;#91;&amp;quot;foo&amp;quot;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above code will define a Javelin cell that contains a vector with the string &lt;code&gt;&amp;quot;foo&amp;quot;&lt;/code&gt; in it. We can now render the value of the cell as follows the the &lt;code&gt;home&lt;/code&gt; element:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;h/defelem home &amp;#91;&amp;#93;
  &amp;#40;h/div
    :id &amp;quot;app&amp;quot;
    &amp;#40;h/h3 &amp;quot;Welcome to Hoplon&amp;quot;&amp;#41;
    &amp;#40;h/p &amp;#40;cell= todo-items&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;cell=&lt;/code&gt; call is reactive and whenever the state of the cell changes the paragraph will be repainted to with its current value. We can now add some code to add new items to the to-do list:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;h/defelem add-todo &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;new-item &amp;#40;cell &amp;quot;&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;h/div
      &amp;#40;h/input :type &amp;quot;text&amp;quot;
               :value new-item
               :change #&amp;#40;reset! new-item @%&amp;#41;&amp;#41;
      &amp;#40;h/button :click #&amp;#40;dosync
                          &amp;#40;swap! todo-items conj @new-item&amp;#41;
                          &amp;#40;reset! new-item &amp;quot;&amp;quot;&amp;#41;&amp;#41;
                &amp;#40;h/text &amp;quot;Add #&amp;#126;{&amp;#40;inc &amp;#40;count todo-items&amp;#41;&amp;#41;}&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above code should be fairly familiar to anybody who's used Reagent. We define a local state in a &lt;code&gt;let&lt;/code&gt; binding and create a &lt;code&gt;div&lt;/code&gt; that contains an &lt;code&gt;input&lt;/code&gt; and a &lt;code&gt;button&lt;/code&gt;. The &lt;code&gt;input&lt;/code&gt; displays the value of the &lt;code&gt;new-item&lt;/code&gt; cell and updates it in its &lt;code&gt;:change&lt;/code&gt; event. Meanwhile, the button will swap the &lt;code&gt;todo-items&lt;/code&gt; cell and add the value of the new item, then reset it to an empty string.&lt;/p&gt;&lt;p&gt;Notice that the button text displays the current item count. This is accomplished by Hoplon &lt;code&gt;#&amp;#126;&lt;/code&gt; helper that allows us to easily display cell values within strings.&lt;/p&gt;&lt;p&gt;We should now be able to update our &lt;code&gt;home&lt;/code&gt; element as follows to have the &lt;code&gt;add-todo&lt;/code&gt; component show up on the page:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;h/defelem home &amp;#91;&amp;#93;
  &amp;#40;h/div
    :id &amp;quot;app&amp;quot;
    &amp;#40;h/h3 &amp;quot;Welcome to Hoplon&amp;quot;&amp;#41;
    &amp;#40;h/p &amp;#40;cell= todo-items&amp;#41;&amp;#41;
    &amp;#40;add-todo&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we add to-do items, they should be showing up in the list. So far everything looks nearly identical to working with Reagent.&lt;/p&gt;&lt;p&gt;Now, let's update the items to be rendered in the list a bit nicer. We'll write the following element to render the list:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;h/defelem todo-list &amp;#91;{:keys &amp;#91;title&amp;#93;}&amp;#93;
  &amp;#40;h/div
      &amp;#40;h/h4 &amp;#40;or title &amp;quot;TODO&amp;quot;&amp;#41;&amp;#41;
      &amp;#40;h/ul
        &amp;#40;h/for-tpl &amp;#91;todo todo-items&amp;#93;
          &amp;#40;h/li todo&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The element uses the Hoplon &lt;code&gt;for-tpl&lt;/code&gt; macro to run through the elements in the list. The macro is used to map dynamically sized collections to DOM nodes. With the element in place, we can update our &lt;code&gt;home&lt;/code&gt; element to display a nice HTML list:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;h/defelem home &amp;#91;&amp;#93;
  &amp;#40;h/div
    :id &amp;quot;app&amp;quot;
    &amp;#40;h/h3 &amp;quot;Welcome to Hoplon&amp;quot;&amp;#41;
    &amp;#40;todo-list {:title &amp;quot;TODO List&amp;quot;}&amp;#41;
    &amp;#40;add-todo&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We should now see a list of items displayed that will get updated as we add items using the &lt;code&gt;add-todo&lt;/code&gt; element. That's all there's to it. While it's a trivial app, I hope it gives you a taste of what working with Hoplon is like. The full source for the project can be seen &lt;a href='https://github.com/yogthos/hoplon-app'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;I was very pleasantly surprised by how easy it was to use Hoplon in a project setup with Leiningen and Figwheel. The semantics that Hoplon provides are very similar to Reagent, and are arguably simpler since there's no need to worry about the component lifecycle.&lt;/p&gt;&lt;p&gt;The one aspect of Reagent that I prefer is that the UI is defined declaratively using the Hiccup syntax. This makes it possible to manipulate UI elements as plain data. However, I don't think that using functions to define the UI is a deal breaker.&lt;/p&gt;&lt;p&gt;Overall, I think that Hoplon is often overlooked when ClojureScript UI libraries are considered, and this is very unfortunate. It's a solid library that provides clean and simple semantics to the user.&lt;/p&gt;&lt;p&gt;If, like me, you've been avoiding Hoplon because you were under the impression that you have to use it in a specific way, then I strongly urge you to give it another look.&lt;/p&gt;&lt;h4 id="update"&gt;Update&lt;/h4&gt;&lt;p&gt;Luminus now provides a Hoplon profile using the &lt;code&gt;+hoplon&lt;/code&gt; flag.&lt;/p&gt;</description><pubDate>Mon, 06 Jun 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-05-20-ExpandableWidgetsInReagent.html</guid><link>https://yogthos.net/posts/2016-05-20-ExpandableWidgetsInReagent.html</link><title>Writing an expandable widget with Reagent</title><description>&lt;p&gt;I recently needed to create an expandable widget and I wanted to be able to close it by clicking elsewhere on the screen. An example would be an input field and an associated component to select the input value such as a date picker.&lt;/p&gt;&lt;p&gt;We'll define an example component to look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn expandable-component &amp;#91;&amp;#93;
  &amp;#91;:div
   &amp;#91;:input
    {:type :text}&amp;#93;
   &amp;#91;:table&amp;gt;tbody      
    &amp;#40;for &amp;#91;row &amp;#40;range 5&amp;#41;&amp;#93;
      &amp;#91;:tr
       &amp;#40;for &amp;#91;n &amp;#40;range 5&amp;#41;&amp;#93;
         &amp;#91;:td&amp;gt;button.btn
          {:on-click
           #&amp;#40;do
              &amp;#40;reset! value n&amp;#41;
              &amp;#40;reset! expanded? false&amp;#41;&amp;#41;} n&amp;#93;&amp;#41;&amp;#93;&amp;#41;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll use the &lt;code&gt;with-let&lt;/code&gt; statement to define some state for the component.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn expandable-component1 &amp;#91;&amp;#93;
  &amp;#40;r/with-let
    &amp;#91;expanded? &amp;#40;r/atom false&amp;#41;
     value     &amp;#40;r/atom nil&amp;#41;&amp;#93;
    &amp;#91;:div
     &amp;#91;:input
      {:type :text
       :value @value
       :on-click #&amp;#40;swap! expanded? not&amp;#41;}&amp;#93;
     &amp;#91;:table&amp;gt;tbody
      {:style &amp;#40;if @expanded?
                {:position :absolute}
                {:display &amp;quot;none&amp;quot;}&amp;#41;}
      &amp;#40;for &amp;#91;row &amp;#40;range 5&amp;#41;&amp;#93;
        &amp;#91;:tr
         &amp;#40;for &amp;#91;n &amp;#40;range 5&amp;#41;&amp;#93;
           &amp;#91;:td&amp;gt;button.btn.btn-secondary
            {:on-click
             #&amp;#40;do
                &amp;#40;reset! value n&amp;#41;
                &amp;#40;reset! expanded? false&amp;#41;&amp;#41;} n&amp;#93;&amp;#41;&amp;#93;&amp;#41;&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The table is now hidden by default, and it's displayed when the user clicks the input. The table contains cells with numbers. When the user clicks a number, then the table is hidden and the input is reset to the value selected.&lt;/p&gt;&lt;p&gt;This works fine. However, the only way we can hide the table is by either picking a number or clicking on the input itself. It's not terrible, but it would be nicer if we could simply click off the table to have it go away.&lt;/p&gt;&lt;p&gt;The problem is that there is no local event the widget can use to detect that the user clicked elsewhere. So, what can we do here?&lt;/p&gt;&lt;p&gt;The solution I ended up using was to use a combination of events to detect the state of the widget. Let's see how this works below.&lt;/p&gt;&lt;p&gt;First, I added the &lt;code&gt;:on-blur&lt;/code&gt; event to the input. When the input loses focus, the table is hidden. Now if I click elsewhere on the screen the table will disappear as intended.&lt;/p&gt;&lt;p&gt;Unfortunately, this breaks the interaction with the table itself. Since now the focus goes away and I'm no longer able to select the number I want.&lt;/p&gt;&lt;p&gt;In order to get around that problem we can use the &lt;code&gt;:on-mouse-enter&lt;/code&gt; and &lt;code&gt;:on-mouse-leave&lt;/code&gt; events on the table. This way we can check if the mouse is in the table before changing the visibility.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn expandable-component &amp;#91;&amp;#93;
  &amp;#40;r/with-let
    &amp;#91;expanded? &amp;#40;r/atom false&amp;#41;
     value     &amp;#40;r/atom nil&amp;#41;
     mounse-on-table? &amp;#40;r/atom false&amp;#41;&amp;#93;
    &amp;#91;:div
     &amp;#91;:input
      {:type :text
       :value @value
       :on-click #&amp;#40;swap! expanded? not&amp;#41;
       :on-blur #&amp;#40;when-not @mounse-on-table? &amp;#40;reset! expanded? false&amp;#41;&amp;#41;}&amp;#93;
     &amp;#91;:table&amp;gt;tbody
      {:style &amp;#40;if @expanded? {:position :absolute} {:display &amp;quot;none&amp;quot;}&amp;#41;
       :on-mouse-enter #&amp;#40;reset! mounse-on-table? true&amp;#41;
       :on-mouse-leave #&amp;#40;reset! mounse-on-table? false&amp;#41;}
      &amp;#40;for &amp;#91;row &amp;#40;range 5&amp;#41;&amp;#93;
        &amp;#91;:tr
         &amp;#40;for &amp;#91;n &amp;#40;range 5&amp;#41;&amp;#93;
           &amp;#91;:td&amp;gt;button.btn.btn-secondary
            {:on-click
             #&amp;#40;do
                &amp;#40;reset! value n&amp;#41;
                &amp;#40;reset! expanded? false&amp;#41;&amp;#41;} n&amp;#93;&amp;#41;&amp;#93;&amp;#41;&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The new approach works as intended. The table will now close whenever the user clicks outside it. You can see this in action &lt;a href='http://cljsfiddle.com/#gist=639bcbe8d328da071713729a714b7f65'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Hopefully this trick will save you some time creating these types of components in Reagent.&lt;/p&gt;</description><pubDate>Fri, 20 May 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-04-28-Luminus-Workflow.html</guid><link>https://yogthos.net/posts/2016-04-28-Luminus-Workflow.html</link><title>Luminus Workflow</title><description>&lt;p&gt;I recently presented at the &lt;a href='http://2016.phillyemergingtech.com/'&gt;Philly ETE conference&lt;/a&gt;, and it was a really great experience. The conference was well organized, there were lots of great talks, and I got to meet a bunch of interesting people.&lt;/p&gt;&lt;p&gt;My &lt;a href='http://chariotsolutions.com/screencast/philly-ete-2016-2-dmitri-sotnikov-transforming-enterprise-development-clojure/'&gt;talk&lt;/a&gt; focused on the workflow using Luminus and Reagent. During the talk I built a simple app from scratch. The app illustrates how to work with a relational database, create a documented service API, and build a UI for it using Reagent. The live demo portion stats around the 11 minute mark.&lt;/p&gt;&lt;p&gt;If you're interested in my workflow using Luminus and Cursive, then I definitely recommend watching the talk.&lt;/p&gt;</description><pubDate>Thu, 28 Apr 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-04-17-state-of-web-clj-dev.html</guid><link>https://yogthos.net/posts/2016-04-17-state-of-web-clj-dev.html</link><title>The State of Clojure Web Development</title><description>&lt;p&gt;The Kickstarter for the &lt;a href='https://www.kickstarter.com/projects/1346708779/arachne-rapid-web-development-for-clojure'&gt;Arachne&lt;/a&gt; framework was just announced. I think this is very exciting, and I sincerely hope that it will be successful. There is plenty of room for frameworks in the Clojure web application domain. However, I also think that the pitch in the video severely misrepresents the current state of Clojure web development.&lt;/p&gt;&lt;h3 id="is&amp;#95;it&amp;#95;hard&amp;#95;to&amp;#95;make&amp;#95;an&amp;#95;app?"&gt;Is it hard to make an app?&lt;/h3&gt;&lt;p&gt;Luke says that the motivation for the project is that there is no simple way to put a Clojure web app together. You want to make a website quickly, but unfortunately Clojure is not well suited for this task because the lead time is just too long.&lt;/p&gt;&lt;p&gt;Luke goes as far as to say that starting a new Clojure web application with all the parts together, that's actually deployable is a one to three months process.&lt;/p&gt;&lt;p&gt;Simplifying this process is precisely the &lt;a href='https://www.youtube.com/watch?v=JKoaG4kSyxs&amp;t=14m53s'&gt;motivation&lt;/a&gt; behind &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt;. In fact, Luminus, and other frameworks such as &lt;a href='https://hoplon.io/'&gt;Hoplon&lt;/a&gt;, have been filling this exact niche for years now. While I’m not as familiar with Hoplon, I will focus on contrasting the stated goals behind Arachne and the goals for Luminus.&lt;/p&gt;&lt;p&gt;First thing I’d like to address is the claim that it takes a long time to create a web application following best practices. Creating a new Luminus app is as easy as running &lt;code&gt;lein new luminus myapp&lt;/code&gt; in the terminal. Perhaps what Luke meant was that creating an application using his preferred stack and defaults takes a long time.&lt;/p&gt;&lt;p&gt;Luminus is based on over a decade of experience working in the enterprise environment and building real world applications. It's built on top of mature libraries that are known to work well together. These are wrapped up in a template that follows the best practices, and makes it easy to create a working application that's ready for deployment out of the box.&lt;/p&gt;&lt;p&gt;Some of the things Luke lists are:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Overall structure&lt;/li&gt;&lt;li&gt;Resource lifecycle management&lt;/li&gt;&lt;li&gt;Routing&lt;/li&gt;&lt;li&gt;Content negotiation&lt;/li&gt;&lt;li&gt;HTML rendering&lt;/li&gt;&lt;li&gt;Authentication &amp; authorization&lt;/li&gt;&lt;li&gt;Validation&lt;/li&gt;&lt;li&gt;Logging&lt;/li&gt;&lt;li&gt;Testing&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;All of these are supported out of the box in Luminus.&lt;/p&gt;&lt;h3 id="what&amp;#95;about&amp;#95;beginners?"&gt;What about beginners?&lt;/h3&gt;&lt;p&gt;Another problem Luke identifies is that there needs to be a tool for beginners, or people new to the Clojure language. Once again, this is precisely the target demographic for Luminus.&lt;/p&gt;&lt;p&gt;I've literally spent years working with existing libraries, &lt;a href='https://github.com/yogthos/Selmer'&gt;creating my own&lt;/a&gt; when necessary, &lt;a href='http://www.luminusweb.net/docs'&gt;writing documentation&lt;/a&gt;, and putting things together for that express purpose. I've even written &lt;a href='https://pragprog.com/book/dswdcloj2/web-development-with-clojure-second-edition'&gt;a couple of books&lt;/a&gt; on this topic now.&lt;/p&gt;&lt;p&gt;Arachne aims to experiment with creating an easy to start with solution that will scale. Luminus is designed to scale, and it’s currently being used in production in the enterprise. It's not experimental in any way, it's an actual proven solution that exists today.&lt;/p&gt;&lt;p&gt;Luminus allows you to start fast and deploy out of the box, but it is also designed to be built on as you go. Like Arachne aims to do, Luminus already embraces modular design. It's built on top of battle tested libraries such as Ring and Compojure, but it doesn't lock you into doing things a particular way.&lt;/p&gt;&lt;p&gt;Luminus makes it trivial to swap things like the underlying HTTP server, templating engine, the database you're using, and so on. The core template provides a minimal skeleton app. This template can then be extended using hints to provide additional functionality.&lt;/p&gt;&lt;h3 id="but&amp;#95;is&amp;#95;it&amp;#95;modular?"&gt;But is it modular?&lt;/h3&gt;&lt;p&gt;Arachne has an ambitious goal to provide a way to specify the application using a data driven approach. The idea being that this makes it easier to swap different components in the existing project.&lt;/p&gt;&lt;p&gt;I’ve considered similar approaches for Luminus, but ultimately decided against that. First, I think that Ring middleware already provides an extremely powerful mechanism for injecting functionality in the request handling pipeline. This is where most of the changes will happen in your project. You might decide to swap out or change things like session handling middleware as your project evolves.&lt;/p&gt;&lt;p&gt;However, my experience is that in most cases it’s not possible to simply swap a component such as the database for a different one without having to change some code in the application.&lt;/p&gt;&lt;p&gt;For example, if I switch the templating engine, then I have to update my HTML templates. When I switch a database from SQL to Datomic, I have to rewrite the queries and the business logic. That’s where the most of effort will end up being spent. &lt;/p&gt;&lt;p&gt;That said, the code that deals with any particular component in Luminus is minimal by design. So, the vast majority of the code you’d have to change would be the code that you’ve written yourself.&lt;/p&gt;&lt;p&gt;The one place I found it to be possible to provide swappable components is the underlying HTTP server. Luminus provides wrapper libraries for all the popular servers, and it’s possible to swap them out by simply changing the dependency in the project.&lt;/p&gt;&lt;p&gt;I think it would be possible to build things like authentication and authorization modules that are swappable. However, a generic solution is necessarily more complex than a focused one. A component that can be used in many different situations will always be more complex than one that solves a specific problem.&lt;/p&gt;&lt;p&gt;For this reason, I firmly believe that such design decisions should be left up to the user. The libraries should provide focused functionality, while the user decides how to put them together in a way that makes sense for their project.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;At the end of the day, Luminus isn’t based just on my experience, but also that of the contributors and the users over the years. Arachne will be informed by Luke’s experience and that necessarily means that it will provide a new and interesting way to put together Clojure web applications.&lt;/p&gt;&lt;p&gt;Overall, I think it will be great to see a new web framework for Clojure. There is plenty of room for alternatives to Luminus, and Arachne could explore many areas that aren't the focus for Luminus at the moment. Therefore, I wholeheartedly urge you to support the Kickstarter so that we can have more choices for Clojure web development.&lt;/p&gt;</description><pubDate>Sun, 17 Apr 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-02-22-LuminusEmbracingHugSQL.html</guid><link>https://yogthos.net/posts/2016-02-22-LuminusEmbracingHugSQL.html</link><title>Luminus embraces HugSQL</title><description>&lt;p&gt;There are lots of Clojure libraries available for working with SQL. The core libraries that provide the low level functionality are &lt;a href='https://github.com/clojure/java.jdbc'&gt;clojure.java.jdbc&lt;/a&gt; and the more recent &lt;a href='https://github.com/funcool/clojure.jdbc'&gt;clojure.jdbc&lt;/a&gt;. Some of the more popular libraries built on top of them are &lt;a href='https://github.com/korma/Korma'&gt;Korma&lt;/a&gt;, &lt;a href='https://github.com/jkk/honeysql'&gt;Honey SQL&lt;/a&gt;, and &lt;a href='https://github.com/krisajenkins/yesql'&gt;Yesql&lt;/a&gt;.   &lt;/p&gt;&lt;p&gt;I've been a huge fan of the approach that Yesql takes since it was released. Every time I've worked with a DSL for SQL, I've found that I'd always run into cases where I knew exactly what to do if I was writing plain SQL, but I couldn't find a clean way to express using the abstraction on top of it. Since Yesql approach lets you keeps your SQL as SQL the problem largely goes away.&lt;/p&gt;&lt;p&gt;Luminus has been using Yesql since it came out and I think it made the framework much more approachable. Unfortunately, Yesql doesn't appear to be actively developed, and I found myself falling back to using clojure.java.jdbc directly for things like &lt;a href='https://github.com/krisajenkins/yesql/issues/51'&gt;batch inserts&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Another problem from Luminus perspective is that Yesql API defines query functions directly. Luminus uses &lt;a href='https://github.com/luminus-framework/conman'&gt;conman&lt;/a&gt; for connection management, and it creates its own connection-aware functions. This required an ugly hack of using a shadow namespace for interning the functions generated by Yesql.&lt;/p&gt;&lt;p&gt;I recently learned about the &lt;a href='http://www.hugsql.org/'&gt;HugSQL&lt;/a&gt; library that is inspired by Yesql, and addresses all the issues I've run into using it. The official site does a good job enumerating the &lt;a href='http://www.hugsql.org/#faq-yesql'&gt;major differences&lt;/a&gt; from Yesql. Some of the highlights for HugSQL are:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='http://www.hugsql.org/#using-snippets'&gt;snippets&lt;/a&gt; that facilitate composable queries&lt;/li&gt;&lt;li&gt;support for &lt;a href='http://www.hugsql.org/#using-insert'&gt;multi-row inserts&lt;/a&gt;&lt;/li&gt;&lt;li&gt;supports &lt;a href='http://www.hugsql.org/#adapter'&gt;multiple backends&lt;/a&gt; such as clojure.java.jdbc and clojure.jdbc&lt;/li&gt;&lt;li&gt;great documentation&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The latest version of HugSQL provides an API that returns a map of query functions keyed on their names as well as the ability to define the functions directly.&lt;/p&gt;&lt;p&gt;I think this is a very useful feature even if you're not using conman or Luminus. Having a map of the query functions allows the user to decide what they want to do with them explicitly. For example, you're able to do things like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def queries &amp;#40;hugsql.core/map-of-db-fns &amp;quot;queries.sql&amp;quot;&amp;#41;

&amp;#40;defn get-user &amp;#91;db opts&amp;#93;
  &amp;#40;&amp;#40;-&amp;gt; queries :get-user :fn&amp;#41; db opts&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id="yesql&amp;#95;vs&amp;#95;hugsql"&gt;Yesql vs HugSQL&lt;/h2&gt;&lt;p&gt;Let's take a look at the basic usage of HugSQL and differences from Yesql.&lt;/p&gt;&lt;p&gt;The core syntax in HugSQL is quite similar to Yesql. Both Yesql and HugSQL use comments with a special format to provide the metadata for generating the functions to work with queries.&lt;/p&gt;&lt;h4 id="yesql"&gt;Yesql&lt;/h4&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- name: create-user!
-- creates a new user record
INSERT INTO users
&amp;#40;id, pass&amp;#41;
VALUES &amp;#40;:id, :pass&amp;#41;

-- name: get-users
-- retrieve all users
SELECT &amp;#42; FROM users

-- name: get-user
-- retrieve a user given the id.
SELECT &amp;#42; FROM users
WHERE id = :id
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Yesql uses the &lt;code&gt;-- name: fn-name&lt;/code&gt; syntax to specify the function name, the comment below the function name is implicitly used as the doc for the function. The &lt;code&gt;!&lt;/code&gt; at the end of the function name is used as a convention to indicate that it mutates the data. The query parameter placeholders are identified using the &lt;code&gt;:&lt;/code&gt; prefix.&lt;/p&gt;&lt;h4 id="hugsql"&gt;HugSQL&lt;/h4&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- :name create-user! :! :n
-- :doc creates a new user record
INSERT INTO users
&amp;#40;id, pass&amp;#41;
VALUES &amp;#40;:id, :pass&amp;#41;

-- :name get-users :? :&amp;#42;
-- :doc retrieve all users
SELECT &amp;#42; FROM users

-- :name get-user :? :1
-- :doc retrieve a user given the id
SELECT &amp;#42; FROM users
WHERE id = :id
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The HugSQL version uses the &lt;code&gt;-- :name&lt;/code&gt; syntax instead that mirrors the Clojure keyword syntax. The function name is followed by two additional flags. The first flag indicates the SQL command type and the second indicates the result.&lt;/p&gt;&lt;p&gt;This provides more flexibility for handling the results. For example, the &lt;code&gt;get-users&lt;/code&gt; query indicates that it selects multiple records, while the &lt;code&gt;get-user&lt;/code&gt; indicates that it selects exactly one record. This helps document the intent of the query and cuts down on boilerplate, as you'd have to write a wrapper otherwise that gets the first result from the query.&lt;/p&gt;&lt;h4 id="command&amp;#95;flags"&gt;command flags&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;:query&lt;/code&gt; or &lt;code&gt;:?&lt;/code&gt; - query with a result-set (default)&lt;/li&gt;&lt;li&gt;&lt;code&gt;:execute&lt;/code&gt; or &lt;code&gt;:!&lt;/code&gt; - any statement&lt;/li&gt;&lt;li&gt;&lt;code&gt;:returning-execute&lt;/code&gt; or &lt;code&gt;:&amp;lt;!&lt;/code&gt; - support for &lt;code&gt;INSERT ... RETURNING&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;:insert&lt;/code&gt; or &lt;code&gt;:i!&lt;/code&gt; - support for insert and jdbc &lt;code&gt;.getGeneratedKeys&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h4 id="result&amp;#95;flags"&gt;result flags&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;:one&lt;/code&gt; or &lt;code&gt;:1&lt;/code&gt; - one row as a hash-map&lt;/li&gt;&lt;li&gt;&lt;code&gt;:many&lt;/code&gt; or &lt;code&gt;:&amp;#42;&lt;/code&gt; - many rows as a vector of hash-maps&lt;/li&gt;&lt;li&gt;&lt;code&gt;:affected&lt;/code&gt; or &lt;code&gt;:n&lt;/code&gt; - number of rows affected (inserted/updated/deleted)&lt;/li&gt;&lt;li&gt;&lt;code&gt;:raw&lt;/code&gt; - passthrough an untouched result (default)&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;In HugSQL, all the comments that represent metadata start with a key describing the type of metadata. In the examples above, the doc string is explicitly specified using the &lt;code&gt;-- :doc&lt;/code&gt; prefix.&lt;/p&gt;&lt;p&gt;HugSQL also supports additional syntax within its queries. For example, if we wanted to insert multiple records using a single query, then we could use a vector of records as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- :name add-users! :! :n
-- :doc add multiple users
INSERT INTO users
&amp;#40;id, pass&amp;#41;
VALUES :t&amp;#42;:users
&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;add-users! db {:users
                &amp;#91;&amp;#91;&amp;quot;bob&amp;quot; &amp;quot;Bob&amp;quot;&amp;#93;
                 &amp;#91;&amp;quot;alice&amp;quot; &amp;quot;Alice&amp;quot;&amp;#93;&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The syntax for for in-list queries is also a bit different from Yesql. The SQL query uses the &lt;code&gt;:v&amp;#42;&lt;/code&gt; flag to indicate the value list parameter.&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- :name find-users :? :&amp;#42;
-- :doc find users with a matching ID
SELECT &amp;#42;
FROM users
WHERE id IN &amp;#40;:v&amp;#42;:ids&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The function parameters will now consist of a map with the key &lt;code&gt;:ids&lt;/code&gt; that points to a vector of ids that we would like to match on.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;find-users db {:ids &amp;#91;&amp;quot;foo&amp;quot; &amp;quot;bar&amp;quot; &amp;quot;baz&amp;quot;&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, the syntactic differences for basic queries are very minor. I've migrated a number of projects to HugSQL already, and found the process to be completely painless.&lt;/p&gt;&lt;p&gt;I haven't covered the advanced features of HugSQL, but I highly recommend looking over the official documentation to see what's available.&lt;/p&gt;</description><pubDate>Mon, 22 Feb 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-01-19-ContrastingComponentAndMount.html</guid><link>https://yogthos.net/posts/2016-01-19-ContrastingComponentAndMount.html</link><title>Contrasting Component and Mount</title><description> &lt;p&gt;There was a recent wave of discussions on pros and cons of using Component and Mount approaches to state management. Both libraries aim to provide a clean way to manage stateful resources in the application. However, each one takes a very different approach.&lt;/p&gt;&lt;p&gt;Component is the currently accepted way to manage state, and it works well when you structure your application around it. However, it does require certain trade-offs in order to make the most of it. Let's take a look at some of the reasons you may wish to choose Mount over Component for your project.&lt;/p&gt;&lt;h3 id="managing&amp;#95;the&amp;#95;state&amp;#95;with&amp;#95;component"&gt;Managing the State with Component&lt;/h3&gt;&lt;p&gt;Component uses the dependency injection approach to managing stateful resources in the application. A system map is used to track all the components and their relationships. This map is then passed around the application explicitly, and used to provide access to the resources.&lt;/p&gt;&lt;p&gt;This approach encourages coupling between the code managing the resources and the business logic. A common pattern is to pass the component system around the application. The system is injected from the top level, and then functions pick parts of the system to pass down until they're eventually used by a function that relies on a particular resource.&lt;/p&gt;&lt;p&gt;One side-effect of this design is that it becomes impossible to test any part of the application without having the resources available. Therefore, if we wish to run tests in the REPL, then we need to instantiate a separate system map using the test resources. This problem makes it important to be able to create multiple instances of the components at runtime.&lt;/p&gt;&lt;h3 id="component&amp;#95;and&amp;#95;the&amp;#95;repl"&gt;Component and the REPL&lt;/h3&gt;&lt;p&gt;Since Component is based on protocols it doesn't play well with the REPL workflow, as changes to &lt;code&gt;defrecord&lt;/code&gt; do not affect the instances that have already been created. The whole app needs to be restarted in order to make sure that the REPL is still in a good state.&lt;/p&gt;&lt;p&gt;This problem is discussed in detail by Stuart Sierra in his post on the &lt;a href='http://thinkrelevance.com/blog/2013/06/04/clojure-workflow-reloaded'&gt;reloaded workflow&lt;/a&gt;. I find that the reloaded workflow used with Component is much closer to TDD than the traditional Lisp style REPL driven workflow.&lt;/p&gt;&lt;p&gt;However, one of the advantages of working with a language like Clojure is that we shouldn't need to run tests all that often. Since development is primarily done using the REPL, we should have a good idea of what the code is doing while we're working on it.&lt;/p&gt;&lt;p&gt;RDD provides a very tight feedback loop. I can develop the features interactively, then create the tests based on the REPL session once the code is doing what I need.&lt;/p&gt;&lt;p&gt;There are only a handful of situations where I find it necessary to run the full test suite. I run tests before I commit code, I run tests on the CI server, but I don't find it necessary to rerun tests any time I write a bit of code during development. I certainly shouldn't have to reload the whole app for changes to take effect.&lt;/p&gt;&lt;p&gt;I like the guard rail metaphor Rich Hickey used in his &lt;a href='http://www.infoq.com/presentations/Simple-Made-Easy'&gt;Simple Made Easy&lt;/a&gt; talk:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;"I can make changes 'cause I have tests!  Who does that?!  Who drives their car around banging against the guard rails saying, "Whoa!  I'm glad I've got these guard rails!" &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;This is a good reminder that the tests are primarily a sanity check. We should have confidence in our code because we understand it and are able to reason about it.&lt;/p&gt;&lt;p&gt;To facilitate understanding, most code in the application should be pure, and we shouldn't have to rely on any external resources to test such code. I think that it helps to treat core business logic as you would a library. It should be completely agnostic about where the data is coming from and where it's going.&lt;/p&gt;&lt;p&gt;However, Component encourages a different kind of design where business logic ends up being reliant on the resources. In this situation, it's no longer possible to test the business logic in isolation.&lt;/p&gt;&lt;p&gt;Finally, any functions that takes the system map as a parameter are invariably tied to it. This is at odds with treating functions as core reusable building blocks.&lt;/p&gt;&lt;h3 id="the&amp;#95;mount&amp;#95;approach"&gt;The Mount Approach&lt;/h3&gt;&lt;p&gt;Mount takes the approach of encapsulating stateful resources using namespaces. This leads to a natural separation between the code that deals with state from the pure core of the application logic.&lt;/p&gt;&lt;p&gt;When the core is kept pure, then it can be safely tested in isolation without having to provide any mock resources to it. This also makes the code reusable out of the box.&lt;/p&gt;&lt;p&gt;Mount makes it trivial to integrate into existing applications. The app doesn't need to be designed up front to take advantage of it, as it does with Component.&lt;/p&gt;&lt;p&gt;Since Mount doesn't rely on protocols, it doesn't impact the REPL driven workflow. There's no need for an elaborate setup to facilitate reloading the whole application any time a change is made.&lt;/p&gt;&lt;p&gt;The primary disadvantages of Mount are that it's not possible to create multiple instances of a resource, and that we have to be mindful not to couple namespaces representing resources to the business logic.&lt;/p&gt;&lt;p&gt;Conceptually, most resources in the application are singletons by their very nature. When we have a database connection or a queue, there is precisely one external resource that we're working with.&lt;/p&gt;&lt;p&gt;As I illustrated earlier, the primary reason for having multiple instances of a resource is testing. Mount provides a simple solution for running tests with alternate implementations as described in its &lt;a href='https://github.com/tolitius/mount#swapping-alternate-implementations'&gt;documentation&lt;/a&gt;. This facilitates practically the same workflow as Component, where an instance of the resource can be swapped out with another for testing. However, the bigger advantage is that we no longer need to have resources available to test majority of the code in the first place.&lt;/p&gt;&lt;p&gt;Another argument is that you may have different instances of the same type of resource. For example, an application might use multiple queues that all have the same API. In this case, we can use &lt;code&gt;defrecord&lt;/code&gt; to define the class representing the API for the queue. We'll then manage the lifecycle of each instance using &lt;code&gt;defstate&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;While we do have to be mindful of our design when using Mount, the same is true for Component as well. For example, nothing stops us from putting the Component system in a var that's referenced directly. The same reasoning we use to avoid doing that should be used when working with Mount as well.&lt;/p&gt;&lt;p&gt;In general, I see very few downsides to using Mount and I see a lot of practical benefits, some of which I've outlined above.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;I think that both Component and Mount have their own sets of trade-offs. Component is a framework that requires the application to be structured around it. Conversely, it necessitates a TDD style workflow to work with it effectively.&lt;/p&gt;&lt;p&gt;On the other hand, Mount is not prescriptive about the workflow or application structure. I think this makes it a more flexible solution that's a great fit for many kinds of applications. The flip side is that we have to be more careful about how we structure the application as Mount is agnostic regarding the architecture.&lt;/p&gt;</description><pubDate>Tue, 19 Jan 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2016-01-01-ClojureWebDev2.html</guid><link>https://yogthos.net/posts/2016-01-01-ClojureWebDev2.html</link><title>Web Development with Clojure 2nd Edition</title><description>&lt;h3 id="beta&amp;#95;release&amp;#95;update"&gt;Beta Release Update&lt;/h3&gt;&lt;p&gt;Unfortunately, it looks like there's been a bit of editorial delay and we missed the 13th release date. The new date is set for the second of February. Apologies to everybody who's waiting for the release. &lt;/p&gt;&lt;hr/&gt;&lt;p&gt;I'm glad to report that the second edition of Web Development with Clojure is just around the corner. The beta release is planned for January the 13th, and then I'm hoping to have the final release shortly after. The second edition took a bit longer than I anticipated, but I think the wait will be worth it.&lt;/p&gt;&lt;h3 id="what&amp;#95;to&amp;#95;expect"&gt;What to Expect&lt;/h3&gt;&lt;p&gt;The primary goal of the book is to provide a solid introduction to the world of Clojure web development. Clojure community is growing rapidly and most new users come from languages such as Java, Ruby, and Python.&lt;/p&gt;&lt;p&gt;My aim is to illustrate how to build typical web applications using Clojure in a style that's friendly to those who come from using a mainstream language. In order to keep the material accessible, I deliberately chose to focus on the core concepts and avoid some of the more advanced topics. Conversely, if you're already familiar with Clojure and would like to get into web development then the book will serve as a great introduction.&lt;/p&gt;&lt;p&gt;The first edition of my book came out at the time when Clojure web stack was in a great deal of flux. &lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt; micro-framework just got deprecated, Cognitect announced &lt;a href='https://github.com/pedestal/pedestal'&gt;Pedestal&lt;/a&gt;, and ClojureScript was in its infancy. It was hard to predict where things would go from there.&lt;/p&gt;&lt;p&gt;Much has changed in the past year in Clojure web ecosystem, and the second edition of the book reflects that. While the first edition was fairly unopinionated and gave a broad overview of different libraries, the new version primarily focuses on the &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; stack.&lt;/p&gt;&lt;p&gt;Majority of the tools and libraries I cover are the ones I've used professionally to build real world applications. This naturally means that there is an inherent bias towards my workflow and the way I like to build applications. On the other hand, if you're new to building Clojure web applications it's helpful to learn using a particular workflow that you can adjust to your needs as you get comfortable.&lt;/p&gt;&lt;p&gt;Just like the first edition, the book is based around projects that illustrate how to accomplish different tasks in a typical web app. Each chapter introduces a particular concept and gets the reader to work through it by building a project from scratch. By the end of the book the reader should be comfortable writing many typical web applications using Clojure and have the background to explore further on their own.&lt;/p&gt;&lt;h3 id="topics&amp;#95;covered"&gt;Topics Covered&lt;/h3&gt;&lt;p&gt;The book will consist of the following chapter:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;h4&gt;Getting Your Feet Wet&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;takes the reader through setting up the environment and building a simple application using Luminus&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Clojure Web Stack&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;takes a step back and looks at Ring and Compojure in detail&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Luminus Architecture&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;provides an overview of the Luminus template and ways to organize your projects&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Add ClojureScript&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;illustrates how to convert the applications from the first chapter to a SPA style app using Reagent&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Real-time Messaging With Websockets&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;illustrates how to use Websockets in a Clojure/Script application using Sente&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Writing RESTful Web Services&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;covers the basics of using the &lt;a href='https://github.com/metosin/compojure-api'&gt;compojure-api&lt;/a&gt; library to provide &lt;a href='http://swagger.io/'&gt;Swagger&lt;/a&gt; style service API&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Database Access&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;introduces clojure.java.jdbc and Yesql, and how to use these libraries to work with a relational database&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Picture Gallery&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;ties all the above concepts together by working through a picture gallery application&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Finishing Touches&lt;/h4&gt;&lt;ul&gt;&lt;li&gt;covers testing and packaging the application for deployment&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The book will also contain a number of appendices that deal with topics such as NoSQL databases.&lt;/p&gt;&lt;h3 id="what's&amp;#95;not&amp;#95;covered"&gt;What's Not Covered&lt;/h3&gt;&lt;p&gt;As Clojure web ecosystem continues to evolve, many new tools and libraries, such as the &lt;a href='https://github.com/juxt'&gt;JUXT stack&lt;/a&gt;, have appeared just this year. While I would love to cover them all, that simply wouldn't fit the goals I set for this project.&lt;/p&gt;&lt;p&gt;One notable omission from the book is &lt;a href='https://github.com/omcljs/om'&gt;Om Next&lt;/a&gt;. First, I'd like to say that it's a fantastic library and I think very highly of it as well as the ideas behind it. However, I simply haven't used it in anger as I have Reagent. I also think that Reagent is the simpler of the two libraries and therefore more suitable for beginners. I hope that the book will provide a solid foundation for the reader to explore libraries like Om on their own.&lt;/p&gt;</description><pubDate>Fri, 01 Jan 2016 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-12-26-AOTGotchas.html</guid><link>https://yogthos.net/posts/2015-12-26-AOTGotchas.html</link><title>Trouble with AOT</title><description> &lt;p&gt;I recently ran into an interesting issue when I added the &lt;a href='https://github.com/fzakaria/slf4j-timbre'&gt;slf4j-timbre&lt;/a&gt; dependency to a project. As soon as the dependency was added the project would fail to build and I'd see the following error:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Caused by: java.io.FileNotFoundException: Could not locate clojure/tools/reader/impl/ExceptionInfo&amp;#95;&amp;#95;init.class or clojure/tools/reader/impl/ExceptionInfo.clj on classpath.
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;slf4j-timbre&lt;/code&gt; library does not depend on &lt;code&gt;clojure.tools.reader&lt;/code&gt;, and at first glance there's nothing in it that should've caused problems. I did notice that the library depends on &lt;code&gt;com.taoensso/timbre 4.1.4&lt;/code&gt; that in turn depends on &lt;code&gt;com.taoensso/encore 2.18.0&lt;/code&gt;, and it uses on an older version of &lt;code&gt;clojure.tools.reader&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;At this point I thought the solution would be simple. I'd just include the latest version of &lt;code&gt;encore&lt;/code&gt; and everything should work fine. However that didn't turn out to be the case.&lt;/p&gt;&lt;p&gt;I decided to take another look at &lt;code&gt;slf4j-timbre&lt;/code&gt; to see what else might be happening. At this point I noticed that it uses &lt;code&gt;:aot :all&lt;/code&gt; in the project configuration. This causes the library to be compiled to Java classes as opposed to being distributed at source. This is necessary since the library has to implement the SLF4J interface and has to provide a Java class in its implementation.&lt;/p&gt;&lt;p&gt;When the namespace that references &lt;code&gt;Timbre&lt;/code&gt; is compiled then any namespaces it depends on are also compiled and packaged in the &lt;code&gt;jar&lt;/code&gt;. These compiled classes will take precedence over the source dependencies when the library is included in the project.&lt;/p&gt;&lt;p&gt;So, even though I was explicitly including the version of &lt;code&gt;encore&lt;/code&gt; that uses the latest &lt;code&gt;clojure.tools.reader&lt;/code&gt;, the compiled version packaged in &lt;code&gt;slf4j-timbre&lt;/code&gt; would end up being used causing the exception above. As far as I can tell there's no way to overwrite these in the project configuration.&lt;/p&gt;&lt;h3 id="implications&amp;#95;for&amp;#95;luminus"&gt;Implications for Luminus&lt;/h3&gt;&lt;p&gt;Unfortunately, Luminus dependencies require both a SLF4J compliant logger and the latest &lt;code&gt;clojure.tools.reader&lt;/code&gt;. While I think &lt;code&gt;Timbre&lt;/code&gt; is an excellent library, it's just not the right fit at the moment.&lt;/p&gt;&lt;p&gt;Luckily, &lt;a href='https://github.com/clojure/tools.logging'&gt;clojure.tools.logging&lt;/a&gt; provides a SLF4J compliant API for Clojure logging. The latest release of Luminus uses &lt;code&gt;clojure.tools.logging&lt;/code&gt; along with the &lt;a href='https://logging.apache.org/log4j/2.x/'&gt;log4j&lt;/a&gt; library as the default logging implementation. It's a mature library that has excellent performance and provides a &lt;a href='https://logging.apache.org/log4j/2.x/manual/appenders.html'&gt;plethora of logging appenders&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Since &lt;code&gt;log4j&lt;/code&gt; can be configured using a properties file, it fits the Luminus approach of using 12 factor style configuration. The library will look for a file called &lt;code&gt;log4j.properties&lt;/code&gt; on the classpath to get its default configuration. Luminus packages this file in the &lt;code&gt;resources&lt;/code&gt; folder with the following configuration:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;### stdout appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=&amp;#91;%d&amp;#93;&amp;#91;%p&amp;#93;&amp;#91;%c&amp;#93; %m%n

### rolling file appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./log/app-name.log

log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=20

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=&amp;#91;%d&amp;#93;&amp;#91;%p&amp;#93;&amp;#91;%c&amp;#93; %m%n

### root logger sets the minimum logging level
### and aggregates the appenders
log4j.rootLogger=DEBUG, stdout, R
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see the configuration is very straight forward, it's also &lt;a href='https://logging.apache.org/log4j/2.x/manual/configuration.html#Properties'&gt;well documented&lt;/a&gt;. The default configuration can be overridden at runtime by setting the &lt;code&gt;:log-config&lt;/code&gt; environment variable. You can now create a custom logging configuration on the target system and then set an environment variable to point to it as seen below:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;export LOG&amp;#95;CONFIG=prod-log.properties
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I think that the new approach provides a solid solution for most situations with minimal changes from the existing behavior.&lt;/p&gt;&lt;h3 id="final&amp;#95;thoughts"&gt;Final Thoughts&lt;/h3&gt;&lt;p&gt;The moral of the story is that you want to be very careful when using AOT in libraries. Whenever possible it is best to avoid it, and if you do have to use it then try to find the minimal subset of the namespaces that absolutely have to be compiled.&lt;/p&gt;</description><pubDate>Sat, 26 Dec 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-12-05-LuminusComponents.html</guid><link>https://yogthos.net/posts/2015-12-05-LuminusComponents.html</link><title>Managing State in Luminus</title><description>&lt;h3 id="the&amp;#95;problem&amp;#95;of&amp;#95;state"&gt;The problem of State&lt;/h3&gt;&lt;p&gt;Most real-world applications will interact with external resources such as databases. Typically, in order to interact with a database we have to initialize a connection when our application starts, use this connection to access the database, and then tear it down when the application shuts down. &lt;/p&gt;&lt;p&gt;In some cases these resources may even depend on one another. We may be getting configuration from one resource and then using it to initialize another. A large application may have a number of different resources that are interdependent and have to be coordinated.&lt;/p&gt;&lt;h4 id="using&amp;#95;component"&gt;Using Component&lt;/h4&gt;&lt;p&gt;One popular approach to addressing this problem is to use the &lt;a href='https://github.com/stuartsierra/component'&gt;component&lt;/a&gt; library. Component creates a graph that describes all the resources and then we pass it around to any functions that rely on them. This library was originally developed to support the &lt;a href='http://thinkrelevance.com/blog/2013/06/04/clojure-workflow-reloaded'&gt;reloaded workflow&lt;/a&gt; advocated by Stuart Sierra.&lt;/p&gt;&lt;p&gt;The advantage of this approach is that it allows us to keep the application code completely stateless and lets us inject the stateful resources at runtime. The two main benefits are that the core application logic remains pure and we can easily provide mock resources to it for testing. If you're interested in learning more about building applications based on component I recommend checking out the &lt;a href='https://github.com/weavejester/duct'&gt;Duct&lt;/a&gt; framework by James Reeves that I covered in an earlier &lt;a href='http://yogthos.net/posts/2015-10-01-Compojure-API.html'&gt;post&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I think that's a fine approach for building applications, but I also think that there are tradeoffs that one has to buy into when using component.&lt;/p&gt;&lt;p&gt;Component introduces simplicity by providing a formal separation between pure and impure code, but also adds complexity in terms of the structure of the application.&lt;/p&gt;&lt;p&gt;The application has to keep a global component graph that tracks the relationships between the resources and pass it explicitly to any code that needs to interact with them. My experience is that this introduces boilerplate and indirection making the overall application structure more complex. Component also requires the developer to adopt a specific workflow to take full advantage of it.&lt;/p&gt;&lt;p&gt;Component can also be rather confusing for beginners and I have avoided using it in Luminus for that reason. However, the problems that component addresses are real and if we're not using component we still need a way to address them. For this reason Luminus uses the &lt;a href='https://github.com/tolitius/mount'&gt;mount&lt;/a&gt; library to orchestrate the stateful resources in the application.&lt;/p&gt;&lt;h4 id="using&amp;#95;mount"&gt;Using Mount&lt;/h4&gt;&lt;p&gt;Unlike component, mount does not require us to structure the application in a specific way or to adopt a particular workflow to use it.&lt;/p&gt;&lt;p&gt;The library leverages the existing namespace hierarchy to resolve the resource dependencies. This approach obviates the need to keep a separate component graph and pass it all over the application.&lt;/p&gt;&lt;p&gt;Mount uses the &lt;code&gt;defstate&lt;/code&gt; macro to define stateful resources. The macro allows specifying the code to initialize and tear down the resource by associating it with the &lt;code&gt;:start&lt;/code&gt; and &lt;code&gt;:stop&lt;/code&gt; keys. In case of a connection we would associate the code that initializes the connection in the &lt;code&gt;:start&lt;/code&gt; key and the code that tears it down with the &lt;code&gt;:stop&lt;/code&gt; key respectively.&lt;/p&gt;&lt;p&gt;Mount will look for any namespaces that define states with &lt;code&gt;defstate&lt;/code&gt; and and compile a set of stateful resources based on that. The resources are started and stopped based on the order of reference of their namespaces.&lt;/p&gt;&lt;p&gt;Mount system is started by calling &lt;code&gt;mount.core/start&lt;/code&gt; and stopped using &lt;code&gt;mount.core/stop&lt;/code&gt;. This ensures that the lifecycle of the resources is managed in automated fashion and their relationships are all accounted for.&lt;/p&gt;&lt;p&gt;Like component, mount &lt;a href='https://github.com/tolitius/mount#the-importance-of-being-reloadable'&gt;supports the reloaded workflow&lt;/a&gt; and even provides ways to restart parts of the application. Mount also supports &lt;a href='https://github.com/tolitius/mount#swapping-alternate-implementations'&gt;swapping in alternate implementations&lt;/a&gt; for the resources. This provides a simple way to run tests with mock resources without having to restart the REPL.&lt;/p&gt;&lt;h3 id="structuring&amp;#95;the&amp;#95;application"&gt;Structuring the Application&lt;/h3&gt;&lt;p&gt;While mount provides us with a solution for managing the lifecycle of the components, we still need a way to ensure that our application is easy to reason about. Since mount does not enforce the separation between pure and impure code, we have to structure the application in such a way that side effects aren't mixed into the core application logic.&lt;/p&gt;&lt;h4 id="encapsulating&amp;#95;resources"&gt;Encapsulating Resources&lt;/h4&gt;&lt;p&gt;The approach I like to take in my applications is to keep the code that interacts with external resources at the edges of the application. The core business logic should be pure and testable, while anything that deals with side effects and external resources should be pushed to a thin layer around it.&lt;/p&gt;&lt;p&gt;I also find it useful to localize resource management in order to reduce coupling between components. For example, when I'm dealing with a database resource I'll create a namespace to manage it. This namespace will be responsible for handling the connection lifecycle internally and providing the connection to the functions defined in it.&lt;/p&gt;&lt;p&gt;Such a namespace provides an API for interacting with the resource for the rest of the application. Any functions calling this API do not have to be aware of its internal implementation.&lt;/p&gt;&lt;p&gt;My experience is that this approach allows compartmentalizing the application into self-contained components that can be reasoned about individually. When I update the internal implementation of a particular component the rest of the application does not need to be aware of the change.&lt;/p&gt;&lt;p&gt;An example of this would be changing the underlying resource. We may start writing the application by using a database directly, then realize that the functionality can be extracted into a shared service. When the mechanics of communicating with an external resource are internal to the component we can safely update it to use the new type of resource without affecting the rest of the application.&lt;/p&gt;&lt;h4 id="organizing&amp;#95;the&amp;#95;components"&gt;Organizing the Components&lt;/h4&gt;&lt;p&gt;The workflows in web applications are typically driven by the client requests. Since requests will often require interaction with a resource, such as a database, we will generally have to access that resource from the route handling the request. In order to isolate the stateful code we should have our top level functions deal with managing the side effects.&lt;/p&gt;&lt;p&gt;Consider a concrete example. Let's say we have a route that facilitates user authentication. The client will supply the username and the password in the request. The route will have to pull the user credentials from the database and compare these to the ones supplied by the client. Then a decision is made whether the user logged in successfully or not and its outcome communicated back to the client.&lt;/p&gt;&lt;p&gt;In this workflow, the code that deals with the external resources should be localized to the namespace that provides the route and the namespace that handles the database access.&lt;/p&gt;&lt;p&gt;The route handler function will be responsible for calling the function that fetches the credentials from the database. The code that determines whether the password and username match represents the core business logic. This code should be pure and accept the supplied credentials along with those found in the database explicitly. This structure can be seen in the diagram below.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;            pure code
+----------+
| business |
|  logic   |
|          |
+-----+----+
      |
------|---------------------
      |     stateful code
+-----+----+   +-----------+
|  route   |   |           |
| handlers +---+  database |
|          |   |           |
+----------+   +-----------+
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Keeping the business logic pure ensures that we can reason about it and test it without considering the external resources. Meanwhile the code that deals with side effects is pushed to the top making it easy for us to manage it.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;Clojure makes it easy to structure the application in such a way that the core of the application logic is kept pure. Doing this is a very good practice and will help you keep your applications manageable as they continue to grow. While it's possible to formalize the handling of stateful resources, using libraries such as component, I personally have not found this to be necessary in my applications.&lt;/p&gt;&lt;p&gt;I hope this post provides a bit of an insight into how Luminus based applications should be structured for long term maintainability.&lt;/p&gt;</description><pubDate>Sat, 05 Dec 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-11-28-TheSkyIsNotFalling.html</guid><link>https://yogthos.net/posts/2015-11-28-TheSkyIsNotFalling.html</link><title>The Sky Is not Falling</title><description>&lt;p&gt;A recent post by Elben Shira boldy proclaims &lt;a href='http://elbenshira.com/blog/the-end-of-dynamic-languages/'&gt;the end of dynamic languages&lt;/a&gt;. There was &lt;a href='http://pointersgonewild.com/2015/11/25/have-static-languages-won/'&gt;a great followup&lt;/a&gt; by Maxime Chevalier-Boisvert that I'd like to expand on a bit in this post.&lt;/p&gt;&lt;p&gt;I think that people often forget that programming is a human endeavor. When all is said and done what really matters is whether you enjoy working with a particular language or not. Of course, different people like different things and hence the plethora of languages available today.&lt;/p&gt;&lt;p&gt;I would not presume to tell people that the way I develop is the one true way. I've found an approach that works for me, I know I'm productive with it, and most importantly I enjoy it.&lt;/p&gt;&lt;p&gt;The truth is that this is the case for everybody else out there as well. Anybody who tells you that they found the one true way is frankly deluded. There's no empirical evidence to show that the typing discipline is the deciding factor of code quality, and everybody out there is using their own anecdotal experience to find the workflow that works for them.&lt;/p&gt;&lt;p&gt;Proponents of static typing accept its benefits as axiomatic. However, I think that's a case of putting the cart before the horse. Let's take a look at the claims from the perspective of a dynamic language user.&lt;/p&gt;&lt;h3 id="the&amp;#95;case&amp;#95;for&amp;#95;static&amp;#95;typing"&gt;The Case for Static Typing&lt;/h3&gt;&lt;p&gt;Static typing provides a way to formally track relationships in code and thus allows catching a certain class of errors at compile time. The advantage of this approach is that it becomes possible to guarantee that these types of errors cannot occur at runtime.&lt;/p&gt;&lt;p&gt;Many proponents of static typing argue that this is a common source of errors in dynamic languages and that it's not possible to write and maintain large codebases in absence of static types. It's common to see assertions such as the following:&lt;/p&gt;&lt;p&gt;&lt;a href='http://conf.researchr.org/event/POPL-2016/popl-2016-papers-is-sound-gradual-typing-dead-'&gt;Programmers have come to embrace dynamically typed languages for prototyping and delivering large and complex systems. When it comes to maintaining and evolving these systems, the lack of explicit static typing becomes a bottleneck.&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In practice, very little research has been done to determine whether this is a major source of errors for applications written in dynamic languages, and the few studies that are available don’t show anything conclusive in this regard.&lt;/p&gt;&lt;p&gt;Furthermore, there’s no evidence that real world projects written in statically typed languages produce superior results to their dynamic counterparts. In fact, some of the largest and most robust systems out there are written in dynamic languages such as Erlang:&lt;/p&gt;&lt;p&gt;&lt;a href='https://pragprog.com/articles/erlang'&gt;Erlang is used all over the world in high-tech projects where reliability counts. The Erlang flagship project (built by Ericsson, the Swedish telecom company) is the AXD301. This has over 2 million lines of Erlang.&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://pragprog.com/articles/erlang'&gt;The AXD301 has achieved a NINE nines reliability (yes, you read that right, 99.9999999%). Let’s put this in context: 5 nines is reckoned to be good (5.2 minutes of downtime/year). 7 nines almost unachievable ... but we did 9.&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Erlang is a poster child for robust and fault tolerant systems. However, plenty of large projects have been written in other dynamic languages as well. There's a good chance that a piece of software you rely on daily is written using a dynamic language and it works just fine.&lt;/p&gt;&lt;h3 id="complexity&amp;#95;inherent&amp;#95;in&amp;#95;static&amp;#95;typing"&gt;Complexity inherent in static typing&lt;/h3&gt;&lt;p&gt;Since static typing sounds like a net win on paper, the obvious questions are why many people prefer dynamic languages and why hasn't static typing been decisively shown to be more effective.&lt;/p&gt;&lt;p&gt;The main drawback of static typing is that you're required to prove what you're stating to the compiler. Anybody who has done proofs knows that stating something is always simpler than proving it. In fact, many things are very simple to state, but are notoriously difficult to prove. Fermat's last theorem is a famous example of this.&lt;/p&gt;&lt;p&gt;Baking a proof into the solution leads to incidental complexity. Once you run into limits of what the type system can easily express then you end up having to write increasingly more convoluted code to satisfy it.&lt;/p&gt;&lt;p&gt;This results in code that’s harder to understand because it compounds the complexity of the problem being solved with the complexity of expressing it using the type system. Effectively, any statement we make in our program has to be accompanied by a proof of correctness to make it possible for the compiler to verify it. The requirement of proving that the code is self-consistent is often at odds with making it simple.&lt;/p&gt;&lt;p&gt;A concrete example of this would be the use of state monad to formally represent mutation in a language like Haskell. Here's what Timothy Baldridge has to say about his experience trying to apply this pattern in Clojure when working on the &lt;a href='https://github.com/clojure/core.async'&gt;core.async&lt;/a&gt; library:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;a href='https://groups.google.com/d/msg/clojure/wccacRJIXvg/tFAxZBuO0wMJ'&gt;When I first wrote the core.async go macro I based it on the state monad. It seemed like a good idea; keep everything purely functional. However, over time I've realized that this actually introduces a lot of incidental complexity. And let me explain that thought.&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;&lt;a href='https://groups.google.com/d/msg/clojure/wccacRJIXvg/tFAxZBuO0wMJ'&gt;What are we concerned about when we use the state monad, we are shunning mutability. Where do the problems surface with mutability? Mostly around backtracking (getting old data or getting back to an old state), and concurrency.&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;&lt;a href='https://groups.google.com/d/msg/clojure/wccacRJIXvg/tFAxZBuO0wMJ'&gt;In the go macro transformation, I never need old state, and the transformer isn't concurrent. So what's the point? Recently I did an experiment that ripped out the state monad and replaced it with mutable lists and lots of atoms. The end result was code that was about 1/3rd the size of the original code, and much more readable.&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;&lt;a href='https://groups.google.com/d/msg/clojure/wccacRJIXvg/tFAxZBuO0wMJ'&gt;So more and more, I'm trying to see mutability through those eyes: I should reach for immutable data first, but if that makes the code less readable and harder to reason about, why am I using it?&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;In a language that forces us to use a particular formalism to represent this problem there would be no alternative solution. While the resulting code would be provably correct, it would be harder for the developer to reason about its intent. Therefore, it's difficult to say whether it's correct in any meaningful sense.&lt;/p&gt;&lt;p&gt;Ultimately, a human needs to be able to understand what the code is doing and why. The more complexity is layered on top of the original problem the more difficult it becomes to tell what purpose the code serves.&lt;/p&gt;&lt;p&gt;As another example, let’s consider what we would need to understand to read an HTTP request using a Haskell web framework such as &lt;a href='https://github.com/scotty-web/scotty'&gt;Scotty&lt;/a&gt;. We'll quickly run into &lt;code&gt;ScottyM&lt;/code&gt; type that's defined as &lt;code&gt;type ScottyM = ScottyT Text IO&lt;/code&gt;. To use it effectively we need to understand the &lt;code&gt;ScottyT&lt;/code&gt;. It in turn requires understanding the &lt;code&gt;ReaderT&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Understanding &lt;code&gt;ReaderT&lt;/code&gt; relies on understanding of monads, monad transformers and the &lt;code&gt;Reader&lt;/code&gt; monad. Meanwhile, to understand the &lt;code&gt;Reader&lt;/code&gt; we have to know about functors and applicatives. To understand these we have to understand higher kinded types and constructor classes. This leads us to type classes, type constructors, algebraic datatypes, and so forth.&lt;/p&gt;&lt;p&gt;All of this is needed to satisfy the formalisms of the Haskell type system and is completely tangential to the problem of reading HTTP requests from a client.&lt;/p&gt;&lt;p&gt;Of course, one might argue that Haskell is at the far end of the formal spectrum. In a language with a more relaxed type system you have escape hatches such as casting and unchecked side effects.&lt;/p&gt;&lt;p&gt;However, once you go down that road then it's only a matter of degrees with how relaxed a system you're comfortable with. At this point you've already accepted that working around the type system can make your life easier.&lt;/p&gt;</description><pubDate>Sat, 28 Nov 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-11-24-Serverside-Reagent.html</guid><link>https://yogthos.net/posts/2015-11-24-Serverside-Reagent.html</link><title>Rendering Reagent on the Server using Hiccup</title><description>&lt;p&gt;I recently watched a great talk titled &lt;a href='https://www.youtube.com/watch?v=fICC26GGBpg'&gt;Optimizing ClojureScript Apps For Speed&lt;/a&gt;, where Allen Rohner discusses the benefits and hurdles of server-side rendering.&lt;/p&gt;&lt;p&gt;React supports hooking in to server generated HTML at runtime. However, since React is a JavaScript library it becomes problematic to leverage this functionality from Clojure. While the JVM provides a Js runtime with Nashorn, it's extremely slow and requires a lot of twiddling to work for even basic examples.&lt;/p&gt;&lt;p&gt;Another approach is to run an instance of Node.js and farm out React rendering to it. This avoids the limitations of Nashorn, but introduces a host of new problems described in the talk.&lt;/p&gt;&lt;p&gt;Allen then proposes an alternative approach where he implements parts of the Om API and cross-compiles the components that way. You can see how this works in his &lt;a href='https://github.com/arohner/foam'&gt;Foam&lt;/a&gt; library.&lt;/p&gt;&lt;p&gt;The main difficulty identified in the talk is in implementing a sufficient amount of Om API in order to generate HTML on the server.&lt;/p&gt;&lt;p&gt;This got me thinking about what it would take to leverage this approach using Reagent. Unlike Om, Reagent has a tiny API and the only part of it used to create components is the Reagent atom implementation. The components themselves are written using plain Hiccup syntax.&lt;/p&gt;&lt;p&gt;Let's see how this could work. We'll start by creating a new Reagent project:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new reagent reagent-serverside
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll add a new namespace in called &lt;code&gt;reagent-serverside.home&lt;/code&gt; &lt;code&gt;src/cljc/reagent&amp;#95;serverside/home.cljc&lt;/code&gt;. This namespace will house the home page component that we'll pre-render on the server.&lt;/p&gt;&lt;p&gt;All we have to do now is to use a reader conditional to only require the Reagent atom during ClojureScript compilation:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns reagent-serverside.home
  #?&amp;#40;:cljs
     &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now write our components as we would normally:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns reagent-serverside.home
  #?&amp;#40;:cljs
     &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;def items &amp;#40;atom nil&amp;#41;&amp;#41;

&amp;#40;defn item-list &amp;#91;items&amp;#93;
  &amp;#91;:ul
   &amp;#40;for &amp;#91;item items&amp;#93;
     &amp;#94;{:key item}
     &amp;#91;:li item&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#40;defn add-item-button &amp;#91;items&amp;#93;
  &amp;#91;:button
   {:on-click #&amp;#40;swap! items conj &amp;#40;count @items&amp;#41;&amp;#41;}
   &amp;quot;add item&amp;quot;&amp;#93;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;:div &amp;#91;:h2 &amp;quot;Welcome to reagent-serverside&amp;quot;&amp;#93;
   &amp;#91;add-item-button items&amp;#93;
   &amp;#91;item-list @items&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll have the &lt;code&gt;items&lt;/code&gt; atom to house a collection of items, an &lt;code&gt;item-list&lt;/code&gt; function to render it, and the &lt;code&gt;home-page&lt;/code&gt; function that will use the &lt;code&gt;item-list&lt;/code&gt; component. We also have a button that lets the user add new items with an &lt;code&gt;:on-click&lt;/code&gt; event. This is all standard Reagent code.&lt;/p&gt;&lt;h3 id="rendering&amp;#95;on&amp;#95;the&amp;#95;server"&gt;Rendering on the Server&lt;/h3&gt;&lt;p&gt;Now, let's navigate to the &lt;code&gt;reagent-serverside.handler&lt;/code&gt; namespace and reference the &lt;code&gt;reagent-serverside.home&lt;/code&gt; we just created.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns reagent-serverside.handler
  &amp;#40;:require ...
            &amp;#91;reagent-serverside.home :refer &amp;#91;items home-page&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll now have to write the functions that will traverse the components and render them as appropriate. We'll attach a &lt;code&gt;:data-reactid&lt;/code&gt; key to each one to give it an identifier that React looks for, and inject the result into our Hiccup markup.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn react-id-str &amp;#91;react-id&amp;#93;
  &amp;#40;assert &amp;#40;vector? react-id&amp;#41;&amp;#41;
  &amp;#40;str &amp;quot;.&amp;quot; &amp;#40;clojure.string/join &amp;quot;.&amp;quot; react-id&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn set-react-id &amp;#91;react-id element&amp;#93;
  &amp;#40;update element 1 merge {:data-reactid &amp;#40;react-id-str react-id&amp;#41;}&amp;#41;&amp;#41;

&amp;#40;defn normalize &amp;#91;component&amp;#93;
  &amp;#40;if &amp;#40;map? &amp;#40;second component&amp;#41;&amp;#41;
    component
    &amp;#40;into &amp;#91;&amp;#40;first component&amp;#41; {}&amp;#93; &amp;#40;rest component&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn render
  &amp;#40;&amp;#91;component&amp;#93; &amp;#40;render &amp;#91;0&amp;#93; component&amp;#41;&amp;#41;  
  &amp;#40;&amp;#91;id component&amp;#93;
   &amp;#40;cond
    &amp;#40;fn? component&amp;#41;
    &amp;#40;render &amp;#40;component&amp;#41;&amp;#41;    

    &amp;#40;not &amp;#40;coll? component&amp;#41;&amp;#41;
    component
    
    &amp;#40;coll? &amp;#40;first component&amp;#41;&amp;#41;
    &amp;#40;map-indexed #&amp;#40;render &amp;#40;conj id %1&amp;#41; %2&amp;#41; component&amp;#41;
    
    &amp;#40;keyword? &amp;#40;first component&amp;#41;&amp;#41;
    &amp;#40;let &amp;#91;&amp;#91;tag opts &amp;amp; body&amp;#93; &amp;#40;normalize component&amp;#41;&amp;#93;
      &amp;#40;-&amp;gt;&amp;gt; body
           &amp;#40;map-indexed #&amp;#40;render &amp;#40;conj id %1&amp;#41; %2&amp;#41;&amp;#41;
           &amp;#40;into &amp;#91;tag opts&amp;#93;&amp;#41;
           &amp;#40;set-react-id id&amp;#41;&amp;#41;&amp;#41;
    
    &amp;#40;fn? &amp;#40;first component&amp;#41;&amp;#41;
    &amp;#40;render id &amp;#40;apply &amp;#40;first component&amp;#41; &amp;#40;rest component&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;reset! items &amp;#40;range 10&amp;#41;&amp;#41;

&amp;#40;def mount-target
  &amp;#91;:div#app &amp;#40;render home-page&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;render&lt;/code&gt; function will recursively walk the components evaluating any functions it finds and assigning the React id to each element.&lt;/p&gt;&lt;p&gt;Next, we'll set the &lt;code&gt;items&lt;/code&gt; atom to a range of numbers, and then call &lt;code&gt;render&lt;/code&gt; inside the &lt;code&gt;mount-target&lt;/code&gt; to generate the markup.&lt;/p&gt;&lt;h3 id="rendering&amp;#95;on&amp;#95;the&amp;#95;client"&gt;Rendering on the Client&lt;/h3&gt;&lt;p&gt;Finally, let's navigate to the &lt;code&gt;reagent-serverside.core&lt;/code&gt; namespace in the &lt;code&gt;src/cljs&lt;/code&gt; source path. We'll update it to reference the &lt;code&gt;home&lt;/code&gt; namespace we created and render the &lt;code&gt;home-page&lt;/code&gt; component on load.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns reagent-serverside.core
    &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
              &amp;#91;reagent-serverside.home :refer &amp;#91;items home-page&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn mount-root &amp;#91;&amp;#93;
  &amp;#40;reagent/render &amp;#91;home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;reset! items &amp;#40;range 20&amp;#41;&amp;#41;
  &amp;#40;mount-root&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we load the page we'll immediately see the server generated markup and then it will be updated by Reagent when ClojureScript is loaded. There are a few caveats here that you should be aware of.&lt;/p&gt;&lt;p&gt;Any components you wish to render on the server have to be written in &lt;code&gt;cljc&lt;/code&gt;, so you may end up having to add some shims for things like Ajax calls.&lt;/p&gt;&lt;p&gt;The component syntax has to work with both Reagent and Hiccup, so you have to be mindful to use the common subset.&lt;/p&gt;&lt;p&gt;React is fairly picky about the structure and the &lt;code&gt;data-reactid&lt;/code&gt; tags. So, it can be tricky to generate a DOM tree that it likes. The example in the post will give a React warning about the DOM being different. Some more work is needed around this.&lt;/p&gt;&lt;p&gt;However, even in the case that React doesn't reuse the DOM, the user will see the page immediately and you'll get the benefits of SEO for your site.&lt;/p&gt;&lt;p&gt;Full source is available on &lt;a href='https://github.com/yogthos/reagent-serverside'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="conclusions"&gt;Conclusions&lt;/h3&gt;&lt;p&gt;Overall, I'm very happy with the results and it looks like it would be fairly easy to wrap this up into a library. The data focused approach is a huge win for Reagent here in my opinion. Since the components are laid out using regular Clojure data structures there's no need to implement any special API and things just work out of the box.&lt;/p&gt;</description><pubDate>Tue, 24 Nov 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-11-12-ClojureScript-Eval.html</guid><link>https://yogthos.net/posts/2015-11-12-ClojureScript-Eval.html</link><title>Evaluating ClojureScript in the Browser</title><description>&lt;p&gt;ClojureScript can now &lt;a href='https://swannodette.github.io/2015/07/29/clojurescript-17/'&gt;compile itself without relying on the Google Closure compiler&lt;/a&gt;, and it's now possible to evaluate code straight in the browser. In this post we'll look at how that's accomplished by creating a code editor using &lt;a href='https://codemirror.net/'&gt;CodeMirror&lt;/a&gt;, &lt;a href='https://highlightjs.org/'&gt;highlight.js&lt;/a&gt;, and &lt;a href='https://reagent-project.github.io/'&gt;Reagent&lt;/a&gt;. The code entered in the editor will be sent for evaluation and the result displayed to the user.&lt;/p&gt;&lt;p&gt;Let's start by creating a new Reagent project by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new reagent cljs-eval-example +figwheel
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll navigate to the project folder and start Figwheel by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein figwheel
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's open the browser at &lt;code&gt;http://localhost:3449&lt;/code&gt; and navigate to the &lt;code&gt;cljs-eval-example.core&lt;/code&gt; namespace in the &lt;code&gt;src/cljs&lt;/code&gt; folder. We'll first need to reference &lt;code&gt;cljs.js&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns cljs-eval-example.core
  &amp;#40;:require
   ...
   &amp;#91;cljs.js :refer &amp;#91;empty-state eval-str js-eval&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll create &lt;code&gt;evaluate&lt;/code&gt; function that will accept a string and a callback. This function calls &lt;a href='https://cljs.github.io/api/cljs.js/eval-str'&gt;cljs.js/eval-str&lt;/a&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn evaluate &amp;#91;s cb&amp;#93;
  &amp;#40;eval-str
     &amp;#40;empty-state&amp;#41;
     s
     nil
     {:eval       js-eval    
      :source-map true
      :context    :expr}
     cb&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;eval-str&lt;/code&gt; function accepts an initial state, followed by the string representing the form to evaluate, a name, a map with the options, and a callback function for handling the result of the evaluation. We can create an initial state by calling &lt;code&gt;cljs.js/empty-state&lt;/code&gt; function. We can now test that our code works by adding a button to our &lt;code&gt;home-page&lt;/code&gt; component:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#91;:div
   &amp;#91;:button
    {:on-click #&amp;#40;evaluate &amp;quot;&amp;#40;println \&amp;quot;hello world!\&amp;quot;&amp;#41;&amp;quot; &amp;#40;fn &amp;#91;&amp;#95;&amp;#93;&amp;#41;&amp;#41;}
    &amp;quot;let's compile!&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we click the button we should see &lt;code&gt;&amp;quot;hello world!&amp;quot;&lt;/code&gt; printed in the browser console. Next, let's add a &lt;code&gt;:textarea&lt;/code&gt; to allow entering some text and then send it for evaluation.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;input &amp;#40;atom nil&amp;#41;
        output &amp;#40;atom nil&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;:textarea
        {:value @input
         :on-change #&amp;#40;reset! input &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;}&amp;#93;       
       &amp;#91;:div&amp;gt;button
        {:on-click #&amp;#40;evaluate @input &amp;#40;fn &amp;#91;result&amp;#93; &amp;#40;reset! output result&amp;#41;&amp;#41;&amp;#41;}
        &amp;quot;let's compile!&amp;quot;&amp;#93;
       &amp;#91;:p @output&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;At this point we can type some code in our input box, click the button to evaluate it, and see the result. So far so good, now let's make the editor look a bit nicer by replacing it with the CodeMirror version.&lt;/p&gt;&lt;p&gt;We'll open up the &lt;code&gt;cljs-eval-example.handler&lt;/code&gt; namespace in the &lt;code&gt;src/clj&lt;/code&gt; folder. There, we'll update the &lt;code&gt;include-css&lt;/code&gt; and &lt;code&gt;include-js&lt;/code&gt; portions of the &lt;code&gt;head&lt;/code&gt; to add the respective CSS and Js files for running CodeMirror.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn head &amp;#91;&amp;#93;
  &amp;#91;:head
   &amp;#91;:meta {:charset &amp;quot;utf-8&amp;quot;}&amp;#93;
   &amp;#91;:meta {:name &amp;quot;viewport&amp;quot;
           :content &amp;quot;width=device-width, initial-scale=1&amp;quot;}&amp;#93;
   &amp;#40;include-css
    &amp;#40;if &amp;#40;env :dev&amp;#41; &amp;quot;/css/site.css&amp;quot; &amp;quot;/css/site.min.css&amp;quot;&amp;#41;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/codemirror.min.css&amp;quot;
    &amp;#40;if &amp;#40;env :dev&amp;#41; &amp;quot;css/site.css&amp;quot; &amp;quot;css/site.min.css&amp;quot;&amp;#41;&amp;#41;
   &amp;#40;include-js
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/codemirror.min.js&amp;quot;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/mode/clojure/clojure.min.js&amp;quot;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that in place we'll need to reload the page for the new assets to become available. Since we're using external JavaScript that modifies the DOM, we'll need to use the &lt;code&gt;reagent.core/create-class&lt;/code&gt; function to create the editor component.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;create-class&lt;/code&gt; function accepts a map keyed on the &lt;a href='https://facebook.github.io/react/docs/component-specs.html'&gt;React lifecycle methods&lt;/a&gt;. The methods that we wish to implement are &lt;code&gt;:render&lt;/code&gt; and &lt;code&gt;:component-did-mount&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn editor &amp;#91;input&amp;#93;
  &amp;#40;reagent/create-class
   {:render &amp;#40;fn &amp;#91;&amp;#93; &amp;#91;:textarea 
                     {:default-value &amp;quot;&amp;quot;
                      :auto-complete &amp;quot;off&amp;quot;}&amp;#93;&amp;#41;
    :component-did-mount &amp;#40;editor-did-mount input&amp;#41;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;editor&lt;/code&gt; component will accept the &lt;code&gt;input&lt;/code&gt; atom as the parameter and pass it to the &lt;code&gt;editor-did-mount&lt;/code&gt; function. This function will look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn editor-did-mount &amp;#91;input&amp;#93;
  &amp;#40;fn &amp;#91;this&amp;#93;
    &amp;#40;let &amp;#91;cm &amp;#40;.fromTextArea  js/CodeMirror
                             &amp;#40;reagent/dom-node this&amp;#41;
                             #js {:mode &amp;quot;clojure&amp;quot;
                                  :lineNumbers true}&amp;#41;&amp;#93;
      &amp;#40;.on cm &amp;quot;change&amp;quot; #&amp;#40;reset! input &amp;#40;.getValue %&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;editor-did-mount&lt;/code&gt; is a closure that returns a function that accepts the mounted React component, it then calls &lt;code&gt;reagent/dom-node&lt;/code&gt; on it to get the actual DOM node mounted in the browser. We'll then call &lt;code&gt;.fromTextArea&lt;/code&gt; method on &lt;code&gt;js/CodeMirror&lt;/code&gt; and pass it the node along with a map of rendering hints.&lt;/p&gt;&lt;p&gt;Calling &lt;code&gt;.fromTextArea&lt;/code&gt; returns an instance of the CodeMirror. As a last step we'll add the &lt;code&gt;change&lt;/code&gt; event to this instance to reset the &lt;code&gt;input&lt;/code&gt; atom with the updated text whenever the text in the editor is changed.&lt;/p&gt;&lt;p&gt;We can now update the &lt;code&gt;home-page&lt;/code&gt; component to use the &lt;code&gt;editor&lt;/code&gt; component instead of a plain &lt;code&gt;textarea&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;input &amp;#40;atom nil&amp;#41;
        output &amp;#40;atom nil&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;editor input&amp;#93;
       &amp;#91;:div
        &amp;#91;:button
         {:on-click #&amp;#40;evaluate @input &amp;#40;fn &amp;#91;{:keys &amp;#91;value&amp;#93;}&amp;#93; &amp;#40;reset! output value&amp;#41;&amp;#41;&amp;#41;}
         &amp;quot;run&amp;quot;&amp;#93;&amp;#93;
       &amp;#91;:p @output&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The editor looks a lot nicer now, but the output doesn't have any highlighting. Let's fix that by running it through highlight.js to generate nicely formatted results.&lt;/p&gt;&lt;p&gt;Once again, we'll need to add the additional CSS and Js files in the &lt;code&gt;cljs-eval-example.handler&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn head &amp;#91;&amp;#93;
  &amp;#91;:head
   &amp;#91;:meta {:charset &amp;quot;utf-8&amp;quot;}&amp;#93;
   &amp;#91;:meta {:name &amp;quot;viewport&amp;quot;
           :content &amp;quot;width=device-width, initial-scale=1&amp;quot;}&amp;#93;
   &amp;#40;include-css
    &amp;#40;if &amp;#40;env :dev&amp;#41; &amp;quot;/css/site.css&amp;quot; &amp;quot;/css/site.min.css&amp;quot;&amp;#41;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/codemirror.min.css&amp;quot;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.9.1/styles/default.min.css&amp;quot;
    &amp;#40;if &amp;#40;env :dev&amp;#41; &amp;quot;css/site.css&amp;quot; &amp;quot;css/site.min.css&amp;quot;&amp;#41;&amp;#41;
   &amp;#40;include-js
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.9.1/highlight.min.js&amp;quot;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/codemirror.min.js&amp;quot;
    &amp;quot;//cdnjs.cloudflare.com/ajax/libs/codemirror/5.8.0/mode/clojure/clojure.min.js&amp;quot;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Back in the &lt;code&gt;cljs-eval-example.core&lt;/code&gt; namespace we'll add a reference for &lt;code&gt;&amp;#91;cljs.pprint :refer &amp;#91;pprint&amp;#93;&amp;#93;&lt;/code&gt; and write the &lt;code&gt;result-view&lt;/code&gt; component that will take care of highlighting the output.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns cljs-eval-example.core
  &amp;#40;:require ...
            &amp;#91;cljs.pprint :refer &amp;#91;pprint&amp;#93;&amp;#93;&amp;#41;&amp;#41;

...
            
&amp;#40;defn result-view &amp;#91;output&amp;#93;
  &amp;#40;reagent/create-class
   {:render &amp;#40;fn &amp;#91;&amp;#93;
              &amp;#91;:pre&amp;gt;code.clj
               &amp;#40;with-out-str &amp;#40;pprint @output&amp;#41;&amp;#41;&amp;#93;&amp;#41;
    :component-did-update render-code}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Highlight.js defaults to using &lt;code&gt;&amp;lt;pre&amp;gt;&amp;lt;code&amp;gt;...&amp;lt;/pre&amp;gt;&amp;lt;/code&amp;gt;&lt;/code&gt; blocks, so we'll generate one in the &lt;code&gt;:render&lt;/code&gt; function. Then we'll call the &lt;code&gt;render-code&lt;/code&gt; function when the &lt;code&gt;:component-did-update&lt;/code&gt; state is triggered. This function will simply pass the node to the &lt;code&gt;.highlightBlock&lt;/code&gt; function provided by highlight.js:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn render-code &amp;#91;this&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; this reagent/dom-node &amp;#40;.highlightBlock js/hljs&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we'll have to update the &lt;code&gt;home-page&lt;/code&gt; component to use the &lt;code&gt;result-view&lt;/code&gt; component we just wrote:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;input &amp;#40;atom nil&amp;#41;
        output &amp;#40;atom nil&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;editor input&amp;#93;
       &amp;#91;:div
        &amp;#91;:button
         {:on-click #&amp;#40;evaluate @input &amp;#40;fn &amp;#91;{:keys &amp;#91;value&amp;#93;}&amp;#93; &amp;#40;reset! output value&amp;#41;&amp;#41;&amp;#41;}
         &amp;quot;run&amp;quot;&amp;#93;&amp;#93;
       &amp;#91;:div
        &amp;#91;result-view output&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now both the editor and the output should look nicely highlighted, and the output will be formatted as a bonus. The entire code listing is as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns cljs-eval-example.core
  &amp;#40;:require
   &amp;#91;reagent.dom :as dom&amp;#93;
   &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
   &amp;#91;cljs.js :refer &amp;#91;empty-state eval-str js-eval&amp;#93;&amp;#93;
   &amp;#91;cljs.pprint :refer &amp;#91;pprint&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn evaluate &amp;#91;s cb&amp;#93;
  &amp;#40;eval-str
     &amp;#40;empty-state&amp;#41;
     s
     nil
     {:eval       js-eval    
      :source-map true
      :context    :expr}
     cb&amp;#41;&amp;#41;

&amp;#40;defn editor-did-mount &amp;#91;input&amp;#93;
  &amp;#40;fn &amp;#91;this&amp;#93;
    &amp;#40;let &amp;#91;cm &amp;#40;.fromTextArea  js/CodeMirror
                             &amp;#40;dom/dom-node this&amp;#41;
                             #js {:mode &amp;quot;clojure&amp;quot;
                                  :lineNumbers true}&amp;#41;&amp;#93;
      &amp;#40;.on cm &amp;quot;change&amp;quot; #&amp;#40;reset! input &amp;#40;.getValue %&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn editor &amp;#91;input&amp;#93;
  &amp;#40;reagent/create-class
   {:render &amp;#40;fn &amp;#91;&amp;#93; &amp;#91;:textarea
                    {:default-value &amp;quot;&amp;quot;
                     :auto-complete &amp;quot;off&amp;quot;}&amp;#93;&amp;#41;
    :component-did-mount &amp;#40;editor-did-mount input&amp;#41;}&amp;#41;&amp;#41;

&amp;#40;defn render-code &amp;#91;this&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; this dom/dom-node &amp;#40;.highlightBlock js/hljs&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn result-view &amp;#91;output&amp;#93;
  &amp;#40;reagent/create-class
   {:render &amp;#40;fn &amp;#91;&amp;#93;
              &amp;#91;:pre&amp;gt;code.clj
               &amp;#40;with-out-str &amp;#40;pprint @output&amp;#41;&amp;#41;&amp;#93;&amp;#41;
    :component-did-update render-code}&amp;#41;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;input &amp;#40;atom nil&amp;#41;
        output &amp;#40;atom nil&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;editor input&amp;#93;
       &amp;#91;:div
        &amp;#91;:button
         {:on-click #&amp;#40;evaluate @input &amp;#40;fn &amp;#91;{:keys &amp;#91;value&amp;#93;}&amp;#93; &amp;#40;reset! output value&amp;#41;&amp;#41;&amp;#41;}
         &amp;quot;run&amp;quot;&amp;#93;&amp;#93;
       &amp;#91;:div
        &amp;#91;result-view output&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn mount-root &amp;#91;&amp;#93;
  &amp;#40;dom/render &amp;#91;home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;mount-root&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A complete example project is available on &lt;a href='https://github.com/yogthos/cljs-eval-example'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Thu, 12 Nov 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-10-08-Using-JConsole.html</guid><link>https://yogthos.net/posts/2015-10-08-Using-JConsole.html</link><title>Troubleshooting With JConsole</title><description>&lt;p&gt;It's often useful to be able to tell how much resources your app happens to be using. I've previously discussed how &lt;a href='/posts/2012-08-21-Reflecting-on-performance.html'&gt;JVisualVM&lt;/a&gt; can be used to do some basic profiling for the application. In this post we'll look at how to use another great tool called &lt;code&gt;jconsole&lt;/code&gt; that also comes with the JVM. First, let's create and run a new Luminus web app as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus guestbook
cd guestbook
lein uberjar
java -jar target/guestbook.jar
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll run the following command in a separate terminal:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;jconsole
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We should be greeted by a screen that looks something like the following:&lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-default-screen.png" alt="jconsole" /&gt;&lt;/p&gt;&lt;p&gt;We'll select guestbook and connect to it. Once the connection is established we'll see an overview screen detailing memory, class instances, threads, and CPU usage.&lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-summary-screen.png" alt="jconsole summary" /&gt;&lt;/p&gt;&lt;p&gt;We can also select tabs to drill down into details about each of these as well as the VM summary. The &lt;code&gt;Memory&lt;/code&gt; tab is the one of most interest to start. This screen will let us see a graph of memory usage over time and allow us to initiate garbage collection. It also shows the details about application memory usage and how it compares to the overall memory allocated by the JVM. &lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-memory-screen.png" alt="jconsole summary" /&gt;&lt;/p&gt;&lt;p&gt;Let's run the &lt;a href='https://httpd.apache.org/docs/2.2/programs/ab.html'&gt;Apache HTTP server benchmarking tool&lt;/a&gt;, that comes bundled by default on OS X, and see how that affects our application.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;ab -c 10 -n 1000 http://127.0.0.1:3000/
This is ApacheBench, Version 2.3 &amp;lt;$Revision: 1663405 $&amp;gt;
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 &amp;#40;be patient&amp;#41;
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        undertow
Server Hostname:        127.0.0.1
Server Port:            3000

Document Path:          /
Document Length:        3918 bytes

Concurrency Level:      10
Time taken for tests:   3.544 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      4251000 bytes
HTML transferred:       3918000 bytes
Requests per second:    282.14 &amp;#91;#/sec&amp;#93; &amp;#40;mean&amp;#41;
Time per request:       35.444 &amp;#91;ms&amp;#93; &amp;#40;mean&amp;#41;
Time per request:       3.544 &amp;#91;ms&amp;#93; &amp;#40;mean, across all concurrent requests&amp;#41;
Transfer rate:          1171.26 &amp;#91;Kbytes/sec&amp;#93; received

Connection Times &amp;#40;ms&amp;#41;
              min  mean&amp;#91;+/-sd&amp;#93; median   max
Connect:        0    0   0.1      0       3
Processing:    15   35  27.4     26     252
Waiting:       15   35  26.3     26     226
Total:         15   35  27.5     26     252

Percentage of the requests served within a certain time &amp;#40;ms&amp;#41;
  50%     26
  66%     31
  75%     37
  80%     41
  90%     54
  95%     75
  98%    110
  99%    227
 100%    252 &amp;#40;longest request&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;note that 282 req/sec number is running without any warmup while being instrumented&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;We can see that as the server is getting hammered by requests the memory usage spikes from roughly a 100 megs to about 275. However, once GC is performed the memory usage goes right back down.&lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-gc.png" alt="jconsole summary" /&gt;&lt;/p&gt;&lt;p&gt;This tells us that the application starts using more resources as it serves multiple concurrent requests, but then releases these as the GC runs indicating that no memory leaks are happening. We can also confirm that the threads and class instances are not getting out of hand as the application continues to run using the the respective tabs.&lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-threads.png" alt="jconsole summary" /&gt;&lt;/p&gt;&lt;p&gt;&lt;img src="/files/jconsole-classes.png" alt="jconsole summary" /&gt;&lt;/p&gt;&lt;p&gt;As you can see &lt;code&gt;jconsole&lt;/code&gt; is a handy tool that can be used to quickly diagnose the behavior of a Clojure application. Should we find anything that warrants further investigation then it would be time to run a profiler such as &lt;code&gt;jvisualvm&lt;/code&gt; to see where specifically the resources are being used.&lt;/p&gt;</description><pubDate>Thu, 08 Oct 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-10-01-Compojure-API.html</guid><link>https://yogthos.net/posts/2015-10-01-Compojure-API.html</link><title>Building services with Duct and compojure-api</title><description>&lt;p&gt;In this post we'll look at writing a RESTful service using &lt;a href='https://github.com/weavejester/duct'&gt;Duct&lt;/a&gt; and &lt;a href='https://github.com/metosin/compojure-api'&gt;compojure-api&lt;/a&gt;. Our service will use a SQLite database and illustrate how to do operations such as adding, remove, and authenticating users.&lt;/p&gt;&lt;h3 id="prerequisites"&gt;Prerequisites&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html'&gt;JDK&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='http://leiningen.org/'&gt;Leiningen&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="creating&amp;#95;the&amp;#95;project"&gt;Creating the Project&lt;/h3&gt;&lt;p&gt;Duct is a minimal web framework with emphasis on using &lt;a href='https://github.com/stuartsierra/component'&gt;component&lt;/a&gt; to manage stateful resources such as database connections. We can create a new Duct application by running the following command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new duct swagger-service +example
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will generate a fresh application and add an example route component to it. Once the application is created we'll have to run the &lt;code&gt;setup&lt;/code&gt; task to generate local assets in the root folder of the application:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;cd swagger-service
lein setup
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now test that our application works as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein run
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If everything went well then we should be able to navigate to &lt;code&gt;localhost:3000&lt;/code&gt; and see &lt;code&gt;Hello World&lt;/code&gt; displayed on the page. We're now ready to start working on creating our service.&lt;/p&gt;&lt;h4 id="adding&amp;#95;dependencies"&gt;Adding Dependencies&lt;/h4&gt;&lt;p&gt;We'll start by adding some dependencies in &lt;code&gt;project.clj&lt;/code&gt; that we'll need in order to create our service:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:dependencies
&amp;#91;...
 &amp;#91;crypto-password &amp;quot;0.1.3&amp;quot;&amp;#93;
 &amp;#91;metosin/compojure-api &amp;quot;0.23.1&amp;quot;&amp;#93;
 &amp;#91;org.xerial/sqlite-jdbc &amp;quot;3.8.11.1&amp;quot;&amp;#93;
 &amp;#91;yesql &amp;quot;0.5.0&amp;quot;&amp;#93;
 &amp;#91;migratus &amp;quot;0.8.4&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll use &lt;code&gt;crypto-password&lt;/code&gt; to handle password hashing when we create user accounts and checking passwords during authentication. The &lt;code&gt;compojure-api&lt;/code&gt; library will be used to generate the service endpoints. The &lt;code&gt;sqlite-jdbc&lt;/code&gt; driver will be used as our data store, we'll access it using &lt;code&gt;yesql&lt;/code&gt;, and we'll generate the database using &lt;code&gt;migratus&lt;/code&gt;.&lt;/p&gt;&lt;h4 id="configuring&amp;#95;migrations"&gt;Configuring Migrations&lt;/h4&gt;&lt;p&gt;Let's add the &lt;code&gt;migratus&lt;/code&gt; plugin along with its configuration to our project:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:plugins &amp;#91;&amp;#91;lein-environ &amp;quot;1.0.1&amp;quot;&amp;#93;
          &amp;#91;lein-gen &amp;quot;0.2.2&amp;quot;&amp;#93;
          &amp;#91;migratus-lein &amp;quot;0.1.7&amp;quot;&amp;#93;&amp;#93;

:migratus {:store :database             
           :db {:classname &amp;quot;org.sqlite.JDBC&amp;quot;
                :connection-uri &amp;quot;jdbc:sqlite:service-store.db&amp;quot;}}          
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now run the following commands to generate the migration files for the &lt;code&gt;users&lt;/code&gt; table:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;mkdir resources/migrations
lein migratus create users
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will produce files for &lt;code&gt;up&lt;/code&gt; and &lt;code&gt;down&lt;/code&gt; migrations such as:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;20151001145313-users.down.sql
20151001145313-users.up.sql
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;up&lt;/code&gt; migrations file will create the table:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;CREATE TABLE users
&amp;#40;id VARCHAR&amp;#40;20&amp;#41; PRIMARY KEY,
 first&amp;#95;name VARCHAR&amp;#40;30&amp;#41;,
 last&amp;#95;name VARCHAR&amp;#40;30&amp;#41;,
 email VARCHAR&amp;#40;30&amp;#41;,
 admin BOOLEAN,
 last&amp;#95;login TIME,
 is&amp;#95;active BOOLEAN,
 pass VARCHAR&amp;#40;100&amp;#41;&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Conversely, the &lt;code&gt;down&lt;/code&gt; migrations file will delete it:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;DROP TABLE users;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now run the following command to create the database:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein migratus migrate
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="adding&amp;#95;database&amp;#95;queries"&gt;Adding Database Queries&lt;/h4&gt;&lt;p&gt;With the database created, we'll need to add some queries to access the database. We'll create a new file called &lt;code&gt;resources/sql/queries.sql&lt;/code&gt; and put the following SQL queries in it:&lt;/p&gt;&lt;pre&gt;&lt;code class="sql"&gt;-- name: create-user!
-- creates a new user record
INSERT INTO users
&amp;#40;id, first&amp;#95;name, last&amp;#95;name, email, pass&amp;#41;
VALUES &amp;#40;:id, :first&amp;#95;name, :last&amp;#95;name, :email, :pass&amp;#41;

-- name: get-user
-- retrieve a user given the id.
SELECT &amp;#42; FROM users
WHERE id = :id

-- name: get-users
-- retrieve a user given the id.
SELECT id, first&amp;#95;name, last&amp;#95;name, email FROM users

-- name: delete-user!
-- delete a user given the id
DELETE FROM users
WHERE id = :id
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="creating&amp;#95;the&amp;#95;database&amp;#95;component"&gt;Creating the Database Component&lt;/h3&gt;&lt;p&gt;Now, let's create a component that will be used to access it. We'll create a new namespace called &lt;code&gt;swagger-service.component.db&lt;/code&gt; then put the following code there:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns swagger-service.component.db
  &amp;#40;:require &amp;#91;yesql.core :refer &amp;#91;defqueries&amp;#93;&amp;#93;
            &amp;#91;com.stuartsierra.component :as component&amp;#93;
            &amp;#91;crypto.password.bcrypt :as password&amp;#93;
            &amp;#91;environ.core :refer &amp;#91;env&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defqueries &amp;quot;sql/queries.sql&amp;quot;&amp;#41;

&amp;#40;defn create-user-account! &amp;#91;user db&amp;#93;
  &amp;#40;create-user! &amp;#40;update user :pass password/encrypt&amp;#41; db&amp;#41;&amp;#41;

&amp;#40;defn authenticate &amp;#91;user db&amp;#93;
  &amp;#40;boolean
   &amp;#40;when-let &amp;#91;db-user &amp;#40;-&amp;gt; user &amp;#40;get-user db&amp;#41; first&amp;#41;&amp;#93;
     &amp;#40;password/check &amp;#40;:pass user&amp;#41; &amp;#40;:pass db-user&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defrecord DbComponent &amp;#91;connection&amp;#93;
  component/Lifecycle
  &amp;#40;start &amp;#91;component&amp;#93;
         &amp;#40;assoc component :connection connection&amp;#41;&amp;#41;
  &amp;#40;stop &amp;#91;component&amp;#93;
        &amp;#40;dissoc component :connection&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn db-component &amp;#91;connection&amp;#93;
  &amp;#40;-&amp;gt;DbComponent connection&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The namespace will define query functions by calling the &lt;code&gt;defqueries&lt;/code&gt; macro and giving it the path to the &lt;code&gt;queries.sql&lt;/code&gt; file we just created.&lt;/p&gt;&lt;p&gt;Then we'll add a couple of helper functions to create a user account with a hashed password and to check whether the user and the password match the stored credentials.&lt;/p&gt;&lt;p&gt;Next, we define the &lt;code&gt;DbComponent&lt;/code&gt; record that will manage the lifecycle of the database. The &lt;code&gt;start&lt;/code&gt; function in the component will associate the given connection settings with the &lt;code&gt;:connection&lt;/code&gt; key in the component, and the &lt;code&gt;stop&lt;/code&gt; function will remove the connection.&lt;/p&gt;&lt;p&gt;The connection is specified in the &lt;code&gt;swagger-service.config&lt;/code&gt; namespace and points to the &lt;code&gt;connection-uri&lt;/code&gt; key that is expected to be found in the environment.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def environ
  {:http {:port &amp;#40;some-&amp;gt; env :port Integer.&amp;#41;}
   :db   {:connection-uri &amp;#40;:connection-uri env&amp;#41;}}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll add the actual connection information under the &lt;code&gt;:env&lt;/code&gt; key in &lt;code&gt;profiles.clj&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;;; Local profile overrides

{:profiles/dev  {:env {:connection-uri &amp;quot;jdbc:sqlite:service-store.db&amp;quot;}}
 :profiles/test {}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we have a helper function to instantiate the component called &lt;code&gt;db-component&lt;/code&gt;.&lt;/p&gt;&lt;h4 id="adding&amp;#95;a&amp;#95;new&amp;#95;component&amp;#95;to&amp;#95;the&amp;#95;system"&gt;Adding a New Component to the System&lt;/h4&gt;&lt;p&gt;With the component created we can now add it to the system found in the &lt;code&gt;swagger-service.system&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns swagger-service.system
 &amp;#40;:require ...
           &amp;#91;swagger-service.component.db :refer &amp;#91;db-component&amp;#93;&amp;#93;&amp;#41;&amp;#41;

...
           
&amp;#40;defn new-system &amp;#91;config&amp;#93;
 &amp;#40;let &amp;#91;config &amp;#40;meta-merge base-config config&amp;#41;&amp;#93;
   &amp;#40;-&amp;gt; &amp;#40;component/system-map
        :db      &amp;#40;db-component &amp;#40;:db config&amp;#41;&amp;#41;
        :app     &amp;#40;handler-component &amp;#40;:app config&amp;#41;&amp;#41;
        :http    &amp;#40;jetty-server &amp;#40;:http config&amp;#41;&amp;#41;
        :example &amp;#40;endpoint-component example-endpoint&amp;#41;&amp;#41;
       &amp;#40;component/system-using
        {:http &amp;#91;:app&amp;#93;
         :app  &amp;#91;:example&amp;#93;
         :example &amp;#91;&amp;#93;          
         :db &amp;#91;&amp;#93;}&amp;#41;&amp;#41;&amp;#41;&amp;#41;            
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="creating&amp;#95;an&amp;#95;http&amp;#95;endpoint&amp;#95;component"&gt;Creating an HTTP Endpoint Component&lt;/h3&gt;&lt;p&gt;The final step is to add the service endpoint that will provide the RESTful interface to the database. We'll create a new namespace called &lt;code&gt;swagger-service.endpoint.service&lt;/code&gt;. The namespace will use the &lt;code&gt;compojure-api&lt;/code&gt; library to define the service operations. The library requires us to declare the types of request parameters and responses for each endpoint using the &lt;a href='https://github.com/Prismatic/schema'&gt;schema&lt;/a&gt; library.&lt;/p&gt;&lt;p&gt;Let's start by creating the namespace declaration with the following references:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns swagger-service.endpoint.service
 &amp;#40;:require &amp;#91;clojure.java.io :as io&amp;#93;
           &amp;#91;ring.util.http-response :refer :all&amp;#93;
           &amp;#91;compojure.api.sweet :refer :all&amp;#93;
           &amp;#91;schema.core :as s&amp;#93;
           &amp;#91;swagger-service.component.db :as db&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then we'll create the schema for the User type that matches the user table in our database:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;s/defschema User
 {:id String
  &amp;#40;s/optional-key :first&amp;#95;name&amp;#41; String
  &amp;#40;s/optional-key :last&amp;#95;name&amp;#41; String
  &amp;#40;s/optional-key :email&amp;#41; String
  &amp;#40;s/optional-key :pass&amp;#41; String}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, let's create the &lt;code&gt;service-endpoint&lt;/code&gt; component that will define the service routes. The component accepts the &lt;code&gt;config&lt;/code&gt; as its parameter. The config will contain the &lt;code&gt;:db&lt;/code&gt; key that we added to our system earlier with the database connection.&lt;/p&gt;&lt;p&gt;The routes are created by calling the &lt;code&gt;api&lt;/code&gt; macro from &lt;code&gt;compojure-api&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn service-endpoint &amp;#91;config&amp;#93;
 &amp;#40;api
   &amp;#40;ring.swagger.ui/swagger-ui
    &amp;quot;/swagger-ui&amp;quot;&amp;#41;
   &amp;#40;swagger-docs
    {:info {:title &amp;quot;User API&amp;quot;}}&amp;#41;
   &amp;#40;context&amp;#42; &amp;quot;/api&amp;quot; &amp;#91;&amp;#93;
             :tags &amp;#91;&amp;quot;users&amp;quot;&amp;#93;

             &amp;#40;GET&amp;#42; &amp;quot;/users&amp;quot; &amp;#91;&amp;#93;
                   :return  &amp;#91;User&amp;#93;
                   :summary &amp;quot;returns the list of users&amp;quot;
                   &amp;#40;ok &amp;#40;db/get-users {} &amp;#40;:db config&amp;#41;&amp;#41;&amp;#41;&amp;#41;
             
             &amp;#40;GET&amp;#42; &amp;quot;/user/:id&amp;quot;  &amp;#91;&amp;#93;
                   :return      User
                   :path-params &amp;#91;id :- String&amp;#93;
                   :summary     &amp;quot;returns the user with a given id&amp;quot;
                   &amp;#40;ok &amp;#40;db/get-users {:id id} &amp;#40;:db config&amp;#41;&amp;#41;&amp;#41;&amp;#41;

             &amp;#40;POST&amp;#42; &amp;quot;/authenticate&amp;quot; &amp;#91;&amp;#93;
                    :return         Boolean
                    :body-params    &amp;#91;user :- User&amp;#93;
                    :summary        &amp;quot;authenticates the user using the id and pass.&amp;quot;
                    &amp;#40;ok &amp;#40;db/authenticate user &amp;#40;:db config&amp;#41;&amp;#41;&amp;#41;&amp;#41;
             
             &amp;#40;POST&amp;#42; &amp;quot;/user&amp;quot;      &amp;#91;&amp;#93;
                    :return      Long
                    :body-params &amp;#91;user :- User&amp;#93;
                    :summary     &amp;quot;creates a new user record.&amp;quot;
                    &amp;#40;ok &amp;#40;db/create-user-account! user &amp;#40;:db config&amp;#41;&amp;#41;&amp;#41;&amp;#41;
             
             &amp;#40;DELETE&amp;#42; &amp;quot;/user&amp;quot;    &amp;#91;&amp;#93;
                    :return      Long
                    :body-params &amp;#91;id :- String&amp;#93;
                    :summary     &amp;quot;deletes the user record with the given id.&amp;quot;
                    &amp;#40;ok &amp;#40;db/delete-user! {:id id} &amp;#40;:db config&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice that we call &lt;code&gt;ring.swagger.ui/swagger-ui&lt;/code&gt; and &lt;code&gt;swagger-docs&lt;/code&gt; at the beginning of the definition of &lt;code&gt;api&lt;/code&gt;. This will automatically produce the API documentation for the service operations defined within it. Once our service is hooked up, we'll be able to navigate to &lt;code&gt;localhost:3000/swagger-ui&lt;/code&gt; and see an interactive page for testing the API endpoints.&lt;/p&gt;&lt;p&gt;As you may have noticed, &lt;code&gt;compojure-api&lt;/code&gt; mimics Compojure route definitions with the difference that the route method name has a &lt;code&gt;&amp;#42;&lt;/code&gt; after it. The route definition also has some additional keys associated with it.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;the &lt;code&gt;:return&lt;/code&gt; key specifies the return type for the service operation&lt;/li&gt;&lt;li&gt;the &lt;code&gt;:summary&lt;/code&gt; key provides the documentation about the purpose of the operation&lt;/li&gt;&lt;li&gt;the parameters are specified using different keys depending on the parameter type, such as &lt;code&gt;:path-params&lt;/code&gt; and &lt;code&gt;:body-params&lt;/code&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Finally, each route will return a response type with the result of calling the handler associated with it.&lt;/p&gt;&lt;p&gt;If we look at the &lt;code&gt;&amp;quot;/users&amp;quot;&lt;/code&gt; route we see that it calls the &lt;code&gt;get-users&lt;/code&gt; function from the database and passes it the value of the &lt;code&gt;:db&lt;/code&gt; key from the config. This will be used to resolve the database connection at runtime.&lt;/p&gt;&lt;h3 id="adding&amp;#95;the&amp;#95;endpoint&amp;#95;to&amp;#95;the&amp;#95;system"&gt;Adding the Endpoint to the System&lt;/h3&gt;&lt;p&gt;With the route added we can now navigate back to the &lt;code&gt;swagger-service.system&lt;/code&gt; namespace and add the component there:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns swagger-service.system
 &amp;#40;:require ...
           &amp;#91;swagger-service.component.db :refer &amp;#91;db-component&amp;#93;&amp;#93;
           &amp;#91;swagger-service.endpoint.service :refer &amp;#91;service-endpoint&amp;#93;&amp;#93;&amp;#41;&amp;#41;
           
...

&amp;#40;defn new-system &amp;#91;config&amp;#93;
 &amp;#40;let &amp;#91;config &amp;#40;meta-merge base-config config&amp;#41;&amp;#93;
   &amp;#40;-&amp;gt; &amp;#40;component/system-map
        :db      &amp;#40;db-component &amp;#40;:db config&amp;#41;&amp;#41;
        :app     &amp;#40;handler-component &amp;#40;:app config&amp;#41;&amp;#41;
        :http    &amp;#40;jetty-server &amp;#40;:http config&amp;#41;&amp;#41;
        :example &amp;#40;endpoint-component example-endpoint&amp;#41;
        :service &amp;#40;endpoint-component service-endpoint&amp;#41;&amp;#41;
       &amp;#40;component/system-using
        {:http &amp;#91;:app&amp;#93;
         :app  &amp;#91;:example :service&amp;#93;
         :service &amp;#91;:db&amp;#93;
         :example &amp;#91;&amp;#93;          
         :db &amp;#91;&amp;#93;}&amp;#41;&amp;#41;&amp;#41;&amp;#41;            
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The service component is initialized using the &lt;code&gt;endpoint-component&lt;/code&gt; Duct helper. Next, the component relationships have to be described explicitly. We can see that the &lt;code&gt;:service&lt;/code&gt; component depends on the &lt;code&gt;:db&lt;/code&gt; component, and the &lt;code&gt;:app&lt;/code&gt; in turn depends on both the &lt;code&gt;:example&lt;/code&gt; and the &lt;code&gt;:service&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;We can now restart our app and navigate to &lt;code&gt;localhost:3000/swagger-ui&lt;/code&gt; to see the service test page. Using this page we can test all the service operations that we defined such as creating new users, authenticating, and listing users.&lt;/p&gt;&lt;p&gt;The full source for this tutorial is available on &lt;a href='https://github.com/yogthos/swagger-service'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;As you can see, &lt;code&gt;compojure-api&lt;/code&gt; allows us to easily define RESTful services with type assertions, documentation, and a helpful test page. I've found this approach to be extremely effective when creating service APIs as it documents what each endpoint is doing and makes it easy to collaborate with consumers of the service. Meanwhile, Duct provides an excellent base for building services using the component pattern.&lt;/p&gt;</description><pubDate>Thu, 01 Oct 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-07-11-Luminus-HTTPKit.html</guid><link>https://yogthos.net/posts/2015-07-11-Luminus-HTTPKit.html</link><title>Luminus is Moving -&gt; HTTP Kit -&gt; Immutant</title><description> &lt;h2 id="update"&gt;Update&lt;/h2&gt;&lt;p&gt;After having some discussions with the author of HTTP Kit and doing a deeper evaluation of Immutant I'm switching to it as the default.&lt;/p&gt;&lt;p&gt;It turns out that Immutant addresses all of the concerns as well as HTTP Kit while having the benefit of a larger team maintaining it.&lt;/p&gt;&lt;p&gt;The version 2 of Immutant is modular and provides a minimal runtime that has low overhead. The websocket support works similarly to HTTP Kit and is now documented as well. Unlike Jetty 9 adapters with websocket support, Immutant builds do not require JRE 8 to run.&lt;/p&gt;&lt;p&gt;Finally, Immutant provides many useful pluggable libraries for caching, message queues, and scheduling.&lt;/p&gt;&lt;h2 id="end&amp;#95;update"&gt;End Update&lt;/h2&gt; &lt;p&gt;One of the guiding principles for Luminus has been to provide a great user experience out of the box. Having to go through a tedious setup before you can focus on the problem you actually want to solve should be unnecessary.&lt;/p&gt;&lt;p&gt;Luminus removes the burden or having to find the libraries, configure middleware, and add the common boilerplate. The application generated by the template is ready for  deployment out of the box. The only part that's missing is the domain logic for your application.&lt;/p&gt;&lt;p&gt;As the project evolves I'm always looking for new ways to streamline user experience. Clojure web ecosystem is rapidly evolving along with the best practices and tools. Luminus aims to keep abreast of these changes and to provide a reference implementation for Ring based applications.&lt;/p&gt;&lt;p&gt;Recently, Luminus moved to using &lt;a href='https://github.com/yogthos/migratus'&gt;Migratus&lt;/a&gt; for handling database migrations for reasons discussed in &lt;a href='http://yogthos.net/posts/2015-06-29-Luminus-Migratus.html'&gt;this&lt;/a&gt; post. This time we'll look at the reasons for moving to HTTP Kit as the default server.&lt;/p&gt;&lt;p&gt;Up to now, Luminus applications would use the version of Jetty packaged by the Ring dependency. The major drawback of the default Jetty adapter is its lack of support for websockets. After evaluating the alternatives I settled on HTTP Kit as the default server for Luminus.&lt;/p&gt;&lt;p&gt;HTTP Kit is built on top of &lt;a href='https://en.wikipedia.org/wiki/Non-blocking_I/O_(Java&amp;#41;'&gt;NIO&lt;/a&gt;. It combines &lt;a href='https://github.com/ptaoussanis/clojure-web-server-benchmarks'&gt;high performance&lt;/a&gt; when handling a large number of connections with &lt;a href='http://www.http-kit.org/600k-concurrent-connection-http-kit.html'&gt;low memory overhead&lt;/a&gt; per connection. Finally, it provides a Ring/Compojure compatible API for working with &lt;a href='https://en.wikipedia.org/wiki/WebSocket'&gt;websockets&lt;/a&gt; that's now &lt;a href='http://www.luminusweb.net/docs/websockets.md'&gt;part&lt;/a&gt; of the official Luminus documentation.&lt;/p&gt;&lt;p&gt;While HTTP Kit is the default, all the major HTTP servers are supported via their respective flags:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;+alpeh&lt;/code&gt; - &lt;a href='https://github.com/ztellman/aleph'&gt;Aleph&lt;/a&gt; is a stream based server built on top of Netty&lt;/li&gt;&lt;li&gt;&lt;code&gt;+immutant&lt;/code&gt; - &lt;a href='http://immutant.org/'&gt;Immutant&lt;/a&gt; is a &lt;a href='http://www.jboss.org/'&gt;JBoss&lt;/a&gt; based server with many built in features such as messaging, scheduling and caching&lt;/li&gt;&lt;li&gt;&lt;code&gt;+jetty&lt;/code&gt; - &lt;a href='https://github.com/mpenet/jet'&gt;Jet&lt;/a&gt; is the Ring Jetty adapter with websocket support&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Another major change is that the &lt;a href='https://github.com/weavejester/lein-ring'&gt;lein-ring&lt;/a&gt; plugin is no longer used by default. Since the plugin is based on the Jetty based &lt;a href='https://github.com/weavejester/ring-server'&gt;ring-server&lt;/a&gt; library, a separate workflow was required for the alternative HTTP servers.&lt;/p&gt;&lt;p&gt;Instead, the template now provides its own &lt;code&gt;core&lt;/code&gt; namespace that manages the server lifecycle. This provides a consistent experience regardless of the server being used. The &lt;code&gt;lein-ring&lt;/code&gt; plugin is now part of the &lt;code&gt;+war&lt;/code&gt; profile used to generate server independent WAR archives for deployment to application servers such as &lt;a href='http://tomcat.apache.org/'&gt;Apache Tomcat&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 11 Jul 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-07-07-Data-Focused.html</guid><link>https://yogthos.net/posts/2015-07-07-Data-Focused.html</link><title>Data Focused</title><description>&lt;p&gt;One interesting part I noticed about working with Clojure is that I practically never look for solutions to problems on Google or StackOverflow. I might google to see if a library exists for accomplishing a particular task, but I rarely end up having to google how to do a specific task.&lt;/p&gt;&lt;p&gt;This got me thinking about why that may be since I used to do that commonly back when I worked with Java. I think the key reason is that Clojure encourages writing code that operates on plain data.&lt;/p&gt;&lt;h3 id="object&amp;#95;oriented&amp;#95;approach"&gt;Object Oriented Approach&lt;/h3&gt;&lt;p&gt;Object oriented languages, such as Java, encourage encapsulating the data in domain specific abstractions. Rich Hickey discusses this in detail in his excellent &lt;a href='https://www.youtube.com/watch?v=VSdnJDO-xdg'&gt;Clojure, Made Simple&lt;/a&gt; talk. The OO approach ultimately leads to creation of frameworks that provide formalized ways to tie all the different domain abstractions together.&lt;/p&gt;&lt;p&gt;The problem with frameworks is that they impose a particular workflow on the user. However, in most cases there are many valid ways to solve a particular problem. The approach that the framework takes is just one way to do things and not necessarily the best way. If you happen to think about a problem differently from the authors of the framework then using it will not feel intuitive.&lt;/p&gt;&lt;p&gt;When you encounter a problem then you either have to spend the time to understand the internals of the framework and its design or simply memorize how different tasks are accomplished.&lt;/p&gt;&lt;p&gt;Understanding the internals of a complex piece of software is an arduous process that can take a long time and it's often time that you do not have. Conversely, having to understand the internals typically indicates that the abstraction you're working with is a leaky one.&lt;/p&gt;&lt;p&gt;This is where googling comes in. You know what your problem is, you know how you would solve it given the time, but you don't know how the authors of the framework expect you to solve it using their approach.&lt;/p&gt;&lt;p&gt;Since the choice of the solution completely arbitrary, there's no way for you to logically deduce what it is. In many cases the only realistic option is to hope that someone else ran into a similar problem already and see how they solved it within the context of the framework.&lt;/p&gt;&lt;h3 id="data&amp;#95;centric&amp;#95;approach"&gt;Data Centric Approach&lt;/h3&gt;&lt;p&gt;Clojure takes the approach of keeping the data and logic separate. Instead of building local abstractions for each domain as we do with objects, all the functions operate on a common set of data structures. When a function is called its output can be used in a new context without any additional ceremony.&lt;/p&gt;&lt;p&gt;Since all Clojure libraries use the same core data structures, it's trivial to take the output of one library and pass it as input to another. Using the REPL we can quickly see how a particular library behaves and what output it generates.&lt;/p&gt;&lt;p&gt;This approach allows the user to find the libraries that fit the problem they're solving and then compose them in the way that makes sense in their particular scenario. The same core pattern of composing data transformations can be applied at different resolutions within a project.&lt;/p&gt;&lt;p&gt;At the lowest level we have functions as our building blocks. We combine these in different ways to transform the data on the small scale.&lt;/p&gt;&lt;p&gt;Once we have a number of related functions that represent a particular domain we combine them into a namespace, and then we pass the data between the namespaces to move data from one domain to another.&lt;/p&gt;&lt;p&gt;Libraries are simply collections of namespaces, and we use the same pattern when  transform the data by combining them. A great example of this would be the &lt;a href='https://github.com/ring-clojure/ring-defaults/blob/3dca3756a33892f607c45bc4eb582796e4997dd9/src/ring/middleware/defaults.clj#L90'&gt;ring-defaults&lt;/a&gt; library that chains a number libraries to achieve complex transformations of HTTP requests and responses.&lt;/p&gt;&lt;p&gt;Finally, at the top level we may have multiple projects passing data between each other in form of services. This approach is becoming increasingly popular in the industry as seen with the micro-services movement.&lt;/p&gt;&lt;p&gt;With Clojure, the focus is always on the data. When solving a problem, all we have to do is figure out how we need to transform the data and then find the appropriate building blocks for our problem.&lt;/p&gt;&lt;p&gt;Focusing on the data helps keep code simple and reusable without introducing unnecessary indirection into the process. I think this is the key reason why it's possible to work with Clojure without having to constantly memorize new patterns to solve different kinds problems.&lt;/p&gt;</description><pubDate>Tue, 07 Jul 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-06-29-Luminus-Migratus.html</guid><link>https://yogthos.net/posts/2015-06-29-Luminus-Migratus.html</link><title>Luminus is Migrating to Migratus</title><description> &lt;p&gt;There was a recent discussion on &lt;a href='https://groups.google.com/forum/#!topic/luminusweb/rRJYbyUOKAY'&gt;google groups&lt;/a&gt; regarding migrations and handling of database credentials in Luminus. Up to now, Luminus would generate a template where the database credentials were hardcoded in the &lt;code&gt;&amp;lt;app&amp;gt;.db.core&lt;/code&gt; namespace and migrations were handled by the &lt;a href='https://github.com/weavejester/ragtime/tree/0.3/ragtime.lein'&gt;ragtime.lein&lt;/a&gt; plugin.&lt;/p&gt;&lt;p&gt;This was not ideal for a couple of reasons. First, the hardcoded credentials aren't great for any serious applications. The credentials end up being checked in the code repository and have to be manually updated for each environment the application runs in. Second, you end up with separate sets of database configuration for the application and for the plugin. This is error prone as it puts the burden on the user to keep the credentials in sync.&lt;/p&gt;&lt;p&gt;The proposed approach was to use the &lt;code&gt;profiles.clj&lt;/code&gt; instead to keep a single set of credentials for development. The production credentials would then be supplied using environment variables. This is a much cleaner approach to handling credentials as they're no longer part of the code and can be configured in a single place.  &lt;/p&gt;&lt;p&gt;In the meantime, Ragtime had a new major version release &lt;a href='https://github.com/weavejester/ragtime'&gt;0.4.0&lt;/a&gt; that introduces a number of changes. Ragtime is moving away from using a Leiningen plugin, and instead recommends &lt;a href='https://github.com/weavejester/ragtime/wiki/Leiningen-Integration'&gt;running the commands from the REPL&lt;/a&gt;. The other major change is that it&lt;a href='https://github.com/weavejester/ragtime/wiki/SQL-Migrations#sql'&gt; no longer allows multiple statements  in a single migrations file&lt;/a&gt;.  &lt;/p&gt;&lt;p&gt; The rationale here is that different SQL databases have different restrictions on the commands that can be sent in a single message. Therefore using a heuristic to split up migrations isn't guaranteed to work correctly across different database engines.  &lt;/p&gt;&lt;p&gt; While this is true, in my view it also results in subpar user experience. While it's ok for trivial migrations, such as the ones seen in the examples, it doesn't scale well for larger ones. I think that there is a lot of value in being able to see the entirety of a migration in a single place without having to jump across multiple files.  &lt;/p&gt;&lt;p&gt; &lt;strong&gt;update:&lt;/strong&gt; Since the writing of the post, Ragtime has &lt;a href='https://github.com/weavejester/ragtime/commit/eea75fcfc1a6d51c28bfb9dc58540a842f2111d5'&gt;added&lt;/a&gt; the ability to use a custom separator, so it should be available in the next release.  &lt;/p&gt;&lt;p&gt;At this point I decided to see what other migrations libraries were available and to evaluate if any of them would be a good fit for the workflow that Luminus aims to provide. The one I settled on was &lt;a href='https://github.com/pjstadig/migratus'&gt;Migratus&lt;/a&gt;. It provides a workflow that's nearly identical to the original Ragtime based one that Luminus used.&lt;/p&gt;&lt;p&gt;Migrtus elegantly addresses the problem of splitting up statements by using a custom separator &lt;code&gt;--;;&lt;/code&gt; to identify individual statements within the file. This removes the ambiguity of having to infer where one statement ends and another begins without forcing the user to split their migrations into multiple files.&lt;/p&gt;&lt;p&gt;Unfortunately, Migratus has not been maintained for the past two years and relied on a deprecated version of the &lt;code&gt;clojure.java.jdbc&lt;/code&gt; library. Since Migratus already works well and it's a relatively simple library I decided to see if I could bring it up to date.&lt;/p&gt;&lt;p&gt;This turned out to be a relatively painless process and I ended up making some minor changes and improvements along the way. I contacted Paul Stadig, who is the author of the library, and he graciously agreed to transfer the ownership as he's no longer planning on developing it himself. I've released the updated library to Clojars and the latest version of Luminus uses Migratus to handle migrations.&lt;/p&gt;&lt;p&gt;As I mentioned earlier, using a Leiningen plugin to handle dev migrations requires dupliction of credentials. Instead, Luminus now provides an &lt;code&gt;&amp;lt;app&amp;gt;.db.migrations&lt;/code&gt; namespace that manages migrations. This namespace is invoked from the &lt;code&gt;&amp;lt;app&amp;gt;.core/-main&lt;/code&gt; when it's passed in &lt;code&gt;migrate&lt;/code&gt; or &lt;code&gt;rollback&lt;/code&gt; arguments. These arguments can be optionally followed by the migration ids in order to apply specific migrations. So, when previously you would run &lt;code&gt;lein ragtime migrate&lt;/code&gt;, you'd now run &lt;code&gt;lein run migrate&lt;/code&gt; to apply migrations.&lt;/p&gt;&lt;p&gt;Since this code is now part of the project it can now be run from the packaged &lt;code&gt;uberjar&lt;/code&gt; as well. This allows the application to run its migrations on the server without necessitating a separate process for migrating the production database. Complete migrations documentation is available on &lt;a href='http://www.luminusweb.net/docs/migrations.md'&gt;the offical Luminus site&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Having a straight forward way to run migrations and store credentials securely, taking into account production environments, is an important aspect of providing a solid base for developing web applications.&lt;/p&gt;</description><pubDate>Mon, 29 Jun 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-06-17-Using-Pulsar.html</guid><link>https://yogthos.net/posts/2015-06-17-Using-Pulsar.html</link><title>Using Pulsar</title><description>&lt;p&gt;In this post, we'll take a look at a basic usage example for Pulsar and see how to package it for production.&lt;/p&gt;&lt;h3 id="what&amp;#95;is&amp;#95;pulsar?"&gt;What is Pulsar?&lt;/h3&gt;&lt;p&gt;&lt;a href='http://docs.paralleluniverse.co/pulsar/'&gt;Pulsar&lt;/a&gt; is the official Clojure API for the &lt;a href='http://www.paralleluniverse.co/quasar/'&gt;Quasar&lt;/a&gt; library that provides lightweight green threads and Erlang style actors for the JVM.&lt;/p&gt;&lt;p&gt;Quasar has a lot of similarities to the popular &lt;a href='http://akka.io/'&gt;Akka framewok&lt;/a&gt;, but has the advantage of being a library as opposed to a framework that imposes its own workflow. For those interested, a detailed comparison of Quasar and Akka is availble &lt;a href='http://blog.paralleluniverse.co/2015/05/21/quasar-vs-akka/'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Using Pulsar is very straight forward, however there are a few caveats to be aware of when it comes to packaging it for production. Quasar requires bytecode instrumentation in order to provide suspendanble functions, and this means that the &lt;code&gt;project.clj&lt;/code&gt; needs to have additional hints to facilitate it. &lt;/p&gt;&lt;h3 id="creating&amp;#95;the&amp;#95;project"&gt;Creating the Project&lt;/h3&gt;&lt;p&gt;Let's start by creating a new project called &lt;code&gt;pulsar-example&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new pulsar-example
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll add the following dependencies to the &lt;code&gt;project.clj&lt;/code&gt; file:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;co.paralleluniverse/pulsar &amp;quot;0.7.2&amp;quot;&amp;#93;
&amp;#91;co.paralleluniverse/quasar-core &amp;quot;0.7.2&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll also have to add a &lt;code&gt;:java-agents&lt;/code&gt; key that will invoke the Quasar agent responsible for the instrumentation:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:java-agents &amp;#91;&amp;#91;co.paralleluniverse/quasar-core &amp;quot;0.7.2&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="adding&amp;#95;actors"&gt;Adding Actors&lt;/h3&gt;&lt;p&gt;Let's open up the &lt;code&gt;pulsar-example.core&lt;/code&gt; namespace and update the &lt;code&gt;ns&lt;/code&gt; declaration as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns pulsar-example.core
  &amp;#40;:require
   &amp;#91;co.paralleluniverse.pulsar
    &amp;#91;core :refer :all&amp;#93;
    &amp;#91;actors :refer :all&amp;#93;&amp;#93;&amp;#41;
  &amp;#40;:refer-clojure :exclude &amp;#91;promise await&amp;#93;&amp;#41;
  &amp;#40;:gen-class&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll implement &lt;a href='https://github.com/puniverse/pulsar/blob/master/src/test/clojure/co/paralleluniverse/pulsar/examples/pingpong.clj'&gt;one of the official examples&lt;/a&gt; where two actors send messages to one another. In the example we have two functions called &lt;code&gt;ping&lt;/code&gt; and &lt;code&gt;pong&lt;/code&gt;. These are defined using the &lt;code&gt;defsfn&lt;/code&gt; macro as opposed to regular &lt;code&gt;defn&lt;/code&gt;. This is necessary in order for these functions to be suspendable.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;ping&lt;/code&gt; function will accept two parameters consisting of the number representing remaining iterations and the actor to send messages to.&lt;/p&gt;&lt;p&gt;The function checks if there are remaining iterations and notfies &lt;code&gt;pong&lt;/code&gt; that the conversation is complete when &lt;code&gt;n&lt;/code&gt; is zero. Otherwise, it sends a ping message to the &lt;code&gt;pong&lt;/code&gt; actor and waits to receive an acknowledgement before recurring. As you may have guessed, the &lt;code&gt;receive&lt;/code&gt; call will block until a message is received.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;@self&lt;/code&gt; notation is used to access the actor itself. This is needed to pass it to the other actor as part of the message in order to receive a response.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defsfn ping &amp;#91;n pong&amp;#93;
  &amp;#40;if &amp;#40;== n 0&amp;#41;
    &amp;#40;do
      &amp;#40;! pong :finished&amp;#41;
      &amp;#40;println &amp;quot;ping finished&amp;quot;&amp;#41;&amp;#41;
    &amp;#40;do
      &amp;#40;! pong &amp;#91;:ping @self&amp;#93;&amp;#41;
      &amp;#40;receive
        :pong &amp;#40;println &amp;quot;Ping received pong&amp;quot;&amp;#41;&amp;#41;
      &amp;#40;recur &amp;#40;dec n&amp;#41; pong&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Meanwhile, the &lt;code&gt;pong&lt;/code&gt; function will wait to receive a message, if the message is &lt;code&gt;:finished&lt;/code&gt; then it finishes its run, and if it matches &lt;code&gt;&amp;#91;:ping ping&amp;#93;&lt;/code&gt; then it will return the message &lt;code&gt;:ping&lt;/code&gt; to the caller and recur:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defsfn pong &amp;#91;&amp;#93;
  &amp;#40;receive
    :finished &amp;#40;println &amp;quot;Pong finished&amp;quot;&amp;#41;
    &amp;#91;:ping ping&amp;#93; &amp;#40;do
                   &amp;#40;println &amp;quot;Pong received ping&amp;quot;&amp;#41;
                   &amp;#40;! ping :pong&amp;#41;
                   &amp;#40;recur&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that the message can either be a keyword or a vector containing the parameters we wish to pass to the actor. Finally, we'll add a &lt;code&gt;-main&lt;/code&gt; function as the entry point to our program. Note that we &lt;code&gt;join&lt;/code&gt; our actors to ensure that the application keeps running until the actors exit.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn -main &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;a1 &amp;#40;spawn pong&amp;#41;
        b1 &amp;#40;spawn ping 3 a1&amp;#41;&amp;#93;
    &amp;#40;join a1&amp;#41;
    &amp;#40;join b1&amp;#41;
    :ok&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now test that everything is working by running it from the REPL or using &lt;code&gt;lein run&lt;/code&gt;.&lt;/p&gt;&lt;h3 id="packaging&amp;#95;for&amp;#95;deployment"&gt;Packaging for Deployment&lt;/h3&gt;&lt;p&gt;Once we're ready to package our app for deployment we need to make sure that the Quasar agent can be run to instrument our suspendable functions. To do that we'll have to add a &lt;code&gt;:manifest&lt;/code&gt; key to our project that points to the following configuration:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:manifest
 {&amp;quot;Premain-Class&amp;quot; &amp;quot;co.paralleluniverse.fibers.instrument.JavaAgent&amp;quot;
  &amp;quot;Agent-Class&amp;quot; &amp;quot;co.paralleluniverse.fibers.instrument.JavaAgent&amp;quot;
  &amp;quot;Can-Retransform-Classes&amp;quot; &amp;quot;true&amp;quot;
  &amp;quot;Can-Redefine-Classes&amp;quot; &amp;quot;true&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will be written out to the &lt;code&gt;META-INF/MANIFEST.MF&lt;/code&gt; file in the jar and provide the necessary information about the agent. The project can now be packaged by running &lt;code&gt;lein uberjar&lt;/code&gt;. One final thing to be aware of is that the resulting jar must be run with the &lt;code&gt;-javaagent&lt;/code&gt; flag as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;java -javaagent:target/pulsar-example.jar -jar target/pulsar-example.jar
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is all that needs to be done in order to package and run Pulsar projects using Leiningen. As always, the complete source for the example is available &lt;a href='https://github.com/yogthos/pulsar-example'&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Wed, 17 Jun 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-06-16-Figwheel-nREPL.html</guid><link>https://yogthos.net/posts/2015-06-16-Figwheel-nREPL.html</link><title>ClojureScript REPL with Figwheel</title><description>&lt;h4 id="update:&amp;#95;figwheel&amp;#95;changed&amp;#95;recently&amp;#95;and&amp;#95;the&amp;#95;new&amp;#95;process&amp;#95;of&amp;#95;starting&amp;#95;the&amp;#95;repl&amp;#95;is&amp;#95;documented&amp;#95;on&amp;#95;the&amp;#95;&lt;a href='https://github.com/bhauman/lein-figwheel/wiki'&gt;official Wiki&lt;/a&gt;."&gt;update: Figwheel changed recently and the new process of starting the REPL is documented on the &lt;a href='https://github.com/bhauman/lein-figwheel/wiki'&gt;official Wiki&lt;/a&gt;.&lt;/h4&gt;&lt;p&gt;Figwheel provides a fantastic developer experience and if you're not using it already I highly encourage you to give it a shot. I found that in most cases live code reloading is sufficient for my workflow, but there are occasions where I do want to have an actual REPL available.&lt;/p&gt;&lt;p&gt;This mostly comes up when I'm working with code that's not directly tied to rendering UI components and it can quickly devolve into &lt;code&gt;println&lt;/code&gt; debugging.&lt;/p&gt;&lt;p&gt;You probably noticed that Figwheel starts a REPL in the terminal when it runs. However, this REPL is not terribly useful in practice. What would be better is to have a REPL that's connected to the editor, such as Cursive or Emacs, so that you can evaluate the code you're working on the same way you would with Clojure.&lt;/p&gt;&lt;p&gt;Luckily, getting this to work turns out to be a pretty simple affair. First thing we need to do is to make sure that the Figwheel config in &lt;code&gt;project.clj&lt;/code&gt; has the &lt;code&gt;:nrepl-port&lt;/code&gt; key set as seen below:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:figwheel
{:http-server-root &amp;quot;public&amp;quot;
 :server-port 3449
 :nrepl-port 7002 ;;start nREPL on port 7002
 :css-dirs &amp;#91;&amp;quot;resources/public/css&amp;quot;&amp;#93;
 :ring-handler yourapp/handler}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When you run &lt;code&gt;lein figwheel&lt;/code&gt; the nREPL server will become available and you can connect your editor to it at &lt;code&gt;localhost:7002&lt;/code&gt;, or whatever port you've specifcied. Once the nREPL is connected you'll have to run the following commands there:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;user&amp;gt; &amp;#40;use 'figwheel-sidecar.repl-api&amp;#41;
user&amp;gt; &amp;#40;cljs-repl&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You should see the Figwheel REPL start up the same way it did when you ran &lt;code&gt;lein figwheel&lt;/code&gt; in the terminal. You should now be able to send any code from the editor to the REPL for evaluation.&lt;/p&gt;</description><pubDate>Tue, 16 Jun 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-06-11-Websockets.html</guid><link>https://yogthos.net/posts/2015-06-11-Websockets.html</link><title>Websockets with HTTP Kit</title><description>&lt;p&gt;In this post we'll look at working with websocks using Reagent and HTTP Kit. We'll see how to create a multi-user chat server that allows multiple clients to communicate with one another.&lt;/p&gt;&lt;p&gt;First thing to mention is that there are a couple of Clojure/Script libraries for working with websockets, such as &lt;a href='https://github.com/ptaoussanis/sente'&gt;Sente&lt;/a&gt; and &lt;a href='https://github.com/james-henderson/chord'&gt;Chord&lt;/a&gt;. However, what I'd like to illustrate is that using websockets directly from ClojureScript is extremely straight forward. Let's start by creating a new Luminus project that we'll use as the base for our example. We'll create the project using the &lt;code&gt;+http-kit&lt;/code&gt; profile:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus multi-client-ws +http-kit +cljs
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the application is created we'll need to startup the server and Figwheel. To do that, we'll need to run the following commands in separate terminals.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein run
&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;lein figwheel
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="the&amp;#95;server"&gt;The Server&lt;/h3&gt;&lt;p&gt;Let's create a new namespace called &lt;code&gt;multi-client-ws.routes.websockets&lt;/code&gt; and add the following references there:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
&amp;#40;ns multi-client-ws.routes.websockets
 &amp;#40;:require &amp;#91;compojure.core :refer &amp;#91;GET defroutes&amp;#93;&amp;#93;
           &amp;#91;org.httpkit.server
            :refer &amp;#91;send! with-channel on-close on-receive&amp;#93;&amp;#93;
           &amp;#91;cognitect.transit :as t&amp;#93;
           &amp;#91;taoensso.timbre :as timbre&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll create a Compojure route for our websocket handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defroutes websocket-routes
 &amp;#40;GET &amp;quot;/ws&amp;quot; request &amp;#40;ws-handler request&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where the &lt;code&gt;ws-handler&lt;/code&gt; function will look as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn ws-handler &amp;#91;request&amp;#93;
 &amp;#40;with-channel request channel
               &amp;#40;connect! channel&amp;#41;
               &amp;#40;on-close channel &amp;#40;partial disconnect! channel&amp;#41;&amp;#41;
               &amp;#40;on-receive channel #&amp;#40;notify-clients %&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The function accepts the request and passes it to the &lt;code&gt;org.httpkit.server/with-channel&lt;/code&gt; macro provided by the HTTP Kit API. The macro creates accepts the request as its argument and binds the value of the &lt;code&gt;:async-channel&lt;/code&gt; key to the second paramets representing the name of the channel. The statement following the channel name will be called once when the channel is created. In our case we'll call the &lt;code&gt;connect!&lt;/code&gt; function defined below any time a new client connects:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defonce channels &amp;#40;atom #{}&amp;#41;&amp;#41;

&amp;#40;defn connect! &amp;#91;channel&amp;#93;
 &amp;#40;timbre/info &amp;quot;channel open&amp;quot;&amp;#41;
 &amp;#40;swap! channels conj channel&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The function will log that a new channel was opened and add the channel to the set of open channels defined above.&lt;/p&gt;&lt;p&gt;When the client disconnects the &lt;code&gt;on-close&lt;/code&gt; function will be called. This function accepts the channel along with a handler. The handler should accept the channel and the disconnect status. Our handler will log that the channel disconnected and remove it from the set of open channels.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn disconnect! &amp;#91;channel status&amp;#93;
 &amp;#40;timbre/info &amp;quot;channel closed:&amp;quot; status&amp;#41;
 &amp;#40;swap! channels #&amp;#40;remove #{channel} %&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we have the &lt;code&gt;on-receive&lt;/code&gt; function that's called any time a client message is received. We'll pass it the &lt;code&gt;notify-clients&lt;/code&gt; function as the handler. This function will broadcast the message to all the connected clients.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn notify-clients &amp;#91;msg&amp;#93;
 &amp;#40;doseq &amp;#91;channel @channels&amp;#93;
     &amp;#40;send! channel msg&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's all we need to do to manage the lifecycle of the websocket connections and to handle client communication.&lt;/p&gt;&lt;p&gt;Next, We'll need to add the routes in our &lt;code&gt;multi-client-ws.handler&lt;/code&gt; namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def app
 &amp;#40;-&amp;gt; &amp;#40;routes
       websocket-routes
       &amp;#40;wrap-routes home-routes middleware/wrap-csrf&amp;#41;
       base-routes&amp;#41;
     middleware/wrap-base&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We will also have to update our &lt;code&gt;multi-client-ws.middleware/wrap-base&lt;/code&gt; middleware wrapper to remove the &lt;code&gt;wrap-formats&lt;/code&gt; middleware as it conflicts with handling websocket requests.&lt;/p&gt;&lt;h3 id="the&amp;#95;client"&gt;The Client&lt;/h3&gt;&lt;p&gt;We'll start by creating a &lt;code&gt;multi-client-ws.websockets&lt;/code&gt; in the &lt;code&gt;src-cljs/multi&amp;#95;client&amp;#95;ws&lt;/code&gt; folder. The namespace will require the transit library:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns multi-client-ws.websockets
 &amp;#40;:require &amp;#91;cognitect.transit :as t&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll define an atom to hold our websocket channel and a couple of helpers for reading and writing the JSON encoded transit messages.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defonce ws-chan &amp;#40;atom nil&amp;#41;&amp;#41;
&amp;#40;def json-reader &amp;#40;t/reader :json&amp;#41;&amp;#41;
&amp;#40;def json-writer &amp;#40;t/writer :json&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll now create a function to handle received messages. The function will accept the callback handler and return a function that decodes the transit message and passes it to the handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn receive-transit-msg!
 &amp;#91;update-fn&amp;#93;
 &amp;#40;fn &amp;#91;msg&amp;#93;
   &amp;#40;update-fn
     &amp;#40;-&amp;gt;&amp;gt; msg .-data &amp;#40;t/read json-reader&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll also create a function that sends messages to the socket if it's open:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn send-transit-msg!
 &amp;#91;msg&amp;#93;
 &amp;#40;if @ws-chan
   &amp;#40;.send @ws-chan &amp;#40;t/write json-writer msg&amp;#41;&amp;#41;
   &amp;#40;throw &amp;#40;js/Error. &amp;quot;Websocket is not available!&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, we'll add a function to create a new websocket given the URL and the received message handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn make-websocket! &amp;#91;url receive-handler&amp;#93;
 &amp;#40;println &amp;quot;attempting to connect websocket&amp;quot;&amp;#41;
 &amp;#40;if-let &amp;#91;chan &amp;#40;js/WebSocket. url&amp;#41;&amp;#93;
   &amp;#40;do
     &amp;#40;set! &amp;#40;.-onmessage chan&amp;#41; &amp;#40;receive-transit-msg! receive-handler&amp;#41;&amp;#41;
     &amp;#40;reset! ws-chan chan&amp;#41;
     &amp;#40;println &amp;quot;Websocket connection established with: &amp;quot; url&amp;#41;&amp;#41;
   &amp;#40;throw &amp;#40;js/Error. &amp;quot;Websocket connection failed!&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="the&amp;#95;ui"&gt;The UI&lt;/h3&gt;&lt;p&gt;We'll now navigate to the &lt;code&gt;multi-client-ws.core&lt;/code&gt; namespace and remove the code that's already there. We'll set the &lt;code&gt;ns&lt;/code&gt; definition to the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns multi-client-ws.core
 &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
           &amp;#91;multi-client-ws.websockets :as ws&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we'll create an atom to keep a list of messages and a Reagent component that renders it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defonce messages &amp;#40;atom &amp;#91;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn message-list &amp;#91;&amp;#93;
 &amp;#91;:ul
  &amp;#40;for &amp;#91;&amp;#91;i message&amp;#93; &amp;#40;map-indexed vector @messages&amp;#41;&amp;#93;
    &amp;#94;{:key i}
    &amp;#91;:li message&amp;#93;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll now create a &lt;code&gt;message-input&lt;/code&gt; component that will allow us to type in a message and send it to the server. This component creates a local atom to keep track of the message being typed in and sends the message to the server when the &lt;code&gt;enter&lt;/code&gt; key is pressed.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn message-input &amp;#91;&amp;#93;
 &amp;#40;let &amp;#91;value &amp;#40;atom nil&amp;#41;&amp;#93;
   &amp;#40;fn &amp;#91;&amp;#93;
     &amp;#91;:input.form-control
      {:type :text
       :placeholder &amp;quot;type in a message and press enter&amp;quot;
       :value @value
       :on-change #&amp;#40;reset! value &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;
       :on-key-down
       #&amp;#40;when &amp;#40;= &amp;#40;.-keyCode %&amp;#41; 13&amp;#41;
          &amp;#40;ws/send-transit-msg!
           {:message @value}&amp;#41;
          &amp;#40;reset! value nil&amp;#41;&amp;#41;}&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now create the &lt;code&gt;home-page&lt;/code&gt; component that looks as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;#93;
 &amp;#91;:div.container
  &amp;#91;:div.row
   &amp;#91;:div.col-md-12
    &amp;#91;:h2 &amp;quot;Welcome to chat&amp;quot;&amp;#93;&amp;#93;&amp;#93;
  &amp;#91;:div.row
   &amp;#91;:div.col-sm-6
    &amp;#91;message-list&amp;#93;&amp;#93;&amp;#93;
  &amp;#91;:div.row
   &amp;#91;:div.col-sm-6
    &amp;#91;message-input&amp;#93;&amp;#93;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll also create an &lt;code&gt;update-messages!&lt;/code&gt; function that will be used as the handler for the received messages. This function will append the new message and keep a buffer of 10 last received messages.&lt;/p&gt;&lt;p&gt;All that's left to do is mount the &lt;code&gt;home-page&lt;/code&gt; component and create the websocket in the &lt;code&gt;init!&lt;/code&gt; function:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn mount-components &amp;#91;&amp;#93;
 &amp;#40;reagent/render-component &amp;#91;#'home-page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
 &amp;#40;ws/make-websocket! &amp;#40;str &amp;quot;ws://&amp;quot; &amp;#40;.-host js/location&amp;#41; &amp;quot;/ws&amp;quot;&amp;#41; update-messages!&amp;#41;
 &amp;#40;mount-components&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We should now be able to open multiple browser windows and any messages typed in one window should show up in all the open windows.&lt;/p&gt;&lt;h3 id="conclusion"&gt;Conclusion&lt;/h3&gt;&lt;p&gt;As you can see, it's very easy to setup basic client-server communication between HTTP Kit and ClojureScript. While you may wish to use one of the libraries mentioned earlier for more sophisticated apps, it's certainly not necessary in many cases. The complete source for the example can be found on &lt;a href='https://github.com/luminus-framework/examples/tree/master/multi-client-ws-http-kit'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Thu, 11 Jun 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-04-14-Web-Development-with-Clojure-2.html</guid><link>https://yogthos.net/posts/2015-04-14-Web-Development-with-Clojure-2.html</link><title>Web Development with Clojure 2</title><description>&lt;p&gt;First, I'd like to thank all those who purchased the first edition of the book. I was overwhelmed by the response from the readers, and exhilirated to learn that it helped many start developing their web applications using Clojure. I'm excited to announce that I'm working on the second edition of &lt;a href='https://pragprog.com/book/dswdcloj/web-development-with-clojure'&gt;Web Development with Clojure&lt;/a&gt; and that I'm expecting to publish it sometime this summer.&lt;/p&gt;&lt;h2 id="what&amp;#95;to&amp;#95;expect"&gt;What to Expect&lt;/h2&gt;&lt;p&gt;The main goal of the book is to provide a no-nonsense introduction to web development using Clojure. As such, I chose to cover tools and libraries that I consider to be beginner friendly.&lt;/p&gt;&lt;p&gt;Clojure web ecosystem has been steadily maturing since the release of the first edition. Last time I illustrated a number of approaches for putting applications together without recommending any one in particular over the others. This time around I'm primarily focusing on building application based on the  &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; stack. Luminus has recently seen &lt;a href='http://yogthos.net/posts/2015-02-28-Luminus-2.0.html'&gt;a major update&lt;/a&gt; and continues to provide a solid foundation for building Clojure web applications according to best practices.&lt;/p&gt;&lt;p&gt;Clojure community favors using composable libraries over monolithic frameworks. This approach offers a number of advantages by giving the developer full control over the structure of the application the components used in it.&lt;/p&gt;&lt;p&gt;However, this approach works best for experienced developers who have a good understanding of the ecosystem and the available libraries. Having to develop this experience presents a significant barrier for newcomers. Luminus mitigates this issue by providing a batteries included template coupled with centralized documentation. This makes it a perfect foundation for a book aimed at beginners.&lt;/p&gt;&lt;p&gt;If you're familiar with the Clojure basics and you're looking to apply it for building web applications then this book is for you. The book aims to provide the reader with the understanding of the core ecosystem and the available tooling.&lt;/p&gt;&lt;h2 id="what's&amp;#95;new"&gt;What's New&lt;/h2&gt;&lt;p&gt;Those who are familiar with the first edition will find a number of changes and a number of new topics covered this time around.&lt;/p&gt;&lt;p&gt;At the time of writing of the first edition I felt that ClojureScript was not quite ready for general consumption. While some companies were already using it in production, the tooling around it was often challenging to use. As such, the book only gave it a very brief introduction and focused on traditional server side templating instead.&lt;/p&gt;&lt;p&gt;ClojureScript has matured greatly in the past year and the tooling is rapidly improving, while libraries such as Om and Reagent provide a clear benefit over using plain JavaScript. This time around ClojureScript is front and center with a primary focus on building single page apps using the Reagent library. I chose Reagent over Om for reasons I've discussed &lt;a href='http://yogthos.net/posts/2014-07-15-Building-Single-Page-Apps-with-Reagent.html'&gt;here&lt;/a&gt;. In short, I find that it's much easier to learn and apply effectively. The main project in the book that guides the reader through developing a multi-user picture gallery application is now developed as a single page application using Reagent.&lt;/p&gt;&lt;p&gt;Another major change is that I no longer recommend using &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt; for developing new applications. While the library provides a number of helpers for achieving many common tasks found in typical web applications, it also introduces some problems inherent in its design. I've discussed some of these  in my &lt;a href='http://yogthos.net/posts/2015-02-28-Luminus-2.0.html'&gt;last post&lt;/a&gt;. Today, there are excellent standalone libraries available for each of the tasks that &lt;code&gt;lib-noir&lt;/code&gt; was used for and I recommend using these instead.&lt;/p&gt;&lt;p&gt;The database chapter has been updated to introduce the excellent &lt;a href='https://github.com/krisajenkins/yesql'&gt;Yesql&lt;/a&gt; library and use the syntax of the latest version of &lt;a href='https://github.com/clojure/java.jdbc'&gt;clojure.java.jdbc&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I’m now covering the use of the &lt;a href='https://github.com/metosin/compojure-api'&gt;compojure-api&lt;/a&gt; library along side &lt;a href='http://clojure-liberator.github.io/liberator/'&gt;Liberator&lt;/a&gt;. I’ve had an excellent experience using this library and I highly recommend trying it out if you haven’t already. The library uses &lt;a href='https://github.com/Prismatic/schema'&gt;Prismatic/schema&lt;/a&gt;  to define the service API and allows automatic generation of interactive &lt;a href='http://swagger.io/'&gt;Swagger&lt;/a&gt; documentation such as seen &lt;a href='http://petstore.swagger.io/'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Finally, the book will provide more information on topics such as database migrations and deployment as part of addressing some of the feedback from the previous edition.&lt;/p&gt;&lt;p&gt;My hope is that the book will be useful to both new readers as well as those who purchased the first edition.&lt;/p&gt;</description><pubDate>Tue, 14 Apr 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-02-28-Luminus-2.0.html</guid><link>https://yogthos.net/posts/2015-02-28-Luminus-2.0.html</link><title>Announcing Luminus 2.0</title><description>&lt;p&gt;I'm excited to announce the release of Luminus 2.0. This release is a major update and introduces a number of changes to the framework. These changes reflect the evolution of the Clojure web stack and best practices over the past year.&lt;/p&gt;&lt;p&gt;The biggest change is that Luminus is no longer using &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt;, nor will I be actively developing the library going forward. I intend to continue maintaining it and to provide bug fixes, but I will not be working on additional features. If anybody is interested in taking it over then please leave a comment on GitHub in that regard.&lt;/p&gt;&lt;p&gt;I believe that lib-noir has served an important role providing many useful features such as input validation, access rules, session handling and so on. However, today there are great standalone libraries available for accomplishing each of these tasks. I believe that using simple and focused libraries leads to better overall user experience. The libraries that Luminus currently defaults to are as follows:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;access rules - &lt;a href='https://github.com/funcool/buddy'&gt;Buddy&lt;/a&gt;&lt;/li&gt;&lt;li&gt;cache  - &lt;a href='https://github.com/clojure/core.cache'&gt;core.cache&lt;/a&gt;&lt;/li&gt;&lt;li&gt;crypto - &lt;a href='https://github.com/funcool/buddy'&gt;Buddy&lt;/a&gt;&lt;/li&gt;&lt;li&gt;database - &lt;a href='https://github.com/krisajenkins/yesql'&gt;Yesql&lt;/a&gt;&lt;/li&gt;&lt;li&gt;sessions/cookies - &lt;a href='https://github.com/ring-clojure/ring/wiki/Sessions'&gt;Ring&lt;/a&gt;&lt;/li&gt;&lt;li&gt;validation - &lt;a href='https://github.com/leonardoborges/bouncer'&gt;Bouncer&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Session management is the biggest change from the user perspective. While lib-noir uses a request bound session that can be manipulated anywhere within the scope of the request, Ring requires sessions to be associated with the response explicitly by the handler.&lt;/p&gt;&lt;p&gt;While lib-noir approach is unquestionably convenient it introduces a subtle problem. Since the session is bound to a thread-local variable it's possible to run into race conditions with the in-memory session store. I feel that the Ring approach results in simpler design that’s more explicit about what it’s doing.&lt;/p&gt;&lt;p&gt;The new middleware stack is now based on  &lt;a href='https://github.com/ring-clojure/ring-defaults'&gt;ring-defaults&lt;/a&gt; instead of the &lt;code&gt;app-handler&lt;/code&gt; from lib-noir as Noir specific middleware is no longer required.&lt;/p&gt;&lt;p&gt;The move from Korma to Yesql is another major change. While Korma provides a nice DLS for working with SQL, I feel that the sheer simplicity of Yesql is preferable in the long run.&lt;/p&gt;&lt;p&gt;Meanwhile, Buddy is an exciting set of libraries for handling authorization, authentication, and access rules. It has an intuitive API and excellent documentation.&lt;/p&gt;&lt;p&gt;Bouncer is an excellent validation library that works with both Clojure and ClojureScript allowing for shared validation logic between the server and the client.&lt;/p&gt;&lt;p&gt;Some other changes include the &lt;code&gt;+cljs&lt;/code&gt; profile updates for &lt;a href='https://github.com/bhauman/lein-figwheel'&gt;Figwheel&lt;/a&gt; support and the deprecation of the &lt;code&gt;+site&lt;/code&gt; profile. It's been replaced with the &lt;code&gt;+auth&lt;/code&gt; profile  that sets up Buddy middleware for session based authentication instead.&lt;/p&gt;&lt;p&gt;As always, the framework primarily strives to remove the boilerplate from typical web projects and provide reasonable defaults. If you don’t agree with any of the library choices that it makes it’s trivial to swap them out with your own. The base profile is intentionally kept minimal to provide an unopinionated default.&lt;/p&gt;&lt;p&gt;The &lt;a href='https://github.com/yogthos/luminus-template'&gt;template project&lt;/a&gt; for Luminus has been completely rewritten as well. The new template cleanly separates different profiles making it much easier to maintain and add new features.&lt;/p&gt;&lt;p&gt;Finally, all the documentation has been updated to reflect the changes with the original made available on &lt;a href='https://github.com/yogthos/luminus/tree/master/resources/docs-1.x'&gt;GitHub&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 28 Feb 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2015-01-15-A-Plugin-System-in-Clojure.html</guid><link>https://yogthos.net/posts/2015-01-15-A-Plugin-System-in-Clojure.html</link><title>A simple plugin system in Clojure</title><description>&lt;p&gt;In this post we’ll see how to create a simplistic plugin system where plugins can be supplied as Leiningen dependencies and automatically initialized without any additional code change in the application.&lt;/p&gt;&lt;p&gt;Let’s take a look at Cryogen for a concrete example of how this can be useful. Cryogen started out using Markdown for content encoding, and we recently got a pull request that adds &lt;a href='https://github.com/cryogen-project/cryogen/pull/43'&gt;AsciiDoc support&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;It’s always great to get additional features, but sometimes features also carry an undesirable cost. It turns out that AsciiDoc support relies on &lt;a href='https://github.com/asciidoctor/asciidoctorj'&gt;AsciidoctorJ&lt;/a&gt;, that in turn relies on JRuby and pulls in a huge amount of additional dependencies. This has a significant impact on the startup time of the application.&lt;/p&gt;&lt;p&gt;For anybody who isn’t using AsciiDoc the new feature simply degrades the user experience. So, ideally we’d like to keep AsciiDoc as a feature, but also avoid impacting users who aren’t using it. The ideal scenario is to be able to split out the parsers into standalone libraries and include the ones we need. This also has the benefit of people being able to write their own custom plugins that add the features they need without having to update the core project.&lt;/p&gt;&lt;p&gt;The approach I took here was to create an &lt;code&gt;init&lt;/code&gt; function for each plugin that will take care of any initialization that the plugin needs to do and register it with the system.&lt;/p&gt;&lt;p&gt;All the available parsers are stored in an atom called &lt;code&gt;markup-registry&lt;/code&gt; in &lt;a href='https://github.com/cryogen-project/cryogen-core'&gt;cryogen-core&lt;/a&gt;, and each plugin simply updates the registry when it loads:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn init &amp;#91;&amp;#93;
  &amp;#40;swap! markup-registry conj &amp;#40;markdown&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The full code for the Markdown plugin can be seen &lt;a href='https://github.com/cryogen-project/cryogen-markdown/blob/master/src/cryogen_markdown/core.clj'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Next, we need to make our plugins discoverable so that they can be loaded when the application starts. This can be done using a configuration file that can be found on a classpath. Cryogen plugin configuration is stored in &lt;code&gt;resources/plugin.edn&lt;/code&gt; using the following format:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:description &amp;quot;Markdown parser&amp;quot;
 :init cryogen-markdown.core/init}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using the above information we can load the appropriate namespace and run the initializer function for the plugin.&lt;/p&gt;&lt;p&gt;First, we need to grab all the resources with the name &lt;code&gt;plugin.edn&lt;/code&gt; which can done as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn load-plugins &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;plugins &amp;#40;.getResources &amp;#40;ClassLoader/getSystemClassLoader&amp;#41; &amp;quot;plugin.edn&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;loop &amp;#91;&amp;#93;
      &amp;#40;load-plugin &amp;#40;.. plugins nextElement openStream&amp;#41;&amp;#41;
      &amp;#40;when &amp;#40;.hasMoreElements plugins&amp;#41;
        &amp;#40;recur&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we read the configuration for each resource, require its namespace and then run the initializer functions as seen below:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn load-plugin &amp;#91;url&amp;#93;
  &amp;#40;let &amp;#91;{:keys &amp;#91;description init&amp;#93;} &amp;#40;edn/read-string &amp;#40;slurp url&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;println &amp;#40;green &amp;#40;str &amp;quot;loading module: &amp;quot; description&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;-&amp;gt; init str &amp;#40;s/split #&amp;quot;/&amp;quot;&amp;#41; first symbol require&amp;#41;
    &amp;#40;&amp;#40;resolve init&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that in place we simply run &lt;code&gt;load-plugins&lt;/code&gt; when the applicatin starts and any plugins found on the classpath will be initialized. All the user has to do is select what plugins they want to include in their dependencies to get the functionality they need.&lt;/p&gt;</description><pubDate>Thu, 15 Jan 2015 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-12-1-State-of-Reagent.html</guid><link>https://yogthos.net/posts/2014-12-1-State-of-Reagent.html</link><title>The State of Reagent</title><description>&lt;p&gt;I'm happy to report that Dan Holmsand has graciously agreed to move &lt;a href='https://github.com/reagent-project/reagent'&gt;Reagent&lt;/a&gt; to a GitHub Organization called the &lt;a href='https://github.com/reagent-project'&gt;reagent-project&lt;/a&gt;. The organization will help spread the work as well as provide a hub for all the related projects. There has been a lot of recent interest in the org and several projects have already migrated under the umbrella.&lt;/p&gt;&lt;p&gt;First, I'd like to mention the &lt;a href='https://github.com/reagent-project/reagent-cookbook'&gt;reagent-cookbook&lt;/a&gt; project that provides many recipes for accomplishing common tasks, such as Js library integration, using Reagent. The project provides clear and simple guidelines for contributing to help ensure that all recipes have a common format that's easy to follow. Next addition is the &lt;a href='https://github.com/reagent-project/historian'&gt;Historian&lt;/a&gt; project that provides drop-in undo/redo functionality for Reagent. World Singles has recently &lt;a href='https://groups.google.com/forum/#!msg/clojurescript/r9B1k4MoTXA/J5gdZBa-BwUJ'&gt;switched from Om to Reagent&lt;/a&gt; and Sean Corfield has added &lt;a href='https://github.com/reagent-project/reagent-cursor'&gt;reagent-cursor&lt;/a&gt; library for Om-like cursor support in the process. Finally, there is my own &lt;a href='https://github.com/reagent-project/reagent-forms'&gt;reagent-forms&lt;/a&gt; library for creating data bindings using Reagent.&lt;/p&gt;&lt;p&gt;New Reagent projects can now be easily created and run using the &lt;a href='https://github.com/reagent-project/reagent-template'&gt;reagent-template&lt;/a&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new reagent my-app
cd my-app
lein cljsbuild auto &amp;amp;
lein ring server
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The template will generate a Clojure/Clojurescript web app that's designed to get you up and running without any tedious setup. The resulting project is setup to use &lt;a href='https://github.com/bhauman/lein-figwheel'&gt;Figwheel&lt;/a&gt; for live code reloading and &lt;a href='https://github.com/tomjakubowski/weasel'&gt;weasel&lt;/a&gt; for the REPL enabling smooth development out of the box.&lt;/p&gt;&lt;p&gt;The template uses sane library and configuration choices across the stack with Reagent for the UI, &lt;a href='https://github.com/gf3/secretary'&gt;Secretary&lt;/a&gt; for client side routing, and the Ring/Compojure stack on the backend.&lt;/p&gt;&lt;p&gt;The dev server and packaging are handled by &lt;a href='https://github.com/weavejester/lein-ring'&gt;lein-ring&lt;/a&gt; that will take care of reloading changes during development and producing either an uberjar or an uberwar for running standalone or deploying to a container respectively. The project also contains a &lt;code&gt;Procfile&lt;/code&gt; for instant Heroku deployment. For more details, please visit the project page &lt;a href='https://github.com/reagent-project/reagent-template'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;As you can see, much has happened with Reagent in the past month and the future is looking very bright. If you haven't tried Reagent yet, there's never been a better time than now. :)&lt;/p&gt;</description><pubDate>Mon, 01 Dec 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-11-26-Moving-to-Cryogen.html</guid><link>https://yogthos.net/posts/2014-11-26-Moving-to-Cryogen.html</link><title>Moving to Cryogen</title><description>&lt;p&gt;The blog has officially been moved over to &lt;a href='https://github.com/lacarmen/cryogen'&gt;Cryogen&lt;/a&gt;. While, all the content has been migrated over, the links for the posts have changed and the original comments are no longer available since I'm now using Disqus.&lt;/p&gt;&lt;p&gt;&lt;a href='https://github.com/yogthos/yuggoth'&gt;Yuggoth&lt;/a&gt; was a fun experment and it held up to most traffic storms over the years, but at the end of the day it's hard to beat the simplicity of a static site.&lt;/p&gt;&lt;p&gt;Porting the content from my old blog turned out to be a simple affair. I used Postgres to store all the blog content in Yuggoth. The database contains tables for the posts, the comments, the tags, and the files. All I had to do was extract the data and write it back out using the Cryogen format. First, I extracted the binary data for the files as seen below.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn write-file &amp;#91;{:keys &amp;#91;data name&amp;#93;}&amp;#93;
   &amp;#40;with-open &amp;#91;w &amp;#40;clojure.java.io/output-stream
                   &amp;#40;str &amp;quot;resources/templates/files/&amp;quot; name&amp;#41;&amp;#41;&amp;#93;
     &amp;#40;.write w data&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn extract-files &amp;#91;&amp;#93;
  &amp;#40;doseq &amp;#91;file &amp;#40;sql/query db &amp;#91;&amp;quot;select &amp;#42; from file&amp;quot;&amp;#93;&amp;#41;&amp;#93;
    &amp;#40;write-file file&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The posts table contains the content, while the tags are stored in a separate table. The tags can be aggregated by post using the handy &lt;code&gt;array&amp;#95;agg&lt;/code&gt; function. This function will produce a &lt;code&gt;Jdbc4Array&lt;/code&gt; as the result, and its contents can then be extracted to a vector.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn extract-tags &amp;#91;post&amp;#93;
  &amp;#40;update-in post &amp;#91;:tags&amp;#93; #&amp;#40;vec &amp;#40;.getArray %&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn get-posts &amp;#91;&amp;#93;
  &amp;#40;map extract-tags
       &amp;#40;sql/query db
         &amp;#91;&amp;quot;select array&amp;#95;agg&amp;#40;t.tag&amp;#41; as tags,
                  b.id, b.time, b.title, b.content from blog b, tag&amp;#95;map t
           where t.blogid = b.id
           group by b.id, b.time, b.title, b.content&amp;quot;&amp;#93;&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, all that's left to do is to generate the post metadata and the file name. Since each post contains a publication date and a title, these can be used to produce a filename in the format expected by Cryogen.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn format-post-date &amp;#91;date&amp;#93;
  &amp;#40;let &amp;#91;fmt &amp;#40;java.text.SimpleDateFormat. &amp;quot;dd-MM-yyyy&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;.format fmt date&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn format-post-filename &amp;#91;time title&amp;#93;
  &amp;#40;str
    &amp;#40;-&amp;gt;&amp;gt; &amp;#40;re-seq #&amp;quot;&amp;#91;a-zA-Z0-9&amp;#93;+&amp;quot; title&amp;#41;
         &amp;#40;clojure.string/join &amp;quot;-&amp;quot;&amp;#41;
         &amp;#40;str &amp;quot;resources/templates/md/posts/&amp;quot; &amp;#40;format-post-date time&amp;#41; &amp;quot;-&amp;quot;&amp;#41;&amp;#41;
   &amp;quot;.md&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that in place we can simply run through all the posts and extract them into appropriate files.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn write-post &amp;#91;{:keys &amp;#91;id time tags content title&amp;#93;}&amp;#93;
  &amp;#40;with-open &amp;#91;wrt &amp;#40;clojure.java.io/writer &amp;#40;format-post-filename time title&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;.write wrt
            &amp;#40;with-out-str
              &amp;#40;clojure.pprint/pprint
                {:title title
                 :layout :post
                 :tags &amp;#40;vec &amp;#40;.split tags &amp;quot; &amp;quot;&amp;#41;&amp;#41;}&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;.write wrt &amp;quot;\n&amp;quot;&amp;#41;
    &amp;#40;.write wrt content&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn extract-posts &amp;#91;&amp;#93;
  &amp;#40;doseq &amp;#91;post &amp;#40;get-posts&amp;#41;&amp;#93;
    &amp;#40;write-post post&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And that's all there is to it. Moral of the story is that we should always keep the data separate from its representation as you never know when you will need it down the road.&lt;/p&gt;</description><pubDate>Wed, 26 Nov 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-11-13-Cryogen-static-site-generation-made-easy.html</guid><link>https://yogthos.net/posts/2014-11-13-Cryogen-static-site-generation-made-easy.html</link><title>Cryogen: static site generation made easy</title><description>&lt;p&gt;&lt;a href='https://github.com/lacarmen/cryogen'&gt;Cryogen&lt;/a&gt; is a new Clojure static site generator by &lt;a href='https://github.com/lacarmen'&gt;Carmen La&lt;/a&gt;. Since there are already many popular site generators such as Jekyll, let's take a look at what makes Cryogen interesting.&lt;/p&gt;&lt;p&gt;In my opinion, the main feature of this project is its simplicity. Cryogen is shipped as a Leiningen template and all you have to do to create a site is run:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new cryogen my-blog
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will create an instance of the project with a template site initialized. The site can be run in dev mode using:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein ring server
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt; Once started, a helpful readme is shown on what to do next, which is a really nice touch.&lt;/p&gt;&lt;p&gt;The server will watch for changes in the &lt;code&gt;resources/templates&lt;/code&gt; folder and recompile the site whenever updates are detected. The compiled site is served from &lt;code&gt;resources/public&lt;/code&gt;. The static assets generated there can now be copied to over to be served by Nginx or Apache in production.&lt;/p&gt;&lt;p&gt;The layout is handled using &lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt; templates, while the content of the posts and the pages is written using Markdown with the help of &lt;a href='https://github.com/yogthos/markdown-clj'&gt;markdown-clj&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The generator handles all the common things like linking up pages, creating tags, syntax highlighting, sitemap, and RSS our of the box.&lt;/p&gt;&lt;p&gt;While most site generators take the approach of providing numerous configuration options for customization, Cryogen simply gives you the code to customize any way you see fit. You can simply go to the &lt;code&gt;cryogen.compiler&lt;/code&gt; namespace and easily change its behaviour to fit whatever it is you're doing. The compiler code is very clean and easy to follow, making it easy to customize.&lt;/p&gt;&lt;p&gt;I definitely recommend taking a look at this project if you're looking to make a static site in the future.&lt;/p&gt;</description><pubDate>Thu, 13 Nov 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-10-08-Clojure-Cup-Results.html</guid><link>https://yogthos.net/posts/2014-10-08-Clojure-Cup-Results.html</link><title>Clojure Cup Results</title><description>&lt;p&gt;Clojure Cup results are in and you can see the winning entries &lt;a href='https://clojurecup.com/'&gt;here&lt;/a&gt;. Kudos to all the teams who participated in the event!&lt;/p&gt;&lt;p&gt;It was exciting to see a wide variety of ideas explored during the event as well as the number of projects that were taken to completion. It's extremely impressive to see the kinds of Clojure apps that can be built from scratch in just a couple of days.&lt;/p&gt;&lt;p&gt;The scope of the competition clearly grew from last year, the prizes were bigger, the teams were larger, and the projects were more ambitious. One major change that I noticed was that a lot more projects were using ClojureScript and many of these used Om and Reagent to build the UI. It's great to see ClojureScript taking off and bringing some sanity to the world of front-end development.&lt;/p&gt;&lt;p&gt;Overall, I think it was an exciting event and I highly recommend browsing through the &lt;a href='https://clojurecup.com/#/apps'&gt;apps&lt;/a&gt;. Many of the projects are &lt;a href='https://github.com/clojurecup2014'&gt;hosted on GitHub&lt;/a&gt; and it's worth exploring the code to learn some new tricks. :)&lt;/p&gt;&lt;p&gt;I can't wait to see what Clojure Cup 2015 will bring.&lt;/p&gt;</description><pubDate>Wed, 08 Oct 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-10-03-Parsing-and-rendering-templates-in-Clojure-Haskell.html</guid><link>https://yogthos.net/posts/2014-10-03-Parsing-and-rendering-templates-in-Clojure-Haskell.html</link><title>Parsing and rendering templates in Clojure &amp; Haskell</title><description>&lt;p&gt;A little while back &lt;a href='https://github.com/bitemyapp'&gt;Chris Allen&lt;/a&gt; discovered the joys of Haskell. We had a few discussions regarding the merits of static typing and whether Haskell would be a more productive language than Clojure.&lt;/p&gt;&lt;p&gt;Haskell was my first foray into functional programming, and it's the language that made me fall in love with it. However, I also found that non-trivial type relationships would often require a lot of mental gymnastics. Eventually, I ended up moving to Clojure as I realized that I was simply more productive in it.&lt;/p&gt;&lt;p&gt;Chris would have none of this, and repeatedly told me that I was simply lying about having tried Haskell, since nobody could possibly enjoy using a dynamic language after seeing the glory of HM type inference.&lt;/p&gt;&lt;p&gt;These sorts of debates are rather tiring, so instead I proposed that Chris would translate a small piece of Clojure code to Haskell. Then we could discuss the merits of each approach using a concrete example.&lt;/p&gt;&lt;p&gt;On December of 2013, I posted &lt;a href='https://gist.github.com/yogthos/8025281'&gt;this gist&lt;/a&gt; and while it's not trivial, it weighs in at about 70 lines of code. It's a minimal example where I find Haskell starts making things unnecessarily difficult.&lt;/p&gt;&lt;p&gt;The code runs through a stream and looks for either &lt;code&gt;{{...}}&lt;/code&gt; or &lt;code&gt;{% if ... %}&lt;/code&gt; tags. It is intentionally kept short to limit noise, so it simply reads the tag names and prints them out. Since the code is a dumbed down version of &lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt;, which Chris participated on writing, I assumed he would have little difficulty reading and translating it.&lt;/p&gt;&lt;p&gt;To my surprise he started making excuses that if he did translate it then it would give me ammunition to complain about Haskell being difficult. I think that's a rather strange argument to make for somebody making the case that Haskell makes things simpler.&lt;/p&gt;&lt;p&gt;Then he said he'd do it using the &lt;a href='http://www.haskell.org/haskellwiki/Parsec'&gt;Parsec&lt;/a&gt; library, which obviously defeats the point. The question is not whether you can figure out a library API in Haskell, but how would you translate specific piece of Clojure code to Haskell.&lt;/p&gt;&lt;p&gt;The power of Clojure is that it allows me to solve hard problems instead of having to rely on somebody else to write libraries that do the hard stuff and then glue them together.&lt;/p&gt;&lt;p&gt;At this point Chris proceeded to ignore the request for over half a year, until he suddenly decided to start &lt;a href='https://twitter.com/bitemyapp/status/517829996975370240'&gt;messaging me about it on Twitter&lt;/a&gt; last night. All of a sudden he couldn't wait a second more and what's more apparently my code was broken! As he so eloquently put it &lt;a href='https://twitter.com/bitemyapp/status/517830192509624320'&gt;"@yogthos broken software in a unityped language...whodathunkit..."&lt;/a&gt;. He proceeded to berate me and insisted that the code does not work, that &lt;a href='https://twitter.com/bitemyapp/status/517833301801721856'&gt;I'm a liar&lt;/a&gt; for suggesting that it does, and he must make a blog post regarding this situation immediately.&lt;/p&gt;&lt;p&gt;I was surprised to hear this as I clearly recall the parser example working last I touched it. Since there was no reason to change it, I was fairly confident that it would be in working order. However, not having access to a computer at the time I could not check it myself.&lt;/p&gt;&lt;p&gt;Normally, if an individual contacts me respectfully I would be glad to help and work with them to figure out what the problem is. I make mistakes, we all do, and it's conceivable that there might've been a problem with my code. The approach Chris chosen was frankly insulting.&lt;/p&gt;&lt;p&gt;I explained to Chris that I was not at a computer and I can't look at the code, but evidently the blog post simply could not wait. You can read it in full &lt;a href='http://bitemyapp.com/posts/2014-10-02-parsing-and-rendering-templates-in-haskell.html'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The problem turned out to be that Chris is apparently incapable of reading code. The parser gets initialized with the &lt;code&gt;render-file&lt;/code&gt; function:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn render-file &amp;#91;filename args&amp;#93;
  &amp;#40;render &amp;#40;parse filename&amp;#41; args&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This function calls the &lt;code&gt;parse&lt;/code&gt; function on the &lt;code&gt;filename&lt;/code&gt; and then passes the parsed content to &lt;code&gt;render&lt;/code&gt;. Chris tried to call &lt;code&gt;render&lt;/code&gt; with:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;parser/render &amp;quot;Hello {{name}}!&amp;quot; {:name &amp;quot;Yogthos&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Shockingly enough he got an error doing that, at this point he evidently was incapable figuring out on his own what was causing the error and proceeded to throw a tantrum on Twitter.&lt;/p&gt;&lt;p&gt;Of course, if the goal was to actually figure out what the problem was then one would at least look at what parse is doing:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn parse &amp;#91;file&amp;#93;
  &amp;#40;with-open &amp;#91;rdr &amp;#40;clojure.java.io/reader file&amp;#41;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then it would immediately become obvious that we must pass in something that can be read by &lt;code&gt;clojure.java.io/reader&lt;/code&gt;, such as &lt;code&gt;java.io.StringBufferInputStream&lt;/code&gt;, and then pass the result of &lt;code&gt;parse&lt;/code&gt; to &lt;code&gt;render&lt;/code&gt;. Naturally, when called correctly the code does exactly what it's supposed to:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;render
  &amp;#40;parse
    &amp;#40;java.io.StringBufferInputStream. &amp;quot;Hello {{name}}&amp;quot;&amp;#41;&amp;#41;
    {:name &amp;quot;Yogthos&amp;quot;}&amp;#41;
=&amp;gt;&amp;quot;Hello filter tag value: name&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Since Chris managed to run the &lt;code&gt;render-file&lt;/code&gt; function as seen in one the snippets in his blog post, he doesn't seem to understand that I asked him to translate that code to Haskell. For whatever reason, he includes a screenshot of Selmer documentation, which is &lt;em&gt;not&lt;/em&gt; the behavior of the parser and was never intended to be. The spec that Chris was asked to translate to Haskell is the code in the gist.&lt;/p&gt;&lt;p&gt;In his post, Chris went ahead and answered the question he would like to have been asked as opposed to the one he was actually asked. I suppose making a straw man is a lot easier than answering the original question.&lt;/p&gt;&lt;p&gt;What I learned from this experience is that some Haskell users like to talk a lot about their favorite language, but when asked to solve a simple problem they will do anything but that. I don't find that to be terribly convincing myself.&lt;/p&gt;</description><pubDate>Fri, 03 Oct 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-09-27-Yet-Another-Clojure-Intro-Guide.html</guid><link>https://yogthos.net/posts/2014-09-27-Yet-Another-Clojure-Intro-Guide.html</link><title>Yet Another Clojure Intro Guide</title><description>&lt;p&gt;There are already lots of guides introducing Clojure syntax and many of its features, but these guides tend to focus on individual examples as opposed to the broad concepts behind the language.&lt;/p&gt;&lt;p&gt;In my experience, the difficulty in learning Clojure doesn't stem from the syntax, but from having to approach problems with a new mindset. The goal of this guide is to impart such a mindset on the reader. How badly I fail at this task remains to be seen. :P&lt;/p&gt;&lt;p&gt;Without further ado, &lt;a href='http://yogthos.github.io/ClojureDistilled.html'&gt;here's&lt;/a&gt; the guide itself, and I hope you'll find it useful if you're starting out with Clojure.&lt;/p&gt;</description><pubDate>Sat, 27 Sep 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-09-20-Using-ClojureScript-REPL-from-Light-Table.html</guid><link>https://yogthos.net/posts/2014-09-20-Using-ClojureScript-REPL-from-Light-Table.html</link><title>Using ClojureScript REPL from Light Table</title><description>&lt;p&gt;I recently discovered that &lt;a href='http://www.lighttable.com/'&gt;Light Table&lt;/a&gt; REPL works with ClojureScript without the need for any specific setup in your project.  All you need is the &lt;a href='https://github.com/emezeske/lein-cljsbuild'&gt;lein-cljsbuild&lt;/a&gt; plugin to run the incremental compiler and follow the steps below:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;start the ClojureScript compiler using &lt;code&gt;lein cljsbuild auto&lt;/code&gt;&lt;/li&gt;&lt;li&gt;start the server using &lt;code&gt;lein ring server&lt;/code&gt;&lt;/li&gt;&lt;li&gt;open the Light Table browser connection to the server&lt;/li&gt;&lt;li&gt;navigate to a ClojureScript namespace in your project and start evaluating expressions&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;I tried other ClojureScript REPL setups before and I always found the process extremely fiddly, with Light Table everything just worked out of the box. I definitely recommend giving it a shot if you haven't yet, especially if you're working with ClojureScript.&lt;/p&gt;</description><pubDate>Sat, 20 Sep 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-08-31-Introducing-reagent-forms.html</guid><link>https://yogthos.net/posts/2014-08-31-Introducing-reagent-forms.html</link><title>Introducing reagent-forms</title><description>&lt;p&gt;One thing I’ve always found to be particularly tedious is having to create data bindings for form elements. Reagent makes this much more palatable than most libraries I’ve used. All you need to do is create an atom and use it to track the state of the components.&lt;/p&gt;&lt;p&gt;However, creating the components and binding them to the state atom is still a manual affair. I decided to see if I could roll this into a library that would provide a simple abstraction for tracking the state of the fields in forms.&lt;/p&gt;&lt;p&gt;The usual way to bind inputs to atoms as illustrated in the &lt;a href='http://holmsand.github.io/reagent/'&gt;official Reagent docs&lt;/a&gt; can be seen below:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns example
  &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn atom-input &amp;#91;value&amp;#93;
  &amp;#91;:input {:type &amp;quot;text&amp;quot;
           :value @value
           :on-change #&amp;#40;reset! value &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;}&amp;#93;&amp;#41;

&amp;#40;defn shared-state &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;val &amp;#40;atom &amp;quot;foo&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;:p &amp;quot;The value is now: &amp;quot; @val&amp;#93;
       &amp;#91;:p &amp;quot;Change it here: &amp;quot; &amp;#91;atom-input val&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We create an atom with some state and then pass it to our input component. The component will display the current value and update the state when its &lt;code&gt;:on-change&lt;/code&gt; event is triggered.&lt;/p&gt;&lt;p&gt;Normally, we’d have to go through each field in the form and pass the state to it so that it can bind itself to the document we’re generating.&lt;/p&gt;&lt;p&gt;I wanted to be able to specify a template for a form and then pass the entire template to a function that would take care of binding all the fields to an atom representing the document.&lt;/p&gt;&lt;p&gt;This function would need to know what parts of the form need to be bound, how to bind each type of element, and how to uniquely identify it in the document.&lt;/p&gt;&lt;p&gt;My solution was to introduce the &lt;code&gt;:field&lt;/code&gt; attribute that would identify the component as a form field, and to use the &lt;code&gt;:id&lt;/code&gt; attribute as the unique key for the element.&lt;/p&gt;&lt;p&gt;The binding function would then walk the form and check for any component that contain the &lt;code&gt;:field&lt;/code&gt; key in its attribute map. The key would point to the type of component such as text, numeric, list, and so on.&lt;/p&gt;&lt;p&gt;Then it could pass the component to a specific binding function that would be responsible for linking the field with the document and return a bound component. Let’s take a look at how this all works with an example.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;We’ll first need to include the library in our project `[reagent-forms "0.1.3"] &lt;code&gt;, then we’ll require the &lt;/code&gt;reagent-forms.core/bind-fields` function in our namespace:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns myform.core
  &amp;#40;:require &amp;#91;reagent-forms.core :refer &amp;#91;bind-fields&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, we need to create a form template to represent our form:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn row &amp;#91;label input&amp;#93;
  &amp;#91;:div.row
    &amp;#91;:div.col-md-2 &amp;#91;:label label&amp;#93;&amp;#93;
    &amp;#91;:div.col-md-5 input&amp;#93;&amp;#93;&amp;#41;

&amp;#40;def form-template
  &amp;#91;:div
   &amp;#40;row &amp;quot;first name&amp;quot; &amp;#91;:input {:field :text :id :person.first-name}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;last name&amp;quot; &amp;#91;:input {:field :text :id :person.last-name}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;age&amp;quot; &amp;#91;:input {:field :numeric :id :person.age}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;email&amp;quot; &amp;#91;:input {:field :email :id :person.email}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;comments&amp;quot; &amp;#91;:textarea {:field :textarea :id :comments}&amp;#93;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that we call helper functions, such as &lt;code&gt;row&lt;/code&gt;, eagerly. The &lt;code&gt;bind-fields&lt;/code&gt;  function will walk the template to construct the actual components that will be used by Reagent.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;.&lt;/code&gt; in the &lt;code&gt;:id&lt;/code&gt; key indicates nested structure. When we have a key like &lt;code&gt;:person.first-name&lt;/code&gt;, then its value will be stored under &lt;code&gt;{:person {:first-name &amp;lt;field-value&amp;gt;}}&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Our form component will then create an atom to represent the document and bind it to the template to produce the actual form:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn form &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;doc &amp;#40;atom {}&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;
       &amp;#91;bind-fields form-template doc&amp;#93;
       &amp;#91;:label &amp;#40;str @doc&amp;#41;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That’s all there is to it. Whenever the state of any of the components changes the &lt;code&gt;doc&lt;/code&gt; atom will be updated and vice versa.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;bind-fields&lt;/code&gt; function also accepts optional events. Events are triggered whenever the document is updated, and will be executed in order they are listed. Each event sees the document modified by its predecessor. The event must take 3 parameters, which are the id, the value, and the document.&lt;/p&gt;&lt;p&gt;The id and the value represent the value that was changed to trigger the event, and the document is the atom that contains the state of the form. Note that the id is in form of a vector representing the path in the document. The event can either return an updated document or &lt;code&gt;nil&lt;/code&gt;, when &lt;code&gt;nil&lt;/code&gt; is returned then the state of the document is unmodified. The following is an example of an event to calculate the value of the &lt;code&gt;:bmi&lt;/code&gt; key when the &lt;code&gt;:weight&lt;/code&gt; and &lt;code&gt;:height&lt;/code&gt; keys are populated:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn row &amp;#91;label input&amp;#93;
  &amp;#91;:div.row
    &amp;#91;:div.col-md-2 &amp;#91;:label label&amp;#93;&amp;#93;
    &amp;#91;:div.col-md-5 input&amp;#93;&amp;#93;&amp;#41;

&amp;#40;def form-template
 &amp;#91;:div
   &amp;#91;:h3 &amp;quot;BMI Calculator&amp;quot;&amp;#93;
   &amp;#40;row &amp;quot;Height&amp;quot; &amp;#91;:input {:field :numeric :id :height}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;Weight&amp;quot; &amp;#91;:input {:field :numeric :id :weight}&amp;#93;&amp;#41;
   &amp;#40;row &amp;quot;BMI&amp;quot; &amp;#91;:input {:field :numeric :id :bmi :disabled true}&amp;#93;&amp;#41;&amp;#93;&amp;#41;

&amp;#91;w/bind-fields
  form-template
  doc
  &amp;#40;fn &amp;#91;&amp;#91;id&amp;#93; value {:keys &amp;#91;weight height&amp;#93; :as doc}&amp;#93;
    &amp;#40;when &amp;#40;and &amp;#40;some #{id} &amp;#91;:height :weight&amp;#93;&amp;#41; weight height&amp;#41;
      &amp;#40;assoc-in doc &amp;#91;:bmi&amp;#93; &amp;#40;/ weight &amp;#40;&amp;#42; height height&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The library provides support for a number of common fields such as inputs, checkboxes, radio buttons, lists, and multi-selects. However, it also makes it easy to add your own custom fields by implementing the &lt;code&gt;reagent-forms.core/init-field&lt;/code&gt; multimethod.&lt;/p&gt;&lt;p&gt;The method must take two parameters, where the first parameter is the field component and the second is the options map. The options contain two keys called  &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;save!&lt;/code&gt;. The &lt;code&gt;get&lt;/code&gt; key points to a function that accepts an id and returns the document value associated with it. The &lt;code&gt;save!&lt;/code&gt; function accepts an id and a value that will be associated with it. Let’s take a look at the &lt;code&gt;:radio&lt;/code&gt; field implementation as an example:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmethod init-field :radio
  &amp;#91;&amp;#91;type {:keys &amp;#91;field id value&amp;#93; :as attrs} &amp;amp; body&amp;#93;
   {:keys &amp;#91;get save!&amp;#93;}&amp;#93;
  &amp;#40;let &amp;#91;state &amp;#40;atom &amp;#40;= value &amp;#40;get id&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#40;into
        &amp;#91;type
         &amp;#40;merge {:type :radio
                 :checked @state
                 :class &amp;quot;form-control&amp;quot;
                 :on-change
                 #&amp;#40;do
                    &amp;#40;save! id value&amp;#41;
                    &amp;#40;reset! state &amp;#40;= value &amp;#40;get id&amp;#41;&amp;#41;&amp;#41;&amp;#41;}
                attrs&amp;#41;&amp;#93;
         body&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As you can see, the method simply returns a new component that’s bound to the supplied id in the document. For more details please see the &lt;a href='https://github.com/yogthos/reagent-forms'&gt;documentation&lt;/a&gt; on the project page.&lt;/p&gt;&lt;p&gt;The library is still rather new and as such has some rough edges, such as poor error reporting. However, I already find it to be quite useful in my own projects.&lt;/p&gt;</description><pubDate>Sun, 31 Aug 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-08-17-File-Snooping.html</guid><link>https://yogthos.net/posts/2014-08-17-File-Snooping.html</link><title>File Snooping</title><description>&lt;p&gt;I recently needed to watch files for changes and had a chance to play around with using the &lt;code&gt;WatchService&lt;/code&gt; functionality in JDK 7. As is generally the case with Java, the API requires you to jump through a number of hoops to do anything, but turns out that it’s possible to wrap it up into something reasonable in the end.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;WatchService&lt;/code&gt; can be used to watch directories and provides different types of events, such as create, modify, delete, and overflow. The first three are self-explanatory and the last is a special event that’s triggered when an event might have been discarded or lost.&lt;/p&gt;&lt;p&gt;What we’d like to do is create a function called &lt;code&gt;watch&lt;/code&gt; that accepts an input path along with event handlers for each of the above events.&lt;/p&gt;&lt;p&gt;To create a watcher we first need to get an instance of a &lt;code&gt;Path&lt;/code&gt;. To do that we have to call &lt;code&gt;&amp;#40;-&amp;gt; path &amp;#40;file&amp;#41; &amp;#40;.toURI&amp;#41; &amp;#40;Paths/get&amp;#41;&amp;#41;&lt;/code&gt;. Next, we can get an instance of the &lt;code&gt;WatchService&lt;/code&gt; by calling &lt;code&gt;&amp;#40;.newWatchService &amp;#40;FileSystems/getDefault&amp;#41;&amp;#41;&lt;/code&gt;&lt;/p&gt;&lt;p&gt;Now that we have a &lt;code&gt;Path&lt;/code&gt; and a &lt;code&gt;WatchService&lt;/code&gt;, we can register the service with the path to listen for the events we specify.&lt;/p&gt;&lt;p&gt;To handle this, I ended up creating a map with the keys representing the events and the values being the event handling functions.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:create event-handler
 :modify event-handler}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When the event is triggered we will receive an instance of the  &lt;code&gt;WatchEvent&lt;/code&gt;. So, the handler functions should accept it as the parameter.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn event-handler &amp;#91;event&amp;#93;
  &amp;#40;println &amp;#40;.kind event&amp;#41; &amp;#40;.context event&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, I created a couple of helpers to map the keywords to the appropriate events:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn register-events! &amp;#91;dir watch-service opts&amp;#93;
  &amp;#40;.register dir watch-service
    &amp;#40;-&amp;gt; opts
       &amp;#40;select-keys &amp;#91;StandardWatchEventKinds/ENTRY&amp;#95;CREATE
                     StandardWatchEventKinds/ENTRY&amp;#95;MODIFY
                     StandardWatchEventKinds/ENTRY&amp;#95;DELETE
                     StandardWatchEventKinds/OVERFLOW&amp;#93;&amp;#41;
       &amp;#40;keys&amp;#41;
       &amp;#40;into-array&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn rename-event-keys &amp;#91;opts&amp;#93;
  &amp;#40;rename-keys opts
    {:create StandardWatchEventKinds/ENTRY&amp;#95;CREATE
     :modify StandardWatchEventKinds/ENTRY&amp;#95;MODIFY
     :delete StandardWatchEventKinds/ENTRY&amp;#95;DELETE
     :overflow StandardWatchEventKinds/OVERFLOW}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The transformed map is now ready for use. The &lt;code&gt;WatchService&lt;/code&gt; implements closeable, so we can use the &lt;code&gt;with-open&lt;/code&gt; macro to manage it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn watch &amp;#91;path opts&amp;#93;
  &amp;#40;let &amp;#91;dir &amp;#40;-&amp;gt; path &amp;#40;file&amp;#41; &amp;#40;.toURI&amp;#41; &amp;#40;Paths/get&amp;#41;&amp;#41;
        opts &amp;#40;rename-event-keys opts&amp;#41;&amp;#93;
    &amp;#40;with-open &amp;#91;watch-service
                &amp;#40;.newWatchService &amp;#40;FileSystems/getDefault&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;register-events! dir watch-service opts&amp;#41;
      &amp;#40;watch-loop watch-service opts&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;watch&lt;/code&gt; function will register the events we passed in, open the watch service and then call the &lt;code&gt;watch-loop&lt;/code&gt; function to do the actual watching.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn watch-loop &amp;#91;watch-service opts&amp;#93;
  &amp;#40;loop &amp;#91;&amp;#93;
    &amp;#40;let &amp;#91;k &amp;#40;.take watch-service&amp;#41;&amp;#93;      
      &amp;#40;doseq &amp;#91;event &amp;#40;.pollEvents k&amp;#41;&amp;#93;
        &amp;#40;if-let &amp;#91;handler &amp;#40;get opts &amp;#40;.kind event&amp;#41;&amp;#41;&amp;#93;
          &amp;#40;handler event&amp;#41;&amp;#41;&amp;#41;
      &amp;#40;when &amp;#40;.reset k&amp;#41; &amp;#40;recur&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;watch-loop&lt;/code&gt; starts each iteration by calling &lt;code&gt;take&lt;/code&gt; on the watch service. This method blocks until it receives an event, the service is closed or it’s interrupted.&lt;/p&gt;&lt;p&gt;Once we receive an event we can look it up in our options map and call the handler for the event. Finally, we need to call &lt;code&gt;reset&lt;/code&gt; on the key before we start the next iteration.&lt;/p&gt;&lt;p&gt;Since the &lt;code&gt;take&lt;/code&gt; function blocks, we probably want to run it in a thread:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn start-watcher! &amp;#91;path opts&amp;#93;
  &amp;#40;doto &amp;#40;Thread. #&amp;#40;watch path opts&amp;#41;&amp;#41;
    &amp;#40;.setDaemon true&amp;#41;
    &amp;#40;.start&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above will start a background watcher thread and return it. The thread is daemonized, so that it doesn’t prevent the application from exiting. Example usage for the above can be to track when files are created or modified in the directory:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;start-watcher! “&amp;#126;/downlads”
  {:create #&amp;#40;println “file created” &amp;#40;-&amp;gt; % &amp;#40;.context&amp;#41; &amp;#40;.toString&amp;#41;&amp;#41;&amp;#41;
   :modify #&amp;#40;println “file modified” &amp;#40;-&amp;gt; % &amp;#40;.context&amp;#41; &amp;#40;.toString&amp;#41;&amp;#41;&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That’s all there is to it and the full source for the example can be seen &lt;a href='https://gist.github.com/yogthos/911e6aba9802ceacd83c'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="update"&gt;Update&lt;/h3&gt;&lt;p&gt;As one of the comments points out, JDK will poll on OS X and the default poll interval is quite large. In order to get around this we can force high sensitivity when we register the &lt;code&gt;WatchService&lt;/code&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn register-events! &amp;#91;dir watch-service&amp;#93;
  &amp;#40;.register dir
    watch-service
    &amp;#40;into-array
      &amp;#91;StandardWatchEventKinds/ENTRY&amp;#95;CREATE
       StandardWatchEventKinds/ENTRY&amp;#95;MODIFY
       StandardWatchEventKinds/ENTRY&amp;#95;DELETE
       StandardWatchEventKinds/OVERFLOW&amp;#93;&amp;#41;
    &amp;#40;into-array
      &amp;#91;&amp;#40;com.sun.nio.file.SensitivityWatchEventModifier/HIGH&amp;#41;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt; </description><pubDate>Sun, 17 Aug 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-08-14-Routing-With-Secretary.html</guid><link>https://yogthos.net/posts/2014-08-14-Routing-With-Secretary.html</link><title>Routing With Secretary</title><description>&lt;p&gt;In the last post, we looked at using Reagent for building single page apps. The &lt;a href='https://github.com/yogthos/reagent-example'&gt;example&lt;/a&gt; app contained a single page with a form in it, which isn't terribly exciting as far as single page apps go.&lt;/p&gt;&lt;p&gt;In this post we’ll see see how to create an app with multiple pages and how we can route between them using the &lt;a href='https://github.com/gf3/secretary'&gt;secretary&lt;/a&gt; library.&lt;/p&gt;&lt;p&gt;The app will be a guestbook with a page that shows a list of users and another page that allows new users to sign in. We’ll use the project from the last post as the base for this tutorial.&lt;/p&gt;&lt;p&gt;&lt;b&gt;&lt;i&gt;update&lt;/i&gt;&lt;/b&gt; the tutorial has been updated to the latest version of Luminus, you'll need to create a new project to follow along using &lt;code&gt;lein new luminus guestbook +cljs&lt;/code&gt;&lt;/p&gt;&lt;p&gt;First thing that we have to do is to add the &lt;code&gt;&amp;#91;secretary &amp;quot;1.2.3&amp;quot;&amp;#93;&lt;/code&gt; dependency to our &lt;code&gt;project.clj&lt;/code&gt;. Next, let’s refactor our namespaces in &lt;code&gt;src/cljs&lt;/code&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;src
  └ cljs
    └ guestbook
      └ core.cljs
      └ pages
        └ guest.cljs
        └ guest&amp;#95;list.cljs
&lt;/code&gt;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;The &lt;code&gt;core&lt;/code&gt; namespace will act as the entry point for the client.&lt;/li&gt;&lt;li&gt;The &lt;code&gt;session&lt;/code&gt; will house the global state of the application.&lt;/li&gt;&lt;li&gt;The &lt;code&gt;guest&lt;/code&gt; namespace will house the sign-in form.&lt;/li&gt;&lt;li&gt;The &lt;code&gt;guest-list&lt;/code&gt; namespace will display the guests.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Since we refactored the namespaces we’ll also need to update our &lt;code&gt;app.html&lt;/code&gt; template to reflect that.&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;goog.require&amp;#40;&amp;quot;guestbook.core&amp;quot;&amp;#41;;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="session&amp;#95;management"&gt;Session Management&lt;/h3&gt;&lt;p&gt;In our example, the session will track the currently selected page and the saved documents.&lt;/p&gt;&lt;p&gt;We’ll use the &lt;a href='https://github.com/reagent-project/reagent-utils/blob/master/src/reagent/session.cljs'&gt;reagent-utils&lt;/a&gt; session. The session is simply a Ragent atom with some helper functions around it.&lt;/p&gt;&lt;h3 id="listing&amp;#95;guests"&gt;Listing Guests&lt;/h3&gt;&lt;p&gt;Let’s open up the &lt;code&gt;guest-list&lt;/code&gt; namespace and add the following code there.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.pages.guest-list
  &amp;#40;:require &amp;#91;reagent.session :as session&amp;#93;
            &amp;#91;clojure.string :as s&amp;#93;
            &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
            &amp;#91;secretary.core :refer &amp;#91;dispatch!&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn guest-list-page &amp;#91;&amp;#93;
  &amp;#91;:div
   &amp;#91;:div.page-header &amp;#91;:h2 &amp;quot;Guests&amp;quot;&amp;#93;&amp;#93;
   &amp;#40;for &amp;#91;{:keys &amp;#91;first-name last-name&amp;#93;}
         &amp;#40;session/get :guests&amp;#41;&amp;#93;
     &amp;#91;:div.row
      &amp;#91;:p first-name &amp;quot; &amp;quot; last-name&amp;#93;&amp;#93;&amp;#41;
   &amp;#91;:button {:type &amp;quot;submit&amp;quot;
             :class &amp;quot;btn btn-default&amp;quot;
             :on-click #&amp;#40;dispatch! &amp;quot;/sign-in&amp;quot;&amp;#41;}
    &amp;quot;sign in&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The namespace will contain a page that lists the guests that are currently in the session. The &lt;code&gt;“sign in”&lt;/code&gt; button on the page uses the &lt;code&gt;dispatch!&lt;/code&gt; function in order to route to the &lt;code&gt;“/sign-in”&lt;/code&gt; page.&lt;/p&gt;&lt;h3 id="adding&amp;#95;routes"&gt;Adding Routes&lt;/h3&gt;&lt;p&gt;The &lt;code&gt;core&lt;/code&gt; namespace will specify the list of routes and provide an &lt;code&gt;init!&lt;/code&gt; function to set the current page and render it when the application loads.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.core
  &amp;#40;:require &amp;#91;reagent.core :as r&amp;#93;
            &amp;#91;reagent.session :as session&amp;#93;
            &amp;#91;secretary.core :as secretary :include-macros true&amp;#93;
            &amp;#91;goog.events :as events&amp;#93;
            &amp;#91;goog.history.EventType :as HistoryEventType&amp;#93;
            &amp;#91;guestbook.ajax :refer &amp;#91;load-interceptors!&amp;#93;&amp;#93;
            &amp;#91;guestbook.pages.guest-list
            :refer &amp;#91;guest-list-page&amp;#93;&amp;#93;
           &amp;#91;guestbook.pages.guest :refer &amp;#91;guest-page&amp;#93;&amp;#93;&amp;#41;
  &amp;#40;:import goog.History&amp;#41;&amp;#41;

&amp;#40;defn page &amp;#91;&amp;#93;
  &amp;#91;&amp;#40;session/get :current-page&amp;#41;&amp;#93;&amp;#41;

;; -------------------------
;; Routes
&amp;#40;secretary/set-config! :prefix &amp;quot;#&amp;quot;&amp;#41;

&amp;#40;secretary/defroute &amp;quot;/&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;session/put! :current-page guest-list-page&amp;#41;&amp;#41;

&amp;#40;secretary/defroute &amp;quot;/sign-in&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;session/put! :current-page guest-page&amp;#41;&amp;#41;

;; -------------------------
;; History
;; must be called after routes have been defined
&amp;#40;defn hook-browser-navigation! &amp;#91;&amp;#93;
  &amp;#40;doto &amp;#40;History.&amp;#41;
        &amp;#40;events/listen
          HistoryEventType/NAVIGATE
          &amp;#40;fn &amp;#91;event&amp;#93;
              &amp;#40;secretary/dispatch! &amp;#40;.-token event&amp;#41;&amp;#41;&amp;#41;&amp;#41;
        &amp;#40;.setEnabled true&amp;#41;&amp;#41;&amp;#41;

;; -------------------------
;; Initialize app
&amp;#40;defn mount-components &amp;#91;&amp;#93;
  &amp;#40;r/render &amp;#91;#'page&amp;#93; &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;load-interceptors!&amp;#41;
  &amp;#40;hook-browser-navigation!&amp;#41;
  &amp;#40;mount-components&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As we can see above, &lt;code&gt;secretary&lt;/code&gt; uses Compojure inspired syntax that should look very familiar to anybody who's dabbled in Clojure web development.&lt;/p&gt;&lt;p&gt;In our case the routes will simply set the appropriate page in the session when called. The &lt;code&gt;render&lt;/code&gt; function will then be triggered by the atom update and render the page for us.&lt;/p&gt;&lt;h3 id="signing&amp;#95;in"&gt;Signing In&lt;/h3&gt;&lt;p&gt;Finally, we’ll add the sign-in form in the &lt;code&gt;guest&lt;/code&gt; namespace. The page will keep its local state in an atom and update the session using the callback handler in the &lt;code&gt;save-doc&lt;/code&gt; function.&lt;/p&gt;&lt;p&gt;Note that we don’t have to do anything else to update the list of guests once the callback completes. Since the session atom has been updated, it will trigger the guest list to repaint with the new elements.&lt;/p&gt;&lt;p&gt;I found that this behavior largely obviates the need to use &lt;code&gt;core.async&lt;/code&gt; since the Reagent atom can act as a sync point between the view and the model. It also makes it trivial to implements the &lt;a href='http://facebook.github.io/react/docs/flux-overview.html'&gt;React Flux&lt;/a&gt; pattern.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Views---&amp;gt;&amp;#40;actions&amp;#41; --&amp;gt; Dispatcher--&amp;gt;&amp;#40;callback&amp;#41;--&amp;gt; Stores---+
Ʌ                                                          |
|                                                          V
+--&amp;#40;event handlers update&amp;#41;--&amp;#40;Stores emit &amp;quot;change&amp;quot; events&amp;#41;--+
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Our view components dispatch updates to the atoms, which represent the stores. The atoms in turn notify any components that dereference them when their state changes.&lt;/p&gt;&lt;p&gt;Using &lt;code&gt;get/set!&lt;/code&gt; functions to access the atoms, as we’re doing in this example, allows us to easily listen for changes and hook in event handlers.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.pages.guest
  &amp;#40;:refer-clojure :exclude &amp;#91;get&amp;#93;&amp;#41;
  &amp;#40;:require &amp;#91;reagent.session :as session&amp;#93;
            &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
            &amp;#91;secretary.core :refer &amp;#91;dispatch!&amp;#93;&amp;#93;
            &amp;#91;ajax.core :refer &amp;#91;POST&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn put! &amp;#91;doc id value&amp;#93;
  &amp;#40;swap! doc assoc :saved? false id value&amp;#41;&amp;#41;

&amp;#40;defn get &amp;#91;doc id&amp;#93;
  &amp;#40;id @doc&amp;#41;&amp;#41;

&amp;#40;defn row &amp;#91;label &amp;amp; body&amp;#93;
  &amp;#91;:div.row
   &amp;#91;:div.col-md-2 &amp;#91;:span label&amp;#93;&amp;#93;
   &amp;#91;:div.col-md-3 body&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn text-input &amp;#91;doc id label&amp;#93;
  &amp;#91;row label
   &amp;#91;:input {:type &amp;quot;text&amp;quot;
            :class &amp;quot;form-control&amp;quot;
            :value &amp;#40;get doc id&amp;#41;
            :onChange #&amp;#40;put! doc id &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;}&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn save-doc &amp;#91;doc&amp;#93;
  &amp;#40;POST &amp;quot;/save&amp;quot;
        {:params &amp;#40;dissoc @doc :saved?&amp;#41;
         :handler
         &amp;#40;fn &amp;#91;&amp;#95;&amp;#93;
           &amp;#40;put! doc :saved? true&amp;#41;
           &amp;#40;session/update-in! &amp;#91;:guests&amp;#93; conj @doc&amp;#41;
           &amp;#40;dispatch! &amp;quot;/&amp;quot;&amp;#41;&amp;#41;}&amp;#41;&amp;#41;

&amp;#40;defn guest-page &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;doc &amp;#40;atom {}&amp;#41;&amp;#93;
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div
       &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Sign In&amp;quot;&amp;#93;&amp;#93;

       &amp;#91;text-input doc :first-name &amp;quot;First name&amp;quot;&amp;#93;
       &amp;#91;text-input doc :last-name &amp;quot;Last name&amp;quot;&amp;#93;

       &amp;#40;if &amp;#40;get doc :saved?&amp;#41;
         &amp;#91;:p &amp;quot;Saved&amp;quot;&amp;#93;
         &amp;#91;:button {:type &amp;quot;submit&amp;quot;
                   :class &amp;quot;btn btn-default&amp;quot;
                   :on-click #&amp;#40;save-doc doc&amp;#41;}
          &amp;quot;Submit&amp;quot;&amp;#93;&amp;#41;
       &amp;#91;:button {:type &amp;quot;submit&amp;quot;
                 :class &amp;quot;btn btn-default&amp;quot;
                 :on-click #&amp;#40;dispatch! &amp;quot;/&amp;quot;&amp;#41;} &amp;quot;back&amp;quot;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The form code on this page is based on the &lt;a href='http://yogthos.net/#/blog/54'&gt;previous tutorial&lt;/a&gt; and should hopefully be self explanatory at this point.&lt;/p&gt;&lt;h3 id="hooking&amp;#95;in&amp;#95;browser&amp;#95;navigation"&gt;Hooking in Browser Navigation&lt;/h3&gt;&lt;p&gt;As a final touch, we can add support for managing history using &lt;code&gt;goog.events&lt;/code&gt; to enable more intelligent navigation using the browser.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.core
 &amp;#40;:require &amp;#91;reagent.session :as session&amp;#93;
           &amp;#91;guestbook.pages.guest-list
            :refer &amp;#91;guest-list-page&amp;#93;&amp;#93;
           &amp;#91;guestbook.pages.guest :refer &amp;#91;guest-page&amp;#93;&amp;#93;
           &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
           &amp;#91;secretary.core :as secretary
             :include-macros true :refer &amp;#91;defroute&amp;#93;&amp;#93;
           &amp;#91;goog.events :as events&amp;#93;
           &amp;#91;goog.history.EventType :as EventType&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn hook-browser-navigation! &amp;#91;&amp;#93;
  &amp;#40;doto &amp;#40;History.&amp;#41;
    &amp;#40;events/listen
      EventType/NAVIGATE
      &amp;#40;fn &amp;#91;event&amp;#93;
        &amp;#40;secretary/dispatch! &amp;#40;.-token event&amp;#41;&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;.setEnabled true&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The function is then run by the &lt;code&gt;init!&lt;/code&gt; function when the app loads:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn init! &amp;#91;&amp;#93;
  &amp;#40;load-interceptors!&amp;#41;
  &amp;#40;hook-browser-navigation!&amp;#41;
  &amp;#40;mount-components&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As usual, the source for the project can be found &lt;a href='https://github.com/yogthos/reagent-secretary-example'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h3 id="final&amp;#95;thoughts"&gt;Final Thoughts&lt;/h3&gt;&lt;p&gt;The example in this post is intentionally kept trivial, but hopefully it illustrates a simple way to hook up multiple pages and navigate between them using Reagent and secretary.&lt;/p&gt;&lt;p&gt;I recently rewrote this blog engine to use Reagent and I found that it made the code much cleaner and easier to maintain. I think one of the main benefits of the single page approach is that it enforces a clear separation between the server and the client portions of the application.&lt;/p&gt;&lt;p&gt;If you’d like to see a complete application built using the approach discussed here, don’t hesitate to take a look at the &lt;a href='https://github.com/yogthos/yuggoth'&gt;code&lt;/a&gt; behind this blog.&lt;/p&gt;</description><pubDate>Thu, 14 Aug 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-07-15-Building-Single-Page-Apps-with-Reagent.html</guid><link>https://yogthos.net/posts/2014-07-15-Building-Single-Page-Apps-with-Reagent.html</link><title>Building Single Page Apps with Reagent</title><description>&lt;h2 id="background"&gt;Background&lt;/h2&gt;&lt;p&gt;I recently started working on a new project that has a significant UI component. I decided that this was a good opportunity to take a look at Angular and React for building the client as a single page application.&lt;/p&gt;&lt;p&gt;After a bit of evaluation, I decided that React was a better fit for the project. Specifically, I found the idea of the virtual DOM very appealing and its component based approach to be a good way to manage the application state.&lt;/p&gt;&lt;p&gt;Once I got a bit deeper into using React I found it lacking in many areas. For example, it doesn't provide an adequate solution for complex data binding and while there are a few libraries such as &lt;a href='https://github.com/prometheusresearch/react-forms'&gt;react-forms&lt;/a&gt;, I didn't find them to be a good fit for my needs.&lt;/p&gt;&lt;p&gt;Having heard lots of great things about Om, I decided that this might be a good time to revisit ClojureScript. While I've done some projects in ClojureScript &lt;a href='http://yogthos.net/blog/43-Introducing+cljs-ajax'&gt;previously&lt;/a&gt;, I always ended up going back to JavaScript in the end.&lt;/p&gt;&lt;p&gt;For me, the benefits were not enough to outweigh the maturity of JavaScript and the tooling available for it. One of the things I found to be particularly painful was debugging generated JavaScript. This problem has now been addressed by the addition of source maps.&lt;/p&gt;&lt;h2 id="trying&amp;#95;om"&gt;Trying Om&lt;/h2&gt;&lt;p&gt;As I went through Om tutorials, I found that it exposes a lot of the incidental details to the user. Having to pass &lt;code&gt;nil&lt;/code&gt; arguments, reify protocols, and manually convert to Js using &lt;code&gt;#js&lt;/code&gt; hints are a but a few warts that I ran into. Although, it's worth noting that the &lt;a href='https://github.com/Prismatic/om-tools'&gt;om-tools&lt;/a&gt; library from Prismatic address some of these issues.&lt;/p&gt;&lt;p&gt;Overall, I feel that Om requires a significant time investment in order to become productive. I found myself wanting a higher level of abstraction for creating UI components and tracking state between them. This led me to trying &lt;a href='http://holmsand.github.io/reagent/'&gt;Reagent&lt;/a&gt;. This library provides a very intuitive model for assembling UI components and tracking their state, and you have to learn very few concepts to start using it efficiently.&lt;/p&gt;&lt;h2 id="differences&amp;#95;between&amp;#95;om&amp;#95;and&amp;#95;reagent"&gt;Differences between Om and Reagent&lt;/h2&gt;&lt;p&gt;Om and Reagent make different design decisions that result in different tradeoffs, each with its own strength and weaknesses. Which of these libraries is better primarily depends on the problem you're solving.&lt;/p&gt;&lt;p&gt;The biggest difference between Om and Reagent is that Om is highly prescriptive in regards to state management in order to ensure that components are reusable. It's an anti-pattern for Om components to manipulate the global state directly or by calling functions to do so. Instead, components are expected to communicate using &lt;a href='https://github.com/clojure/core.async'&gt;core.async&lt;/a&gt; channels. This is done to ensure high modularity of the components. Reagent leaves this part of the design up to you and allows using a combination of global and local states as you see fit.&lt;/p&gt;&lt;p&gt;Om takes a data centric view of the world by being agnostic about how the data is rendered. It treats the React DOM and Om components as implementation details. This decision often results in code that's verbose and exposes incidental details to the user. These can obviously be abstracted, but Om does not aim to provide such an abstraction and you'd have to write your own helpers as seen with Prismatic and om-tools.&lt;/p&gt;&lt;p&gt;On the other hand, Reagent provides a standard way to define UI components using &lt;a href='https://github.com/weavejester/hiccup'&gt;Hiccup&lt;/a&gt; style syntax for DOM representation. Each UI component is a data structure that represents a particular DOM element. By taking a DOM centric view of the UI, Reagent makes writing composable UI components simple and intuitive. The resulting code is extremely succinct and highly readable. It's worth noting that nothing in the design prevents you from swapping in custom components. The only constraint is that the component must return something that is renderable.&lt;/p&gt;&lt;h2 id="using&amp;#95;reagent"&gt;Using Reagent&lt;/h2&gt;&lt;p&gt;The rest of this post will walk through building a trivial Reagent app where I hope to illustrate what makes Reagent such an excellent library. Different variations of CRUD apps are probably the most common types of web applications nowadays. Let's take a look at creating a simple form with some fields that we'll want to collect and send to the server.&lt;/p&gt;&lt;p&gt;I won't go into details of setting up a ClojureScript project in this post, but you can use the &lt;a href='https://github.com/yogthos/reagent-example'&gt;reagent-example&lt;/a&gt; project to follow along. The project requires &lt;a href='http://leiningen.org/'&gt;Leiningen&lt;/a&gt; build tool and you will need to have it installed before continuing.&lt;/p&gt;&lt;p&gt;Once you check out the project, you will need to start the ClojureScript compiler by running &lt;code&gt;lein cljsbuild auto&lt;/code&gt; and run the server using &lt;code&gt;lein ring server&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;The app consists of UI components that are tied to a model. Whenever the user changes a value of a component, the change is reflected in our model. When the user clicks the submit button then the current state is sent to the server.&lt;/p&gt;&lt;p&gt;The ClojureScript code is found in the &lt;code&gt;main.core&lt;/code&gt; under the &lt;code&gt;src-cljs&lt;/code&gt; source directory. Let's delete its contents and start writing our application from scratch. As the first step, we'll need to reference &lt;code&gt;reagent&lt;/code&gt; in our namespace definition.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns main.core
 &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, let's create a Reagent component to represent the container for our page.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now render this component on the page by calling the &lt;code&gt;render-component&lt;/code&gt; function.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;reagent/render-component &amp;#91;home&amp;#93;
  &amp;#40;.getElementById js/document &amp;quot;app&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As I mentioned above, the components can be nested inside one another. To add a text field to our form we'll write a function to represent it and add it to our &lt;code&gt;home&lt;/code&gt; component.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn text-input &amp;#91;label&amp;#93;
  &amp;#91;:div.row
    &amp;#91;:div.col-md-2
      &amp;#91;:span label&amp;#93;&amp;#93;
    &amp;#91;:div.col-md-3
      &amp;#91;:input {:type &amp;quot;text&amp;quot; :class &amp;quot;form-control&amp;quot;}&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;
    &amp;#91;text-input &amp;quot;First name&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Notice that even though &lt;code&gt;text-input&lt;/code&gt; is a function we're not calling it, but instead we're putting it in a vector. The reason for this is that we're specifying the component hierarchy. The components will be run by Reagent when they need to be rendered.&lt;/p&gt;&lt;p&gt;We can also easily extract the row into a separate component. Once again, we won't need to call the &lt;code&gt;row&lt;/code&gt; function directly, but can treat the component as data and leave it up to Reagent when it should be evaluated.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn row &amp;#91;label &amp;amp; body&amp;#93;
  &amp;#91;:div.row
   &amp;#91;:div.col-md-2 &amp;#91;:span label&amp;#93;&amp;#93;
   &amp;#91;:div.col-md-3 body&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn text-input &amp;#91;label&amp;#93;
  &amp;#91;row label &amp;#91;:input {:type &amp;quot;text&amp;quot; :class &amp;quot;form-control&amp;quot;}&amp;#93;&amp;#93;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We now have an input field that we can display. Next, we need to create a model and bind our component to it. Reagent allows us to do this using its &lt;code&gt;atom&lt;/code&gt; abstraction over the React state. The Reagent atoms behave just like standard Clojure atoms. The main difference is that a change in the value of the atom causes any components that dereference it to be repainted.&lt;/p&gt;&lt;p&gt;Any time we wish to create a local or global state we create an atom to hold it. This allows for a simple model where we can create variables for the state and observe them as they change over time. Let's add an atom to hold the state for our application and a couple of handler functions for accessing and updating it.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def state &amp;#40;atom {:doc {} :saved? false}&amp;#41;&amp;#41;

&amp;#40;defn set-value! &amp;#91;id value&amp;#93;
  &amp;#40;swap! state assoc :saved? false&amp;#41;
  &amp;#40;swap! state assoc-in &amp;#91;:doc id&amp;#93; value&amp;#41;&amp;#41;

&amp;#40;defn get-value &amp;#91;id&amp;#93;
  &amp;#40;get-in @state &amp;#91;:doc id&amp;#93;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now update our &lt;code&gt;text-input&lt;/code&gt; component to set the state when the &lt;code&gt;onChange&lt;/code&gt; event is called and display the current state as its &lt;code&gt;value&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn text-input &amp;#91;id label&amp;#93;
  &amp;#91;row label
   &amp;#91;:input
     {:type &amp;quot;text&amp;quot;
       :class &amp;quot;form-control&amp;quot;
       :value &amp;#40;get-value id&amp;#41;
       :on-change #&amp;#40;set-value! id &amp;#40;-&amp;gt; % .-target .-value&amp;#41;&amp;#41;}&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;
    &amp;#91;text-input :first-name &amp;quot;First name&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's add a save button to our form so that we can persist the state. For now, we'll simply log the current state to the console.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;
    &amp;#91;text-input :first-name &amp;quot;First name&amp;quot;&amp;#93;    
    &amp;#91;:button {:type &amp;quot;submit&amp;quot;
              :class &amp;quot;btn btn-default&amp;quot;
              :on-click #&amp;#40;.log js/console &amp;#40;clj-&amp;gt;js @state&amp;#41;&amp;#41;}
     &amp;quot;Submit&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If we open the console, then we should see the current value of the &lt;code&gt;:first-name&lt;/code&gt; key populated in our document whenever we click submit. We can now easily add a second component for the last name and see that it gets bound to our model in exactly the same way.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;

    &amp;#91;text-input :first-name &amp;quot;First name&amp;quot;&amp;#93;
    &amp;#91;text-input :last-name &amp;quot;First name&amp;quot;&amp;#93;

    &amp;#91;:button {:type &amp;quot;submit&amp;quot;
              :class &amp;quot;btn btn-default&amp;quot;
              :onClick #&amp;#40;.log js/console &amp;#40;clj-&amp;gt;js @state&amp;#41;&amp;#41;}
     &amp;quot;Submit&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So far we've been using a global variable to hold all our state, while it's convenient for small applications this approach doesn't scale well. Fortunately, Reagent allows us to have localized states in our components. Let's take a look at implementing a multi-select component to see how this works.&lt;/p&gt;&lt;p&gt;When the user clicks on an item in the list, we'd like to mark it as selected. Obviously, this is something that's only relevant to the list component and shouldn't be tracked globally. All we have to do to create a local state is to initialize it in a closure.&lt;/p&gt;&lt;p&gt;We'll implement the multi-select by creating a component to represent the list and another to represent each selection item. The list component will accept an id and a label followed by the selection items.&lt;/p&gt;&lt;p&gt;Each item will be represented by a vector containing the id and the value of the item, eg: &lt;code&gt;&amp;#91;:beer &amp;quot;Beer&amp;quot;&amp;#93;&lt;/code&gt;. The value of the list will be represented by a collection of the ids of the currently selected items.&lt;/p&gt;&lt;p&gt;We will use a &lt;code&gt;let&lt;/code&gt; binding to initialize an atom with a map keyed on the item ids to represent the state of each item.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn selection-list &amp;#91;id label &amp;amp; items&amp;#93;
  &amp;#40;let &amp;#91;selections &amp;#40;-&amp;gt;&amp;gt; items &amp;#40;map &amp;#40;fn &amp;#91;&amp;#91;k&amp;#93;&amp;#93; &amp;#91;k false&amp;#93;&amp;#41;&amp;#41; &amp;#40;into {}&amp;#41; atom&amp;#41;&amp;#93;    
    &amp;#40;fn &amp;#91;&amp;#93;
      &amp;#91;:div.row
       &amp;#91;:div.col-md-2 &amp;#91;:span label&amp;#93;&amp;#93;
       &amp;#91;:div.col-md-5
        &amp;#91;:div.row
         &amp;#40;for &amp;#91;&amp;#91;k v&amp;#93; items&amp;#93;
          &amp;#91;list-item id k v selections&amp;#93;&amp;#41;&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The item component will be responsible for updating its state when clicked and persisting the new value of the list in the document.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn list-item &amp;#91;id k v selections&amp;#93;
  &amp;#40;letfn &amp;#91;&amp;#40;handle-click! &amp;#91;&amp;#93;
            &amp;#40;swap! selections update-in &amp;#91;k&amp;#93; not&amp;#41;
            &amp;#40;set-value! id &amp;#40;-&amp;gt;&amp;gt; @selections
                                &amp;#40;filter second&amp;#41;
                                &amp;#40;map first&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#91;:li {:class &amp;#40;str &amp;quot;list-group-item&amp;quot;
                      &amp;#40;if &amp;#40;k @selections&amp;#41; &amp;quot; active&amp;quot;&amp;#41;&amp;#41;
          :on-click handle-click!}
      v&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's add an instance of the &lt;code&gt;selection-list&lt;/code&gt; component to our form and see how it looks.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;

    &amp;#91;text-input :first-name &amp;quot;First name&amp;quot;&amp;#93;
    &amp;#91;text-input :last-name &amp;quot;First name&amp;quot;&amp;#93;

    &amp;#91;selection-list :favorite-drinks &amp;quot;Favorite drinks&amp;quot;
     &amp;#91;:coffee &amp;quot;Coffee&amp;quot;&amp;#93;
     &amp;#91;:beer &amp;quot;Beer&amp;quot;&amp;#93;
     &amp;#91;:crab-juice &amp;quot;Crab juice&amp;quot;&amp;#93;&amp;#93;

    &amp;#91;:button {:type &amp;quot;submit&amp;quot;
              :class &amp;quot;btn btn-default&amp;quot;
              :onClick #&amp;#40;.log js/console &amp;#40;clj-&amp;gt;js @state&amp;#41;&amp;#41;}
     &amp;quot;Submit&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, let's update our submit button to actually send the data to the server. We'll use the &lt;a href='https://github.com/JulianBirch/cljs-ajax'&gt;cljs-ajax&lt;/a&gt; library to handle our Ajax calls. Let's add the following dependency &lt;code&gt;&amp;#91;cljs-ajax &amp;quot;0.2.6&amp;quot;&amp;#93;&lt;/code&gt; to our &lt;code&gt;project.clj&lt;/code&gt; and update our namespace to reference it.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns main.core
 &amp;#40;:require &amp;#91;reagent.core :as reagent :refer &amp;#91;atom&amp;#93;&amp;#93;
           &amp;#91;ajax.core :refer &amp;#91;POST&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that in place we can write a &lt;code&gt;save-doc&lt;/code&gt; function that will send the current state of the document to the server and set the state to saved on success.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn save-doc &amp;#91;&amp;#93;
  &amp;#40;POST &amp;#40;str js/context &amp;quot;/save&amp;quot;&amp;#41;
        {:params &amp;#40;:doc @state&amp;#41;
         :handler &amp;#40;fn &amp;#91;&amp;#95;&amp;#93; &amp;#40;swap! state assoc :saved? true&amp;#41;&amp;#41;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now update our form to either display a message indicating that the document has been saved or the submit button based on the value of the &lt;code&gt;:saved?&lt;/code&gt; key in our state atom.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home &amp;#91;&amp;#93;
  &amp;#91;:div
    &amp;#91;:div.page-header &amp;#91;:h1 &amp;quot;Reagent Form&amp;quot;&amp;#93;&amp;#93;

    &amp;#91;text-input :first-name &amp;quot;First name&amp;quot;&amp;#93;
    &amp;#91;text-input :last-name &amp;quot;Last name&amp;quot;&amp;#93;
    &amp;#91;selection-list :favorite-drinks &amp;quot;Favorite drinks&amp;quot;
     &amp;#91;:coffee &amp;quot;Coffee&amp;quot;&amp;#93;
     &amp;#91;:beer &amp;quot;Beer&amp;quot;&amp;#93;
     &amp;#91;:crab-juice &amp;quot;Crab juice&amp;quot;&amp;#93;&amp;#93;

   &amp;#40;if &amp;#40;:saved? @state&amp;#41;
     &amp;#91;:p &amp;quot;Saved&amp;quot;&amp;#93;
     &amp;#91;:button {:type &amp;quot;submit&amp;quot;
              :class &amp;quot;btn btn-default&amp;quot;
              :onClick save-doc}
     &amp;quot;Submit&amp;quot;&amp;#93;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;On the server side we'll simply log the value submitted by the client and return "ok".&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns reagent-example.routes.services
  &amp;#40;:use compojure.core&amp;#41;
  &amp;#40;:require &amp;#91;reagent-example.layout :as layout&amp;#93;
            &amp;#91;noir.response :refer &amp;#91;edn&amp;#93;&amp;#93;
            &amp;#91;clojure.pprint :refer &amp;#91;pprint&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn save-document &amp;#91;doc&amp;#93;
  &amp;#40;pprint doc&amp;#41;
  {:status &amp;quot;ok&amp;quot;}&amp;#41;

&amp;#40;defroutes service-routes
  &amp;#40;POST &amp;quot;/save&amp;quot; {:keys &amp;#91;body-params&amp;#93;}
        &amp;#40;edn &amp;#40;save-document body-params&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With the route hooked up in our handler we should see something like the following whenever we submit a message from our client:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:first-name &amp;quot;Jasper&amp;quot;, :last-name &amp;quot;Beardly&amp;quot;, :favorite-drinks &amp;#40;:coffee :beer&amp;#41;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, getting started with Reagent is extremely easy and it requires very little code to create a working application. You could say that single page Reagent apps actually fit on a single page. :) In the next installment we'll take a look at using the &lt;a href='https://github.com/gf3/secretary'&gt;secretary&lt;/a&gt; library to add client side routing to the application.&lt;/p&gt;</description><pubDate>Tue, 15 Jul 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2014-01-26-No-Free-Lunch.html</guid><link>https://yogthos.net/posts/2014-01-26-No-Free-Lunch.html</link><title>No Free Lunch</title><description>&lt;p&gt;On paper static typing sounds strictly superior to dynamic typing. The compiler can track the data flow throughout our code and tell us when we're using the data incorrectly. This clearly eliminates a whole class of errors that are otherwise possible. What's more, types allow us to encode the business logic of our application allowing us to write code that's provably correct.&lt;/p&gt;&lt;p&gt;All this is unarguably correct, however these benefits do not come for free. One major problem is that static typing requires us to declare all the relationships globally. When you have global relationships a change at any level requires global refactoring at every level.&lt;/p&gt;&lt;p&gt;In my opinion, this makes static typing poorly suited for situations where your requirements are incomplete or subject to change, and in reality there are very few scenarios where your requirements are set in stone.&lt;/p&gt;&lt;p&gt;In most cases, we only care about a local contract between any two functions. What we want to know is that the function being called produces the type expected by the caller. A modification of a local contract should not cause global change in our code base.&lt;/p&gt;&lt;p&gt;Another cost of static typing is that it forces us to handle cases that are not part of the application workflow. For example, our code might have an undefined behavior, but the interface does not allow the user to access this state. This is a case of a tree falling in the woods when no one's around.&lt;/p&gt;&lt;p&gt;Regardless of the type system that you use, you will need to do functional testing in order to ensure that the business logic does what's intended. At the end of the day, the goal of the application is to handle the intended use cases as opposed to providing a proof of correctness.&lt;/p&gt;&lt;p&gt;When I look at the GitHub issues for my own projects such as &lt;a href='https://github.com/yogthos/Selmer'&gt;Selemer&lt;/a&gt; or &lt;a href='https://github.com/yogthos/markdown-clj/issues?page=1&amp;state=closed'&gt;markdown-clj&lt;/a&gt;, vast majority of them stem from lack of specification. Practically none of these issues would have been caught by the type system. Had I used a statically typed language to write these projects, I would've simply had to jump through more hoops to end up with the same result.&lt;/p&gt;&lt;p&gt;In my opinion the value added by a static type system has to be weighed against the complexity of the problem and the cost of errors. Since it's obviously useful in some cases and provides dubious value in others, an optional type system might provide the right balance. Static typing is a tool and it should be up to the developer to decide how and when to apply it.&lt;/p&gt;&lt;p&gt;With an optional static checker we can add types where it makes sense and leave the rest of the code dynamic. This is precisely the situation &lt;a href='http://blog.circleci.com/supporting-typed-clojure/'&gt;CircleCI found themselves in&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 26 Jan 2014 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-12-09-Clojure-High-Performance-Programming-Review.html</guid><link>https://yogthos.net/posts/2013-12-09-Clojure-High-Performance-Programming-Review.html</link><title>Clojure High Performance Programming Review</title><description>&lt;p&gt;First thing I'd like to say is that I'm very excited by the shift in nature of Clojure books that are coming out. There are already many excellent books about the language itself. Some of these include &lt;a href='http://www.amazon.com/The-Joy-Clojure-Michael-Fogus/dp/1617291412/'&gt;The Joy of Clojure&lt;/a&gt;, &lt;a href='http://www.amazon.com/Programming-Clojure-Stuart-Halloway/dp/1934356867'&gt;Programming Clojure&lt;/a&gt;, and &lt;a href='http://www.amazon.com/Clojure-Action-Amit-Rathore/dp/1935182595'&gt;Clojure in Action&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;This year we can add &lt;a href='http://www.amazon.com/Clojure-Data-Analysis-Cookbook-Rochester-ebook/dp/B00BECVV9C'&gt;Clojure Data Analysis Cookbook&lt;/a&gt;, &lt;a href='http://clojure-cookbook.com/'&gt;Clojure Cookbook&lt;/a&gt;, my own &lt;a href='http://pragprog.com/book/dswdcloj/web-development-with-clojure'&gt;Web Development With Clojure&lt;/a&gt;, and &lt;a href='http://www.amazon.com/Clojure-Performance-Programming-Shantanu-Kumar-ebook/dp/B00GTE1RVW'&gt;Clojure High Performance Programming&lt;/a&gt; to the roster. All these books focus on applying the language in the real world.&lt;/p&gt;&lt;p&gt;To me this indicates that developers are moving from simply experimenting with the language to actually using it professionally. The results from the &lt;a href='http://cemerick.com/2013/11/18/results-of-the-2013-state-of-clojure-clojurescript-survey/'&gt;2013 State of Clojure &amp; ClojureScript&lt;/a&gt;, where more than half the respondents reported using Clojure at work, appear to corroborate this idea.&lt;/p&gt;&lt;p&gt;One of the things that makes Clojure attractive is the fact that it's one of the more performant dynamic languages. As can be seen in the recent round of &lt;a href='http://www.techempower.com/benchmarks/'&gt;TechEmpower Benchmarks&lt;/a&gt;, Clojure web frameworks fare quite well compared to the popular offerings in Ruby and Python. Since performance is a major factor in using Clojure, a book discussing high performance programming is a welcome addition.&lt;/p&gt;&lt;p&gt;The book starts off by introducing the reader to performance use case classification. It does a decent job of explaining the background concepts and the vocabulary that will be used throughout.&lt;/p&gt;&lt;p&gt;Different types of scenarios are discussed and their related performance concerns. For example, when we deal with user interfaces, responsiveness is our main concern. On the other hand if we're doing data-processing then we want to optimize CPU and memory usage.&lt;/p&gt;&lt;p&gt;The author then moves on to discuss how common Clojure idioms impact the performance of the application. Understanding what goes on behind the scenes helps reason about potential pitfalls down the road.&lt;/p&gt;&lt;p&gt;There's a good discussion about the explicit use of &lt;code&gt;loop/recur&lt;/code&gt; over higher order functions that illustrates a way to squeeze out additional performance. In another section the author goes on to explain the impact of laziness on performance in functional languages. &lt;/p&gt;&lt;p&gt;There are also tips regarding the use of different data formats. One example compares the benefits of EDN over JSON. EDN can save memory by using interned symbols and keywords, while JSON uses string keys which will not be interned. The author explains that in addition to saving memory, interning also avoids heap usage and this helps minimize garbage collection. This is something you would definitely want to consider if you were working with a high performance application.&lt;/p&gt;&lt;p&gt;The techniques used by some of the popular libraries, such as &lt;a href='https://github.com/ptaoussanis/nippy'&gt;Nippy&lt;/a&gt;, are examined to see how they achieve high performance. These kinds of real world examples are very helpful. Not only do we learn about the theory, but we also get to see how it's applied in practice.&lt;/p&gt;&lt;p&gt;In general, the book covers a wide range of topics, but only offers a superficial overview for many. The reader will most certainly need to do further research in order to apply many of the concepts discussed.&lt;/p&gt;&lt;p&gt;If you're looking for a refresher or a primer on the topics discussed, then it's not a bad place to start. However, if you're looking for a comprehensive discussion on doing high performance programming with Clojure, you'll likely be left wanting.&lt;/p&gt;</description><pubDate>Mon, 09 Dec 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-11-21-Making-Selmer-User-Friendly.html</guid><link>https://yogthos.net/posts/2013-11-21-Making-Selmer-User-Friendly.html</link><title>Making Selmer User Friendly</title><description>&lt;p&gt;It's been nearly 5 month since Selmer was released. In that time many bugs have been squashed and lots of new features added. However, there is one aspect that remained shameful and that was error reporting.&lt;/p&gt;&lt;p&gt;When Selmer failed to parse a template it would often produce error messages that were less than useful. For example, given the following template:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;html&amp;gt;
  &amp;lt;body&amp;gt;
    {% blok %}
    {% endblock %}
    &amp;lt;h2&amp;gt;Hello {{name}}&amp;lt;/h2&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;we'd end up with the following error after trying to render it:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Exception in thread &amp;quot;main&amp;quot; java.lang.Exception: unrecognized tag: :blok - did you forget to close a tag?
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;While the error indicated the name of the problem tag, it didn't say what template this tag originated from or on what line it appeared.&lt;/p&gt;&lt;p&gt;These types of errors can result in a lot of wasted time and frustration. It would be much better to provide a clear error that contains the actual offending tag along with the name of the template and the line number.&lt;/p&gt;&lt;p&gt;As of version &lt;code&gt;0.4.8&lt;/code&gt;, Selmer has a validator that checks the following cases:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;can the tag be parsed successfully&lt;/li&gt;&lt;li&gt;is the filter found in the map of filters&lt;/li&gt;&lt;li&gt;does the tag contain a name&lt;/li&gt;&lt;li&gt;is the tag name found in the map of tags&lt;/li&gt;&lt;li&gt;if a tag is a block tag, is the corresponding closing tag found&lt;/li&gt;&lt;li&gt;is the tag a closing tag for an opening tag that's not present&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Here's the error returned by the validator when rendering the above template:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Exception in thread &amp;quot;main&amp;quot; java.lang.Exception: Unrecognized tag: {% blok %} on line 3 for template file:/Users/Yogthos/selmer-test/resources/index.html
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This gives us a lot more information as to what went wrong and where. This is a big improvement on the original error, however we still have an ugly stacktrace to look at to figure out what happened.&lt;/p&gt;&lt;p&gt;It would be even better to return a distinct validation error that could be intercepted by some middleware to produce a friendly error page.&lt;/p&gt;&lt;p&gt;This is precisely what Selmer does as of version &lt;code&gt;0.5.3&lt;/code&gt;. The validator will now return &lt;code&gt;ex-info&lt;/code&gt; with a key &lt;code&gt;:type&lt;/code&gt; that's set to &lt;code&gt;:selmer-validation-error&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;It will also contain an error page template that can be rendered using the &lt;code&gt;ex-data&lt;/code&gt; attached to the exception. We can now write a simple middleware function to catch these errors and render the error page:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn template-error-page &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;request&amp;#93;
    &amp;#40;try
      &amp;#40;handler request&amp;#41;
      &amp;#40;catch clojure.lang.ExceptionInfo ex
        &amp;#40;let &amp;#91;{:keys &amp;#91;type error-template&amp;#93; :as data} &amp;#40;ex-data ex&amp;#41;&amp;#93;
          &amp;#40;if &amp;#40;= :selmer-validation-error type&amp;#41;
            {:status 500
             :body   &amp;#40;selmer.parser/render error-template data&amp;#41;}
            &amp;#40;throw ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using the above middleware, we'll see the following page whenever the parser fails to compile a template:&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="http://yogthos.net/files/selmererror.png" alt="Selmer error" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;We can now immediately tell that an error occurred during the template compilation and see only the information pertaining to the nature of the error.&lt;/p&gt;&lt;p&gt;Of course, we wouldn't want to display this information when running in production. A simple solution would be to set a &lt;code&gt;dev&lt;/code&gt; flag and check for it in our middleware.&lt;/p&gt;&lt;p&gt;This is precisely what the latest &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; template will do using the &lt;a href='https://github.com/weavejester/environ'&gt;environ&lt;/a&gt; library. The &lt;code&gt;project.clj&lt;/code&gt; now contains an &lt;code&gt;:env&lt;/code&gt; key under the &lt;code&gt;:dev&lt;/code&gt; profile with the &lt;code&gt;:selmer-dev&lt;/code&gt; flag set to &lt;code&gt;true&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:dev {:dependencies &amp;#91;&amp;#91;ring-mock &amp;quot;0.1.5&amp;quot;&amp;#93;
                     &amp;#91;ring/ring-devel &amp;quot;1.2.1&amp;quot;&amp;#93;&amp;#93;
      :env {:selmer-dev true}}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The middleware will check that the key is present and only render the error page in development mode:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn template-error-page &amp;#91;handler&amp;#93;
  &amp;#40;if &amp;#40;env :selmer-dev&amp;#41;
    &amp;#40;fn &amp;#91;request&amp;#93;
      &amp;#40;try
        &amp;#40;handler request&amp;#41;
        &amp;#40;catch clojure.lang.ExceptionInfo ex
          &amp;#40;let &amp;#91;{:keys &amp;#91;type error-template&amp;#93; :as data} &amp;#40;ex-data ex&amp;#41;&amp;#93;
            &amp;#40;if &amp;#40;= :selmer-validation-error type&amp;#41;
              {:status 500
               :body &amp;#40;parser/render error-template data&amp;#41;}
              &amp;#40;throw ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
    handler&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When it comes to writing libraries it's easy to forget about the little things like error reporting and documentation. However, these things are just as important as having good code and a clean API. &lt;/p&gt;&lt;p&gt;In the end, this is what makes the difference between a pleasant development experience and one that's fraught with frustration.&lt;/p&gt;</description><pubDate>Thu, 21 Nov 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-08-28-Web-Development-With-Clojure-Beta.html</guid><link>https://yogthos.net/posts/2013-08-28-Web-Development-With-Clojure-Beta.html</link><title>Web Development With Clojure Beta</title><description>&lt;p&gt;I'm happy to announce that &lt;a href='http://pragprog.com/book/dswdcloj/web-development-with-clojure'&gt;Web Development With Clojure&lt;/a&gt; has finally reached beta and it's now available for purchase.&lt;/p&gt;&lt;p&gt;The book covers working with the core Ring/Compojure stack, common libraries as well as techniques for accomplishing common tasks. My main goal is to make the reader comfortable with the Clojure ecosystem and demonstrate how to take an application from inception all the way to deployment.&lt;/p&gt;&lt;p&gt;It's been a long journey to get to this point and I learned much along the way. This book is my way to share that experience with you and hopefully save you time when working on your projects.&lt;/p&gt;&lt;p&gt;There's still some clean up left to do and you might see a few typos here and there. However, there won't be any changes to the core content at this point and I hope that you'll be curious enough to take a look. :)&lt;/p&gt;</description><pubDate>Wed, 28 Aug 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-08-18-Why-I-m-Productive-in-Clojure.html</guid><link>https://yogthos.net/posts/2013-08-18-Why-I-m-Productive-in-Clojure.html</link><title>Why I'm Productive in Clojure</title><description>&lt;p&gt;I find that I often get excited about learning a new language, but after I use it for a while it will inevitably lose its lustre. Eventually it becomes just another language in my tool box. &lt;/p&gt;&lt;p&gt;One exception to this rule is Clojure. I still enjoy using the language as much as I did when I first learned it. The reason for this is that it strikes the right balance between power and simplicity.&lt;/p&gt;&lt;h3 id="the&amp;#95;balance&amp;#95;of&amp;#95;power"&gt;The Balance of Power&lt;/h3&gt;&lt;p&gt;Some languages are simple but they're also verbose. You've probably heard people say that verbosity really doesn't matter. These people will go to great length to point out that all languages are Turing complete and that in certain languages you simply have to write a bit more code.&lt;/p&gt;&lt;p&gt;I think that's missing the point however. The question is not whether something can be expressed in principle. It's how well the language maps to the problem being solved. One language will let you think in terms of your problem domain, while another will force you to translate the problem to its constructs.&lt;/p&gt;&lt;p&gt;The latter is often tedious and rarely enjoyable. You end up writing a lot of boilerplate code and constantly repeating yourself. I hope you'll agree that there is a certain amount of irony involved in having to write repetitive code.&lt;/p&gt;&lt;p&gt;Other languages aren't verbose and they provide many different tools for solving problems. Unfortunately, working in such languages is often akin to trying to decide on a particular set of screwdrivers at a hardware megastore.&lt;/p&gt;&lt;p&gt;You end up comparing this brand against that, checking the number of bits that comes with each set, seeing which one's on sale today, and soon you forget why you wanted a screwdriver in the first place. &lt;/p&gt;&lt;p&gt;The more features there are the more things you have to keep in your head to work with the language effectively. With many languages I find myself constantly expending mental overhead thinking about all the different features and how they interact with one another.&lt;/p&gt;&lt;p&gt;What matters to me in a language is whether I can use it without thinking about it. When the language is lacking in expressiveness I'm acutely aware that I'm writing code that I shouldn't be. On the other hand when the language has too many features I often feel overwhelmed or I get distracted playing with them.&lt;/p&gt;&lt;p&gt;To make an analogy with math, it's nicer to have a general formula that you can derive others from than having to memorize a whole bunch of formulas for specific problems.&lt;/p&gt;&lt;p&gt;This is where Clojure comes in. With it I can always easily derive a solution to a particular problem from a small set of general patterns. The number of things I have to keep in my head is not overbearing.&lt;/p&gt;&lt;p&gt;All you need to become productive is to learn a few simple concepts and a bit of syntax. However, the number of ways that these concepts can be combined to solve all manner of problems appears to be inexhaustible. I've been writing Clojure for years and I discover new ways to combine the things I already know every single day.&lt;/p&gt;&lt;p&gt;Macros are a good example of this. The fact that you can transform the language using itself allows tackling a wide range of problems that would otherwise require a range of specific tools and language features.&lt;/p&gt;&lt;h3 id="interactive&amp;#95;development"&gt;Interactive Development&lt;/h3&gt;&lt;p&gt;When I'm solving a problem in Clojure I inevitably want to write an elegant solution that expresses the gist of it cleanly and clearly. This is largely due to the fact that the development process is interactive. &lt;/p&gt;&lt;p&gt;When I work with the REPL I can fumble around looking for a solution and make sense of it through experimentation. Once I've internalized the problem I can quickly write a clean solution using my newly gained understanding.&lt;/p&gt;&lt;p&gt;The REPL also helps keep me engaged in trying to find the solution. Being able to try things and get immediate feedback is enjoyable. Even when your code doesn't do what you want you can see the progression and that is often enough of a motivator to keep going.&lt;/p&gt;&lt;p&gt;Another important feature of the REPL is that it encourages refactoring. I'm much more likely to refactor code when I can easily test it without disrupting my workflow.&lt;/p&gt;&lt;h3 id="finishing&amp;#95;things"&gt;Finishing Things&lt;/h3&gt;&lt;p&gt;Interactivity alone isn't enough however. All the feedback in the world wouldn't make one bit of difference if you couldn't actually solve your problem in a reasonable amount of time.&lt;/p&gt;&lt;p&gt;I find that I have a sharp falloff curve when it comes to staying engaged in a project. You've probably noticed this phenomenon yourself. When you start a project you're excited and you enjoy seeing it take shape.&lt;/p&gt;&lt;p&gt;However, after working on a project for some amount of time the excitement wanes. Eventually, you might even dread having to touch the code again. I find that it's critical to get the core functionality working before I hit this stage.&lt;/p&gt;&lt;p&gt;Once the project solves a particular problem that I have I'll start using it. At this point I get to reap the benefits of having spent the effort on it. This also lets me identify the functionality that I'm missing through usage. There is a lot more incentive to add features to a project that you're actually using.&lt;/p&gt;&lt;p&gt;Most recently I found this to be the case working on &lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt;. I was able to implement the base parser in just a couple of days, while &lt;a href='https://github.com/cesarbp'&gt;cesarbp&lt;/a&gt; implemented the logic for the filters.&lt;/p&gt;&lt;p&gt;It took a couple of more days to get the template inheritance logic working. All of a sudden we had a usable library in under a week of effort. I'm already actively using it for actual work and new features are added piecemeal as the need comes up.&lt;/p&gt;&lt;p&gt;Here's the GitHub &lt;a href='https://github.com/yogthos/Selmer/graphs/code-frequency'&gt;activity&lt;/a&gt; graph for Selmer:&lt;/p&gt;&lt;p&gt;&lt;a href='https://github.com/yogthos/Selmer/graphs/code-frequency'&gt;&lt;img src="http://yogthos.net/files/selmercommits.png" alt="Selmer activity" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;As you can see there's a big initial spike with a very sharp falloff. A similar patten can be seen in my other projects such as &lt;a href='https://github.com/yogthos/clj-pdf'&gt;clj-pdf&lt;/a&gt; and with &lt;a href='https://github.com/yogthos/luminus'&gt;Luminus&lt;/a&gt;:&lt;/p&gt;&lt;p&gt;&lt;a href='https://github.com/yogthos/clj-pdf/graphs/code-frequency'&gt;&lt;img src="http://yogthos.net/files/clj-pdfcommits.png" alt="clj-pdf activity" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://github.com/yogthos/luminus/graphs/code-frequency'&gt;&lt;img src="http://yogthos.net/files/luminuscommits.png" alt="Luminus activity" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;As the project matures bugs are inevitably found or new features are added, these correspond the occasional spikes in the activity. However, if the initial phase of the project can't be completed in a timely fashion then nothing else can happen.&lt;/p&gt;&lt;p&gt;In my experience, if you can't get something interesting working in a few days the likelihood of actually finishing the project starts rapidly approaching zero.&lt;/p&gt;&lt;p&gt;With Clojure you can get things done fast, fast enough that you get something working while the initial spark of excitement is still present. I would hazard to guess that this is the reason why Clojure has so many great libraries despite being a young language.&lt;/p&gt;</description><pubDate>Sun, 18 Aug 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-07-30-Introducing-Selmer.html</guid><link>https://yogthos.net/posts/2013-07-30-Introducing-Selmer.html</link><title>Introducing Selmer</title><description>&lt;h2 id="rationale"&gt;Rationale&lt;/h2&gt;&lt;p&gt;There are a number of templating engines available in Clojure. Some of the popular ones include &lt;a href='https://github.com/weavejester/hiccup'&gt;Hiccup&lt;/a&gt;, &lt;a href='https://github.com/cgrand/enlive'&gt;Enlive&lt;/a&gt;, &lt;a href='https://github.com/Raynes/laser'&gt;Laser&lt;/a&gt;, &lt;a href='https://github.com/davidsantiago/stencil'&gt;Stencil&lt;/a&gt;, &lt;a href='https://github.com/shenfeng/mustache.clj'&gt;mustache.clj&lt;/a&gt; and &lt;a href='https://github.com/danlarkin/clabango'&gt;Clabango&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;As &lt;a href='http://yogthos.net/blog/41-New+Templating+Engine+in+Luminus'&gt;I've mentioned previously&lt;/a&gt;, my personal preference is for Clabango syntax. In my opinion it provides the right balance between simplicity and flexibility. Being modeled on Django template syntax it's also very accessible to those who are new to Clojure web development.&lt;/p&gt;&lt;p&gt;However, one major downside to Clabango is that it's slow. On TechEmpower &lt;a href='http://www.techempower.com/benchmarks/#section=data-r6&amp;hw=i7&amp;test=fortune&amp;f=4-0-1s'&gt;fortunes benchmark&lt;/a&gt; Luminus is crawling behind the Compojure results. Yes, you read that right, it's nearly 20 times slower for Clabango to render the results. The difference being that the Compojure benchmark is using Hiccup for rendering the results while Luminus is using Clabango.&lt;/p&gt;&lt;p&gt;The core problem is that Clabango always parses the source files when rendering a template. This is very expensive as it involves disk access and scanning each character in the source file each time a page is served. Dan states that &lt;a href='https://github.com/danlarkin/clabango/issues/13'&gt;performance has not been a priority&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;On top of that, some of the existing behaviours put limitations on how much the performance can ultimately be improved. For example, the child templates aren't required to put their content inside blocks. Clabango parses the templates and creates the AST that's then evaluated. This means that you can put blocks inside the &lt;code&gt;if&lt;/code&gt; tags and decide at runtime whether they will be included. If inheritance resolution is pushed to compile time this becomes a problem.&lt;/p&gt;&lt;p&gt;After having some discussions with &lt;a href='https://github.com/bitemyapp'&gt;bitemyapp&lt;/a&gt; and &lt;a href='https://github.com/cesarbp'&gt;ceaserbp&lt;/a&gt; we decided that it would be worth writing a fresh impelementation with pefromance as its primary goal. Another reason is that I would like to be able to ensure that the templating engine in Luminus isn't a compromise between speed and convenience. Owning the implementation is the best way to achieve that.&lt;/p&gt;&lt;h2 id="enter&amp;#95;selmer"&gt;Enter Selmer&lt;/h2&gt;&lt;p&gt;All this resulted in &lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt; named after &lt;a href='http://en.wikipedia.org/wiki/Selmer_guitar'&gt;the guitar favored by Django Reinhardt&lt;/a&gt; whom in turn Django is named after. Selmer aims to be a near drop in replacement for Clabango. The current version is already quite fast keeping pace with Stencil which is one of the faster engines around.&lt;/p&gt;&lt;p&gt;In order to minimize the work that's done at runtime Selmer splits the process into three distinct steps. These steps include preprocessing, compilation and rendering. &lt;/p&gt;&lt;p&gt;First, Selmer will resolve the inheritance hierarchy and generate the definitive template source to be compiled. The &lt;code&gt;extends&lt;/code&gt; and &lt;code&gt;include&lt;/code&gt; tags will be handled at this time.&lt;/p&gt;&lt;p&gt;The compilation step then produces a vector of text nodes and runtime transformer functions.&lt;/p&gt;&lt;p&gt;The renderer uses these compiled templates to generate its output. The text gets rendered without further manipulation while the transformers use the context map to generate their output at runtime.&lt;/p&gt;&lt;p&gt;Using this approach we minimize the amount of logic that needs to be executed during each request as well as avoiding any disk access in the process.&lt;/p&gt;&lt;p&gt;In order not to have to restart the application when the source templates are changed the renderer checks the last updated timestamp of the template. When the timestamp is changed a recompile is triggered.&lt;/p&gt;&lt;h2 id="performance&amp;#95;tricks"&gt;Performance Tricks&lt;/h2&gt;&lt;p&gt;To our chagrin the first run of the parser ran no better than Clabango. This was rather disappointing considering we took pains to be mindful of the performance issues. However, this mystery was quickly solved by profiling the parser.&lt;/p&gt;&lt;p&gt;Sure enough majority of time was spent in reflection calls. One major problem was that the renderer had to check whether each node was text or a function:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn render &amp;#91;template params&amp;#93;  
  &amp;#40;let &amp;#91;buf &amp;#40;StringBuilder.&amp;#41;&amp;#93;
    &amp;#40;doseq &amp;#91;element template&amp;#93; 
      &amp;#40;.append buf &amp;#40;if &amp;#40;string? element&amp;#41; element &amp;#40;element params&amp;#41;&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;.toString buf&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Protocols offer an elegant solution to this problem. With their help we can move this work to compile time as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defprotocol INode
  &amp;#40;render-node &amp;#91;this context-map&amp;#93; &amp;quot;Renders the context&amp;quot;&amp;#41;&amp;#41;

&amp;#40;deftype FunctionNode &amp;#91;handler&amp;#93;
  INode
  &amp;#40;render-node &amp;#94;String &amp;#91;this context-map&amp;#93;
    &amp;#40;handler context-map&amp;#41;&amp;#41;&amp;#41;

&amp;#40;deftype TextNode &amp;#91;text&amp;#93;
  INode
  &amp;#40;render-node &amp;#94;String &amp;#91;this context-map&amp;#93;
    text&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now our parser can happily run along and call &lt;code&gt;render-node&lt;/code&gt; on each element:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn render-template &amp;#91;template context-map&amp;#93;
  &amp;quot;&amp;quot;&amp;quot; vector of &amp;#94;selmer.node.INodes and a context map.&amp;quot;&amp;quot;&amp;quot;
  &amp;#40;let &amp;#91;buf &amp;#40;StringBuilder.&amp;#41;&amp;#93;
    &amp;#40;doseq &amp;#91;&amp;#94;selmer.node.INode element template&amp;#93;
        &amp;#40;if-let &amp;#91;value &amp;#40;.render-node element context-map&amp;#41;&amp;#93;
          &amp;#40;.append buf value&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;.toString buf&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With this change and a few type annotations the performance improved dramatically. Running &lt;a href='https://github.com/bitemyapp/clojure-template-benchmarks'&gt;clojure-template-benchmarks&lt;/a&gt; the results are comparable to Stencil. Here are the results from benchmarking on my machine:&lt;/p&gt;&lt;h3 id="clabango"&gt;Clabango&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Simple Data Injection&lt;ul&gt;&lt;li&gt;Execution time mean : 657.530826 µs&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 2.118301 µs&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Small List (50 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 2.446739 ms&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 17.448003 µs&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Big List (1000 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 28.230365 ms&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 173.518425 µs&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="selmer"&gt;Selmer&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Simple Data Injection&lt;ul&gt;&lt;li&gt;Execution time mean : 42.444958 µs&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 235.652171 ns&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Small List (50 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 209.158509 µs&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 4.045131 µs&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Big List (1000 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 3.223797 ms&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 55.511322 µs    &lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="stencil"&gt;Stencil&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Simple Data Injection&lt;ul&gt;&lt;li&gt;Execution time mean : 92.317566 µs&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 213.253353 ns&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Small List (50 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 290.403204 µs&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 1.801479 µs&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Big List (1000 items)&lt;ul&gt;&lt;li&gt;Execution time mean : 1.223634 ms&lt;/li&gt;&lt;li&gt;Execution time std-deviation : 4.264979 µs    &lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;As you can see Selmer is showing a large improvement over Clabango and has no trouble keeping up with Stencil.&lt;/p&gt;&lt;p&gt;Obviously, this benchmark is fairly simplistic so you can take it with a grain of salt. If anybody would like to put together a more comprehensive suite that would be great. :)&lt;/p&gt;&lt;h2 id="current&amp;#95;status"&gt;Current status&lt;/h2&gt;&lt;p&gt;The library implements all the functionality offered by Clabango and passes the Clabango test sutie. There are a few minor deviations, but overall it should work as a drop in replacement without the need to change your existing HTML templates. &lt;/p&gt;&lt;p&gt;We also have a few new features such as the Django &lt;code&gt;{{block.super}}&lt;/code&gt; tag support and ability to use filters in if statements. In Selmer you can write things like:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;selmer.filters/add-filter! :empty? empty?&amp;#41;

&amp;#40;render 
  &amp;quot;{% if files|empty? %}
   no files available 
   {% else %} 
       {% for file in files %}{{file}}{% endfor %} 
   {% endif %}&amp;quot;
  {:files &amp;#91;&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Switching to Selmer involves swapping the &lt;code&gt;&amp;#91;clabango &amp;quot;0.5&amp;quot;&amp;#93;&lt;/code&gt; dependency for &lt;code&gt;&amp;#91;selmer &amp;quot;0.5.3&amp;quot;&amp;#93;&lt;/code&gt; and referencing &lt;code&gt;selmer.parser&lt;/code&gt; instead of &lt;code&gt;clabango.parser&lt;/code&gt;. Selmer provides the same API for rendering templates using the &lt;code&gt;selmer.parser/render&lt;/code&gt; and &lt;code&gt;selmer.parser/render-file&lt;/code&gt; functions.&lt;/p&gt;&lt;p&gt;One major area of difference is in how custom tags and filters are defined. Defining a filter is done by calling &lt;code&gt;selmer.filters/add-filter!&lt;/code&gt; with the id of the filter and the filter function:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;use 'selmer.filters&amp;#41;

&amp;#40;add-filter! :embiginate #&amp;#40;.toUpperCase %&amp;#41;&amp;#41;

&amp;#40;render &amp;quot;{{shout|embiginate}}&amp;quot; {:shout &amp;quot;hello&amp;quot;}&amp;#41;
=&amp;gt;&amp;quot;HELLO&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Defining custom tags is equally simple using the &lt;code&gt;selmer.parser/add-tag!&lt;/code&gt; macro:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;use 'selmer.parser&amp;#41;

&amp;#40;add-tag! :foo
  &amp;#40;fn &amp;#91;args context-map&amp;#93;
    &amp;#40;str &amp;quot;foo &amp;quot; &amp;#40;first args&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;render &amp;quot;{% foo quux %} {% foo baz %}&amp;quot; {}&amp;#41;
=&amp;gt;&amp;quot;foo quux foo baz&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;tags can also contain content and intermediate tags:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;add-tag! :foo
  &amp;#40;fn &amp;#91;args context-map content&amp;#93;
    &amp;#40;str content&amp;#41;&amp;#41;
  :bar :endfoo&amp;#41;

&amp;#40;render &amp;quot;{% foo %} some text {% bar %} some more text {% endfoo %}&amp;quot; {}&amp;#41;
=&amp;gt;&amp;quot;{:foo {:args nil, :content \&amp;quot; some text \&amp;quot;}, :bar {:args nil, :content \&amp;quot; some more text \&amp;quot;}}&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Selmer also supports overriding the default tag characters using &lt;code&gt;:tag-open&lt;/code&gt;, &lt;code&gt;:tag-close&lt;/code&gt;, &lt;code&gt;:filter-open&lt;/code&gt;, &lt;code&gt;:filter-close&lt;/code&gt; and &lt;code&gt;:tag-second&lt;/code&gt; keys:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;render &amp;quot;&amp;#91;% for ele in foo %&amp;#93;&amp;lt;&amp;lt;&amp;#91;{ele}&amp;#93;&amp;gt;&amp;gt;&amp;#91;%endfor%&amp;#93;&amp;quot;
                 {:foo &amp;#91;1 2 3&amp;#93;}
                 {:tag-open \&amp;#91;
                  :tag-close \&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This makes it much easier to use it in conjunction with client-side frameworks such as AngularJs.&lt;/p&gt;&lt;p&gt;One limitation Selmer has is the way it handles inheritance. Since the inheritance block hierarchy is compiled before the parsing step, any content in child templates must be encapsulated in block tags. Free-floating tags and text will simply be ignored by the parser. This is in line with &lt;a href='http://stackoverflow.com/questions/1408925/django-templates-include-and-extends'&gt;Django behavior&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;So there you have it. If you like Django template syntax or just want a fast templating engine then give Selmer a try.&lt;/p&gt;&lt;p&gt;As it is a new project there may be bugs and oddities so don't hesitate to open an issue on the project page if you find any. So far I haven't found any problems in switching my application from Clabango to Selmer and the test coverage is fairly extensive at this point. &lt;/p&gt;</description><pubDate>Tue, 30 Jul 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-06-12-lib-noir-access-rule-madness.html</guid><link>https://yogthos.net/posts/2013-06-12-lib-noir-access-rule-madness.html</link><title>lib-noir access rule madness</title><description>&lt;p&gt;Access rule handling in &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt; has seen some major rework. James Reeves pointed out that the way the &lt;code&gt;restrict&lt;/code&gt; macro worked was not ideal as it wasn't entirely idiomatic and wasn't very composable. For example it didn't take into account the use of the &lt;code&gt;context&lt;/code&gt; macro in Compojure.&lt;/p&gt;&lt;p&gt;While there are some breaking changes, it's pretty easy to migrate the old rules and the new approach provides a lot more flexibility.&lt;/p&gt;&lt;p&gt;The first thing that's changed is how the restricted routes are defined. The macro now wraps the handler itself instead of the whole route. So instead of doing&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;restricted GET &amp;quot;/private&amp;quot; &amp;#91;&amp;#93; handler&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;you would now write:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;GET &amp;quot;/private&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted handler&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Access rules definitions in the &lt;code&gt;noir.util.middleware/app-handler&lt;/code&gt; have been revamped as well. The rules can now be specified by passing either a function representing a single rule or a map representing a group of rules.&lt;/p&gt;&lt;p&gt;When specified as a function, the rule must accept a single parameter that is the request map. Such rules will implicitly redirect to the "/" URI.&lt;/p&gt;&lt;p&gt;The rule group map contains the following keys:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;:redirect&lt;/code&gt; - the URI string or a function to specify where requests will be redirected to if rejected (optional defaults to "/")&lt;/li&gt;&lt;li&gt;&lt;code&gt;:uri&lt;/code&gt; - the URI for which the rules in the map will be activated (optional if none specified applies to all URIs)&lt;/li&gt;&lt;li&gt;&lt;code&gt;:uris&lt;/code&gt; - a vector of URI patterns for which the rules in the map will be activated (optional)&lt;/li&gt;&lt;li&gt;&lt;code&gt;:rule&lt;/code&gt; - a single rule function for the group&lt;/li&gt;&lt;li&gt;&lt;code&gt;:rules&lt;/code&gt; - a vector containing the rule functions associated with the specified &lt;code&gt;:redirect&lt;/code&gt; and the &lt;code&gt;:uri&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;:on-fail&lt;/code&gt; - alternative to &lt;code&gt;:redirect&lt;/code&gt; allows providing a function that accepts a request and handles the failure case&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The &lt;code&gt;:rules&lt;/code&gt; key can point to either a vector or a map. If the rules are a vector the default behavior is that every rule in the group must succeed. If rules are specified as a map, you can provide the resolution strategy using the &lt;code&gt;:any&lt;/code&gt; and &lt;code&gt;:every&lt;/code&gt; keys.&lt;/p&gt;&lt;p&gt;Let's take a look at an example of how this all works below:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def-restricted-routes

&amp;#40;defroutes app-routes
 ;;restricted routes
 &amp;#40;GET &amp;quot;/restricted&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;this page is restricted&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/restricted1&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;this is another restricted page&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/users/:id&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;howdy&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/admin&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;admin route&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/config&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;config route&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/super-secret&amp;quot; &amp;#91;&amp;#93; &amp;#40;restricted &amp;quot;secret route&amp;quot;&amp;#41;&amp;#41;
 ;;public routes
 &amp;#40;GET &amp;quot;/denied1&amp;quot; &amp;#91;&amp;#93; &amp;quot;denied&amp;quot;&amp;#41;
 &amp;#40;GET &amp;quot;/denied2&amp;quot; &amp;#91;&amp;#93; &amp;quot;denied differently&amp;quot;&amp;#41;&amp;#41;

&amp;#40;def app 
 &amp;#40;middleware/app-handler 
   &amp;#91;app-routes&amp;#93;
   :access-rules 
   &amp;#91;&amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :user&amp;#41;&amp;#41;

    {:uri &amp;quot;/restricted&amp;quot;
     :redirect &amp;quot;/denied1&amp;quot;
     :rule &amp;#40;fn &amp;#91;req&amp;#93; false&amp;#41;}

    {:redirect &amp;#40;fn &amp;#91;req&amp;#93; 
                 &amp;#40;log/info &amp;#40;str &amp;quot;redirecting &amp;quot; &amp;#40;:uri req&amp;#41;&amp;#41;&amp;#41;
                 &amp;quot;/denied2&amp;quot;&amp;#41;
     :uri &amp;quot;/users/&amp;#42;&amp;quot;
     :rule &amp;#40;fn &amp;#91;req&amp;#93; false&amp;#41;}

    {:uris &amp;#91;&amp;quot;/admin&amp;#42;&amp;quot; &amp;quot;/config&amp;#42;&amp;quot;&amp;#93;
     :rules {:any &amp;#91;&amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :admin&amp;#41;&amp;#41;
                   &amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :root&amp;#41;&amp;#41;&amp;#93;}}

    {:on-fail &amp;#40;fn &amp;#91;req&amp;#93; &amp;quot;you tried to access the super secret page!&amp;quot;&amp;#41;
     :uri &amp;quot;/super-secret&amp;#42;&amp;quot;
     :rules &amp;#91;&amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :admin&amp;#41;&amp;#41;
             &amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :root&amp;#41;&amp;#41;&amp;#93;}

    {:uri &amp;quot;/super-secret&amp;#42;&amp;quot;
     :rules {:every &amp;#91;&amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :admin&amp;#41;&amp;#41;
                     &amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :root&amp;#41;&amp;#41;&amp;#93;
             :any   &amp;#91;&amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :zeus&amp;#41;&amp;#41;
                     &amp;#40;fn &amp;#91;req&amp;#93; &amp;#40;session/get :athena&amp;#41;&amp;#41;&amp;#93;}}
&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first rule will be activated for any handler that's marked as restricted. This means that all of the restricted pages will redirect to &lt;code&gt;&amp;quot;/&amp;quot;&lt;/code&gt; if there is no user in the session.&lt;/p&gt;&lt;p&gt;The second rule will only activate if the request URI matches &lt;code&gt;&amp;quot;/restricted&amp;quot;&lt;/code&gt; and will be ignored for other URIs. The &lt;code&gt;&amp;quot;/restricted&amp;quot;&lt;/code&gt; route will redirect to the &lt;code&gt;&amp;quot;/denied1&amp;quot;&lt;/code&gt; URI.&lt;/p&gt;&lt;p&gt;The third rule will match any requests matching the &lt;code&gt;&amp;quot;/users/&amp;quot;&lt;/code&gt; URI pattern. These requests will be redirected to the &lt;code&gt;&amp;quot;/denied2&amp;quot;&lt;/code&gt; URI and the URI of the request will be logged.&lt;/p&gt;&lt;p&gt;The next rule group matches both the &lt;code&gt;&amp;quot;/admin&amp;#42;&amp;quot;&lt;/code&gt; and the &lt;code&gt;&amp;quot;/config&amp;#42;&amp;quot;&lt;/code&gt; patterns and required that either the &lt;code&gt;:admin&lt;/code&gt; or the &lt;code&gt;:root&lt;/code&gt; keys are set in the session in addition to the &lt;code&gt;:user&lt;/code&gt; key specified by the global rule.&lt;/p&gt;&lt;p&gt;Next, we have a rule group that uses &lt;code&gt;:on-fail&lt;/code&gt; function that can provide its own handler instead of doing a redirect. It requires that both  the &lt;code&gt;:admin&lt;/code&gt; or the &lt;code&gt;:root&lt;/code&gt; keys are set in the session.&lt;/p&gt;&lt;p&gt;Finally, we have a group that uses a mix of &lt;code&gt;:every&lt;/code&gt; and &lt;code&gt;:any&lt;/code&gt; keys to specify its rules.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;access-rule&lt;/code&gt; macro has been removed in favor of specifying rule groups directly in the handler. This makes it easier to see how all the rules are defined and what routes each set of rules affects.&lt;/p&gt;&lt;p&gt;With this new approach we can create independent rule groups for specific URI patterns as well as easily specify generic rules that affect all restricted handlers.&lt;/p&gt;&lt;p&gt;I found the new rule managing scheme to work better for my projects. I'd be interested on getting feedback whether it works for others as well and I'm always open to suggestions for improvements. :)&lt;/p&gt;</description><pubDate>Wed, 12 Jun 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-05-25-what-s-new-in-lib-noir.html</guid><link>https://yogthos.net/posts/2013-05-25-what-s-new-in-lib-noir.html</link><title>what's new in lib-noir</title><description>&lt;p&gt;It's been nearly a year since &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt; was split out into a stand-alone library. During this time the work on it has continued at a steady pace. There have been numerous bug fixes and many new features have been added to the library.&lt;/p&gt;&lt;p&gt;Many of these come either from user suggestions or contributions. So, if there is something that you'd like to see improved don't hesitate to submit an issue or make a pull request.&lt;/p&gt;&lt;p&gt;In this post I'd like to highlight some of the major new features that have been recently added.&lt;/p&gt;&lt;h3 id="middleware"&gt;Middleware&lt;/h3&gt;&lt;p&gt;The &lt;code&gt;app-handler&lt;/code&gt; in &lt;code&gt;noir.util.middleware&lt;/code&gt; now accepts optional&lt;code&gt;:middleware&lt;/code&gt; and &lt;code&gt;:access-rules&lt;/code&gt; parameters.&lt;/p&gt;&lt;p&gt;Since the outer middleware is evaluated first, if you wrap the &lt;code&gt;app-handler&lt;/code&gt; in custom middleware it will execute before any of the standard middleware is executed. This is a problem if you wish to get access to things like the session, eg:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn log-user-in-session &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req&amp;#93;
    &amp;#40;timbre/info &amp;#40;session/get :user&amp;#41;&amp;#41;
    &amp;#40;handler req&amp;#41;&amp;#41;&amp;#41;

&amp;#40;def app &amp;#40;-&amp;gt; &amp;#40;middleware/app-handler all-routes&amp;#41;
             log-user-in-session&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If we try to run our app with the above handler we'll get the following exception:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;java.lang.ClassCastException: clojure.lang.Var$Unbound cannot be cast to java.util.concurrent.Future
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This happens due to the fact that &lt;code&gt;noir.session&lt;/code&gt; uses the &lt;code&gt;&amp;#42;noir-session&amp;#42;&lt;/code&gt; dynamic variable to keep track of the session. This variable is bound by the &lt;code&gt;wrap-noir-session&lt;/code&gt; middleware. Since the &lt;code&gt;log-user-in-session&lt;/code&gt; executes before it, the session is not yet bound.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;:middleware&lt;/code&gt; key allows specifying a vector containing custom middleware to wrap the handler before the standard middleware:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def app &amp;#40;middleware/app-handler all-routes
          :middleware &amp;#91;log-user-in-session&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, the &lt;code&gt;log-user-in-session&lt;/code&gt; will be called after the &lt;code&gt;wrap-noir-session&lt;/code&gt; is called and work as expected.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;:access-rules&lt;/code&gt; key allows specifying the access rules for the &lt;code&gt;wrap-access-rules&lt;/code&gt; middleware. Each set of rules should be specified as a vector with the contents matching the &lt;code&gt;wrap-access-rules&lt;/code&gt; arguments:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn private-pages &amp;#91;method url params&amp;#93;    
    &amp;#40;session/get :user-id&amp;#41;&amp;#41;

&amp;#40;def app &amp;#40;middleware/app-handler all-routes 
          :access-rules
          &amp;#91;&amp;#91;{:redirect &amp;quot;/unauthorized&amp;quot;} private-pages&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;There's also a new middleware wrapper called &lt;code&gt;wrap-rewrites&lt;/code&gt; that allows rewriting URIs based on regex. &lt;/p&gt;&lt;p&gt;The rewrite rules should be supplied as pairs of the regex and the string the matching URL should be rewritten with. The first regex that matches the request's URI will cause it to be replaced with its corresponding string before calling the wrapped handler:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;wrap-rewrites handler #&amp;quot;/foo&amp;quot; &amp;quot;/bar&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Above, all occurances of  the&lt;code&gt;/foo&lt;/code&gt; URI will be replaced with &lt;code&gt;/bar&lt;/code&gt;.&lt;/p&gt;&lt;h3 id="routes"&gt;Routes&lt;/h3&gt;&lt;p&gt;There's now a &lt;code&gt;noir.util.route/def-restricted-routes&lt;/code&gt; macro for creating groups of restricted routes. Where before you had to do something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defroutes private-routes
  &amp;#40;restricted GET &amp;quot;/route1&amp;quot; &amp;#91;&amp;#93; handler1&amp;#41;
  &amp;#40;restricted GET &amp;quot;/route2&amp;quot; &amp;#91;&amp;#93; handler2&amp;#41;
  &amp;#40;restricted GET &amp;quot;/route3&amp;quot; &amp;#91;&amp;#93; handler3&amp;#41;
  &amp;#40;restricted GET &amp;quot;/route4&amp;quot; &amp;#91;&amp;#93; handler4&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;you can now simply do:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def-restricted-routes private-routes
  &amp;#40;GET &amp;quot;/route1&amp;quot; &amp;#91;&amp;#93; handler1&amp;#41;
  &amp;#40;GET &amp;quot;/route2&amp;quot; &amp;#91;&amp;#93; handler2&amp;#41;
  &amp;#40;GET &amp;quot;/route3&amp;quot; &amp;#91;&amp;#93; handler3&amp;#41;
  &amp;#40;GET &amp;quot;/route4&amp;quot; &amp;#91;&amp;#93; handler4&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The macro will automatically mark all the routes as restricted for you. &lt;/p&gt;&lt;p&gt;Finally, the access rules used to control the &lt;code&gt;restricted&lt;/code&gt; routes are more flexible now as well. The redirect target can now point to a function as well as a string, eg:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def app &amp;#40;middleware/app-handler all-routes 
          :access-rules
          &amp;#91;&amp;#91;{:redirect 
             &amp;#40;fn &amp;#91;&amp;#93; 
              &amp;#40;println &amp;quot;redirecting&amp;quot;&amp;#41; &amp;quot;/unauthorized&amp;quot;&amp;#41;} 
             private-pages&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As always, &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; provides the latest &lt;code&gt;lib-noir&lt;/code&gt;, so all the new features are available there as well.&lt;/p&gt;</description><pubDate>Sat, 25 May 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-05-22-Packaging-a-Clojure-ClojureScript-jar.html</guid><link>https://yogthos.net/posts/2013-05-22-Packaging-a-Clojure-ClojureScript-jar.html</link><title>Packaging a Clojure+ClojureScript jar</title><description>&lt;p&gt;I maintain a Clojure Markdown parser library called &lt;a href='https://github.com/yogthos/markdown-clj'&gt;markdown-clj&lt;/a&gt;. I originally wrote it because I was curious to see just how concise a Clojure Markdown parser would be. Turns out that it's pretty concise. :)&lt;/p&gt;&lt;p&gt;Then I saw &lt;a href='http://briancarper.net/blog/415/clojure-and-markdown-and-javascript-and-java-and'&gt;a post&lt;/a&gt; from Brian Carper that highlighted a problem with having different Markdown parsers on the client and the server.&lt;/p&gt;&lt;p&gt;Since Markdown specification is somewhat loose, most implementations interpret it differently. This means that if you're rendering a preview on the client using a JavaScript library and using a different library, such as &lt;a href='https://github.com/sirthias/pegdown'&gt;pegdown&lt;/a&gt;, to render it on the server you may get some surprises.&lt;/p&gt;&lt;p&gt;Since my library was already written in pure Clojure I figured it wouldn't be difficult to cross-compile it to ClojureScript as well.&lt;/p&gt;&lt;p&gt;That turned out to be very easy to do. I split out the element transformers into a separate namespace that's shared between Clojure and ClojureScript cores. However, for the longest time I only packaged it for distribution as a Clojure library.&lt;/p&gt;&lt;p&gt;I finally had a bit of free time to look at ClojureScript packaging over the weekend and I'm happy to report that the dependency now works for both Clojure and ClojureScript out of the box.&lt;/p&gt;&lt;p&gt;While pure ClojureScript libraries compile without any extra work, I found a few gotchas that are specific to cross-compiling. &lt;/p&gt;&lt;p&gt;If you have a project that contains both Clojure and ClojureScript code in it, then &lt;strong&gt;only&lt;/strong&gt; the &lt;code&gt;clj&lt;/code&gt; files will be packaged in the jar by default. After some reading of the &lt;a href='https://github.com/emezeske/lein-cljsbuild'&gt;lein-cljsbuild&lt;/a&gt; docs I found the solution. &lt;/p&gt;&lt;p&gt;Here's what I ended up doing to get &lt;code&gt;cljs&lt;/code&gt; namespaces to be packaged along with the &lt;code&gt;clj&lt;/code&gt; namespaces:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;:cljsbuild
{:crossovers &amp;#91;markdown.transformers&amp;#93;
  :crossover-path &amp;quot;crossover&amp;quot;
  :crossover-jar true        
  :builds {:main
           {:source-paths &amp;#91;&amp;quot;src-cljs&amp;quot;&amp;#93;
            :jar true
            :compiler {:output-to &amp;quot;js/markdown.js&amp;quot;
                       :optimizations :advanced
                       :pretty-print false}}
           :dev 
           {:compiler {:optimizations :whitespace
                       :pretty-print true}}}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I specify the &lt;code&gt;:crossover-path&lt;/code&gt;, note that this path has to be different from your &lt;code&gt;:source-paths&lt;/code&gt; or the files there will be overwritten.&lt;/p&gt;&lt;p&gt;Next, I added the &lt;code&gt;:corssover-jar true&lt;/code&gt; to indicate that I wish the crossover namespaces to appear in the resulting jar.&lt;/p&gt;&lt;p&gt;I also added &lt;code&gt;:jar true&lt;/code&gt; to the &lt;code&gt;:main&lt;/code&gt; section of the &lt;code&gt;:builds&lt;/code&gt;. This is needed to include the namespaces in the &lt;code&gt;src-cljs&lt;/code&gt; source directory.&lt;/p&gt;&lt;p&gt;Finally, you also need to include &lt;code&gt;:clojurescript? true&lt;/code&gt; in &lt;code&gt;project.clj&lt;/code&gt; to indicate that the project contains ClojureScript sources. Here's the complete project file that I'm using:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject markdown-clj &amp;quot;0.9.25&amp;quot;
  :clojurescript? true
  :description &amp;quot;Markdown parser&amp;quot;
   :url &amp;quot;https://github.com/yogthos/markdown-clj&amp;quot;
   :license {:name &amp;quot;Eclipse Public License&amp;quot;
             :url &amp;quot;http://www.eclipse.org/legal/epl-v10.html&amp;quot;}
   :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.5.1&amp;quot;&amp;#93;
                  &amp;#91;criterium &amp;quot;0.3.1&amp;quot; :scope &amp;quot;test&amp;quot;&amp;#93;&amp;#93;
   :plugins &amp;#91;&amp;#91;lein-cljsbuild &amp;quot;0.3.2&amp;quot;&amp;#93;&amp;#93;
   :hooks &amp;#91;leiningen.cljsbuild&amp;#93;
   :test-selectors {:default &amp;#40;complement :benchmark&amp;#41;
                    :benchmark :benchmark
                    :all &amp;#40;constantly true&amp;#41;}
   
   :cljsbuild
   {:crossovers &amp;#91;markdown.transformers&amp;#93;
    :crossover-path &amp;quot;crossover&amp;quot;
    :crossover-jar true        
    :builds {:main
             {:source-paths &amp;#91;&amp;quot;src-cljs&amp;quot;&amp;#93;
              :jar true
              :compiler {:output-to &amp;quot;js/markdown.js&amp;quot;
                         :optimizations :advanced
                         :pretty-print false}}
             :dev 
             {:compiler {:optimizations :whitespace
                         :pretty-print true}}}}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The resulting jar will contain all your &lt;code&gt;clj&lt;/code&gt; and &lt;code&gt;cljs&lt;/code&gt; files along with the crossover namespaces.&lt;/p&gt;&lt;p&gt;For me, being able to manage dependencies using Leiningen is a definite killer feature when it comes to ClojureScript.&lt;/p&gt;</description><pubDate>Wed, 22 May 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-04-24-Clojure-Data-Analysis-Cookbook-Review.html</guid><link>https://yogthos.net/posts/2013-04-24-Clojure-Data-Analysis-Cookbook-Review.html</link><title>Clojure Data Analysis Cookbook Review</title><description>&lt;p&gt;I was recently asked to review the &lt;a href='http://www.packtpub.com/clojure-data-analysis-cookbook/book'&gt;Clojure Data Analysis Cookbook&lt;/a&gt;. Data analysis happens to one of the major niches where Clojure has been gaining popularity. However, the documentation on the subject is far from focused. &lt;/p&gt;&lt;p&gt;The book provides a collection of recipes for accomplishing common tasks associated with analyzing different types of data sets. It starts out by showing how to read data from a variety of sources such as JSON, CSV, and JDBC. The next chapter provides a number of examples of how to sanitize the collected data and sample large data sets. After covering loading and sanitizing the data, the book discusses a number of different strategies for processing it.&lt;/p&gt;&lt;p&gt;Some of the highlights include using the Clojure STM, parallel processing of the data, including useful tricks for partitioning, using &lt;a href='http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html'&gt;reducers&lt;/a&gt;, and distributed processing with Hadoop and Casalog.&lt;/p&gt;&lt;p&gt;I found the sections on handling large amounts of data particularly interesting. Often times, it's easy to come up with a solution that works for a small data set, but doesn't scale to handle large amounts of data. One of the techniques the book discusses is the use of lazy sequences. Another example is using heuristics to decide how to partition large data sets data sets effectively.&lt;/p&gt;&lt;p&gt;The book closes with a chapter dealing with the presentation the processed data. First, it covers using Incanter charts and then shows how to display the results in the browser with ClojureScript and &lt;a href='http://nvd3.org/'&gt;NVD3&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;For the most part, the book is very much example oriented. The examples are accompanied by explantation of how they all fit together. If you're like me and like to get hands on experience then I think you'll like the style of the book.&lt;/p&gt;&lt;p&gt;The examples are short in size and easy to understand. I found that the best way to work through the book was by following along with a REPL.&lt;/p&gt;&lt;p&gt;The book also introduces the reader to a number of libraries. Some, such as &lt;a href='http://incanter.org/'&gt;Incanter&lt;/a&gt; are well known, while others like &lt;a href='https://github.com/protoflex/parse-ez'&gt;parse-ez&lt;/a&gt; less so. In my experience, the documentation for many Clojure libraries is often lacking. The recipes in the book serve as a good reference for how to make the most of the tools available.&lt;/p&gt;&lt;p&gt;I would say one missed opportunity in the book is that the examples don't seem to build on each other. You'll see many examples of doing specific tasks, but they will tend to be self contained and don't build up to anything more substantial. &lt;/p&gt;&lt;p&gt;I suspect this was done in order to keep content accessible so that the reader can look at any section without having to have read the others. Conversely, don't expect to see examples of how to structure your projects and build applications end to end.&lt;/p&gt;&lt;p&gt;Overall, I would say this book is aimed at somebody who is already comfortable using Clojure and would like to learn some of the more advanced techinques for working with data processing and analysis. If you're thinking of using Clojure for analyzing your data sets this book will likely save you a lot of time and serve as a handy reference down the road.&lt;/p&gt;</description><pubDate>Wed, 24 Apr 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-04-09-Introducing-cljs-ajax.html</guid><link>https://yogthos.net/posts/2013-04-09-Introducing-cljs-ajax.html</link><title>Introducing cljs-ajax</title><description>&lt;p&gt;I recently started working on a project using ClojureScript and it's turning out to be a really good experience so far. I've been using &lt;a href='https://github.com/levand/domina'&gt;Domina&lt;/a&gt; and &lt;a href='https://github.com/Prismatic/dommy'&gt;Dommy&lt;/a&gt; for DOM manipulation and templating. Both libraries are very easy to use and provide all  the functionality needed for common operations.&lt;/p&gt;&lt;p&gt;Surprisingly, I didn't find any up to date libraries for handling Ajax. The only one I could find is &lt;a href='https://github.com/ibdknox/fetch'&gt;fetch&lt;/a&gt;. Unfortunately, it depends on Noir which is no longer maintained.&lt;/p&gt;&lt;p&gt;I ended up writing a wrapper for &lt;code&gt;goog.net.XhrIo&lt;/code&gt; called &lt;a href='https://github.com/yogthos/cljs-ajax'&gt;cljs-ajax&lt;/a&gt;. It provides an API similar to &lt;a href='https://github.com/dakrone/clj-http'&gt;clj-http&lt;/a&gt; and handles all the nitty gritty details for you.&lt;/p&gt;&lt;p&gt;Currently, the API provides &lt;code&gt;ajax-request&lt;/code&gt;, &lt;code&gt;GET&lt;/code&gt;, and &lt;code&gt;PUT&lt;/code&gt; functions. The &lt;code&gt;ajax-request&lt;/code&gt; function accepts the following parameters:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;uri&lt;/code&gt; - the URI for the request&lt;/li&gt;&lt;li&gt;&lt;code&gt;method&lt;/code&gt; - a string representing the HTTP request type, eg: "PUT", "DELETE", etc.&lt;/li&gt;&lt;li&gt;&lt;code&gt;format&lt;/code&gt; - a keyword indicating the response format, can be either &lt;code&gt;:json&lt;/code&gt; or &lt;code&gt;:edn&lt;/code&gt;, defaults to &lt;code&gt;:edn&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;handler&lt;/code&gt; - success handler, a function that accepts the response as a single argument&lt;/li&gt;&lt;li&gt;&lt;code&gt;error-handler&lt;/code&gt; - error handler, a function that accepts a map representing the error with keys &lt;code&gt;:status&lt;/code&gt; and &lt;code&gt;:status-text&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;params&lt;/code&gt; - a map of params to be sent to the server&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt; are helper functions that accept a URI followed by a map of options containing any of the following keys:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;:handler&lt;/code&gt; - the handler function for successful operation should accept a single parameter which is the deserialized response&lt;/li&gt;&lt;li&gt;&lt;code&gt;:error-handler&lt;/code&gt; - the handler function for errors, should accept a map with keys &lt;code&gt;:status&lt;/code&gt; and &lt;code&gt;:status-text&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;:format&lt;/code&gt; - the format for the response &lt;code&gt;:edn&lt;/code&gt; or &lt;code&gt;:json&lt;/code&gt; defaults to &lt;code&gt;:edn&lt;/code&gt;&lt;/li&gt;&lt;li&gt;&lt;code&gt;:params&lt;/code&gt; - a map of parameters that will be sent with the request&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Here's some example usage:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns foo
 &amp;#40;:require &amp;#91;ajax.core :refer &amp;#91;GET POST&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn handler &amp;#91;response&amp;#93;
 &amp;#40;.log js/console &amp;#40;str response&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn error-handler &amp;#91;{:keys &amp;#91;status status-text&amp;#93;}&amp;#93;
 &amp;#40;.log js/console 
  &amp;#40;str &amp;quot;something bad happened: &amp;quot; status &amp;quot; &amp;quot; status-text&amp;#41;&amp;#41;&amp;#41;

&amp;#40;GET &amp;quot;/hello&amp;quot;&amp;#41;

&amp;#40;GET &amp;quot;/hello&amp;quot; {:handler handler
               :error-handler error-handler}&amp;#41;

&amp;#40;POST &amp;quot;/hello&amp;quot;&amp;#41;

&amp;#40;POST &amp;quot;/send-message&amp;quot; 
      {:params {:message &amp;quot;Hello World&amp;quot;
                :user    &amp;quot;Bob&amp;quot;}
      :handler handler
      :error-handler error-handler}&amp;#41;

&amp;#40;POST &amp;quot;/send-message&amp;quot; 
      {:params {:message &amp;quot;Hello World&amp;quot;
                :user    &amp;quot;Bob&amp;quot;}
      :handler handler
      :format :json
      :error-handler error-handler}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The latest version of Luminus comes packaged with a ClojureScript example when the &lt;code&gt;+cljs&lt;/code&gt; option is selected. Let's create a new project called &lt;code&gt;ajax-example&lt;/code&gt; and take a look at how it works:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus ajax-example +cljs
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;project.clj&lt;/code&gt; will contain the dependencies for Domina, Dommy, and cljs-ajax as well as a &lt;code&gt;cljsbuild&lt;/code&gt; configuration. The current version of cljsbuild references an old version of ClojureScript, so the latest version is also explicitly included as a dependency.&lt;/p&gt;&lt;p&gt;In order to use the ClojureScript from our page we'll first need to compile it. This is done by running &lt;code&gt;lein cljsbuild once&lt;/code&gt;. The resulting artifact will be placed under &lt;code&gt;resources/public/js/site.js&lt;/code&gt; as specified in the cljsbuild section of the project.&lt;/p&gt;&lt;p&gt;You'll notice that the build takes a while to run. Luckily, if we run it using &lt;code&gt;lein cljsbuild auto&lt;/code&gt; it will run much faster and any time we make changes to any of the ClojureScript namespaces they will trigger an incremental build.&lt;/p&gt;&lt;p&gt;Working with the auto build running is nearly as seamless as working with plain old JavaScript. You make a change in the source, save, and reload the page. The compilation step tends to take under a second, so the intermediate delay is barely noticeable.&lt;/p&gt;&lt;p&gt;Our project has a source directory called &lt;code&gt;src-cljs&lt;/code&gt; where ClojureScript namespaces live. It contains a file called &lt;code&gt;main.cljs&lt;/code&gt;. This example illustrates using GET and POST calls to interact with the server as well as rendering DOM elements. Let's take a look inside it:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns cljs-test.main
 &amp;#40;:require &amp;#91;ajax.core :refer &amp;#91;GET POST&amp;#93;&amp;#93;
           &amp;#91;domina :refer &amp;#91;value by-id destroy-children! append!&amp;#93;&amp;#93;
           &amp;#91;domina.events :refer &amp;#91;listen!&amp;#93;&amp;#93;
           &amp;#91;dommy.template :as template&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn render-message &amp;#91;{:keys &amp;#91;message user&amp;#93;}&amp;#93;
 &amp;#91;:li &amp;#91;:p {:id user} message &amp;quot; - &amp;quot; user&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn render-messages &amp;#91;messages&amp;#93;
 &amp;#40;let &amp;#91;messages-div &amp;#40;by-id &amp;quot;messages&amp;quot;&amp;#41;&amp;#93;
   &amp;#40;destroy-children! messages-div&amp;#41;
   &amp;#40;-&amp;gt;&amp;gt; messages
        &amp;#40;map render-message&amp;#41;
        &amp;#40;into &amp;#91;:ul&amp;#93;&amp;#41;
        template/node
        &amp;#40;append! messages-div&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn add-message &amp;#91;&amp;#95;&amp;#93;
 &amp;#40;POST &amp;quot;/add-message&amp;quot;
       {:params {:message &amp;#40;value &amp;#40;by-id &amp;quot;message&amp;quot;&amp;#41;&amp;#41;
                 :user    &amp;#40;value &amp;#40;by-id &amp;quot;user&amp;quot;&amp;#41;&amp;#41;}
        :handler render-messages}&amp;#41;&amp;#41;

&amp;#40;defn &amp;#94;:export init &amp;#91;&amp;#93;
 &amp;#40;GET &amp;quot;/messages&amp;quot; {:handler render-messages}&amp;#41;
 &amp;#40;listen! &amp;#40;by-id &amp;quot;send&amp;quot;&amp;#41;
          :click add-message&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here, we have a couple of functions to render the messages we receive from the server. The &lt;code&gt;render-message&lt;/code&gt; function accepts a map with the keys message and user and creates a list item. The &lt;code&gt;render-messages&lt;/code&gt; will create a list from the messages and render it using &lt;code&gt;template/node&lt;/code&gt; function. The rendered messages will be appended to the div with the id &lt;code&gt;messages&lt;/code&gt; using the &lt;code&gt;append!&lt;/code&gt; function.&lt;/p&gt;&lt;p&gt;Next, we have a function to add a a new message. It grabs the values from elements selected by their ids and sends them as params named message and user. The server responds with a list of current messages. So we use &lt;code&gt;render-messages&lt;/code&gt; as the response handler.&lt;/p&gt;&lt;p&gt;In our &lt;code&gt;init&lt;/code&gt; function, we send a GET request to grab the current messages, then we bind the &lt;code&gt;add-message&lt;/code&gt; function to the button with the id &lt;code&gt;send&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;On the server side we have a &lt;code&gt;ajax-example.routes.cljsexample&lt;/code&gt; namespace. It provides the routes to render the page and handle the &lt;code&gt;/messages&lt;/code&gt; and &lt;code&gt;/add-message&lt;/code&gt; operations.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns ajax-example.routes.cljsexample
 &amp;#40;:require &amp;#91;compojure.core :refer :all&amp;#93;
           &amp;#91;noir.response :as response&amp;#93;
           &amp;#91;ajax-example.views.layout :as layout&amp;#93;&amp;#41;&amp;#41;

&amp;#40;def messages
 &amp;#40;atom
   &amp;#91;{:message &amp;quot;Hello world&amp;quot;
     :user    &amp;quot;Foo&amp;quot;}
    {:message &amp;quot;Ajax is fun&amp;quot;
     :user    &amp;quot;Bar&amp;quot;}&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defroutes cljs-routes
 &amp;#40;GET &amp;quot;/cljsexample&amp;quot; &amp;#91;&amp;#93; &amp;#40;layout/render &amp;quot;cljsexample.html&amp;quot;&amp;#41;&amp;#41;
 &amp;#40;GET &amp;quot;/messages&amp;quot; &amp;#91;&amp;#93; &amp;#40;response/edn @messages&amp;#41;&amp;#41;
 &amp;#40;POST &amp;quot;/add-message&amp;quot; &amp;#91;message user&amp;#93;
       &amp;#40;response/edn
         &amp;#40;swap! messages conj {:message message :user user}&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, the routes simply return EDN responses to the client. Finally, we have the template for the actual example page, that looks as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;{% extends &amp;quot;cljs&amp;#95;test/views/templates/base.html&amp;quot; %}


{% block content %}

&amp;lt;br/&amp;gt;
&amp;lt;div id=&amp;quot;messages&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;textarea id=&amp;quot;message&amp;quot;&amp;gt;&amp;lt;/textarea&amp;gt;
&amp;lt;br/&amp;gt;
&amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;user&amp;quot;&amp;gt;&amp;lt;/input&amp;gt;
&amp;lt;br/&amp;gt;
&amp;lt;button id=&amp;quot;send&amp;quot;&amp;gt;add message&amp;lt;/button&amp;gt;

&amp;lt;!--  scripts --&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;js/site.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
	cljs&amp;#95;test.main.init&amp;#40;&amp;#41;;
&amp;lt;/script&amp;gt;

{% endblock %}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The page references the &lt;code&gt;site.js&lt;/code&gt; script that will be output by the compiler and calls the &lt;code&gt;init&lt;/code&gt; function that we saw above.&lt;/p&gt;&lt;p&gt;Overall, I feel that ClojureScript is rapidly becoming a viable alternative to using JavaScript on the client. There are still some rough edges, but most things work out of the box and you get many of the same benefits associated with using Clojure on the server.&lt;/p&gt;</description><pubDate>Tue, 09 Apr 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-03-23-a-book-is-coming.html</guid><link>https://yogthos.net/posts/2013-03-23-a-book-is-coming.html</link><title>a book is coming</title><description>&lt;p&gt;First of all, I'd like to thank all those who've helped with Luminus. Since the original release on Clojars at the end of December there's been over &lt;a href='https://clojars.org/luminus/lein-template'&gt;700 downloads&lt;/a&gt;, and the framework site has over 3,500 unique visits!&lt;/p&gt;&lt;p&gt;There's also been many contributions for improved documentation, template fixes, and lib-noir improvements. I'm really thankful for all the help improving the framework and moving it forward. I'd especially like to thank &lt;a href='http://about.me/edtsech'&gt;Ed Tsech&lt;/a&gt;, who's been toiling on it with me for the last few months. :)&lt;/p&gt;&lt;p&gt;I'm really glad to be able to contribute to popularizing the language and making it more accessible. On that note I have some exciting news. I've recently got signed by the &lt;a href='http://pragprog.com/'&gt;The Pragmatic Programmers&lt;/a&gt; to write a book on web development using Clojure.&lt;/p&gt;&lt;p&gt;There is a number of books discussing the fundamentals of Clojure as a language. However, none of the books focus on applying these fundamentals to building real-world solutions. Respondents of the &lt;a href='http://cemerick.com/2012/07/19/2012-state-of-clojure-survey/'&gt;2012 State of Clojure survey&lt;/a&gt; indicated that there still exists a gap in traditional documentation. Specifically, an interest in current tools, libraries, and best practices is not being met. It is my goal to help fill this gap.&lt;/p&gt;&lt;p&gt;I will provide an overview of Clojure as a web development platform, highlighting exactly what makes it so effective. The book will take a tutorial-focused approach to building a production-ready web application from conception to deployment.&lt;/p&gt;&lt;p&gt;The target audience is anyone interested in using Clojure as a web development platform. This includes: those who are currently using the JVM for development; Ruby and Python users who would like to take advantage of the breadth of features and libraries offered by the JVM; and readers simply interested in learning how to develop web applications using Clojure.&lt;/p&gt;&lt;p&gt;I'm quite thrilled about this project and I hope to write the book I wish I had when I spent countless hours googling for tutorials and examples. :)&lt;/p&gt;</description><pubDate>Sat, 23 Mar 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-03-10-New-Templating-Engine-in-Luminus.html</guid><link>https://yogthos.net/posts/2013-03-10-New-Templating-Engine-in-Luminus.html</link><title>New Templating Engine in Luminus</title><description>&lt;p&gt;I'm happy to announce that &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; now defaults to using &lt;a href='https://github.com/danlarkin/clabango'&gt;Clabango&lt;/a&gt; for HTML templating instead of &lt;a href='https://github.com/weavejester/hiccup'&gt;Hiccup&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I'd like to explain some of the reasoning behind this decision. The primary drive behind Luminus is to make Clojure web development more accessible. This means that the barrier to entry for those who are new to the language should be as low as possible.&lt;/p&gt;&lt;p&gt;Since Clabango is based on the &lt;a href='https://docs.djangoproject.com/en/1.10/intro/overview/#design-your-templates'&gt;Django templates&lt;/a&gt;, it's immediately familiar to anybody who's done templating with other frameworks such as Django, Rails, or JSP. This also makes it easier to migrate exiting sites to use Luminus.&lt;/p&gt;&lt;p&gt;Because the templates are written in plain HTML it's easy to work with designers and other people who aren't versed in Clojure.&lt;/p&gt;&lt;p&gt;Finally, Clabango enforces the separation between the application logic and the presentation. When using Hiccup it's for one to start bleeding into the other if you're not careful.&lt;/p&gt;&lt;p&gt;However, if you are a fan of Hiccup there's nothing to worry about.  Everything will work as it did before if you use the &lt;code&gt;+hiccup&lt;/code&gt; flag when creating the application.&lt;/p&gt;&lt;p&gt;As always feedback and suggestions are most welcome. :)&lt;/p&gt;</description><pubDate>Sun, 10 Mar 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-03-02-New-kid-on-the-templating-block.html</guid><link>https://yogthos.net/posts/2013-03-02-New-kid-on-the-templating-block.html</link><title>New kid on the templating block</title><description>&lt;h2 id="update:&amp;#95;&lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt;&amp;#95;is&amp;#95;currently&amp;#95;the&amp;#95;recommended&amp;#95;django&amp;#95;style&amp;#95;templating&amp;#95;engine"&gt;Update: &lt;a href='https://github.com/yogthos/Selmer'&gt;Selmer&lt;/a&gt; is currently the recommended Django style templating engine&lt;/h2&gt;&lt;p&gt;As you may know, there are a few Clojure templating engines floating around. The two most popular ones are probably &lt;a href='https://github.com/weavejester/hiccup'&gt;Hiccup&lt;/a&gt; and &lt;a href='https://github.com/cgrand/enlive'&gt;Enlive&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Hiccup is a nice and simple templating engine. Unfortunately, its biggest advantage is also it's greatest weakness. Since Hiccup templates are written using Clojure data structures, they're simply part of your regular code.&lt;/p&gt;&lt;p&gt;This makes the templates inaccessible to people not versed in Clojure. For example, if you're working with a designer, you can't just give them your template to work with.&lt;/p&gt;&lt;p&gt;Another issue is that it makes it easy for your frontend and backend logic to bleed into each other if you're not careful. Finally, you have to redeploy your site any time you wish to make a change to the layout.&lt;/p&gt;&lt;p&gt;Enlive avoids these problems by using a more traditional approach and using plain HTML markup for its templates. The problem with Enlive lies in its complexity. This spawned &lt;a href='https://github.com/Raynes/laser'&gt;Laser&lt;/a&gt;, which also allows using pure HTML without any additional markup for its templates. In the words of the author:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Enlive does its job and is the precursor to the way laser does things. However, it is very large and (arguably?) complex compared to laser. laser strives to be as simple as possible. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;If you haven't already checked out Laser I certainly urge you to do so!&lt;/p&gt;&lt;p&gt;However, the engine I'd like to focus on in this post is &lt;a href='https://github.com/danlarkin/clabango'&gt;Clabango&lt;/a&gt;. It's modeled after Django's templating library and I found that it clicked with me immediately. &lt;/p&gt;&lt;p&gt;Let's take a look at how to convert the example &lt;a href='http://www.luminusweb.net/docs/guestbook.md'&gt;guestbook application&lt;/a&gt; from Luminus to use Clabango instead of Hiccup.&lt;/p&gt;&lt;p&gt;We'll first create the project with support for H2 embedded DB by running:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;lein new luminus guestbook +h2
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll then open up our &lt;code&gt;project.clj&lt;/code&gt; and add the Clabango &lt;code&gt;&amp;#91;clabango &amp;quot;0.5&amp;quot;&amp;#93;&lt;/code&gt; dependency it.&lt;/p&gt;&lt;p&gt;Next, we'll create a &lt;code&gt;templates&lt;/code&gt; folder under resources/public. This is where all the Clabango templates will live.&lt;/p&gt;&lt;p&gt;Clabango provides two way to load templates using the &lt;code&gt;clabango.parser&lt;/code&gt; namespace. We can either use &lt;code&gt;render-file&lt;/code&gt; function to load a template from a file or &lt;code&gt;render&lt;/code&gt; to load it from a string.&lt;/p&gt;&lt;p&gt;These functions take two parameters, the template source and a map containing the items that will be populated in the template when it's compiled.&lt;/p&gt;&lt;p&gt;For example, if we had a template such as:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;h2&amp;gt;Hello {{user}}&amp;lt;/h2&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We could then render it by calling &lt;code&gt;render&lt;/code&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;render &amp;quot;&amp;lt;h2&amp;gt;Hello {{user}}&amp;lt;/h2&amp;gt;&amp;quot; {:user &amp;quot;John&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Clabango will then replace every occurance of &lt;code&gt;{{user}}&lt;/code&gt; with &lt;code&gt;John&lt;/code&gt; instead. In case &lt;code&gt;user&lt;/code&gt; happens to be a map, we can access its keys using the dot notation:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;h2&amp;gt;Hello {{user.last}}&amp;quot;, &amp;quot; {{user.first}}&amp;lt;/h2&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The  templates provide support for some other useful things like filters, tag definitions, and template inheritance. However, we won't worry about any of that right now.&lt;/p&gt;&lt;p&gt;Let's take a look how to load up the templates using the &lt;code&gt;render&lt;/code&gt; function. We won't use &lt;code&gt;render-file&lt;/code&gt; since it looks for resources relative to the &lt;code&gt;src&lt;/code&gt; folder. We'll use &lt;code&gt;lib-noir.io/slurp-resource&lt;/code&gt; to load our templates from the &lt;code&gt;public&lt;/code&gt; folder instead. We'll create a helper in our &lt;code&gt;guestbook.util&lt;/code&gt; namespace to do that:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.util  
  &amp;#40;:require ...
            &amp;#91;clabango.parser :as parser&amp;#93;&amp;#41;&amp;#41;


&amp;#40;defn render &amp;#91;template params&amp;#93;
  &amp;#40;parser/render &amp;#40;io/slurp-resource template&amp;#41; params&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that out of the way, let's create the model for our application. We'll open up the &lt;code&gt;guestboook.models.schema&lt;/code&gt; namespace and replace &lt;code&gt;create-users-table&lt;/code&gt; with  &lt;code&gt;create-guestbook&lt;/code&gt; table:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-guestbook-table &amp;#91;&amp;#93;
  &amp;#40;sql/with-connection
    db-spec
    &amp;#40;sql/create-table
      :guestbook
      &amp;#91;:id &amp;quot;INTEGER PRIMARY KEY AUTO&amp;#95;INCREMENT&amp;quot;&amp;#93;
      &amp;#91;:timestamp :timestamp&amp;#93;
      &amp;#91;:name &amp;quot;varchar&amp;#40;30&amp;#41;&amp;quot;&amp;#93;
      &amp;#91;:message &amp;quot;varchar&amp;#40;200&amp;#41;&amp;quot;&amp;#93;&amp;#41;
    &amp;#40;sql/do-commands
      &amp;quot;CREATE INDEX timestamp&amp;#95;index ON guestbook &amp;#40;timestamp&amp;#41;&amp;quot;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;then update &lt;code&gt;create-tables&lt;/code&gt; to call it instead:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-tables
  &amp;quot;creates the database tables used by the application&amp;quot;
  &amp;#91;&amp;#93;
  &amp;#40;create-guestbook-table&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We'll also update the &lt;code&gt;init&lt;/code&gt; function in the &lt;code&gt;guestbook.handler&lt;/code&gt; to call &lt;code&gt;create-tables&lt;/code&gt; if the database isn't already initialized:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn init &amp;#91;&amp;#93;
  &amp;#40;if-not &amp;#40;schema/initialized?&amp;#41; &amp;#40;schema/create-tables&amp;#41;&amp;#41;
  &amp;#40;println &amp;quot;guestbook started successfully...&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next, let's open up the &lt;code&gt;guestbook.models.db&lt;/code&gt; namespace and replace the code to create and retrieve users with the code to save and load messages:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns guestbook.models.db
  &amp;#40;:use korma.core
        &amp;#91;korma.db :only &amp;#40;defdb&amp;#41;&amp;#93;&amp;#41;
  &amp;#40;:require &amp;#91;guestbook.models.schema :as schema&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defdb db schema/db-spec&amp;#41;

&amp;#40;defentity guestbook&amp;#41;

&amp;#40;defn save-message
  &amp;#91;name message&amp;#93;
  &amp;#40;insert guestbook 
          &amp;#40;values {:name name
                   :message message
                   :timestamp &amp;#40;new java.util.Date&amp;#41;}&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn get-messages &amp;#91;&amp;#93;
  &amp;#40;select guestbook&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can test that everything works by calling &lt;code&gt;save-message&lt;/code&gt; from the REPL to create some messages and then calling &lt;code&gt;get-messages&lt;/code&gt; to see that they're retrieved correctly. If everything works as expected then we're ready to take a look at making our pages. &lt;/p&gt;&lt;p&gt;First, let's create a template for the home page. We'll do this by making a &lt;code&gt;welcome.html&lt;/code&gt; file under the &lt;code&gt;resources/public/templates&lt;/code&gt; folder.&lt;/p&gt;&lt;p&gt;Here is where we finally get to see Clabango in action. We'll first use it to iterate the messages and create a list from them:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;ul&amp;gt;
{% for item in messages %}
  &amp;lt;li&amp;gt; 
      &amp;lt;blockquote&amp;gt;{{item.message}}&amp;lt;/blockquote&amp;gt;
      &amp;lt;p&amp;gt; - {{item.name}}&amp;lt;/p&amp;gt;
      &amp;lt;time&amp;gt;{{item.timestamp}}&amp;lt;/time&amp;gt;
  &amp;lt;/li&amp;gt;
{% endfor %}
&amp;lt;/ul&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see above, we use a &lt;code&gt;for&lt;/code&gt; iterator to walk the messages. Since each message is a map with the &lt;code&gt;message&lt;/code&gt;, &lt;code&gt;name,&lt;/code&gt; and &lt;code&gt;timestamp&lt;/code&gt; keys, we can access them by name.&lt;/p&gt;&lt;p&gt;Next, we'll add an error block for displaying errors that might be populated by the controller:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;{% if error %}
&amp;lt;p&amp;gt;{{error}}&amp;lt;/p&amp;gt;
{% endif %}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here we simply check if the error field was populated and display it. Finally, we'll create a form to allow users to submit their messages:&lt;/p&gt;&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;form action=&amp;quot;/&amp;quot; method=&amp;quot;POST&amp;quot;&amp;gt;
	&amp;lt;p&amp;gt;Name: &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;name&amp;quot; value={{name}}&amp;gt;&amp;lt;/p&amp;gt;
	&amp;lt;p&amp;gt;Message: &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;message&amp;quot; value={{message}}&amp;gt;&amp;lt;/p&amp;gt;
	&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;comment&amp;quot;&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This takes care of creating the template, now let's take a look at how we populate the templated fields in our controller.&lt;/p&gt;&lt;p&gt;We'll navigate to the &lt;code&gt;guestbook.routes.home&lt;/code&gt; namespace and update our home function to render the template when called:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn home-page &amp;#91;&amp;amp; &amp;#91;name message error&amp;#93;&amp;#93;
  &amp;#40;layout/common   
    &amp;#40;util/render &amp;quot;/templates/welcome.html&amp;quot; 
                 {:error    error
                  :name     name
                  :message  message
                  :messages &amp;#40;db/get-messages&amp;#41;}&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Above, we simply create a map with all the fields we wish to populate. Then we pass it along with the name of the template file to the &lt;code&gt;render&lt;/code&gt; function we defined earlier. Note that we can keep using the Hiccup layout to create the skeleton for the pages.  The rest of the code in the &lt;code&gt;home&lt;/code&gt; namespace stays the same as it was:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn save-message &amp;#91;name message&amp;#93;
  &amp;#40;cond
 
    &amp;#40;empty? name&amp;#41;
    &amp;#40;home-page name message &amp;quot;Some dummy who forgot to leave a name&amp;quot;&amp;#41;
 
    &amp;#40;empty? message&amp;#41;
    &amp;#40;home-page name message &amp;quot;Don't you have something to say?&amp;quot;&amp;#41;
 
    :else
    &amp;#40;do
      &amp;#40;db/save-message name message&amp;#41;
      &amp;#40;home-page&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defroutes home-routes
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93; &amp;#40;home-page&amp;#41;&amp;#41;
  &amp;#40;POST &amp;quot;/&amp;quot; &amp;#91;name message&amp;#93; &amp;#40;save-message name message&amp;#41;&amp;#41;
  &amp;#40;GET &amp;quot;/about&amp;quot; &amp;#91;&amp;#93; &amp;#40;about-page&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, Clabango is very simple to use and allows cleanly separating your markup from your controllers. I think it's an excellent addition to the ever growing Clojure toolbox.&lt;/p&gt;&lt;p&gt;Complete sources for this post are available &lt;a href='https://github.com/yogthos/clabango-guestbook'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;update&lt;/strong&gt;&lt;hr/&gt;&lt;/p&gt;&lt;p&gt;The approach I took with putting templates under the &lt;code&gt;resources&lt;/code&gt; folder will not work with template inheritance. So, you're best off simply using &lt;code&gt;render-file&lt;/code&gt; from Clabango and keeping your templates under the &lt;code&gt;src&lt;/code&gt; folder.&lt;/p&gt;</description><pubDate>Sat, 02 Mar 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-02-24-lib-noir-updates.html</guid><link>https://yogthos.net/posts/2013-02-24-lib-noir-updates.html</link><title>lib-noir updates</title><description>&lt;p&gt;I've had a bit of time to hack on lib-noir recently. Specifically, I decided to update the handling of access rules.&lt;/p&gt;&lt;p&gt;Previously, you could use &lt;code&gt;wrap-access-rules&lt;/code&gt; by passing one or more rule functions. Each function would accept a &lt;code&gt;method&lt;/code&gt;, &lt;code&gt;url&lt;/code&gt;, and &lt;code&gt;params&lt;/code&gt; and return a boolean indicating whether the rule is satisfied. Using these functions the wrapper would then decide wether the page should be displayed or if the client will be redirected to "/".&lt;/p&gt;&lt;p&gt;This was serviceable for doing some basic restrictions, like making pages private where a rule would check if a user was in the session:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn private-page &amp;#91;method url params&amp;#93;
  &amp;#40;session/get :user&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;However, it provided no way to redirect to a different URIs based on what rules failed. The update allows using multiple &lt;code&gt;wrap-access-rules&lt;/code&gt; wrappers each redirecting to its own redirect URI, as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;-&amp;gt; handler
  &amp;#40;wrap-access-rules rule1&amp;#41;
  &amp;#40;wrap-access-rules {:redirect &amp;quot;/unauthorized&amp;quot;} rule2 rule3&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first set of rules that fails will redirect to its redirect target, defaulting to "/" if none is provided. This way we can create rule groups each having different behaviours.&lt;/p&gt;&lt;p&gt;Another addition is the &lt;code&gt;noir.util.route/access-rule&lt;/code&gt; macro. The macro accepts a URI pattern and a condition. The condition is only checked if the URI of the page being checked matches the pattern.&lt;/p&gt;&lt;p&gt;The macro implicitly defines the &lt;code&gt;method&lt;/code&gt;, &lt;code&gt;url&lt;/code&gt;, and &lt;code&gt;params&lt;/code&gt; variables, so they can be used by the logic in the condition:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def private-pages
  &amp;#40;access-rule &amp;quot;/private/:id&amp;quot; &amp;#40;= &amp;#40;session/get :user&amp;#41; &amp;#40;first params&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The above rule will only be triggered for pages matching the "/private/:id" pattern. Hopefully, the new additions will make it easier to work with access rules in lib-noir. Complete documentation for the feature is available at &lt;a href='http://www.luminusweb.net/docs/routes.md'&gt;Luminus&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I'm also interested in hearing any feedback and suggestions regarding the current implementation. :)&lt;/p&gt;&lt;p&gt; &lt;strong&gt;update&lt;/strong&gt;&lt;hr/&gt;&lt;/p&gt;&lt;p&gt;After a bit of discussion with &lt;a href='https://github.com/edtsech'&gt;Ed Tsech&lt;/a&gt;, we decided that it would be better to make the parameters to the &lt;code&gt;access-rule&lt;/code&gt; explicit.&lt;/p&gt;&lt;p&gt;So, now instead of defining access-rule by simply providing the URL pattern and a condition, you would also pass the arguments vector with the method, url, and params:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def private-pages 
  &amp;#40;access-rule &amp;quot;/private/:id&amp;quot;  &amp;#91;&amp;#95; &amp;#95; params&amp;#93; 
    &amp;#40;= &amp;#40;session/get :user&amp;#41; &amp;#40;first params&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;While it's slightly more verbose, it's a lot less magical and there's no risk of the macro masking any variables in scope.&lt;/p&gt; </description><pubDate>Sun, 24 Feb 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-01-11-One-Ring-to-rule-them-all.html</guid><link>https://yogthos.net/posts/2013-01-11-One-Ring-to-rule-them-all.html</link><title>One Ring to rule them all</title><description>&lt;p&gt;The latest release of &lt;a href='http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; is no longer using a custom &lt;code&gt;server.clj&lt;/code&gt; which starts up Jetty using &lt;code&gt;run-jetty&lt;/code&gt;. Instead, it now relies on &lt;a href='https://github.com/weavejester/lein-ring'&gt;lein-ring&lt;/a&gt;, which in turns uses &lt;a href='https://github.com/weavejester/ring-server'&gt;ring-server&lt;/a&gt; to create the server.&lt;/p&gt;&lt;p&gt;Snice you no longer have a &lt;code&gt;-main&lt;/code&gt; in the project, you can't use &lt;code&gt;lein run&lt;/code&gt; to start it up for development. Instead, use &lt;code&gt;lein ring server&lt;/code&gt;, which will run Jetty for you.&lt;/p&gt;&lt;p&gt;If you need to start the server from within a REPL, then you can use the new &lt;code&gt;repl&lt;/code&gt; namespace, which provides &lt;code&gt;start-server&lt;/code&gt; and &lt;code&gt;stop-server&lt;/code&gt; functions.&lt;/p&gt;&lt;p&gt;When you're packaging the application as a standalone, you run would now run &lt;code&gt;lein ring uberjar&lt;/code&gt; instead of &lt;code&gt;lein uberjar&lt;/code&gt;. The &lt;code&gt;-main&lt;/code&gt; will be created by &lt;code&gt;lein-ring&lt;/code&gt; for you based on the handler specified in your &lt;code&gt;project.clj&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This means that all the configuration now lives under &lt;code&gt;project.clj&lt;/code&gt; and gets picked up consistently both in development and production modes.&lt;/p&gt;&lt;p&gt;The new changes also simplify Heroku deployment. You no longer need to specify &lt;code&gt;+heroku&lt;/code&gt;, the application will have all the necessary settings to run on Heroku out of the box.&lt;/p&gt;&lt;p&gt;Finally, I dropped support for Leiningen 1.x as it doesn't have support for profiles. There's no good reason to continue using it instead of upgrading to 2.x.&lt;/p&gt;</description><pubDate>Fri, 11 Jan 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2013-01-08-Luminus-progress-report.html</guid><link>https://yogthos.net/posts/2013-01-08-Luminus-progress-report.html</link><title>Luminus progress report</title><description>&lt;p&gt;The work on the framework continues steadily, and I've been integrating some of the feedback I got on the initial release.&lt;/p&gt;&lt;p&gt;I quickly discovered that simply using different files for template modules is insufficient. Many features need to update the &lt;code&gt;project.clj&lt;/code&gt; with dependencies or other options.&lt;/p&gt;&lt;p&gt;To deal with this I made a &lt;a href='https://github.com/yogthos/luminus-template/blob/master/src/leiningen/new/dependency_injector.clj'&gt;util&lt;/a&gt; which reads in the project file and injects dependencies, plugins and other options. Now each plugin can add its own project elements independently of others.&lt;/p&gt;&lt;p&gt;I'm considering taking the same approach to managing the layout as well. For example, if bootstrap support was selected, then its js/css would be included in &lt;code&gt;layout/common&lt;/code&gt;. Another use case would be to update the application routes if a module provided some new routes of its own.&lt;/p&gt;&lt;p&gt;I'd also like to highlight some of the additions to lib-noir. There are several new namespaces, such as &lt;code&gt;noir.util.cache&lt;/code&gt;, &lt;code&gt;noir.io&lt;/code&gt;, and &lt;code&gt;noir.util.route&lt;/code&gt;. Let's take a look at each of these in turn.&lt;/p&gt;&lt;h4 id="caching"&gt;Caching&lt;/h4&gt;&lt;p&gt;Basic caching is provided via &lt;code&gt;noir.util.cache&lt;/code&gt;. Cache allows wrapping any expr using &lt;code&gt;&amp;#40;cache id expr&amp;#41;&lt;/code&gt;, and the expr will only be evaluated if it's not found in the cache or if the cache has been invalidated. In case expr throws an exception the current cached value will be kept.&lt;/p&gt;&lt;p&gt;There are a couple of helpers for invalidating the cache. First, there's &lt;code&gt;invalidate-cache!&lt;/code&gt;, which takes a key and removes it from the cache. Then, there's &lt;code&gt;clear-cache!&lt;/code&gt; which removes all currently cached items.&lt;/p&gt;&lt;p&gt;It's also possible to set the timeout for cached items using &lt;code&gt;set-cache-timeout!&lt;/code&gt; and passing it a value in seconds. If an item remains in the cache longer than the timeout, the cache will attempt to refresh the value by running the expr associated with the item.&lt;/p&gt;&lt;p&gt;Finally, you can set the maximum size of the cache by calling &lt;code&gt;set-cache-size!&lt;/code&gt;, when the cache grows past the specified size, oldest items will be removed to make room for new ones.&lt;/p&gt;&lt;p&gt;I'm currently using the cache in &lt;a href='http://http://www.luminusweb.net/'&gt;Luminus&lt;/a&gt; for the documentation pages. Luminus fetches the documentation from github as markdown and then translates it to HTML. This is slow enough to be noticeable to the user. On top of that, github is known to have an occasional outage or two. :) &lt;/p&gt;&lt;p&gt;With this scheme, I can keep the docs up to date without having to redeploy the site, and I don't have to worry about the latency or github uptime. &lt;/p&gt;&lt;h4 id="io"&gt;IO&lt;/h4&gt;&lt;p&gt;The &lt;code&gt;noir.io&lt;/code&gt; namespace provides some helper functions to make it easier to handle static resources.&lt;/p&gt;&lt;p&gt;You can get the absolute path to the public directory of your application by calling &lt;code&gt;resource-path&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;If you need to read a file located in the public folder you can get a URL for the resource by calling &lt;code&gt;get-resource&lt;/code&gt; and provided the path relative to the public directory.&lt;/p&gt;&lt;p&gt;If the resource is a text file, such as a markdown document, you can use &lt;code&gt;slurp-resource&lt;/code&gt; to read it into a string.&lt;/p&gt;&lt;p&gt;Another addition is the &lt;code&gt;upload-file&lt;/code&gt; function which saves the file generated by a &lt;code&gt;multipart/form-data&lt;/code&gt; form POST to a path relative to the public folder. An example can be seen here:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns myapp.upload
  ...
  &amp;#40;:require &amp;#91;noir.io :as io&amp;#93;&amp;#41;&amp;#41;
 
&amp;#40;defn upload-page &amp;#91;&amp;#93;
  &amp;#40;common/layout
    &amp;#91;:h2 &amp;quot;Upload a file&amp;quot;&amp;#93;
    &amp;#40;form-to {:enctype &amp;quot;multipart/form-data&amp;quot;}
             &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93;            
             &amp;#40;file-upload :file&amp;#41;            
             &amp;#40;submit-button &amp;quot;upload&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
              
&amp;#40;defn handle-upload &amp;#91;file&amp;#93;
  &amp;#40;upload-file &amp;quot;/uploads&amp;quot; file&amp;#41;
  &amp;#40;redirect
    &amp;#40;str &amp;quot;/&amp;quot; &amp;#40;session/get :user&amp;#41; &amp;quot;/&amp;quot; &amp;#40;:filename file&amp;#41;&amp;#41;&amp;#41;&amp;#41;
   
&amp;#40;defroutes upload-routes
  &amp;#40;GET &amp;quot;/upload&amp;quot; &amp;#91;&amp;#93; &amp;#40;upload-page&amp;#41;&amp;#41;
  &amp;#40;POST &amp;quot;/upload&amp;quot; &amp;#91;file&amp;#93; &amp;#40;handle-upload file&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h4 id="access&amp;#95;rules"&gt;Access rules&lt;/h4&gt;&lt;p&gt;Noir used to have a &lt;code&gt;pre-route&lt;/code&gt; macro, which allowed for filtering and redirecting based on some rules.&lt;/p&gt;&lt;p&gt;Now, &lt;code&gt;lib-noir&lt;/code&gt; provides a &lt;code&gt;restricted&lt;/code&gt; macro which provides similar functionality.&lt;/p&gt;&lt;p&gt;You can define access rules as functions which accept the method, url, and params. The function then returns a boolean to indicate if the rule succeeded or not.&lt;/p&gt;&lt;p&gt;For example, if we wanted to restrict access to a page so that it's only accessible if the id in session matches the id in the page, we could write a rule like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn user-page &amp;#91;method url params&amp;#93; 
  &amp;#40;and &amp;#40;= url &amp;quot;/private/:id&amp;quot;&amp;#41;
       &amp;#40;= &amp;#40;first params&amp;#41; &amp;#40;session/get :user&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then we wrap our handler in &lt;code&gt;wrap-access-rules&lt;/code&gt; middleware. The middleware accepts one or more access rule functions, and checks if restricted pages match any of the rules provided.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def app &amp;#40;-&amp;gt; all-routes
             &amp;#40;middleware/app-handler&amp;#41;
             &amp;#40;middleware/wrap-access-rules user-page&amp;#41;&amp;#41;&amp;#41;  
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;With that in place, we can restrict access to our page as follows.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;restricted GET &amp;quot;/private/:id&amp;quot; &amp;#91;id&amp;#93; &amp;quot;private!&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that, you have to use &lt;code&gt;noir.util.middleware/app-handler&lt;/code&gt; for &lt;code&gt;wrap-access-rules&lt;/code&gt; to work correctly. Or manually bind the &lt;code&gt;noir.request/&amp;#42;request&amp;#42;&lt;/code&gt;, eg:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn wrap-request-map &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;req&amp;#93;
    &amp;#40;binding &amp;#91;noir.request/&amp;#42;request&amp;#42; req&amp;#93;
      &amp;#40;handler req&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;update&lt;/strong&gt; I've since made &lt;code&gt;wrap-request-map&lt;/code&gt; public in &lt;code&gt;lib-noir&lt;/code&gt;, so if you need to wrap the request for any reason, you don't need to roll your own.&lt;/p&gt;&lt;p&gt;I hope you find the new features useful, and as always I'm open to feedback and suggestions for improvements as well as new features.&lt;/p&gt;</description><pubDate>Tue, 08 Jan 2013 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-12-28-Luminus-progress-updates.html</guid><link>https://yogthos.net/posts/2012-12-28-Luminus-progress-updates.html</link><title>Luminus progress updates</title><description>&lt;p&gt;In this post I'd like to give some updates on the progress of Luminus and the direction it's moving in. &lt;/p&gt;&lt;p&gt;I've had some great chats over at #clojure on IRC, and there's been lots of ideas and brainstorming. It's a very friendly and informative place if you haven't yet visited. :)&lt;/p&gt;&lt;p&gt;After talking it over with Raynes we decided that it would be much better to simply add things to &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt; than to roll a new library. So, lib-luminus is no more, and instead all the updates will be happening in &lt;code&gt;lib-noir&lt;/code&gt; now.&lt;/p&gt;&lt;p&gt;All the current helper functions have already been rolled into version 0.3.0 of &lt;code&gt;lib-noir&lt;/code&gt;, so definitely switch to it if you're using &lt;code&gt;lib-luminus&lt;/code&gt; currently. The good news is that all you need to do is replace &lt;code&gt;&amp;#91;lib-luminus &amp;quot;0.1.5&amp;quot;&amp;#93;&lt;/code&gt; with &lt;code&gt;&amp;#91;lib-noir &amp;quot;0.3.0&amp;quot;&amp;#93; in your &lt;/code&gt;project.clj`, and update your namespaces to reference it instead. The function names and behaviour haven't changed.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;This segues into the next topic of how the line is drawn between what goes into the library and what belongs in the template. &lt;/p&gt;&lt;p&gt;The strategy here is to add functionality to `lib-noir, while putting configuration in the template. This facilitates an easy path for upgrades as the library continues to improve and evolve, while keeping all the customization in the hands of the user. It also means that the template will act as documentation for how to configure your application.&lt;/p&gt;&lt;p&gt;As the template continues to grow, it will be increasingly difficult to please everybody with a single template. For example, somebody might want to use  PostreSQL for their db, while another person might like MySQL, and yet another uses CouchDB and doesn't want to see any of the SQL business at all. &lt;/p&gt;&lt;p&gt;As these things tend to be rather polarizing, the approach will be to let people choose the items they want. Luminus aims to be more of a buffet, where you pick what's on your plate, as opposed omakase with the chef telling you what to eat. :)&lt;/p&gt;&lt;p&gt;To this end, the latest release of Luminus provides a base template which can be extended using &lt;code&gt;+feature&lt;/code&gt; notation. Currently, there's two features supported, the first is the addition of bootstrap into the project and the second is support for SQLite.&lt;/p&gt;&lt;p&gt;The way this works is if you want to make a basic application, you'd do the same thing you did before.&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;lein new luminus myapp
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But if you wanted to have bootstrap in your app, then you'd simply do this:&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;lein new luminus myapp +bootstrap
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The best part is that you can mix different extensions together, eg:&lt;pre&gt;&lt;code class="bash"&gt;lein new luminus myapp +bootstrap +sqlite
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;When you do that, both features will be added to the resulting project. However, if they have any common files between the two features, then the latest one overwrites the former.&lt;/p&gt;&lt;p&gt;Hopefully, this approach will provide an easy way to add extended configuration while keeping things compartmentalized and easy to maintain. The latest documentation and examples are available at the official &lt;a href='http://www.luminusweb.net'&gt;Luminus&lt;/a&gt; site.&lt;/p&gt;</description><pubDate>Fri, 28 Dec 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-12-24-Luminus-a-web-framework-for-Clojure.html</guid><link>https://yogthos.net/posts/2012-12-24-Luminus-a-web-framework-for-Clojure.html</link><title>Luminus: a web framework for Clojure</title><description>&lt;p&gt;Since the retirement of Noir, there aren't any batteries included web frameworks for Clojure. As I mentioned in an &lt;a href='https://yogthos.net/blog/33-Moving+to+Compojure'&gt;earlier post&lt;/a&gt;, moving to Compojure is fairly painless. However, you still have to put a lot of things together by hand.&lt;/p&gt;&lt;p&gt;I suspect this isn't a problem for most people who've already been doing Clojure development. However, it can be daunting for beginners and it also means having to write a lot of boiler plate when making a new site.&lt;/p&gt;&lt;p&gt;I decided to see if I could tie some common libraries together to provide a more comprehensive solution for creating web applications in Clojure. This led to the creation of the &lt;a href='http://www.luminusweb.net'&gt;Luminus&lt;/a&gt; framework, which follows in footsteps of Noir in attempting to make web development in Clojure an easy and accessible experience.&lt;/p&gt;&lt;p&gt;The framework consists of two parts, first is the &lt;a href='https://github.com/yogthos/lib-luminus'&gt;lib-luminus&lt;/a&gt;, which provides some useful utility functions, which I found to be helpful when writing applications. The second is the &lt;a href='https://github.com/yogthos/luminus-template'&gt;luminus-template&lt;/a&gt;, which is used to generate the base application.&lt;/p&gt;&lt;p&gt;The resulting app is ready to be run standalone or deployed as a war. It can also be run on &lt;a href='http://www.heroku.com/'&gt;Heroku&lt;/a&gt; by following the steps in the &lt;a href='https://devcenter.heroku.com/articles/clojure'&gt;official documentation&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The application generated by the template can be easily modified to fit your needs and shouldn't be any more restrictive than a standard Compojure app. This avoids some of the issues with Noir, where things like using custom middleware were problematic.&lt;/p&gt;&lt;p&gt;The documentation site for Luminus is built using the framework in the spirit of eating my own dog food, and its source is available on &lt;a href='https://github.com/yogthos/luminus'&gt;github&lt;/a&gt; as well.&lt;/p&gt;&lt;p&gt;Hopefully this will be useful in helping people get started. I intend to continue working on it and I'm always open to suggestions, patches, and collaboration. :)&lt;/p&gt;</description><pubDate>Mon, 24 Dec 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-12-16-Creating-Leiningen-Templates.html</guid><link>https://yogthos.net/posts/2012-12-16-Creating-Leiningen-Templates.html</link><title>Creating Leiningen Templates</title><description>&lt;p&gt;If you've used Leiningen before, you've already seen templates in action. When you create a project using &lt;code&gt;lein new myproject&lt;/code&gt;, you end up with a project folder with a namespace called myproject and a core.clj inside it. &lt;/p&gt;&lt;p&gt;The templates are really useful if you need to setup some common boilerplate for your project. In the last post I referenced a template for Compojure, which creates a new batteries included project.&lt;/p&gt;&lt;p&gt;Leiningen uses the &lt;a href='https://github.com/Raynes/lein-newnew'&gt;lein-newnew&lt;/a&gt; plugin for this task. All you have to do to create a new template is to run &lt;code&gt;lein new template &amp;lt;template name&amp;gt;&lt;/code&gt;. In my case I created a template called &lt;code&gt;compojure-app&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;lein new template compojure-app
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As all Leiningen projects, it will contain the &lt;code&gt;project.clj&lt;/code&gt;, which will contain the description for our project:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject compojure-app/lein-template &amp;quot;0.2.7&amp;quot;
  :description &amp;quot;Compojure project template for Leiningen&amp;quot;
  :url &amp;quot;https://github.com/yogthos/compojure-template&amp;quot;
  :eval-in-leiningen true
  :license {:name &amp;quot;Eclipse Public License&amp;quot;
            :url &amp;quot;http://www.eclipse.org/legal/epl-v10.html&amp;quot;}
  :dependencies &amp;#91;&amp;#91;leinjacker &amp;quot;0.2.0&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It looks like a regular project file, except for the &lt;code&gt;eval-in-leiningen&lt;/code&gt; key which &lt;del&gt;causes Leiningen to launch a subprocess&lt;/del&gt; prevents Leiningen from launching a separate process for the given project during the build time.&lt;/p&gt;&lt;p&gt;The actual template resides under&lt;/p&gt;&lt;pre&gt;&lt;code&gt;src/compojure-template/leiningen/new/compojure&amp;#95;app.clj
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It looks as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns leiningen.new.compojure-app
  &amp;#40;:use &amp;#91;leiningen.new.templates :only &amp;#91;renderer sanitize year -&amp;gt;files&amp;#93;&amp;#93;
        &amp;#91;leinjacker.utils :only &amp;#91;lein-generation&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;def project-file
  &amp;#40;if &amp;#40;= &amp;#40;lein-generation&amp;#41; 2&amp;#41;
    &amp;quot;project&amp;#95;lein2.clj&amp;quot;
    &amp;quot;project&amp;#95;lein1.clj&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn compojure-app
  &amp;quot;Create a new Compojure project&amp;quot;
  &amp;#91;name&amp;#93;
  &amp;#40;let &amp;#91;data {:name name
              :sanitized &amp;#40;sanitize name&amp;#41;
              :year &amp;#40;year&amp;#41;}
        render #&amp;#40;&amp;#40;renderer &amp;quot;compojure&amp;#95;app&amp;quot;&amp;#41; % data&amp;#41;&amp;#93;
    &amp;#40;println &amp;quot;Generating a lovely new Compojure project named&amp;quot; &amp;#40;str name &amp;quot;...&amp;quot;&amp;#41;&amp;#41;
    &amp;#40;-&amp;gt;files data
             &amp;#91;&amp;quot;.gitignore&amp;quot;  &amp;#40;render &amp;quot;gitignore&amp;quot;&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;project.clj&amp;quot; &amp;#40;render project-file&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;README.md&amp;quot;   &amp;#40;render &amp;quot;README.md&amp;quot;&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;src/{{sanitized}}/handler.clj&amp;quot;      &amp;#40;render &amp;quot;handler.clj&amp;quot;&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;src/{{sanitized}}/server.clj&amp;quot;       &amp;#40;render &amp;quot;server.clj&amp;quot;&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;src/{{sanitized}}/common.clj&amp;quot; &amp;#40;render &amp;quot;common.clj&amp;quot;&amp;#41;&amp;#93;
             &amp;#91;&amp;quot;resources/public/css/screen.css&amp;quot; &amp;#40;render &amp;quot;screen.css&amp;quot;&amp;#41;&amp;#93;
             &amp;quot;resources/public/js&amp;quot;
             &amp;quot;resources/public/img&amp;quot;
             &amp;quot;src/{{sanitized}}/models&amp;quot;
             &amp;#91;&amp;quot;test/{{sanitized}}/test/handler.clj&amp;quot; &amp;#40;render &amp;quot;handler&amp;#95;test.clj&amp;quot;&amp;#41;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The &lt;code&gt;compojure-app&lt;/code&gt; function is where all the fun happens, and it's what gets called when we run &lt;code&gt;lein new compojure-app myapp&lt;/code&gt; to create an application using this template.&lt;/p&gt;&lt;p&gt;The function is mostly self explanatory. It uses the &lt;code&gt;render&lt;/code&gt; function from &lt;code&gt;leiningen.new.templates&lt;/code&gt; to take the template files and put them at the specified path. The &lt;code&gt;{{sanitized}}&lt;/code&gt; tag ensures that the generated names for the package folders are valid.&lt;/p&gt;&lt;p&gt;Our template files live under &lt;/p&gt;&lt;pre&gt;&lt;code&gt;src/compojure-template/leiningen/new/compojure&amp;#95;app
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and they don't need to have the same folder structure as the resulting project. As you can see above, we specify the resulting path explicitly in our template.&lt;/p&gt;&lt;p&gt;The template files look exactly like any regular Clojure source file, except for the &lt;code&gt;{{name}}&lt;/code&gt; anchor. This will be replaced with the name of the application we specified when creating the project. Here's the &lt;code&gt;common.clj&lt;/code&gt; template as an example:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns {{name}}.common
  &amp;#40;:use &amp;#91;hiccup.page :only &amp;#91;html5 include-css&amp;#93;&amp;#93;&amp;#41;&amp;#41;
       
&amp;#40;defn layout &amp;#91;&amp;amp; body&amp;#93;
  &amp;#40;html5 
    &amp;#91;:head
     &amp;#91;:title &amp;quot;Welcome to {{name}}&amp;quot;&amp;#93;
     &amp;#40;include-css &amp;quot;/css/screen.css&amp;quot;&amp;#41;&amp;#93;
    &amp;#40;into &amp;#91;:body&amp;#93; body&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Every occurrence of &lt;code&gt;{{name}}&lt;/code&gt; will be replaced with myapp instead and we'll have our namespace and greeting customized.&lt;/p&gt;&lt;p&gt;Once you've created your template, you'll need to install it using &lt;code&gt;lein install&lt;/code&gt; and then add it as a plugin to your profile under &lt;code&gt;&amp;#126;/.lein/profiles.clj&lt;/code&gt; using the following format:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;{:user
  {:plugins &amp;#91;&amp;#91;compojure-app/lein-template &amp;quot;0.2.7&amp;quot;&amp;#93;&amp;#93;}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's it, you can now use your new template and never have to write boilerplate for this kind of project again.&lt;/p&gt;&lt;p&gt;If you wish to make your template available to others you can publish it to &lt;a href='https://clojars.org/'&gt;Clojars&lt;/a&gt; by running &lt;code&gt;lein deploy clojars&lt;/code&gt; from the console.&lt;/p&gt;&lt;p&gt;Any template published on Clojars can be used directly without needing to add it to your plugins in the &lt;code&gt;profiles.clj&lt;/code&gt; as shown above.&lt;/p&gt;&lt;p&gt;The complete source for the template discussed in this post is available &lt;a href='https://github.com/yogthos/compojure-template'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 16 Dec 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-12-15-Moving-to-Compojure.html</guid><link>https://yogthos.net/posts/2012-12-15-Moving-to-Compojure.html</link><title>Moving to Compojure</title><description>&lt;p&gt;It was &lt;a href='http://blog.raynes.me/blog/2012/12/13/moving-away-from-noir/'&gt;recently announced&lt;/a&gt; that &lt;a href='https://github.com/noir-clojure/noir'&gt;Noir&lt;/a&gt; is being deprecated. The primary reason cited is that it simply doesn't add a lot of useful functionality over what's already available in Compojure and makes it difficult to integrate other middleware, such as &lt;a href='https://github.com/cemerick/friend'&gt;friend&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;The useful parts of Noir have been moved to &lt;a href='https://github.com/noir-clojure/lib-noir'&gt;lib-noir&lt;/a&gt;. Together, Compojure and lib-noir provide a very similar experience to what you're already used to if you've been using Noir up to now.&lt;/p&gt;&lt;p&gt;There are some differences of course. The main one is that instead of using the &lt;code&gt;defpage&lt;/code&gt; macro, you would now declare your routes using &lt;code&gt;defroutes&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;So, if you previously had something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;common/layout 
    &amp;#40;form-to &amp;#91;:post &amp;quot;/&amp;quot;&amp;#93;                           
              &amp;#40;text-area {:placeholder &amp;quot;say something...&amp;quot;} &amp;quot;message&amp;quot;&amp;#41; 
              &amp;#91;:br&amp;#93;
              &amp;#40;text-field {:placeholder &amp;quot;name&amp;quot;} &amp;quot;id&amp;quot;&amp;#41;
              &amp;#40;submit-button &amp;quot;post message&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;#91;:post &amp;quot;/&amp;quot;&amp;#93; params
  &amp;#40;common/layout 
    &amp;#91;:p &amp;#40;:id params&amp;#41; &amp;quot; says &amp;quot; &amp;#40;:message params&amp;#41;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Noir would then create the GET and POST routes for "/" behind the scenes. With Compojure we'll have to define the routes explicitly using &lt;code&gt;defroutes&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defroutes app-routes  
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93; &amp;#40;message&amp;#41;&amp;#41;
  &amp;#40;POST &amp;quot;/&amp;quot; params &amp;#40;display-message params&amp;#41;&amp;#41;
  &amp;#40;route/resources &amp;quot;/&amp;quot;&amp;#41;
  &amp;#40;route/not-found &amp;quot;Not Found&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Then, we'll write the &lt;code&gt;message&lt;/code&gt; and &lt;code&gt;display-message&lt;/code&gt; functions and put the logic for the pages in them.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn message &amp;#91;&amp;#93;
  &amp;#40;html5 
    &amp;#91;:body 
     &amp;#40;form-to &amp;#91;:post &amp;quot;/&amp;quot;&amp;#93;                           
              &amp;#40;text-area {:placeholder &amp;quot;say something...&amp;quot;} &amp;quot;message&amp;quot;&amp;#41; 
              &amp;#91;:br&amp;#93;
              &amp;#40;text-field {:placeholder &amp;quot;name&amp;quot;} &amp;quot;id&amp;quot;&amp;#41;
              &amp;#40;submit-button &amp;quot;post message&amp;quot;&amp;#41;&amp;#41;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn display-message &amp;#91;params&amp;#93;
  &amp;#40;let &amp;#91;form-params &amp;#40;:form-params params&amp;#41;&amp;#93; 
    &amp;#40;html5 
      &amp;#91;:body 
       &amp;#91;:p &amp;#40;get form-params &amp;quot;id&amp;quot;&amp;#41; &amp;quot; says &amp;quot; &amp;#40;get form-params &amp;quot;message&amp;quot;&amp;#41;&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The Noir template comes with a &lt;code&gt;common&lt;/code&gt; namespace which defines a layout macro, which we use to wrap our pages so that we don't have to keep typing in the boilerplate. We can easily write a helper function to do the same thing.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns myapp.common
  &amp;#40;:use &amp;#91;hiccup.def :only &amp;#91;defhtml&amp;#93;&amp;#93; 
        &amp;#91;hiccup.page :only &amp;#91;include-css&amp;#93;&amp;#93;&amp;#41;&amp;#41;
       
&amp;#40;defhtml layout &amp;#91;&amp;amp; body&amp;#93;  
  &amp;#91;:head
   &amp;#91;:title &amp;quot;Welcome to myapp&amp;quot;&amp;#93;
   &amp;#40;include-css &amp;quot;/css/screen.css&amp;quot;&amp;#41;&amp;#93;
  &amp;#40;into &amp;#91;:body&amp;#93; body&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The next difference is that our request map contains the complete request as opposed to just the form params as is the case with the one in &lt;code&gt;defpage&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This means that we have to grab the &lt;code&gt;:form-params&lt;/code&gt; key from it to access the form parameters. Another thing to note is that the parameter keys are strings, meaning that we can't destructure them using &lt;code&gt;:keys&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This problem is also easily addressed  by a macro which will grab the form-params and keywordize them for us. Note that the original request map will still be available as &lt;code&gt;request&lt;/code&gt; in the resulting function.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro page &amp;#91;f form-params &amp;amp; body&amp;#93;
  `&amp;#40;defn &amp;#126;f &amp;#91;&amp;#126;'request&amp;#93;
     &amp;#40;let &amp;#91;&amp;#126;form-params 
           &amp;#40;into {} &amp;#40;for &amp;#91;&amp;#91;k# v#&amp;#93; &amp;#40;:form-params &amp;#126;'request&amp;#41;&amp;#93; 
                      &amp;#91;&amp;#40;keyword k#&amp;#41; v#&amp;#93;&amp;#41;&amp;#41;&amp;#93;
       &amp;#126;@body&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, we can rewrite our app as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;page message &amp;#91;&amp;#93;
  &amp;#40;layout
    &amp;#40;form-to &amp;#91;:post &amp;quot;/&amp;quot;&amp;#93;                           
             &amp;#40;text-area {:placeholder &amp;quot;say something...&amp;quot;} &amp;quot;message&amp;quot;&amp;#41; 
             &amp;#91;:br&amp;#93;
             &amp;#40;text-field {:placeholder &amp;quot;name&amp;quot;} &amp;quot;id&amp;quot;&amp;#41;
             &amp;#40;submit-button &amp;quot;post message&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;page display-message {:keys &amp;#91;id message&amp;#93;}
  &amp;#40;layout
      &amp;#91;:p id &amp;quot; says &amp;quot; message&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defroutes app-routes  
  &amp;#40;GET &amp;quot;/&amp;quot; &amp;#91;&amp;#93; &amp;#40;message &amp;#91;&amp;#93;&amp;#41;&amp;#41;
  &amp;#40;POST &amp;quot;/&amp;quot; params &amp;#40;display-message params&amp;#41;&amp;#41;
  &amp;#40;route/resources &amp;quot;/&amp;quot;&amp;#41;
  &amp;#40;route/not-found &amp;quot;Not Found&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;update&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Turns out Compojure already provides the functionality provided by the page macro, and to get the form params, we can destructure them as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn display-message &amp;#91;id message&amp;#93;
  &amp;#40;layout &amp;#91;:p id &amp;quot; says &amp;quot; message&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defroutes app-routes  
  &amp;#40;POST &amp;quot;/&amp;quot; &amp;#91;id message&amp;#93; &amp;#40;display-message id message&amp;#41;&amp;#41;
  &amp;#40;route/not-found &amp;quot;Not Found&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Big thanks to James Reeves  aka &lt;a href='https://github.com/weavejester'&gt;weavejester&lt;/a&gt; on &lt;a href='http://www.reddit.com/r/Clojure/comments/14wlew/migrating_from_noir_to_compojure/c7h50m1'&gt;setting me straight&lt;/a&gt; there. :)&lt;/p&gt;&lt;p&gt;This is starting to look very similar to the Noir style apps we're used to. Turns out that migrating from Noir to Compojure is fairly painless. &lt;/p&gt;&lt;p&gt;If you use lib-noir when converting your existing Noir application, then the changes end up being minimal. You can continue using noir.crypt, noir.validation, and etc. as you did before. The only caveat is that you now have to remember to add the appropriate wrappers to your handler, eg:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;-&amp;gt; handler
  &amp;#40;wrap-noir-cookies&amp;#41;
  &amp;#40;session/wrap-noir-session 
    {:store &amp;#40;memory-store session/mem&amp;#41;}&amp;#41;
  &amp;#40;wrap-noir-validation&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One thing which Noir provided was a nice batteries included template. I created a similar one called &lt;a href='https://github.com/yogthos/compojure-template'&gt;compojure-app&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;To use the template you can simply run:&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;lein new compojure-app myapp
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The template sets up a project with a &lt;code&gt;main&lt;/code&gt;, which can be compiled into a standalone using &lt;code&gt;lein uberjar&lt;/code&gt; or into a deployable WAR using &lt;code&gt;leing ring uberwar&lt;/code&gt;. The project is setup to correctly handle loading static resources located in &lt;code&gt;resources/public&lt;/code&gt; and correctly handle the servlet context. &lt;/p&gt;&lt;p&gt;When run with &lt;code&gt;lein run&lt;/code&gt; the project will pickup the dev dependencies and use the &lt;code&gt;wrap-reload&lt;/code&gt;, so that changes to source are picked up automatically in the running app.&lt;/p&gt;&lt;p&gt;This should get all the boiler plate out of the way and let you focus on making your app just as you did with Noir. :)&lt;/p&gt;&lt;br /&gt;</description><pubDate>Sat, 15 Dec 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-10-26-ClojureScript-Adventures.html</guid><link>https://yogthos.net/posts/2012-10-26-ClojureScript-Adventures.html</link><title>ClojureScript Adventures</title><description>&lt;p&gt;I finally got a chance to play around a bit more with ClojureScript. When I was updating &lt;a href='https://github.com/yogthos/markdown-clj'&gt;markdown-clj&lt;/a&gt; to compile to it, the extent of interaction was to accept a markdown string and return the corresponding HTML.&lt;/p&gt;&lt;p&gt;This time around I decided to dive into doing interop with JavaScript and actual interaction with the page. I wrote a silly &lt;a href='https://github.com/yogthos/Clojure-Tetris'&gt;Tetris game&lt;/a&gt; a while back, and it seemed like a perfect fit for the task.&lt;/p&gt;&lt;p&gt;So, let's see what's involved in porting Clojure to ClojureScript and Canvas. First, I had to separate the pure Clojure code from any code which relies on Java interop. The original code can be seen &lt;a href='https://github.com/yogthos/Clojure-Tetris/blob/f614a66524647870bc387ca9615a119bc7d76a36/src/tetris.clj'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;After, splitting it up, I ended up with a &lt;a href='https://github.com/yogthos/Clojure-Tetris/blob/master/src/tetris/game.clj'&gt;game namespace&lt;/a&gt; which contains the bulk of the game logic, and a &lt;a href='https://github.com/yogthos/Clojure-Tetris/blob/master/src/tetris/core.clj'&gt;core namespace&lt;/a&gt; containing all the logic pertaining to the UI and input. The split turned out to be fairly painless since I already had the game logic separated from UI in the original design.&lt;/p&gt;&lt;p&gt;Now it's time to add some ClojureScript to the project. First, we need to create a new source folder for the ClojureScript namespaces. In my project I called this folder &lt;code&gt;src-cljs&lt;/code&gt;. Then we need some way to compile our script.&lt;/p&gt;&lt;p&gt;The easiest way to do that is to use the &lt;a href='https://github.com/emezeske/lein-cljsbuild'&gt;lein-cljsbuild plugin&lt;/a&gt;. With it you can specify the ClojureScript sources, Clojure namespaces you'd like to reference, and the output Js files to produce.&lt;/p&gt;&lt;p&gt;In my case the project file looks as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject tetris &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;a simple Tetris game&amp;quot;
  :url &amp;quot;https://github.com/yogthos/Clojure-Tetris&amp;quot;
  :license {:name &amp;quot;Eclipse Public License&amp;quot;
            :url &amp;quot;http://www.eclipse.org/legal/epl-v10.html&amp;quot;}
  
  :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;&amp;#93;
  :plugins &amp;#91;&amp;#91;lein-cljsbuild &amp;quot;0.2.9&amp;quot;&amp;#93;&amp;#93;
  
  :source-paths &amp;#91;&amp;quot;src&amp;quot;&amp;#93;
  :main tetris.core

  :cljsbuild {:crossovers &amp;#91;tetris.game&amp;#93;
              :builds
              &amp;#91;{:source-path &amp;quot;src-cljs&amp;quot;
                :compiler
                {:output-to &amp;quot;js/tetris.js&amp;quot;
                 :optimizations :advanced
                 :pretty-print false}}&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;All that's needed to include ClojureScript compilation is to add the &lt;code&gt;lein-cljsbuild&lt;/code&gt; in the plugins and specify the options for the &lt;code&gt;cljsbuild&lt;/code&gt;. The &lt;code&gt;crossovers&lt;/code&gt; section specifies a vector of Clojure namespaces which will be included during compilation.&lt;/p&gt;&lt;p&gt;Once the project file is setup, we have two options for invoking ClojureScript compilation. We can either run &lt;code&gt;lein cljsbuild once&lt;/code&gt; or &lt;code&gt;lein cljsbuild auto&lt;/code&gt;. When using the auto option, the build will watch for changes in the source and automatically recompile the Js files as needed. This takes much less time than when compiling using the once option, and turns out to be quite handy for development.&lt;/p&gt;&lt;p&gt;The ClojureScript version of the UI, which uses the canvas, can be seen &lt;a href='https://github.com/yogthos/Clojure-Tetris/blob/master/src-cljs/tetris/core.cljs'&gt;here&lt;/a&gt; . &lt;/p&gt;&lt;p&gt;Interacting with JavaScript turns out to be pretty simple and the syntax is similar to Java interop in Clojure. However, there are some differences  which are worth mentioning.&lt;/p&gt;&lt;p&gt;Any standard Js functions can be accessed using the &lt;code&gt;js&lt;/code&gt; namespace, for example if we want to make a logger which logs to the console we can write something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn log &amp;#91;&amp;amp; items&amp;#93;
  &amp;#40;.log js/console &amp;#40;apply str items&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This works exactly like the Java interop, where we denote methods by using the &lt;code&gt;.&lt;/code&gt; notation and pass in the object as the first argument.&lt;/p&gt;&lt;p&gt;Exporting functions so that they're visible from JavaScript is also quite simple. Instead of denoting them with &lt;code&gt;-&lt;/code&gt; as we do when we interop with Java, we use &lt;code&gt;&amp;#94;:export&lt;/code&gt; annotation:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn &amp;#94;:export init &amp;#91;&amp;#93;
  &amp;#40;log &amp;quot;Hello ClojureScript!&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One thing that's not obvious is the interaction with JavaScript object properties. To access these we use &lt;code&gt;&amp;#40;.-property obj&amp;#41;&lt;/code&gt; notation. Where &lt;code&gt;-&lt;/code&gt; indicates that we're referencing a property and not a function. Writing properties is accomplished by calling the &lt;code&gt;set!&lt;/code&gt; function. Here's an example:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn &amp;#94;:export init &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;canvas &amp;#40;.getElementById js/document &amp;quot;canvas&amp;quot;&amp;#41;
        ctx    &amp;#40;.getContext canvas &amp;quot;2d&amp;quot;&amp;#41;
        width  &amp;#40;.-width canvas&amp;#41; 
        height &amp;#40;.-height canvas&amp;#41;&amp;#93;
 
    &amp;#40;log &amp;quot;width: &amp;quot; width &amp;quot;, height: &amp;quot; height&amp;#41;

    ;;set a property
    &amp;#40;set! &amp;#40;.-fillStyle ctx&amp;#41; &amp;quot;black&amp;quot;&amp;#41;

    &amp;#40;.fillRect ctx 0 0 width height&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Another quirk I ran into is that &lt;code&gt;:use&lt;/code&gt; doesn't seem to work in the namespace declaration as it expects a collection.&lt;/p&gt;&lt;p&gt;For example, if you have the following setup:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns foo&amp;#41;

&amp;#40;defn bar &amp;#91;&amp;#93;&amp;#41;

&amp;#40;ns hello
 &amp;#40;:use foo&amp;#41;&amp;#41;

&amp;#40;defn &amp;#94;:export init &amp;#91;&amp;#93;
	&amp;#40;js/alert &amp;quot;Hello from ClojureScript!&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;the compiler throws the following error:&lt;pre&gt;&lt;code class="clojure"&gt;java.lang.UnsupportedOperationException: nth not supported on this type: Symbol
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Fortunately, both &lt;code&gt;&amp;#40;:use &amp;#91;foo :only &amp;#91;bar&amp;#93;&amp;#93;&amp;#41;&lt;/code&gt; and &lt;code&gt;&amp;#40;:require foo&amp;#41;&lt;/code&gt; work as expected. &lt;/p&gt;&lt;p&gt;Finally, to make a timer, it's possible to use &lt;code&gt;js/setTimeout&lt;/code&gt; and simply pass it the function to call after the timeout:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;declare game-loop&amp;#41;
&amp;#40;defn game-loop &amp;#91;state&amp;#93;
  &amp;#40;if &amp;#40;not &amp;#40;:game-over state&amp;#41;&amp;#41;
    &amp;#40;js/setTimeout
      &amp;#40;fn &amp;#91;&amp;#93; &amp;#40;game-loop &amp;#40;update-state state&amp;#41;&amp;#41;&amp;#41;
      10&amp;#41;&amp;#41;&amp;#41;     
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Everything else appeared to work exactly as it does in Clojure itself. The only caveat when porting code is that it cannot contain any Java interop or use libraries which do so. In case of the game, I simply put the game logic into a shared namespace and wrote separate UI logic for both Java and JavaScript versions.&lt;/p&gt;&lt;p&gt;To try out the ClojureScript version simply grab &lt;a href='https://raw.github.com/yogthos/Clojure-Tetris/master/js/tetris.js'&gt;tetris.js&lt;/a&gt; and &lt;a href='https://raw.github.com/yogthos/Clojure-Tetris/master/tetris.html'&gt;tetris.html&lt;/a&gt; which expects the tetris.js file to be in the &lt;code&gt;js&lt;/code&gt; folder relative to it. &lt;/p&gt;&lt;p&gt;One thing to note is that ClojureScript is definitely chunky compared to writing JavaScript by hand. The game weighs in at a hefty 100k. That said, it should be noted that jQuery weighs in about that as well, and nobody would claim that it's outrageous for a site to include it. &lt;/p&gt;&lt;p&gt;I feel that the benefits of ClojureScript offers far outweigh the downsides of its size. You get a much nicer language without all the quirks of working in JavaScript, immutability, persistent data structures, and the ability to easily share code between the server and the browser.&lt;/p&gt;&lt;p&gt;The good news is that ClojureScript is under active development, and performance and size are both targets for future improvement. As it stands I find it very usable for many situations.&lt;/p&gt;</description><pubDate>Fri, 26 Oct 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-10-17-making-reporting-easy.html</guid><link>https://yogthos.net/posts/2012-10-17-making-reporting-easy.html</link><title>making reporting easy</title><description>&lt;p&gt;There are a bunch of reporting options out there, &lt;a href='http://community.jaspersoft.com/project/jasperreports-library'&gt;JasperReports&lt;/a&gt; is one popular example. While it's got a ton of features, it often involves a disproportionate amount of effort to create even the simplest of reports. &lt;a href='http://java-bytes.blogspot.ca/2009/06/jasper-reports-example.html'&gt;Here's&lt;/a&gt; what's involved in simply printing out some fields from the database to a PDF.&lt;/p&gt;&lt;p&gt;Let's see if we can make things easier with Clojure. We'll produce the same report as the one in the linked example.&lt;/p&gt;&lt;p&gt;First, we'll create our database connection using &lt;a href='https://github.com/clojure/java.jdbc'&gt;java.jdbc&lt;/a&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db {:classname &amp;quot;org.postgresql.Driver&amp;quot;
           :subprotocol &amp;quot;postgresql&amp;quot;
           :subname &amp;quot;//localhost:5432/testdb&amp;quot;
           :user &amp;quot;user&amp;quot;
           :password &amp;quot;secret&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;then we'll make an employee table and populate it with the sample data&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-employee-table &amp;#91;&amp;#93;
  &amp;#40;sql/create-table
    :employee
    &amp;#91;:name &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;
    &amp;#91;:occupation &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;
    &amp;#91;:place &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;
    &amp;#91;:country &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;sql/with-connection 
  db
  &amp;#40;create-employee-table&amp;#41;
  &amp;#40;sql/insert-rows 
    :employee
    &amp;#91;&amp;quot;Babji, Chetty&amp;quot;, &amp;quot;Engineer&amp;quot;, &amp;quot;Nuremberg&amp;quot;, &amp;quot;Germany&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Albert Einstein&amp;quot;, &amp;quot;Engineer&amp;quot;, &amp;quot;Ulm&amp;quot;, &amp;quot;Germany&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Alfred Hitchcock&amp;quot;, &amp;quot;Movie Director&amp;quot;, &amp;quot;London&amp;quot;, &amp;quot;UK&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Wernher Von Braun&amp;quot;, &amp;quot;Rocket Scientist&amp;quot;, &amp;quot;Wyrzysk&amp;quot;, &amp;quot;Poland &amp;#40;Previously Germany&amp;#41;&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Sigmund Freud&amp;quot;, &amp;quot;Neurologist&amp;quot;, &amp;quot;Pribor&amp;quot;, &amp;quot;Czech Republic &amp;#40;Previously Austria&amp;#41;&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Mahatma Gandhi&amp;quot;, &amp;quot;Lawyer&amp;quot;, &amp;quot;Gujarat&amp;quot;, &amp;quot;India&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Sachin Tendulkar&amp;quot;, &amp;quot;Cricket Player&amp;quot;, &amp;quot;Mumbai&amp;quot;, &amp;quot;India&amp;quot;&amp;#93;
    &amp;#91;&amp;quot;Michael Schumacher&amp;quot;, &amp;quot;F1 Racer&amp;quot;, &amp;quot;Cologne&amp;quot;, &amp;quot;Germany&amp;quot;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;finally we'll write a function to read the records from the table.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn read-employees &amp;#91;&amp;#93;
  &amp;#40;sql/with-connection db 
    &amp;#40;sql/with-query-results rs &amp;#91;&amp;quot;select &amp;#42; from employee&amp;quot;&amp;#93; &amp;#40;doall rs&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's run &lt;code&gt;read-employees&lt;/code&gt; to make sure everything is working as expected, we should see something like the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;clojure.pprint/pprint &amp;#40;read-employees&amp;#41;&amp;#41;

&amp;#40;{:country &amp;quot;Germany&amp;quot;,
  :place &amp;quot;Nuremberg&amp;quot;,
  :occupation &amp;quot;Engineer&amp;quot;,
  :name &amp;quot;Babji, Chetty&amp;quot;}
 {:country &amp;quot;Germany&amp;quot;,
  :place &amp;quot;Ulm&amp;quot;,
  :occupation &amp;quot;Engineer&amp;quot;,
  :name &amp;quot;Albert Einstein&amp;quot;}
  ...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;You'll notice that the result is simply a list of maps where the keys are the names of the columns in the table.&lt;/p&gt;&lt;p&gt;We're now ready to generate our report, &lt;a href='https://github.com/yogthos/clj-pdf'&gt;clj-pdf&lt;/a&gt; provides a &lt;code&gt;template&lt;/code&gt; macro, which uses &lt;code&gt;$&lt;/code&gt; to create anchors which are populated from the data using the keys of the same name. &lt;/p&gt;&lt;p&gt;The template returns a function which accepts a sequence of maps and applies the supplied template to each element in the sequence. In our case, since we're building a table, the template is simply a vector with the names of the keys for each cell in the row.&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def employee-template 
  &amp;#40;template &amp;#91;$name $occupation $place $country&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;if we pass our data to the template we'll end up with the following:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;employee-template &amp;#40;take 2 &amp;#40;read-employees&amp;#41;&amp;#41;&amp;#41;

&amp;#40;&amp;#91;&amp;quot;Babji, Chetty&amp;quot; &amp;quot;Engineer&amp;quot; &amp;quot;Nuremberg&amp;quot; &amp;quot;Germany&amp;quot;&amp;#93; 
 &amp;#91;&amp;quot;Albert Einstein&amp;quot; &amp;quot;Engineer&amp;quot; &amp;quot;Ulm&amp;quot; &amp;quot;Germany&amp;quot;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;All that's left is to stick this data into our report:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;pdf
 &amp;#91;{}
  &amp;#40;into &amp;#91;:table 
         {:border false
          :cell-border false
          :header &amp;#91;{:color &amp;#91;0 150 150&amp;#93;} &amp;quot;Name&amp;quot; &amp;quot;Occupation&amp;quot; &amp;quot;Place&amp;quot; &amp;quot;Country&amp;quot;&amp;#93;}&amp;#93;
        &amp;#40;employee-template &amp;#40;read-employees&amp;#41;&amp;#41;&amp;#41;&amp;#93;
 &amp;quot;report.pdf&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;here's the result of running the above code, which looks just as we'd expect:&lt;/p&gt;&lt;p&gt;&lt;img src="/files/report1.png" alt="table report" /&gt;&lt;/p&gt;&lt;p&gt;It only took a few lines to create the report and we can see and manipulate the layout of the report in one place. Of course, the template we used for this report was completely boring, so let's look at another example. Here we'll output the data in a list, and style each element:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def employee-template-paragraph 
  &amp;#40;template 
    &amp;#91;:paragraph 
     &amp;#91;:heading $name&amp;#93;
     &amp;#91;:chunk {:style :bold} &amp;quot;occupation: &amp;quot;&amp;#93; $occupation &amp;quot;\n&amp;quot;
     &amp;#91;:chunk {:style :bold} &amp;quot;place: &amp;quot;&amp;#93; $place &amp;quot;\n&amp;quot;
     &amp;#91;:chunk {:style :bold} &amp;quot;country: &amp;quot;&amp;#93; $country
     &amp;#91;:spacer&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;when writing the report, we can mix the templated elements with regular ones:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;pdf 
  &amp;#91;{:font {:size 11}}      
   &amp;#91;:heading {:size 14} &amp;quot;Employees Test&amp;quot;&amp;#93;
   &amp;#91;:line&amp;#93;
   &amp;#91;:spacer&amp;#93;
   &amp;#40;employee-template-paragraph &amp;#40;read-employees&amp;#41;&amp;#41;&amp;#93;
  &amp;quot;report.pdf&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;here's the new report with the fancy formatting applied to it:&lt;/p&gt;&lt;p&gt;&lt;img src="/files/report2.png" alt="list report" /&gt;&lt;/p&gt;&lt;p&gt;I think that this approach provides a lot of flexibility while keeping things concise and clear. In my experience there are many situations where all you need is a simple well formatted report, and the effort to create that report should be minimal.&lt;/p&gt;</description><pubDate>Wed, 17 Oct 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-09-09-Making-services-with-Liberator.html</guid><link>https://yogthos.net/posts/2012-09-09-Making-services-with-Liberator.html</link><title>Making services with Liberator</title><description>&lt;p&gt;&lt;a href='http://clojure-liberator.github.com/'&gt;Liberator&lt;/a&gt; is a recent Clojure library for writing RESTful services. Its primary feature is that it puts strong emphasis on decoupling the front end and the back end of the application.&lt;/p&gt;&lt;p&gt;Conceptually, Liberator provides a very clean way to reason about your service operations. Each request passes through a series of conditions and handlers defined in the resource. These map to the codes specified by the &lt;a href='http://www.ietf.org/rfc/rfc2616.txt'&gt;HTTP rfc&lt;/a&gt;, such as 200 - OK, 201 - created, 404 - not found, etc. This makes it very easy to write standards compliant services and to group the operations logically.&lt;/p&gt;&lt;p&gt;While the official site has some fairly decent documentation, I found there were a few areas where I had to dig around and look through the source to figure out what to do.&lt;/p&gt;&lt;p&gt;In this post I'll walk you through the steps to create a simple application which serves static resources, provides basic session management, and JSON operations.&lt;/p&gt;&lt;p&gt;Our application will be structures as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;src/liberator&amp;#95;service
         server.clj
         resources.clj
         static&amp;#95;resources.clj
         ui.clj
resources/public
         site.js
project.clj
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Our &lt;code&gt;project.clj&lt;/code&gt; will look as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject liberator-example &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;Example for the Liberator library&amp;quot;
  :url &amp;quot;https://github.com/yogthos/liberator-example&amp;quot;
  :license {:name &amp;quot;Eclipse Public License&amp;quot;
            :url &amp;quot;http://www.eclipse.org/legal/epl-v10.html&amp;quot;}
  :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                 &amp;#91;compojure &amp;quot;1.0.2&amp;quot;&amp;#93;
                 &amp;#91;liberator &amp;quot;0.5.0&amp;quot;&amp;#93;
                 &amp;#91;sandbar &amp;quot;0.4.0-SNAPSHOT&amp;quot;&amp;#93;
                 &amp;#91;org.clojure/data.json &amp;quot;0.1.2&amp;quot;&amp;#93;
                 &amp;#91;ring/ring-jetty-adapter &amp;quot;1.1.0&amp;quot;&amp;#93;&amp;#93;
  :dev-dependencies &amp;#91;&amp;#91;lein-ring &amp;quot;0.7.3&amp;quot;&amp;#93;&amp;#93;
  :ring {:handler liberator-service.server/handler}
  :main liberator-service.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now we'll take a look at the service namespace, in it we'll add the required libraries and create an atom to hold the session information.&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns liberator-service.server
  &amp;#40;:use &amp;#91;liberator.representation :only &amp;#91;wrap-convert-suffix-to-accept-header&amp;#93;&amp;#93;
        &amp;#91;ring.middleware.multipart-params :only &amp;#91;wrap-multipart-params&amp;#93;&amp;#93;
        ring.middleware.session.memory
        sandbar.stateful-session
        compojure.core 
        &amp;#91;compojure.handler :only &amp;#91;api&amp;#93;&amp;#93;
        liberator-service.ui
        liberator-service.resources
        liberator-service.static-resources&amp;#41;
  &amp;#40;:require
   &amp;#91;ring.adapter.jetty :as jetty&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defonce my-session &amp;#40;atom {}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt; Next we will define the routes which our application responds to. In our case we've defined routes for serving the home page, our services, and static content:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn assemble-routes &amp;#91;&amp;#93;
  &amp;#40;routes
    &amp;#40;GET   &amp;quot;/&amp;quot; &amp;#91;&amp;#93; home&amp;#41;
    &amp;#40;POST &amp;quot;/login&amp;quot; &amp;#91;&amp;#93; login&amp;#41;
    &amp;#40;POST &amp;quot;/logout&amp;quot; &amp;#91;&amp;#93; logout&amp;#41;
    &amp;#40;GET   &amp;quot;/resources/:resource&amp;quot; &amp;#91;resource&amp;#93; static&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;we'll also need to create a handler for the application:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-handler &amp;#91;&amp;#93;
  &amp;#40;fn &amp;#91;request&amp;#93;
    &amp;#40;&amp;#40;-&amp;gt;
       &amp;#40;assemble-routes&amp;#41;
       api
       wrap-multipart-params
       &amp;#40;wrap-stateful-session {:store &amp;#40;memory-store my-session&amp;#41;}&amp;#41;
       &amp;#40;wrap-convert-suffix-to-accept-header
         {&amp;quot;.html&amp;quot; &amp;quot;text/html&amp;quot;
          &amp;quot;.txt&amp;quot; &amp;quot;text/plain&amp;quot;
          &amp;quot;.xhtml&amp;quot; &amp;quot;application/xhtml+xml&amp;quot;
          &amp;quot;.xml&amp;quot; &amp;quot;application/xml&amp;quot;
          &amp;quot;.json&amp;quot; &amp;quot;application/json&amp;quot;}&amp;#41;&amp;#41;
      request&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The session handling in our handler is provided by the &lt;code&gt;wrap-stateful-session&lt;/code&gt; from the &lt;a href='https://github.com/brentonashworth/sandbar'&gt;sandbar&lt;/a&gt; library. The &lt;code&gt;wrap-convert-suffix-to-accept-header&lt;/code&gt; is used by the Liberator to decide what types of requests it will accept. Finally, we'll create a main to run our service:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn start &amp;#91;options&amp;#93;
  &amp;#40;jetty/run-jetty
   &amp;#40;fn &amp;#91;request&amp;#93;
     &amp;#40;&amp;#40;create-handler&amp;#41; request&amp;#41;&amp;#41;
   &amp;#40;assoc options :join? false&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn -main
  &amp;#40;&amp;#91;port&amp;#93;
     &amp;#40;start {:port &amp;#40;Integer/parseInt port&amp;#41;}&amp;#41;&amp;#41;
  &amp;#40;&amp;#91;&amp;#93;
     &amp;#40;-main &amp;quot;8000&amp;quot;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Next let's write a resource which will display a login page:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns liberator-service.ui
  &amp;#40;:use hiccup.page
        hiccup.element
        hiccup.form
        sandbar.stateful-session
        &amp;#91;liberator.core :only &amp;#91;defresource&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defresource home
  :available-media-types &amp;#91;&amp;quot;text/html&amp;quot;&amp;#93;
  :available-charsets &amp;#91;&amp;quot;utf-8&amp;quot;&amp;#93;
  :handle-ok &amp;#40;html5 &amp;#91;:head &amp;#40;include-js
                             &amp;quot;http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js&amp;quot;
                             &amp;quot;/resources/site.js&amp;quot;&amp;#41;&amp;#93;
                    &amp;#91;:body
                       &amp;#91;:div#message&amp;#93;
                       &amp;#91;:div#login
                        &amp;#40;text-field &amp;quot;user&amp;quot;&amp;#41;
                        &amp;#40;password-field &amp;quot;pass&amp;quot;&amp;#41;
                        &amp;#91;:button {:type &amp;quot;button&amp;quot; :onclick &amp;quot;login&amp;#40;&amp;#41;&amp;quot;} &amp;quot;login&amp;quot;&amp;#93;&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Here we get a glimpse at how Liberator works. We use &lt;code&gt;defresource&lt;/code&gt; to define the handler for the &lt;code&gt;home&lt;/code&gt; route we specified earlier in our service. The resource specifies what media types it provides as well as the encoding for the content. If the handler is invoked successfully then the &lt;code&gt;:handle-ok&lt;/code&gt; handler is called and its output is set as the body of the &lt;code&gt;response&lt;/code&gt;.  In our &lt;code&gt;site.js&lt;/code&gt; we'll define &lt;code&gt;login&lt;/code&gt; and &lt;code&gt;logout&lt;/code&gt; functions which will use POST to call login and logout operations on the server:&lt;pre&gt;&lt;code class="javascript"&gt;function login&amp;#40;&amp;#41; {
	$&amp;#40;&amp;quot;#message&amp;quot;&amp;#41;.text&amp;#40;&amp;quot;sending login request&amp;quot;&amp;#41;;
	$.post&amp;#40;&amp;quot;/login&amp;quot;, 
	       {user: $&amp;#40;&amp;quot;#user&amp;quot;&amp;#41;.val&amp;#40;&amp;#41;, pass: $&amp;#40;&amp;quot;#pass&amp;quot;&amp;#41;.val&amp;#40;&amp;#41;}, 
    	       function&amp;#40;{window.location.reload&amp;#40;true&amp;#41;;},
    	       &amp;quot;json&amp;quot;&amp;#41;
         .error&amp;#40; function&amp;#40;xhr, textStatus, errorThrown&amp;#41; {       			 
      			 $&amp;#40;&amp;quot;#message&amp;quot;&amp;#41;.text&amp;#40;textStatus + &amp;quot;: &amp;quot; + xhr.responseText&amp;#41;;
   	 }&amp;#41;;
}

function logout&amp;#40;&amp;#41; {
    $.post&amp;#40;&amp;quot;/logout&amp;quot;, 
           function&amp;#40;&amp;#41; {window.location.reload&amp;#40;true&amp;#41;;}&amp;#41;;					  	
}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Since we reference a local JavaScript file, we'll need to create a handler to serve it. We'll create a &lt;code&gt;static-resources&lt;/code&gt; namespace for this purpose:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns liberator-service.static-resources  
  &amp;#40;:use &amp;#91;liberator.core :only &amp;#91;defresource&amp;#93;&amp;#93;
        &amp;#91;ring.util.mime-type :only &amp;#91;ext-mime-type&amp;#93;&amp;#93;&amp;#41;
  &amp;#40;:require &amp;#91;clojure.java.io :as io&amp;#93;&amp;#41;&amp;#41;

&amp;#40;let &amp;#91;static-dir  &amp;#40;io/file &amp;quot;resources/public/&amp;quot;&amp;#41;&amp;#93;
  &amp;#40;defresource static
    :available-media-types
    #&amp;#40;let &amp;#91;file &amp;#40;get-in % &amp;#91;:request :route-params :resource&amp;#93;&amp;#41;&amp;#93;       
       &amp;#40;if-let &amp;#91;mime-type &amp;#40;ext-mime-type file&amp;#41;&amp;#93;
         &amp;#91;mime-type&amp;#93;
         &amp;#91;&amp;#93;&amp;#41;&amp;#41;

    :exists?
    #&amp;#40;let &amp;#91;file &amp;#40;get-in % &amp;#91;:request :route-params :resource&amp;#93;&amp;#41;&amp;#93;       
       &amp;#40;let &amp;#91;f &amp;#40;io/file static-dir file&amp;#41;&amp;#93;
         &amp;#91;&amp;#40;.exists f&amp;#41; {::file f}&amp;#93;&amp;#41;&amp;#41;
    
    :handle-ok &amp;#40;fn &amp;#91;{{{file :resource} :route-params} :request}&amp;#93;                 
                 &amp;#40;io/file static-dir file&amp;#41;&amp;#41;&amp;#41;

    :last-modified &amp;#40;fn &amp;#91;{{{file :resource} :route-params} :request}&amp;#93;                                                               
                     &amp;#40;.lastModified &amp;#40;io/file static-dir file&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;When our home page requests &lt;code&gt;/resources/site.js&lt;/code&gt;, this resource will set the mime type to "text/javascript" based on the extension of the file. It will check if the resource exists and the last modified time, and finally serve the resource in &lt;code&gt;:handle-ok&lt;/code&gt; as needed.&lt;/p&gt;&lt;p&gt;Now let's create a resource which the client can call to login and create a session on the server. We'll put it in the &lt;code&gt;resources&lt;/code&gt; namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns liberator-service.resources
  &amp;#40;:use clojure.data.json                        
        sandbar.stateful-session
        &amp;#91;liberator.core :only &amp;#91;defresource request-method-in&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;For our testing, we'll simply create a dummy list of users and a helper to check if one matches our login params:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def users &amp;#91;{:user &amp;quot;foo&amp;quot; 
             :pass &amp;quot;bar&amp;quot;
             :firstname &amp;quot;John&amp;quot;
             :lastname &amp;quot;Doe&amp;quot;}&amp;#93;&amp;#41;

&amp;#40;defn valid-user &amp;#91;user&amp;#93;
  &amp;#40;some #&amp;#40;= user &amp;#40;select-keys % &amp;#91;:user :pass&amp;#93;&amp;#41;&amp;#41; users&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and now we'll create the login resource itself:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defresource login
  :available-media-types &amp;#91;&amp;quot;application/json&amp;quot; &amp;quot;text/javascript&amp;quot;&amp;#93;
  :method-allowed? &amp;#40;request-method-in :post&amp;#41;  
  :authorized?     &amp;#40;fn &amp;#91;{{user :params} :request}&amp;#93;                 
                     &amp;#40;or &amp;#40;session-get :user&amp;#41; &amp;#40;valid-user user&amp;#41;&amp;#41;&amp;#41;
  
  :post! &amp;#40;fn &amp;#91;{{{:keys &amp;#91;user&amp;#93;} :params} :request :as ctx}&amp;#93;
           &amp;#40;session-put! :user user&amp;#41;&amp;#41;
  
  :handle-unauthorized &amp;#40;fn &amp;#91;ctx&amp;#93; &amp;#40;:message ctx&amp;#41;&amp;#41;  
  :handle-created      &amp;#40;json-str {:message &amp;quot;login successful&amp;quot;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Again, the above is fairly straight forward. We specify the media types the handler responds to,  set it to allow the POST request type , check if the supplied user params are valid, and either create the user or return an error based on whether the &lt;code&gt;:authorized?&lt;/code&gt; handler succeeds.&lt;/p&gt;&lt;p&gt;As I mentioned above, each handler responds to a specific HTTP code. For example, if &lt;code&gt;:authorized?&lt;/code&gt; returns false then the code will be set to 401, which will cause &lt;code&gt;:handle-unauthorized&lt;/code&gt; handler to be invoked. If &lt;code&gt;:authorized?&lt;/code&gt; it true then the &lt;code&gt;:post!&lt;/code&gt; handler gets called, and if it succeeds then subsequently&lt;code&gt;:handle-created&lt;/code&gt;. Next we need a logout resource, and it looks as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defresource logout
  :available-media-types &amp;#91;&amp;quot;application/json&amp;quot; &amp;quot;text/javascript&amp;quot;&amp;#93;
  :method-allowed? &amp;#40;request-method-in :post&amp;#41;  
  :post!           &amp;#40;session-delete-key! :user&amp;#41;
  :handle-created  &amp;#40;json-str {:message &amp;quot;logout successful&amp;quot;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;You might have noticed that Liberator is pretty flexible regarding what you can supply as the handler. It can either be a callable function, an evaluated expression, or a value.&lt;/p&gt;&lt;p&gt;Now that we have a way for the user to login and logout, let's revisit our UI handler and update it to render different content based on whether there is a user in the session:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns liberator-service.ui
  &amp;#40;:use hiccup.page
        hiccup.element
        hiccup.form
        sandbar.stateful-session
        liberator-service.resources
        &amp;#91;liberator.core :only &amp;#91;defresource&amp;#93;&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defn get-user &amp;#91;&amp;#93;
  &amp;#40;first &amp;#40;filter #&amp;#40;= &amp;#40;session-get :user&amp;#41; &amp;#40;get-in % &amp;#91;:user&amp;#93;&amp;#41;&amp;#41; users&amp;#41;&amp;#41;&amp;#41;

&amp;#40;def login-page 
  &amp;#91;:body
   &amp;#91;:div#message&amp;#93;
   &amp;#91;:div#login
    &amp;#40;text-field &amp;quot;user&amp;quot;&amp;#41;
    &amp;#40;password-field &amp;quot;pass&amp;quot;&amp;#41;
    &amp;#91;:button {:type &amp;quot;button&amp;quot; :onclick &amp;quot;login&amp;#40;&amp;#41;&amp;quot;} &amp;quot;login&amp;quot;&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defn home-page &amp;#91;&amp;#93; 
  &amp;#91;:body
   &amp;#40;let &amp;#91;{firstname :firstname lastname :lastname} &amp;#40;get-user&amp;#41;&amp;#93; 
     &amp;#91;:div#message &amp;#40;str &amp;quot;Welcome &amp;quot; firstname &amp;quot; &amp;quot; lastname&amp;#41;&amp;#93;&amp;#41;
   &amp;#91;:div#logout 
    &amp;#91;:button {:type &amp;quot;button&amp;quot; :onclick &amp;quot;logout&amp;#40;&amp;#41;&amp;quot;} &amp;quot;logout&amp;quot;&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defresource home
  :available-media-types &amp;#91;&amp;quot;text/html&amp;quot;&amp;#93;
  :available-charsets &amp;#91;&amp;quot;utf-8&amp;quot;&amp;#93;
  :handle-ok &amp;#40;html5 &amp;#91;:head &amp;#40;include-js
                             &amp;quot;http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js&amp;quot;
                             &amp;quot;/resources/site.js&amp;quot;&amp;#41;&amp;#93;
                    &amp;#40;if &amp;#40;session-get :user&amp;#41; &amp;#40;home-page&amp;#41; login-page&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;That's all there is to it. We have a page which checks if there is a user in the session, if there is then it dsiplays the content of the &lt;code&gt;home-page&lt;/code&gt; and if not then the &lt;code&gt;login-page&lt;/code&gt; content is displayed. The page interacts with the service by calling &lt;code&gt;login&lt;/code&gt; and &lt;code&gt;logout&lt;/code&gt; resources via Ajax.&lt;/p&gt;&lt;p&gt;Complete source for the example is available &lt;a href='https://github.com/yogthos/liberator-example'&gt;here&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;Overall, I definitely think that Liberator makes writing RESTful applications easy and natural. This is a fairly different approach from &lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt;, where you think in terms of pages and simply implement the UI and the backend portion for each one. &lt;/p&gt;&lt;p&gt;While the Noir approach can easily result in tight coupling between the UI and the backend, the Liberator ensures that we're always thinking in terms of service operations whenever any interaction between the service and the client is happening.&lt;/p&gt;</description><pubDate>Sun, 09 Sep 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-09-03-Noir-tutorial-part-7.html</guid><link>https://yogthos.net/posts/2012-09-03-Noir-tutorial-part-7.html</link><title>Noir tutorial - part 7</title><description>&lt;p&gt;In the &lt;a href='http://yogthos.net/blog/28-Noir+tutorial+-+part+6'&gt;last part&lt;/a&gt; of the tutorial we saw how we can use a request handler wrapper to fix the redirect URLs. There is another option for doing this that I'd like to mention.&lt;/p&gt;&lt;p&gt;As we've seen, the &lt;code&gt;defpage&lt;/code&gt; params only contain form parameters, but there is a way to access the complete parameter map provided by &lt;code&gt;ring&lt;/code&gt; using the &lt;code&gt;noir.request/ring-request&lt;/code&gt; helper. &lt;/p&gt;&lt;p&gt;If the application is running on a servlet its context will show up in this map and we can use it in our redirects. We can write a simple macro called &lt;code&gt;local-redirect&lt;/code&gt; which will do this for us:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro local-redirect &amp;#91;url&amp;#93;
  `&amp;#40;noir.response/redirect 
     &amp;#40;if-let &amp;#91;context# &amp;#40;:context &amp;#40;noir.request/ring-request&amp;#41;&amp;#41;&amp;#93;
       &amp;#40;str context# &amp;#126;url&amp;#41; &amp;#126;url&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The advantage to this approach is that we do not try to infer if the redirect is supposed to be local or not. If we want to redirect to the local servlet context we can do it explicitly, and if we wish to do an absolute redirect then we can use the &lt;code&gt;noir.response/redirect&lt;/code&gt; directly.&lt;/p&gt;&lt;p&gt;With that out of the way, I'd like to cover using the servlet init function and accessing files located on the classpath of the servlet. This allows us to run a function once when our serlvet starts up. &lt;/p&gt;&lt;p&gt;For example, we might want to read in a configuration file and setup some environment parameters based on it. To do that we'll open up our &lt;code&gt;project.clj&lt;/code&gt; and add an &lt;code&gt;:init&lt;/code&gt; key to our map or ring parameters:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject my-website &amp;quot;0.1.0-SNAPSHOT&amp;quot;
            :description &amp;quot;my Noir website&amp;quot;
            :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                           &amp;#91;noir &amp;quot;1.3.0-beta3&amp;quot;&amp;#93;
                           &amp;#91;org.clojure/java.jdbc &amp;quot;0.2.3&amp;quot;&amp;#93;
                           &amp;#91;postgresql/postgresql &amp;quot;9.1-901.jdbc4&amp;quot;&amp;#93;
                           &amp;#91;joda-time &amp;quot;2.0&amp;quot;&amp;#93;&amp;#93;
            :dev-dependencies &amp;#91;&amp;#91;lein-ring &amp;quot;0.7.3&amp;quot;&amp;#93;&amp;#93;
            :ring {:handler my-website.server/handler

                   ;;initialization function which will be run 
                   ;;once when the servlet is loaded
                   :init my-website.config/init-config}
            :main my-website.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;update:&lt;/strong&gt; with Leiningen 2.0 you will need to use &lt;code&gt;:plugins&lt;/code&gt; instead of &lt;code&gt;:dev-dependencies&lt;/code&gt; to get &lt;code&gt;lein-ring&lt;/code&gt; to work correctly:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject my-website &amp;quot;0.1.0-SNAPSHOT&amp;quot;
            :description &amp;quot;my Noir website&amp;quot;
            :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                           &amp;#91;noir &amp;quot;1.3.0-beta3&amp;quot;&amp;#93;
                           &amp;#91;org.clojure/java.jdbc &amp;quot;0.2.3&amp;quot;&amp;#93;
                           &amp;#91;postgresql/postgresql &amp;quot;9.1-901.jdbc4&amp;quot;&amp;#93;
                           &amp;#91;joda-time &amp;quot;2.0&amp;quot;&amp;#93;&amp;#93;

            ;;lein 2
            :plugins &amp;#91;&amp;#91;lein-ring &amp;quot;0.7.5&amp;quot;&amp;#93;&amp;#93;
            ;;lein 1
            :dev-dependencies &amp;#91;&amp;#91;lein-ring &amp;quot;0.7.3&amp;quot;&amp;#93;&amp;#93;

            :ring {:handler my-website.server/handler

                   ;;initialization function which will be run 
                   ;;once when the servlet is loaded
                   :init my-website.config/init-config}
            :main my-website.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now we'll create a new namespace which the &lt;code&gt;:init&lt;/code&gt; key is pointing to, and create an &lt;code&gt;init-config&lt;/code&gt; function in it:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.config
  &amp;#40;:use clojure.java.io&amp;#41;&amp;#41;

&amp;#40;defn init-config &amp;#91;&amp;#93; 
  &amp;#40;println &amp;quot;servlet has been initialized&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If you build and deploy the application, the "servlet has been initialized" message is printed in the server log once after deployment. Now, let's add a configuration file in our &lt;code&gt;resources&lt;/code&gt; folder:&lt;pre&gt;&lt;code class="bash"&gt;touch my&amp;#95;webapp/resources/site.config
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;When we run &lt;code&gt;lein ring uberwar&lt;/code&gt; this file will be packaged under &lt;code&gt;/WEB-INF/classes/&lt;/code&gt; path in the servlet. To access this file we'll need to add the following function to our config namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def config-file &amp;quot;site.config&amp;quot;&amp;#41;

&amp;#40;defn load-config-file &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;url &amp;#40;.. 
              &amp;#40;Thread/currentThread&amp;#41; 
              getContextClassLoader 
              &amp;#40;findResource config-file&amp;#41;&amp;#41;&amp;#93; 
    &amp;#40;if &amp;#40;or &amp;#40;nil? url&amp;#41; 
            &amp;#40;.. url 
              getPath 
              &amp;#40;endsWith &amp;#40;str &amp;quot;jar!/&amp;quot; config-file&amp;#41;&amp;#41;&amp;#41;&amp;#41;
      &amp;#40;doto &amp;#40;new java.io.File config-file&amp;#41; 
        &amp;#40;.createNewFile&amp;#41;&amp;#41;
      url&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The &lt;code&gt;load-config-file&lt;/code&gt; function will get the context class loader and attempt to find the resource by name. If the resource is found we will get back a URL pointing to it. Unfortunately, if we're running as a standalone jar, we cannot modify the resource inside it. So, in case the URL is nil, meaning that the file was not found, or if it ends with "jar!/site.config" we will create a new file instead. When running standalone, the file will be created in the same folder as the jar.&lt;/p&gt;&lt;p&gt;Now that we have a function to read the configuration, let's load it so we can actually use it. To do that we will add an atom to hold the configuration, and update our init-config function as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def app-config &amp;#40;atom nil&amp;#41;&amp;#41;

&amp;#40;defn init-config &amp;#91;&amp;#93;
  &amp;#40;with-open
    &amp;#91;r &amp;#40;java.io.PushbackReader. &amp;#40;reader &amp;#40;load-config-file&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;if-let &amp;#91;config &amp;#40;read r nil nil&amp;#41;&amp;#93;
      &amp;#40;reset! app-config config&amp;#41;&amp;#41;&amp;#41;
  &amp;#40;println &amp;quot;servlet has been initialized&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In our &lt;code&gt;log-stats&lt;/code&gt; namespace the path to the logs is currently hard coded. Let's change it to read the path from our config file. We'll open our &lt;code&gt;resources/config&lt;/code&gt; and add the following to it:&lt;pre&gt;&lt;code class="clojure"&gt;{:log-path &amp;quot;logs/&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Then in our &lt;code&gt;log-stats&lt;/code&gt; namespace we'll change all references to "logs/" to (:log-path @app-config) instead:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.log-stats
  ...
  &amp;#40;:use ... my-website.config&amp;#41;&amp;#41;

&amp;#40;defpage &amp;#91;:post &amp;quot;/get-logs&amp;quot;&amp;#93; params  
  &amp;#40;response/json 
    &amp;#40;hits-per-second 
      &amp;#40;read-logs &amp;#40;last-log &amp;#40;:log-path @app-config&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;To ensure that the application still runs correctly standalone we will have to call &lt;code&gt;init-config&lt;/code&gt; in our &lt;code&gt;-main&lt;/code&gt; in the &lt;code&gt;server&lt;/code&gt; namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.server
  &amp;#40;:use my-website.config&amp;#41;
  ...&amp;#41;

&amp;#40;defn -main &amp;#91;&amp;amp; m&amp;#93;
  &amp;#40;let &amp;#91;mode &amp;#40;keyword &amp;#40;or &amp;#40;first m&amp;#41; :dev&amp;#41;&amp;#41;
        port &amp;#40;Integer. &amp;#40;get &amp;#40;System/getenv&amp;#41; &amp;quot;PORT&amp;quot; &amp;quot;8080&amp;quot;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;init-config&amp;#41;
    &amp;#40;server/start port {:mode mode
                        :ns 'my-website}&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now the log path can be specified in the &lt;code&gt;config&lt;/code&gt; file without having to rebuild and redeploy the application each time. Complete source for this section is available &lt;a href='https://github.com/yogthos/Noir-tutorial/commit/4b7d185b2aaa5e8af539344d9f1df677271ea44a'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Mon, 03 Sep 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-09-02-Noir-tutorial-part-6.html</guid><link>https://yogthos.net/posts/2012-09-02-Noir-tutorial-part-6.html</link><title>Noir tutorial - part 6</title><description>&lt;p&gt;In the &lt;a href='https://www.yogthos.net/blog/22'&gt;first part&lt;/a&gt; of the tutorial we've already seen how to run our application in standalone mode.  Here we will look at what we need to do to deploy it on an application server such as &lt;a href='http://glassfish.java.net/'&gt;Glassfish&lt;/a&gt;, &lt;a href='http://tomcat.apache.org/'&gt;Tomcat&lt;/a&gt;, &lt;a href='http://www.jboss.org/'&gt;jBoss&lt;/a&gt;, or &lt;a href='http://immutant.org/'&gt;Immutant&lt;/a&gt; which is a modification of jBoss geared specifically towards Clojure.&lt;/p&gt;&lt;p&gt;There are numerous reasons as to why you might want to do this. For example, an application server lets you run multiple applications at the same time. Another advantage is that the application server can take care of the configuration details, such as handling database connections. &lt;/p&gt;&lt;p&gt;When building real world applications, you will likely have separate dev/staging/prod configurations. Instead of having different builds for our application, we can instead configure our application servers appropriately for each environment. Then we can have a single build process which is much less error prone in my opinion. We can also configure CI, such as &lt;a href='http://jenkins-ci.org/'&gt;Jenkins&lt;/a&gt; to build our application and automatically deploy it to the server ensuring that we always have the latest code running.&lt;/p&gt;&lt;p&gt;Finally, if you plan on using a hosting provider, you may end up deploying on a shared application server as opposed to being able to run your application standalone. &lt;/p&gt;&lt;p&gt;Let's go over the prerequisites for building our application into a WAR and deploying it to a server. You will need to setup an application server of your choice for this section. I will be using Tomcat, but the steps will be similar for other servers as well. If you will be using Tomcat, then download the &lt;a href='http://apache.mirror.nexicom.net/tomcat/tomcat-7/v7.0.29/bin/apache-tomcat-7.0.29.zip'&gt;latest version&lt;/a&gt;. To start up the server you simply unpack the archive, navigate to the resulting directory, and run:&lt;pre&gt;&lt;code class="bash"&gt;chmod +x bin/catalina.sh
bin/catalina.sh start
Using CATALINA&amp;#95;BASE:   apache-tomcat-7.0.29
Using CATALINA&amp;#95;HOME:   apache-tomcat-7.0.29
Using CATALINA&amp;#95;TMPDIR: apache-tomcat-7.0.29/temp
Using JRE&amp;#95;HOME:        /Library/Java/Home
Using CLASSPATH:       apache-tomcat-7.0.29/bin/bootstrap.jar:apache-tomcat-7.0.29/bin/tomcat-juli.jar
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Your Tomcat should now be up and running and you can test it by navigating to &lt;a href='http://localhost:8080'&gt;localhost:8080&lt;/a&gt;: &lt;center&gt;&lt;img src="/files/tomcat.png" alt="tomcat" /&gt;&lt;/center&gt; With the application server running, let's prepare our application for deployment. First, we must ensure that the &lt;code&gt;server&lt;/code&gt; namespace requires all the namespaces in our views package, and has the &lt;code&gt;gen-class&lt;/code&gt; directive specified:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.server
  &amp;#40;:require &amp;#91;noir.server :as server&amp;#93;
            &amp;#91;my-website.views 
             common
             files
             log-stats
             users
             welcome&amp;#93;&amp;#41;     
  &amp;#40;:gen-class&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This will ensure that the server and the views are compiled during the build step, which is needed for them to be picked up by the application server when the application is deployed. Next, we will change &lt;code&gt;server/load-views&lt;/code&gt; call to &lt;code&gt;server/load-vews-ns&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;server/load-views-ns 'my-website.views&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If you used Leiningen 2 to create the project template, then &lt;code&gt;load-views-ns&lt;/code&gt; should already be set correctly.&lt;/p&gt;&lt;p&gt;Finally, we have to add a handler which will be used instead of the &lt;code&gt;-main&lt;/code&gt; when running on the application server:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def base-handler 
  &amp;#40;server/gen-handler 
    {:mode :prod, 
     :ns 'my-website 
     :session-cookie-attrs {:max-age 1800000}}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;It is possible to chain different handlers together. In our case, we will need a wrapper for our handler to prepend the servlet context to all the requests coming to our servlet. This is a workaround for a &lt;a href='https://github.com/noir-clojure/noir/issues/120'&gt;bug&lt;/a&gt; in the current version of Noir, which ignores it. Without this fix none of the redirects will work correctly as they will be routed to the base application server URL instead.&lt;/p&gt;&lt;p&gt;Each wrapper is a function which accepts the current handler, and returns a function which accepts a request, does something to it, and then return the result of calling  the handler on it. The result is in turn a handler itself, so we can chain as many wrappers together as we like. In our case we will override the &lt;code&gt;resolve-url&lt;/code&gt; function in &lt;code&gt;noir.options&lt;/code&gt; with one of our own making:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn fix-base-url &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;request&amp;#93;    
    &amp;#40;with-redefs &amp;#91;noir.options/resolve-url 
                  &amp;#40;fn &amp;#91;url&amp;#93;                    
                    ;prepend context to the relative URLs
                    &amp;#40;if &amp;#40;.contains url &amp;quot;://&amp;quot;&amp;#41; 
                      url &amp;#40;str &amp;#40;:context request&amp;#41; url&amp;#41;&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;handler request&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Above, we will check that the URL contains "://", if not then we treat it as a local URL and prepend the servlet context to it. Now we have to hook it up with our initial handler to produce the final request handler for our servlet:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def handler &amp;#40;-&amp;gt; base-handler fix-base-url&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now that we've created our handler, we need to point our &lt;code&gt;project.clj&lt;/code&gt; to it:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject my-website &amp;quot;0.1.0-SNAPSHOT&amp;quot;
            :description &amp;quot;my Noir website&amp;quot;
            :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                           &amp;#91;noir &amp;quot;1.3.0-beta3&amp;quot;&amp;#93;
                           &amp;#91;org.clojure/java.jdbc &amp;quot;0.2.3&amp;quot;&amp;#93;
                           &amp;#91;postgresql/postgresql &amp;quot;9.1-901.jdbc4&amp;quot;&amp;#93;&amp;#93;
            :dev-dependencies &amp;#91;&amp;#91;lein-ring &amp;quot;0.7.3&amp;quot;&amp;#93;&amp;#93;
            :ring {:handler my-website.server/handler}
            :main my-website.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We've also added &lt;code&gt;lein-ring&lt;/code&gt; plugin to our &lt;code&gt;dev-dependencies&lt;/code&gt;, this is required for generating the WAR artifact from our build. Under the &lt;code&gt;:ring&lt;/code&gt; key we set the &lt;code&gt;:handler&lt;/code&gt; to the one we defined above.&lt;/p&gt;&lt;p&gt;Let's test that our project builds correctly and produces a working WAR by running the following commands from the temrinal:&lt;pre&gt;&lt;code class="bash"&gt;lein deps
Copying 29 files to Noir-tutorial/lib
&amp;#91;INFO&amp;#93; snapshot thneed:thneed:1.0.0-SNAPSHOT: checking for updates from clojars
&amp;#91;INFO&amp;#93; snapshot thneed:thneed:1.0.0-SNAPSHOT: checking for updates from central
Copying 5 files to Noir-tutorial/lib/dev

lein ring uberwar
Compiling my-website.server
Compilation succeeded.
Created Noir-tutorial/my-website-0.1.0-SNAPSHOT-standalone.war
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If we have our application server running, then we should be able to simply drop this WAR in its deployment folder and the server will take care of the rest. If we're using Tomcat, then we have to copy it to the &lt;code&gt;webapps&lt;/code&gt; folder:&lt;pre&gt;&lt;code class="bash"&gt;cp my-website-0.1.0-SNAPSHOT-standalone.war ../apache-tomcat-7/webapps/my-website.war
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Make sure to replace the &lt;code&gt;../apache-tomcat-7&lt;/code&gt; above with the location of your Tomcat server. We can now take a look at our server log and see that the application was deployed successfully:&lt;pre&gt;&lt;code class="bash"&gt;tail -f logs/catalina.out
...
INFO: Deploying web application archive apache-tomcat-7.0.29/webapps/my-website.war
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now let's navigate to &lt;a href='http://localhost:8080/my-website'&gt;localhost:8080/my-website&lt;/a&gt; and we should see our application running: &lt;center&gt;&lt;img src="/files/website-on-tomcat.png" alt="website" /&gt;&lt;/center&gt;&lt;/p&gt;&lt;p&gt;One last thing to note is that any Ajax calls in our pages will have to use the servlet context to be resolved correctly. A workaround for this issue is to use &lt;code&gt;noir.request/ring-request&lt;/code&gt; to check if a context is present and set it as a hidden field on the page:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.log-stats
  &amp;#40;:require &amp;#91;my-website.views.common :as common&amp;#93;
            &amp;#91;noir.request :as request&amp;#93;
            &amp;#91;noir.response :as response&amp;#93;&amp;#41;
  &amp;#40;:use clojure.java.io hiccup.page hiccup.form noir.core&amp;#41;
  &amp;#40;:import java.text.SimpleDateFormat&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/access-chart&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;common/basic-layout
    &amp;#40;include-js &amp;quot;/js/site.js&amp;quot;&amp;#41;
    &amp;#40;hidden-field &amp;quot;context&amp;quot; &amp;#40;:context &amp;#40;request/ring-request&amp;#41;&amp;#41;&amp;#41;
    &amp;#91;:div#hits-by-time &amp;quot;loading...&amp;quot;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Then we can check this value and prepend it to the URL when making our Ajax query:&lt;pre&gt;&lt;code class="javascript"&gt;$&amp;#40;document&amp;#41;.ready&amp;#40;function&amp;#40;&amp;#41;{	
    var context = $&amp;#40;'#context'&amp;#41;.val&amp;#40;&amp;#41;;
    var url = '/get-logs';
    if &amp;#40;context&amp;#41; url = context + url;
    var options = {xaxis: { mode: &amp;quot;time&amp;quot;, 
                            minTickSize: &amp;#91;1, &amp;quot;minute&amp;quot;&amp;#93;}};
	$.post&amp;#40;url, function&amp;#40;data&amp;#41;{
	    $.plot&amp;#40;$&amp;#40;&amp;quot;#hits-by-time&amp;quot;&amp;#41;, &amp;#91;data&amp;#93;, options&amp;#41;;
	    }&amp;#41;;		
}&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As usual, the complete code for this section is available &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/e5964216fd009239d1494c7cfcb7888f4f6b374d'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 02 Sep 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-09-01-Noir-tutorial-part-5.html</guid><link>https://yogthos.net/posts/2012-09-01-Noir-tutorial-part-5.html</link><title>Noir tutorial - part 5</title><description>&lt;p&gt;In this section we will learn how to add some JavaScript to the application and how to use Ajax to query the service. We'll use  the &lt;a href='http://code.google.com/p/flot/'&gt;flot&lt;/a&gt; &lt;a href='http://jquery.com/'&gt;jQuery&lt;/a&gt; library to display the usage statistics for our site. When the page loads it will call the service which will parse today's access log and return a JSON response which will be used to generate the chart.&lt;/p&gt;&lt;p&gt;First, let's generate some sample usage data in the apache &lt;a href='http://httpd.apache.org/docs/1.3/logs.html#combined'&gt;combined log format&lt;/a&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn gen-log-line &amp;#91;&amp;#91;cur-time&amp;#93;&amp;#93; 
  &amp;#40;let &amp;#91;new-time &amp;#40;doto &amp;#40;new java.util.Date&amp;#41; &amp;#40;.setTime &amp;#40;+ &amp;#40;.getTime cur-time&amp;#41; &amp;#40;rand-int 5000&amp;#41;&amp;#41;&amp;#41;&amp;#41;
        browsers &amp;#91;&amp;quot;\&amp;quot;Mozilla/5.0 &amp;#40;Macintosh; Intel Mac OS X 10.7; rv:15.0&amp;#41; Gecko/20100101 Firefox/15.0\&amp;quot;&amp;quot;
                  &amp;quot;\&amp;quot;Mozilla/5.0 &amp;#40;Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91&amp;#41; AppleWebKit/533.1 &amp;#40;KHTML, like Gecko&amp;#41;\&amp;quot;&amp;quot;
                  &amp;quot;\&amp;quot;Mozilla/5.0 &amp;#40;X11; Linux i686&amp;#41; AppleWebKit/536.11 &amp;#40;KHTML, like Gecko&amp;#41; Chrome/20.0.1132.57 Safari/536.11\&amp;quot;&amp;quot;&amp;#93;&amp;#93;
    &amp;#91;new-time
     &amp;#40;-&amp;gt;&amp;gt;
       &amp;#40;concat
         &amp;#40;interpose &amp;quot;.&amp;quot; &amp;#40;take 4 &amp;#40;repeatedly #&amp;#40;rand-int 255&amp;#41;&amp;#41;&amp;#41;&amp;#41;
         &amp;#91;&amp;quot; - - &amp;#91;&amp;quot; &amp;#40;.format &amp;#40;new java.text.SimpleDateFormat 
                                  &amp;quot;dd/MMM/YYYY:HH:mm:ss ZZZZ&amp;quot;&amp;#41; new-time&amp;#41; &amp;quot;&amp;#93;&amp;quot;&amp;#93;
         &amp;#91;&amp;quot; \&amp;quot;GET /files/test.jpg\&amp;quot; &amp;quot; 200 &amp;quot; &amp;quot; &amp;#40;rand-int 4000&amp;#41; &amp;quot; \&amp;quot;http://my-website/files/test.jpg\&amp;quot; &amp;quot; &amp;#40;first &amp;#40;shuffle browsers&amp;#41;&amp;#41;&amp;#93;&amp;#41;
       &amp;#40;apply str&amp;#41;&amp;#41;&amp;#93;&amp;#41;&amp;#41;
 
&amp;#40;defn gen-test-logs &amp;#91;size&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; &amp;#40;gen-log-line &amp;#91;&amp;#40;new java.util.Date&amp;#41;&amp;#93;&amp;#41;
    &amp;#40;iterate gen-log-line&amp;#41;
    &amp;#40;take size&amp;#41;
    &amp;#40;map second&amp;#41;
    &amp;#40;interpose &amp;quot;\n&amp;quot;&amp;#41;
    &amp;#40;apply str&amp;#41;&amp;#41;&amp;#41;

&amp;#40;spit &amp;quot;test-log.txt&amp;quot; &amp;#40;gen-test-logs 500&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If you run the above in the REPL, you will end up with &lt;code&gt;test-log.txt&lt;/code&gt; file which should have the contents that look roughly like the following:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;120.138.220.117 - - &amp;#91;31/Aug/2012:21:06:47 -0400&amp;#93; &amp;quot;GET /files/test.jpg&amp;quot; 200 3989 &amp;quot;http://my-website/files/test.jpg&amp;quot; &amp;quot;Mozilla/5.0 &amp;#40;Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91&amp;#41; AppleWebKit/533.1 &amp;#40;KHTML, like Gecko&amp;#41;&amp;quot;
201.59.151.159 - - &amp;#91;31/Aug/2012:21:06:49 -0400&amp;#93; &amp;quot;GET /files/test.jpg&amp;quot; 200 1729 &amp;quot;http://my-website/files/test.jpg&amp;quot; &amp;quot;Mozilla/5.0 &amp;#40;Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91&amp;#41; AppleWebKit/533.1 &amp;#40;KHTML, like Gecko&amp;#41;&amp;quot;
122.39.249.88 - - &amp;#91;31/Aug/2012:21:06:51 -0400&amp;#93; &amp;quot;GET /files/test.jpg&amp;quot; 200 1650 &amp;quot;http://my-website/files/test.jpg&amp;quot; &amp;quot;Mozilla/5.0 &amp;#40;Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91&amp;#41; AppleWebKit/533.1 &amp;#40;KHTML, like Gecko&amp;#41;&amp;quot;
...
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now that we have a log file with some access logs in it, we'll parse those logs into structured data to make them easier to analyze:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn round-ms-down-to-nearest-sec &amp;#91;date&amp;#93;
  &amp;#40;let &amp;#91;date &amp;#40;.parse 
               &amp;#40;new SimpleDateFormat 
                    &amp;quot;dd/MMM/yyyy:HH:mm:ss zzzzz&amp;quot;&amp;#41; 
               date&amp;#41;&amp;#93; 
    &amp;#40; &amp;#42; 1000 &amp;#40;quot &amp;#40;.getTime date&amp;#41; 1000&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn parse-line &amp;#91;line&amp;#93;
  {:ip &amp;#40;re-find #&amp;quot;\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b&amp;quot; line&amp;#41; 
   :access-time &amp;#40;round-ms-down-to-nearest-sec 
                  &amp;#40;second &amp;#40;re-find #&amp;quot;\&amp;#91;&amp;#40;.&amp;#42;?&amp;#41;\&amp;#93;&amp;quot; line&amp;#41;&amp;#41;&amp;#41; }&amp;#41;

&amp;#40;defn read-logs &amp;#91;file&amp;#93; 
  &amp;#40;with-open &amp;#91;rdr &amp;#40;reader file&amp;#41;&amp;#93; 
    &amp;#40;doall &amp;#40;map parse-line &amp;#40;line-seq rdr&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Above, we simply return a map containing the ip and the access-time for each line in the logs. Using this map we can aggregate the logs by IP to get unique hits, and then group them by time to see hits per second:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn hits-per-second &amp;#91;logs&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; logs 
    &amp;#40;group-by :ip&amp;#41;
    &amp;#40;map #&amp;#40;first &amp;#40;second %&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;group-by :access-time&amp;#41;    
    &amp;#40;map &amp;#40;fn &amp;#91;&amp;#91;t hits&amp;#93;&amp;#93; &amp;#91;t &amp;#40;count hits&amp;#41;&amp;#93;&amp;#41;&amp;#41;
    &amp;#40;sort-by first&amp;#41;&amp;#41;&amp;#41;

&amp;#40;hits-per-second &amp;#40;read-logs &amp;quot;test-log.txt&amp;quot;&amp;#41;&amp;#41;
=&amp;gt;&amp;#40;&amp;#91;1346460948000 2&amp;#93; &amp;#91;1346460949000 1&amp;#93; &amp;#91;1346460954000 1&amp;#93; ...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We now have a list where each element has a time rounded down to the nearest second with a number of unique hits associated with it. This happens to be the exact format that &lt;a href='http://people.iola.dk/olau/flot/examples/time.html'&gt;flot time series is expecting&lt;/a&gt;. We can serve the this data as JSON by using &lt;code&gt;noir.response/json&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;#91;:post &amp;quot;/get-logs&amp;quot;&amp;#93; params
  &amp;#40;response/json &amp;#40;hits-per-second &amp;#40;read-logs &amp;quot;test-log.txt&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Finally, we will have to create the page with a placeholder where our chart will be displayed and reference a Js file which will create shortly:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/access-chart&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;common/basic-layout
    &amp;#40;include-js &amp;quot;/js/site.js&amp;quot;&amp;#41;
    &amp;#91;:div#hits-by-time &amp;quot;loading...&amp;quot;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We will also have to add the CSS to set the height and width of the chart as well as the margin:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;#hits-by-time {
        margin: 25px;
	width: 400px;
	height: 400px;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;All that's left to do is to add the JavaScript which will get the stats and display them. To do that we'll have to &lt;a href='http://code.google.com/p/flot/downloads/list'&gt;download flot&lt;/a&gt;, and put &lt;code&gt;jquery.flot.min.js&lt;/code&gt; in the &lt;code&gt;resources/public/js&lt;/code&gt; folder.&lt;/p&gt;&lt;p&gt;Then we will include it and jQuery in the header of our page. This can be done using &lt;code&gt;include-js&lt;/code&gt; from Hiccup. We'll open up our &lt;code&gt;common&lt;/code&gt; namespace and modify the &lt;code&gt;basic-layout&lt;/code&gt; as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpartial basic-layout &amp;#91;&amp;amp; content&amp;#93;
  &amp;#40;html5
    &amp;#91;:head
     &amp;#91;:title &amp;quot;my-website&amp;quot;&amp;#93;
     &amp;#40;include-css &amp;quot;/css/reset.css&amp;quot;&amp;#41;
     &amp;#40;include-js &amp;quot;http://code.jquery.com/jquery-1.7.2.min.js&amp;quot;
                 &amp;quot;/js/jquery.flot.min.js&amp;quot;
                 &amp;quot;/js/site.js&amp;quot;&amp;#41;&amp;#93;
    &amp;#91;:body content&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now let's create a &lt;code&gt;site.js&lt;/code&gt; file in &lt;code&gt;resources/public/js&lt;/code&gt; and add the following to it:&lt;pre&gt;&lt;code class="javascript"&gt;$&amp;#40;document&amp;#41;.ready&amp;#40;function&amp;#40;&amp;#41;{	
    var options = {xaxis: {mode: &amp;quot;time&amp;quot;, 
                           minTickSize: &amp;#91;1, &amp;quot;minute&amp;quot;&amp;#93;}};
	$.post&amp;#40;'/get-logs', function&amp;#40;data&amp;#41;{
	    $.plot&amp;#40;$&amp;#40;&amp;quot;#hits-by-time&amp;quot;&amp;#41;, &amp;#91;data&amp;#93;, options&amp;#41;;
	    }&amp;#41;;		
}&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If all went well, then when we start up our site and browse to &lt;a href='http://localhost:8080/access-chart'&gt;localhost:8080/access-chart&lt;/a&gt;. we should see something like this: &lt;center&gt;&lt;img src="/files/access-chart.png" alt="access chart" /&gt;&lt;/center&gt;&lt;/p&gt;&lt;p&gt;Finally, &lt;a href='http://yogthos.net/stats-viewer/'&gt;here's&lt;/a&gt; some fun daily stats for the blog generated using the above approach. The sources for this part of the tutorial can be found &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/6bd33d6121edccc1406b5e854e5c980a9f5d30dc'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 01 Sep 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-25-Noir-tutorial-part-4.html</guid><link>https://yogthos.net/posts/2012-08-25-Noir-tutorial-part-4.html</link><title>Noir tutorial - part 4</title><description>&lt;h3 id="securing&amp;#95;pages"&gt;Securing Pages&lt;/h3&gt;&lt;p&gt;This part of the tutorial will focus on controlling page visibility, form validation, and handling complex form parameters. In the &lt;a href='http://yogthos.net/blog/25-Noir+tutorial+-+part+3'&gt;last section&lt;/a&gt; we added support for uploading files, it would make sense to make the &lt;code&gt;upload&lt;/code&gt; page private. This way only registered users can access it.&lt;/p&gt;&lt;p&gt;Noir provides a &lt;a href='http://webnoir.org/autodoc/1.2.1/noir.core-api.html#noir.core/pre-route'&gt;&lt;code&gt;pre-route&lt;/code&gt;&lt;/a&gt; macro for handling this. However, we will not be using it for a couple of reasons. &lt;/p&gt;&lt;p&gt;First, there is currently a bug in Noir, where &lt;code&gt;pre-route&lt;/code&gt; ignores the servlet context, meaning that unless our application is deployed to "/" the routing will not work as expected. The second reason is that you have to remember to add a &lt;code&gt;pre-route&lt;/code&gt; entry for each page that you want to make private. &lt;/p&gt;&lt;p&gt;A better solution, in my opinion, is to simply write a macro which will behave the same way as defpage, but will check if there is a user in session and redirect to "/" otherwise. With this approach we make pages private right in their definition. Let's open up our &lt;code&gt;common&lt;/code&gt; namespace and add the macro:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro private-page &amp;#91;path params &amp;amp; content&amp;#93;
  `&amp;#40;noir.core/defpage 
     &amp;#126;path 
     &amp;#126;params 
     &amp;#40;if &amp;#40;session/get :user&amp;#41; 
      &amp;#40;do &amp;#126;@content&amp;#41; 
      &amp;#40;resp/redirect &amp;quot;/&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As you can see it has exactly same signature as &lt;code&gt;defpage&lt;/code&gt; and calls it  internally as you normally would, but only adds the content if the session contains a user, otherwise the page will redirect to "/".&lt;/p&gt;&lt;p&gt;Now, we'll go to our &lt;code&gt;files&lt;/code&gt; namespace and mark all the pages as private:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;common/private-page &amp;quot;/upload&amp;quot; {:keys &amp;#91;info&amp;#93;}
  ...&amp;#41;

&amp;#40;common/private-page &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93; {:keys &amp;#91;file&amp;#93;}
  ...&amp;#41;

&amp;#40;common/private-page &amp;quot;/files/:name&amp;quot; {:keys &amp;#91;name&amp;#93;} 
  ...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Let's test that it works by navigating to &lt;a href='http://localhost:8080/upload'&gt;localhost:8080/upload&lt;/a&gt; without logging in. We should be redirected right back to "/".&lt;/p&gt;&lt;h3 id="site&amp;#95;navigation"&gt;Site navigation&lt;/h3&gt;&lt;p&gt;Since we now have a couple of pages that we will be navigating we can add a navigation menu in our &lt;code&gt;common&lt;/code&gt; namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn menu &amp;#91;&amp;#93;
  &amp;#91;:div.menu
   &amp;#91;:ul
    &amp;#91;:li &amp;#40;form-to &amp;#91;:post &amp;quot;/logout&amp;quot;&amp;#93; &amp;#40;submit-button &amp;quot;logout&amp;quot;&amp;#41;&amp;#41;&amp;#93;    
    &amp;#91;:li &amp;#40;link-to &amp;quot;/upload&amp;quot; &amp;quot;my files&amp;quot;&amp;#41;&amp;#93;
    &amp;#91;:li &amp;#40;link-to &amp;quot;/&amp;quot; &amp;quot;home&amp;quot;&amp;#41;&amp;#93;&amp;#93;&amp;#93;&amp;#41;

&amp;#40;defpartial layout &amp;#91;&amp;amp; content&amp;#93;
  &amp;#40;html5
    &amp;#91;:head
     &amp;#91;:title &amp;quot;my-website&amp;quot;&amp;#93;
     &amp;#40;include-css &amp;quot;/css/reset.css&amp;quot;&amp;#41;&amp;#93;
    &amp;#91;:body               
     &amp;#40;if-let &amp;#91;user &amp;#40;session/get :user&amp;#41;&amp;#93;
       &amp;#91;:div
        &amp;#40;menu&amp;#41;
        &amp;#91;:h2 &amp;quot;welcome &amp;quot; user&amp;#93;&amp;#93;
       &amp;#91;:div.login
        &amp;#40;login-form&amp;#41; &amp;#91;:p &amp;quot;or&amp;quot;&amp;#93; &amp;#40;link-to &amp;quot;/signup&amp;quot; &amp;quot;sign up&amp;quot;&amp;#41;&amp;#93;&amp;#41;     
     content&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now, if a user logs in, they will see the navigation menu and can either select home or their files page. To keep things clean we'll also move the &lt;code&gt;logout&lt;/code&gt; link into our menu. This is functional, but it's rather ugly, so let's add some CSS to make it a bit nicer. We'll open up our stock &lt;code&gt;resources/public/css/reset.css&lt;/code&gt; which was generated for our site and add the following to it:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;.menu ul {
    list-style: none;
    margin: 0;
    padding-left: 0;
}
.menu li {
    float: right;
    position: relative;
    margin-right: 20px;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Things should look much better now: &lt;center&gt; &lt;img src="/files/menu.png" alt="menu" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="input&amp;#95;validation"&gt;Input Validation&lt;/h3&gt;&lt;p&gt;Next, let's reexamine our sign up page, previously we didn't bother doing any validation when creating a new user, so let's add some now. Noir provides a simple way to validate input fields via the &lt;a href='http://www.webnoir.org/autodoc/1.2.1/noir.validation-api.html'&gt;&lt;code&gt;noir.validation&lt;/code&gt;&lt;/a&gt; namespace. Let's open the &lt;code&gt;users&lt;/code&gt; namespace and add it in:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.users
  &amp;#40;:use &amp;#91;noir.core&amp;#93;
        hiccup.core hiccup.form&amp;#41;
  &amp;#40;:require &amp;#91;my-website.views.common :as common&amp;#93;
            &amp;#91;my-website.models.db :as db&amp;#93;
            &amp;#91;noir.util.crypt :as crypt&amp;#93;
            &amp;#91;noir.session :as session&amp;#93;
            &amp;#91;noir.response :as resp&amp;#93;
            &amp;#91;noir.validation :as vali&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Next we will create our validation function:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn valid? &amp;#91;{:keys &amp;#91;handle pass pass1&amp;#93;}&amp;#93;
  &amp;#40;vali/rule &amp;#40;vali/has-value? handle&amp;#41;
             &amp;#91;:handle &amp;quot;user ID is required&amp;quot;&amp;#93;&amp;#41;
  &amp;#40;vali/rule &amp;#40;vali/min-length? pass 5&amp;#41;
             &amp;#91;:pass &amp;quot;password must be at least 5 characters&amp;quot;&amp;#93;&amp;#41;  
  &amp;#40;vali/rule &amp;#40;= pass pass1&amp;#41;
             &amp;#91;:pass &amp;quot;entered passwords do not match&amp;quot;&amp;#93;&amp;#41;
  &amp;#40;not &amp;#40;vali/errors? :handle :pass :pass1&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The function will check that all the fields conform to the rules, such as user id being provided, minimum password length, and that retyped password matches the original. The rules have the following form:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;rule validator &amp;#91;:filed-name &amp;quot;error message&amp;quot;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;where the validator must return a boolean. We'll also need a helper for displaying the error on the page:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpartial error-item &amp;#91;&amp;#91;first-error&amp;#93;&amp;#93;
  &amp;#91;:p.error first-error&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Next we will update our &lt;code&gt;signup&lt;/code&gt; page to show the errors generated by the validator:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/signup&amp;quot; {:keys &amp;#91;handle error&amp;#93;}
  &amp;#40;common/layout
    &amp;#91;:div.error error&amp;#93;
    &amp;#40;form-to &amp;#91;:post &amp;quot;/signup&amp;quot;&amp;#93;
             &amp;#40;vali/on-error :handle error-item&amp;#41;
             &amp;#40;label &amp;quot;user-id&amp;quot; &amp;quot;user id&amp;quot;&amp;#41;
             &amp;#40;text-field &amp;quot;handle&amp;quot; handle&amp;#41;
             &amp;#91;:br&amp;#93;
             &amp;#40;vali/on-error :pass error-item&amp;#41;
             &amp;#40;label &amp;quot;pass&amp;quot; &amp;quot;password&amp;quot;&amp;#41;
             &amp;#40;password-field &amp;quot;pass&amp;quot;&amp;#41;             
             &amp;#91;:br&amp;#93;
             &amp;#40;vali/on-error :pass1 error-item&amp;#41;
             &amp;#40;label &amp;quot;pass1&amp;quot; &amp;quot;retype password&amp;quot;&amp;#41;
             &amp;#40;password-field &amp;quot;pass1&amp;quot;&amp;#41;             
             &amp;#91;:br&amp;#93;
             &amp;#40;submit-button &amp;quot;create account&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;All we have to do here is add &lt;code&gt;on-error&lt;/code&gt; statements for each field we're validating. Finally, we'll have to update the &lt;code&gt;POST&lt;/code&gt; part of the page, to call the validator and return the errors:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;#91;:post &amp;quot;/signup&amp;quot;&amp;#93; user
  &amp;#40;if &amp;#40;valid? user&amp;#41;
    &amp;#40;try 
      &amp;#40;db/add-user &amp;#40;update-in &amp;#40;dissoc user :pass1&amp;#41; &amp;#91;:pass&amp;#93; crypt/encrypt&amp;#41;&amp;#41;
      &amp;#40;resp/redirect &amp;quot;/&amp;quot;&amp;#41;
      &amp;#40;catch Exception ex
        &amp;#40;render &amp;quot;/signup&amp;quot; &amp;#40;assoc user :error &amp;#40;.getMessage ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;render &amp;quot;/signup&amp;quot; user&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This should give you a basic idea of how to validate input using Noir, and more details about validation can be found on the &lt;a href='http://www.webnoir.org/tutorials/forms'&gt;official site&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;One thing you'll notice that when we navigate to the &lt;code&gt;signup&lt;/code&gt; page, we still see the login option as well as the link to sign up: &lt;center&gt; &lt;img src="/files/signup1.png" alt="sign up" /&gt; &lt;/center&gt; This is because our layout adds these to every page. We can fix this by splitting &lt;code&gt;layout&lt;/code&gt; in the &lt;code&gt;common&lt;/code&gt; namespace as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpartial basic-layout &amp;#91;&amp;amp; content&amp;#93;
  &amp;#40;html5
    &amp;#91;:head
     &amp;#91;:title &amp;quot;my-website&amp;quot;&amp;#93;
     &amp;#40;include-css &amp;quot;/css/reset.css&amp;quot;&amp;#41;&amp;#93;
    &amp;#91;:body content&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defpartial layout &amp;#91;&amp;amp; content&amp;#93;  
  &amp;#40;basic-layout 
    &amp;#91;:div
     &amp;#40;if-let &amp;#91;user &amp;#40;session/get :user&amp;#41;&amp;#93;      
       &amp;#91;:div
        &amp;#40;menu&amp;#41;
        &amp;#91;:h2 &amp;quot;welcome &amp;quot; user&amp;#93;&amp;#93;
       &amp;#91;:div
        &amp;#91;:div.login
         &amp;#40;login-form&amp;#41; 
         &amp;#91;:p &amp;quot;or&amp;quot;&amp;#93; 
         &amp;#40;link-to &amp;quot;/signup&amp;quot; &amp;quot;sign up&amp;quot;&amp;#41;&amp;#93;&amp;#93;&amp;#41;
     content&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Then we simply change:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/signup&amp;quot; {:keys &amp;#91;handle error&amp;#93;}
  &amp;#40;common/layout
  ...&amp;#41;

&amp;#40;defpage &amp;quot;/signup&amp;quot; {:keys &amp;#91;handle error&amp;#93;}
  &amp;#40;common/basic-layout
  ...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Another clean up item is to make our form items aligned, to do that we can use the following bit of CSS:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;label {
    margin-left: 10px;
    width:120px; 
    float:left;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The sign up page should now look as follows: &lt;center&gt; &lt;img src="/files/signup2.png" alt="sign up" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="complex&amp;#95;form&amp;#95;items"&gt;Complex Form Items&lt;/h3&gt;&lt;p&gt;Now that we've cleaned up our &lt;code&gt;singup&lt;/code&gt; page, we'll turn our attention back to file management. We'll add the ability for the user to filter files by their type. To do that we will first create a function in our &lt;code&gt;db&lt;/code&gt; namespace to get all the file types from our database:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn file-types &amp;#91;&amp;#93;
  &amp;#40;map :type &amp;#40;db-read &amp;quot;select distinct type from file&amp;quot;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Then in our &lt;code&gt;files&lt;/code&gt; namespace we will create a new helper called &lt;code&gt;select-files-by-type&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn select-files-by-type &amp;#91;&amp;#93;  
  &amp;#40;let &amp;#91;file-types &amp;#40;db/file-types&amp;#41;&amp;#93; 
    &amp;#40;form-to &amp;#91;:post &amp;quot;/show-files&amp;quot;&amp;#93;
             &amp;quot;select file types to show&amp;quot;
             &amp;#40;into 
               &amp;#40;with-group &amp;quot;file-types&amp;quot;&amp;#41;
               &amp;#40;for &amp;#91;type file-types&amp;#93;
                 &amp;#91;:div 
                  type
                 &amp;#40;check-box type&amp;#41;&amp;#93;&amp;#41;&amp;#41;
             &amp;#40;submit-button &amp;quot;show files&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;which we will add to our "/upload" page:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;common/private-page &amp;quot;/upload&amp;quot; {:keys &amp;#91;info&amp;#93;}
  &amp;#40;common/layout       
    &amp;#91;:h2.info info&amp;#93;
    &amp;#40;select-files-by-type&amp;#41;
    &amp;#40;list-files&amp;#41;
    &amp;#40;form-to {:enctype &amp;quot;multipart/form-data&amp;quot;}
             &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93;
             &amp;#40;label :file &amp;quot;File to upload&amp;quot;&amp;#41;
             &amp;#40;file-upload :file&amp;#41;
             &amp;#91;:br&amp;#93;
             &amp;#40;submit-button &amp;quot;upload&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This function will read the file types from the database and create a checkbox group from them. When we hit submit we'll see something like the following in our params:&lt;pre&gt;&lt;code class="clojure"&gt;{&amp;quot;image/png&amp;quot; &amp;quot;true&amp;quot;, &amp;quot;image/jpeg&amp;quot; &amp;quot;true&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Where the value of each selected checkbox will appear as a key in the params map with the value of "true". We will now have to update our &lt;code&gt;list-files&lt;/code&gt; function to accept optional file type restriction and in turn pass it to &lt;code&gt;list-files&lt;/code&gt; in &lt;code&gt;db&lt;/code&gt; namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn list-files &amp;#91;&amp;amp; &amp;#91;types&amp;#93;&amp;#93;  
  &amp;#40;into &amp;#91;:ul&amp;#93;
        &amp;#40;for &amp;#91;name &amp;#40;db/list-files types&amp;#41;&amp;#93;             
          &amp;#91;:li.file-link &amp;#40;link-to &amp;#40;str &amp;quot;/files/&amp;quot; name&amp;#41; name&amp;#41; 
           &amp;#91;:span &amp;quot;  &amp;quot;&amp;#93; 
           &amp;#91;:div.file&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The following changes will have to be made to retrieve files based on type:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn params-query &amp;#91;params&amp;#93;
  &amp;#40;apply str &amp;#40;interpose &amp;quot;, &amp;quot; &amp;#40;repeat &amp;#40;count params&amp;#41; &amp;quot;?&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn list-files &amp;#91;&amp;amp; &amp;#91;types&amp;#93;&amp;#93;
  &amp;#40;map :name 
       &amp;#40;if types
         &amp;#40;apply &amp;#40;partial db-read &amp;#40;str &amp;quot;select name from file where type in &amp;#40;&amp;quot; &amp;#40;params-query types&amp;#41; &amp;quot;&amp;#41;&amp;quot;&amp;#41;&amp;#41; types&amp;#41;
         &amp;#40;db-read &amp;quot;select name from file&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The &lt;code&gt;params-query&lt;/code&gt; helper will create an appropriate WHERE clause based on the number of types we pass in, and &lt;code&gt;list-files&lt;/code&gt; will now check if types have been passed in and create the appropriate query.  Finally, we'll add a new page which will display the selected files:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;common/private-page &amp;#91;:post &amp;quot;/show-files&amp;quot;&amp;#93; params
  &amp;#40;let &amp;#91;file-types &amp;#40;keys params&amp;#41;&amp;#93; 
    &amp;#40;common/layout 
      &amp;#91;:h2 &amp;quot;showing files types &amp;quot; 
       &amp;#40;apply str &amp;#40;interpose &amp;quot;, &amp;quot; file-types&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;list-files file-types&amp;#41;
      &amp;#40;link-to &amp;quot;/upload&amp;quot; &amp;quot;back&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The "/upload" page should now look as follows: &lt;center&gt; &lt;img src="/files/file-upload1.png" alt="file upload" /&gt; &lt;/center&gt; When we select some files and hit "show files" button we should see our new "show-files" page: &lt;center&gt; &lt;img src="/files/show-files.png" alt="file upload" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="summary"&gt;Summary&lt;/h3&gt;&lt;p&gt;In this section we covered the following topics:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;restricting access to pages&lt;/li&gt;&lt;li&gt;creating a navigation menu&lt;/li&gt;&lt;li&gt;input validation&lt;/li&gt;&lt;li&gt;handling inputs from multi part items such as check boxes&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The complete code for this section is available &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/ee1bd8aaa90b8144015201bf8fc5a99f7d007e57'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 25 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-22-Noir-tutorial-part-3.html</guid><link>https://yogthos.net/posts/2012-08-22-Noir-tutorial-part-3.html</link><title>Noir tutorial - part 3</title><description>&lt;p&gt;&lt;a href='http://yogthos.net/blog/23-Noir+tutorial+-+part+2'&gt;Last time&lt;/a&gt; we created a database to store users, and created pages allowing users to create new accounts and login. This time we'll look at how we can allow users to upload files to the server and how to serve them back using the proper content type. To make things easy, we'll stick our files in the database, so let's design a table to hold them:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn create-file-table &amp;#91;&amp;#93;
  &amp;#40;sql/with-connection 
    db
    &amp;#40;sql/create-table
      :file
      &amp;#91;:type &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;
      &amp;#91;:name &amp;quot;varchar&amp;#40;50&amp;#41;&amp;quot;&amp;#93;
      &amp;#91;:data &amp;quot;bytea&amp;quot;&amp;#93;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;if we run the above in the REPL a file table should be created. We'll now need a few helper functions to read the list of files and add new files to the table:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn to-byte-array &amp;#91;f&amp;#93;  
  &amp;#40;with-open &amp;#91;input &amp;#40;new java.io.FileInputStream f&amp;#41;
              buffer &amp;#40;new java.io.ByteArrayOutputStream&amp;#41;&amp;#93;
    &amp;#40;clojure.java.io/copy input buffer&amp;#41;
    &amp;#40;.toByteArray buffer&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn store-file &amp;#91;{:keys &amp;#91;tempfile filename content-type&amp;#93;}&amp;#93;
  &amp;#40;sql/with-connection 
    db
    &amp;#40;sql/update-or-insert-values
      :file
      &amp;#91;&amp;quot;name=?&amp;quot; filename&amp;#93;
      {:type content-type 
       :name filename
       :data &amp;#40;to-byte-array tempfile&amp;#41;}&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn list-files &amp;#91;&amp;#93;
  &amp;#40;map :name &amp;#40;db-read &amp;quot;select name from file&amp;quot;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn get-file &amp;#91;name&amp;#93;
  &amp;#40;first &amp;#40;db-read &amp;quot;select &amp;#42; from file where name=?&amp;quot; name&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The first helper is used by &lt;code&gt;store-file&lt;/code&gt; to copy the file out of the input stream into a byte array and then store it in the table. The other two functions simply read the file columns from our database.&lt;/p&gt;&lt;h3 id="uploading&amp;#95;files"&gt;Uploading Files&lt;/h3&gt;&lt;p&gt;We'll create a new namespace called &lt;code&gt;files&lt;/code&gt; under views, and make a page facilitating the uploads:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.files
  &amp;#40;:use hiccup.util
        noir.core
        hiccup.core
        hiccup.page
        hiccup.form
        hiccup.element&amp;#41;
  &amp;#40;:require &amp;#91;my-website.views.common :as common&amp;#93;
            &amp;#91;my-website.models.db :as db&amp;#93;
            &amp;#91;noir.response :as resp&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/upload&amp;quot; {:keys &amp;#91;info&amp;#93;}
  &amp;#40;common/layout    
    &amp;#91;:h2.info info&amp;#93;
    &amp;#40;form-to {:enctype &amp;quot;multipart/form-data&amp;quot;}
             &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93;
             &amp;#40;label :file &amp;quot;File to upload&amp;quot;&amp;#41;
             &amp;#40;file-upload :file&amp;#41;
             &amp;#91;:br&amp;#93;
             &amp;#40;submit-button &amp;quot;upload&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;There shouldn't be anything too surprising here, we create an "/upload" page with a an info header and a form. On the form we set &lt;code&gt;enctype&lt;/code&gt; to &lt;code&gt;multipart/form-data&lt;/code&gt;, then we use &lt;code&gt;file-upload&lt;/code&gt; function from &lt;code&gt;hiccup.form&lt;/code&gt; to create the file upload dialog and add a submit button. As a note, all Hiccup helper functions also accept a map of attributes as an optional first parameter, these attributes will be merged with the ones already provided by the helper.&lt;/p&gt;&lt;p&gt;Now we'll have to make its POST counterpart to handle the upload request on the server:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93; {:keys &amp;#91;file&amp;#93;}
  &amp;#40;render &amp;quot;/upload&amp;quot;
    {:info 
      &amp;#40;try
        &amp;#40;db/store-file file&amp;#41; 
        &amp;quot;file uploaded successfully&amp;quot;
        &amp;#40;catch Exception ex
          &amp;#40;do
            &amp;#40;.printStackTrace ex&amp;#41;
            &amp;#40;str &amp;quot;An error has occured while uploading the file: &amp;quot;
              &amp;#40;.getMessage ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Here we accept the params, grab the file and pass it to &lt;code&gt;store-file&lt;/code&gt; function we created earlier in the &lt;code&gt;db&lt;/code&gt; namespace. The file is a map containing the following keys:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;:tempfile - the file itself&lt;/li&gt;&lt;li&gt;:filename - the name of the file being uploaded&lt;/li&gt;&lt;li&gt;:content-type - the content type of the file being uploaded&lt;/li&gt;&lt;li&gt;:size - size of the file in bytes&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;eg:&lt;pre&gt;&lt;code class="clojure"&gt;{:size 422668, 
 :tempfile #&amp;lt;File /var/folders/0s/1vrmt9wx6lqdjlg1qtgc34600000gn/T/ring-multipart-3157719234459115704.tmp&amp;gt;, 
 :content-type &amp;quot;image/jpeg&amp;quot;, 
 :filename &amp;quot;logo.jpg&amp;quot;}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We can now test that file uploading works correctly by navigating to &lt;a href='localhost:8080/upload'&gt;localhost:8080/upload&lt;/a&gt; and uploading a file.&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/file-upload.png" alt="file upload" /&gt; &lt;/center&gt; once we hit upload we should see the following:&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/file-uploaded.png" alt="file uploaded" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="serving&amp;#95;files"&gt;Serving Files&lt;/h3&gt;&lt;p&gt;At this point it might be nice to be able to see what files we have on the server, so let's update our "/upload" page to display a list of files and allow downloading them:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn list-files &amp;#91;&amp;#93;
  &amp;#40;into &amp;#91;:ul&amp;#93;
        &amp;#40;for &amp;#91;name &amp;#40;db/list-files&amp;#41;&amp;#93;             
          &amp;#91;:li.file-link &amp;#40;link-to &amp;#40;str &amp;quot;/files/&amp;quot; name&amp;#41; name&amp;#41; 
           &amp;#91;:span &amp;quot;  &amp;quot;&amp;#93; 
           &amp;#91;:div.file&amp;#93;&amp;#93;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/upload&amp;quot; {:keys &amp;#91;info&amp;#93;}
  &amp;#40;common/layout    
    &amp;#91;:h2.info info&amp;#93;
    &amp;#40;list-files&amp;#41;
    &amp;#40;form-to {:enctype &amp;quot;multipart/form-data&amp;quot;}
             &amp;#91;:post &amp;quot;/upload&amp;quot;&amp;#93;
             &amp;#40;label :file &amp;quot;File to upload&amp;quot;&amp;#41;
             &amp;#40;file-upload :file&amp;#41;
             &amp;#91;:br&amp;#93;
             &amp;#40;submit-button &amp;quot;upload&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/files/:name&amp;quot; {:keys &amp;#91;name&amp;#93;}
  &amp;#40;let &amp;#91;{:keys &amp;#91;name type data&amp;#93;} &amp;#40;db/get-file name&amp;#41;&amp;#93;
    &amp;#40;resp/content-type type &amp;#40;new java.io.ByteArrayInputStream data&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Above, &lt;code&gt;list-files&lt;/code&gt; reads the file names from the database, using the helper function we defined earlier and then sticks them into an unordered list. Notice, that Hiccup allows literal notation for any HTML tags, the syntax is as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:tag {:attr &amp;quot;value&amp;quot;} content&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;So, if we don't have a helper function for a particular tag, or we need to make a custom tag, we can always just make a vector and set the attributes we care about. &lt;/p&gt;&lt;p&gt;The new "/files/:name" page we defined uses &lt;code&gt;resp/content-type&lt;/code&gt; function to set the appropriate content type when returning the file. It accepts the content type string and an input stream as parameters. &lt;/p&gt;&lt;p&gt;If we reload the page after making the above changes we should see the following: &lt;center&gt; &lt;img src="/files/files-list.png" alt="files list" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;and when we click on the file link it should display the image in the browser: &lt;center&gt; &lt;img src="/files/file.png" alt="files list" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="summary"&gt;Summary&lt;/h3&gt;&lt;p&gt;In this section we learned the following:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;storing files in the database&lt;/li&gt;&lt;li&gt;setting custom attributes on Hiccup elements&lt;/li&gt;&lt;li&gt;using &lt;code&gt;multipart/form-data&lt;/code&gt; form to upload a binary file&lt;/li&gt;&lt;li&gt;serving a file with a custom content type&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The complete code for this section is available &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/8686d50e2ed6863a63e48428209de6fe7ad58af8'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;In the &lt;a href='http://yogthos.net/blog/26-Noir+tutorial+-+part+4'&gt;next section&lt;/a&gt; we'll talk about creating private pages, form input validation, and handling multi-select form parameters, such as multi checkbox set.&lt;/p&gt;</description><pubDate>Wed, 22 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-21-Reflecting-on-performance.html</guid><link>https://yogthos.net/posts/2012-08-21-Reflecting-on-performance.html</link><title>Reflecting on performance</title><description>&lt;p&gt;I'm going to take a short break from Noir tutorials and  do a post on optimization and profiling instead. I was playing around with rendering &lt;a href='http://en.wikipedia.org/wiki/Metaballs'&gt;Metaballs&lt;/a&gt; and I stumbled on a neat visualization.&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/metaballs.png" alt="metaballs" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;To get the above effect we simply calculate the influence of each metaball on each point on the screen based on the distances to each ball's center and radius:&lt;/p&gt;&lt;p&gt;i&lt;sub&gt;mp&lt;/sub&gt; = r&lt;sub&gt;mp&lt;/sub&gt; / &amp;#8730; (&amp;#948;x&lt;sub&gt;mp&lt;/sub&gt;&lt;sup&gt;2&lt;/sup&gt; + &amp;#948;y&lt;sub&gt;mp&lt;/sub&gt;&lt;sup&gt;2&lt;/sup&gt;)&lt;/p&gt;&lt;p&gt;where r is the radius of the metabll and &lt;em&gt;&amp;#948;x&lt;sub&gt;mp&lt;/sub&gt;&lt;/em&gt; and &lt;em&gt;&amp;#948;y&lt;sub&gt;mp&lt;/sub&gt;&lt;/em&gt; are the &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt; distances from the center of the metaball &lt;emph&gt;m&lt;/emph&gt; to the point &lt;emph&gt;p&lt;/emph&gt;. The resulting color &lt;emph&gt;c&lt;sub&gt;p&lt;/sub&gt;&lt;/emph&gt; of the point is the sum of all the influences:&lt;/p&gt;&lt;p&gt;c&lt;sub&gt;p&lt;/sub&gt; = &amp;#931; i&lt;sub&gt;mp&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;The algorithm is on the order of &lt;emph&gt;n&lt;sup&gt;2&lt;/sup&gt;&lt;/emph&gt;, given a small number of metaballs relative to the number of pixels and a square viewport. Unsurprisingly, this runs quite slowly without optimizations, so let's see if we can do anything about that.&lt;/p&gt;&lt;p&gt;The code to accomplish this is as follows:&lt;pre&gt;&lt;code class="clojure"&gt;;;compute influence of each metaball
&amp;#40;defn influence &amp;#91;{:keys &amp;#91;x y radius&amp;#93;} px py&amp;#93;
  &amp;#40;let &amp;#91;dx &amp;#40;- x px&amp;#41;
        dy &amp;#40;- y py&amp;#41;&amp;#93;
    &amp;#40;/ radius &amp;#40;Math/sqrt &amp;#40;+ &amp;#40;&amp;#42; dx dx&amp;#41; &amp;#40;&amp;#42; dy dy&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

;;compute the resulting r g b values based on influence
&amp;#40;defn compute-color &amp;#91;x y &amp;#91;red-cur green-cur blue-cur&amp;#93; ball&amp;#93;   
  &amp;#40;let &amp;#91;influence &amp;#40;influence ball x y&amp;#41;
        &amp;#91;r g b&amp;#93; &amp;#40;:color ball&amp;#41;&amp;#93; 
    &amp;#91;&amp;#40;+ red-cur &amp;#40;&amp;#42; influence r&amp;#41;&amp;#41;
     &amp;#40;+ green-cur &amp;#40;&amp;#42; influence g&amp;#41;&amp;#41;
     &amp;#40;+ blue-cur &amp;#40;&amp;#42; influence b&amp;#41;&amp;#41;&amp;#93;&amp;#41;&amp;#41;

...
;;reverse direction if we hit the edge of the screen
&amp;#40;defn direction &amp;#91;p v&amp;#93;
  &amp;#40;if &amp;#40;or &amp;#40;&amp;gt; p SIZE&amp;#41; &amp;#40;neg? p&amp;#41;&amp;#41; &amp;#40;- v&amp;#41; v&amp;#41;&amp;#41;

;;compute the position and velocity of the ball
&amp;#40;defn move &amp;#91;{:keys &amp;#91;x y vx vy radius color&amp;#93;}&amp;#93;
  &amp;#40;let &amp;#91;vx &amp;#40;direction x vx&amp;#41;
        vy &amp;#40;direction y vy&amp;#41;&amp;#93;
    {:x &amp;#40;+ x vx&amp;#41;
     :y &amp;#40;+ y vy&amp;#41;
     :vx vx
     :vy vy
     :radius radius
     :color color}&amp;#41;&amp;#41;

;;for each x,y coordinate compute the color
&amp;#40;reduce &amp;#40;partial compute-color x y&amp;#41; &amp;#91;0 0 0&amp;#93; balls&amp;#41;

;;run this in a loop where we move the 
;;balls around and render them
&amp;#40;loop &amp;#91;balls &amp;#40;take 2 &amp;#40;repeatedly metaball&amp;#41;&amp;#41;&amp;#93;      
      &amp;#40;draw canvas balls&amp;#41;
      &amp;#40;recur &amp;#40;map move balls&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://gist.github.com/3411102'&gt;complete code can be seen here&lt;/a&gt;&lt;/p&gt;&lt;p&gt;First thing to do is to time our our loop:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;loop &amp;#91;balls &amp;#40;take 2 &amp;#40;repeatedly metaball&amp;#41;&amp;#41;&amp;#93;      
      &amp;#40;time &amp;#40;draw canvas balls&amp;#41;&amp;#41;
      &amp;#40;recur &amp;#40;time &amp;#40;map move balls&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;quot;Elapsed time: 250.345 msecs&amp;quot;
&amp;quot;Elapsed time: 0.004 msecs&amp;quot;
&amp;quot;Elapsed time: 171.136 msecs&amp;quot;
&amp;quot;Elapsed time: 0.005 msecs&amp;quot;
&amp;quot;Elapsed time: 212.646 msecs&amp;quot;
&amp;quot;Elapsed time: 0.004 msecs&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As can be expected the draw function eclipses the move function. So we'll focus on what's happening in our rendering code and see where the CPU time is being spent. Instead of guessing, let's profile the application using &lt;a href='https://visualvm.github.io/'&gt;VisualVM&lt;/a&gt;, which should already be bundled with your JVM, and see what's happening.&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/profile1.png" alt="initial profiling" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;We can see that the vast majority of the CPU time is being spent in the &lt;code&gt;color&lt;/code&gt; function, and that reflection is the culprit. So, let's see why reflection is happening by setting the &lt;code&gt;&amp;#42;warn-on-reflection&amp;#42;&lt;/code&gt; flag to true:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;set! &amp;#42;warn-on-reflection&amp;#42; true&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;pre&gt;&lt;code class="bash"&gt;Reflection warning, metaballs.clj:32 - call to java.awt.Color ctor can't be resolved.
Reflection warning, metaballs.clj:40 - call to setColor can't be resolved.
Reflection warning, metaballs.clj:40 - call to fillRect can't be resolved.
Reflection warning, metaballs.clj:52 - reference to field getBufferStrategy can't be resolved.
Reflection warning, metaballs.clj:53 - reference to field getDrawGraphics can't be resolved.
Reflection warning, metaballs.clj:64 - reference to field dispose can't be resolved.
Reflection warning, metaballs.clj:65 - reference to field contentsLost can't be resolved.
Reflection warning, metaballs.clj:66 - reference to field show can't be resolved.
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now we know precisely which spots are causing us trouble. Let's see if adding some annotations will improve things. First warning we hit happens when we  create a new instance of &lt;code&gt;Color&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn color-in-range &amp;#91;c&amp;#93;
  &amp;#40;int
    &amp;#40;cond 
      &amp;#40;&amp;lt; c 0&amp;#41; 0
      &amp;#40;&amp;gt; c 255&amp;#41; 255
      :default c&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn color &amp;#91;r g b&amp;#93;
  &amp;#40;new Color &amp;#40;color-in-range r&amp;#41; &amp;#40;color-in-range g&amp;#41; &amp;#40;color-in-range b&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;what's happening here is that even though we cast the result into &lt;code&gt;int&lt;/code&gt; inside &lt;code&gt;color-in-range&lt;/code&gt;, &lt;code&gt;color&lt;/code&gt; is not aware of it and uses reflection to resolve the constructor for &lt;code&gt;Color&lt;/code&gt;. So we should be doing the cast inside &lt;code&gt;color&lt;/code&gt; instead:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn color &amp;#91;r g b&amp;#93;
  &amp;#40;new Color &amp;#40;int &amp;#40;color-in-range r&amp;#41;&amp;#41; 
             &amp;#40;int &amp;#40;color-in-range g&amp;#41;&amp;#41; 
             &amp;#40;int &amp;#40;color-in-range b&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The rest of the warnings simply require annotations for the classes in the function arguments:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn paint-square &amp;#91;g color x y size&amp;#93;
  &amp;#40;doto g
    &amp;#40;.setColor color&amp;#41;
    &amp;#40;.fillRect x y size size&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;becomes&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn paint-square &amp;#91;&amp;#94;Graphics g &amp;#94;Color color x y size&amp;#93;
  &amp;#40;doto g
    &amp;#40;.setColor color&amp;#41;
    &amp;#40;.fillRect x y size size&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and so on. Finally, we'll cast our distances to doubles when we compute the influence:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn influence &amp;#91;{:keys &amp;#91;x y radius&amp;#93;} px py&amp;#93;
  &amp;#40;let &amp;#91;dx &amp;#40;double &amp;#40;- x px&amp;#41;&amp;#41;
        dy &amp;#40;double &amp;#40;- y py&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;double &amp;#40;/ radius &amp;#40;Math/sqrt &amp;#40;+ &amp;#40;&amp;#42; dx dx&amp;#41; &amp;#40;&amp;#42; dy dy&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://gist.github.com/3411106'&gt;optimized version can be seen here&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Now that we've annotated our code let's see if performance is any better:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;quot;Elapsed time: 55.424 msecs&amp;quot;
&amp;quot;Elapsed time: 55.399 msecs&amp;quot;
&amp;quot;Elapsed time: 55.373 msecs&amp;quot;
&amp;quot;Elapsed time: 55.482 msecs&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Indeed it is, we went from ~200ms to ~55ms a 4X improvement in speed! Let's see what the profiler has to say now:&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/profile2.png" alt="profile" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;From here we can clearly see that majority of the time is spent in the paint-square function, meaning that our code performs as it should. Turns out the the only real factor on performance is reflection. &lt;/p&gt;&lt;p&gt;We could've spent time doing random optimizations here and there, but it's clear from profiling which functions are actually eating up the resources and need optimizing. While this is a toy project, the technique is equally effective for large projects where it might be much more difficult to guess which functions need tuning.&lt;/p&gt;&lt;p&gt;P.S. try setting a negative radius for some of the metaballs in the scene :P&lt;/p&gt;</description><pubDate>Tue, 21 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-18-Noir-tutorial-part-2.html</guid><link>https://yogthos.net/posts/2012-08-18-Noir-tutorial-part-2.html</link><title>Noir tutorial - part 2</title><description>&lt;p&gt;This is the second part of the Noir tutorial, where we'll continue to cover the basics of building a website. In the comments for part 1, somebody suggested  that Noir might be abandoned. This is absolutely not the case, I've contacted Chris Granger and this is what he has to say:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Hey Dmitri,&lt;br /&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;Light Table actually uses Noir, so it's certainly still alive. I'm not the primary one driving things day to day right now, Raynes has been helping out with that. &lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;Cheers,&lt;br /&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;Chris. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Hopefully, this should put any fears regarding the health of the project to rest. And with that out of the way, lets continue building our site. In the &lt;a href='http://yogthos.net/blog/22-Noir+tutorial+-+part+1'&gt;previous section of the tutorial&lt;/a&gt; we setup a basic project and learned how to add pages to it. This time let's look at how to persist data to a database, create sessions, and do some basic user management.&lt;/p&gt;&lt;h3 id="database&amp;#95;access"&gt;Database Access&lt;/h3&gt;&lt;p&gt;There are several Clojure libraries for dealing with relational databases, such as &lt;a href='http://sqlkorma.com/'&gt;SQLKorma&lt;/a&gt;, &lt;a href='http://clojureql.org/'&gt;ClojureQL&lt;/a&gt;, &lt;a href='http://budu.github.com/lobos/index.html'&gt;Lobos&lt;/a&gt;, and [clojure.data.jdbc])(http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/UsingSQL.html). In this tutorial we'll be using clojure.data.jdbc to keep things simple, but I do encourage you to take a look at the others.&lt;/p&gt;&lt;h4 id="setting&amp;#95;up&amp;#95;the&amp;#95;db&amp;#95;connection"&gt;Setting up the DB connection&lt;/h4&gt;&lt;p&gt;First, we'll need to define our database connection, this can be done by either providing a map of connection parameters:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db {:subprotocol &amp;quot;postgresql&amp;quot;
         :subname &amp;quot;//localhost/my&amp;#95;website&amp;quot;
         :user &amp;quot;admin&amp;quot;
         :password &amp;quot;admin&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;by specifying the JNDI name for a connection managed by the application server:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db {:name &amp;quot;jdbc/myDatasource&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;I personally like this option, because it completely separates the code in the application from the environment. For example, if you have dev/staging/production servers, you can point the JNDI connection to their respective databases, and when you deploy your application it will pick it up from the environment.&lt;/p&gt;&lt;p&gt;Finally, you can provide a JDBC data source, which you configure manually:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db
  {:datasource
    &amp;#40;doto &amp;#40;new PGPoolingDataSource&amp;#41;
     &amp;#40;.setServerName   &amp;quot;localhost&amp;quot;&amp;#41;
     &amp;#40;.setDatabaseName &amp;quot;my&amp;#95;website&amp;quot;&amp;#41;
     &amp;#40;.setUser         &amp;quot;admin&amp;quot;&amp;#41;
     &amp;#40;.setPassword     &amp;quot;admin&amp;quot;&amp;#41;
     &amp;#40;.setMaxConnections 10&amp;#41;&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;At this point you should setup a database and create a schema for this tutorial called &lt;code&gt;my&amp;#95;website&lt;/code&gt;. I will be using PostgreSQL so if you use a different DB there might be slight syntactic differences in your SQL. Once you have the DB up and running, we'll need to add the clojure.data.jdbc and JDBC driver dependencies to &lt;code&gt;project.clj&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject my-website &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;&amp;quot;my Noir website&amp;quot;&amp;quot;
  :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                 &amp;#91;noir &amp;quot;1.3.0-beta3&amp;quot;&amp;#93;
                 &amp;#91;org.clojure/java.jdbc &amp;quot;0.2.3&amp;quot;&amp;#93;
                 &amp;#91;postgresql/postgresql &amp;quot;9.1-901.jdbc4&amp;quot;&amp;#93;&amp;#93;
  :main my-website.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;h4 id="using&amp;#95;to&amp;#95;the&amp;#95;database"&gt;Using to the Database&lt;/h4&gt;&lt;p&gt;Next, let's create a new namespace called &lt;code&gt;my-website.models.db&lt;/code&gt; in the models directory of our project, and open it up. Here we'll first need to add a require statement for clojure.data.jdbc:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.models.db
  &amp;#40;:require &amp;#91;clojure.java.jdbc :as sql&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;now let's create a connection:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db 
  {:subprotocol &amp;quot;postgresql&amp;quot;
   :subname &amp;quot;//localhost/my&amp;#95;website&amp;quot;
   :user &amp;quot;admin&amp;quot;
   :password &amp;quot;admin&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;we'll add the following function which will allow us to create the &lt;code&gt;users&lt;/code&gt; table:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn init-db &amp;#91;&amp;#93;
  &amp;#40;try
  &amp;#40;sql/with-connection
    db
    &amp;#40;sql/create-table
      :users
      &amp;#91;:id &amp;quot;SERIAL&amp;quot;&amp;#93;
      &amp;#91;:handle &amp;quot;varchar&amp;#40;100&amp;#41;&amp;quot;&amp;#93;
      &amp;#91;:pass   &amp;quot;varchar&amp;#40;100&amp;#41;&amp;quot;&amp;#93;&amp;#41;&amp;#41;
  &amp;#40;catch Exception ex
    &amp;#40;.getMessage &amp;#40;.getNextException ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Here's you'll notice that the &lt;code&gt;create-table&lt;/code&gt; needs to be wrapped in a &lt;code&gt;with-connection&lt;/code&gt; statement which ensures that the connection is cleaned up correctly after we're done with it. The only other thing to note is the use of "SERIAL" for the id field in the table, which is PostgreSQL specific way to create auto incrementing fields. It's also possible to use keywords such as &lt;code&gt;:int&lt;/code&gt;, &lt;code&gt;:boolean&lt;/code&gt;, and &lt;code&gt;:timestamp&lt;/code&gt; for field types as well as the corresponding SQL string as is done in the above example. The whole statement is wrapped in a try block, so if we get any errors when it runs we'll print the error message.&lt;/p&gt;&lt;p&gt;In the REPL we'll run:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;init-db&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If your DB is configured correctly, then you should now have a &lt;code&gt;users&lt;/code&gt; table. We'll now write a function to add a user to it:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn add-user &amp;#91;user&amp;#93;
  &amp;#40;sql/with-connection 
    db
    &amp;#40;sql/insert-record :users user&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;now test that the function works correctly:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;add-user {:handle &amp;quot;foo&amp;quot; :pass &amp;quot;bar&amp;quot;}&amp;#41;
=&amp;gt;{:pass &amp;quot;bar&amp;quot;, :handle &amp;quot;foo&amp;quot;, :id 1}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;finally we'll need a way to read the records from the database, I wrote the following helper function to do that:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn db-read &amp;#91;query &amp;amp; args&amp;#93;
  &amp;#40;sql/with-connection 
    db
    &amp;#40;sql/with-query-results 
      res 
      &amp;#40;vec &amp;#40;cons query args&amp;#41;&amp;#41; &amp;#40;doall res&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;the function accepts an SQL string and optional parameters:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;db-read &amp;quot;select &amp;#42; from users&amp;quot;&amp;#41;
&amp;#40;{:pass &amp;quot;bar&amp;quot;, :handle &amp;quot;foo&amp;quot;, :id 1}&amp;#41;

&amp;#40;db-read &amp;quot;select &amp;#42; from users where id=?&amp;quot; 1&amp;#41;
&amp;#40;{:pass &amp;quot;bar&amp;quot;, :handle &amp;quot;foo&amp;quot;, :id 1}&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;we'll write another helper function to fetch the user by handle&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn get-user &amp;#91;handle&amp;#93;
  &amp;#40;first 
    &amp;#40;db-read &amp;quot;select &amp;#42; from users where handle=?&amp;quot; handle&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;at this point we've got a user table and helper functions to create and query users. Let's hook that up to our pages and provide the functionality to create user accounts and allow users to login.&lt;/p&gt;&lt;h3 id="creating&amp;#95;a&amp;#95;registration&amp;#95;page"&gt;Creating a Registration Page&lt;/h3&gt;&lt;p&gt;Noir provides a very simple way to manage sessions using &lt;a href='http://www.webnoir.org/autodoc/1.2.0/noir.session-api.html'&gt;noir.ession&lt;/a&gt; namespace. Let's update our site to allow a user to create an account. First we'll create a new namespace called &lt;code&gt;my-website.views.users&lt;/code&gt; and add the following code to it:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.users
  &amp;#40;:use &amp;#91;noir.core&amp;#93;
        hiccup.core hiccup.form&amp;#41;
  &amp;#40;:require &amp;#91;my-website.views.common :as common&amp;#93;
            &amp;#91;my-website.models.db :as db&amp;#93;
            &amp;#91;noir.util.crypt :as crypt&amp;#93;
            &amp;#91;noir.session :as session&amp;#93;
            &amp;#91;noir.response :as resp&amp;#93;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/signup&amp;quot; {:keys &amp;#91;handle error&amp;#93;}
  &amp;#40;common/layout
    &amp;#91;:div.error error&amp;#93;
    &amp;#40;form-to &amp;#91;:post &amp;quot;/signup&amp;quot;&amp;#93;
             &amp;#40;label &amp;quot;user-id&amp;quot; &amp;quot;user id&amp;quot;&amp;#41;
             &amp;#40;text-field &amp;quot;handle&amp;quot; handle&amp;#41;
             &amp;#91;:br&amp;#93;
             &amp;#40;label &amp;quot;pass&amp;quot; &amp;quot;password&amp;quot;&amp;#41;
             &amp;#40;password-field &amp;quot;pass&amp;quot;&amp;#41;             
             &amp;#91;:br&amp;#93;
             &amp;#40;submit-button &amp;quot;create account&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;#91;:post &amp;quot;/signup&amp;quot;&amp;#93; user
  &amp;#40;try 
    &amp;#40;db/add-user &amp;#40;update-in user &amp;#91;:pass&amp;#93; crypt/encrypt&amp;#41;&amp;#41;
    &amp;#40;resp/redirect &amp;quot;/&amp;quot;&amp;#41;
    &amp;#40;catch Exception ex
      &amp;#40;render &amp;quot;/signup&amp;quot; &amp;#40;assoc user :error &amp;#40;.getMessage ex&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;You'll notice that we've required a few new namespaces which we'll be using shortly. Otherwise, we see a similar setup to what we did in the first part of the tutorial, except when we accept the post from the form, we actually add the user to the database.&lt;/p&gt;&lt;p&gt;We will encrypt the user password using &lt;code&gt;noir.util.crypt&lt;/code&gt; and then attempt to store the user in the database. If we fail to add the user we'll render our signup page again, but this time with an error message.&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/noirtutorial1.3.png" alt="create user" /&gt; &lt;br/&gt; create user page&lt;/p&gt;&lt;p&gt;&lt;img src="/files/noirtutorial1.4.png" alt="create user error" /&gt; &lt;br/&gt; error displayed when user creation fails&lt;/p&gt;&lt;p&gt;&lt;/center&gt; Notice that we pass the user fields back to the defpage displaying the form, so if we get an error we don't have to make the user retype all their information.&lt;/p&gt;&lt;h3 id="session&amp;#95;management"&gt;Session Management&lt;/h3&gt;&lt;p&gt;At this point we need to provide the users with the ability to login with their accounts. Let's go to the &lt;code&gt;common&lt;/code&gt; namespace and add a way for users to login. We'll need to add &lt;a href='http://www.webnoir.org/autodoc/1.2.0/noir.session-api.html'&gt;&lt;code&gt;noir.session&lt;/code&gt;&lt;/a&gt; to our &lt;code&gt;:require&lt;/code&gt; statement:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.common
  ...
  &amp;#40;:require &amp;#91;noir.session :as session&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;then we'll go back to &lt;code&gt;users&lt;/code&gt; namespace and create a page to handle logins:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;#91;:post &amp;quot;/login&amp;quot;&amp;#93; {:keys &amp;#91;handle pass&amp;#93;}
  &amp;#40;render &amp;quot;/&amp;quot; 
          &amp;#40;let &amp;#91;user &amp;#40;db/get-user handle&amp;#41;&amp;#93; 
            &amp;#40;if &amp;#40;and user &amp;#40;crypt/compare pass &amp;#40;:pass user&amp;#41;&amp;#41;&amp;#41;
              &amp;#40;session/put! :user handle&amp;#41;
              {:handle handle :error &amp;quot;login failed&amp;quot;}&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We'll use &lt;code&gt;noir.crypt&lt;/code&gt; to validate the password against the one we have in the database, and if the password matches we'll stick the user handle into the session. The syntax for updating the session is fairly straightforward, and the &lt;a href='http://www.webnoir.org/autodoc/1.2.0/noir.session-api.html'&gt;documentation page&lt;/a&gt; explains it well. We'll be using &lt;code&gt;get&lt;/code&gt;, &lt;code&gt;put!&lt;/code&gt;, and &lt;code&gt;clear!&lt;/code&gt; functions, notice that &lt;code&gt;put!&lt;/code&gt; and &lt;code&gt;clear!&lt;/code&gt; have an exclamation mark at the end indicating that they mutate the data in place.&lt;/p&gt;&lt;p&gt;The users will also need a way to logout, so let's add a page to handle that as well:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;#91;:post &amp;quot;/logout&amp;quot;&amp;#93; &amp;#91;&amp;#93;
  &amp;#40;session/clear!&amp;#41;
  &amp;#40;resp/redirect &amp;quot;/&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;When the user logs out, we'll simply clear the session and send them back to the homepage. We will now go to our &lt;code&gt;common&lt;/code&gt; namespace and add the &lt;code&gt;noir.session&lt;/code&gt; and &lt;code&gt;hiccup.form&lt;/code&gt; in our namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.common
  &amp;#40;:use &amp;#91;noir.core :only &amp;#91;defpartial&amp;#93;&amp;#93;
        hiccup.element 
        hiccup.form
        &amp;#91;hiccup.page :only &amp;#91;include-css html5&amp;#93;&amp;#93;&amp;#41;
  &amp;#40;:require &amp;#91;noir.session :as session&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;then add a helper function to create the login form:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn login-form &amp;#91;&amp;#93;
  &amp;#40;form-to &amp;#91;:post &amp;quot;/login&amp;quot;&amp;#93;           
           &amp;#40;text-field {:placeholder &amp;quot;user id&amp;quot;} &amp;quot;handle&amp;quot;&amp;#41;                        
           &amp;#40;password-field {:placeholder &amp;quot;password&amp;quot;} &amp;quot;pass&amp;quot;&amp;#41;                        
           &amp;#40;submit-button &amp;quot;login&amp;quot;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and finally add it to our layout:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpartial layout &amp;#91;&amp;amp; content&amp;#93;
            &amp;#40;html5
              &amp;#91;:head
               &amp;#91;:title &amp;quot;my-website&amp;quot;&amp;#93;
               &amp;#40;include-css &amp;quot;/css/reset.css&amp;quot;&amp;#41;&amp;#93;
              &amp;#91;:body               
               &amp;#40;if-let &amp;#91;user &amp;#40;session/get :user&amp;#41;&amp;#93;
                  &amp;#91;:h2 &amp;quot;welcome &amp;quot; user 
                    &amp;#40;form-to &amp;#91;:post &amp;quot;/logout&amp;quot;&amp;#93; &amp;#40;submit-button &amp;quot;logout&amp;quot;&amp;#41;&amp;#41;&amp;#93;
                  &amp;#91;:div.login
                   &amp;#40;login-form&amp;#41; &amp;#91;:p &amp;quot;or&amp;quot;&amp;#93; &amp;#40;link-to &amp;quot;/signup&amp;quot; &amp;quot;sign up&amp;quot;&amp;#41;&amp;#93;&amp;#41;
               
               content&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;At this point our main page should look like the following: &lt;center&gt; &lt;img src="/files/noirtutorial1.5.png" alt="login" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;and after we sign up and login, we should see:&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/noirtutorial1.6.png" alt="logged in" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;p&gt;The logout button should take us back to the login page by clearing the user session. We now have a complete website with some basic user management, the only thing left to add is actual content. :)&lt;/p&gt;&lt;h3 id="summary"&gt;Summary&lt;/h3&gt;&lt;p&gt;In this section we learned the following:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;how to setup the database and do basic queries&lt;/li&gt;&lt;li&gt;do basic authentication using &lt;code&gt;noir.crypt&lt;/code&gt;&lt;/li&gt;&lt;li&gt;use sessions to store user information&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Hopefully this is enough to get you started using Noir and making your sites with it. If I omitted anything important let me know in comments and I'll be glad to go over it.&lt;/p&gt;&lt;p&gt;The complete source for this part of the tutorial is available &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/f83a894933922eda2b78c84de2e8eb28891eeda5'&gt;here&lt;/a&gt;. Also, for an example of a complete real world site you can see the source for this blog &lt;a href='https://github.com/yogthos/yuggoth'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;In the &lt;a href='http://yogthos.net/blog/25-Noir+tutorial+-+part+3'&gt;next section&lt;/a&gt; we'll talk about setting content types and doing file uploads and downloads.&lt;/p&gt;</description><pubDate>Sat, 18 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-17-Noir-tutorial-part-1.html</guid><link>https://yogthos.net/posts/2012-08-17-Noir-tutorial-part-1.html</link><title>Noir tutorial - part 1</title><description>&lt;h3 id="background"&gt;Background&lt;/h3&gt;&lt;p&gt;Clojure web stack consists of &lt;a href='https://github.com/ring-clojure/ring'&gt;Ring&lt;/a&gt;, which is the base HTTP library akin to Python's WSGI and Ruby's Rack. On top of Ring lives &lt;a href='https://github.com/weavejester/compojure'&gt;Compojure&lt;/a&gt;, which provides some basic routing, and that in turn is leveraged by &lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt; to provide a simple framework for developing websites. Here's we'll see how to use Noir to build a basic website. &lt;/p&gt;&lt;h3 id="setting&amp;#95;up&amp;#95;a&amp;#95;noir&amp;#95;project&amp;#95;with&amp;#95;leiningen"&gt;Setting Up a Noir Project With Leiningen&lt;/h3&gt;&lt;p&gt;The easiest way to get Noir setup is to use &lt;a href='https://github.com/technomancy/leiningen/'&gt;Leiningen 2&lt;/a&gt;, which has become the de facto build tool for Clojure. Once you have Leiningen installed, you can simply do the following to get a template site created:&lt;pre&gt;&lt;code class="bash"&gt;lein new noir my-website
cd my-website
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Alternatively, if you're using &lt;a href='http://code.google.com/p/counterclockwise/'&gt;Counterclockwise&lt;/a&gt; with Eclipse, then all you need to do is make a new Leiningen project and put &lt;code&gt;noir&lt;/code&gt; in the &lt;code&gt;&amp;quot;Leiningen Template to use:&amp;quot;&lt;/code&gt; field.&lt;/p&gt;&lt;h4 id="project&amp;#95;structure"&gt;Project Structure&lt;/h4&gt;&lt;p&gt;The template site will have the following structure:&lt;pre&gt;&lt;code class="bash"&gt;/my-website
  project.clj
  --src/
     --my&amp;#95;website/
       server.clj
       --models/
       --views/common.clj
               welcome.clj
  --test/my&amp;#95;website
  --resources/public/
                  --css/reset.css
                  --img/
                  --js/
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The skeleton application contains a few files in it. The &lt;code&gt;project.clj&lt;/code&gt; file is used for building the application and managing dependencies by Leiningen. Under the &lt;code&gt;src&lt;/code&gt; folder, we  have the folder called &lt;code&gt;my&amp;#95;website&lt;/code&gt; which contains &lt;code&gt;server.clj&lt;/code&gt;. This file contains the entry point to our application. It loads up all the views and provides a main function which can be used to start the application.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;models&lt;/code&gt; folder is used to keep the data layer of the application, such as code for the database access and table management. The &lt;code&gt;views&lt;/code&gt; folder contains the namespaces describing the pages of our application and their supporting code. The template contains &lt;code&gt;common.clj&lt;/code&gt; which provides a basic layout and any code shared between the pages. The &lt;code&gt;welcome.clj&lt;/code&gt; is the namespace where an example page is defined.&lt;/p&gt;&lt;h3 id="dependency&amp;#95;management"&gt;Dependency Management&lt;/h3&gt;&lt;p&gt;Let's first look at the &lt;code&gt;project.clj&lt;/code&gt; file:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject my-site &amp;quot;0.1.0-SNAPSHOT&amp;quot;
            :description &amp;quot;FIXME: write this!&amp;quot;
            :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.4.0&amp;quot;&amp;#93;
                           &amp;#91;noir &amp;quot;1.3.0-beta3&amp;quot;&amp;#93;&amp;#93;
            :main my-site.server&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The file is fairly self explanatory, and currently only contains dependencies for Clojure and Noir.&lt;/p&gt;&lt;h4 id="running&amp;#95;the&amp;#95;project&amp;#95;in&amp;#95;development&amp;#95;mode"&gt;Running the Project in Development Mode&lt;/h4&gt;&lt;p&gt;At this point we should be able to start up our website:&lt;pre&gt;&lt;code class="bash"&gt;lein run

Starting server...
2012-08-16 09:39:22.479:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
Server started on port &amp;#91;8080&amp;#93;.
You can view the site at http://localhost:8080
#&amp;lt;Server Server@2206270b&amp;gt;
2012-08-16 09:39:22.480:INFO::jetty-6.1.25
2012-08-16 09:39:22.521:INFO::Started SocketConnector@0.0.0.0:8080
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Let's point the browser to &lt;a href='http://localhost:8080'&gt;&lt;code&gt;localhost:8080&lt;/code&gt;&lt;/a&gt; and  make sure everything is working as expected. We should be greeted with a Noir help page since we haven't defined one for "/" route yet. At this point we can start editing our pages and any changes we make should be reflected immediately.&lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/noir.png" alt="noir" /&gt; &lt;/center&gt;&lt;/p&gt;&lt;h3 id="creating&amp;#95;pages"&gt;Creating Pages&lt;/h3&gt;&lt;p&gt;Noir provides two primary way to manipulate pages. One useful macro is &lt;code&gt;defpartial&lt;/code&gt; which simply wraps the body in &lt;code&gt;html&lt;/code&gt; function from Hiccup, which will generate the resulting HTML string from our content:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpartial foo &amp;#91;content&amp;#93;
  &amp;#91;:p content&amp;#93;&amp;#41;

&amp;#40;foo &amp;quot;some stuff&amp;quot;&amp;#41;
&amp;quot;&amp;lt;p&amp;gt;some stuff&amp;lt;/p&amp;gt;&amp;quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The other is &lt;code&gt;defpage&lt;/code&gt;, this macro will create a Compojure route for the specified URL. It has the following syntax:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage url params content&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;By default &lt;code&gt;defpage&lt;/code&gt; is expected to return an HTML string. How that string is generated is up to you. In this tutorial we'll be using Hiccup, but you could just as easily use something like &lt;a href='http://paulosuzart.github.com/blog/2012/03/25/web-noir-plus-enlive-template/'&gt;Enlive&lt;/a&gt; to create your templates using actual HTML. Noir itself is completely agnostic in this regard. &lt;/p&gt;&lt;p&gt;Now, let's look at the parameters that &lt;code&gt;defpage&lt;/code&gt; accepts. First we have a URL which supports the following formats:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;a simple string such as &lt;code&gt;&amp;quot;/welcome&amp;quot;&lt;/code&gt;&lt;/li&gt;&lt;li&gt;a RESTful path such as &lt;code&gt;&amp;quot;/welcome/:user&amp;quot;&lt;/code&gt; where the key &lt;code&gt;:user&lt;/code&gt; will be appended to the params map with the value provided when the URL is accessed&lt;/li&gt;&lt;li&gt;a vector specifying the request type which the page responds too : &lt;code&gt;&amp;#91;:post &amp;quot;/welcome&amp;quot;&amp;#93;&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Next, we have params, which is simply a map of keywords and their associated values generated from the request parameters. Any keys from the URL will also appear in this map:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/welcome/:user&amp;quot; {:keys &amp;#91;user&amp;#93;}
  &amp;#40;html &amp;#91;:html &amp;#91;:body &amp;quot;hello &amp;quot; user&amp;#93;&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Finally, we add the actual page content to be rendered. As I mentioned above the result &lt;strong&gt;must&lt;/strong&gt; be a string, so generally we'll wrap the contents of each page in &lt;code&gt;&amp;#40;common/layout ...&amp;#41;&lt;/code&gt; which was provided by the template. The official documentation for &lt;code&gt;defpage&lt;/code&gt; with lots of other examples and details is available &lt;a href='http://www.webnoir.org/tutorials/routes'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h4 id="handling&amp;#95;form&amp;#95;input"&gt;Handling Form Input&lt;/h4&gt;&lt;p&gt;When making pages with forms the general pattern is to create a &lt;code&gt;defpage&lt;/code&gt; for the GET request which will contain the UI, and another for POST which contains the server component. To test that out, let's change &lt;code&gt;welcome.clj&lt;/code&gt; to look like the following:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.views.welcome
  &amp;#40;:require &amp;#91;my-website.views.common :as common&amp;#93;
            &amp;#91;noir.content.getting-started&amp;#93;&amp;#41;
  &amp;#40;:use &amp;#91;noir.core :only &amp;#91;defpage&amp;#93;&amp;#93;
        hiccup.core hiccup.form&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/welcome&amp;quot; {:keys &amp;#91;greeting&amp;#93;}
  &amp;#40;common/layout
    &amp;#40;if greeting &amp;#91;:h2 greeting&amp;#93;&amp;#41;
    &amp;#40;form-to &amp;#91;:post &amp;quot;/welcome&amp;quot;&amp;#93;
      &amp;#40;label &amp;quot;name&amp;quot; &amp;quot;name&amp;quot;&amp;#41;
      &amp;#40;text-field &amp;quot;name&amp;quot;&amp;#41;
      &amp;#40;submit-button &amp;quot;submit&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;#91;:post &amp;quot;/welcome&amp;quot;&amp;#93; {:keys &amp;#91;name&amp;#93;}
  &amp;#40;noir.core/render &amp;quot;/welcome&amp;quot; 
    {:greeting &amp;#40;str &amp;quot;Welcome &amp;quot; name&amp;#41;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As can be seen above, the page which responds to GET creates a form and submits it to its POST counterpart. It in turn generates a greeting and renders the page with it. Note that the names for fields used in the form get translated into keys in the params map when we submit it. &lt;/p&gt;&lt;p&gt;&lt;center&gt; &lt;img src="/files/noirtutorial1.1.png" alt="initial page" /&gt;&lt;/p&gt;&lt;p&gt;before submit&lt;/p&gt;&lt;p&gt;&lt;img src="/files/noirtutorial1.2.png" alt="initial page" /&gt;&lt;/p&gt;&lt;p&gt;and after submit &lt;/center&gt;&lt;/p&gt;&lt;p&gt;This covers the basic model for creating pages and interacting with them. Now, let's look at how we can package our website into a standalone application. &lt;/p&gt;&lt;h3 id="packaging&amp;#95;and&amp;#95;running&amp;#95;standalone"&gt;Packaging and Running Standalone&lt;/h3&gt;&lt;p&gt;To package our project we need to change our server to compile into a class, we can do this by simply adding &lt;code&gt;gen-class&lt;/code&gt; to its namespace like so:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns my-website.server
  &amp;#40;:require &amp;#91;noir.server :as server&amp;#93;&amp;#41; 
  &amp;#40;:gen-class&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now we can build and run our project:&lt;pre&gt;&lt;code class="bash"&gt;lein uberjar
java -jar my-website-0.1.0-SNAPSHOT-standalone.jar

Starting server...
2012-08-16 20:12:47.846:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2012-08-16 20:12:47.846:INFO::jetty-6.1.x
2012-08-16 20:12:47.882:INFO::Started SocketConnector@0.0.0.0:8080
Server started on port &amp;#91;8080&amp;#93;.
You can view the site at http://localhost:8080
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;h3 id="summary"&gt;Summary&lt;/h3&gt;&lt;p&gt;To recap, in this section of the tutorial we learned the following:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;how to create a new Noir project&lt;/li&gt;&lt;li&gt;manage dependencies&lt;/li&gt;&lt;li&gt;create pages&lt;/li&gt;&lt;li&gt;handle submits from forms&lt;/li&gt;&lt;li&gt;create a standalone instance of our application&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Next time we'll look at how to do session management and database access. &lt;/p&gt;&lt;p&gt;&lt;a href='http://yogthos.net/blog/23-Noir+tutorial+-+part+2'&gt;continue to part 2&lt;/a&gt;&lt;/p&gt;&lt;p&gt;The source for the tutorial is available &lt;a href='https://github.com/yogthos/Noir-tutorial/tree/c70514189612f369efb75e1a601a1d10a5b15492'&gt;here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Fri, 17 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-16-Easy-PDF-reports-with-clj-pdf.html</guid><link>https://yogthos.net/posts/2012-08-16-Easy-PDF-reports-with-clj-pdf.html</link><title>Easy PDF reports with clj-pdf</title><description>&lt;p&gt;A few months ago I was tasked with generating reports for one of the applications I was working on. I looked around for some off the shelf libraries for doing this sort of thing. The most popular library in the Java world appears to be iText. It's a mature library with lots of features, but it takes entirely too much code to produce anything useful with it. On top of that, the latest version licensed under LGPL2 is 2.1.7 which, while serviceable, is full of quirks and odd behaviors.&lt;/p&gt;&lt;p&gt;After spending a bit of time playing with it I decided that it would make more sense to have a declarative API for describing the PDF document. I really like the way &lt;a href='http://weavejester.github.com/hiccup/'&gt;Hiccup&lt;/a&gt; allows generating HTML using nested vectors, and decided that something similar could be done for generating PDF documents.&lt;/p&gt;&lt;p&gt;This lead to the creating of &lt;a href='https://github.com/yogthos/clj-pdf'&gt;clj-pdf&lt;/a&gt;, which allows describing the document using this approach. Each vector represents a different element, such as a paragraph, a list, or a table. Internally, I leverage iText to produce the actual PDF document, but the API is completely declarative. The library attempts to abstract away any of the quirks as well as provide useful elements such as headings, spacers, page breaks, etc.&lt;/p&gt;&lt;p&gt;Let's look at how this all works in practice. A document is simply a vector which contains metadata describing it followed by one or more inner elements:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;{:title &amp;quot;My document&amp;quot;} &amp;quot;some content here...&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In the spirit of Hiccup, each element is represented by a vector, where the first item must be a tag describing the type of the element, followed by optional metadata, and finally the content of the element. For example if we wanted to create a paragraph we'd do the following:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:paragraph &amp;quot;a fine paragraph&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;to set the font style we could add the following metadata:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:paragraph
  {:style :bold :size 10 :family :halvetica :color &amp;#91;0 255 221&amp;#93;}
  &amp;quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;any metadata in an element will propagate to its children:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:paragraph
  {:style :bold :size 12 :family :halvetica :color &amp;#91;0 255 221&amp;#93;}
  &amp;quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&amp;quot;
  &amp;#91;:phrase &amp;quot;some text here&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;here the phrase will inherit the font style of its parent paragraph. However, the child element is always free to overwrite the parent metadata:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:paragraph
  {:style :bold :size 12}
  &amp;quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&amp;quot;
  &amp;#91;:phrase {:style :normal :size 10} &amp;quot;some text here&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This provides us with a lot of flexibility, while allowing to specify defaults for the entire document. The library attempts to provide reasonable behavior out of the box, so that adding metadata should not be necessary in most cases. &lt;/p&gt;&lt;p&gt;Some reports might include things like usage statistics. And to that end I leveraged the excellent &lt;a href='http://www.jfree.org/jfreechart/'&gt;JFreeChart&lt;/a&gt; library to provide a simple charting API:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;:chart {:type :line-chart 
         :title &amp;quot;Line Chart&amp;quot; 
         :x-label &amp;quot;checkpoints&amp;quot; 
         :y-label &amp;quot;units&amp;quot;} 
  &amp;#91;&amp;quot;Foo&amp;quot; &amp;#91;1 10&amp;#93; &amp;#91;2 13&amp;#93; &amp;#91;3 120&amp;#93; &amp;#91;4 455&amp;#93; &amp;#91;5 300&amp;#93; &amp;#91;6 600&amp;#93;&amp;#93;
  &amp;#91;&amp;quot;Bar&amp;quot; &amp;#91;1 13&amp;#93; &amp;#91;2 33&amp;#93; &amp;#91;3 320&amp;#93; &amp;#91;4 155&amp;#93; &amp;#91;5 200&amp;#93; &amp;#91;6 300&amp;#93;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;At this time bar charts, line charts, time series, and pie charts are supported. And because a chart is just an image, all the image styling, such as scaling and alignment, can be applied to it as well.&lt;/p&gt;&lt;p&gt;Since the API is completely declarative, it doesn't actually have to be encoded in Clojure structures. We could instead encode it in something like JSON, which is exactly what I ended up doing next. I created a service which would accept POST requests containing JSON encoded documents and return PDF documents. The service can be accessed by any application regardless of what language its written in, and can even be called by JavaScript from a browser as can be seen &lt;a href='http://yogthos.net/instant-pdf/'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Documentation and examples are available on the &lt;a href='https://github.com/yogthos/clj-pdf'&gt;github project page&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Thu, 16 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-14-Blogging-with-Noir.html</guid><link>https://yogthos.net/posts/2012-08-14-Blogging-with-Noir.html</link><title>Blogging with Noir</title><description>&lt;p&gt;Writing a blog engine in Noir turned out to be a very pleasant experience. The &lt;a href='https://github.com/yogthos/yuggoth'&gt;engine&lt;/a&gt; which is currently powering this blog  supports all the features one would expect from a blogging engine, some of which include:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;content caching&lt;/li&gt;&lt;li&gt;RSS feed&lt;/li&gt;&lt;li&gt;tags&lt;/li&gt;&lt;li&gt;markdown in posts and comments with live preview&lt;/li&gt;&lt;li&gt;syntax highlighting&lt;/li&gt;&lt;li&gt;file uploads and management through web UI&lt;/li&gt;&lt;li&gt;captchas for comments&lt;/li&gt;&lt;li&gt;latest comments view&lt;/li&gt;&lt;li&gt;controlling post visibility&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;All that weighs in at under 1K lines of Clojure, and some 50 lines of Js. I've outlined some of the quirks I ran into &lt;a href='http://yogthos.net/blog/16-Noir+tricks'&gt;previously&lt;/a&gt;. Now, I'd like to talk about what went right and what facilitated writing a complete functional website in only a few hundred lines of code.&lt;/p&gt;&lt;p&gt;I used &lt;a href='https://github.com/clojure/java.jdbc/'&gt;clojure.java.jdbc&lt;/a&gt; for database access. The library is very easy to use and provides all the basic functionality you'd expect with minimal fuss. You can define a database either using a map:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def mysql-db {:subprotocol &amp;quot;postgresql&amp;quot;
               :subname &amp;quot;//127.0.0.1:3306/clojure&amp;#95;test&amp;quot;
               :user &amp;quot;clojure&amp;#95;test&amp;quot;
               :password &amp;quot;clojure&amp;#95;test&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;by providing a JNDI name and configuring a JNDI data source on the app server:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def my-db {:name &amp;quot;jdbc/myDatasource&amp;quot;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;or by simply instantiating a data source as I do in the blog:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def db 
  {:datasource 
    &amp;#40;doto &amp;#40;new PGPoolingDataSource&amp;#41;
       &amp;#40;.setServerName   &amp;#40;:host blog-config&amp;#41;&amp;#41;
       &amp;#40;.setDatabaseName &amp;#40;:schema blog-config&amp;#41;&amp;#41;
       &amp;#40;.setUser         &amp;#40;:user blog-config&amp;#41;&amp;#41;
       &amp;#40;.setPassword     &amp;#40;:pass blog-config&amp;#41;&amp;#41;
       &amp;#40;.setMaxConnections 10&amp;#41;&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Calling SQL commands is straightforward as well, all statements must be wrapped with a &lt;code&gt;with-connection&lt;/code&gt; statement. This ensures that any result sets are cleaned up and the connection is closed once you're done with it. I found the library to be very intuitive and easy to work with. The documentation &lt;a href='https://github.com/clojure/java.jdbc/tree/master/doc/clojure/java/jdbc'&gt;is available on github&lt;/a&gt; and covers most use cases. All of my db interaction ended up fitting in just under 250 lines, which makes it easy to keep on top of.&lt;/p&gt;&lt;p&gt;&lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt; has been indispensable in making things concise and easy to manage. Noir and &lt;a href='http://weavejester.github.com/hiccup/'&gt;Hiccup&lt;/a&gt; make it trivial to organize the pages and their controllers into self contained chunks.&lt;/p&gt;&lt;p&gt;Because it encourages making things stateless, it's easy to add functionality in isolated chunks. This means that you can add a particular feature, such as RSS support, without having to worry how it might interact with existing code. I find this especially important when writing side projects as it means that you have a very short ramp up time when you come back to a project after not having touched it for a while.&lt;/p&gt;&lt;p&gt;I'm personally a fan of using Hiccup for generating HTML, as it allows using the full power of Clojure for templating. However, some people have concerns about not having the actual HTML that designers can then style. Fortunately, there's nothing inherent to Noir that ties it to Hiccup. A &lt;code&gt;defpage&lt;/code&gt; simply has to return an HTML string, how that string gets generated is entirely up to you. And there's a &lt;a href='http://paulosuzart.github.com/blog/2012/03/25/web-noir-plus-enlive-template/'&gt;great guide&lt;/a&gt; for using Noir with &lt;a href='https://github.com/cgrand/enlive/'&gt;Enlive&lt;/a&gt;, which is designed for HTML based templating. Again, I have to point out the thoughtfulness of design which separates creating routes and serving pages from the libraries which deal with actually generating them.&lt;/p&gt;&lt;p&gt;For Markdown parsing I dredged up &lt;a href='https://github.com/yogthos/markdown-clj'&gt;an old library of mine&lt;/a&gt;, and with a few tweaks it's been doing its job as far as far as this blog is concerned. One advantage of this particular library is that it compiles to both Clojure and ClojureScript, so I can do previews in the browser and guarantee that they will be rendered the same by the server.&lt;/p&gt;&lt;p&gt;I added the ability to add language hinting using github style markdown, eg: &amp;#96;&amp;#96;&amp;#96;clojure, to output tags compatible with the &lt;a href='http://alexgorbatchev.com/SyntaxHighlighter/'&gt;syntax highlighter&lt;/a&gt;, which I then use to do code highlighting in the browser.&lt;/p&gt;&lt;p&gt;I also didn't find any readily available libraries for generating RSS from Clojure, so I proceeded to make &lt;a href='https://github.com/yogthos/clj-rss'&gt;clj-rss&lt;/a&gt;, which turned out to be very easy thanks to the excellent XML support in the standard library and a few macros.&lt;/p&gt;&lt;p&gt;For my captcha needs I turned to a Java library called &lt;a href='http://mvnrepository.com/artifact/net.sf.jlue/jlue-core'&gt;jlue&lt;/a&gt;. Thanks to the excellent Java interop, using it is quite seamless:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn gen-captcha &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;text &amp;#40;gen-captcha-text&amp;#41;
        captcha &amp;#40;doto &amp;#40;new Captcha&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;session/put! :captcha 
                  {:text text 
                   :image &amp;#40;.gen captcha text 250 40&amp;#41;}&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defpage &amp;quot;/captcha&amp;quot; &amp;#91;&amp;#93;
  &amp;#40;gen-captcha&amp;#41;
  &amp;#40;resp/content-type 
    &amp;quot;image/jpeg&amp;quot; 
    &amp;#40;let &amp;#91;out &amp;#40;new ByteArrayOutputStream&amp;#41;&amp;#93;
      &amp;#40;ImageIO/write &amp;#40;:image &amp;#40;session/get :captcha&amp;#41;&amp;#41; &amp;quot;jpeg&amp;quot; out&amp;#41;
      &amp;#40;new ByteArrayInputStream &amp;#40;.toByteArray out&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Finally, all of the building and packaging is handled by &lt;a href='http://github.com/technomancy/leiningen/'&gt;Leiningen&lt;/a&gt;, which makes it trivial to track dependencies and package up the resulting application. In my case I'm deploying the blog to Tomcat, and so I simply build a WAR using:&lt;pre&gt;&lt;code class="bash"&gt;lein ring uberwar
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The resulting WAR can be dropped on any Java application server. If you wanted to deploy to Heroku, you simply have to add a &lt;code&gt;Procfile&lt;/code&gt; to the root directory of the project with the following contents:&lt;pre&gt;&lt;code class="bash"&gt;web: lein trampoline run -m yuggoth.server
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Overall, I experienced very few issues and found the experience to be overwhelmingly positive. In my opinion the current tools and libraries available in Clojure allow writing web sites just as easily, if not more so, as most of the established languages out there.&lt;/p&gt;</description><pubDate>Tue, 14 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-11-Why-be-conservative.html</guid><link>https://yogthos.net/posts/2012-08-11-Why-be-conservative.html</link><title>Why be conservative</title><description>&lt;p&gt;&lt;a href='https://plus.google.com/110981030061712822816/posts'&gt;Steve Yegge&lt;/a&gt; has made a post introducing the idea of liberalism and conservatism in programming languages. While it is an entertaining read I have to question the usefulness of the proposed metric.&lt;/p&gt;&lt;p&gt;In my opinion the language either gets out of your way and makes it easy to do what you need to do or it doesn't. I don't really care how it does it as long as at the end of the day I enjoy using it and I'm productive in it.&lt;/p&gt;&lt;p&gt;It can certainly be argued that Clojure is conservative in some ways. As has been pointed out in the results of the &lt;a href='http://java.dzone.com/articles/results-2012-state-clojure'&gt;2012 State of Clojure&lt;/a&gt; survey, some people find the process for contributing to the language too restrictive. Rich Hickey is very cautious about adding new features and about the way they're added to the language.&lt;/p&gt;&lt;p&gt;But I would argue that this is in fact a good thing and the end result is a cleaner and more consistent language. Destructuring is a concrete example of this. At one point people were asking for named arguments for functions and Rich resisted the idea of adding them. Instead, we got destructuring which is a more powerful and general purpose tool. It can be used for naming arguments in functions, but it can also be used for many other things as well.&lt;/p&gt;&lt;p&gt;Let's consider what the result would have been if Clojure was more liberal about adding features, and named arguments were in fact added. There would now be two separate ways to do the same thing, each with its own quirks. Different code bases would use different rules for naming function parameters and you would have to make adapters to make them work together.&lt;/p&gt;&lt;p&gt;The more eagerly features get accepted into a language, the more likely they it is that the solution won't be elegant or general purpose. Which means that inevitably a new feature needs to be added to cover the case which isn't adequately addressed by the original attempt. &lt;/p&gt;&lt;p&gt;In my opinion this quickly leads to having a crufty syntax, and requires a lot of mental overhead to work with code written by others. Since, some people will prefer this or that particular style of doing things you have to be aware of every quirk and their interactions.&lt;/p&gt;&lt;p&gt;Fact of the matter is that Lisp is already phenomenally powerful, more so than most languages out there. It would seem prudent not to be rash about trying to improve it. &lt;/p&gt;</description><pubDate>Sat, 11 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-07-Setting-up-Eclipse-for-Clojure.html</guid><link>https://yogthos.net/posts/2012-08-07-Setting-up-Eclipse-for-Clojure.html</link><title>Setting up Eclipse for Clojure</title><description>&lt;p&gt;The &lt;a href='http://cemerick.com/2012/08/06/results-of-the-2012-state-of-clojure-survey/'&gt;Results of the 2012 State of Clojure survey&lt;/a&gt; are out, and they look very exciting indeed. More people are using Clojure, the community is growing, and for the most part things appear to be progressing well. However, one notable problem that people are reporting is actually getting started with Clojure.&lt;/p&gt;&lt;p&gt;I'd like to spend some time here to help people actually get up and running with the language. First, I'll cover setting up the development environment. Many Clojure users gravitate towards Emacs, which is a natural choice for Lisp development. But if you're new to Clojure and you haven't used Emacs before, I would strongly suggest against learning both Emacs and Clojure at the same time. &lt;/p&gt;&lt;p&gt;The reason being is that Emacs is fairly arcane in many ways, and it behaves very differently from traditional IDEs, such as NetBeans or Eclipse. Learning a new language, which has very different syntax from languages you might be used to, and requires learning a new programming paradigm is enough to keep one busy without having to learn a quirky IDE on the side.&lt;/p&gt;&lt;p&gt;My recommendation would be to grab a copy of &lt;a href='http://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/junor'&gt;Eclipse&lt;/a&gt; and install the &lt;a href='http://code.google.com/p/counterclockwise/'&gt;Counterclockwise plugin&lt;/a&gt;. Installing the plugin is incredibly simple, once you have Eclipse running follow the following steps:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;navigate to the "Install new Software" tab under the help menu&lt;/li&gt;&lt;li&gt;paste in the CCW update URL: http://ccw.cgrand.net/updatesite in the "Work with:" text field&lt;/li&gt;&lt;li&gt;check the "Clojure Programming" checkbox and hit the "Next" button&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Counterclockwise takes care of setting up Clojure and Leiningen for you. And once the plugin is installed, you will be able to create a new Clojure project or a new Leiningen project. I would recommend making Leiningen projects, since they allow easily managing dependencies by updating the &lt;code&gt;project.clj&lt;/code&gt; file in the project directory. I'll touch more on this later.&lt;/p&gt;&lt;p&gt;At this point, I'll assume that you have Eclipse with CCW up and running. So, navigate to File-&gt;new-&gt;project in Eclipse menu. Then select Leiningen-&gt;Leiningen project. Here you'll see the &lt;code&gt;default&lt;/code&gt; Leiningen Template filled in. And only thing you have to do is provide a project name. Let's call our project "clojure-test" and hit the finish button.&lt;/p&gt;&lt;p&gt;You should now see a new project in your Package Explorer view on the left. The project template will have a &lt;code&gt;src&lt;/code&gt; folder which will contain the package folder named &lt;code&gt;clojure&amp;#95;test&lt;/code&gt;. Since Java cannot use dashes in names, all the dashes in package folders for namespaces get converted to underscores. The pckage will contain a &lt;code&gt;core.clj&lt;/code&gt; file, and its contents should look like the following:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns clojure-test.core&amp;#41;

&amp;#40;defn -main
  &amp;quot;I don't do a whole lot.&amp;quot;
  &amp;#91;&amp;amp; args&amp;#93;
  &amp;#40;println &amp;quot;Hello, World!&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Let's open it and then hit the run button. You should see a REPL pop up momentarily on the bottom of the IDE. If all went well, your project should be ready to work on. The code that's in the file will have already been loaded up in the REPL when we hit run, and we should now be able to call our &lt;code&gt;-main&lt;/code&gt; function.&lt;/p&gt;&lt;p&gt;To do that, let's write the code which calls main below it:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;-main&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Then navigate the cursor inside the call body and hit CTRL+ENTER on Linux/Windows or CMD+ENTER on OS X. You should see "Hello, World!" printed in the REPL view on the bottom. We can now change the behavior of the &lt;code&gt;-main&lt;/code&gt; function and after it is reloaded the new behavior will be available next time it's called.&lt;/p&gt;&lt;p&gt;I would also recommend enabling the "strict/paredit" mode under Preferences-&gt;Clojure-&gt;Editor section. This will allow the editor to keep track of balancing the parens for you. It might seem odd at first, but I highly encourage you to stick with it. &lt;/p&gt;&lt;p&gt;Another useful feature of the editor is the ability to select code by expression. If you navigate inside a function and press ALT+SHIFT+UP (use CMD instead of ALT in OS X), then inner body of the expression will be selected, pressing it again, will select the expression, and then the outer body, and so on. Conversely pressing ALT+SHIFT+DOWN will narrow the selection. This allows you to quickly navigate nested structures, and select code by chunks of logic as opposed to simply selecting individual lines.&lt;/p&gt;&lt;p&gt;I've also mentioned the &lt;code&gt;project.clj&lt;/code&gt; file in your project folder earlier. This file should look like the following:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defproject clojure-test &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;http://example.com/FIXME&amp;quot;
  :license {:name &amp;quot;Eclipse Public License&amp;quot;
            :url &amp;quot;http://www.eclipse.org/legal/epl-v10.html&amp;quot;}
  :dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.3.0&amp;quot;&amp;#93;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;You can add new dependencies to your project by simply sticking them in the dependencies vector. For example, if we wanted to add an HTTP client, we'd go to http://clojuresphere.herokuapp.com/ click on clj-http link. From there select the &lt;a href='http://clojars.org/clj-http/clj-http'&gt;Clojars link&lt;/a&gt; and copy the following:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#91;clj-http &amp;quot;0.5.2&amp;quot;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;now we'll simply paste it under dependencies in our &lt;code&gt;project.clj&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;:dependencies &amp;#91;&amp;#91;org.clojure/clojure &amp;quot;1.3.0&amp;quot;&amp;#93;
               &amp;#91;clj-http &amp;quot;0.5.2&amp;quot;&amp;#93;&amp;#93;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In our package explorer view on the left we should be able to expand "Leiningen dependencies" and see the &lt;code&gt;clj-http&lt;/code&gt; jar included there. We will now have to kill our current REPL, to do that navigate to the terminal view next to it and press the stop button. When we start a new instance of the REPL, the library will be available for use. In the core file we can now add it to the namespace:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns clojure-test.core
 &amp;#40;:require &amp;#91;clj-http.client :as client&amp;#93;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and test using the client by typing&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;client/get &amp;quot;http://google.com&amp;quot;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and running it as we did earlier. This should cover all the basics of using Clojure with Counterclockwise, and allow you to get hacking on your project.&lt;/p&gt;&lt;p&gt;I'd also recommend visiting the following sites:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='http://www.4clojure.com/'&gt;4Clojure&lt;/a&gt; is an excellent site for practicing small exercises in Clojure. Be sure to make an account and follow some of the top users. When you solve a problem, you'll be able to see how others solve it and get a taste for idiomatic Clojure code.&lt;/li&gt;&lt;li&gt;&lt;a href='http://java.ociweb.com/mark/clojure/article.html'&gt;Clojure - Functional Programming for the JVM&lt;/a&gt; is a very comprehensive introduction to Clojure aimed at Java programmers.&lt;/li&gt;&lt;li&gt;&lt;a href='http://clojuredocs.org/'&gt;ClojureDocs&lt;/a&gt; is an excellent documentation site for Clojure which contains many examples on using the functions in the standard library.&lt;/li&gt;&lt;li&gt;&lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt; is an great Clojure framework for making web apps, in fact this blog is built on top of it with source available &lt;a href='http://github.com/yogthos/yuggoth'&gt;here&lt;/a&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;There are many other great Clojure sites that I failed to mention here, but the above should provide a good starting point.&lt;/p&gt;</description><pubDate>Tue, 07 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-04-Serving-RSS-with-Clojure.html</guid><link>https://yogthos.net/posts/2012-08-04-Serving-RSS-with-Clojure.html</link><title>Serving RSS with Clojure</title><description>&lt;p&gt;I recently got invited to join &lt;a href='http://planet.clojure.in/'&gt;Planet Clojure&lt;/a&gt;, which is an excellent place for keeping up with what people are up to in Clojure world. As part of being syndicated I had to add an &lt;a href='http://en.wikipedia.org/wiki/RSS'&gt;RSS&lt;/a&gt; feed to my blog. A cursory Google search came up with lots of tutorials for parsing RSS, but nothing regarding generating it. Turns out that it's very straight forward and it takes less than a 50 lines of code to create a proper RSS feed for your site.&lt;/p&gt;&lt;p&gt;First, a bit of background about RSS. Essentially, it's a very simple syndication format designed to allow pushing out notifications about frequently updated content such as blog posts. RSS is served as XML and each feed has to consist of a channel tag with some metadata and item tags, each one describing a specific update such as a new blog post.&lt;/p&gt;&lt;p&gt;All we have to do to create our RSS feed is to structure the data accordingly and serialize it to XML. Clojure standard library provides a simple way to output XML using the &lt;code&gt;emit&lt;/code&gt; function in the &lt;code&gt;clojure.xml&lt;/code&gt; namespace. It accepts data in the following format:&lt;pre&gt;&lt;code class="clojure"&gt;{:tag :tag-name :attrs attrs-map :content &amp;#91;content&amp;#93;}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The content in the above can contain a mix of strings and tags. One thing to be aware of is that any other content will result in a null pointer exception, so it's one of rare cases where that doesn't get handled gracefully by default. Once we've constructed a proper tag we can serialize it to XML as follows:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;with-out-str 
  &amp;#40;clojure.xml/emit 
    {:tag :channel :attrs nil :content &amp;#91;&amp;#93;}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;which results in&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;?xml version='1.0' encoding='UTF-8'?&amp;gt;
&amp;lt;channel&amp;gt;
&amp;lt;/channel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Note that &lt;code&gt;emit&lt;/code&gt; needs to be wrapped in &lt;code&gt;with-out-str&lt;/code&gt; to capture its output into a string. RSS also specifies the format in which time should be output, so we'll make a helper function to handle that:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn format-time &amp;#91;time&amp;#93; 
  &amp;#40;.format &amp;#40;new java.text.SimpleDateFormat 
                &amp;quot;EEE, dd MMM yyyy HH:mm:ss ZZZZ&amp;quot;&amp;#41; time&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Writing out the tags by hand gets tedious, so I wrote a macro to output the tags for us: &lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro tag &amp;#91;id attrs &amp;amp; content&amp;#93;
  `{:tag &amp;#126;id :attrs &amp;#126;attrs :content &amp;#91;&amp;#126;@content&amp;#93;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;I covered macros briefly in an &lt;a href='http://yogthos.net/blog/14'&gt;earlier post&lt;/a&gt;. The only new syntax used here is the &lt;code&gt;&amp;#126;@&lt;/code&gt; notation, which simply says that the items in content should be inserted into the enclosing structure, eg:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;tag :foo nil &amp;quot;foo&amp;quot; &amp;quot;bar&amp;quot; &amp;quot;baz&amp;quot;&amp;#41;
{:tag :foo, :attrs nil, :content &amp;#91;&amp;quot;foo&amp;quot; &amp;quot;bar&amp;quot; &amp;quot;baz&amp;quot;&amp;#93;}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Armed with this macro let's write the function to describe an individual post. The function accepts the site, the author and a map describing the post as parameters, then generates the appropriate tags as per RSS specification.&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn item &amp;#91;site author {:keys &amp;#91;id title content time&amp;#93;}&amp;#93;
  &amp;#40;let &amp;#91;link &amp;#40;str site &amp;quot;/&amp;quot; id &amp;#41;&amp;#93; 
    &amp;#40;tag :item nil
         &amp;#40;tag :guid nil link&amp;#41;
         &amp;#40;tag :title nil title&amp;#41;
         &amp;#40;tag :dc:creator nil author&amp;#41;
         &amp;#40;tag :description nil content&amp;#41;
         &amp;#40;tag :link nil link&amp;#41;
         &amp;#40;tag :pubDate nil &amp;#40;format-time time&amp;#41;&amp;#41;
         &amp;#40;tag :category nil &amp;quot;clojure&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Let's test that it does what we expect:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;item &amp;quot;http://yogthos.net&amp;quot;
      &amp;quot;Yogthos&amp;quot; 
      {:id 1 
       :title &amp;quot;Test post&amp;quot; 
       :content &amp;quot;Some content&amp;quot; 
       :time &amp;#40;new Date&amp;#41;}&amp;#41;

{:content
 &amp;#91;{:content &amp;#91;&amp;quot;http://yogthos.net/1&amp;quot;&amp;#93;, :attrs nil, :tag :guid}
  {:content &amp;#91;&amp;quot;Test post&amp;quot;&amp;#93;, :attrs nil, :tag :title}
  {:content &amp;#91;&amp;quot;Yogthos&amp;quot;&amp;#93;, :attrs nil, :tag :dc:creator}
  {:content &amp;#91;&amp;quot;Some content&amp;quot;&amp;#93;, :attrs nil, :tag :description}
  {:content &amp;#91;&amp;quot;http://yogthos.net/1&amp;quot;&amp;#93;, :attrs nil, :tag :link}
  {:content &amp;#91;&amp;quot;Sat, 04 Aug 2012 18:16:03 -0400&amp;quot;&amp;#93;,
   :attrs nil,
   :tag :pubDate}
  {:content &amp;#91;&amp;quot;clojure&amp;quot;&amp;#93;, :attrs nil, :tag :category}&amp;#93;,
 :attrs nil,
 :tag :item}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;If we pass the above to &lt;code&gt;xml/emit&lt;/code&gt; we'll get the corresponding XML. Next we'll need a function which will will create the representation of the channel:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn message &amp;#91;site title author posts&amp;#93;
  &amp;#40;let &amp;#91;date &amp;#40;format-time &amp;#40;new Date&amp;#41;&amp;#41;&amp;#93; 
    &amp;#40;tag :rss {:version &amp;quot;2.0&amp;quot;
               :xmlns:dc &amp;quot;http://purl.org/dc/elements/1.1/&amp;quot;
               :xmlns:sy &amp;quot;http://purl.org/rss/1.0/modules/syndication/&amp;quot;}
         &amp;#40;update-in 
           &amp;#40;tag :channel nil
                &amp;#40;tag :title nil &amp;#40;:title &amp;#40;first posts&amp;#41;&amp;#41;&amp;#41;
                &amp;#40;tag :description nil title&amp;#41;
                &amp;#40;tag :link nil site&amp;#41;
                &amp;#40;tag :lastBuildDate nil date&amp;#41;
                &amp;#40;tag :dc:creator nil author&amp;#41;
                &amp;#40;tag :language nil &amp;quot;en-US&amp;quot;&amp;#41;
                &amp;#40;tag :sy:updatePeriod nil &amp;quot;hourly&amp;quot;&amp;#41;
                &amp;#40;tag :sy:updateFrequency nil &amp;quot;1&amp;quot;&amp;#41;&amp;#41;
           &amp;#91;:content&amp;#93;
           into &amp;#40;map &amp;#40;partial item site author&amp;#41; posts&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Again, this is fairly straight forward, the function takes the site url, blog title, the author and the posts. Then it creates the necessary tags to describe the channel and inserts the formatted posts into it. We should now be able to generate valid RSS content by calling it with some data:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;message &amp;quot;http://yogthos.net&amp;quot; &amp;quot;My blog&amp;quot; &amp;quot;Yogthos&amp;quot; 
         &amp;#91;{:id 1 
           :title &amp;quot;Test post&amp;quot; 
           :content &amp;quot;Some content&amp;quot; 
           :time &amp;#40;new Date&amp;#41;}&amp;#93;&amp;#41;

{:content
 &amp;#91;{:content
   &amp;#91;{:content &amp;#91;&amp;quot;Test post&amp;quot;&amp;#93;, :attrs nil, :tag :title}
    {:content &amp;#91;&amp;quot;My blog&amp;quot;&amp;#93;, :attrs nil, :tag :description}
    {:content &amp;#91;&amp;quot;http://yogthos.net&amp;quot;&amp;#93;, :attrs nil, :tag :link}
    {:content &amp;#91;&amp;quot;Sat, 04 Aug 2012 18:23:06 -0400&amp;quot;&amp;#93;,
     :attrs nil,
     :tag :lastBuildDate}
    {:content &amp;#91;&amp;quot;Yogthos&amp;quot;&amp;#93;, :attrs nil, :tag :dc:creator}
    {:content &amp;#91;&amp;quot;en-US&amp;quot;&amp;#93;, :attrs nil, :tag :language}
    {:content &amp;#91;&amp;quot;hourly&amp;quot;&amp;#93;, :attrs nil, :tag :sy:updatePeriod}
    {:content &amp;#91;&amp;quot;1&amp;quot;&amp;#93;, :attrs nil, :tag :sy:updateFrequency}
    {:content
     &amp;#91;{:content &amp;#91;&amp;quot;http://yogthos.net/blog/1&amp;quot;&amp;#93;, :attrs nil, :tag :guid}
      {:content &amp;#91;&amp;quot;Test post&amp;quot;&amp;#93;, :attrs nil, :tag :title}
      {:content &amp;#91;&amp;quot;Yogthos&amp;quot;&amp;#93;, :attrs nil, :tag :dc:creator}
      {:content &amp;#91;&amp;quot;Some content&amp;quot;&amp;#93;, :attrs nil, :tag :description}
      {:content &amp;#91;&amp;quot;http://yogthos.net/blog/1&amp;quot;&amp;#93;, :attrs nil, :tag :link}
      {:content &amp;#91;&amp;quot;Sat, 04 Aug 2012 18:23:06 -0400&amp;quot;&amp;#93;,
       :attrs nil,
       :tag :pubDate}
      {:content &amp;#91;&amp;quot;clojure&amp;quot;&amp;#93;, :attrs nil, :tag :category}&amp;#93;,
     :attrs nil,
     :tag :item}&amp;#93;,
   :attrs nil,
   :tag :channel}&amp;#93;,
 :attrs
 {:version &amp;quot;2.0&amp;quot;,
  :xmlns:dc &amp;quot;http://purl.org/dc/elements/1.1/&amp;quot;,
  :xmlns:sy &amp;quot;http://purl.org/rss/1.0/modules/syndication/&amp;quot;},
 :tag :rss}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Finally, we'll write a function which converts the message to XML:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn rss-feed &amp;#91;site title author posts&amp;#93;
  &amp;#40;with-out-str &amp;#40;emit &amp;#40;message site title author posts&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We can confirm that we're generating valid content by pasting it to &lt;a href='http://validator.w3.org/feed/#validate_by_input'&gt;W3C Feed Validation Service&lt;/a&gt;. This is all that's needed to create a valid RSS message. It can now be served over HTTP using your favorite library or framework. &lt;/p&gt;&lt;p&gt;Complete code for the example can be found &lt;a href='https://gist.github.com/3260456'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;h2 id="updates"&gt;Updates&lt;/h2&gt;&lt;p&gt;I've since rolled all of the above into a (hopefully :) friendly &lt;a href='https://github.com/yogthos/clj-rss'&gt;clj-rss&lt;/a&gt; library.&lt;/p&gt;</description><pubDate>Sat, 04 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-08-02-Noir-tricks.html</guid><link>https://yogthos.net/posts/2012-08-02-Noir-tricks.html</link><title>Noir tricks</title><description>&lt;p&gt;This blog is built on top of &lt;a href='http://www.webnoir.org/'&gt;Noir&lt;/a&gt;, which is quite excellent for the most part. However, I did run into one problem which I spent a bit of time on. I'd like to share my workarounds to save others time.&lt;/p&gt;&lt;p&gt;First issue I noticed is that &lt;code&gt;response/redirect&lt;/code&gt; doesn't respect the servlet context. This means that if you're not deploying your app to the root context, your redirects will not work properly. &lt;/p&gt;&lt;p&gt;After some digging and questions on the Google groups I found out that the offending function is &lt;code&gt;resolve-url&lt;/code&gt; in &lt;code&gt;noir.options&lt;/code&gt; namespace. When it builds the URL string it doesn't check for the context and as such the resulting URL ends up redirecting to the root of the app server regardless of what context the servlet was deployed at.&lt;/p&gt;&lt;p&gt;My workaround for this is a bit of a hack, and if anybody has a better solution I'd love to know, but it works well for most purposes. In my &lt;code&gt;server.clj&lt;/code&gt; I added a new handler wrapper, which redefines the offending function with one that checks if the URL is relative and prepends the context to it as needed.&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn fix-base-url &amp;#91;handler&amp;#93;
  &amp;#40;fn &amp;#91;request&amp;#93;
    &amp;#40;with-redefs &amp;#91;noir.options/resolve-url 
                  &amp;#40;fn &amp;#91;url&amp;#93; 
                    ;prepend context to the relative URLs
                    &amp;#40;if &amp;#40;.contains url &amp;quot;://&amp;quot;&amp;#41;
                      url &amp;#40;str &amp;#40;:context request&amp;#41; url&amp;#41;&amp;#41;&amp;#41;&amp;#93;
      &amp;#40;handler request&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;A related issue is that &lt;code&gt;pre-route&lt;/code&gt; doesn't respect the context either. I decided to simply write a macro for defining private pages:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro private-page &amp;#91;path params &amp;amp; content&amp;#93;
  `&amp;#40;noir.core/defpage 
     &amp;#126;path 
     &amp;#126;params 
     &amp;#40;if &amp;#40;session/get :admin&amp;#41; 
       &amp;#40;do &amp;#126;@content&amp;#41; &amp;#40;resp/redirect &amp;quot;/&amp;quot;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;An added advantage of the macro is that I don't have to remember to update &lt;code&gt;pre-routes&lt;/code&gt; when I want to make a page private. &lt;/p&gt;&lt;p&gt;Also, there are a couple of things to be aware of if you wish to make a WAR. Make sure that all your views are required in your server namespace, &lt;code&gt;:gen-class&lt;/code&gt; is set and that &lt;code&gt;server/load-views-ns&lt;/code&gt; is used instead of &lt;code&gt;server/load-views&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns yuggoth.server
  &amp;#40;:require 
   ...
   &amp;#91;yuggoth.views archives auth blog comments common profile rss upload&amp;#93;&amp;#41;
   &amp;#40;:gen-class&amp;#41;&amp;#41;

&amp;#40;server/load-views-ns 'yuggoth.views&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In your project.clj add the following:&lt;pre&gt;&lt;code class="clojure"&gt;:ring {:handler yuggoth.server/handler}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;With the above in place you can build an uberwar with&lt;pre&gt;&lt;code class="bash"&gt;lein ring uberwar
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The resulting WAR should deploy on any app server such as Tomcat or Glassfish without problems. Aside from the above quirks, I haven't run into any other issues with Noir, and I'm absolutely in love with it. &lt;/p&gt;</description><pubDate>Thu, 02 Aug 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-31-open-access.html</guid><link>https://yogthos.net/posts/2012-07-31-open-access.html</link><title>open access</title><description>&lt;p&gt;Sometimes you might run into a situation where you're using a library which defines a certain function in a way that might not work the way you need it to in a particular context. To make things worse, this function might be used by the library internally, so you can't simply write your own version and use it. &lt;/p&gt;&lt;p&gt;In some languages it's possible to use &lt;a href='http://en.wikipedia.org/wiki/Monkey_patch'&gt;monkey patching&lt;/a&gt; to get around this problem. This approach allows you to simply redefine the offending function at runtime with your own version. The downside of this approach is that the change is global and as such might interact poorly with other code which expects the original version.&lt;/p&gt;&lt;p&gt; In Clojure it's possible redefine an existing function in a particular context using &lt;code&gt;with-redefs&lt;/code&gt;. This approach gives us the ability to make runtime modifications in a safer fashion where we know exactly what code is affected. &lt;/p&gt;&lt;p&gt;Let's look at an example where we have a &lt;code&gt;get-data&lt;/code&gt; function defined in namespace &lt;code&gt;foo&lt;/code&gt; which is used by &lt;code&gt;display-results&lt;/code&gt; in namespace &lt;code&gt;bar&lt;/code&gt;. When we write tests for &lt;code&gt;bar&lt;/code&gt; we would like to use preset test data instead of calling out to the database:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;ns foo&amp;#41;

&amp;#40;defn get-data &amp;#91;&amp;#93;
  ;gets some data from a db
  &amp;#41;

&amp;#40;ns bar
 &amp;#40;:require foo&amp;#41;&amp;#41;

&amp;#40;defn display-results &amp;#91;&amp;#93;
  &amp;#40;apply str &amp;#40;interpose &amp;quot;, &amp;quot; &amp;#40;foo/get-data&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;ns tests
  &amp;#40;:use clojure.test&amp;#41;
  &amp;#40;:require foo bar&amp;#41;&amp;#41;

&amp;#40;deftest display-results-test
  &amp;#40;with-redefs &amp;#91;foo/get-data &amp;#40;fn&amp;#91;&amp;#93; &amp;#91;&amp;quot;Doe&amp;quot;, &amp;quot;John&amp;quot;&amp;#93;&amp;#41;&amp;#93;
    &amp;#40;is &amp;#40;= &amp;quot;Doe, John&amp;quot; &amp;#40;bar/display-results&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now any code that references &lt;code&gt;foo/get-data&lt;/code&gt; inside the &lt;code&gt;with-redefs&lt;/code&gt; scope will get &lt;code&gt;&amp;#91;&amp;quot;Doe&amp;quot;, &amp;quot;John&amp;quot;&amp;#93;&lt;/code&gt; as a result. &lt;/p&gt;</description><pubDate>Tue, 31 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-27-a-look-at-macros.html</guid><link>https://yogthos.net/posts/2012-07-27-a-look-at-macros.html</link><title>a look at macros</title><description>&lt;p&gt;Lisp macros can be rather confusing and especially so for newcomers. In fact, the rule of thumb is not to use macros if you can avoid them. That said, macros can be an incredibly powerful tool and have innumerable uses. I'd like to give a concrete example of a macro that I'm using in this blog engine.&lt;/p&gt;&lt;p&gt;I wanted to be able to cache page content in memory, so that the page doesn't need to be generated for every single request. This means that before rendering a page I want to check if the page is in my cache, and if the cache hasn't expired then serve the cached page, otherwise render a new version and cache it.&lt;/p&gt;&lt;p&gt;First I created an atom which would store the cached content:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;def cache &amp;#40;atom {}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Next I wrote the cache logic for the &lt;code&gt;/blog&lt;/code&gt; page:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/blog/:postid&amp;quot; {:keys &amp;#91;id&amp;#93;}
  &amp;#40;let &amp;#91;last-updated &amp;#40;:time &amp;#40;get @cache id&amp;#41;&amp;#41;
        cur-time     &amp;#40;.getTime &amp;#40;new java.util.Date&amp;#41;&amp;#41;&amp;#93;

    &amp;#40;if &amp;#40;or &amp;#40;nil? last-updated&amp;#41;
            &amp;#40;&amp;gt; &amp;#40;- cur-time last-updated&amp;#41; 10000&amp;#41;&amp;#41;
      &amp;#40;swap! cache assoc id {:time cur-time 
                             :content &amp;#40;entry &amp;#40;db/get-post id&amp;#41;&amp;#41;}&amp;#41;&amp;#41;
    &amp;#40;:content &amp;#40;get @cache id&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Obviously, we don't want to repeat this logic each time we wish to cache something, and we'd like an easy way to modify existing functions to allow caching. Here's where macros come in. One property of macros is that, unlike functions, they do not execute the s-expressions which are passed in. Let's look at how this works in practice:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defn foo &amp;#91;&amp;#93; &amp;#40;println &amp;quot;foo was called&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn bar &amp;#91;f&amp;#93;&amp;#41;

&amp;#40;bar &amp;#40;foo&amp;#41;&amp;#41;

=&amp;gt;foo was called
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Here &lt;code&gt;foo&lt;/code&gt; is executed as we would expect and "foo was called" is printed, but what happens if we make bar a macro instead?&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro bar &amp;#91;f&amp;#93;&amp;#41;
&amp;#40;bar &amp;#40;foo&amp;#41;&amp;#41;
=&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This time nothing is printed! In a macro the parameters are treated as data and are not evaluated unless we explicitly choose to do so:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro bar &amp;#91;f&amp;#93; f&amp;#41;
&amp;#40;bar &amp;#40;foo&amp;#41;&amp;#41;
=&amp;gt;foo was called
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;A macro allows us to change code before it is compiled, and at compile time it is replaced with its output. We can check this by running &lt;code&gt;macroexpand&lt;/code&gt;:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;macroexpand '&amp;#40;bar &amp;#40;foo&amp;#41;&amp;#41;&amp;#41;
=&amp;gt;&amp;#40;foo&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We can see that &lt;code&gt;&amp;#40;bar &amp;#40;foo&amp;#41;&amp;#41;&lt;/code&gt; simply gets replaced with &lt;code&gt;&amp;#40;foo&amp;#41;&lt;/code&gt; which is what our macro is returning. While the previous version would evaluate to nil, and &lt;code&gt;foo&lt;/code&gt; would never be executed.&lt;/p&gt;&lt;p&gt;As you might have guessed by now, we can pass any s-expression to a macro and then decide inside the macro whether we'd like to evaluate it. So, let's see how we can use this to make our caching macro:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defmacro cache &amp;#91;id content&amp;#93;
  `&amp;#40;let &amp;#91;last-updated# &amp;#40;:time &amp;#40;get @cached &amp;#126;id&amp;#41;&amp;#41;
         cur-time#     &amp;#40;.getTime &amp;#40;new java.util.Date&amp;#41;&amp;#41;&amp;#93;

      &amp;#40;if &amp;#40;or &amp;#40;nil? last-updated#&amp;#41;
              &amp;#40;&amp;gt; &amp;#40;- cur-time# last-updated#&amp;#41; 10000&amp;#41;&amp;#41;
        &amp;#40;swap! cached assoc &amp;#126;id {:time cur-time#
                                 :content &amp;#126;content}&amp;#41;&amp;#41;
      &amp;#40;:content &amp;#40;get @cached &amp;#126;id&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We can move the logic which checks if we should use a cached value into our macro and pass in the id and the s-expression to run if cache needs to be updated. The code looks very similar to our original version, except for a few new symbols. First thing you'll notice is that we used ` in front of our &lt;i&gt;let&lt;/i&gt; expression, this quotes the body of the expression. The # at the end of the binding names ensures that the names are unique and won't collide with other symbols at compile time. Finally ~ says that the next expression should be unquoted.&lt;/p&gt;&lt;p&gt;Let's run &lt;i&gt;macroexpand&lt;/i&gt; again to make sure our macro is outputting something reasonable:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;pprint &amp;#40;macroexpand '&amp;#40;cache postid &amp;#40;entry &amp;#40;get-post postid&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;let&amp;#42;
 &amp;#91;last-updated&amp;#95;&amp;#95;1294&amp;#95;&amp;#95;auto&amp;#95;&amp;#95;
  &amp;#40;:time &amp;#40;clojure.core/get @agents/cached postid&amp;#41;&amp;#41;
  cur-time&amp;#95;&amp;#95;1295&amp;#95;&amp;#95;auto&amp;#95;&amp;#95;
  &amp;#40;.getTime &amp;#40;new java.util.Date&amp;#41;&amp;#41;&amp;#93;
 &amp;#40;if
  &amp;#40;clojure.core/or
   &amp;#40;clojure.core/nil? last-updated&amp;#95;&amp;#95;1294&amp;#95;&amp;#95;auto&amp;#95;&amp;#95;&amp;#41;
   &amp;#40;clojure.core/&amp;gt;
    &amp;#40;clojure.core/- cur-time&amp;#95;&amp;#95;1295&amp;#95;&amp;#95;auto&amp;#95;&amp;#95; last-updated&amp;#95;&amp;#95;1294&amp;#95;&amp;#95;auto&amp;#95;&amp;#95;&amp;#41;
    10000&amp;#41;&amp;#41;
  &amp;#40;clojure.core/swap!
   agents/cached
   clojure.core/assoc
   postid
   {:content &amp;#40;entry &amp;#40;get-post postid&amp;#41;&amp;#41;, :time cur-time&amp;#95;&amp;#95;1295&amp;#95;&amp;#95;auto&amp;#95;&amp;#95;}&amp;#41;&amp;#41;
 &amp;#40;:content &amp;#40;clojure.core/get @agents/cached postid&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This definitely looks like the logic we're expecting. Any time we use this macro, it will be replaced with the code similar to the above, where the s-expression is inside the &lt;i&gt;if&lt;/i&gt; block, and only gets called if cache needs to be updated. Now we can easily cache any s-expressions with minimal change to the original code and all the caching logic sits in one convenient place:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;defpage &amp;quot;/blog/:postid&amp;quot; {:keys &amp;#91;postid&amp;#93;}
  &amp;#40;cache postid &amp;#40;entry &amp;#40;db/get-post postid&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As I've mentioned before, there are many other uses for macros, but I hope this gives a clear example of a concrete situation where a macro facilitates cleaner code and provides an easy way to avoid repetition.&lt;/p&gt;</description><pubDate>Fri, 27 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-20-perfection.html</guid><link>https://yogthos.net/posts/2012-07-20-perfection.html</link><title>perfection</title><description>&lt;p&gt;There's a quote by Antoine de Saint-Exupery that says: "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away". I think any experienced programmer can relate to that. You always strive to find the most elegant solution which describes the problem simply and clearly. &lt;/p&gt;&lt;p&gt;A lot of novice programmers have a habit of writing clever code which uses some esoteric properties of the language, or other tricks to get the job done. An experienced programmer knows that the real cleverness lies in being able to solve a problem with very simple code, that might even seem obvious in retrospect. &lt;/p&gt;&lt;p&gt;Eventually one develops an intuition for coming up with solutions which do not involve kludges, avoid edge cases, and forgo cleverness in favor of simplicity. Sometimes, however, this can lead to paralysis, where you don't yet know the elegant solution and you are unwilling to write down the one you know to be imperfect.&lt;/p&gt;&lt;p&gt;I find that REPL development is a great tool for overcoming this dilemma. You can quickly start experimenting with your problem, and through the experimentation gain the understanding necessary to implement it properly. At this point you can  easily refactor your existing ugly solution into something beautiful. &lt;/p&gt;</description><pubDate>Fri, 20 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-20-less-is-more.html</guid><link>https://yogthos.net/posts/2012-07-20-less-is-more.html</link><title>less is more</title><description>&lt;p&gt;An expressive language has many benefits. The most obvious one is that you have to write less code to solve your problem. The reason you write less code is often not because the syntax is more terse, but because you're using better abstractions. For example, instead of writing a loop, you can use an iterator function to do the work:&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;loop &amp;#91;count 0
         &amp;#91;head &amp;amp; tail&amp;#93; items&amp;#93;
    &amp;#40;if tail
      &amp;#40;recur &amp;#40;+ count head&amp;#41; tail&amp;#41;
      &amp;#40;+ count head&amp;#41;&amp;#41;&amp;#41;

&amp;#40;reduce + items&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;One non-obvious benefit of having less code is that it makes it much easier to throw code away. In a verbose language where you have to write a lot of code to solve simple problems, you tend to become attached to that code. In a language where you can express complex things in a relatively few lines, it's not a big issue to replace those with a few different lines. This encourages refactoring as you go, instead of waiting until you have a mountain of code accumulated and you really need to do something about it.&lt;/p&gt;</description><pubDate>Fri, 20 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-13-all-things-being-equal.html</guid><link>https://yogthos.net/posts/2012-07-13-all-things-being-equal.html</link><title>all things being equal</title><description>&lt;p&gt;You might have heard terms such as &lt;a href='http://en.wikipedia.org/wiki/Anonymous_function'&gt;anonymous functions&lt;/a&gt;, &lt;a href='http://en.wikipedia.org/wiki/First-class_function'&gt;first class functions&lt;/a&gt;,  &lt;a href='http://en.wikipedia.org/wiki/Higher-order_function'&gt;higher order functions&lt;/a&gt;, and &lt;a href='http://en.wikipedia.org/wiki/Closure_%28computer_science%29'&gt;closures&lt;/a&gt;. These might sounds mathy and imposing, but they're very simple ideas. In fact, I'll argue that they make the language simpler and more consistent.&lt;/p&gt;&lt;p&gt;In some languages there's a distinction between a function and a variable. You can assign variables, pass them in as parameters, and return them. Yet when it comes to functions, all you can do is define them and call them. &lt;/p&gt;&lt;p&gt;If you take a moment to think about it, I think you'll agree that this distinction is fairly arbitrary. There's no practical reason why we shouldn't be able to do all the things we do with variables with functions. &lt;/p&gt;&lt;p&gt;Let's look at some things that become possible once this distinction is erased. Sometimes we like to use values inline and not assign them to a variable, we usually do this because the value is only going to appear once, and we don't want to go through the ceremony of naming it.&lt;/p&gt;&lt;p&gt;If our language supports anonymous functions, we can do the same thing with a small piece of logic. If it's only needed in a single situation then we can make an anonymous function and call it directly:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;&amp;#40;fn &amp;#91;x&amp;#93; &amp;#40;&amp;#42; 2 x&amp;#41;&amp;#41; 5&amp;#41;
    10
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Here we created an anonymous function which takes a value and multiplies it by 2, and we passed 5 to it as a parameter. Just as we name values which we reuse in multiple places, so can we name functions:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;def times-2 &amp;#40;fn &amp;#91;x&amp;#93; &amp;#40;&amp;#42; 2 x&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and then call them by their name instead&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;times-2 5&amp;#41;
    10
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The other thing we said that we can do with variables is pass them as parameters to functions. By being able to pass functions to other functions, we're able to decompose our logic into smaller chunks. &lt;/p&gt;&lt;p&gt;If we takes our &lt;code&gt;times-2&lt;/code&gt; function and pass it in as a parameter to an iterator function such as map, it in turn can apply it to each element in a collection:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;map times-2 '&amp;#40;1 2 3 4&amp;#41;&amp;#41;
    &amp;#40;2 4 6 8&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;You might recognize this as the &lt;a href='http://en.wikipedia.org/wiki/Strategy_pattern'&gt;strategy pattern&lt;/a&gt; from OO. Turns out that all the complexity in the pattern comes from the idea of treating functions as second class citizens. Which brings us to the idea of a first class function. All that means is that a function is treated no differently than a variable. The only other thing we haven't defined is the higher order function, &lt;code&gt;map&lt;/code&gt; in the above example is such a function. Once again, there's nothing complicated about the concept. Any function which can accept another function as a parameter is a higher order function.&lt;/p&gt;&lt;p&gt;Finally, what happens if functions can return functions as output. There are many uses for this, but I'd like to focus on one that will be familiar from OO. When we create a class we often use a constructor to initialize some data that will be available to the methods of the instantiated object. &lt;/p&gt;&lt;p&gt;In a functional language we can achieve this by having a function which takes some parameters and returns another function. Because the inner function was defined in scope where the parameters are declared it too can access them. Here's an example:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;defn foo &amp;#91;x&amp;#93;
      &amp;#40;fn &amp;#91;y&amp;#93; &amp;#40;&amp;#42; x y&amp;#41;&amp;#41;&amp;#41;

    &amp;#40;&amp;#40;foo 2&amp;#41; 5&amp;#41;
    10
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Function &lt;code&gt;foo&lt;/code&gt; accepts parameter &lt;code&gt;x&lt;/code&gt; and returns an anonymous function which in turn accepts a parameter &lt;code&gt;y&lt;/code&gt; and multiplies them together. Function &lt;code&gt;foo&lt;/code&gt; is said to &lt;i&gt;close over&lt;/i&gt; its parameters, and hence it's called a closure. Unlike a constructor a closure does not introduce any special cases. It's just a function that returns a result which itself happens to be a function.&lt;/p&gt;&lt;p&gt;Treating functions as first class citizens makes the language more uniform. Instead of having special constructs for specific cases, we have a general purpose tool that we can apply in many situations. &lt;/p&gt;</description><pubDate>Fri, 13 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-12-limits-of-mutation.html</guid><link>https://yogthos.net/posts/2012-07-12-limits-of-mutation.html</link><title>limits of mutation</title><description>&lt;p&gt;When you start learning functional programming you will quickly notice that you can't simply mutate data in place as you might be used to. Initially you might find this odd and restrictive, but it turns out there are also some tangible benefits to this approach.&lt;/p&gt;&lt;p&gt;Mutable data structures are very simple in nature. They reference a location in memory where some value can be stored, when that value changes the old one is simply replaced with the new.&lt;/p&gt;&lt;p&gt;&lt;a href='http://en.wikipedia.org/wiki/Persistent_data_structure'&gt;Persistent data structures&lt;/a&gt; create revisions of the data when changes are made. We pay a small penalty in performance compared to in place mutation, but we gain a history of changes that exists as long as its referenced somewhere. &lt;/p&gt;&lt;p&gt;This means that if a function accepts some data as a parameter, you don't have to worry if anybody else is referencing that data when you work with it. Any time you change the data you get a new version without paying the penalty of copying it. By contrast, we always have to be aware if a reference may be used else where when working with mutable data. By removing this worry, we can reduce the scope of things that we need to keep in our heads when trying to understand what a particular piece of code does. &lt;/p&gt;&lt;p&gt;The benefits stack up as your project grows, as it becomes infeasible to keep the totality of the code in ones head. And it's a huge benefit when working in a threaded environment and shared data can easily be corrupted.&lt;/p&gt;&lt;p&gt;What might seem like an inconvenience at first turns out to be a net benefit. Ensuring that the data is not modified outside the intended context has been offloaded to the language instead of being done by you manually. I would liken this to use of garbage collection, where the language is responsible for most memory reclamation. In both cases it's better to let the machine do tasks that can be automated leaving you to solve the real problems.&lt;/p&gt;</description><pubDate>Thu, 12 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-10-we-ll-do-it-live.html</guid><link>https://yogthos.net/posts/2012-07-10-we-ll-do-it-live.html</link><title>we'll do it live!</title><description>&lt;p&gt;One thing I love about working in Clojure is how interactive the development environment is. Clojure being a Lisp provides a REPL (read, evaluate, print, loop), which works exactly like it sounds. You send an expression to the reader, which will then evaluate it, print the result, and wait for another expression to read.&lt;/p&gt;&lt;p&gt;Clojure IDEs provide tight integration with the REPL. It is possible to connect your application to it and have it load all the libraries and dependencies. At this point you can write your new code in the IDE and have the REPL evaluate it in the context of your running application.&lt;/p&gt;&lt;p&gt;In non-trivial applications it's often necessary to build up a particular state before you can add more functionality. For example a user has to login then view some data from a backend, then you need to write functions to format and display this data. With a REPL you can get the application to the state where the data is loaded and then write the display logic interactively without having to reload the application every time you make a change.&lt;/p&gt;&lt;p&gt;I find this method of development a lot more satisfying, as you get immediate feedback from your application when you add or modify code, and you can easily try things and see how they work. It encourages extermination and refactoring code as you go, which I think helps write better and cleaner code. &lt;/p&gt;&lt;p&gt;This technique is common in Lisp and Smalltalk development, but for reasons unknown has not penetrated into mainstream languages.&lt;/p&gt;</description><pubDate>Tue, 10 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-09-lost-in-patterns.html</guid><link>https://yogthos.net/posts/2012-07-09-lost-in-patterns.html</link><title>lost in patterns</title><description>&lt;p&gt;Design patterns are heavily used in the OO world, and there are many lengthy books written about them. I'd like to examine why this is and what these patterns stem from exactly. &lt;/p&gt;&lt;p&gt;As the name implies, design patterns are templates for structuring code to solve common problems. This is a fine idea in and of itself, but the following question needs to be asked. If programming is ultimately about automation, and patterns are repetitive tasks by their very nature, then why are we forced to write them out by hand each time?&lt;/p&gt;&lt;p&gt;The reason for this appears to be due to lack of abstraction in the language. Many design patterns are simply specific cases of an underlying abstraction which unifies them. Having a language which can express such abstractions means that you don't have to learn many different patterns for specific situations. &lt;/p&gt;&lt;p&gt;Bruce Lee once said "I fear not the man who has practiced ten thousand kicks once. But I fear the man who has practiced one kick ten thousand times". I think this applies here as well: it's better to learn a general solution for many problems, than to have a specific solution for each small problem you run into.&lt;/p&gt;&lt;p&gt;So, next time you're looking at a language, don't simply look at the one that has the bigger list of features, instead look for one with a few features that work well together.&lt;/p&gt;</description><pubDate>Mon, 09 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-08-living-in-a-structured-world.html</guid><link>https://yogthos.net/posts/2012-07-08-living-in-a-structured-world.html</link><title>living in a structured world</title><description>&lt;p&gt;If you've seen any Lisp code before, you've probably noticed that it looks different from other languages in that the parens come before the function name, prefix notation is prevalent, and that functions are often nested inside one another. The technical term for this is that Lisp uses &lt;a href='http://en.wikipedia.org/wiki/S-expression'&gt;s-expressions&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;These might look awkward at first, and many newcomers immediately think that they can and should be improved upon. Surely it would be easy to write a preprocessor that would let you write code as you write it in other languages and then convert it to s-expressions. This is absolutely true and in fact there is one prominent attempt called &lt;a href='http://www.dwheeler.com/readable/sweet-expressions.html'&gt;sweet-expressions&lt;/a&gt;. Despite all that, the idea just doesn't catch on and I'd like to explore what the advantages of working with raw s-expressions are.&lt;/p&gt;&lt;p&gt;One immediate benefit is that Lisp syntax follows the &lt;a href='http://en.wikipedia.org/wiki/Principle_of_least_astonishment'&gt;principle of least astnoishment&lt;/a&gt; very well. Any time you read code, it always follows the pattern of &lt;code&gt;&amp;#40;function-name arguments&amp;#41;&lt;/code&gt;,  which makes for very consistent looking code. This helps reduce the mental overhead when reading and writing code, instead of worrying about language quirks you can focus on the actual problem you're solving.&lt;/p&gt;&lt;p&gt;Another benefit is that the code provides extra information about itself, which is not available in other languages. With s-expressions you can visually see how functions relate to one another. In essence the code is rendered as a tree representing the execution logic.&lt;/p&gt;&lt;p&gt;Finally, the s-expressions make editing code a completely different experience from other languages. Instead of working in terms of lines, you work in terms of functions. With a &lt;a href='http://emacswiki.org/emacs/ParEdit'&gt;ParEdit&lt;/a&gt; style editor you can select code not by line but by function! Now you can easily select, move, and reparent pieces of logic. Editing code becomes like playing with Lego pieces and arranging them in different ways.&lt;/p&gt;&lt;p&gt;In my experience these things make the language more enjoyable to work with and the benefits far outweigh any perceived ugliness. After a while you don't even see the parens.&lt;/p&gt;</description><pubDate>Sun, 08 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-07-04-Temporally-oblivious.html</guid><link>https://yogthos.net/posts/2012-07-04-Temporally-oblivious.html</link><title>Temporally oblivious</title><description>&lt;p&gt;Objects are state machines, yet no mainstream OO language ensures the consistency of the internal state of the object over time. This means that in a multi-threaded environment it's possible to see the internal state of the object while it's being updated. What's even worse is that even if you don't see a partial state, you might be seeing an unexpected state, since someone else with a reference to the object might have updated it for their use, which conflicts with the way you're using it.&lt;/p&gt;&lt;p&gt;The whole situation is fairly messy, but what is the alternative you might ask. My answer would be not to use in place mutation unless absolutely necessary. Instead it's much better to use &lt;a href='http://en.wikipedia.org/wiki/Persistent_data_structure'&gt;persistent data structures&lt;/a&gt;, which &lt;em&gt;are&lt;/em&gt; temporally aware. A persistent data structure works in a fashion akin to version control. Any time a change to the data is made, a delta is created between the existing data and the new data. From user perspective you're simply copying the data, but you're only paying the price of the change.&lt;/p&gt;&lt;p&gt;This concept turns out to be very powerful as it inherently contextualizes any changes. It also allows doing things like rollbacks trivially as you just have to unwind your operations to see a previous state.&lt;br /&gt;&lt;/p&gt;</description><pubDate>Wed, 04 Jul 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-06-28-why-all-the-parens.html</guid><link>https://yogthos.net/posts/2012-06-28-why-all-the-parens.html</link><title>why all the parens</title><description>&lt;p&gt;A common complaint you hear from people about Lisp is that there are too many parens. Let's compare what's involved in writing a Java method to writing a Clojure function:&lt;pre&gt;&lt;code class="java"&gt;    public static void foo&amp;#40;String bar, Integer baz&amp;#41; {
        System.out.println&amp;#40;bar + &amp;quot;, &amp;quot; + baz&amp;#41;;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;defn foo &amp;#91;bar baz&amp;#93; 
      &amp;#40;println bar &amp;quot;, &amp;quot; baz&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The number of parens is exactly the same, but there's clearly more noise in the Java version. In my opinion the noise adds up and it distracts from the intent of the code. The more code you have the harder it is to tell what it's doing and conversely the harder it is to spot bugs in it. I'll illustrate this with a concrete example. &lt;/p&gt;&lt;p&gt;The problem is to display a formatted address given the fields representing it. Commonly an address has a street, a city, a postal code, and a country. We'll have to examine each of these pieces, remove the null and empty ones and insert some separator between them.&lt;/p&gt;&lt;p&gt;So given something like&lt;/p&gt;&lt;pre&gt;&lt;code&gt;street: 1 Main street
city: Toronto
posal: A1B 2C3
country: Canada&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;we'd like to output&lt;/p&gt;&lt;pre&gt;&lt;code&gt;1 Main street, Toronto, A1B 2C3, Canada&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;we should obviously handle empty fields and not have &lt;em&gt;,,&lt;/em&gt; if the field isn't there, and we should make sure we handle nulls in case the whole address is null or some fields in the address are null.&lt;/p&gt;&lt;p&gt;Let's first examine how we would write this in Java:&lt;pre&gt;&lt;code class="java"&gt;    public static String concat&amp;#40;String... strings&amp;#41; {
        if &amp;#40;null == strings&amp;#41; return null;
        StringBuffer sb = new StringBuffer&amp;#40;&amp;#41;;
        for &amp;#40;String s : strings&amp;#41; {
            if &amp;#40;null == s || s.equals&amp;#40;&amp;quot;&amp;quot;&amp;#41;&amp;#41; continue;
            sb.append&amp;#40;s&amp;#41;;
            sb.append&amp;#40;','&amp;#41;;
        }
        String s =  sb.toString&amp;#40;&amp;#41;;
        return s.substring&amp;#40;0, s.lastIndexOf&amp;#40;','&amp;#41;&amp;#41;;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;lines of code : 11&lt;/li&gt;&lt;li&gt;parens: 26&lt;/li&gt;&lt;li&gt;curly braces: 4&lt;/li&gt;&lt;li&gt;semicolons: 7&lt;/li&gt;&lt;li&gt;colons: 1&lt;/li&gt;&lt;li&gt;dots: 6&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Now let's compare this to Clojure:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;defn concat-fields &amp;#91;&amp;amp; fields&amp;#93;
      &amp;#40;apply str &amp;#40;interpose &amp;quot;,&amp;quot; &amp;#40;remove empty? fields&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;lines of code : 2&lt;/li&gt;&lt;li&gt;parens: 8&lt;/li&gt;&lt;li&gt;brackets: 2&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The Clojure version has significantly less code, and a lot less noise. In addition, we didn't have to do any explicit null checks in our code, and we were able to write the complete solution simply by composing together functions from the standard library!&lt;/p&gt;&lt;p&gt;One very important difference between the Java version and the Clojure version is that the Java version talks about &lt;strong&gt;how&lt;/strong&gt; something is being done, while the Clojure version talks about &lt;strong&gt;what&lt;/strong&gt; is being done. In other words, we have to step through the Java version in our heads to understand what the code is doing. &lt;/p&gt;&lt;p&gt;In the Clojure version this step is not present because the code says what it's doing, and all the implementation details have been abstracted from us. This is code reuse at work, where we can write simple functions that do one thing well and chain them together to achieve complex functionality. &lt;/p&gt;&lt;p&gt;This bears a lot of resemblance with the Unix philosophy: "&lt;a href='http://en.wikipedia.org/wiki/Unix_philosophy'&gt;Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.&lt;/a&gt;" Except in our case we're dealing with functions instead of programs and common data structures as a universal interface in the language.&lt;/p&gt;</description><pubDate>Thu, 28 Jun 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-06-23-popularity-contests.html</guid><link>https://yogthos.net/posts/2012-06-23-popularity-contests.html</link><title>popularity contests</title><description>&lt;p&gt;The argument that Lisp is not popular because it's somehow a bad language is not really sound. A lot of great technologies have lost out to inferior ones because of poor marketing. The Lisp community has not in general been great at marketing the language, and it is viewed as downright scary by majority of people. &lt;/p&gt;&lt;p&gt;It also doesn't help that there is no definitive standard distribution of Lisp, or a comprehensive standard library. Most people aren't going to jump through hoops to learn an esoteric language. So, it is no surprise that there aren't a lot of big commercial Lisp projects. It becomes a catch 22, where due to lack of Lisp developers companies develop apps in more popular languages, and people don't bother learning Lisp because there are no jobs for it.&lt;/p&gt;&lt;p&gt;Clojure avoids a lot of the pitfalls by running on the JVM and interfacing with Java. Java is rather dominant in the industry, a lot of companies already use it, and using alternative languages on the JVM is also becoming a fairly common practice. Strong Java integration also means that you have access to a great wealth of existing libraries. &lt;/p&gt;&lt;p&gt;Having the ability to introduce Clojure in an existing project without having to change your environment is a huge plus. You can continue to use the same build tools, the same IDE, and same application servers for deployment. The only thing that changes is the actual language.&lt;/p&gt;&lt;p&gt;From the language design perspective I think it is also an improvement over the traditional Lisp syntax. For example let's compare &lt;code&gt;let&lt;/code&gt; in CL to &lt;code&gt;let&lt;/code&gt; in Clojure:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;let 
      &amp;#40;&amp;#40;a1 b1&amp;#41; 
       &amp;#40;a2 b2&amp;#41; 
       &amp;#40;an bn&amp;#41;&amp;#41;
      &amp;#40;some-code a1 a2 an&amp;#41;&amp;#41;

    &amp;#40;let &amp;#91;a1 b1
          a2 b2
          an bn&amp;#93;
      &amp;#40;some-code a1 a2 an&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;To me Clojure version is easier to read because there's less noise, and I find the literal vector notation helps break up the code visually. Which brings me to the second thing I like, having literal vector, set, and map notation. I find it makes code more legible and helps see what's going on in a function.&lt;/p&gt;&lt;p&gt;The next thing I really like, that Clojure introduces, is destructuring. You can take any arbitrary data structure and read it backwards. Here are a few examples of what I'm talking about:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;def {:a &amp;#91;1 2 3&amp;#93; :b {:c 4} :d 5}&amp;#41;

    &amp;#40;defn foo &amp;#91;{a :a b :b}&amp;#93;
      &amp;#40;println a b&amp;#41;&amp;#41;

    &amp;#40;defn bar &amp;#91;{:keys &amp;#91;a b d&amp;#93;&amp;#93;
      &amp;#40;println a b d&amp;#41;&amp;#41;

    &amp;#40;defn baz &amp;#91;{&amp;#91;a b c&amp;#93; :a {d :c} :b e :d}&amp;#93;
      &amp;#40;println a b c&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;this also works in &lt;code&gt;let&lt;/code&gt; statements, and again I find that it improves readability, especially in larger programs. While a minor nitpick I also like the naming conventions in Clojure standard library better. Names such as &lt;code&gt;car&lt;/code&gt; and &lt;code&gt;cdr&lt;/code&gt; are archaic in my opinion.&lt;/p&gt;</description><pubDate>Sat, 23 Jun 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-06-17-why-you-shouldn-t-jump-through-loops.html</guid><link>https://yogthos.net/posts/2012-06-17-why-you-shouldn-t-jump-through-loops.html</link><title>why you shouldn't jump through loops</title><description>&lt;p&gt;In Java passing logic as a parameter requires an inordinate amount of work and it's never the first choice to do so. So in most cases you're better off just writing a loop and doing the null check in it. Let's look at a concrete example of what I'm talking about here. Let's say we want to filter collections based on a predicate. The standard way you would do that in Java is to write a loop:&lt;pre&gt;&lt;code class="java"&gt;public static List&amp;lt;Integer&amp;gt; filterEven&amp;#40;Collection&amp;lt;Integer&amp;gt; col&amp;#41; {
    if &amp;#40;null == col&amp;#41; return null;
    List&amp;lt;Integer&amp;gt; result = new LinkedList&amp;lt;Integer&amp;gt;&amp;#40;&amp;#41;;
    for &amp;#40;Integer i  : col&amp;#41; {			
        if &amp;#40;i % 2 == 0&amp;#41; result.add&amp;#40;i&amp;#41;;			
     }		
     return result;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;then if later I need to filter odd numbers I'll probably write another loop that looks almost identical except for the actual test. Obviously, the looping logic should be abstracted here, but let's look at what's involved in doing that in Java:&lt;pre&gt;&lt;code class="java"&gt;public interface Predicate&amp;lt;T&amp;gt; {
    public boolean matches&amp;#40;T t&amp;#41;;
}

public class EvenPredicate implements Predicate&amp;lt;Integer&amp;gt; {
	
    public boolean matches&amp;#40;Integer i&amp;#41; {
 	return i % 2 == 0; 
    }			
}

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class Filter {

    public static &amp;lt;T&amp;gt; List&amp;lt;T&amp;gt; filterCollection&amp;#40;Collection&amp;lt;T&amp;gt; col, 
                                          Predicate&amp;lt;T&amp;gt; predicate&amp;#41; {
        List&amp;lt;T&amp;gt; result = new LinkedList&amp;lt;T&amp;gt;&amp;#40;&amp;#41;;
	    for &amp;#40;T t : col&amp;#41; {			
                    if &amp;#40;predicate.matches&amp;#40;t&amp;#41;&amp;#41; {
                        result.add&amp;#40;t&amp;#41;;
                    }
            }		
            return result;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;That's a lot more work than just writing a loop, and unless you saw this pattern many times you probably wouldn't consider doing it. Now let's compare this to a language like Clojure, where I would use a higher order function and pass in the matcher without having to do any preliminary setup:&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;filter even? &amp;#40;range 10&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;what if I wanted to write a loop to do that&lt;pre&gt;&lt;code class="clojure"&gt;&amp;#40;loop &amp;#91;nums &amp;#40;range 10&amp;#41;
       even-nums &amp;#91;&amp;#93;&amp;#93;
    &amp;#40;if &amp;#40;empty? nums&amp;#41;
        even-nums
        &amp;#40;recur &amp;#40;rest nums&amp;#41; 
                  &amp;#40;if &amp;#40;even? &amp;#40;first nums&amp;#41;&amp;#41; 
                     &amp;#40;conj even-nums &amp;#40;first nums&amp;#41;&amp;#41; even-nums&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;all of a sudden the situation is reversed, it's &lt;i&gt;a lot&lt;/i&gt; more code to do explicit looping, and it's trivial to use a higher order function to do this task. So the language encourages you to write code through function composition by design. Being able to easily separate iteration from the logic applied inside it means that we can write code that's shorter, cleaner, and less error prone.&lt;/p&gt;</description><pubDate>Sun, 17 Jun 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-06-05-I-don-t-need-a-method-to-function.html</guid><link>https://yogthos.net/posts/2012-06-05-I-don-t-need-a-method-to-function.html</link><title>I don't need a method to function</title><description>&lt;p&gt;Instance methods are always associated with a particular object that may or may not exist. This means that before we can call a method we must first check if an object is null. This becomes especially tedious if you have nested objects. For example if we have a following situation:&lt;pre&gt;&lt;code class="java"&gt;    users.getUser&amp;#40;&amp;quot;foo&amp;quot;&amp;#41;.getAddress&amp;#40;&amp;#41;.getStreet&amp;#40;&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;the above code would be unsafe, since every single method call could potentially lead to a null pointer. This means that we have to instantiate and check each object individually:&lt;pre&gt;&lt;code class="java"&gt;    String street = null;
    User user = users.getUser&amp;#40;&amp;quot;foo&amp;quot;&amp;#41;;
    if &amp;#40;null != user&amp;#41;
       Address address = user.getAddress&amp;#40;&amp;#41;;
       if &amp;#40;null != address&amp;#41;
           street = address.getStreet&amp;#40;&amp;#41;;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Not only is this tedious and error prone, but it's also one more thing that you actively have to think about.&lt;/p&gt;&lt;p&gt;Let's compare this situation to the functional approach. In a functional language functions exist independent of data, much like static methods in OO. This means that we can't get a null pointer while calling a function. The author of the function can do all the error checking in the function &lt;strong&gt;once&lt;/strong&gt;, and the user does not need to worry about it. When you chain such functions together, the null values can bubble up as the result:&lt;pre&gt;&lt;code class="clojure"&gt;    &amp;#40;:street &amp;#40;:address &amp;#40;:foo users&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This code will not throw any null pointer exceptions, and instead a null value will be returned. It has less noise, it's less error prone, and it's easier to read.&lt;/p&gt;</description><pubDate>Tue, 05 Jun 2012 00:00:00 +0000</pubDate></item><item><guid>https://yogthos.net/posts/2012-05-03-subject-to-change.html</guid><link>https://yogthos.net/posts/2012-05-03-subject-to-change.html</link><title>subject to change</title><description>&lt;p&gt;The OO world view requires us to classify data in order to work with it. For example if we're talking about a person, we might create a &lt;code&gt;Person&lt;/code&gt; class and add some fields to it, such as &lt;code&gt;age&lt;/code&gt;, &lt;code&gt;name&lt;/code&gt;, and etc. Then we'll create instances of this class and use them in our program.&lt;/p&gt;&lt;p&gt;The problem with this approach is that the classification is only meaningful within a particular context. The classification is not inherent to the data itself, but rather it's a transient view of the data at a specific time in a particular domain.&lt;/p&gt;&lt;p&gt;When we create a class we make assumptions about the context in which the data will be used. These assumptions are often incomplete, and even when they are, the nature of the problem can change over time. The requirements may change, new requirements might come up, or we might have simply misunderstood the problem when we designed our classes.&lt;/p&gt;&lt;p&gt;The way OO deals with this is by remapping the classes to a new domain. We might extend the class, write a wrapper, or use an adapter pattern to bridge the contexts. But this is solving a problem we ourselves have introduced by assigning a permanent  classification to our data.&lt;/p&gt;</description><pubDate>Thu, 03 May 2012 00:00:00 +0000</pubDate></item></channel></rss>