Alpha.16 · standard library

Functions and State cookbook

Build a retained counter and HTTP services with request counts and uptime.

These pages describe alpha.16. Host I/O requires the native toolchain; browser capabilities are limited. Browse the stdlib guides.

These complete programs combine anonymous functions, closures and State. Start with those pages if the concepts are new to you. These examples require alpha.16. The standalone counter also runs in the matching browser playground; the HTTP services require the native toolchain.

Keep a counter between calls

The standalone counter creates one cell, then stores a closure named next that retains its handle. Calling next updates that same cell each time. The pure increment callback receives the current count and returns its replacement.

The program prints 1, 2, then 2: two increments followed by a read. The callback expresses the calculation; the State operation makes the shared change explicit.

Combine state and an async HTTP handler

The closure example keeps its start instant and request counter in an anonymous handler. The contextual example uses a named handler and passes the same values through an explicit context. Neither style is required by State; choose the one that makes your code clearest.

Both examples count committed increments for /status and report monotonic uptime. An unrecognised route does not increment the count. A request rejected before entering the handler is not counted either.

The handler increments before reading the clock. If that clock read fails, the response is HTTP 503 and includes the committed count. Failure to read the clock at startup prints an explanation and exits instead of starting an unusable service.

Cancellation or a trap before commit preserves the old cell value. Cancellation or response failure after commit does not undo it. A cancelled waiter never runs the callback. These rules define what the counter measures; it is not a count of successfully delivered responses. Restarting the server resets the count.

Keep external work outside an update

An update callback cannot read the clock, perform I/O, await work or create, read or update a cell. Do that work before or after the update. If the update needs a value obtained asynchronously, await it first and pass the resulting immutable data into the callback. There are no callback retries, public locks or multi-cell transactions in this API.

Complete example: A counter without HTTP

import stdlib/state as state

main(): Void {
  count = state.create[Nat](0)
  increment = (current: Nat) => current + 1
  next = () => state.update(count, increment)
  print(next.call())
  print(next.call())
  print(state.read(count))
}

Complete example: Request count and uptime with a closure

import http/server as http
import stdlib/time/async as time
import stdlib/state/async as state
import stdlib/host/async as host

async main(): Unit {
  arguments = await host.arguments()
  port = if arguments.len() == 0 { 8082 } else { arguments[0].parse_nat() }
  match await time.now() {
    Error(problem) => {
      reported = await host.stderr("Cannot start: the monotonic clock is unavailable.")
      await host.exit(1)
    },
    Ok(started) => {
      requests = await state.create[Nat](0)
      server = http.create_bound_server("127.0.0.1", port)
      server.get("/status", async (request: http.Request, response: http.ResponseWriter): Result[Unit,Str] => {
        total = await state.update(requests, (current: Nat) => current + 1)
        reading: Result[Instant,time.ClockError] = await time.now()
        match reading {
          Error(problem) => {
            response.status(503)
            response.send("Requests counted: ${total}; uptime unavailable: the clock could not be read.")
            Ok(())
          },
          Ok(now) => {
            elapsed = now.difference(started)
            seconds = elapsed.as_seconds()
            response.send("Requests counted: ${total}; uptime: ${seconds} seconds")
            Ok(())
          }
        }
      })
      match await server.listen() {
        Ok(done) => (),
        Error(problem) => {
          reported = await host.stderr(problem.message)
          await host.exit(1)
        }
      }
    }
  }
}

Complete example: Request count and uptime with a named handler

import http/server as http
import stdlib/time/async as time
import stdlib/state/async as state
import stdlib/host/async as host

record AppContext { started: Instant, requests: State[Nat] }

async status(context: AppContext, request: http.Request, response: http.ResponseWriter): Result[Unit,Str] {
  started = context.started
  requests = context.requests
  total = await state.update(requests, (current: Nat) => current + 1)
  reading: Result[Instant,time.ClockError] = await time.now()
  match reading {
    Error(problem) => {
      response.status(503)
      response.send("Requests counted: ${total}; uptime unavailable: the clock could not be read.")
      Ok(())
    },
    Ok(now) => {
      elapsed = now.difference(started)
      seconds = elapsed.as_seconds()
      response.send("Requests counted: ${total}; uptime: ${seconds} seconds")
      Ok(())
    }
  }
}

async main(): Unit {
  arguments = await host.arguments()
  port = if arguments.len() == 0 { 8082 } else { arguments[0].parse_nat() }
  match await time.now() {
    Error(problem) => {
      reported = await host.stderr("Cannot start: the monotonic clock is unavailable.")
      await host.exit(1)
    },
    Ok(started) => {
      requests = await state.create[Nat](0)
      server = http.create_bound_contextual_server("127.0.0.1", port, AppContext(started, requests))
      server.get("/status", @status)
      match await server.listen() {
        Ok(done) => (),
        Error(problem) => {
          reported = await host.stderr(problem.message)
          await host.exit(1)
        }
      }
    }
  }
}

Keep exploring

Explore Panackelty.