The conventions

Build a small araara helpdesk app step by step, covering logins, roles, typed routes, live HTML and a shared JSON API.

The libraries provide the components. The conventions describe how an application is organized. This page is a tutorial that builds a small helpdesk application. Customers open and follow their own support tickets, and operators triage tickets from all customers. The tutorial goes file by file and names each convention where it is used. The application has logins, roles, an htmx interface and a JSON API. Each OCaml block below is taken from the file named above it in examples/helpdesk/, which is compiled and run in the test suite. The blocks therefore match the code that the tests exercise.

Application layout

An araara application is split into a core and a web layer. The core does not depend on HTTP. The web layer depends on the core, and the core does not depend on the web layer. The core holds the model and the business logic, and the web layer is one of its consumers. The same core can also be used by a CLI, a desktop app, or a background worker. The domain can also be tested without starting a server.

examples/helpdesk/
examples/helpdesk/
├── bin/
│   └── main.ml             -- boot: migrate, seed, serve
├── lib/
│   ├── helpdesk/           -- CORE (library helpdesk_core): no HTTP
│   │   ├── db.ml           -- the driver-bound repo
│   │   ├── role.ml         -- Customer | Operator
│   │   ├── models/         -- one file per table
│   │   │   ├── account.ml
│   │   │   ├── ticket.ml
│   │   │   └── reply.ml
│   │   ├── contexts/       -- business logic + authorization
│   │   │   ├── accounts.ml
│   │   │   └── tickets.ml
│   │   └── migrations.ml   -- ordered migration list
│   └── helpdesk_web/       -- WEB (library helpdesk_web): over the core
│       ├── routes.ml       -- typed paths, single source of truth
│       ├── router.ml       -- pipelines + scopes
│       ├── endpoint.ml     -- static assets + router
│       ├── plugs/auth.ml   -- session gate; the current account
│       ├── views/          -- TyXML pages and fragments
│       │   ├── layout.ml
│       │   ├── tickets.ml
│       │   └── auth.ml
│       ├── controllers/web.ml  -- HTML actions
│       └── api/tickets.ml      -- the JSON twin
├── priv/static/app.css     -- the stylesheet (served as a static asset)
└── test/test.ml            -- Alcotest context tests

The tree above is the directory layout of the application. It has two libraries: helpdesk_core (models and contexts) and helpdesk_web (views, controllers, an api, routes, a router and plugs), which depends on helpdesk_core. It also has a bin/ directory that serves the application, priv/static for the stylesheet, and a test/ suite. Each file has a small role, often ten or twenty lines. Each code block below names the file it comes from. The tutorial builds the application in dependency order, starting with the core and then the web layer.

How the layers depend on each other

Inside that split, a feature is organized as Model → Context → Controller or Api → View → Router. A layer uses the layers below it in this order. The sections below follow this order.

  • Model. A record plus its repodb schema, changeset and named queries. There is one model per table, and business rules are kept out of the model.
  • Context. The public API of a bounded subdomain. Business rules, transactions and side effects are handled here, with uniform naming: list_*, get_*, create_*, update_*, delete_*.
  • Controller / Api. HTML and JSON handlers over the same context. Business logic belongs in the context.
  • View. A pure function from data to HTML nodes. It does not perform I/O, check authentication, or read the database.
  • Router. Pipelines and scopes. Sessions, CSRF, auth, rate limits and security headers are handled by pipeline plugs.

The model and its table

A model is one record, its table, and the typed queries over it. There is one model per table, and other layers access the database through the model. A ticket's status is a three-way variant. Code that receives a status therefore receives one of the three values the type defines. The type system rejects code that tries to construct a status outside those values. The migration describes the schema with typed columns.

lib/helpdesk/models/ticket.ml
(* The domain type. [status] is a three-way variant, not a string, so no
   layer downstream can be handed a status that cannot exist. *)
type status = Open | Pending | Closed
type t = { id : int; requester_id : int; subject : string; body : string; status : status }

let status_to_string = function Open -> "open" | Pending -> "pending" | Closed -> "closed"
let status_of_string = function "pending" -> Pending | "closed" -> Closed | _ -> Open

let table = Repodb.Schema.table "tickets"
let field name ty get set = Field.make ~table_name:"tickets" ~name ~ty ~get ~set ()
let id_f = field "id" Types.int (fun t -> t.id) (fun v t -> { t with id = v })

let requester_f =
  field "requester_id" Types.int (fun t -> t.requester_id) (fun v t -> { t with requester_id = v })

