Alpha.16 ยท standard library

Input and file publication

Read bounded input, publish a complete directory and use confined reads.

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

These examples require the native alpha.16 toolchain. They use the ordinary operation names through /async imports and explicitly await host work.

Read bounded input until EOF

async_console_input.panack reads standard input in chunks of at most 512 bytes, with a separate 4096-byte total message limit. It converts the complete message with the checked pure UTF-8 API and prints the Unicode scalar count.

printf 'Aฮป๐Ÿ™‚' | ./bin/panack run examples/async_console_input.panack
Received 3 characters.

An empty stream is valid and prints Received 0 characters.. When typing into an interactive terminal, end input with EOF (usually Ctrl-D); this example does not finish merely because a newline arrives. On a terminal with pending input, EOF may first deliver that input and require another EOF to end the stream.

console.read returns Ok(Some(bytes)), Ok(None()) for EOF, or an error. A short read is not EOF. The example waits for None() and does not interpret byte chunks as lines. It decodes once, after EOF, so a UTF-8 character split between reads is preserved.

Oversized input prints Input exceeds the 4096-byte message limit. and exits with status 1. Invalid text prints Input is not valid UTF-8. and also exits 1. An I/O error uses the console error's explanation. A diagnostic-output failure still leads to a failing exit status.

The 4096-byte limit is application policy, not the console API's maximum. Each console read permits a limit of 1 through 65536 bytes. Repeated concatenation is reasonable for this small bounded message; a larger stream should be processed in chunks or use a suitable buffering strategy. Do not collect an unlimited stream just to decode it at EOF.

Publish a complete directory, then read within it

async_publish_note.panack demonstrates the staging and confined-read APIs together:

./bin/panack run examples/async_publish_note.panack
Published note: hello

The example creates a unique temporary parent beneath the current directory, so it needs write permission there. It builds a stage containing a file named note, publishes the stage under the name note, reads the published file, and removes its own file and directories before returning. The resulting path is <temporary parent>/note/note; it never overwrites an existing application file.

The sequence is:

  1. staging.create(parent) creates an opaque DirectoryStage.
  2. staging.write_chunk(stage, relative, data, offset) writes relative to the stage.
  3. staging.publish(stage, name, CreateOnly()) makes the prepared directory available at the chosen sibling name. An existing destination causes failure.
  4. confined.read(published_root, relative, limit) performs the bounded read beneath that root and returns contents plus its physical root identity.

A successful publication consumes the stage. Do not discard it afterwards. For an operation or pre-commit publication failure, the example attempts discard and preserves any cleanup failure alongside the original error. Publication is not implemented by exposing a partly written directory and hoping readers wait for the last file.

The API also offers ReplaceExisting, but replacement has additional generation and cleanup rules. This introductory example deliberately uses CreateOnly. Read the publication contract and filesystem specification before implementing replacement. An error after an unrelated operation is not proof that a previously successful publication was rolled back.

Confinement is an operation, not a string prefix

confined.read(root, relative, limit) enforces the filesystem boundary using the native confined operation. Joining a root with user-provided text and calling an ordinary read is not equivalent. The read result carries a physical root identity; applications that need to bind multiple operations to an expected root must check the relevant identity contract rather than assuming a pathname never changes.

The example's cleanup removes only paths it created beneath its unique parent. It attempts cleanup after a read failure too, and reports cleanup errors instead of claiming that temporary files were removed. It does not promise cleanup code will execute after cancellation or process termination. The native staging resource has its own cancellation and shutdown rules; arbitrary published files do not acquire automatic lifetime management.

For a simpler file round trip without directory publication, see async_temporary_note.panack.

Complete example: async console input

import stdlib/console/async as console
import stdlib/encoding/utf8 as utf8
import stdlib/host/async as host

async read_message(limit: Nat): Result[Bytes,Str] {
  mut data = bytes()
  mut finished = false
  mut failure: Option[Str] = None()
  while !finished {
    match await console.read(512) {
      Error(problem) => { failure = Some(problem.render()); finished = true },
      Ok(input) => match input {
        None() => { finished = true },
        Some(chunk) => {
          if data.len() + chunk.len() > limit {
            failure = Some("Input exceeds the ${limit}-byte message limit.")
            finished = true
          } else { data = data.join(chunk) }
        }
      }
    }
  }
  match failure { Some(message) => Error(message), None() => Ok(data) }
}

async main(): Unit {
  match await read_message(4096) {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(data) => match utf8.decode(data) {
      Error(problem) => {
        reported = await console.write_error_line("Input is not valid UTF-8.")
        await host.exit(1)
      },
      Ok(text) => {
        count = text.len()
        match await console.write_line("Received ${count} characters.") {
          Error(write_error) => await host.exit(1), Ok(written) => ()
        }
      }
    }
  }
}

Complete example: async publish note

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

async publish(parent: Path, name: Path): Result[Unit,Str] {
  match await staging.create(parent) {
    Error(problem) => Error(problem.render()),
    Ok(stage) => {
      result = match await staging.write_chunk(stage, name, "hello".encode_utf8(), 0) {
        Error(problem) => Error(problem),
        Ok(written) => await staging.publish(stage, name, staging.CreateOnly())
      }
      match result {
        // Successful publication consumes the stage; do not discard it afterwards.
        Ok(published) => Ok(()),
        Error(problem) => match await staging.discard(stage) {
          Ok(discarded) => Error(problem.render()),
          Error(cleanup) => Error(problem.render() + "\nDiscard also failed: " + cleanup.render())
        }
      }
    }
  }
}

async read_note(root: Path, name: Path): Result[Str,Str] {
  match await confined.read(root, name, 1024) {
    Error(problem) => Error(problem.render()),
    Ok(read) => match utf8.decode(read.contents) {
      Error(problem) => Error("The published note is not valid UTF-8."),
      Ok(text) => Ok(text)
    }
  }
}

async exercise(parent: Path, name: Path): Result[Str,Str] {
  match parent.join(name) {
    Error(problem) => Error("Cannot form the publication path."),
    Ok(published) => match published.join(name) {
      Error(problem) => Error("Cannot form the note path."),
      Ok(file) => match await publish(parent, name) {
        Error(problem) => Error(problem),
        Ok(done) => {
          result = await read_note(published, name)
          // These exact paths belong to this example's newly created directory.
          removed_file = await files.remove_file(file)
          removed_directory = await files.remove_directory(published)
          mut combined = result
          for cleanup in [removed_file, removed_directory] {
            match cleanup {
              Ok(removed) => {},
              Error(problem) => {
                combined = match combined {
                  Ok(text) => Error(problem.render()),
                  Error(original) => Error(original + "\nCleanup also failed: " + problem.render())
                }
              }
            }
          }
          combined
        }
      }
    }
  }
}

async run_example(name: Path): Result[Str,Str] {
  match await files.create_temp_directory(paths.current()) {
    Error(problem) => Error(problem.render()),
    Ok(parent) => {
      result = await exercise(parent, name)
      match await files.remove_directory(parent) {
        Ok(removed) => result,
        Error(cleanup) => match result {
          Ok(text) => Error(cleanup.render()),
          Error(original) => Error(original + "\nCleanup also failed: " + cleanup.render())
        }
      }
    }
  }
}

async main(): Unit {
  result = match paths.from_text("note") {
    Error(problem) => Error("The example's relative path is invalid."),
    Ok(name) => await run_example(name)
  }
  match result {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(text) => match await console.write_line("Published note: ${text}") {
      Error(write_error) => await host.exit(1), Ok(written) => ()
    }
  }
}

Keep exploring

Explore Panackelty.