moon-lander

    MoonBit application framework without a user interface

    Download zip
    Author
    Version
    0.17.0
    License
    Apache-2.0
    Last updated
    yesterday
    Downloads
    6K

    #Moon-Lander

    Moon-Lander is an application framework for MoonBit with no user interface. It gives a MoonBit program what .NET hosting and configuration give a .NET program: layered configuration from files, environment variables, and the command line, typed binding, structured logging, typed actors, SignalR hubs, and a host that runs commands and services with clear exit codes.

    The umbrella module is moonrockz/moon-lander, imported as @lander. The configuration packages are in moonrockz/moon-lander-config: its pure core and formats run on wasm, wasm-gc, js, and native, its file host adapters support native and js, and its browser adapter supports js.

    #The layer stack

    A run moves down this stack. Each layer uses only the layers below it. The configuration core is pure: hosts give it files and environment values, so the same inputs give the same configuration on every target.

    Umbrella | @lander: batteries-included CLI entry with sane defaults Hosting | @hosting: bare builder, services, lifecycle, drivers, exit codes Binding | @config.bind: typed values with source-aware errors and validation Conventions | @conventions: discovery, workspaces, environments, profiles Configuration core | @config: sources, file tree, pure load, merge, provenance Formats | TOML, YAML, JSON5 and Ion; linked set selected by a virtual package

    Host adapters sit beside the core. On native and js they read the files that a load asks for. A wasm or wasm-gc host gives the files through a FileTree.

    The mediator sits beside the stack. It is pure and uses no other layer: the parts of an application send requests and publish events through typed values, and middleware holds the cross-cutting steps. The async mediator adds handlers that wait, on wasm, js and native.

    Logging sits at the bottom, beside core. Each part writes structured events through one Logger trait, and the application brings the backend that gets them. It uses only the MoonBit core library, so each module above can take a &Logger.

    #What exists today

    LayerPackageStatus
    Coremoonrockz/moon-lander-coreAppName, EnvPrefix, AbsolutePath, TimeLimit, and shared typed errors on all four targets
    Configuration coremoonrockz/moon-lander-configValue tree, key paths, typed file-tree paths, sources (defaults, files, environment, overrides), file tree and pure load, merge with null rules, provenance, merge policies, lazy secrets, redaction, display helpers (show, explain, path_text) and typed errors
    Formatsformats, parsers/* in moonrockz/moon-lander-configTOML, YAML with default/strict profiles, JSON/JSON5 and Ion; default and TOML-only linked sets through a virtual package
    Host adaptershost in moonrockz/moon-lander-confignative and js read files and fill missing variables and the working directory
    Browser adapterbrowser in moonrockz/moon-lander-configjs browser URL mounts with explicit manifests, run inputs, limits, cancellation, and typed boundary errors
    Conventions & profilesconventions, profiles in moonrockz/moon-lander-configWalk-up discovery in three layouts, system and global user directories on every platform, workspaces and member selection, environment files, configuration profiles, local and user overrides, explicit project file, ambiguity, legacy fallback, stop boundary, and isolated mode
    Bindingmoonrockz/moon-lander-configbind, bind_root, bind_or, bind_with (FromConfig), Sourced[T], Options[T], NamedOptions[T], and Validate with source-aware decode and validation errors
    Mediatormoonrockz/moon-lander-mediatorTyped senders, publish topics that run every handler and report every failure in one PublishFailed, a middleware pipeline with fixed order and short-circuit, an explicit context value and MediatorError on all four targets
    Async mediatormoonrockz/moon-lander-mediator/asyncAsync senders and topics with sequential and concurrent publish, caller cancellation, the timeout middleware, async middleware with a sync finally_, and from_sync on wasm, js and native
    Loggingmoonrockz/moon-lander-logging, logging-hosting-asyncBring-your-own Logger trait, six levels, structured events with Serilog-style message templates, category routing, context enrichment, configuration binding, console and rolling-file sinks, and hosted lifecycle integration
    Hostingmoonrockz/moon-lander-hosting (@hosting), console, argparse, moonrunBare builder, six-hook lifecycle engine, Lifetime, cancellation checks, exit codes and reports, shutdown timeout, moonbitlang/core/argparse integration with priority-700 overrides, native C signal stub and Node/Bun console drivers, embedded wasm/wasm-gc driver, explicit wasm Moonrun driver, enclosing host controls, and Program trait
    Umbrellamoonrockz/moon-lander (@lander)Batteries-included @lander.cli with linked formats, app_dirs, standard flags, environment-file discovery, @lander.command, @lander.build, target-selecting @lander.run and @lander.run_app, and pub using re-exports
    Actors & SignalR hubsmoonrockz/moon-lander-actors, moonrockz/signalr, moonrockz/moon-lander-hubsTyped actors with runtime events, standalone SignalR protocol/client/server, and hosted SignalR hubs

    The Configuration, Hosting, Mediator, Async mediator and Logging guides show each module's API with compiled examples.

    #Batteries-included entry

    @lander.cli(name, args) starts a host builder with sane defaults enabled:

    DefaultEnabled by @lander.cliChange or turn off
    FormatsLinked set from moonrockz/moon-lander-config/formats (TOML, YAML, JSON5, Ion)\|> @lander.formats(["toml", "yaml"])
    Conventionsapp_dirs(name, prefix~)\|> @lander.conventions(c => ...)
    Standard flags--environment, --config, --isolated, --project\|> @lander.no_standard_flags()
    Environment filesDiscovery on; loads only when a name is set\|> @lander.no_environments()
    Environment variables<PREFIX>_* at priority 600\|> @lander.env_prefix(...), \|> @lander.skip_env_source()
    Services recordUnit until build\|> @lander.build(factory)
    DriverConsole on native/js; embedded on wasm/wasm-gc\|> @lander.run(command) or \|> @lander.run_app(factory)
    Shutdown timeout30 seconds\|> @lander.shutdown_timeout(limit)

    The smallest program builds from one source on all four targets:

    ///|
    fn smallest_program(args : Array[String]) -> Unit raise {
    "acme" |> @lander.AppName::parse |> @lander.cli(args) |> @lander.run(_ => ())
    }

    ///|
    test "smallest program compiles on all four targets" {
    ignore(smallest_program)
    }

    A larger application writes its full pipeline in the one @lander style:

    ///|
    struct DemoServices {
    label : String
    flushes : Ref[Int32]
    }

    ///|
    fn demo_pipeline(
    args : Array[String],
    flushes : Ref[Int32],
    ) -> @lander.HostBuilder[DemoServices] raise {
    "acme"
    |> @lander.AppName::parse
    |> @lander.cli(args)
    |> @lander.configure(sources => {
    sources |> @config.defaults({ "app": { "label": "ready" } })
    })
    |> @lander.build(b => {
    label: @config.get_text(b.config, "app.label"),
    flushes,
    })
    |> @lander.service("telemetry", stopping=ctx => {
    ignore(ctx.services.label)
    ctx.services.flushes.val += 1
    })
    |> @lander.shutdown_timeout(@lander.TimeLimit::seconds(5))
    }

    ///|
    test "batteries pipeline builds cleanly on all four targets" {
    let flushes = Ref(0)
    ignore(demo_pipeline([], flushes))
    assert_eq(flushes.val, 0)
    }

    Use @lander.command(fn(name, standard) { ... }) to define a custom argparse command while keeping the active standard flags. Call standard.without(...) when your command defines its own option with the same id:

    ///|
    test "custom command composes active standard flags" {
    let builder = "acme"
    |> @lander.AppName::parse
    |> @lander.cli(["build", "--environment", "Staging"])
    |> @lander.command((name, standard) => {
    @hosting_argparse.Command(
    name,
    options=standard.options(),
    flags=standard.flags(),
    subcommands=[@hosting_argparse.Command("build")],
    )
    })
    ignore(builder)
    }

    Implement @lander.Program on your services record to run it directly with @lander.run_app(factory) instead of a lambda:

    ///|
    struct DemoApp {
    greeting : String
    }

    ///|
    impl @lander.Program for DemoApp with fn run(self, ctx) {
    ignore((self.greeting, ctx.environment.application_name))
    }

    ///|
    fn run_demo_app(args : Array[String]) -> Unit raise {
    "acme"
    |> @lander.AppName::parse
    |> @lander.cli(args)
    |> @lander.run_app(_ => { greeting: "hello", })
    }

    ///|
    test "run_app compiles on all four targets" {
    ignore(run_demo_app)
    }

    For full manual control with no defaults enabled, start with @hosting.builder from moonrockz/moon-lander-hosting.

    #Names, exit codes and starting settings

    Names and exit codes are parsed domain types with smart constructors, so invalid values cannot exist:

    TypeParseRule
    AppName@lander.AppName::parse("acme")Starts with an ASCII letter; then only ASCII letters, digits, - and _
    ServiceName@lander.ServiceName::parse("db")Safe as one file path component: starts with XID_Start, continues with XID_Continue, - or ., no invisible characters, no trailing ., not a Windows device name, at most 128 UTF-8 bytes
    ExitCode@lander.ExitCode::from_int(3), ExitCode::success(), ExitCode::failure()0 to 255

    Starting settings can supply the variable set, absolute working directory and default environment name on any target. Later steps replace them before the run:

    ///|
    test "explicit starting settings in one lander style" {
    let builder = "acme"
    |> @lander.AppName::parse
    |> @lander.cli(
    [],
    env_vars={ "ACME_PORT": "8080" },
    working_dir=@lander.AbsolutePath::parse("/work"),
    environment=@lander.EnvironmentName::parse("Staging"),
    )
    |> @lander.env_vars(({ "ACME_PORT": 9090, "ACME_DEBUG": true } : Json))
    |> @lander.working_dir(@lander.AbsolutePath::parse("/other"))
    |> @lander.formats(["toml"])
    |> @lander.no_environments()
    |> @lander.no_standard_flags()
    ignore(builder)
    }

    @lander.cli registers the formats from moonrockz/moon-lander-config/formats. To trim unused parsers at link time, override that virtual package with moonrockz/moon-lander-config/formats/toml (or a custom implementation) in your executable's moon.pkg. To narrow the active subset at runtime without changing link-time overrides, add |> @lander.formats(["toml"]).

    The format selection guide explains virtual package overrides and trimming checks.

    Configuration profiles are opt-in through @lander.profiles(@lander.Policy::new()). The umbrella re-exports ProfileName, ProfileNames, ProfileSelection, ProfileState, ProfileResolution and Policy.

    AbsolutePath

    Core domain types re-exported from moonrockz/moon-lander-core.

    AppName

    Core domain types re-exported from moonrockz/moon-lander-core.

    AppNameError

    Core domain types re-exported from moonrockz/moon-lander-core.

    AppNameRule

    Core domain types re-exported from moonrockz/moon-lander-core.

    BuildContext

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    Context

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    EnvPrefix

    Core domain types re-exported from moonrockz/moon-lander-core.

    EnvironmentName

    The parsed environment name for the starting default, from moonrockz/moon-lander-config/conventions.

    ExitCode

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    Hook

    type Hook[S] = async (
    Context
    [S]) -> Unit

    A hook of a hosted service, or the command of a run. It can wait, and it can raise an error.

    HostBuilder

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    HostEnvironment

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    HostError

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    IntoEnvVars

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    IntoServiceName

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    Lifetime

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    Mapping

    Set the command factory and explicit mappings used before configuration or hooks. The host appends the mapped source after its environment source.

    MappingAction

    Set the command factory and explicit mappings used before configuration or hooks. The host appends the mapped source after its environment source.

    MappingError

    Set the command factory and explicit mappings used before configuration or hooks. The host appends the mapped source after its environment source.

    OverrideOption

    Set the command factory and explicit mappings used before configuration or hooks. The host appends the mapped source after its environment source.

    Policy

    The opt-in profile policy used by @lander.profiles.

    ProfileName

    Parsed profile selection and loaded activation metadata.

    ProfileNames

    Parsed profile selection and loaded activation metadata.

    ProfileResolution

    Parsed profile selection and loaded activation metadata.

    ProfileSelection

    Parsed profile selection and loaded activation metadata.

    ProfileState

    Parsed profile selection and loaded activation metadata.

    Program

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    ServiceName

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    SignalKind

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    StandardFlag

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    StandardFlags

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    StopReason

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    StopRequested

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    StopToken

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    TimeLimit

    Core domain types re-exported from moonrockz/moon-lander-core.

    UsageError

    Hosting steps and types re-exported so batteries-included applications can write pipelines in one @lander style.

    build

    Set the services record factory for a @lander pipeline, changing HostBuilder[Unit] to HostBuilder[S] while keeping every earlier setting and hosted service. Services registered before build keep their order and receive a Context[Unit].

    cli

    Start a batteries-included host builder for the application name with the command-line arguments args. The services record defaults to Unit until @lander.build(factory) changes it.

    Defaults turned on by cli:
    • Linked configuration formats from moonrockz/moon-lander-config/formats (@lander.formats narrows them).
    • Standard application directory conventions app_dirs(name, prefix~) (@lander.conventions transforms or replaces them).
    • Standard global discovery flags --environment, --config, --isolated and --project (@lander.no_standard_flags disables them).
    • Environment-file discovery without a default name; files load only when --environment, <PREFIX>_ENVIRONMENT or a default sets a name (@lander.no_environments disables them).
    • <PREFIX>_* environment-variable source at priority 600 and a 30-second shutdown timeout.

    Explicit starting settings replace process inputs. environment sets a default name and enables environment-file discovery. Parse the name with @lander.EnvironmentName::parse at the caller boundary.

    command

    Define a custom argparse root command. make receives the application name and the active StandardFlags (empty when no_standard_flags() is set). Use standard.options() and standard.flags() to include the standard flags, and standard.without(flag) to omit any flag that the application defines itself.

    configure

    Add application sources and formats to the core configuration pipeline. Callbacks run in registration order, after arguments and environment resolution. Sources merge in this order: configure callbacks, the host-owned conventions set (System 100 through UserOverride 400), the _* source at 600, then argparse overrides at 700. Core load requires priorities that do not go down. With app_dirs() or conventions(f), configure sources must have priority 100 or less, such as defaults or an in-memory value at 0. Put a higher-priority file in the conventions set, or leave out the host-owned set. Conventions added here keep their own discovery options and do not see standard host flags. Use app_dirs() and conventions() for host-owned flag-aware discovery. The run's variable set and working directory replace values that a callback sets; use env_vars or working_dir on the host builder. A callback error ends the run before the factory or any hook.

    content_root

    Set the content root to an absolute path. A later step replaces the value. Without this step, the host uses the working directory of the run.

    conventions

    Transform or replace the host-owned convention set. Under @lander.cli, transform receives the default app_dirs(name, prefix~) set.

    default_environment

    Set the default environment and enable the environments part. Environment files need a primary part such as app_dirs(). The flag and the run's prefixed variable still take precedence. A later step replaces the default. Parse the name with @conventions.EnvironmentName::parse.

    env_prefix

    Replace the prefix for both the variable source and application directories.

    env_vars

    Replace the variable set for every reader. Conversion errors end the run with a usage error, before configuration I/O or hooks.

    error_report

    Replace the default standard-error report. At the end of a run, the driver calls this for each shutdown timeout for every exit code, and for each other failure only for code 1 or 2. Reports follow failure order. If a report raises, the driver ignores its error and reports the next failure. A report error cannot change the outcome or make run raise.

    files

    Supply the immutable file snapshot for wasm and wasm-gc. An incomplete snapshot ends configuration loading with usage code 2 and the requested paths in its error message. Native and js ignore this snapshot and read disk through the config host adapter.

    formats

    Keep only the linked formats whose Format.name matches an entry in names without regard to ASCII letter case, preserving linked order. An unknown name ends the run before any file read with HostError::UnknownFormat and exit code 1, naming the unknown name and the linked format names.

    map

    Map a parsed argument id to a parsed configuration key. action must match the argument declaration: Flag, Count, Set or Append. The default is Set. Append keeps a list with one value; Count keeps an integer even at zero. With parse, convert each text value, or the boolean/count text for a flag.

    no_environments

    Turn off environment-file discovery on the host-owned conventions set. HostEnvironment.environment_name still resolves from --environment, <PREFIX>_ENVIRONMENT and any default environment.

    no_standard_flags

    Turn off the four standard discovery flags (--environment, --config, --isolated, --project) on the default root command and pass an empty StandardFlags set to @lander.command.

    profiles

    Enable configuration profiles on the host-owned conventions set. This step adds no discovery parts; use app_dirs to discover primary files. A later app_dirs replaces earlier convention steps, including this policy.

    reserve_env

    Add full variable names that the source must not turn into keys. Names are compared after conversion to upper case, as in the variable source. A later env_prefix step does not change these names.

    run

    Build the host from its stored factory and run it with the console driver on native and js, starting the moonbitlang/core/async event loop and ending the process with the run's exit code.

    run_app

    Build a services record that implements Program and run it with the same target driver selection as @lander.run.

    service

    Add a hosted service with six optional hooks. The host runs all starting, then all start, then all started hooks in registration order. After the command it runs all stopping, then all stop, then all stopped hooks in reverse order, for started services only. A service counts as started when its start hook returns without an error, or when the service has no start hook, the start phase reached its starting step, and its starting hook succeeded or is absent. A service that the start phase did not reach is not started. A start failure skips the remaining start hooks and the command. A stop failure does not skip later hooks.

    Each service has its own name, without regard to letter case. A duplicate raises DuplicateService. name is a ServiceName, or a String that the step parses; a bad name raises InvalidServiceName.

    shutdown_timeout

    Set one time budget for the full stop phase, after the command task ends. The default is 30 seconds. A later step replaces an earlier value. run applies the limit, so the console driver on native and js and the Moonrun driver on wasm apply it. The embedded driver has no timer. The host cancels the current hook at the limit. A hook that protects itself from cancellation, or does not yield, runs until it returns, and run waits for it.

    shutdown_timeout_key

    Read this application-named key once after loading, before the factory. Its TimeLimit value overrides shutdown_timeout; an absent value keeps the builder limit, which defaults to 30 seconds. A bad value is a configuration error and no factory or hook runs.

    skip_env_source

    Skip only the prefixed configuration source. Other readers keep the set.

    version

    fn version() -> String

    The module version, kept in sync with the root moon.mod.

    working_dir

    Replace the absolute working directory. The last step wins.