let subject_f = field "subject" Types.string (fun t -> t.subject) (fun v t -> { t with subject = v })
let body_f = field "body" Types.string (fun t -> t.body) (fun v t -> { t with body = v })

let status_f =
  field "status" Types.string
    (fun t -> status_to_string t.status)
    (fun v t -> { t with status = status_of_string v })

let migration =
  let open Repodb.Migration in
  migration ~version:2L ~name:"create_tickets" ~down:[ drop_table "tickets" ]
    ~up:
      [
        create_table "tickets"
          [
            typed_column "id" Types.int ~primary_key:true;
            typed_column "requester_id" Types.int ~nullable:false;
            typed_column "subject" Types.string ~nullable:false;
            typed_column "body" Types.string ~nullable:false;
            typed_column "status" Types.string ~nullable:false;
          ];
      ]

Validation is also defined in the model, as a changeset. cast copies only the fields named in the whitelist, so an extra parameter is dropped. This prevents an extra field in a form or JSON body from being written (mass assignment). The validators collect each failure into one error list. Data that passes the changeset has passed those validators, and the error list can be shown in a form or returned in a JSON response.

lib/helpdesk/models/ticket.ml
(* CHANGESET — cast whitelists the fields a client may set (neither id nor
   requester_id can be smuggled in from a form), then the validators
   accumulate every failure at once. *)
let changeset params =
  Changeset.create { id = 0; requester_id = 0; subject = ""; body = ""; status = Open }
  |> Changeset.cast params ~fields:[ subject_f; body_f ]
  |> Changeset.validate_required [ subject_f; body_f ]
  |> Changeset.validate_length subject_f ~min:4 ~max:120

Building queries

The model builds its reads and writes with repodb's query DSL, which the driver compiles to prepared statements. Queries are type-checked against the schema, and values are passed as parameters. The same query code runs on SQLite, PostgreSQL and MariaDB. Hand-written SQL strings are not used in application code here. (repodb also provides a raw SQL option for a query the DSL cannot express; the repodb page covers when to use it.) These four functions are the model's contract with the database. decode converts a row to a record.

lib/helpdesk/models/ticket.ml
(* QUERIES — every read and write through the Query DSL. [all] and
   [for_requester] are the two reads authorization picks between. *)
let decode row =
  {
    id = Repodb.Driver.row_int row 0;
    requester_id = Repodb.Driver.row_int row 1;
    subject = Repodb.Driver.row_text row 2;
    body = Repodb.Driver.row_text row 3;
    status = status_of_string (Repodb.Driver.row_text row 4);
  }

let all conn = Db.Repo.all_query conn (Query.from table |> Query.desc (Expr.column id_f)) ~decode

let for_requester conn ~requester_id =
  Db.Repo.all_query conn
    (Query.from table
    |> Query.where Expr.(column requester_f = int requester_id)
    |> Query.desc (Expr.column id_f))
    ~decode

let get conn ~id = Db.Repo.get conn ~table ~id ~decode

let insert conn ~requester_id ~subject ~body =
  let q =
    Query.insert_into table
    |> Repodb.Query_values.values4 (requester_f, subject_f, body_f, status_f)
         ( Expr.int requester_id,
           Expr.string subject,
           Expr.string body,
           Expr.string (status_to_string Open) )
  in
  match Db.Repo.insert_query conn q with
  | Error e -> Error e
  | Ok () -> (
      match Db.last_insert_id conn with
      | Error e -> Error (Repodb.Error.Query_failed (Repodb_sqlite.error_message e))
      | Ok id -> get conn ~id:(Int64.to_int id))

let set_status conn ~id ~status =
  Db.Repo.update_query conn
    (Query.update table
    |> Query.set status_f (Expr.string (status_to_string status))
    |> Query.where Expr.(column id_f = int id))

The context

The context is the public API of a bounded subdomain, such as Tickets, Accounts or Billing. Business logic is handled in the context. The context works through the model. It calls the model's queries and does not build a query or access the database directly. The create function follows three conventions. It runs its work in a single transaction. It returns a result with a named error variant instead of raising an exception. It sends the pubsub broadcast, a domain event, after the transaction commits. Capabilities (the connection, the bus) are passed in as arguments, so the same function can run against a database or an in-memory test database.

lib/helpdesk/contexts/tickets.ml
(* An operator sees every ticket; a customer only their own. *)
let visible conn ~(viewer : Models.Account.t) =
  let r =
    if Role.is_operator viewer.role then Models.Ticket.all conn
    else Models.Ticket.for_requester conn ~requester_id:viewer.id
  in
  match r with Ok ts -> ts | Error _ -> []

