Alpha.16 · standard library

Async stdlib in practice

Read the clock, work with files and subprocesses, and handle HTTP failures.

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

These examples use the native alpha.16 toolchain. Install the release to run them; their host I/O is unavailable in the browser playground. The full source is included below each recipe.

Choose the effect at the import

import stdlib/time/async as time

Read the clock with await time.now(). Use pure helpers such as time.seconds(5) without await. An ordinary caller instead imports stdlib/time as time and calls time.now() directly. The function names stay the same.

Async operations allow the calling task to suspend. They do not make impure work pure and do not mean that every operation starts a new thread.

Measure elapsed time

The timing example reads a monotonic clock, awaits a short timer and reads again. It reports whether the clock stayed monotonic; actual timings vary, so its output does not claim a precise delay.

./bin/panack run examples/async_timing.panack
Clock did not move backwards: true

now.difference(start) returns a Duration. The clock is for elapsed time, not calendar dates, and equal consecutive readings are allowed.

Write and read a temporary note

The temporary-note example creates a unique file, writes a note, reads it with a byte limit, checks UTF-8 and attempts cleanup on success or failure. It needs a writable current directory.

./bin/panack run examples/async_temporary_note.panack
remember the milk

Filesystem errors explain the failed operation. If cleanup also fails, preserve both explanations rather than losing the original failure.

Run a bounded subprocess

The subprocess example invokes /bin/cat with explicit input, an exact empty environment, a five-second timeout and a 64-byte output limit. It requires a POSIX host with that executable.

./bin/panack run examples/async_pipe_input.panack
hello λ

A completed process can return a nonzero status or be terminated by a signal. Check output.termination, not just the outer Result. Decode captured bytes with the checked UTF-8 API.

Return uptime from an HTTP handler

The uptime service stores its start Instant and service name in an immutable context. Each /health request awaits a new clock reading. No closure or mutable global is needed.

./bin/panack run --project examples/network/http_uptime/panack.json 8082

Open http://127.0.0.1:8082/health on the same machine. The response contains uptime_ns= followed by elapsed nanoseconds. A clock failure returns HTTP 503 with an explanation. Nanosecond representation does not imply nanosecond accuracy. The service binds to loopback; Ctrl-C stops it.

Keep HTTP failures useful

The diagnostic client imports http/client/async. It applies explicit bounds and prints either the HTTP status/body size or the rendered error with available transport detail.

./bin/panack run --project examples/network/http_diagnostic_client/panack.json https://example.com/

This command needs network access. A valid HTTP 404 is a received response; this example prints its status and exits unsuccessfully as an application policy. A URL, DNS, connection, TLS or framing failure is an error result. Certificates and hostnames remain verified. The error preserves details rather than guessing a cause; use typed categories for program decisions instead of parsing prose.

See the stdlib reference, migration guide, resource guide and input/publication guide for the rest of the API.

Complete example: async timing

import stdlib/time/async as time
import stdlib/console/async as console
import stdlib/host/async as host

async measure_pause(): Result[Bool,Str] {
  match await time.now() {
    Error(clock_error) => Error("The monotonic clock is unavailable."),
    Ok(start) => match await time.sleep(time.milliseconds(1)) {
      Error(problem) => Error(problem.render()),
      Ok(slept) => match await time.now() {
        Error(second_clock_error) => Error("The monotonic clock is unavailable."),
        Ok(end) => Ok(!end.is_before(start))
      }
    }
  }
}

async main(): Unit {
  match await measure_pause() {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(monotonic) => match await console.write_line("Clock did not move backwards: ${monotonic}") {
      Error(write_error) => await host.exit(1), Ok(written) => ()
    }
  }
}

Complete example: async temporary note

import stdlib/encoding/utf8 as utf8
import stdlib/filesystem/async as files
import stdlib/path as paths
import stdlib/console/async as console
import stdlib/host/async as host

async write_and_read(file: Path): Result[Str,Str] {
  match await files.write(file, "remember the milk".encode_utf8()) {
    Error(problem) => Error(problem.render()),
    Ok(written) => match await files.read(file, 1024) {
      Error(problem) => Error(problem.render()),
      Ok(data) => match utf8.decode(data) {
        Error(decode_error) => Error("The note is not valid UTF-8."), Ok(text) => Ok(text)
      }
    }
  }
}