let create conn ~pubsub ~(requester : Models.Account.t) ~params =
  let cs = Models.Ticket.changeset params in
  if not (Changeset.is_valid cs) then Error (`Validation (Changeset.error_messages cs))
  else
    let value f = Option.value (Changeset.get_change cs f) ~default:"" in
    let subject = value Models.Ticket.subject_f and body = value Models.Ticket.body_f in
    let insert c = Models.Ticket.insert c ~requester_id:requester.id ~subject ~body in
    match Db.transaction conn insert with
    | Error e -> Error (`Db e)
    | Ok t ->
        (* Post-commit: the ticket is durable, so fan out a domain event
           carrying its id (the live operator feed is one subscriber). *)
        pubsub.Pubsub.publish ~topic:"tickets" ~payload:(string_of_int t.Models.Ticket.id);
        Ok t

(* Resolving (and any status change) is operator-only. *)
let triage conn ~(viewer : Models.Account.t) ~id ~status =
  if not (Role.is_operator viewer.role) then Error `Forbidden
  else
    match Db.transaction conn (fun c -> Models.Ticket.set_status c ~id ~status) with
    | Error e -> Error (`Db e)
    | Ok () -> ( match Models.Ticket.get conn ~id with Ok t -> Ok t | Error _ -> Error `Not_found)

Authorization is also handled in the context. A read is scoped by the viewer's role. An operator can read all tickets, and a customer can read their own tickets. Triage is limited to operators, and it returns a Forbidden value for a customer. Both transports call the context, so they apply the same authorization rules.

The layers after the context handle transport. A browser and an API client can both call this same create function.

Authentication in the pipeline

Authorization decides what a known user may do. Authentication decides who the user is, and it is handled in the pipeline. A successful login stores the account id in the session. For each request, the require_login plug loads the account and attaches it to the request with Request.with_assign. It rejects an unauthenticated request before a controller runs. Handlers read the viewer from the request and do not read the session or the database to identify the caller. The API endpoint uses the same plug and answers 401 instead of redirecting.

lib/helpdesk_web/plugs/auth.ml
(* A typed key for the account, set by the plug below and read by handlers. *)
let account_key : Models.Account.t Hcs.Assigns.key = Hcs.Assigns.create_key ()

(* The account the plug attached to this request. Safe behind the gate. *)
let viewer req =
  match Hcs.Request.assign req account_key with
  | Some a -> a
  | None -> failwith "viewer: route is not behind require_login"

let resolve conn =
  match Session.get "uid" with
  | None -> None
  | Some s ->
      Option.bind (int_of_string_opt s) (fun id ->
          match Models.Account.get conn ~id with Ok a -> Some a | Error _ -> None)

let require_login conn handler req =
  match resolve conn with
  | Some a -> handler (Hcs.Request.with_assign req account_key a)
  | None -> Hcs.Response.found "/login"

let require_api conn handler req =
  match resolve conn with
  | Some a -> handler (Hcs.Request.with_assign req account_key a)
  | None -> Hcs.Response.json ~status:`Unauthorized {|{"error":"login required"}|}

Views: pure functions to HTML

A view is a pure function from data to HTML nodes. It does not perform I/O, check authentication, or read the database. One ticket_li function renders a ticket inside the queue page and as the fragment returned by a write, so both uses render a ticket in the same way.

lib/helpdesk_web/views/tickets.ml
(* One view, reused two ways: inside the queue page, and as the fragment a
   create returns (appended to the list) or the SSE feed pushes. The whole
   row links to the ticket's conversation, where the work happens. *)
let ticket_li ~(viewer : Models.Account.t) (t : Models.Ticket.t) =
  li
    [ id "ticket-%d" t.id; class_ "ticket" ]
    [
      a [ class_ "subject"; href "%s" (url (Routes.ticket ()) t.id) ] [ txt "%s" t.subject ];
      (if Role.is_operator viewer.role then span [ class_ "who" ] [ txt "from #%d" t.requester_id ]
       else null []);
      span [ class_ "badge %s" (Models.Ticket.status_to_string t.status) ]
        [ txt "%s" (Models.Ticket.status_to_string t.status) ];
    ]

Controllers returning pages and fragments

The index action renders a complete page. The create and triage actions return a single row, which htmx swaps into the page without a reload. Each action calls the context and passes its result to a view. Business logic is handled in the context. An invalid submission returns a 422 response with the changeset's messages.

lib/helpdesk_web/controllers/web.ml
(* Captures arrive as typed arguments (the [id : int] below comes from the
   route, no param lookup). [index] returns a COMPLETE page; [create] and
   [triage] return a PORTION the htmx swaps in. The viewer comes from the
   plug; the rules from the context. *)
let index conn req =
  let viewer = Plugs.Auth.viewer req in
  respond (Views.Tickets.index_page ~viewer ~tickets:(Contexts.Tickets.visible conn ~viewer))

let show conn id req =
  let viewer = Plugs.Auth.viewer req in
  match Contexts.Tickets.show conn ~viewer ~id with
  | Ok detail -> respond (Views.Tickets.detail_page ~viewer detail)
  | Error `Forbidden -> Hcs.Response.forbidden ~body:"not your ticket" ()
  | Error `Not_found -> Hcs.Response.not_found ~body:"no such ticket" ()
  | Error _ -> Hcs.Response.found (url (Routes.home ()))

let create conn pubsub req =
  let requester = Plugs.Auth.viewer req in
  match Contexts.Tickets.create conn ~pubsub ~requester ~params:(Hcs.Request.parse_query_string (Hcs.Request.body req)) with
  | Ok t -> respond (Views.Tickets.ticket_li ~viewer:requester t)
  | Error (`Validation msgs) -> Hcs.Response.unprocessable_entity ~body:(String.concat "; " msgs) ()
  | Error _ -> Hcs.Response.unprocessable_entity ~body:"could not open ticket" ()

let triage conn id to_ req =
  let viewer = Plugs.Auth.viewer req in
  match Contexts.Tickets.triage conn ~viewer ~id ~status:(Models.Ticket.status_of_string to_) with
  | Ok t -> respond (Views.Tickets.status_region ~viewer t)
  | Error `Forbidden -> Hcs.Response.forbidden ~body:"operators only" ()
  | Error `Not_found -> Hcs.Response.not_found ~body:"no such ticket" ()
  | Error _ -> Hcs.Response.unprocessable_entity ~body:"could not update" ()

Sharing a context between HTML and JSON

When a script, a bot, or another service needs to file tickets, it can use a JSON endpoint under /api/v1. This endpoint calls the same Tickets.create, so it applies the same validation and the same post-commit broadcast as the web form. The two endpoints differ in how they encode the request and response.

lib/helpdesk_web/api/tickets.ml
let codec =
  let open Simdjsont.Decode in
  Obj.field (fun id subject status ->
      { Models.Ticket.id; requester_id = 0; subject; body = ""; status = Models.Ticket.status_of_string status })
  |> Obj.mem "id" int ~enc:(fun (t : Models.Ticket.t) -> t.id)
  |> Obj.mem "subject" string ~enc:(fun (t : Models.Ticket.t) -> t.subject)
  |> Obj.mem "status" string ~enc:(fun (t : Models.Ticket.t) -> Models.Ticket.status_to_string t.status)
  |> Obj.finish

let index conn req =
  let viewer = Plugs.Auth.viewer req in
  Hcs.Response.json
    (Simdjsont.Encode.to_string (Simdjsont.Decode.list codec) (Contexts.Tickets.visible conn ~viewer))

let create conn pubsub req =
  let requester = Plugs.Auth.viewer req in
  let params = Hcs.Request.parse_query_string (Hcs.Request.body req) in
  match Contexts.Tickets.create conn ~pubsub ~requester ~params with
  | Ok t -> Hcs.Response.json ~status:`Created (Simdjsont.Encode.to_string codec t)
  | Error err ->
      let msgs = match err with `Validation m -> m | _ -> [ "could not open ticket" ] in
      let body = Printf.sprintf {|{"errors":[%s]}|} (String.concat "," (List.map (Printf.sprintf "%S") msgs)) in
      Hcs.Response.unprocessable_entity ~body () |> Hcs.Response.with_header "Content-Type" "application/json"

Live updates for operators

The context broadcasts a domain event after a ticket is committed. An operator's queue keeps a Server-Sent Events connection open. The handler subscribes to the tickets topic, and each new ticket is sent as a row that htmx prepends to the list. When a customer opens a ticket, subscribed operators receive the row without polling or reloading the page. The subscription is released when the connection closes. The write path publishes the event and does not handle the subscriptions.

lib/helpdesk_web/controllers/web.ml
(* LIVE UPDATES — the context's post-commit broadcast, consumed. An operator
   holds open this SSE connection; each create event becomes the new ticket
   row pushed down the stream, which htmx prepends to the queue. The
   subscription is released when the connection drops. *)
let events conn pubsub req =
  let viewer = Plugs.Auth.viewer req in
  if not (Role.is_operator viewer.role) then Hcs.Sse.respond (fun () -> None)
  else
    let inbox = Eio.Stream.create 64 in
    let unsubscribe = pubsub.Hive.Pubsub.subscribe ~topic:"tickets" (fun ~payload -> Eio.Stream.add inbox payload) in
    Hcs.Sse.respond (fun () ->
        match Eio.Stream.take inbox with
        | exception (Eio.Cancel.Cancelled _ as e) -> unsubscribe (); raise e
        | payload -> (
            match Option.bind (int_of_string_opt payload) (fun id -> Result.to_option (Models.Ticket.get conn ~id)) with
            | Some t -> Some (Hcs.Sse.make ~event_type:"new-ticket" (to_string (Views.Tickets.ticket_li ~viewer t)))
            | None -> Some (Hcs.Sse.make ~event_type:"ping" "")))

Routes: typed and bidirectional

A route value registers a handler and builds URLs. Captures are typed. tickets / int makes a route that passes an int to its handler, and the matching Route.link takes an int to build the path. A controller does not look up a parameter by string or parse it, and a view builds a path with Route.link. If a route's shape changes, a handler or link that no longer matches fails to compile.

lib/helpdesk_web/routes.ml
let home () = R.s ""
let login () = R.s "login"
let logout () = R.s "logout"
let events () = R.s "events"
let tickets () = R.s "tickets"
let ticket () = R.(s "tickets" / int)
let ticket_replies () = R.(s "tickets" / int / s "replies")
let ticket_status () = R.(s "tickets" / int / s "status" / str)

The router: pipelines and scopes

Logging, recovery, sessions, CSRF, auth, rate limits and security headers are plugs composed into named pipelines. They are not written inside handlers. A scope declares which pipeline its routes run through, so the pipeline for each URL can be read in the router. The HTML routes and their /api/v1 counterparts are listed together and call the same context.

lib/helpdesk_web/router.ml
R.compile_scopes
  [
    R.scope "/" ~through:base
      [ Rt.get (Routes.login ()) Controllers.Web.login_form; Rt.post (Routes.login ()) (Controllers.Web.login conn) ];
    R.scope "/" ~through:web
      [
        Rt.get (Routes.home ()) (Controllers.Web.index conn);
        Rt.post (Routes.logout ()) Controllers.Web.logout;
        Rt.post (Routes.tickets ()) (Controllers.Web.create conn pubsub);
        Rt.get (Routes.ticket ()) (Controllers.Web.show conn);
        Rt.post (Routes.ticket_replies ()) (Controllers.Web.reply conn);
        Rt.post (Routes.ticket_status ()) (Controllers.Web.triage conn);
        Rt.get (Routes.events ()) (Controllers.Web.events conn pubsub);
      ];
    R.scope "/api/v1" ~through:api
      [
        Rt.get (Routes.tickets ()) (Api.Tickets.index conn);
        Rt.post (Routes.tickets ()) (Api.Tickets.create conn pubsub);
      ];
  ]

Summary of the conventions

The conventions used in the helpdesk are listed below:

  • Precise types for input. Raw input is converted to a precise type at the edge. A ticket's status is a variant, so downstream code handles only the values defined by that type.
  • Errors as values. Workflows return a result with named error variants. The context's create returns the changeset's error list as a value. Exceptions are caught at the boundary that can translate them.
  • Authentication and authorization. A pipeline plug checks whether a user is logged in. The context checks what that user may see or do and returns Forbidden as a value. The web route and its API counterpart both call the context, so they apply the same checks.
  • I/O at the edges. Contexts perform effects, and the decisions around them are pure functions that can be called in a test. Capabilities (the clock, the connection, the pubsub bus) are passed in as arguments.
  • HTML over the wire. The server renders fragments that htmx swaps into the page. alpinejs is used for local UI state. A JSON endpoint is added when a client needs one, and it calls the same context as the HTML route.
  • One transactional boundary per write. A public context write runs in one transaction. Post-commit effects, such as a pubsub broadcast or a background job, run after the transaction commits.
  • Supervised work. Long-lived work runs as Eio fibers under one switch, started by application.ml, which is the root of the supervision tree.

Running the example

The test suite calls the context directly against an in-memory database, without a server or HTTP. It checks that customers see only their tickets, that triage is limited to operators, that a too-short subject is rejected, and that one customer cannot access another customer's ticket:

$ dune build @examples/helpdesk/test/runtest

To use the app, run the binary and open it in a browser. Sign in as ada / secret (a customer) or sam / secret (an operator):

$ dune exec examples/helpdesk/bin/main.exe

For a larger application that uses these conventions, with many contexts, a database, background workers and a clustered deployment, see ahoj.