async temporary_note(): Result[Str,Str] {
  match await files.create_temp_file(paths.current()) {
    Error(problem) => Error(problem.render()),
    Ok(file) => {
      result = await write_and_read(file)
      // Always attempt cleanup, including when writing or reading failed.
      match await files.remove_file(file) {
        Ok(removed) => result,
        Error(cleanup) => match result {
          Ok(text) => Error(cleanup.render()),
          Error(original) => Error(original + "\nCleanup also failed: " + cleanup.render())
        }
      }
    }
  }
}

async main(): Unit {
  match await temporary_note() {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(text) => match await console.write_line(text) {
      Error(write_error) => await host.exit(1), Ok(displayed) => ()
    }
  }
}

Complete example: async pipe input

import stdlib/encoding/utf8 as utf8
import stdlib/path as paths
import stdlib/process/async as process
import stdlib/time/async as time
import stdlib/console/async as console

async copy_text(): Result[Str,Str] {
  match paths.from_text("/bin/cat") {
    Error(path_error) => Error("The executable path is invalid."),
    Ok(executable) => {
      command = process.Command(executable, [], "hello λ".encode_utf8(),
        paths.current(), process.ExactEnvironment([]), time.seconds(5), 64)
      match await process.run(command) {
        Error(problem) => Error(problem.render()),
        Ok(output) => match output.termination {
          process.Signalled(signal) => Error("cat was terminated by signal ${signal}."),
          process.Exited(status) => {
            if status != 0 { Error("cat exited with status ${status}.") }
            else { match utf8.decode(output.stdout) {
              Error(decode_error) => Error("cat returned invalid UTF-8."), Ok(text) => Ok(text)
            } }
          }
        }
      }
    }
  }
}

async main(): Unit {
  match await copy_text() {
    Error(message) => {
      reported = await console.write_error_line(message)
      await process.exit(1)
    },
    Ok(text) => match await console.write_line(text) {
      Error(write_error) => await process.exit(1), Ok(written) => ()
    }
  }
}

Complete example: HTTP uptime service

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

record AppContext { started: Instant, service_name: Str }

async health(context: AppContext, request: http.Request, response: http.ResponseWriter): Result[Unit,Str] {
  match await time.now() {
    Error(problem) => {
      response.status(503)
      response.send("The monotonic clock is unavailable; uptime cannot be measured.")
      Ok(())
    },
    Ok(now) => {
      elapsed = now.difference(context.started)
      response.header("X-Service", context.service_name)
      ticks = elapsed.as_nanoseconds()
      response.send("uptime_ns=${ticks}")
      Ok(())
    }
  }
}

async main(): Unit {
  arguments = await host.arguments()
  port = if arguments.len() == 0 { 8082 } else { arguments[0].parse_nat() }
  service_name = (await environment.get("PANACK_SERVICE_NAME")).value_or("uptime-example")
  match await time.now() {
    Error(problem) => {
      reported = await host.stderr("Cannot start the service: the monotonic clock is unavailable.")
      await host.exit(1)
    },
    Ok(started) => {
      server = http.create_bound_contextual_server(
        "127.0.0.1", port, AppContext(started, service_name)
      )
      server.get("/health", @health)
      match await server.listen() {
        Ok(done) => (),
        Error(problem) => {
          reported = await host.stderr(problem.message)
          await host.exit(1)
        }
      }
    }
  }
}

Complete example: Diagnostic HTTP client

import http/client/async as http
import stdlib/console/async as console
import stdlib/host/async as host

async main(): Unit {
  arguments = await host.arguments()
  if arguments.len() != 1 {
    reported = await console.write_error_line("Usage: provide one HTTP or HTTPS URL.")
    await host.exit(2)
  } else {
    match await http.get_with_limits(arguments[0], http.ClientLimits(5000, 16384, 65536)) {
      Error(problem) => {
        // render includes available transport detail; do not guess a TLS cause.
        reported = await console.write_error_line(problem.render())
        await host.exit(1)
      },
      Ok(response) => {
        status = response.status
        size = response.body.len()
        match await console.write_line("HTTP ${status}; ${size} body bytes.") {
          Error(write_error) => await host.exit(1),
          Ok(written) => {
            // An HTTP error status is still a successfully received response.
            if status >= 400 { await host.exit(1) }
            ()
          }
        }
      }
    }
  }
}

Keep exploring

Explore Panackelty.