From 0c9e0126335607ec552ee1e859c347220dfd9571 Mon Sep 17 00:00:00 2001 From: Scott Andrews Date: Mon, 23 Nov 2026 02:24:20 +0000 Subject: [PATCH 1/2] Use componentized/build Start transition to componentized build. Build and test appears functional, publishing has not transitioned yet. Replaced http-client with version from componentized/http. make components make test make test-integration Signed-off-by: Scott Andrews --- .config/wasm-pkg/config.toml | 7 + .devcontainer/devcontainer-lock.json | 19 + .devcontainer/devcontainer.json | 46 + .devcontainer/init.sh | 14 + .github/workflows/bump-version.yaml | 171 ++++ .github/workflows/ci.yaml | 438 ++++++++ .github/workflows/release.yaml | 59 ++ .github/workflows/release.yml | 65 -- .github/workflows/update-build.yaml | 108 ++ Cargo.lock | 157 ++- Cargo.toml | 14 +- Makefile | 222 +++++ build/MANIFEST | 32 + build/README.md | 13 + build/VERSION | 1 + build/build.mk | 119 +++ build/completions.jq | 18 + build/components.mk | 234 +++++ build/local.jq | 24 + build/pinned.jq | 17 + build/publish.mk | 28 + build/sbom.mk | 97 ++ build/scripts/bump-version.sh | 164 +++ build/scripts/check-build.sh | 68 ++ build/scripts/completions.sh | 43 + build/scripts/components.sh | 62 ++ build/scripts/create-commit.sh | 75 ++ build/scripts/install-cargo-binstall.sh | 40 + build/scripts/pack-components.sh | 57 ++ build/scripts/publish-crates.sh | 108 ++ build/scripts/publish.sh | 175 ++++ build/scripts/sbom-cargo.sh | 57 ++ build/scripts/sbom.sh | 359 +++++++ build/scripts/update-build.sh | 215 ++++ build/scripts/wac-deps.sh | 51 + build/scripts/wit-canonical.sh | 31 + build/scripts/wit-paths.sh | 79 ++ build/sync.mk | 14 + build/tools.mk | 258 +++++ build/tools/Cargo.toml | 55 ++ build/tools/lib.rs | 4 + build/wit.mk | 60 ++ components/Cargo.lock | 935 ------------------ components/Cargo.toml | 9 - components/build.sh | 15 - components/http-client/README.md | 3 + components/http-client/http-client.wkg | 2 + components/http/README.md | 48 - components/http/client/Cargo.toml | 15 - components/http/client/src/lib.rs | 245 ----- .../http/wit/deps/wasi-cli-0.3.0/package.wit | 28 - .../wit/deps/wasi-clocks-0.3.0/package.wit | 43 - .../http/wit/deps/wasi-http-0.3.0/package.wit | 509 ---------- .../wit/deps/wasi-random-0.3.0/package.wit | 18 - components/http/wit/package.wit | 72 -- components/http/wkg.lock | 12 - components/http/wkg.toml | 5 - components/lib/.gitignore | 1 - examples/filesystem/wkg.toml | 0 examples/hello-world/wkg.toml | 0 examples/host-capability/Cargo.lock | 10 - examples/interceptor/wkg.lock | 12 + examples/interceptor/wkg.toml | 2 + examples/named-imports/wkg.lock | 12 + examples/named-imports/wkg.toml | 0 examples/otel-components/Cargo.lock | 10 - examples/otel-components/build.sh | 2 +- examples/otel-service/Cargo.lock | 10 - examples/service/Cargo.lock | 10 - rust-toolchain.toml | 3 + scripts/smoke-test-cli.sh | 25 + wkg.lock | 4 + wkg.toml | 0 73 files changed, 3874 insertions(+), 2064 deletions(-) create mode 100644 .config/wasm-pkg/config.toml create mode 100644 .devcontainer/devcontainer-lock.json create mode 100644 .devcontainer/devcontainer.json create mode 100755 .devcontainer/init.sh create mode 100644 .github/workflows/bump-version.yaml create mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/release.yaml delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/update-build.yaml create mode 100644 Makefile create mode 100644 build/MANIFEST create mode 100644 build/README.md create mode 100644 build/VERSION create mode 100644 build/build.mk create mode 100644 build/completions.jq create mode 100644 build/components.mk create mode 100644 build/local.jq create mode 100644 build/pinned.jq create mode 100644 build/publish.mk create mode 100644 build/sbom.mk create mode 100755 build/scripts/bump-version.sh create mode 100755 build/scripts/check-build.sh create mode 100644 build/scripts/completions.sh create mode 100755 build/scripts/components.sh create mode 100755 build/scripts/create-commit.sh create mode 100755 build/scripts/install-cargo-binstall.sh create mode 100755 build/scripts/pack-components.sh create mode 100755 build/scripts/publish-crates.sh create mode 100755 build/scripts/publish.sh create mode 100755 build/scripts/sbom-cargo.sh create mode 100755 build/scripts/sbom.sh create mode 100755 build/scripts/update-build.sh create mode 100755 build/scripts/wac-deps.sh create mode 100755 build/scripts/wit-canonical.sh create mode 100755 build/scripts/wit-paths.sh create mode 100644 build/sync.mk create mode 100644 build/tools.mk create mode 100644 build/tools/Cargo.toml create mode 100644 build/tools/lib.rs create mode 100644 build/wit.mk delete mode 100644 components/Cargo.lock delete mode 100644 components/Cargo.toml delete mode 100755 components/build.sh create mode 100644 components/http-client/README.md create mode 100644 components/http-client/http-client.wkg delete mode 100644 components/http/README.md delete mode 100644 components/http/client/Cargo.toml delete mode 100644 components/http/client/src/lib.rs delete mode 100644 components/http/wit/deps/wasi-cli-0.3.0/package.wit delete mode 100644 components/http/wit/deps/wasi-clocks-0.3.0/package.wit delete mode 100644 components/http/wit/deps/wasi-http-0.3.0/package.wit delete mode 100644 components/http/wit/deps/wasi-random-0.3.0/package.wit delete mode 100644 components/http/wit/package.wit delete mode 100644 components/http/wkg.lock delete mode 100644 components/http/wkg.toml delete mode 100644 components/lib/.gitignore create mode 100644 examples/filesystem/wkg.toml create mode 100644 examples/hello-world/wkg.toml create mode 100644 examples/interceptor/wkg.lock create mode 100644 examples/interceptor/wkg.toml create mode 100644 examples/named-imports/wkg.lock create mode 100644 examples/named-imports/wkg.toml create mode 100644 rust-toolchain.toml create mode 100755 scripts/smoke-test-cli.sh create mode 100644 wkg.lock create mode 100644 wkg.toml diff --git a/.config/wasm-pkg/config.toml b/.config/wasm-pkg/config.toml new file mode 100644 index 0000000..d9c828d --- /dev/null +++ b/.config/wasm-pkg/config.toml @@ -0,0 +1,7 @@ +[namespace_registries] +wasi = "wasi.dev" +componentized = "componentized.dev" +# modulewise.dev does not yet serve /.well-known/wasm-pkg/registry.json, so +# provide the registry metadata inline. WIT packages are published to +# ghcr.io/modulewise/wit// (see publish-wit.yml). +modulewise = { registry = "modulewise.dev", metadata = { preferredProtocol = "oci", oci = { registry = "ghcr.io", namespacePrefix = "modulewise/wit/" } } } diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000..854ecb5 --- /dev/null +++ b/.devcontainer/devcontainer-lock.json @@ -0,0 +1,19 @@ +{ + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "version": "2.7.1", + "resolved": "ghcr.io/devcontainers/features/common-utils@sha256:e76a6a8a35d1ad824daad1540725e0ec9f8ed2dc00d2850e990a9830013c7d08", + "integrity": "sha256:e76a6a8a35d1ad824daad1540725e0ec9f8ed2dc00d2850e990a9830013c7d08" + }, + "ghcr.io/devcontainers/features/docker-in-docker:4": { + "version": "4.1.3", + "resolved": "ghcr.io/devcontainers/features/docker-in-docker@sha256:fae40f3c8be5a7c3b0db344c1d30341bc2c91ba38d1d5b14cd2ad72e6d65d084", + "integrity": "sha256:fae40f3c8be5a7c3b0db344c1d30341bc2c91ba38d1d5b14cd2ad72e6d65d084" + }, + "ghcr.io/devcontainers/features/github-cli:1": { + "version": "1.1.3", + "resolved": "ghcr.io/devcontainers/features/github-cli@sha256:bd7ab48a832228f633239277552c30b353867fef2e5b037e064b4e64f0b843f2", + "integrity": "sha256:bd7ab48a832228f633239277552c30b353867fef2e5b037e064b4e64f0b843f2" + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..672b99e --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,46 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/rust +{ + "name": "modulewise-composable-runtime", + "image": "mcr.microsoft.com/devcontainers/rust", + "runArgs": [ + "--name=modulewise-composable-runtime" + ], + // Use 'mounts' to make the cargo cache persistent in a Docker Volume. + "mounts": [ + { + "source": "devcontainer-cargo-cache", + "target": "/usr/local/cargo", + "type": "volume" + }, + { + "source": "devcontainer-rustup-cache", + "target": "/usr/local/rustup", + "type": "volume" + } + ], + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/devcontainers/features/common-utils:2": {}, + "ghcr.io/devcontainers/features/docker-in-docker:4": { + "moby": false + }, + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "./.devcontainer/init.sh", + // Configure tool-specific properties. + "customizations": { + // Configure properties specific to VS Code. + "vscode": { + // Set *default* container specific settings.json values on container create. + "settings": { + "dev.containers.githubCLILoginWithToken": true + }, + "extensions": [ + "bytecodealliance.wit-idl", + "tamasfe.even-better-toml" + ] + } + } +} \ No newline at end of file diff --git a/.devcontainer/init.sh b/.devcontainer/init.sh new file mode 100755 index 0000000..cfe49cf --- /dev/null +++ b/.devcontainer/init.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +# Setup script run once for new devcontainers to init the environment. + +set -euo pipefail + +curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash + +echo "PATH=\"\$(make -s tools-path):\${PATH}\"" | tee -a ~/.zshrc ~/.bashrc >/dev/null +echo "source \"$(pwd)/build/scripts/completions.sh\"" | tee -a ~/.zshrc ~/.bashrc >/dev/null + +make tools wit + +cargo check diff --git a/.github/workflows/bump-version.yaml b/.github/workflows/bump-version.yaml new file mode 100644 index 0000000..c71af5f --- /dev/null +++ b/.github/workflows/bump-version.yaml @@ -0,0 +1,171 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +name: Bump version + +on: + workflow_dispatch: + inputs: + version: + description: The new version of the interface package and crates, e.g. 0.1.0 or 0.2.0-dev + required: true + type: string + # the repository's own version, carried forward by build/scripts/update-build.sh, and ignored + # by build/scripts/check-build.sh + default: "0.1.6" # the current version, kept current by build/scripts/bump-version.sh + +jobs: + # bumps the version with read only access, the changes are handed to the push job as a patch so + # the third party actions used to build never run with write access + bump: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + current: ${{ steps.version.outputs.current }} + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Check version + id: version + # a semver version without a leading `v`, the tag adds it. Build metadata is used to tag the + # debug builds of components, e.g. 0.1.0+debug, and isn't allowed in the version itself. + run: | + # the checkout is before the bump, the wit package's version is the current version + current=$( sed -n "s/^package ${GITHUB_REPOSITORY/\//:}@\(.*\);$/\1/p" wit/worlds.wit ) + identifier='(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)' + semver="^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-${identifier}(\.${identifier})*)?$" + if ! [[ "${VERSION}" =~ ${semver} ]] ; then + echo "::error::the version '${VERSION}' is not a valid semver version, e.g. 0.1.0 or 0.2.0-dev" + exit 1 + fi + if [[ "${VERSION}" == *+* ]] ; then + echo "::error::the version '${VERSION}' must not contain build metadata" + exit 1 + fi + echo "bumping ${current} to ${VERSION}" + echo "current=${current}" >> "${GITHUB_OUTPUT}" + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + env: + VERSION: ${{ inputs.version }} + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Install tools + run: | + make tools + make -s tools-path >> "${GITHUB_PATH}" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Bump version + # also fetches the wit dependencies for the new version, and builds and tests the components + run: build/scripts/bump-version.sh "${VERSION}" + env: + VERSION: ${{ steps.version.outputs.version }} + - name: Collect changes + run: | + git add --all + git diff --cached --binary > bump-version.patch + - name: Upload changes + uses: actions/upload-artifact@v7 + with: + name: bump-version.patch + path: bump-version.patch + if-no-files-found: error + retention-days: 1 + + # pushes the bump to the branch the workflow was run on, using only first party actions and the gh + # cli + push: + needs: + - bump + # the bump is a new commit on the branch, a tag can't be moved forward + if: github.ref_type == 'branch' + runs-on: ubuntu-latest + # the commit is pushed with a token for the custodian GitHub App rather than the GITHUB_TOKEN, + # which can't change workflow files and doesn't trigger the CI workflow. The app must be allowed + # to bypass the branch's ruleset, the commit is pushed without the status checks it requires, + # the bump job built and tested the changes instead. + permissions: + contents: read + env: + CURRENT_VERSION: ${{ needs.bump.outputs.current }} + VERSION: ${{ needs.bump.outputs.version }} + steps: + - name: Check custodian app credentials + run: | + if [ -z "${CLIENT_ID}" ] || [ -z "${PRIVATE_KEY}" ] ; then + echo "::error::the CUSTODIAN_CLIENT_ID and CUSTODIAN_PRIVATE_KEY secrets must be available to this repository, the private key of the custodian GitHub App is needed to create a token" + exit 1 + fi + env: + CLIENT_ID: ${{ secrets.CUSTODIAN_CLIENT_ID }} + PRIVATE_KEY: ${{ secrets.CUSTODIAN_PRIVATE_KEY }} + - name: Create custodian app token + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.CUSTODIAN_CLIENT_ID }} + private-key: ${{ secrets.CUSTODIAN_PRIVATE_KEY }} + # only this repository, with only the permissions the bump needs + repositories: ${{ github.event.repository.name }} + permission-contents: write + # the bump may change a workflow file, e.g. a reference to the package + permission-workflows: write + # a release runs this workflow again, to bump to the next dev version + permission-actions: write + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Download changes + uses: actions/download-artifact@v8 + with: + name: bump-version.patch + path: ${{ runner.temp }} + - name: Commit changes + # the commit is created with the REST API, as the app's token can't push + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + run: | + api="repos/${GITHUB_REPOSITORY}" + base=$( git rev-parse HEAD ) + git apply --index "${RUNNER_TEMP}/bump-version.patch" + commit=$( build/scripts/create-commit.sh "${base}" "Bump version from ${CURRENT_VERSION} to ${VERSION}" ) + + # a release, rather than a pre-release, is tagged, e.g. v0.1.0. Tags are immutable, check the + # tag is free before pushing the branch, so a release isn't left without its tag + tag="" + if [[ "${VERSION}" != *-* ]] ; then + tag="v${VERSION}" + if gh api "${api}/git/ref/tags/${tag}" --silent 2> /dev/null ; then + echo "::error::the tag ${tag} already exists" + exit 1 + fi + fi + + # fast forwards the branch to the commit, failing rather than losing commits pushed to the + # branch since the workflow started + if ! gh api --method PATCH "${api}/git/refs/heads/${GITHUB_REF_NAME}" -f sha="${commit}" -F force=false --silent ; then + echo "::error::failed to push ${commit} to ${GITHUB_REF_NAME}, either the branch moved since ${base} and the workflow should be run again, or the custodian app is not allowed to bypass the branch's ruleset" + exit 1 + fi + echo "pushed ${commit} to ${GITHUB_REF_NAME}" + + # a lightweight tag, pushed with the app's token so the CI workflow runs for it and drafts + # the release + if [ -n "${tag}" ] ; then + gh api --method POST "${api}/git/refs" -f ref="refs/tags/${tag}" -f sha="${commit}" --silent + echo "tagged ${commit} as ${tag}" + fi + - name: Bump to the next dev version + # after a release, the branch moves on to a pre-release of the next patch version, e.g. 0.3.0 + # is followed by 0.3.1-dev. Run with the app's token, the GITHUB_TOKEN can't start workflows. + if: ${{ !contains(needs.bump.outputs.version, '-') }} + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + run: | + IFS=. read -r major minor patch <<< "${VERSION}" + next="${major}.${minor}.$(( patch + 1 ))-dev" + gh workflow run bump-version.yaml --repo "${GITHUB_REPOSITORY}" --ref "${GITHUB_REF_NAME}" -f version="${next}" + echo "started the ${GITHUB_WORKFLOW} workflow for ${next} on ${GITHUB_REF_NAME}" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..6c44e91 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,438 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +name: CI + +on: + push: + branches: + - "**" + - "!dependabot/**" + - "!update-build/**" + tags: + - 'v[0-9]+\.[0-9]+\.[0-9]+-?**' + pull_request: {} + +# read only unless a job asks for more, e.g. publish, the GITHUB_TOKEN is otherwise the repository's +# default, which may be able to write +permissions: + contents: read + +jobs: + # the settings of the repository's Makefile the other jobs need, e.g. whether it builds a cli + settings: + runs-on: ubuntu-latest + outputs: + cli: ${{ steps.settings.outputs.cli }} + steps: + - uses: actions/checkout@v7 + - name: Check build + # the files synced from componentized/build are unchanged, see build/README.md + run: build/scripts/check-build.sh + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Read settings + id: settings + run: echo "cli=$( make -s print-CLI_BIN )" >> "${GITHUB_OUTPUT}" + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Cache tools + # the tools installed here, with a read only GITHUB_TOKEN, are restored by the publish job, + # which doesn't install them with its token that can write. Saved once the job succeeds. + uses: actions/cache@v6 + with: + path: target/tools + key: tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('build/tools/Cargo.toml', 'tools/Cargo.toml', 'rust-toolchain.toml', 'build/tools.mk') }} + - name: Install tools + # the versions pinned in build/tools/Cargo.toml and tools/Cargo.toml, on the path for later + # steps. Nothing to install when the cache is restored. The token raises cargo binstall's + # GitHub API rate limit. + run: | + make tools + make -s tools-path >> "${GITHUB_PATH}" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Generate + # the wit dependencies, and anything else the repository generates, see `make generate` + run: make generate + - name: Check for drift in generated files + run: git diff --exit-code . + - name: Check crate version matches the interface version + # the crates inherit the workspace version, bumped with the interface by + # build/scripts/bump-version.sh. A repository without a workspace version has nothing to check. + run: | + interface_version=$( sed -n "s/^package ${GITHUB_REPOSITORY/\//:}@\(.*\);$/\1/p" wit/worlds.wit ) + workspace_version=$( sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"$/\1/p' Cargo.toml ) + if [ -n "${workspace_version}" ] && [ "${workspace_version}" != "${interface_version}" ] ; then + echo "::error::the workspace version ${workspace_version} in Cargo.toml does not match the interface version ${interface_version}, see build/scripts/bump-version.sh" + exit 1 + fi + - name: Check crates can be published + # the release workflow publishes the crates when a release is published, too late to find a + # crate can't be published. A cli is verified against the library being published with it. + run: | + read -ra crates <<< "$( make -s print-PUBLISH_CRATES )" + if [ "${#crates[@]}" -eq 0 ] ; then + echo "no crates to publish, see PUBLISH_CRATES" + exit 0 + fi + cargo publish --dry-run --locked "${crates[@]/#/--package=}" + - name: Build components + run: make components + - name: Collect components.tar + run: tar -cvf ../../components.tar . + working-directory: ./target/components + - name: Upload components.tar + uses: actions/upload-artifact@v7 + with: + name: components.tar + path: components.tar + retention-days: 7 + - name: Test + run: make test + - name: Integration test + # the tests that need more than cargo, e.g. a server in a container, see `make test-integration` + run: make test-integration + - name: Capture WIT + working-directory: ./target/components + run: | + dump_wit() { + echo "::group::$(basename "$1") ($(du -h "$1" | awk '{print $1}' ))" + wasm-tools component wit "$1" + echo "::endgroup::" + } + + # print interface.wasm first + if [ -f interface.wasm ] ; then + dump_wit interface.wasm + fi + for component in $(find . -name '*.wasm' -not -name '*.debug.wasm' -not -name 'interface.wasm' | sort) ; do + dump_wit "${component}" + done + + # the cli built from the repository, see CLI_BIN, packaged for each platform as cargo binstall + # expects, e.g. constants-aarch64-apple-darwin.tar.gz + cli: + needs: + - settings + if: needs.settings.outputs.cli != '' + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-26.04 + target: x86_64-unknown-linux-musl + - os: ubuntu-26.04-arm + target: aarch64-unknown-linux-musl + - os: macos-26 + target: aarch64-apple-darwin + - os: macos-26-intel + target: x86_64-apple-darwin + - os: windows-2025 + target: x86_64-pc-windows-msvc + - os: windows-11-arm + target: aarch64-pc-windows-msvc + # each runner builds for its own platform, linux builds are static with musl + runs-on: ${{ matrix.os }} + # bash on windows too, where pwsh is the default, the steps read CLI_BIN from the environment. The + # windows packaging steps are pwsh, reading it as `${env:CLI_BIN}`. + defaults: + run: + shell: bash + env: + CLI_BIN: ${{ needs.settings.outputs.cli }} + steps: + - uses: actions/checkout@v7 + - uses: actions-rust-lang/setup-rust-toolchain@v2 + with: + target: ${{ matrix.target }} + - name: Install musl + # the static linux builds compile the C of a crate the cli depends on, e.g. aws-lc-sys of rustls, + # with musl-gcc, cc looks for a cross compiler, e.g. x86_64-linux-musl-gcc, the runners have none + if: endsWith(matrix.target, '-linux-musl') + env: + TARGET: ${{ matrix.target }} + run: | + sudo apt-get update + sudo apt-get install -y musl-tools + echo "CC_${TARGET//-/_}=musl-gcc" >> "${GITHUB_ENV}" + - name: Build cli + run: cargo build --release --locked --bin "${CLI_BIN}" --target ${{ matrix.target }} + - name: Package cli + if: runner.os != 'Windows' + run: | + mkdir -p dist + tar -czvf "dist/${CLI_BIN}-${{ matrix.target }}.tar.gz" -C target/${{ matrix.target }}/release "${CLI_BIN}" -C "${PWD}" LICENSE NOTICE README.md + - name: Package cli + if: runner.os == 'Windows' + shell: pwsh + run: | + New-Item -ItemType Directory -Force dist + Compress-Archive -Path "target/${{ matrix.target }}/release/${env:CLI_BIN}.exe", LICENSE, NOTICE, README.md -DestinationPath "dist/${env:CLI_BIN}-${{ matrix.target }}.zip" + # the smoke test runs the cli from the package, as a user would + - name: Unpack cli + if: runner.os != 'Windows' + run: | + mkdir -p smoke + tar -xzvf "dist/${CLI_BIN}-${{ matrix.target }}.tar.gz" -C smoke + - name: Unpack cli + if: runner.os == 'Windows' + shell: pwsh + run: Expand-Archive -Path "dist/${env:CLI_BIN}-${{ matrix.target }}.zip" -DestinationPath smoke + - name: Install wasmtime + uses: bytecodealliance/actions/wasmtime/setup@v1 + - name: Smoke test cli + # the repository's scripts/smoke-test-cli.sh runs the unpacked cli, given its path and a + # directory for its files + run: | + if [ ! -f scripts/smoke-test-cli.sh ] ; then + echo "::warning::no scripts/smoke-test-cli.sh to smoke test ${CLI_BIN}" + exit 0 + fi + bash scripts/smoke-test-cli.sh "./smoke/${CLI_BIN}" smoke + - name: Upload cli + uses: actions/upload-artifact@v7 + with: + name: cli-${{ matrix.target }} + path: dist/* + if-no-files-found: error + retention-days: 7 + + # a single check for branch protection to require, rather than each job and matrix entry. It always + # runs, a skipped required check counts as passing, and fails when any job it needs did not succeed. + # The cli is skipped for a repository without one. + ci: + if: always() + needs: + - settings + - build + - cli + runs-on: ubuntu-latest + steps: + - name: Check jobs succeeded + env: + RESULTS: ${{ toJSON(needs.*.result) }} + CLI: ${{ needs.settings.outputs.cli }} + CLI_RESULT: ${{ needs.cli.result }} + run: | + echo "results: ${RESULTS}" + if [ -z "${CLI}" ] && [ "${CLI_RESULT}" = "skipped" ] ; then + RESULTS=$( jq -c 'map(select(. != "skipped"))' <<< "${RESULTS}" ) + fi + if jq -e 'any(. != "success")' <<< "${RESULTS}" > /dev/null ; then + echo "::error::a required job did not succeed" + exit 1 + fi + + publish: + # the ci job's result rather than the default success(), which is false when the cli is skipped, + # even though the ci job succeeded without it + if: ${{ !cancelled() && needs.ci.result == 'success' && github.event_name == 'push' && ( startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main' ) }} + needs: + - settings + - ci + permissions: + contents: write + packages: write + id-token: write + runs-on: ubuntu-latest + env: + # the repository variable DRY_RUN=true goes through publishing without publishing anything: + # nothing is pushed or signed, and no release is drafted + DRY_RUN: ${{ vars.DRY_RUN == 'true' }} + outputs: + # the version published, and whether anything was, for the directory-scan job + version: ${{ steps.version.outputs.VERSION }} + published: ${{ steps.publish.outputs.published == 'true' }} + steps: + - name: Dry run + if: env.DRY_RUN == 'true' + run: echo "::notice::a dry run, the repository variable DRY_RUN is true, nothing is published" + - uses: actions/checkout@v7 + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Restore tools + # installed by the build job, so the tools aren't downloaded, or built, where the GITHUB_TOKEN + # can write and OIDC tokens can be requested. The key must match the build job's. + uses: actions/cache/restore@v6 + with: + path: target/tools + key: tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('build/tools/Cargo.toml', 'tools/Cargo.toml', 'rust-toolchain.toml', 'build/tools.mk') }} + fail-on-cache-miss: true + - name: Add tools to the path + # the restored tools, nothing is installed. Publishing only needs the pinned tools, wkg and + # cosign, a local tool isn't built here. + run: make -s tools-path >> "${GITHUB_PATH}" + - name: Download components.tar + uses: actions/download-artifact@v8 + with: + name: components.tar + - name: Download cli + if: needs.settings.outputs.cli != '' + uses: actions/download-artifact@v8 + with: + pattern: cli-* + path: dist + merge-multiple: true + - name: Extract components + run: mkdir -p target/components && tar -xvf components.tar -C target/components + - name: Get interface version + id: interface_version + run: echo "VERSION=$( wasm-tools component wit target/components/interface.wasm --json | jq -r "[.packages[] | select(.name | contains(\"${GITHUB_REPOSITORY/\//:}@\"))][0].name" | cut -d'@' -f2 )" >> $GITHUB_OUTPUT + - name: Get tag version + if: startsWith(github.ref, 'refs/tags/') + id: tag_version + run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT + - name: Get publish version + # the interface version on main, the tag on a tag, without a leading `v`, e.g. 0.1.0 for v0.1.0 + id: version + env: + VERSION: ${{ case(github.ref == 'refs/heads/main', steps.interface_version.outputs.VERSION, steps.tag_version.outputs.VERSION) }} + run: echo "VERSION=${VERSION#v}" >> $GITHUB_OUTPUT + - name: Check tag matches the workspace version + # cargo binstall finds the cli archives at the release tagged with the cli crate's version, + # and publishing the release publishes the crates to crates.io at that version. A repository + # without a workspace version has nothing to check. + if: startsWith(github.ref, 'refs/tags/') + run: | + workspace_version=$( sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"$/\1/p' Cargo.toml ) + if [ -n "${workspace_version}" ] && [ "v${workspace_version}" != "${{ steps.tag_version.outputs.VERSION }}" ] ; then + echo "::error::tag ${{ steps.tag_version.outputs.VERSION }} does not match the workspace version ${workspace_version} in Cargo.toml" + exit 1 + fi + - name: Login to GitHub Container Registry + if: env.DRY_RUN != 'true' + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Publish components to gchr.io + # only publish tags and pre-releases from main + if: startsWith(github.ref, 'refs/tags/') || (github.ref == 'refs/heads/main' && contains(steps.interface_version.outputs.VERSION, '-')) + id: publish + run: | + make publish + # nothing may be published, e.g. a repository of tests, see PUBLISH_INTERFACE + if [ "${DRY_RUN}" != "true" ] && [ -s "${PUBLISH_LOG}" ] ; then + echo "published=true" >> "${GITHUB_OUTPUT}" + fi + env: + PUBLISH_LOG: "${{ runner.temp }}/published.txt" + REPOSITORY: "ghcr.io/${{ github.repository }}" + VERSION: "${{ steps.version.outputs.VERSION }}" + - name: Draft release notes + if: startsWith(github.ref, 'refs/tags/') || (github.ref == 'refs/heads/main' && contains(steps.interface_version.outputs.VERSION, '-')) + # with COMPONENTIZED_DIRECTORY_SCAN=true, each file leads with its id and icon linking to the + # page componentized.dev serves its version at once the directory-scan job's scan has indexed + # it, the debug build to the page of its version. The directory's id of a package is its repository + # path, e.g. ghcr.io/componentized/logging is componentized:logging, the interface, and + # ghcr.io/componentized/logging/levels is componentized:logging-levels, a component. The icon + # is the directory's for the kind of package, https://componentized.dev/_icons/, in the colors + # of GitHub's light or dark theme, neutral where the theme isn't known. + env: + DIRECTORY: ${{ vars.COMPONENTIZED_DIRECTORY_SCAN == 'true' }} + VERSION: ${{ steps.version.outputs.VERSION }} + run: | + icons="https://componentized.dev/_icons" + published="${RUNNER_TEMP}/published.txt" + if [ ! -s "${published}" ] ; then + # nothing published, e.g. a repository of tests, see PUBLISH_INTERFACE, or a dry run + echo "No components are published with this release." > "${RUNNER_TEMP}/release-notes.md" + cat "${RUNNER_TEMP}/release-notes.md" + exit 0 + fi + { + echo "## Published components" + echo + if [ "${DIRECTORY}" = "true" ] ; then + echo "| Directory | File | Size | Image |" + echo "| --- | --- | --: | --- |" + else + echo "| File | Size | Image |" + echo "| --- | --: | --- |" + fi + while read -r file bytes image ; do + size=$( numfmt --to=iec-i --suffix=B --format=%.1f "${bytes}" ) + row="| \`${file}\` | ${size} | \`${image}\` |" + if [ "${DIRECTORY}" = "true" ] ; then + # e.g. ghcr.io/componentized/logging/levels:0.3.1@sha256:... -> componentized/logging/levels + path="${image#*/}" + path="${path%%[:@]*}" + namespace="${path%%/*}" + name="${path#*/}" + name="${name//\//-}" + # the directory's kind: the interface is a package, a component composed with wac + # is a composition, e.g. levels.debug.wasm from components/levels/levels.wac. A + # component's files are named for its directory, found by the build, e.g. + # examples/hello/hello.wac for example-hello + component="${file%.wasm}" + component="${component%.debug}" + dir=$( make -s "print-COMPONENT_DIR_${component}" ) + base="${dir##*/}" + if [ "${file}" = "interface.wasm" ] ; then + kind=package + elif [ -n "${dir}" ] && { [ -f "${dir}/${base}.wac" ] || [ -f "${dir}/${base}.plug" ] ; } ; then + kind=composition + else + kind=component + fi + id="${namespace}:${name}@${VERSION}" + # each icon is 26 by 26, a 16 by 16 icon with a margin for its badges, centered on the + # text. GitHub drops the styles that would keep the id on one line, so a word joiner + # holds the id to its icon and its hyphens are non-breaking hyphens, the link and its + # title have the id as it is. The link has GitHub's color, GitHub drops the styles + # that would give it the directory's. + picture="\"${kind}\"" + label="${id//-/$'\xe2\x80\x91'}" + row="| ${picture}"$'\xe2\x81\xa0'"${label} ${row}" + fi + echo "${row}" + done < "${published}" + } > "${RUNNER_TEMP}/release-notes.md" + cat "${RUNNER_TEMP}/release-notes.md" + - name: Pack components.tar with the published SBOMs + # each component released with an SBOM, the one it's published with, see PUBLISHED_SBOM_DIR in + # build/sbom.mk, in place of the build's, which doesn't name its version or image. A file that + # isn't published, e.g. a dep- component, keeps the build's, see build/scripts/pack-components.sh + if: startsWith(github.ref, 'refs/tags/') && env.DRY_RUN != 'true' + run: build/scripts/pack-components.sh target/components target/sbom/published components.tar + - name: Draft GitHub Release + if: startsWith(github.ref, 'refs/tags/') && env.DRY_RUN != 'true' + uses: softprops/action-gh-release@v3 + with: + draft: true + body_path: ${{ runner.temp }}/release-notes.md + # the components with their SBOMs, and the cli archives of a repository with a cli + files: | + components.tar + ${{ needs.settings.outputs.cli != '' && 'dist/*' || '' }} + fail_on_unmatched_files: true + token: ${{ secrets.GITHUB_TOKEN }} + + # asks componentized/directory to scan the components just published. The organization variable + # COMPONENTIZED_DIRECTORY_SCAN=true limits it to componentized repositories, a repository outside + # it uses the build without the custodian's access to the directory. + directory-scan: + # !cancelled() rather than the default success(), which is false when the cli is skipped + if: ${{ !cancelled() && vars.COMPONENTIZED_DIRECTORY_SCAN == 'true' && needs.publish.result == 'success' && needs.publish.outputs.published == 'true' }} + needs: publish + # the app token is used, not the GITHUB_TOKEN + permissions: {} + runs-on: ubuntu-latest + steps: + - name: Create directory token + id: directory-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.CUSTODIAN_CLIENT_ID }} + private-key: ${{ secrets.CUSTODIAN_PRIVATE_KEY }} + repositories: directory + permission-contents: write + - name: Request a directory scan + env: + GH_TOKEN: ${{ steps.directory-token.outputs.token }} + VERSION: ${{ needs.publish.outputs.version }} + run: gh api repos/componentized/directory/dispatches -f event_type=release -f "client_payload[only]=${GITHUB_REPOSITORY}" -f "client_payload[version]=${VERSION}" diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..6c9287e --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,59 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +name: Release + +on: + release: + types: + - published + +jobs: + # the crates of a repository that publishes crates, see PUBLISH_CRATES + crates: + runs-on: ubuntu-latest + permissions: + contents: read + # crates.io trusted publishing exchanges a GitHub OIDC token for a short lived crates.io token + id-token: write + env: + # the repository variable DRY_RUN=true checks the crates with `cargo publish --dry-run` rather + # than publishing them + DRY_RUN: ${{ vars.DRY_RUN == 'true' }} + steps: + - uses: actions/checkout@v7 + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Read settings + id: settings + run: | + crates=$( make -s print-PUBLISH_CRATES ) + [ -z "${crates}" ] && echo "no crates to publish, see PUBLISH_CRATES" + echo "crates=${crates}" >> "${GITHUB_OUTPUT}" + - name: Check crate version matches the release + # the crates inherit the workspace version + if: steps.settings.outputs.crates != '' + run: | + tag="${{ github.event.release.tag_name }}" + workspace_version=$( sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"$/\1/p' Cargo.toml ) + if [ "v${workspace_version}" != "${tag}" ] ; then + echo "::error::release ${tag} does not match the workspace version ${workspace_version} in Cargo.toml" + exit 1 + fi + - name: Authenticate with crates.io + if: steps.settings.outputs.crates != '' && env.DRY_RUN != 'true' + id: auth + uses: rust-lang/crates-io-auth-action@v1 + - name: Publish crates + # cargo publishes a library before the cli that depends on it. The crates already published + # are skipped and a failure is retried, rerunning the workflow publishes the rest, see + # build/scripts/publish-crates.sh + if: steps.settings.outputs.crates != '' + run: | + read -ra crates <<< "${CRATES}" + if [ "${DRY_RUN}" = "true" ] ; then + echo "::notice::a dry run, the repository variable DRY_RUN is true, the crates are not published" + fi + build/scripts/publish-crates.sh "${crates[@]}" + env: + CRATES: ${{ steps.settings.outputs.crates }} + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index e340e80..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,65 +0,0 @@ -name: Release to GitHub - -on: - push: - tags: - - 'v[0-9]+.[0-9]+.[0-9]+-?**' - -jobs: - build: - name: Build (${{ matrix.target }}) - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - include: - - target: aarch64-apple-darwin - os: macos-15 - - target: aarch64-unknown-linux-musl - os: ubuntu-24.04-arm - - target: x86_64-unknown-linux-musl - os: ubuntu-24.04 - steps: - - uses: actions/checkout@v6 - - name: Install musl toolchain - if: contains(matrix.target, 'musl') - run: sudo apt-get update && sudo apt-get install -y musl-tools - - name: Add target - run: rustup target add ${{ matrix.target }} - - name: Build - run: cargo build --release --workspace --target ${{ matrix.target }} - - name: Package binaries - run: | - mkdir -p dist - for bin in composable waspect composable-http-gateway; do - cp target/${{ matrix.target }}/release/$bin dist/${bin}-${{ matrix.target }} - done - - name: Upload binaries - uses: actions/upload-artifact@v7 - with: - name: binaries-${{ matrix.target }} - path: dist/* - retention-days: 7 - - release: - name: GitHub Release - if: startsWith(github.ref, 'refs/tags/') - needs: build - permissions: - contents: write - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - name: Download all binaries - uses: actions/download-artifact@v8 - with: - pattern: binaries-* - path: ./dist/ - merge-multiple: true - - name: Draft GitHub Release - uses: softprops/action-gh-release@v2 - with: - draft: true - files: dist/* - fail_on_unmatched_files: true - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/update-build.yaml b/.github/workflows/update-build.yaml new file mode 100644 index 0000000..627713e --- /dev/null +++ b/.github/workflows/update-build.yaml @@ -0,0 +1,108 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +name: Update build + +on: + schedule: + # weekly, Monday morning + - cron: "17 6 * * 1" + workflow_dispatch: + inputs: + version: + description: The release of componentized/build to update to, e.g. v0.2.0, or a branch, tag, commit or ref, e.g. main. Empty updates to the latest release, unless the build is of a newer commit. + required: false + type: string + +jobs: + # opens a pull request updating the build synced from componentized/build to its latest release, like + # dependabot. The pull request is left for the repository to merge when it's ready. + update: + # componentized/build is the source of the build, it has no synced copy to update + if: github.repository != 'componentized/build' + runs-on: ubuntu-latest + # the branch and pull request are created with a token for the custodian GitHub App rather than the + # GITHUB_TOKEN, which can't change workflow files and doesn't trigger the CI workflow + permissions: + contents: read + steps: + - name: Check custodian app credentials + run: | + if [ -z "${CLIENT_ID}" ] || [ -z "${PRIVATE_KEY}" ] ; then + echo "::error::the CUSTODIAN_CLIENT_ID and CUSTODIAN_PRIVATE_KEY secrets must be available to this repository, the private key of the custodian GitHub App is needed to create a token" + exit 1 + fi + env: + CLIENT_ID: ${{ secrets.CUSTODIAN_CLIENT_ID }} + PRIVATE_KEY: ${{ secrets.CUSTODIAN_PRIVATE_KEY }} + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Update build + # the script finds the version, the latest release unless the build is of a newer commit, and + # records it in build/VERSION, a commit for a branch or ref + id: release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ inputs.version }} + run: | + current=$( cat build/VERSION ) + build/scripts/update-build.sh "${VERSION}" + version=$( cat build/VERSION ) + echo "current=${current}" >> "${GITHUB_OUTPUT}" + echo "version=${version}" >> "${GITHUB_OUTPUT}" + if [ "${version}" = "${current}" ] ; then + echo "the build is already componentized/build ${current}" + fi + - name: Create custodian app token + if: steps.release.outputs.version != steps.release.outputs.current + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.CUSTODIAN_CLIENT_ID }} + private-key: ${{ secrets.CUSTODIAN_PRIVATE_KEY }} + # only this repository, with only the permissions the update needs + repositories: ${{ github.event.repository.name }} + permission-contents: write + # the build includes workflow files + permission-workflows: write + permission-pull-requests: write + - name: Open pull request + if: steps.release.outputs.version != steps.release.outputs.current + # the commit is created with the REST API, as the app's token can't push + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + CURRENT_VERSION: ${{ steps.release.outputs.current }} + VERSION: ${{ steps.release.outputs.version }} + # a scheduled run has no one to credit as a co-author + GITHUB_ACTOR: ${{ github.event_name == 'workflow_dispatch' && github.actor || '' }} + run: | + api="repos/${GITHUB_REPOSITORY}" + branch="update-build/${VERSION}" + # a pull request for the release was already opened, maybe closed, it isn't opened again + if gh api "${api}/git/ref/heads/${branch}" --silent 2> /dev/null ; then + echo "the branch ${branch} already exists" + exit 0 + fi + + base=$( git rev-parse HEAD ) + git add --all + commit=$( build/scripts/create-commit.sh "${base}" "Update build from ${CURRENT_VERSION} to ${VERSION}" ) + gh api --method POST "${api}/git/refs" -f ref="refs/heads/${branch}" -f sha="${commit}" --silent + echo "pushed ${commit} to ${branch}" + + { + if [[ "${VERSION}" =~ ^v[0-9] ]] ; then + notes="see the [release notes](https://github.com/componentized/build/releases/tag/${VERSION})" + else + notes="a commit rather than a release, see the [changes](https://github.com/componentized/build/compare/${CURRENT_VERSION}...${VERSION})" + fi + echo "Updates the build synced from [componentized/build](https://github.com/componentized/build) from ${CURRENT_VERSION} to ${VERSION}, ${notes}." + echo + echo '```' + git diff --cached --stat "${base}" + echo '```' + } > "${RUNNER_TEMP}/body.md" + gh pr create --repo "${GITHUB_REPOSITORY}" --base "${GITHUB_REF_NAME}" --head "${branch}" \ + --title "Update build to ${VERSION}" --body-file "${RUNNER_TEMP}/body.md" diff --git a/Cargo.lock b/Cargo.lock index f2e9430..da6afbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1148,6 +1148,15 @@ dependencies = [ "wit-parser 0.263.0", ] +[[package]] +name = "function-factory" +version = "0.5.1" +dependencies = [ + "composable-factory", + "function-adapter", + "wit-bindgen 0.63.0", +] + [[package]] name = "function-invoker" version = "0.1.0" @@ -2008,6 +2017,17 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "matchers" version = "0.2.0" @@ -2484,6 +2504,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -3942,7 +3972,7 @@ version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ - "wit-bindgen", + "wit-bindgen 0.57.1", ] [[package]] @@ -4046,6 +4076,16 @@ dependencies = [ "wasmparser 0.261.0", ] +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser 0.262.0", +] + [[package]] name = "wasm-encoder" version = "0.263.0" @@ -4106,6 +4146,18 @@ dependencies = [ "wasmparser 0.261.0", ] +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder 0.262.0", + "wasmparser 0.262.0", +] + [[package]] name = "wasm-metadata" version = "0.263.0" @@ -4241,6 +4293,18 @@ dependencies = [ "serde", ] +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", + "semver", +] + [[package]] name = "wasmparser" version = "0.263.0" @@ -4856,6 +4920,59 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser 0.262.0", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 3.0.10", + "wasm-metadata 0.262.0", + "wit-bindgen-core", + "wit-component 0.262.0", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn 3.0.10", + "wit-bindgen-core", + "wit-bindgen-rust", +] + [[package]] name = "wit-component" version = "0.253.0" @@ -4894,6 +5011,25 @@ dependencies = [ "wit-parser 0.261.0", ] +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder 0.262.0", + "wasm-metadata 0.262.0", + "wasmparser 0.262.0", + "wit-parser 0.262.0", +] + [[package]] name = "wit-component" version = "0.263.0" @@ -4952,6 +5088,25 @@ dependencies = [ "wasmparser 0.261.0", ] +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.262.0", +] + [[package]] name = "wit-parser" version = "0.263.0" diff --git a/Cargo.toml b/Cargo.toml index b730b3e..44e173c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ keywords = ["wasm"] [workspace] members = [ ".", + "components/function-factory", "crates/function-adapter", "crates/function-invoker", "crates/http-server", @@ -39,7 +40,13 @@ opentelemetry_sdk = "0.33" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } tempfile = "3" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "sync", "time"] } +tokio = { version = "1", features = [ + "macros", + "rt-multi-thread", + "signal", + "sync", + "time", +] } tracing = "0.1" uuid = { version = "1", features = ["v4"] } wasm-encoder = "0.263" @@ -47,6 +54,7 @@ wasmparser = "0.263" wasmtime = { version = "50", features = ["component-model-async"] } wat = "1.263" wit-parser = "0.263" +wit-bindgen = "0.63" [dependencies] anyhow.workspace = true @@ -61,7 +69,9 @@ http-body-util.workspace = true hyper = { workspace = true, features = ["client", "http1", "http2"] } oci-client = "0.17" petgraph = "0.8" -rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"] } +rustls = { version = "0.23", default-features = false, features = [ + "aws_lc_rs", +] } rustyline = "19" serde.workspace = true serde_json.workspace = true diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ac21c26 --- /dev/null +++ b/Makefile @@ -0,0 +1,222 @@ +# the cli, released with an archive for each platform, and published to crates.io +CLI_BIN := composable +PUBLISH_CRATES := composable-interceptor composable-runtime composable-http-gateway + +# the cli installed as a tool built from the workspace, like a cli the components are built with, e.g. +# the constants cli in componentized/constants, run as `$(COMPONENTIZED_BUILD)` +LOCAL_TOOLS := composable-runtime composable-http-server + +# exclude http-client from publishing in addition to the typical patterns +UNPUBLISHED_COMPONENTS := "dep-% %-dep internal-% %-internal test-% %-test http-client" + + +include build/build.mk + +test: check-components validate-components +test-integration: test-cli test-examples + + +# the cli installed with the tools, run in this repository as the CI workflow runs the cli unpacked +# from its archive, see scripts/smoke-test-cli.sh +.PHONY: test-cli ## Run the componentized-build cli installed with the tools +test-cli: $(call tool,composable-runtime) + scripts/smoke-test-cli.sh $(COMPOSABLE) + +.PHONY: test-examples +test-examples: + @true + +.PHONY: clean-examples +clean-all: clean-examples +clean-examples: + @true + +.PHONY: test-example-7cs +test-examples: test-example-7cs +test-example-7cs: examples/7cs/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/7cs && ./build.sh ) + ( cd examples/7cs && ./run.sh 1 ) + +.PHONY: clean-example-7cs +clean-examples: clean-example-7cs +clean-example-7cs: +# rm -rf examples/7cs/wit/deps + rm -rf examples/7cs/lib/*.wasm + ( cd examples/7cs/components && cargo clean ) + +.PHONY: test-example-filesystem +test-examples: test-example-filesystem +test-example-filesystem: examples/filesystem/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/filesystem && ./build.sh ) + ( cd examples/filesystem && ./run.sh ) + +.PHONY: clean-example-filesystem +clean-examples: clean-example-filesystem +clean-example-filesystem: +# rm -rf examples/filesystem/wit/deps + rm -rf examples/filesystem/lib/*.wasm + rm -f examples/filesystem/data/from-guest.txt + ( cd examples/filesystem/file-store && cargo clean ) + +.PHONY: test-example-function +test-examples: test-example-function +test-example-function: $(call tool,composable-runtime) + ( cd examples/function && ./run.sh ) + +.PHONY: clean-example-function +clean-examples: clean-example-function +clean-example-function: + @true + +.PHONY: test-example-function-adapter +test-examples: test-example-function-adapter +test-example-function-adapter: $(call tool,wkg) $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/function-adapter && ./build.sh ) + ( cd examples/function-adapter && ./run.sh ) + +.PHONY: clean-example-function-adapter +clean-examples: clean-example-function-adapter +clean-example-function-adapter: + rm -rf examples/function-adapter/lib/*.wasm + +.PHONY: test-example-hello-world +test-examples: test-example-hello-world +test-example-hello-world: examples/hello-world/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/hello-world && ./build.sh ) + ( cd examples/hello-world && ./run.sh ) + +.PHONY: clean-example-hello-world +clean-examples: clean-example-hello-world +clean-example-hello-world: +# rm -rf examples/hello-world/wit/deps + rm -rf examples/hello-world/lib/*.wasm + ( cd examples/hello-world/greeter && cargo clean ) + +.PHONY: test-example-host-capability +test-examples: test-example-host-capability +test-example-host-capability: $(call tool,wasm-tools) + ( cd examples/host-capability && ./build.sh ) + ( cd examples/host-capability && ./run.sh ) + +.PHONY: clean-example-host-capability +clean-examples: clean-example-host-capability +clean-example-host-capability: +# rm -rf examples/host-capability/wit/deps + rm -rf examples/host-capability/lib/*.wasm + ( cd examples/host-capability && cargo clean ) + +.PHONY: test-example-http-server +test-examples: test-example-http-server +test-example-http-server: $(call tool,wasm-tools) $(call tool,composable-http-server) + ( cd examples/http-server && exec ./run-server.sh ) & pid=$$!; \ + trap 'pkill -P $$pid 2>/dev/null; kill $$pid 2>/dev/null; wait $$pid 2>/dev/null' EXIT; \ + for i in $$(seq 1 300); do \ + curl -s -o /dev/null localhost:8888 && break; \ + kill -0 $$pid 2>/dev/null || { echo "http-server exited before listening"; exit 1; }; \ + sleep 1; \ + done; \ + curl -s -o /dev/null localhost:8888 || { echo "timed out waiting for port 8888"; exit 1; }; \ + ( cd examples/http-server && ./greet.sh ) + +.PHONY: clean-example-http-server +clean-examples: clean-example-http-server +clean-example-http-server: + @true + +.PHONY: test-example-interceptor +test-examples: test-example-interceptor +test-example-interceptor: examples/interceptor/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/interceptor && ./build.sh ) + ( cd examples/interceptor && ./run.sh ) + +.PHONY: clean-example-interceptor +clean-examples: clean-example-interceptor +clean-example-interceptor: +# rm -rf examples/interceptor/wit/deps + rm -rf examples/interceptor/lib/*.wasm + ( cd examples/interceptor && cargo clean ) + +.PHONY: test-example-local-registry +test-examples: test-example-local-registry +test-example-local-registry: test-example-hello-world $(call tool,wkg) $(call tool,composable-runtime) + ( cd examples/local-registry && ./start-registry.sh ) + ( cd examples/local-registry && ./push-component.sh ) + ( cd examples/local-registry && ./run.sh ) + ( cd examples/local-registry && ./list.sh ) + ( cd examples/local-registry && ./stop-registry.sh ) + +.PHONY: clean-example-local-registry +clean-examples: clean-example-local-registry +clean-example-local-registry: + @true + +.PHONY: test-example-messaging +test-examples: test-example-messaging +test-example-messaging: test-example-hello-world $(call tool,composable-runtime) + ( cd examples/messaging && ./publish.sh Alice) + ( cd examples/messaging && ./publish.sh Bob) + +.PHONY: clean-example-messaging +clean-examples: clean-example-messaging +clean-example-messaging: + @true + +.PHONY: test-example-named-imports +test-examples: test-example-named-imports +test-example-named-imports: examples/named-imports/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/named-imports && ./build.sh) + ( cd examples/named-imports && ./run.sh) + +.PHONY: clean-example-named-imports +clean-examples: clean-example-named-imports +clean-example-named-imports: +# rm -rf examples/named-imports/wit/deps + rm -rf examples/named-imports/lib/*.wasm + ( cd examples/named-imports && cargo clean ) + +.PHONY: test-example-otel-components +test-examples: test-example-otel-components +test-example-otel-components: examples/otel-components/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/otel-components && ./build.sh) + ( cd examples/otel-components && ./run.sh) + +.PHONY: clean-example-otel-components +clean-examples: clean-example-otel-components +clean-example-otel-components: +# rm -rf examples/otel-components/wit/deps + rm -rf examples/otel-components/lib/*.wasm + ( cd examples/otel-components && cargo clean ) + +.PHONY: test-example-otel-service +test-examples: test-example-otel-service +test-example-otel-service: examples/otel-service/wit/deps $(call tool,wasm-tools) $(call tool,composable-runtime) + ( cd examples/otel-service && ./build.sh) + ( cd examples/otel-service && exec ./run.sh ) & pid=$$!; \ + trap 'pkill -P $$pid 2>/dev/null; kill $$pid 2>/dev/null; wait $$pid 2>/dev/null' EXIT; \ + for i in $$(seq 1 300); do \ + curl -s -o /dev/null localhost:8080 && break; \ + kill -0 $$pid 2>/dev/null || { echo "http-server exited before listening"; exit 1; }; \ + sleep 1; \ + done; \ + curl -s -o /dev/null localhost:8080 || { echo "timed out waiting for port 8080"; exit 1; }; \ + ( cd examples/otel-service && ./curl.sh) + +.PHONY: clean-example-otel-service +clean-examples: clean-example-otel-service +clean-example-otel-service: +# rm -rf examples/otel-service/wit/deps + rm -rf examples/otel-service/lib/*.wasm + ( cd examples/otel-service && cargo clean ) + +.PHONY: test-example-service +test-examples: test-example-service +test-example-service: $(call tool,wasm-tools) + ( cd examples/service && ./build.sh) + ( cd examples/service && ./run.sh) + +.PHONY: clean-example-service +clean-examples: clean-example-service +clean-example-service: +# rm -rf examples/service/wit/deps + rm -rf examples/service/lib/*.wasm + ( cd examples/service && cargo clean ) diff --git a/build/MANIFEST b/build/MANIFEST new file mode 100644 index 0000000..43049c2 --- /dev/null +++ b/build/MANIFEST @@ -0,0 +1,32 @@ +ad9dc8fecef6a479a90071c4fd58a7cf0233916178ba2a825259b3b9dd2d9cf6 build/build.mk +37a8710560a5fecb78177a067926f31704f5143f4afd9e14ff4e8372448fd457 build/completions.jq +3fdcf30b00423929b04c48a8488703425cf3747faedd6c332d8be3cded39c7d9 build/components.mk +fdd3f5d358745a532ffe057d3fe12cd0d156f63e90357a648a08fc5471d62fa2 build/local.jq +a37069b0e8adaded10458514d45f3f126a8965dc8a7f669a7ca634e2c292866d build/pinned.jq +695b4f5a77b50f370476dc2e47a750b61b1e50ecd0ba0257d1708aa7da564a52 build/publish.mk +7f6ddce118913edc584a3702c8082f06aea84d178ddbe594e16b49f3688847e8 build/README.md +f1ff7c2deab40ecd38d2b1da9e6d6d2516be66a70bb06a01509ca9e3b4cec51b build/sbom.mk +f72dbfc64a35c63da39d8c4ca94c75e03df3680df348cced42d1dc026c63d398 build/scripts/bump-version.sh +83f89189b2eaa2020a5e2a00da7ae916510cac7cb2bee68f1c12406daa8e0d5f build/scripts/check-build.sh +9a0aa7a7d3fc086d0acae27dbdce2ffec29f2f15161fbb553f52b8d2ff1a9df5 build/scripts/completions.sh +4ab9c52b6725126a4947b00b0c3ca2628c63cd5af9c0b1908f5ce7176b040bc9 build/scripts/components.sh +ee2cd44e0f47852659a68be6cc5697c0828b38c46524fa786f835588aae55888 build/scripts/create-commit.sh +31b4d924ddc9e03884d6504fcd066e5a5c18e115f5794143f32f8ed78f9e1e42 build/scripts/install-cargo-binstall.sh +4a047ae47306f967e54b91179397eca119e9be294d7c48bb19aa5e3f814f7cef build/scripts/pack-components.sh +c729ec895a165a7c6e56989497a3fb67b770aac625fb8724bbee962c52cb7351 build/scripts/publish-crates.sh +2398a5f4166e82666449825d244498a1064d1c91d294b9a232a9decdbf261a93 build/scripts/publish.sh +644f78ba37ce99299aa32f79151401897406c7f48c023f02241f51ac2167b33f build/scripts/sbom-cargo.sh +536d626db118272a339e224fa19132a6a99c0e98a27db03f5e11061a8d48f5ef build/scripts/sbom.sh +e48f153de8c5f12c24805d2a6e8e7343464dd3dbb360bdb45aa969711f515541 build/scripts/update-build.sh +00acf974b3d59fa292a7403c5e900ffe41a863a77a4768b1b6d01cbf1bf31d01 build/scripts/wac-deps.sh +b7dfcb359d653b3eef96adaaa2e13d5ad31d383d3d978cb4210840a1406f408c build/scripts/wit-canonical.sh +82ede1aa854d701ce7d9d78cd9013f3a7b765dff360da96c3059dfbcb265f1ee build/scripts/wit-paths.sh +506b787c00e211c913880d63c65c65599c816309e7f5217785a029d1a0705dd2 build/sync.mk +5979975d3be7da9cdf086f432be007cfe72ee53f6e8397d6e8e9af703fd0ffe9 build/tools/Cargo.toml +c89b1b7ec870821e1579b1bbc99ac0a4a4d954b401f368fd47b0e7507d995005 build/tools/lib.rs +f81068c29f05c4f6c85000aba4f19c8df70096d0dc46155e2865eadf227220f7 build/tools.mk +71590685d965268bbef5e61e246abe30e48d4ff79766c953bc2a09ea37dc18bd build/wit.mk +799dfdc2258646ced230b6d57b4cd5636e1ac5dc4e6397c79d759f5fb2b01286 .github/workflows/bump-version.yaml +7a434c29ead0924d3b6d52deed8e7959fbd9a6a6c6f2cd763e9ec882691308f1 .github/workflows/ci.yaml +5d92b9b54b1cddf57c51d1e7f7e6f3ea16f046e389ae070ac866e9aa7136f9e4 .github/workflows/release.yaml +05e6c18b75cf2ebf64f153367ab7060b9deab9ed1bb51abb4b153f86d7c89d28 .github/workflows/update-build.yaml diff --git a/build/README.md b/build/README.md new file mode 100644 index 0000000..94e1bd4 --- /dev/null +++ b/build/README.md @@ -0,0 +1,13 @@ + + +# Build + +The build shared by the componentized repositories, synced from [componentized/build](https://github.com/componentized/build) at the version in [`VERSION`](VERSION). + +Nothing in this directory, nor the workflows synced with it, is edited here: `make check-build`, run by the CI workflow, fails when a synced file differs from [`MANIFEST`](MANIFEST). Changes go to componentized/build, and come back with its next release: + +- `make update-build` updates to the latest release, `make update-build BUILD_VERSION=v0.2.0` to a given one, or `BUILD_VERSION=main` to a commit not yet released. A build synced from a commit is kept until a newer release. +- The `Update build` workflow opens a pull request each week when there is a newer release. + +The repository's own `Makefile` sets the settings of the build, includes [`build.mk`](build.mk), then adds its own targets. See the [componentized/build README](https://github.com/componentized/build#readme) for the settings and the targets a repository can extend. diff --git a/build/VERSION b/build/VERSION new file mode 100644 index 0000000..0693e75 --- /dev/null +++ b/build/VERSION @@ -0,0 +1 @@ +a0ff26840c21061fec78fd3cc3fc336243c5e9d6 diff --git a/build/build.mk b/build/build.mk new file mode 100644 index 0000000..31da7bd --- /dev/null +++ b/build/build.mk @@ -0,0 +1,119 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# The build shared by the componentized repositories, synced from https://github.com/componentized/build +# at the version in build/VERSION. Nothing in build/ is edited here, see build/README.md. +# +# The repository's Makefile sets its settings, includes this file, then adds its own targets and +# prerequisites, e.g. +# +# COMPONENT_TARGET := wasm32-wasip3 +# include build/build.mk +# test-integration: test-valkey + +SHELL := /bin/bash + +export RUST_BACKTRACE ?= 1 +export WASMTIME_BACKTRACE_DETAILS ?= 1 +# the repository's wkg config, e.g. the registry of each namespace, optional: without one wkg uses its +# own, the user's config or its defaults. wkg fails when WKG_CONFIG_FILE names a missing file. +ifneq ($(wildcard .config/wasm-pkg/config.toml),) +export WKG_CONFIG_FILE ?= $(abspath .config/wasm-pkg/config.toml) +endif + +# `make` without a goal runs all, otherwise the first target of an included file would run +.DEFAULT_GOAL := all + +# the rust target components are built for, `wasm32-wasip3` builds components that run std threads on +# component model cooperative threads, see build/components.mk, `wasm32-wasip2` builds components +# rust links itself, e.g. a command. A component built with cargo may name +# its own in its Cargo.toml, `COMPONENT_TARGET` given on the command line overrides it, e.g. +# +# [package.metadata.componentized] +# target = "wasm32-wasip3" +COMPONENT_TARGET ?= wasm32-unknown-unknown + +# the components and their directories, each `=`, e.g. `example-hello=examples/hello`, found +# in components/ and each directory with a components.toml naming the prefix of its components, see +# build/scripts/components.sh. Read once while parsing, defines COMPONENTS, and for each component +# COMPONENT_DIR_, its directory, and COMPONENT_BASE_, the name of its directory +# its files are named for, e.g. hello for examples/hello/hello.wac +COMPONENT_DIRS := $(shell build/scripts/components.sh | tr ' ' '=') +COMPONENTS := $(sort $(foreach entry,$(COMPONENT_DIRS),$(firstword $(subst =, ,$(entry))))) +$(foreach name,$(COMPONENTS),$(if $(word 2,$(filter $(name)=%,$(COMPONENT_DIRS))),$(error the component $(name) is in more than one directory, $(patsubst $(name)=%,%,$(filter $(name)=%,$(COMPONENT_DIRS))), rename one or give its directory of components a prefix, see build/scripts/components.sh))) +$(foreach entry,$(COMPONENT_DIRS),$(eval COMPONENT_DIR_$(firstword $(subst =, ,$(entry))) := $(lastword $(subst =, ,$(entry))))) +$(foreach name,$(COMPONENTS),$(eval COMPONENT_BASE_$(name) := $(notdir $(COMPONENT_DIR_$(name))))) + +# the components built with cargo, those with a Cargo.toml, and their packages, CARGO_PACKAGE_, +# named in their Cargo.toml, e.g. examples/hello's may be example-hello, or hello +CARGO_COMPONENTS := $(foreach name,$(COMPONENTS),$(if $(wildcard $(COMPONENT_DIR_$(name))/Cargo.toml),$(name))) +$(foreach name,$(CARGO_COMPONENTS),$(eval CARGO_PACKAGE_$(name) := $(shell sed -n '/^\[package\]/,/^\[/s/^name *= *"\(.*\)"/\1/p' $(COMPONENT_DIR_$(name))/Cargo.toml))) + +# read once while parsing, defines COMPONENT_TARGET_ for those that name one +$(foreach name,$(CARGO_COMPONENTS),$(eval COMPONENT_TARGET_$(name) := $(shell sed -n '/^\[package\.metadata\.componentized\]/,/^\[/s/^target *= *"\(.*\)"/\1/p' $(COMPONENT_DIR_$(name))/Cargo.toml))) + +# the rust target a component is built for, e.g. `$(call component_target,trace)` +component_target = $(if $(filter command line,$(origin COMPONENT_TARGET)),$(COMPONENT_TARGET),$(or $(COMPONENT_TARGET_$(1)),$(COMPONENT_TARGET))) + +# the targets the components built with cargo are built for +COMPONENT_TARGETS = $(sort $(foreach name,$(CARGO_COMPONENTS),$(call component_target,$(name)))) + +# the cli built from this repository, e.g. `constants`, released with an archive for each platform by +# the CI workflow. Empty for a repository without a cli. +CLI_BIN ?= +# the crates published to crates.io when a release is published, e.g. `componentized-constants +# componentized-constants-cli`, checked by the CI workflow. Empty for a repository without crates. +PUBLISH_CRATES ?= + +# tools first, the others use the variables it defines for each tool when their rules are read +include build/tools.mk +include build/wit.mk +include build/components.mk +include build/sbom.mk +include build/publish.mk +include build/sync.mk + + +.PHONY: all ## Install the tools, generate, build the components and test them, `make` without a target +all: tools generate components test + +# the help of a target follows `## ` on its .PHONY line, e.g. `.PHONY: tools ## Install the tools`, or +# on the line of its rule, e.g. `run: cli.wasm ## Run the cli`. A variable's line, with an `=`, is not +# a target. +.PHONY: help ## Display this help screen +help: + @awk '/^[^#[:space:]][^=]*:[^=]*## / { \ + names = substr($$0, 1, index($$0, "## ") - 1); \ + if (sub(/^\.PHONY:/, "", names) == 0) sub(/:.*$$/, "", names); \ + text = substr($$0, index($$0, "## ") + 3); \ + count = split(names, list, /[[:space:]]+/); \ + for (i = 1; i <= count; i++) if (list[i] != "" && !(list[i] in seen)) { seen[list[i]] = 1; printf "\033[36m%-20s\033[0m %s\n", list[i], text } \ + }' $(MAKEFILE_LIST) | sort + +# the repository adds what else it generates and commits as prerequisites, e.g. `generate: config` +.PHONY: generate ## Generate the files committed with the sources, the CI workflow fails when they drift +generate: wit + @: + +.PHONY: clean ## Remove the built components and the fetched wit dependencies +clean: clean-components clean-wit + @: + +.PHONY: clean-all ## Remove everything built, the installed tools and cargo's target directory too +clean-all: clean-components clean-tools clean-wit + cargo clean + +.PHONY: test ## Build the components and run the tests of the workspace +test: components + cargo test --workspace + +# the repository adds the tests that need more than cargo as prerequisites, e.g. a server in a +# container, `test-integration: test-valkey` +.PHONY: test-integration ## Run the tests that need more than cargo, run by the CI workflow after `make test` +test-integration: + @: + +# prints the value of a variable, e.g. `make -s print-CLI_BIN`, for the workflows +print-%: + $(info $($*)) + @: diff --git a/build/completions.jq b/build/completions.jq new file mode 100644 index 0000000..dae82d2 --- /dev/null +++ b/build/completions.jq @@ -0,0 +1,18 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# generates target/tools/completions from `cargo metadata --no-deps` of build/tools/Cargo.toml, +# followed by that of the repository's tools/Cargo.toml when it has one, slurped, see build/tools.mk. +# Each line is a binary and the arguments that print its completions, quoted for the shell, e.g. +# `'wasm-tools' 'completion'`, read by build/scripts/completions.sh. A binary the repository lists +# overrides the build's, one listed with no arguments has none. +def completions($manifest): + (.packages[0].metadata.completions // {}) + | to_entries[] + | if (.value | type) == "array" and all(.value[]; type == "string") then . + else error("\(.key) in [package.metadata.completions] in \($manifest) is not a list of arguments") end; +([.[0] | completions("build/tools/Cargo.toml")] + [.[1] // empty | completions("tools/Cargo.toml")]) +| reduce .[] as $binary ({}; .[$binary.key] = $binary.value) +| to_entries | sort_by(.key)[] +| select(.value != []) +| [.key] + .value | @sh diff --git a/build/components.mk b/build/components.mk new file mode 100644 index 0000000..cc14c18 --- /dev/null +++ b/build/components.mk @@ -0,0 +1,234 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +COMPONENTS_DIR := target/components + +# the WIT packages of components/wit/deps, when it has any, encoded where `wac compose` looks for a package a +# composition names without instantiating it, e.g. `import stderr: wasi:cli/stderr@0.3.0;` +WAC_DEPS_DIR := target/wac-deps + +# COMPONENTS, the components, and CARGO_COMPONENTS, those built with cargo, are found by +# build/build.mk, with the directory of each, COMPONENT_DIR_ + +# the WIT paths of the wit_bindgen::generate! of each component with a Cargo.toml, in its sources and +# in those of the workspace crates it depends on, e.g. a crate of shared bindings, see +# build/scripts/wit-paths.sh. Defines WIT_BINDGEN_PATHS_, for the component's package, +# CARGO_PACKAGE_. Generated when a Rust source or the workspace changes, make restarts +# after generating it. +WIT_PATHS_MK := target/wit-paths.mk +ifneq ($(CARGO_COMPONENTS),) +# quietly, the first time make generates it before reading it +-include $(WIT_PATHS_MK) +endif + +$(WIT_PATHS_MK): Cargo.toml Cargo.lock $(foreach name,$(CARGO_COMPONENTS),$(COMPONENT_DIR_$(name))/Cargo.toml) build/scripts/wit-paths.sh $(shell find . -name '*.rs' -not -path '*/target/*' -not -path '*/wit/deps/*') + @mkdir -p $(@D) + @build/scripts/wit-paths.sh $(foreach name,$(CARGO_COMPONENTS),$(CARGO_PACKAGE_$(name))) > $@.tmp + @mv $@.tmp $@ + +# the cargo profiles components are built with, `component` and `component-debug` when Cargo.toml +# defines them, e.g. to build smaller components than the release profile a cli is built with +COMPONENT_PROFILE ?= $(if $(shell grep -s '^\[profile\.component\]' Cargo.toml),component,release) +COMPONENT_DEBUG_PROFILE ?= $(if $(shell grep -s '^\[profile\.component-debug\]' Cargo.toml),component-debug,dev) + +# the core module cargo built for a component with a profile, e.g. `$(call cargo_wasm,gate,dev)` for +# target/wasm32-unknown-unknown/debug/gate.wasm, `$(call cargo_wasm,gate,release,.opt)` for the +# module wasm-opt optimized. For wasm32-wasip2 cargo builds a component rather than a core module. +cargo_wasm = target/$(call component_target,$(1))/$(if $(filter dev,$(2)),debug,$(2))/$(call cargo_artifact,$(1))$(3).wasm + +# the name of the wasm file cargo builds for a component's package, a library's has `_` for each `-`, a +# binary keeps the package's name, e.g. a command for wasm32-wasip2 with a src/main.rs and no src/lib.rs +cargo_artifact = $(if $(and $(wildcard $(COMPONENT_DIR_$(1))/src/main.rs),$(if $(wildcard $(COMPONENT_DIR_$(1))/src/lib.rs),,bin)),$(CARGO_PACKAGE_$(1)),$(subst -,_,$(CARGO_PACKAGE_$(1)))) + +# the files the components cargo builds need besides the sources, e.g. a component the library +# embeds, `CARGO_COMPONENT_DEPS := crates/componentized-static-config/constants-config.wasm` +CARGO_COMPONENT_DEPS ?= + +ifneq ($(filter wasm32-wasip3,$(COMPONENT_TARGETS)),) +# wasm32-wasip3 runs std threads on component model cooperative threads, which needs a wasi-libc built +# for them from wasi-sdk 34+'s experimental sysroot, installed with the tools or from WASI_SDK_PATH, or +# built from WASI_LIBC_VERSION, see build/tools.mk, and a rust toolchain with cooperative thread +# support, 1.100+. `make components COMPONENT_TARGET=wasm32-unknown-unknown` builds without. +WASI_SYSROOT_LIB := $(WASI_SYSROOT)/lib/wasm32-wasip3 +# linked with wasm-component-ld, like the target's default, against the coop threads wasi-libc in +# place of the libc vendored with std. Linked by clang, a cdylib is a shared library, not a component. +# It links a core module, like wasm32-unknown-unknown, wasm-opt removes the code the release build +# doesn't reach, and with it the imports only that code uses, before it's made a component. +export CARGO_TARGET_WASM32_WASIP3_LINKER := $(WASI_SDK_PATH)/bin/wasm-component-ld +export CARGO_TARGET_WASM32_WASIP3_RUSTFLAGS := -Clink-self-contained=n -Clink-arg=-L$(WASI_SYSROOT_LIB) -Clink-arg=$(WASI_SYSROOT_LIB)/crt1-reactor.o -Clink-arg=--export=cabi_realloc -Clink-arg=--skip-wit-component +endif + +# turn the core module cargo built for a component into a component, e.g. `$(call +# componentize,gate,,)`. For wasm32-wasip2 rust links a component itself, with +# wasm-component-ld, which is copied. +componentize = $(if $(filter wasm32-wasip2,$(call component_target,$(1))),cp $(2) $(3),$(WASM_TOOLS) component new $(2) -o $(3)) + +# the release build of a component is optimized again for size with wasm-opt when set, e.g. +# `COMPONENT_OPTIMIZE := true`, the build provides wasm-opt to every repository. wasm-opt optimizes +# core modules, a component built for wasm32-wasip2 is not optimized again. +COMPONENT_OPTIMIZE ?= + +# whether the release build of a component is optimized again, e.g. `$(call component_optimize,gate)` +component_optimize = $(if $(COMPONENT_OPTIMIZE),$(filter-out wasm32-wasip2,$(call component_target,$(1)))) + +# the wasm features rust enables for wasm32-unknown-unknown and wasm32-wasip3, `rustc --print cfg +# --target wasm32-unknown-unknown`. The stripped modules don't say which features they use, wasm-opt +# is limited to these so it doesn't introduce instructions rust wouldn't emit. +WASM_OPT_FEATURES ?= --enable-bulk-memory --enable-multivalue --enable-mutable-globals --enable-nontrapping-float-to-int --enable-reference-types --enable-sign-ext + +.PHONY: clean-components ## Remove the built components +clean-components: clean-wit + rm -rf ${COMPONENTS_DIR} ${WAC_DEPS_DIR} + +.PHONY: components ## Build the interface and each component into target/components, `make components/` builds one, `make ` those in a directory, e.g. `make examples` +components: ${COMPONENTS_DIR}/interface.wasm $(foreach component,$(COMPONENTS),${COMPONENTS_DIR}/$(component)/$(component).wasm ${COMPONENTS_DIR}/$(component)/$(component).debug.wasm) + +# the components whose release and debug builds may have different WIT, not checked by `make +# check-components`, e.g. a wasm32-wasip3 component whose release build wasm-opt optimizes, see +# COMPONENT_OPTIMIZE, dropping imports of the standard library the debug build keeps: +# `CHECK_COMPONENTS_SKIP := gate`. `make check-components/` still checks one. +CHECK_COMPONENTS_SKIP ?= + +.PHONY: check-components ## Check the release and debug build of each component have the same WIT, `make check-components/` checks one +check-components: $(foreach component,$(filter-out $(CHECK_COMPONENTS_SKIP),$(COMPONENTS)),check-components/$(component)) + +.PHONY: validate-components ## Validate the release and debug build of each component, `make validate-components/` checks one +validate-components: $(foreach component,$(COMPONENTS),validate-components/$(component)) + +define BUILD_COMPONENT + +.PHONY: components/$1 +components/$1: ${COMPONENTS_DIR}/$1/$1.wasm ${COMPONENTS_DIR}/$1/$1.debug.wasm + +# the same imports and exports, e.g. a debug build that isn't optimized may keep imports the release +# build doesn't use, the order of the WIT may differ, see build/scripts/wit-canonical.sh +.PHONY: check-components/$1 +check-components/$1: ${COMPONENTS_DIR}/$1/$1.wasm ${COMPONENTS_DIR}/$1/$1.debug.wasm build/scripts/wit-canonical.sh | $(call tool,wasm-tools) + @diff -u --label $1.wasm --label $1.debug.wasm \ + <(WASM_TOOLS=$(WASM_TOOLS) build/scripts/wit-canonical.sh ${COMPONENTS_DIR}/$1/$1.wasm) \ + <(WASM_TOOLS=$(WASM_TOOLS) build/scripts/wit-canonical.sh ${COMPONENTS_DIR}/$1/$1.debug.wasm) \ + || { echo "the WIT of the release and debug build of $1 differ" >&2; exit 1; } + +.PHONY: validate-components/$1 +validate-components/$1: ${COMPONENTS_DIR}/$1/$1.wasm | $(call tool,wasm-tools) + @$(WASM_TOOLS) validate --features all ${COMPONENTS_DIR}/$1/$1.wasm || { echo "$1.wasm is not a valid component"; exit 1; } + @$(WASM_TOOLS) validate --features all ${COMPONENTS_DIR}/$1/$1.debug.wasm || { echo "$1.debug.wasm is not a valid component"; exit 1; } + +ifneq ($(wildcard $(COMPONENT_DIR_$1)/wit/$(COMPONENT_BASE_$1).constants.wit),) + +${COMPONENTS_DIR}/$1/$1.wasm: $(call wit_prerequisites,$(COMPONENT_DIR_$1)/wit) ${COMPONENTS_DIR}/$1/README.md $(call tool_prerequisite,componentized-constants-cli) + $(CONSTANTS) --wit $(COMPONENT_DIR_$1)/wit -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(call wit_prerequisites,$(COMPONENT_DIR_$1)/wit) ${COMPONENTS_DIR}/$1/README.md $(call tool_prerequisite,componentized-constants-cli) + $(CONSTANTS) --wit $(COMPONENT_DIR_$1)/wit -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties),) + +${COMPONENTS_DIR}/$1/$1.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties ${COMPONENTS_DIR}/$1/README.md $(call tool_prerequisite,componentized-static-config-cli) + $(STATIC_CONFIG) -f $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties ${COMPONENTS_DIR}/$1/README.md $(call tool_prerequisite,componentized-static-config-cli) + $(STATIC_CONFIG) -f $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac),) + +# the local packages the composition instantiates, e.g. `new local:latch-n2 { ... }` +WAC_DEPS_$1 := $$(shell grep -v '^\s*//' $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac | grep -oE 'local:[a-z0-9-]+' | sed 's/^local://' | sort -u) + +${COMPONENTS_DIR}/$1/$1.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).wasm) ${COMPONENTS_DIR}/$1/README.md ${WAC_DEPS_DIR} | $(call tool,wac-cli) + $(WAC) compose --deps-dir ${WAC_DEPS_DIR} $$(foreach component,$$(WAC_DEPS_$1),-d local:$$(component)=$${COMPONENTS_DIR}/$$(component)/$$(component).wasm) -o ${COMPONENTS_DIR}/$1/$1.wasm $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) ${COMPONENTS_DIR}/$1/README.md ${WAC_DEPS_DIR} | $(call tool,wac-cli) + $(WAC) compose --deps-dir ${WAC_DEPS_DIR} $$(foreach component,$$(WAC_DEPS_$1),-d local:$$(component)=$${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) -o ${COMPONENTS_DIR}/$1/$1.debug.wasm $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).plug),) + +# the components plugged together with `wac plug`, each a component of the repository named on a line +# of its own, the socket first, then each plug, `#` starts a comment, e.g. +# +# greeter +# defaults +# +# Where the socket and a plug import different versions of the same interface, e.g. wasi:io@0.2.6 and +# wasi:io@0.2.12, the plugged component imports the newer one, a composition the one it imports first. +PLUG_COMPONENTS_$1 := $$(shell sed 's/\#.*//' $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).plug) +PLUG_SOCKET_$1 := $$(firstword $$(PLUG_COMPONENTS_$1)) +PLUG_PLUGS_$1 := $$(wordlist 2,$$(words $$(PLUG_COMPONENTS_$1)),$$(PLUG_COMPONENTS_$1)) + +${COMPONENTS_DIR}/$1/$1.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).plug $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).wasm) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wac-cli) + $(WAC) plug $${COMPONENTS_DIR}/$$(PLUG_SOCKET_$1)/$$(PLUG_SOCKET_$1).wasm $$(foreach component,$$(PLUG_PLUGS_$1),--plug $${COMPONENTS_DIR}/$$(component)/$$(component).wasm) -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).plug $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wac-cli) + $(WAC) plug $${COMPONENTS_DIR}/$$(PLUG_SOCKET_$1)/$$(PLUG_SOCKET_$1).debug.wasm $$(foreach component,$$(PLUG_PLUGS_$1),--plug $${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg),) + +${COMPONENTS_DIR}/$1/$1.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg ${COMPONENTS_DIR}/$1/README.md | $(call tool,wkg) + $(WKG) oci pull $(shell cat $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg 2> /dev/null | head -1) -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg ${COMPONENTS_DIR}/$1/README.md | $(call tool,wkg) + $(WKG) oci pull $(shell cat $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg 2> /dev/null | tail -1 2> /dev/null) -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +# cargo is checked last, other strategies may have a Cargo.toml for tests of non-rust sources +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/Cargo.toml),) + +# the WIT the bindings are generated from, the path of each wit_bindgen::generate! of the component +# and the workspace crates it depends on, e.g. `path: "../wit"` for components/wit, or else the wit +# beside the component's directory, e.g. components/wit for components/gate, e.g. bindings generated +# other than with wit-bindgen's macro +WIT_PATHS_$1 := $$(foreach path,$$(or $$(WIT_BINDGEN_PATHS_$(CARGO_PACKAGE_$1)),$$(wildcard $(patsubst %/,%,$(dir $(COMPONENT_DIR_$1)))/wit)),$$(call relpath,$$(path))) + +${COMPONENTS_DIR}/$1/$1.wasm: $(CARGO_COMPONENT_DEPS) Cargo.toml Cargo.lock $$(call wit_prerequisites,$$(WIT_PATHS_$1)) $(shell find $(COMPONENT_DIR_$1) -type f) $(shell find crates -type f 2> /dev/null) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wasm-tools) $(if $(call component_optimize,$1),$(call tool,wasm-opt)) $(if $(filter wasm32-wasip3,$(call component_target,$1)),$(WASI_SDK) $(WASI_LIBC)) + cargo build -p $(CARGO_PACKAGE_$1) --target $(call component_target,$1) --profile $(COMPONENT_PROFILE) +ifneq ($(call component_optimize,$1),) + $(WASM_OPT) -Oz $(WASM_OPT_FEATURES) $(call cargo_wasm,$1,$(COMPONENT_PROFILE)) -o $(call cargo_wasm,$1,$(COMPONENT_PROFILE),.opt) + $(call componentize,$1,$(call cargo_wasm,$1,$(COMPONENT_PROFILE),.opt),${COMPONENTS_DIR}/$1/$1.wasm) +else + $(call componentize,$1,$(call cargo_wasm,$1,$(COMPONENT_PROFILE)),${COMPONENTS_DIR}/$1/$1.wasm) +endif + +${COMPONENTS_DIR}/$1/$1.debug.wasm: $(CARGO_COMPONENT_DEPS) Cargo.toml Cargo.lock $$(call wit_prerequisites,$$(WIT_PATHS_$1)) $(shell find $(COMPONENT_DIR_$1) -type f) $(shell find crates -type f 2> /dev/null) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wasm-tools) $(if $(filter wasm32-wasip3,$(call component_target,$1)),$(WASI_SDK) $(WASI_LIBC)) + cargo build -p $(CARGO_PACKAGE_$1) --target $(call component_target,$1) --profile $(COMPONENT_DEBUG_PROFILE) + $(call componentize,$1,$(call cargo_wasm,$1,$(COMPONENT_DEBUG_PROFILE)),${COMPONENTS_DIR}/$1/$1.debug.wasm) + +endif + +${COMPONENTS_DIR}/$1/README.md: $(COMPONENT_DIR_$1)/README.md + @mkdir -p ${COMPONENTS_DIR}/$1 + @cp $(COMPONENT_DIR_$1)/README.md ${COMPONENTS_DIR}/$1/README.md + +endef + +$(foreach component,$(COMPONENTS),$(eval $(call BUILD_COMPONENT,$(component)))) + +# a target for each directory holding components, a component's directory and each directory it's in, +# building the components in it and under it, with their SBOMs, e.g. `make examples`, `make +# components/gate` for gate and its group, gate-internal and gate-config, or `make components/deps` +# for those of components/deps/componentized/components.toml. `make components` builds every +# component, those of components/ and of every other directory of components. +COMPONENT_DIR_TARGETS = $(sort $(foreach component,$(COMPONENTS),$(call dir_ancestors,$(COMPONENT_DIR_$(component))))) + +# a directory and each directory it's in, but the repository's, e.g. components/gate/internal, +# components/gate and components for components/gate/internal +dir_ancestors = $(if $(filter-out .,$(1)),$(1) $(call dir_ancestors,$(patsubst %/,%,$(dir $(1))))) + +# the components in a directory or under it, e.g. `$(call components_in,components/gate)` +components_in = $(foreach component,$(COMPONENTS),$(if $(filter $(1) $(1)/%,$(COMPONENT_DIR_$(component))),$(component))) + +define COMPONENT_DIR_TARGET +.PHONY: $1 +$1: $(foreach component,$(call components_in,$1),$(foreach build,$(component) $(component).debug,${COMPONENTS_DIR}/$(component)/$(build).wasm ${COMPONENTS_DIR}/$(component)/$(build).cdx.json)) + +.PHONY: $1/ +$1/: $1 +endef + +$(foreach dir,$(COMPONENT_DIR_TARGETS),$(eval $(call COMPONENT_DIR_TARGET,$(dir)))) + +${WAC_DEPS_DIR}: $(call wit_prerequisites,components/wit) build/scripts/wac-deps.sh | $(call tool,wasm-tools) + WASM_TOOLS=$(WASM_TOOLS) build/scripts/wac-deps.sh components/wit/deps ${WAC_DEPS_DIR} + +${COMPONENTS_DIR}/interface.wasm: wit/deps README.md | $(call tool,wkg) + @mkdir -p ${COMPONENTS_DIR} + $(call wkg,.,build -o $(abspath ${COMPONENTS_DIR})/interface.wasm) + @cp README.md ${COMPONENTS_DIR}/README.md diff --git a/build/local.jq b/build/local.jq new file mode 100644 index 0000000..c2ac0f8 --- /dev/null +++ b/build/local.jq @@ -0,0 +1,24 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# generates target/tools/local.mk from `cargo metadata --no-deps` of the workspace, for the packages +# named in $tools, LOCAL_TOOLS, see build/tools.mk +.workspace_root as $root +| (.packages | map({key: .name, value: .}) | from_entries) as $packages +| def relative: if . == $root then "." else ltrimstr($root + "/") end; + def dir: sub("/[^/]*$"; ""); + # the workspace packages a package depends on by path, but for tests, cargo forbids cycles + def path_deps: .dependencies[] | select(.path != null and .kind != "dev") | $packages[.name] | select(. != null); + # the manifest and the sources of a package's targets, but its tests, benches and examples. A + # target in the package's own directory, e.g. build.rs, is a file, others are their directory, + # e.g. src, a root package's directory holds the whole repository. + def sources: + (.manifest_path | dir) as $dir + | (.manifest_path | relative), + (.targets[] | select(any(.kind[]; IN("lib", "rlib", "cdylib", "staticlib", "dylib", "bin", "proc-macro", "custom-build"))) + | .src_path | if dir == $dir then relative else dir | relative end); + ($tools | split(" ") | map(select(. != "")))[] as $name + | ($packages[$name] // error("\($name) in LOCAL_TOOLS is not a package of the workspace")) as $package + | "LOCAL_TOOL_PATH_\($name) := \($package.manifest_path | dir | relative)", + "LOCAL_TOOL_SOURCES_\($name) := \([$package | recurse(path_deps) | sources] | unique | join(" "))", + ($package.targets[] | select(.kind | index("bin")) | .name | "\(ascii_upcase | gsub("-"; "_")) := $(TOOLS_BIN)/\(.)") diff --git a/build/pinned.jq b/build/pinned.jq new file mode 100644 index 0000000..5bb756a --- /dev/null +++ b/build/pinned.jq @@ -0,0 +1,17 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# generates target/tools/pinned.mk from `cargo metadata --no-deps` of build/tools/Cargo.toml, the +# tools the build provides, followed by that of the repository's tools/Cargo.toml when it has one, +# slurped, see build/tools.mk. A tool pinned by the repository overrides the build's. +def pinned($manifest): + .packages[0] as $tools + | $tools.dependencies[] + | {name, version: (.req | ltrimstr("=")), + bins: ($tools.metadata.bins[.name] // error("\(.name) is missing from [package.metadata.bins] in \($manifest)"))}; +([.[0] | pinned("build/tools/Cargo.toml")] + [.[1] // empty | pinned("tools/Cargo.toml")]) +| reduce .[] as $tool ({}; .[$tool.name] = $tool) +| [.[]] | sort_by(.name) +| "TOOLS := \(map(.name) | join(" "))", + "TOOLS_PINNED := \(map("\(.name)@\(.version)") | join(" "))", + (.[].bins[] | "\(ascii_upcase | gsub("-"; "_")) := $(TOOLS_BIN)/\(.)") diff --git a/build/publish.mk b/build/publish.mk new file mode 100644 index 0000000..13cd9fb --- /dev/null +++ b/build/publish.mk @@ -0,0 +1,28 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# sign published components with cosign, `SIGN=false` to push without signing, e.g. to a local registry +SIGN ?= true +# show what would be published without pushing or signing anything, `DRY_RUN=true` +DRY_RUN ?= false +# append each published file, its size in bytes and its image to this file, e.g. `gate.wasm 1234567 ghcr.io/componentized/http/gate:0.1.0@sha256:...` +PUBLISH_LOG ?= + +# publish the interface, interface.wasm, `false` for a repository whose interface isn't one to depend +# on, e.g. componentized/build, whose interface is there to test the build +PUBLISH_INTERFACE ?= true + +# the files that can be published, e.g. gate.wasm, published from target/components/gate/gate.wasm. +# Components are not published when they are pulled from elsewhere, `dep`, built here for use by +# other components, `internal`, or tests, `test`, named with it as a prefix or a suffix, e.g. +# `test-greeter` or `greeter-test`. +UNPUBLISHED_COMPONENTS ?= $(foreach kind,dep internal test,$(kind)-% %-$(kind)) +PUBLISH_FILES := $(if $(filter true,$(PUBLISH_INTERFACE)),interface.wasm) $(foreach component,$(filter-out $(UNPUBLISHED_COMPONENTS),$(COMPONENTS)),$(component).wasm $(component).debug.wasm) + +.PHONY: publish ## Publish each component in the target/components directory, `make publish-` publishes one, e.g. publish-gate.wasm +publish: $(addprefix publish-,$(PUBLISH_FILES)) + +.PHONY: $(addprefix publish-,$(PUBLISH_FILES)) +$(addprefix publish-,$(PUBLISH_FILES)): publish-%: | $(call tool,wkg) $(COSIGN_INSTALLED) + @COSIGN="$(COSIGN)" VERSION="$(VERSION)" REPOSITORY="$(REPOSITORY)" COMPONENTS_DIR="$(COMPONENTS_DIR)" SIGN="$(SIGN)" PUBLISH_LOG="$(PUBLISH_LOG)" SBOM_DIR="$(PUBLISHED_SBOM_DIR)" DRY_RUN="$(DRY_RUN)" \ + COMPONENT_PATH="$(COMPONENT_DIR_$(patsubst %.debug,%,$(*:.wasm=)))" build/scripts/publish.sh $* diff --git a/build/sbom.mk b/build/sbom.mk new file mode 100644 index 0000000..b7b2acb --- /dev/null +++ b/build/sbom.mk @@ -0,0 +1,97 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# the SBOM of each component and of the interface, CycloneDX JSON beside the wasm file it describes, +# e.g. target/components/greeter/greeter.cdx.json for greeter.wasm and greeter.debug.cdx.json for +# greeter.debug.wasm, built with the components and published with them, see build/scripts/sbom.sh + +# the SBOMs cargo-cyclonedx generates for the packages of the workspace, a directory for each target +CARGO_SBOM_DIR := target/sbom/cargo + +# the SBOM of each file published, with its version and image, see build/scripts/publish.sh, laid out +# like the components directory, e.g. greeter/greeter.debug.cdx.json for greeter.debug.wasm. The CI +# workflow packs them with the components into the components.tar of the release it drafts, in place +# of the SBOMs of the build. +PUBLISHED_SBOM_DIR := target/sbom/published + +# the time the SBOMs are generated at, the time of the commit, so the SBOMs of a commit are the same +# each time they are generated +SBOM_EPOCH := $(or $(shell git log -1 --format=%ct 2> /dev/null),0) + +# the version of the cli a component is generated with, a local tool's is its package's version, e.g. +# `$(call tool_crate_version,componentized-constants-cli)` +tool_crate_version = $(if $(filter $(1),$(LOCAL_TOOLS)),$(shell cargo pkgid -p $(1) | sed 's/.*[\#@]//'),$(call tool_version,$(1))) + +.PHONY: sboms ## Generate the SBOM of the interface and of each component, built with them by `make components` +sboms: ${COMPONENTS_DIR}/interface.cdx.json $(foreach component,$(COMPONENTS),${COMPONENTS_DIR}/$(component)/$(component).cdx.json ${COMPONENTS_DIR}/$(component)/$(component).debug.cdx.json) + +components: sboms + +.PHONY: clean-sboms ## Remove the SBOMs cargo-cyclonedx generated and those published, `make clean-components` removes the others +clean-sboms: + rm -rf $(CARGO_SBOM_DIR) $(PUBLISHED_SBOM_DIR) + +clean-components: clean-sboms + +# the SBOM of each package of the workspace built for the target, e.g. target/sbom/cargo/wasm32-wasip2. +# A stamp, the directory isn't made newer when an SBOM in it is replaced. +$(CARGO_SBOM_DIR)/%.stamp: Cargo.toml Cargo.lock $(shell find . -name Cargo.toml -not -path './target/*' -not -path './build/tools/*' -not -path './tools/*') build/scripts/sbom-cargo.sh | $(call tool,cargo-cyclonedx) + CARGO_CYCLONEDX=$(CARGO_CYCLONEDX) SOURCE_DATE_EPOCH=$(SBOM_EPOCH) build/scripts/sbom-cargo.sh $* $(CARGO_SBOM_DIR)/$* + @touch $@ + +# `$(call sbom,,,,)` +sbom = SOURCE_DATE_EPOCH=$(SBOM_EPOCH) build/scripts/sbom.sh $(1) $(2) $(3) $(4) + +define BUILD_SBOM + +ifneq ($(or $(wildcard $(COMPONENT_DIR_$1)/wit/$(COMPONENT_BASE_$1).constants.wit),$(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).properties)),) + +# a component generated with a cli embeds the cli's code, e.g. the constants cli's +SBOM_CLI_$1 := $(if $(wildcard $(COMPONENT_DIR_$1)/wit/$(COMPONENT_BASE_$1).constants.wit),componentized-constants-cli,componentized-static-config-cli) + +${COMPONENTS_DIR}/$1/$1.cdx.json ${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/%.cdx.json: ${COMPONENTS_DIR}/$1/%.wasm build/scripts/sbom.sh + $$(call sbom,generated,$$<,$$@,$$(SBOM_CLI_$1) $$(call tool_crate_version,$$(SBOM_CLI_$1))) + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wac),) + +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json)) + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).plug),) + +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json)) + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg),) + +# the image the release build is pulled from is the first line of the .wkg file, the debug build's +# the last. cosign verifies the SBOM attested to it, the base of its SBOM. +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg build/scripts/sbom.sh | $(COSIGN_INSTALLED) + COSIGN=$(COSIGN) $$(call sbom,oci,$$<,$$@,$$(shell head -1 $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg build/scripts/sbom.sh | $(COSIGN_INSTALLED) + COSIGN=$(COSIGN) $$(call sbom,oci,$$<,$$@,$$(shell tail -1 $(COMPONENT_DIR_$1)/$(COMPONENT_BASE_$1).wkg)) + +else ifneq ($(wildcard $(COMPONENT_DIR_$1)/Cargo.toml),) + +# the release and debug builds depend on the same crates. A wasm32-wasip3 component links the +# wasi-libc of the wasi-sdk sysroot or the one built from WASI_LIBC_VERSION, see build/tools.mk. +${COMPONENTS_DIR}/$1/$1.cdx.json ${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/%.cdx.json: ${COMPONENTS_DIR}/$1/%.wasm $(CARGO_SBOM_DIR)/$(call component_target,$1).stamp build/scripts/sbom.sh | $(call tool,wasm-tools) $(if $(filter wasm32-wasip3,$(call component_target,$1)),$(WASI_SDK) $(WASI_LIBC)) + WASM_TOOLS=$(WASM_TOOLS) WASI_SDK_PATH=$(WASI_SDK_PATH) WASI_LIBC_VERSION=$(WASI_LIBC_VERSION) WASI_LIBC_WASI_VERSION=$(WASI_LIBC_WASI_VERSION) \ + $$(call sbom,cargo,$$<,$$@,$(CARGO_SBOM_DIR)/$(call component_target,$1)/$(CARGO_PACKAGE_$1).cdx.json $(call component_target,$1)) + +endif + +endef + +$(foreach component,$(COMPONENTS),$(eval $(call BUILD_SBOM,$(component)))) + +# wkg.lock is optional, written when the interface is built +${COMPONENTS_DIR}/interface.cdx.json: ${COMPONENTS_DIR}/interface.wasm $(wildcard wkg.lock) build/scripts/sbom.sh + $(call sbom,interface,$<,$@,wkg.lock) diff --git a/build/scripts/bump-version.sh b/build/scripts/bump-version.sh new file mode 100755 index 0000000..a0e6102 --- /dev/null +++ b/build/scripts/bump-version.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Bump the version of the wit interface package, and of the crates. +# +# build/scripts/bump-version.sh +# +# Updates the package declaration and every reference to the package in tracked files, then +# refreshes the generated wit dependencies. The crates share the interface's version: the +# workspace version the crates inherit, and the workspace's requirements on its own crates that name +# a version, e.g. `componentized-constants = { path = "./crates/componentized-constants", version = +# "=0.2.1-dev" }`, move to the new version too. A release, not a prerelease, also moves the pins of +# the workspace's crates in the tools manifests, e.g. `componentized-build-cli = "=0.1.6"` in +# build/tools/Cargo.toml. A repository without a workspace version only bumps the interface. The default version of the bump-version workflow moves to the new version, the next bump +# is offered from it. Items whose `@since` names an unreleased (prerelease) +# version move to the new version, since they were never published under the old one. Items +# released under the old version keep their `@since`. +# +# 0.1.0-dev -> 0.1.0 releases 0.1.0, `@since(version = 0.1.0-dev)` becomes 0.1.0 +# 0.1.0 -> 0.2.0-dev starts 0.2.0, `@since(version = 0.1.0)` is unchanged +# +# PACKAGE the interface package, the first package declared in wit/worlds.wit by default, e.g. +# componentized:valkey + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +PACKAGE="${PACKAGE:-$(sed -n 's/^package \([^@]*\)@.*;$/\1/p' wit/worlds.wit | head -n 1)}" +SEMVER='^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' + +new="${1:-}" +if [[ ! "$new" =~ $SEMVER ]]; then + echo "usage: $0 , e.g. 0.1.0 or 0.2.0-dev" >&2 + exit 1 +fi + +old=$(sed -n "s/^package ${PACKAGE}@\(.*\);$/\1/p" wit/worlds.wit) +if [[ -z "$old" ]]; then + echo "unable to find the ${PACKAGE} package declaration in wit/worlds.wit" >&2 + exit 1 +fi + +# succeeds when version $1 is lower than version $2, a prerelease is lower than its release +version_lt() { + local a_core="${1%%-*}" b_core="${2%%-*}" + local a_pre="" b_pre="" + [[ "$1" == *-* ]] && a_pre="${1#*-}" + [[ "$2" == *-* ]] && b_pre="${2#*-}" + if [[ "$a_core" != "$b_core" ]]; then + local IFS=. + # shellcheck disable=SC2206 # split on the dots + local -a a=($a_core) b=($b_core) + for i in 0 1 2; do + (( a[i] < b[i] )) && return 0 + (( a[i] > b[i] )) && return 1 + done + fi + [[ -n "$a_pre" && -z "$b_pre" ]] && return 0 + [[ -z "$a_pre" && -n "$b_pre" ]] && return 1 + [[ -n "$a_pre" && "$a_pre" < "$b_pre" ]] +} + +if ! version_lt "$old" "$new"; then + echo "the new version ${new} must be greater than the current version ${old}" >&2 + exit 1 +fi + +old_re="${old//./\\.}" + +# the bump-version workflow offers the current version as the default for the next bump, checked +# before changing anything +workflow=.github/workflows/bump-version.yaml +workflow_default="default: \"${old}\" # the current version, kept current by build/scripts/bump-version.sh" +if ! grep -qF "$workflow_default" "$workflow"; then + echo "unable to find the current version as the default in ${workflow}, expected: ${workflow_default}" >&2 + exit 1 +fi + +# the version in the [workspace.package] section, inherited by the crates +workspace_version=$(sed -n '/^\[workspace\.package\]/,/^\[/s/^version = "\(.*\)"$/\1/p' Cargo.toml 2> /dev/null || true) +# the workspace's requirements on its own crates that name a version, e.g. a cli requiring the +# library at exactly the current version, publishing fails without a version requirement +crate_re='^[a-z0-9_-]+ = \{.*\bpath = "\./crates/[^"]*".*\bversion = "' +if [[ -n "$workspace_version" ]]; then + if [[ "$workspace_version" != "$old" ]]; then + echo "the workspace version ${workspace_version} in Cargo.toml does not match the interface version ${old}" >&2 + exit 1 + fi + # checked before changing anything + requirements=$(grep -E "$crate_re" Cargo.toml | grep -vE "\bversion = \"=?${old_re}\"" || true) + if [[ -n "$requirements" ]]; then + echo "unable to bump requirements in Cargo.toml that are not on the current version ${old}:" >&2 + echo "$requirements" >&2 + exit 1 + fi +fi + +# references to the package or one of its interfaces, an interface named for a keyword is escaped +# with `%`, e.g. `componentized:constants/%u8@0.2.1-dev` +ref_re="${PACKAGE}(/%?[a-z0-9-]+)?" +# the fetched wit dependencies and the wkg.lock files are left to `make wit`, wkg replaces the +# dependencies and updates the locks for the new version. The files synced from componentized/build +# are left alone, an example in them may name the package. +synced=() +if [[ -f build/MANIFEST ]]; then + while read -r _ path; do + synced+=(":(exclude,literal)${path}") + done < build/MANIFEST +fi +files=$(git grep --untracked -l -E "${ref_re}@${old_re}" -- ':(exclude,glob)**/wit/deps/**' ':(exclude,glob)**/wkg.lock' ${synced[@]+"${synced[@]}"} || true) +for file in $files; do + sed -i.bak -E "s#(${ref_re})@${old_re}#\1@${new}#g" "$file" + rm "$file.bak" + echo "updated ${file}" +done + +if [[ "$old" == *-* ]]; then + files=$(git grep --untracked -l -F "@since(version = ${old})" -- 'wit/*.wit' || true) + for file in $files; do + sed -i.bak "s/@since(version = ${old_re})/@since(version = ${new})/g" "$file" + rm "$file.bak" + echo "updated @since in ${file}" + done +fi + +if [[ -n "$workspace_version" ]]; then + perl -pi -e 'if (/^\[workspace\.package\]/ .. /^\[(?!workspace\.package\])/) { s/^version = "[^"]*"/version = "'"${new}"'"/ }' Cargo.toml + echo "updated the workspace version in Cargo.toml" + for crate in $(grep -E "$crate_re" Cargo.toml | sed 's/ .*//'); do + perl -pi -e 's/^(\Q'"${crate}"'\E = \{.*\bversion = "=?)[^"]*(")/${1}'"${new}"'${2}/' Cargo.toml + echo "updated the ${crate} requirement in Cargo.toml" + done +fi + +# the tools manifests' pins of the workspace's own crates, e.g. componentized/build pins its cli in +# build/tools/Cargo.toml for the repositories it's synced to, while it builds the cli itself with +# LOCAL_TOOLS. Moved only by a release, a prerelease isn't published to crates.io, so the pin stays +# on the last release until the next one, published before a repository syncs it. A manifest synced +# from componentized/build is left alone. +if [[ -n "$workspace_version" && "$new" != *-* ]]; then + crates=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[].name') + for manifest in build/tools/Cargo.toml tools/Cargo.toml; do + [[ -f "$manifest" ]] || continue + if [[ -f build/MANIFEST ]] && awk -v path="$manifest" '$2 == path { found = 1 } END { exit !found }' build/MANIFEST; then + continue + fi + for crate in $crates; do + grep -qE "^${crate} = \"=[^\"]*\"" "$manifest" || continue + perl -pi -e 's/^(\Q'"${crate}"'\E = "=)[^"]*(")/${1}'"${new}"'${2}/' "$manifest" + echo "updated the ${crate} pin in ${manifest}" + done + done +fi + +perl -pi -e 's{^(\s+)\Q'"${workflow_default}"'\E$}{${1}'"${workflow_default/\"${old}\"/\"${new}\"}"'}' "$workflow" +echo "updated the default version in ${workflow}" + +# regenerate the wit dependencies for the new version +make generate components test + +echo "bumped ${PACKAGE} from ${old} to ${new}" diff --git a/build/scripts/check-build.sh b/build/scripts/check-build.sh new file mode 100755 index 0000000..2a98f34 --- /dev/null +++ b/build/scripts/check-build.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Check the files synced from componentized/build are unchanged since build/scripts/update-build.sh +# synced them, the version in build/VERSION. +# +# build/scripts/check-build.sh +# +# Fails when a synced file was changed or removed, or a file was added to build/. A change to the +# build belongs in componentized/build, released and synced to each repository, rather than here. +# The current version the repository keeps in a synced file, the default of the bump-version +# workflow, is its own, and may change. + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +# the line of a synced file the repository keeps current, the default version of the bump-version +# workflow, e.g. `default: "0.1.0-dev" # the current version, kept current by +# build/scripts/bump-version.sh`. Its value is the repository's own, left out of the checksum. +CURRENT_VERSION_RE='"[^"]*"( # the current version, kept current by build/scripts/bump-version\.sh)$' +# the checksum of a synced file, without the value the repository keeps current +checksum() { + sed -E "s|${CURRENT_VERSION_RE}|\"\"\1|" "$1" | shasum -a 256 | cut -d ' ' -f 1 +} + +# componentized/build itself, the source of the files rather than a copy of them +if [[ -f SYNC ]]; then + echo "the build repository, nothing synced to check" + exit 0 +fi + +if [[ ! -f build/MANIFEST || ! -f build/VERSION ]]; then + echo "unable to find build/MANIFEST and build/VERSION, run \`make update-build\` to sync the build" >&2 + exit 1 +fi +version=$(cat build/VERSION) + +status=0 +while read -r sum path; do + if [[ ! -f "$path" ]]; then + echo "${path}: removed" + status=1 + elif [[ "$(checksum "$path")" != "$sum" ]]; then + echo "${path}: changed" + status=1 + fi +done < build/MANIFEST + +# build/ only holds synced files +while read -r path; do + case "$path" in + build/VERSION | build/MANIFEST) ;; + *) + if ! grep -qE "^[0-9a-f]{64} ${path//./\\.}$" build/MANIFEST; then + echo "${path}: not synced from componentized/build ${version}" + status=1 + fi + ;; + esac +done < <(find build -type f | sort) + +if [[ "$status" != 0 ]]; then + echo "the build differs from componentized/build ${version}. Make the change in componentized/build and update to its release, or run \`make update-build BUILD_VERSION=${version}\` to undo it." >&2 +fi +exit "$status" diff --git a/build/scripts/completions.sh b/build/scripts/completions.sh new file mode 100644 index 0000000..db6ae18 --- /dev/null +++ b/build/scripts/completions.sh @@ -0,0 +1,43 @@ +# shellcheck shell=bash +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Registers the shell completions of the installed tools, sourced by bash or zsh at startup once the +# tools are on the PATH, e.g. in ~/.bashrc: +# +# PATH="$(make -s tools-path):${PATH}" +# source /path/to/repository/build/scripts/completions.sh +# +# The tools that have completions, and how each prints them, are listed in +# [package.metadata.completions] of build/tools/Cargo.toml and the repository's tools/Cargo.toml, +# generated into target/tools/completions by `make tools`. Generated as each shell starts, so a tool +# installed or bumped since completes in new shells. A tool that isn't installed is skipped, as is +# one that fails to print its completions. + +# the arguments are the ones each line of completions sets +# shellcheck disable=SC2120 +__componentized_completions() { + local script completions shell line + if [ -n "${ZSH_VERSION:-}" ]; then + # zsh's path of the sourced script, BASH_SOURCE in bash + # shellcheck disable=SC2296 + script="${(%):-%x}" + shell=zsh + else + script="${BASH_SOURCE[0]}" + shell=bash + fi + completions="$(cd "$(dirname "$script")/../.." && pwd)/target/tools/completions" + [ -f "$completions" ] || return 0 + while IFS= read -r line; do + # the binary and its arguments, quoted by build/completions.jq + eval "set -- $line" + command -v "$1" > /dev/null 2>&1 || continue + # only a script the tool printed, one that fails may print its usage to stdout, which isn't + # run, and none reads the terminal, which would hang the shell + line=$("$@" "$shell" < /dev/null 2> /dev/null) || continue + [ -n "$line" ] && eval "$line" + done < "$completions" +} +__componentized_completions +unset -f __componentized_completions diff --git a/build/scripts/components.sh b/build/scripts/components.sh new file mode 100755 index 0000000..5b70060 --- /dev/null +++ b/build/scripts/components.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Print the components of the repository, each a line of its name and its directory, e.g. +# `example-hello examples/hello`, read by build/build.mk. +# +# build/scripts/components.sh +# +# Components are found in directories of components: components/, and each directory with a +# components.toml, e.g. examples/components.toml. The file names the prefix of the components in the +# directory, components/ has none unless it has a components.toml too, e.g. +# +# prefix = "example-" +# +# Each directory in a directory of components is a component named for the prefix and the directory, +# e.g. examples/hello is example-hello, when it has the files of one, named for the directory: +# wit/.constants.wit, .properties, .wac, .plug, .wkg or Cargo.toml. A +# component's directory may hold a group of components, those of its directories that are +# components, named for it, e.g. components/gate/gate.wac is gate, the composition of +# components/gate/internal, gate-internal, and components/gate/config, gate-config. + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +# the prefix a components.toml names, e.g. `prefix = "example-"` +prefix_of() { + [[ -f "$1/components.toml" ]] && sed -n 's/^prefix *= *"\(.*\)" *$/\1/p' "$1/components.toml" | head -n 1 + return 0 +} + +# whether a directory has the files of a component, named for the directory +is_component() { + local base + base=$(basename "$1") + [[ -f "$1/wit/${base}.constants.wit" || -f "$1/${base}.properties" || -f "$1/${base}.wac" \ + || -f "$1/${base}.plug" || -f "$1/${base}.wkg" || -f "$1/Cargo.toml" ]] +} + +# the components of a directory of components with a prefix, and those of each group, a component +# with components of its own. The components of a directory with a components.toml are named for its +# prefix instead, found as a directory of its own. +visit() { + local dir="$1" prefix="$2" sub name + for sub in "$dir"/*/; do + sub="${sub%/}" + [[ -d "$sub" ]] && is_component "$sub" || continue + name="${prefix}$(basename "$sub")" + printf '%s %s\n' "$name" "$sub" + [[ -f "$sub/components.toml" ]] || visit "$sub" "${name}-" + done +} + +{ + [[ -d components ]] && echo components + find . -name components.toml -not -path '*/target/*' -not -path '*/wit/deps/*' -not -path './.git/*' \ + | sed 's|^\./||; s|^components.toml$|.|; s|/components.toml$||' +} | sort -u | while read -r dir; do + visit "$dir" "$(prefix_of "$dir")" +done diff --git a/build/scripts/create-commit.sh b/build/scripts/create-commit.sh new file mode 100755 index 0000000..e42e6bb --- /dev/null +++ b/build/scripts/create-commit.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Create a commit of the staged changes with the GitHub REST API, signed by GitHub, for a GitHub App +# token that can't push. +# +# GH_TOKEN= APP_SLUG= build/scripts/create-commit.sh +# +# Prints the commit, a child of , the commit the changes are staged against. No branch is moved +# to it. The changes are only staged locally to find the changed files and their modes. +# +# The commit is authored, committed and signed off (DCO) by the app's bot. GitHub only signs commits +# it attributes entirely to the app, so the author and committer are left for GitHub to fill in. The +# user who triggered the workflow is credited as a co-author, with their GitHub noreply email so their +# email address isn't exposed. A run started by the app has no one else to credit. +# +# GH_TOKEN a token for the app, with contents write permission, and workflows write +# permission to change workflow files +# APP_SLUG the slug of the app, e.g. custodian +# GITHUB_REPOSITORY the repository to create the commit in, e.g. componentized/http +# GITHUB_ACTOR the user who triggered the workflow, credited as a co-author +# GITHUB_ACTOR_ID the id of the user +# RUNNER_TEMP a directory for temporary files + +set -euo pipefail + +base="${1:?usage: $0 }" +subject="${2:?usage: $0 }" +: "${GH_TOKEN:?GH_TOKEN is undefined}" +: "${APP_SLUG:?APP_SLUG is undefined}" +: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is undefined}" + +api="repos/${GITHUB_REPOSITORY}" +temp="${RUNNER_TEMP:-$(mktemp -d)}" + +# a blob for each changed file, or a null sha for a deleted file +entries="${temp}/tree-entries.json" +echo '[]' > "${entries}" +git diff --cached --no-renames --name-status "${base}" | while IFS=$'\t' read -r status path ; do + if [ "${status}" = "D" ] ; then + entry=$( jq -n --arg path "${path}" '{path: $path, mode: "100644", type: "blob", sha: null}' ) + else + mode=$( git ls-files --stage -- "${path}" | cut -d' ' -f1 ) + sha=$( base64 < "${path}" | tr -d '\n' | jq -Rs '{encoding: "base64", content: .}' | gh api --method POST "${api}/git/blobs" --input - --jq .sha ) + entry=$( jq -n --arg path "${path}" --arg mode "${mode}" --arg sha "${sha}" '{path: $path, mode: $mode, type: "blob", sha: $sha}' ) + fi + jq --argjson entry "${entry}" '. + [$entry]' "${entries}" > "${entries}.tmp" && mv "${entries}.tmp" "${entries}" + echo "${status} ${path}" >&2 +done +tree=$( jq --arg base "$( git rev-parse "${base}^{tree}" )" '{base_tree: $base, tree: .}' "${entries}" | gh api --method POST "${api}/git/trees" --input - --jq .sha ) + +bot="${APP_SLUG}[bot]" +bot_email="$( gh api "users/${bot}" --jq .id )+${bot}@users.noreply.github.com" +message=$( printf '%s\n\nSigned-off-by: %s <%s>' "${subject}" "${bot}" "${bot_email}" ) +if [ -n "${GITHUB_ACTOR:-}" ] && [ "${GITHUB_ACTOR}" != "${bot}" ] ; then + name=$( gh api "users/${GITHUB_ACTOR}" --jq '.name // .login' ) + name="${name:-${GITHUB_ACTOR}}" + email="${GITHUB_ACTOR_ID}+${GITHUB_ACTOR}@users.noreply.github.com" + message=$( printf '%s\nCo-authored-by: %s <%s>' "${message}" "${name}" "${email}" ) +fi +read -r commit verified < <( jq -n \ + --arg message "${message}" \ + --arg tree "${tree}" --arg parent "${base}" \ + '{message: $message, tree: $tree, parents: [$parent]}' \ + | gh api --method POST "${api}/git/commits" --input - --jq '"\(.sha) \(.verification.verified)"' ) +echo "created commit ${commit}" >&2 +# the branch requires signed commits, fail before pushing rather than after +if [ "${verified}" != "true" ] ; then + echo "::error::the commit '${commit}' was not created, or was not signed by GitHub" >&2 + exit 1 +fi + +echo "${commit}" diff --git a/build/scripts/install-cargo-binstall.sh b/build/scripts/install-cargo-binstall.sh new file mode 100755 index 0000000..3d46a21 --- /dev/null +++ b/build/scripts/install-cargo-binstall.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Install the binary of a cargo-binstall release, which can't install itself the way it installs the +# other tools, see build/tools.mk. +# +# build/scripts/install-cargo-binstall.sh +# +# Downloads the release's archive for the host, a rust host tuple, e.g. aarch64-unknown-linux-gnu, +# and has the binary install itself in the root, `cargo-binstall --self-install`, with its record of +# the installed version alongside those of the tools it installs. Fails for a host the release has no +# archive for, the Makefile builds it with cargo install instead. + +set -euo pipefail + +version=$1 +root=$2 +host=$3 + +case "${host}" in + *-apple-darwin | *-pc-windows-msvc) format=zip ;; + *) format=tgz ;; +esac +archive="cargo-binstall-${host}.${format}" + +# in the root, the binary moves itself into it, which fails across file systems, e.g. from /tmp +mkdir -p "${root}" +download=$(mktemp -d "${root}/.cargo-binstall.XXXXXX") +trap 'rm -rf "${download}"' EXIT + +curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -o "${download}/${archive}" \ + "https://github.com/cargo-bins/cargo-binstall/releases/download/v${version}/${archive}" +case "${format}" in + zip) unzip -q "${download}/${archive}" -d "${download}" ;; + tgz) tar xzf "${download}/${archive}" -C "${download}" ;; +esac + +CARGO_INSTALL_ROOT=${root} "${download}/cargo-binstall" --self-install diff --git a/build/scripts/pack-components.sh b/build/scripts/pack-components.sh new file mode 100755 index 0000000..cf89857 --- /dev/null +++ b/build/scripts/pack-components.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Pack the components with an SBOM for each, the SBOM it's published with when it is, into a tar, e.g. +# the components.tar of a release. +# +# build/scripts/pack-components.sh +# +# e.g. `build/scripts/pack-components.sh target/components target/sbom/published components.tar`. The +# published SBOMs are laid out like the components directory, see build/scripts/publish.sh. Each wasm +# file is packed with, beside it as .cdx.json: +# +# - the SBOM it's published with, naming its version and image, e.g. greeter.wasm's +# - for a debug build not published as it's identical to the release build, the release build's +# published SBOM, it's the same file, e.g. defaults.debug.wasm's is defaults.wasm's +# - otherwise the SBOM of the build, for a file that isn't published, e.g. a component pulled with +# wkg, whose SBOM is the one it's published with where cosign verifies it, see +# build/scripts/sbom.sh, or an internal component +# +# The components directory isn't changed, the tar is packed from a copy of it. + +set -euo pipefail + +components="${1:-}" +published="${2:-}" +tar="${3:-}" +if [[ -z "$components" || -z "$published" || -z "$tar" ]]; then + echo "usage: $0 , e.g. target/components target/sbom/published components.tar" >&2 + exit 1 +fi + +staging=$(mktemp -d) +trap 'rm -rf "$staging"' EXIT +cp -R "${components}/." "$staging" + +while IFS= read -r wasm; do + file="${wasm#./}" + sbom="${file%.wasm}.cdx.json" + release="${file%.debug.wasm}.wasm" + if [[ -f "${published}/${sbom}" ]]; then + cp "${published}/${sbom}" "${staging}/${sbom}" + echo "${file}: the SBOM it's published with" + elif [[ "$file" == *.debug.wasm && -f "${published}/${release%.wasm}.cdx.json" ]] \ + && cmp -s "${staging}/${file}" "${staging}/${release}"; then + cp "${published}/${release%.wasm}.cdx.json" "${staging}/${sbom}" + echo "${file}: the SBOM ${release} is published with, it's the same file" + elif [[ -f "${staging}/${sbom}" ]]; then + echo "${file}: the SBOM of the build, it isn't published" + else + echo "${file}: no SBOM" >&2 + exit 1 + fi +done < <(cd "$staging" && find . -name '*.wasm' | sort) + +tar -cf "$tar" -C "$staging" . diff --git a/build/scripts/publish-crates.sh b/build/scripts/publish-crates.sh new file mode 100755 index 0000000..030decb --- /dev/null +++ b/build/scripts/publish-crates.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Publish crates of the workspace to crates.io, skipping those already published, retrying a failure. +# +# [DRY_RUN=true] build/scripts/publish-crates.sh ... +# +# cargo publishes the crates together, a library before the crates that depend on it, waiting for each +# to show up in the index before publishing its dependents. A crate can still fail to publish, e.g. +# the index is slow to show a library its cli depends on, or crates.io is unavailable or rate limits +# the upload, leaving the crates before it published. cargo refuses to publish a version again, so +# each attempt publishes only the crates whose version isn't in the crates.io index yet, and running +# it again, e.g. rerunning the release workflow, finishes what a failed run started. +# +# DRY_RUN true checks the crates with `cargo publish --dry-run` rather than publishing them +# PUBLISH_ATTEMPTS the attempts to publish the crates, defaults to 3 +# PUBLISH_DELAY the seconds to wait before the second attempt, doubled for each attempt after it, +# defaults to 30 +# CRATES_INDEX the sparse index of the registry, defaults to https://index.crates.io + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +DRY_RUN="${DRY_RUN:-false}" +PUBLISH_ATTEMPTS="${PUBLISH_ATTEMPTS:-3}" +PUBLISH_DELAY="${PUBLISH_DELAY:-30}" +CRATES_INDEX="${CRATES_INDEX:-https://index.crates.io}" + +if [[ $# == 0 ]]; then + echo "usage: $0 ..., e.g. componentized-constants componentized-constants-cli" >&2 + exit 1 +fi + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +metadata=$(cargo metadata --no-deps --format-version 1 --locked) + +# the version of a crate of the workspace, e.g. 0.2.0 +version_of() { + jq -r --arg name "$1" '.packages[] | select(.name == $name) | .version' <<< "$metadata" +} + +# the path of a crate in a sparse index, e.g. co/mp/componentized-build-cli, 3/s/syn +index_path() { + local name + name=$(tr '[:upper:]' '[:lower:]' <<< "$1") + case "${#name}" in + 1) echo "1/${name}" ;; + 2) echo "2/${name}" ;; + 3) echo "3/${name:0:1}/${name}" ;; + *) echo "${name:0:2}/${name:2:2}/${name}" ;; + esac +} + +# whether a version of a crate is in the index, failing when the index can't be read +published() { + local status + status=$(curl -sSL -o "$work/index" -w '%{http_code}' "${CRATES_INDEX}/$(index_path "$1")" || true) + case "$status" in + 200) jq -se --arg version "$2" 'any(.[]; .vers == $version)' "$work/index" > /dev/null ;; + # a crate never published + 404) return 1 ;; + *) + echo "unable to read ${CRATES_INDEX}/$(index_path "$1"), HTTP ${status}" >&2 + exit 1 + ;; + esac +} + +dry_run=() +[[ "$DRY_RUN" == true ]] && dry_run=(--dry-run) + +for (( attempt = 1; ; attempt++ )); do + pending=() + for crate in "$@"; do + version=$(version_of "$crate") + if [[ -z "$version" ]]; then + echo "unable to find the crate ${crate} in the workspace" >&2 + exit 1 + fi + if published "$crate" "$version"; then + echo "${crate} ${version} is already published, skipped" + else + pending+=("$crate") + fi + done + if [[ ${#pending[@]} == 0 ]]; then + echo "the crates are published" + exit 0 + fi + + echo "publishing ${pending[*]}, attempt ${attempt} of ${PUBLISH_ATTEMPTS}" + if cargo publish --locked ${dry_run[@]+"${dry_run[@]}"} "${pending[@]/#/--package=}"; then + exit 0 + fi + # a dry run publishes nothing, it fails the same way again + if [[ "$DRY_RUN" == true || "$attempt" -ge "$PUBLISH_ATTEMPTS" ]]; then + echo "unable to publish ${pending[*]}, run it again to publish the crates not yet published" >&2 + exit 1 + fi + delay=$(( PUBLISH_DELAY * (1 << (attempt - 1)) )) + echo "publishing failed, trying again in ${delay}s" >&2 + sleep "$delay" +done diff --git a/build/scripts/publish.sh b/build/scripts/publish.sh new file mode 100755 index 0000000..1f2dac4 --- /dev/null +++ b/build/scripts/publish.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Publish a built component to an OCI registry, sign it with cosign, and attest its SBOM. +# +# VERSION= REPOSITORY= build/scripts/publish.sh +# +# The file is one of the files built into the components directory, components are in a directory +# of their own, the interface is not, e.g. gate.wasm from target/components/gate/gate.wasm and +# interface.wasm from target/components/interface.wasm. The interface is published to the +# repository, each component to a repository of its own under it, a debug build is tagged with a +# `_debug` suffix. A debug build identical to the release build adds nothing, e.g. components +# without debug info, and is not published. +# +# The SBOM built beside the file, e.g. gate.cdx.json for gate.wasm, see build/scripts/sbom.sh, names +# the component it describes, by the directory's id of the package, its version and its image, and is +# attested to the image with cosign, a signed CycloneDX attestation, `cosign verify-attestation --type +# cyclonedx` verifies it. +# +# interface.wasm -> ${REPOSITORY}:0.1.0 +# gate.wasm -> ${REPOSITORY}/gate:0.1.0 +# gate.debug.wasm -> ${REPOSITORY}/gate:0.1.0_debug +# +# VERSION the version to publish, with or without a leading `v`, e.g. v0.1.0 or 0.1.0. The +# org.opencontainers.image.version annotation always has the `v`, the tag never +# does, e.g. v0.1.0 is tagged 0.1.0 +# REPOSITORY the repository to publish to, e.g. ghcr.io/componentized/http +# GITHUB_REPOSITORY the GitHub repository the components are built from, e.g. componentized/http +# COMPONENTS_DIR the directory the components are built into, defaults to target/components +# COMPONENT_PATH the directory of the component's sources, e.g. examples/hello, linked from the +# image, defaults to components/ +# SIGN sign the published components with cosign, `false` to push without signing, +# e.g. to a local registry +# PUBLISH_LOG append the published file, its size in bytes and its image to this file, e.g. +# `gate.wasm 1234567 ghcr.io/componentized/http/gate:0.1.0@sha256:...` +# COSIGN the cosign binary, defaults to cosign on the PATH +# SBOM_DIR the directory the SBOM published with the file is written to, laid out like the +# components directory, e.g. gate/gate.debug.cdx.json for gate.debug.wasm and +# interface.cdx.json for interface.wasm, defaults to target/sbom/published +# DRY_RUN `true` to show what would be published without pushing or signing anything, +# the image is logged with a `dry-run` digest + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +file="${1:-}" +if [[ -z "$file" ]]; then + echo "usage: $0 , e.g. interface.wasm or gate.wasm" >&2 + exit 1 +fi +: "${VERSION:?VERSION is undefined}" +: "${REPOSITORY:?REPOSITORY is undefined}" +GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-componentized/$(basename "$(git rev-parse --show-toplevel)")}" +COMPONENTS_DIR="${COMPONENTS_DIR:-target/components}" +SIGN="${SIGN:-true}" +PUBLISH_LOG="${PUBLISH_LOG:-}" +SBOM_DIR="${SBOM_DIR:-target/sbom/published}" +COSIGN="${COSIGN:-cosign}" +DRY_RUN="${DRY_RUN:-false}" + +component="${file%.wasm}" +component="${component%.debug}" +COMPONENT_PATH="${COMPONENT_PATH-components/${component}}" +debug="" +[[ "$file" == *.debug.wasm ]] && debug=true + +# the directory's id of the package, e.g. componentized:http for the interface of componentized/http +# and componentized:http-gate for its gate component +if [[ "$file" == interface.wasm ]]; then + component_file="$file" + id="${GITHUB_REPOSITORY/\//:}" +else + component_file="${component}/${file}" + id="${GITHUB_REPOSITORY/\//:}-${component}" +fi +title="$id" +[[ -n "$debug" ]] && title="${title} (debug)" +sbom="${COMPONENTS_DIR}/${component_file%.wasm}.cdx.json" + +if [[ -n "$debug" ]] && cmp -s "${COMPONENTS_DIR}/${component_file}" "${COMPONENTS_DIR}/${component}/${component}.wasm"; then + echo "Not publishing ${file} as it is identical to ${component}.wasm" + exit 0 +fi + +# the description is the line following the title in the readme +readme="${COMPONENTS_DIR}/$(dirname "$component_file")/README.md" +description=$(sed -n 3p "$readme") + +commit=$(git rev-parse HEAD) +revision="$commit" +git diff --quiet HEAD || revision="${commit}+dirty" +url="https://github.com/${GITHUB_REPOSITORY}/tree/${commit}" +[[ -n "$COMPONENT_PATH" && -f "${COMPONENT_PATH}/README.md" ]] && url="${url}/${COMPONENT_PATH}" + +# the version has a leading `v`, the tag does not, whether or not VERSION has one +component_version="v${VERSION#v}" +[[ -n "$debug" ]] && component_version="${component_version}+debug" +tag="${component_version#v}" +tag="${tag//+/_}" + +if [[ "$file" == interface.wasm ]]; then + image="${REPOSITORY}:${tag}" +else + image="${REPOSITORY}/${component}:${tag}" +fi + +echo "::group::${file} -> ${image}" +# close the group when the push or signing fails, so the error isn't hidden in it +trap 'echo "::endgroup::"' EXIT + +annotations=( + --annotation="org.opencontainers.image.title=${title}" + --annotation="org.opencontainers.image.description=${description}" + --annotation="org.opencontainers.image.version=${component_version}" + --annotation="org.opencontainers.image.url=${url}" + --annotation="org.opencontainers.image.source=https://github.com/${GITHUB_REPOSITORY}.git" + --annotation="org.opencontainers.image.revision=${revision}" + --annotation="org.opencontainers.image.licenses=Apache-2.0" +) + +if [[ "$DRY_RUN" == true ]]; then + echo "Not pushing ${COMPONENTS_DIR}/${component_file} to ${image}, DRY_RUN=${DRY_RUN}" + printf ' %s\n' "${annotations[@]}" + digest=dry-run +else + digest=$( + wkg oci push \ + "${annotations[@]}" \ + "$image" \ + "${COMPONENTS_DIR}/${component_file}" \ + 2>&1 \ + | tee /dev/stderr \ + | grep -o 'sha256:[a-f0-9]\{64\}' + ) +fi + +if [[ -n "$PUBLISH_LOG" ]]; then + size=$(wc -c < "${COMPONENTS_DIR}/${component_file}" | tr -d ' ') + echo "${file} ${size} ${image}@${digest}" >> "$PUBLISH_LOG" +fi + +# the SBOM of the component published, the component already named by its id, with its version and +# image, e.g. pkg:oci/gate@sha256%3A...?repository_url=ghcr.io/componentized/http/gate&tag=0.1.0 +published_sbom="${SBOM_DIR}/${component_file%.wasm}.cdx.json" +mkdir -p "$(dirname "$published_sbom")" +repository="${image%:*}" +purl="pkg:oci/${repository##*/}" +[[ "$digest" == sha256:* ]] && purl="${purl}@${digest/:/%3A}" +purl="${purl}?repository_url=${repository}&tag=${tag}" +jq \ + --arg version "${component_version#v}" \ + --arg purl "$purl" \ + --arg description "$description" \ + --arg source "https://github.com/${GITHUB_REPOSITORY}.git" \ + --arg url "$url" \ + --arg revision "$revision" \ + '.metadata.component += { + version: $version, + description: $description, + purl: $purl, + licenses: [{expression: "Apache-2.0"}], + externalReferences: [{type: "vcs", url: $source, comment: "revision \($revision)"}, {type: "website", url: $url}] + }' "$sbom" > "$published_sbom" + +if [[ "$DRY_RUN" == true ]]; then + echo "Not signing ${image}@${digest}, nor attesting its SBOM ${published_sbom}, DRY_RUN=${DRY_RUN}" +elif [[ "$SIGN" == true ]]; then + "$COSIGN" sign --yes "${image}@${digest}" + "$COSIGN" attest --yes --type cyclonedx --predicate "$published_sbom" "${image}@${digest}" +else + echo "Not signing ${image}@${digest}, nor attesting its SBOM ${published_sbom}, SIGN=${SIGN}" +fi diff --git a/build/scripts/sbom-cargo.sh b/build/scripts/sbom-cargo.sh new file mode 100755 index 0000000..4b1e86b --- /dev/null +++ b/build/scripts/sbom-cargo.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Generate the CycloneDX SBOM of each package of the cargo workspace, built for a target, with +# cargo-cyclonedx. +# +# CARGO_CYCLONEDX= build/scripts/sbom-cargo.sh +# +# Writes /.cdx.json for each package of the workspace, e.g. +# target/sbom/cargo/wasm32-wasip2/greeter.cdx.json, the dependencies the package has built for the +# target, without the build dependencies. build/scripts/sbom.sh makes the SBOM of a component from +# its package's. cargo-cyclonedx writes the SBOM of each package beside its Cargo.toml, under a name of +# its own for each target so that two targets can be generated at once, and they're moved to . +# +# CARGO_CYCLONEDX the cargo-cyclonedx binary, run as `$CARGO_CYCLONEDX cyclonedx` +# SOURCE_DATE_EPOCH the time the SBOMs are generated at, e.g. the time of the commit, for SBOMs that +# are the same each time they are generated + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +target="${1:-}" +dir="${2:-}" +if [[ -z "$target" || -z "$dir" ]]; then + echo "usage: $0 , e.g. wasm32-wasip2 target/sbom/cargo/wasm32-wasip2" >&2 + exit 1 +fi +: "${CARGO_CYCLONEDX:?CARGO_CYCLONEDX is undefined}" + +# the name of each package's SBOM beside its Cargo.toml, cargo-cyclonedx adds `.json` +name=".sbom-${target}" + +# the name and directory of each package of the workspace +packages=$( + cargo metadata --no-deps --format-version 1 \ + | jq -r '.workspace_members as $members | .packages[] | select(.id | IN($members[])) | "\(.name)\t\(.manifest_path | rtrimstr("/Cargo.toml"))"' +) + +# remove what's left beside the packages' Cargo.toml when generating fails +trap 'while IFS=$'"'"'\t'"'"' read -r _ path; do rm -f "${path}/${name}.json"; done <<< "$packages"' EXIT + +"$CARGO_CYCLONEDX" cyclonedx \ + --manifest-path Cargo.toml \ + --format json \ + --spec-version 1.6 \ + --target "$target" \ + --no-build-deps \ + --override-filename "$name" \ + --quiet + +mkdir -p "$dir" +while IFS=$'\t' read -r package path; do + mv "${path}/${name}.json" "${dir}/${package}.cdx.json" +done <<< "$packages" diff --git a/build/scripts/sbom.sh b/build/scripts/sbom.sh new file mode 100755 index 0000000..b695bf6 --- /dev/null +++ b/build/scripts/sbom.sh @@ -0,0 +1,359 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Generate the CycloneDX SBOM of a component the build makes, or of the interface, from how it's made. +# +# build/scripts/sbom.sh cargo a component built with cargo +# build/scripts/sbom.sh composition ... composed or plugged with wac +# build/scripts/sbom.sh generated generated by a cli, e.g. constants +# build/scripts/sbom.sh oci pulled with wkg, e.g. a dep- component +# build/scripts/sbom.sh interface the interface, built with wkg +# +# The SBOM describes the wasm file as its component, `metadata.component`, by its SHA-256, the digest +# of the layer it's published as, and lists what it's made from: +# +# cargo the package and the crates it depends on built for its target, from the SBOM +# build/scripts/sbom-cargo.sh generated for the package, the Rust standard library of +# the toolchain, by the commit of rustc, and the wasi-libc it links for a wasm32-wasi* +# target: for wasm32-wasip3 the wasi-libc of the wasi-sdk sysroot, or the one built from +# WASI_LIBC_VERSION, otherwise the wasi-libc bundled with the standard library. Each +# adapter the component embeds, e.g. wasi_snapshot_preview1 embedded by +# wasm-component-ld or `wasm-tools component new --adapt`, by its SHA-256 +# composition the components it's composed from, each with what it's made from, from their SBOMs +# generated the crate of the cli it's generated with, e.g. componentized-constants-cli, whose +# code it embeds +# oci what the SBOM attested to the image it's pulled from says, verified with cosign, or +# else nothing, it is the image, named by its purl and OCI coordinates +# interface the WIT packages it depends on, from wkg.lock +# +# The component is named by the directory's id of the package it's published as, e.g. +# componentized:build-greeter for greeter.wasm and greeter.debug.wasm of componentized/build, +# componentized:build for the interface, as build/scripts/publish.sh names it, and referenced as +# `component:`, e.g. component:componentized:build-greeter. A component pulled +# with wkg is named after the image it's pulled from, e.g. componentized:logging-to-stderr for +# ghcr.io/componentized/logging/to-stderr. Its version and image are known when it's published, +# build/scripts/publish.sh adds them. +# +# GITHUB_REPOSITORY the GitHub repository the components are built from, e.g. componentized/http, +# defaults to the componentized repository named after the checkout +# COSIGN the cosign binary, to verify the SBOM attested to an image a component is +# pulled from, defaults to cosign on the PATH, without it the SBOM is made from +# the image alone +# SOURCE_DATE_EPOCH the time the SBOM is generated at, e.g. the time of the commit, for an SBOM +# that is the same each time it is generated, defaults to now +# WASM_TOOLS the wasm-tools binary, to find the adapters a component embeds, defaults to +# wasm-tools on the PATH +# WASI_SDK_PATH the wasi-sdk a wasm32-wasip3 component is linked with, see build/tools.mk +# WASI_LIBC_VERSION the wasi-libc a wasm32-wasip3 component links when built from source, a +# commit or tag, empty for the wasi-sdk sysroot's +# WASI_LIBC_WASI_VERSION the WASI 0.3 version the wasi-libc built from WASI_LIBC_VERSION was rewritten +# to import + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +kind="${1:-}" +wasm="${2:-}" +out="${3:-}" +if [[ -z "$kind" || -z "$wasm" || -z "$out" ]]; then + echo "usage: $0 ..., e.g. cargo target/components/greeter/greeter.wasm target/components/greeter/greeter.cdx.json target/sbom/cargo/wasm32-wasip2/greeter.cdx.json" >&2 + exit 1 +fi +shift 3 + +component=$(basename "$wasm" .wasm) +component="${component%.debug}" +# the directory's id of the package, as build/scripts/publish.sh names it +GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-componentized/$(basename "$(git rev-parse --show-toplevel)")}" +if [[ "$kind" == interface ]]; then + name="${GITHUB_REPOSITORY/\//:}" +else + name="${GITHUB_REPOSITORY/\//:}-${component}" +fi +sha256=$( (sha256sum "$wasm" 2> /dev/null || shasum -a 256 "$wasm") | cut -d' ' -f1) +epoch="${SOURCE_DATE_EPOCH:-$(date +%s)}" + +# the SBOM of the component, made of what's given as $components, $dependencies, what the component +# depends on directly as $depends_on, and the tools it's generated with as $tools +bom=' + {type: "library", "bom-ref": "component:\($name)", name: $name, hashes: [{alg: "SHA-256", content: $sha256}]} as $component + | { + bomFormat: "CycloneDX", + specVersion: "1.6", + version: 1, + metadata: { + timestamp: ($epoch | tonumber | todate), + tools: {components: $tools}, + component: ($component + $root) + }, + components: $components, + dependencies: ([{ref: $component["bom-ref"], dependsOn: $depends_on}] + $dependencies) + } +' + +case "$kind" in + cargo) + package_sbom="${1:?the SBOM of the package is undefined}" + target="${2:?the target the component is built for is undefined}" + # the component's package, the SBOM is named for it, e.g. greeter.cdx.json, which may differ + # from the component's name, e.g. hello for example-hello + package=$(basename "$package_sbom" .cdx.json) + + # the Rust standard library, of the toolchain the repository pins, by the commit of rustc + rustc=$(rustc -vV) + rust_release=$(sed -n 's/^release: //p' <<< "$rustc") + rust_commit=$(sed -n 's/^commit-hash: //p' <<< "$rustc") + + # the wasi-libc a wasm32-wasip3 component links, and the wasi-sdk it's linked with, as JSON + wasi_libc=null + wasi_sdk=null + if [[ "$target" == wasm32-wasip3 ]]; then + : "${WASI_SDK_PATH:?WASI_SDK_PATH is undefined, the wasi-sdk a wasm32-wasip3 component is linked with}" + # e.g. `34.0` followed by `wasi-libc: 2e6fb9d8ee0c` + sdk_version=$(head -1 "${WASI_SDK_PATH}/VERSION") + wasi_sdk=$(jq -n --arg version "$sdk_version" '{type: "application", name: "wasi-sdk", version: $version}') + if [[ -n "${WASI_LIBC_VERSION:-}" ]]; then + wasi_libc=$(jq -n --arg version "$WASI_LIBC_VERSION" --arg wasi "${WASI_LIBC_WASI_VERSION:-}" --arg sdk "$sdk_version" '{ + version: $version, + description: "built from source with wasi-sdk \($sdk)", + pedigree: (if $wasi != "" then {notes: "its WASI 0.3 bindings rewritten to import WASI \($wasi)"} else null end) + } | del(..|nulls)') + else + wasi_libc=$(jq -n --arg version "$(sed -n 's/^wasi-libc: //p' "${WASI_SDK_PATH}/VERSION")" --arg sdk "$sdk_version" '{ + version: $version, + description: "the experimental-coop-threads sysroot of wasi-sdk \($sdk)" + }') + fi + elif [[ "$target" == wasm32-wasi* ]]; then + wasi_libc=$(jq -n --arg target "$target" --arg release "$rust_release" '{ + description: "bundled with the Rust standard library for \($target) of rustc \($release)" + }') + fi + + # each adapter the component embeds, a module wit-component names `wit-component:adapter:`, + # by the SHA-256 of its bytes + adapters=$( + "${WASM_TOOLS:-wasm-tools}" metadata show --json "$wasm" \ + | jq -c '.. | objects | select(has("module")) | .module | select((.name // "") | startswith("wit-component:adapter:"))' \ + | while read -r module; do + start=$(jq -r '.range.start' <<< "$module") + end=$(jq -r '.range.end' <<< "$module") + adapter_sha256=$(tail -c +$((start + 1)) "$wasm" | head -c $((end - start)) | (sha256sum 2> /dev/null || shasum -a 256) | cut -d' ' -f1) + jq -c --arg sha256 "$adapter_sha256" '{name: (.name | ltrimstr("wit-component:adapter:")), sha256: $sha256, producers: (.producers // [])}' <<< "$module" + done \ + | jq -s '.' + ) + + # the crates whose code the component can contain, e.g. ["greeter@0.1.0", "wit-bindgen@0.63.0"]: + # the package and its normal dependencies for the target, without the proc-macros and the + # crates only they depend on, e.g. syn and wit-parser, which run as it's compiled + runtime=$( + cargo tree --quiet --locked -p "$package" --target "$target" -e normal,no-proc-macro --prefix none --format '{p}' \ + | sed -E 's/ \(.*//; s/ v/@/' \ + | sort -u \ + | jq -R . | jq -s . + ) + + # cargo-cyclonedx names the package by its path, absolute, it's made relative to the + # repository, e.g. path+file://./components/greeter#0.1.0. The package's targets are dropped, + # the component is built from one of them. A crate the component's code can't contain is + # scoped `excluded`, it's listed, with its version, hashes and licenses, as a crate the + # component is built with rather than one it's made of. + jq --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg root "$PWD" \ + --arg target "$target" --arg rust_release "$rust_release" --arg rust_commit "$rust_commit" \ + --argjson wasi_libc "$wasi_libc" --argjson wasi_sdk "$wasi_sdk" --argjson adapters "$adapters" \ + --argjson runtime "$runtime" ' + walk(if type == "string" then gsub($root; ".") else . end) + | .components |= map(if "\(.name)@\(.version)" | IN($runtime[]) then . else . + {scope: "excluded"} end) + | (.metadata.component | del(.components)) as $package + | "pkg:github/rust-lang/rust@\($rust_commit)" as $rust_purl + | { + type: "library", + "bom-ref": "rust-std:\($rust_commit):\($target)", + name: "rust-std", + version: $rust_release, + description: "the Rust standard library for \($target)", + purl: $rust_purl + } as $rust_std + | (if $wasi_libc == null then null + elif $wasi_libc.version then + {type: "library", "bom-ref": "pkg:github/webassembly/wasi-libc@\($wasi_libc.version)", name: "wasi-libc", purl: "pkg:github/webassembly/wasi-libc@\($wasi_libc.version)"} + $wasi_libc + else + {type: "library", "bom-ref": "wasi-libc:\($rust_commit):\($target)", name: "wasi-libc"} + $wasi_libc + end) as $libc + | [$adapters[] | { + type: "library", + "bom-ref": "adapter:\(.name)@\(.sha256)", + name: .name, + description: "a WASI adapter embedded in the component", + hashes: [{alg: "SHA-256", content: .sha256}], + properties: [.producers[] | .[0] as $field | .[1] | to_entries[] | {name: "producers:\($field):\(.key)", value: .value}] + }] as $adapter_components + | ([.metadata.tools[]? | {type: "application", name, version}] + [$wasi_sdk | values]) as $tools + | {} as $root + | ([$package, $rust_std, ($libc | values)] + $adapter_components + (.components // [])) as $components + | ((.dependencies // []) + + [{ref: $rust_std["bom-ref"], dependsOn: [$libc | values | .["bom-ref"]]}] + + [$libc | values | {ref: .["bom-ref"], dependsOn: []}] + + [$adapter_components[] | {ref: .["bom-ref"], dependsOn: []}]) as $dependencies + | ([$package["bom-ref"], $rust_std["bom-ref"], ($libc | values | .["bom-ref"])] + [$adapter_components[]["bom-ref"]]) as $depends_on + | '"$bom" "$package_sbom" > "$out" + ;; + composition) + if [[ $# -eq 0 ]]; then + echo "the SBOMs of the components composed are undefined" >&2 + exit 1 + fi + # each component composed, with what it's made from, a crate two components depend on is + # listed once + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" ' + [inputs] as $sboms + | ([$sboms[].metadata.tools.components[]?] | unique_by([.name, .version])) as $tools + | {} as $root + # a crate one component is made of and another only built with, scoped `excluded`, is + # one the composition is made of + | ([$sboms[] | [.metadata.component] + .components] | add | group_by(.["bom-ref"]) + | map(if any(.[]; .scope != "excluded") then (map(select(.scope != "excluded")) | .[0]) else .[0] end)) as $components + | ([$sboms[].dependencies[]] | unique_by(.ref)) as $dependencies + | [$sboms[].metadata.component["bom-ref"]] as $depends_on + | '"$bom" "$@" > "$out" + ;; + generated) + crate="${1:?the crate of the cli is undefined}" + version="${2:?the version of the cli is undefined}" + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg crate "$crate" --arg version "$version" ' + "pkg:cargo/\($crate)@\($version)" as $purl + | [{type: "application", name: $crate, version: $version}] as $tools + | {} as $root + | [{type: "library", "bom-ref": $purl, name: $crate, version: $version, purl: $purl}] as $components + | [{ref: $purl, dependsOn: []}] as $dependencies + | [$purl] as $depends_on + | '"$bom" > "$out" + ;; + oci) + image="${1:?the image is undefined}" + # e.g. ghcr.io/componentized/logging/to-stderr:0.3.1@sha256:... is + # pkg:oci/to-stderr@sha256%3A...?repository_url=ghcr.io/componentized/logging/to-stderr&tag=0.3.1 + repository="${image%%@*}" + digest="" + [[ "$image" == *@* ]] && digest="${image#*@}" + tag="" + if [[ "${repository##*/}" == *:* ]]; then + tag="${repository##*:}" + repository="${repository%:*}" + fi + # the directory's id of the image's package, e.g. componentized:logging-to-stderr for + # ghcr.io/componentized/logging/to-stderr, the registry dropped, then the namespace and the + # rest of the path joined with `-` + path="${repository#*/}" + rest="${path#*/}" + name="${path%%/*}:${rest//\//-}" + # the SBOM published with the image, attested with cosign as build/scripts/publish.sh attests + # it, verified to be signed by a GitHub Actions workflow of the image's org, e.g. + # https://github.com/componentized/... for ghcr.io/componentized/logging/to-stderr. Without + # cosign, a digest, or a verified attestation, e.g. an image published before its SBOM was, + # the SBOM is made from the image alone. + published=null + cosign="${COSIGN:-cosign}" + org="${path%%/*}" + if [[ -z "$digest" ]]; then + echo "not fetching the SBOM of ${image}, it has no digest" >&2 + elif ! command -v "$cosign" > /dev/null; then + echo "not fetching the SBOM attested to ${repository}@${digest}, cosign is not installed" >&2 + elif envelopes=$("$cosign" verify-attestation --type cyclonedx \ + --certificate-identity-regexp "^https://github\.com/${org}/" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + "${repository}@${digest}" 2> /dev/null) && [[ -n "$envelopes" ]]; then + # each attestation verified is a DSSE envelope of an in-toto statement whose predicate is + # the SBOM, the last is used + published=$(tail -1 <<< "$envelopes" | jq '.payload | @base64d | fromjson | .predicate') + published_sha256=$(jq -r '.metadata.component.hashes[]? | select(.alg == "SHA-256") | .content' <<< "$published") + if [[ -n "$published_sha256" && "$published_sha256" != "$sha256" ]]; then + echo "the SBOM attested to ${repository}@${digest} describes a component with the SHA-256 ${published_sha256}, not ${wasm}'s ${sha256}" >&2 + exit 1 + fi + echo "using the SBOM attested to ${repository}@${digest}" >&2 + else + echo "no SBOM attested to ${repository}@${digest} by a workflow of github.com/${org} verified, the SBOM is made from the image alone" >&2 + fi + + # the image's OCI coordinates: the registry, the repository in it, the tag and the digest, e.g. + # ghcr.io, componentized/logging/to-stderr, 0.3.1 and sha256:..., and the reference it's + # pulled by. The version is the tag's, a debug build's `_debug` tag is version `+debug`, as + # build/scripts/publish.sh tags it, e.g. 0.3.1_debug is 0.3.1+debug. A published SBOM is the + # base: what it says of the component, its version, licenses and what it's made from, is kept, + # and the component's SHA-256, OCI coordinates and the reference to the SBOM are added. + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg image "$image" --arg repository "$repository" --arg digest "$digest" --arg tag "$tag" --argjson published "$published" ' + ($repository | split("/") | last) as $last + | "pkg:oci/\($last)\(if $digest != "" then "@\($digest | sub(":"; "%3A"))" else "" end)?repository_url=\($repository)\(if $tag != "" then "&tag=\($tag)" else "" end)" as $purl + | [{type: "application", name: "wkg"}] as $tools + | { + version: (if $tag != "" then $tag | sub("_"; "+") else null end), + purl: $purl, + externalReferences: [{type: "distribution", url: "oci://\($image)", comment: "the OCI image the component is pulled from with wkg"}], + properties: [ + {name: "oci:registry", value: ($repository | split("/") | first)}, + {name: "oci:repository", value: ($repository | split("/") | .[1:] | join("/"))}, + (if $tag != "" then {name: "oci:tag", value: $tag} else empty end), + (if $digest != "" then {name: "oci:digest", value: $digest} else empty end) + ] + } | del(..|nulls) as $root + | [] as $components + | [] as $dependencies + | [] as $depends_on + | '"$bom"' + | if $published == null then . else + . as $local + | $published + | .metadata.timestamp = $local.metadata.timestamp + | .metadata.tools = {components: ([(.metadata.tools | if type == "array" then .[] else .components[]? end)] + $local.metadata.tools.components + [{type: "application", name: "cosign"}] | unique_by(.name))} + | .metadata.component |= ( + .hashes = $local.metadata.component.hashes + | .purl = $local.metadata.component.purl + | .version //= $local.metadata.component.version + | .externalReferences = ((.externalReferences // []) + $local.metadata.component.externalReferences + [{ + type: "bom", + url: "oci://\($repository)@\($digest)", + comment: "the SBOM attested to the image with cosign, the base of this SBOM" + }]) + | .properties = ((.properties // []) + $local.metadata.component.properties) + ) + end + ' > "$out" + ;; + interface) + lock="${1:?the wkg.lock is undefined}" + # each version of each package in wkg.lock, a line of its name, registry, version and digest. A + # missing lock has no packages, e.g. an interface without dependencies. + packages="" + [[ -f "$lock" ]] && packages=$(awk ' + /^\[\[packages\]\]/ { name = ""; registry = "" } + /^name = / { gsub(/"/, "", $3); name = $3 } + /^registry = / { gsub(/"/, "", $3); registry = $3 } + /^version = / && name != "" { gsub(/"/, "", $3); version = $3 } + /^digest = / && name != "" { gsub(/"/, "", $3); print name "\t" registry "\t" version "\t" $3 } + ' "$lock") + jq -n -R --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" ' + [inputs | select(. != "") | split("\t") | {name: .[0], registry: .[1], version: .[2], digest: .[3]}] as $packages + | [{type: "application", name: "wkg"}] as $tools + | {} as $root + | [$packages[] | { + type: "library", + "bom-ref": "wit:\(.name)@\(.version)", + name, + version, + hashes: [{alg: "SHA-256", content: (.digest | ltrimstr("sha256:"))}], + properties: [{name: "wkg:registry", value: .registry}] + }] as $components + | [$components[] | {ref: .["bom-ref"], dependsOn: []}] as $dependencies + | [$components[]["bom-ref"]] as $depends_on + | '"$bom" <<< "$packages" > "$out" + ;; + *) + echo "unknown kind ${kind}, one of cargo, composition, generated, oci or interface" >&2 + exit 1 + ;; +esac diff --git a/build/scripts/update-build.sh b/build/scripts/update-build.sh new file mode 100755 index 0000000..901f2e2 --- /dev/null +++ b/build/scripts/update-build.sh @@ -0,0 +1,215 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Update the build synced from componentized/build to one of its releases, or to a commit of it. +# +# build/scripts/update-build.sh [] +# +# Downloads the release or commit, removes the files synced from the previous version, listed in +# build/MANIFEST, copies in the files of the release, listed in its SYNC file, and records the +# version in build/VERSION and a checksum of each file in build/MANIFEST, checked by +# build/scripts/check-build.sh. The current version the repository keeps in a synced file, the +# default of the bump-version workflow, is carried forward. A tool the repository's tools/Cargo.toml +# overrides is removed from it once the release's build/tools/Cargo.toml pins the same version or a +# newer one. +# +# the release to update to, e.g. v0.2.0, or a branch, tag, commit or other ref of +# the build's repository, e.g. main, 6f2b296 or refs/pull/23/head, recorded as its +# commit in build/VERSION. The latest release by default, unless build/VERSION is a +# commit newer than it, e.g. of main ahead of the latest release, which is kept: a +# release is newer when it includes the commit, or when it diverged from the +# commit, e.g. merged from a pull request by a squash, and was committed after it +# BUILD_REPOSITORY the GitHub repository of the build, defaults to componentized/build +# BUILD_SOURCE a checkout of the build repository to update from in place of a release, e.g. to +# try a change before releasing it, recorded as its commit in build/VERSION +# GH_TOKEN a GitHub token for the API, optional, raises its rate limit + +set -euo pipefail + +# the update replaces this script, bash reads a script while it runs it, so the whole script is in a +# block bash reads before running any of it +{ + +cd "$(dirname "$0")/../.." + +BUILD_REPOSITORY="${BUILD_REPOSITORY:-componentized/build}" +BUILD_SOURCE="${BUILD_SOURCE:-}" +version="${1:-}" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +if [[ -n "$BUILD_SOURCE" ]]; then + source=$(cd "$BUILD_SOURCE" && pwd) + if [[ -z "$version" ]]; then + version="$(git -C "$source" rev-parse --verify --quiet HEAD || echo local)" + [[ -n "$(git -C "$source" status --porcelain 2> /dev/null)" ]] && version="${version}+dirty" + fi +else + auth=() + [[ -n "${GH_TOKEN:-}" ]] && auth=(--header "Authorization: Bearer ${GH_TOKEN}") + # the GitHub API of the build's repository, e.g. `api releases/latest` + api() { + curl -fsSL ${auth[@]+"${auth[@]}"} "https://api.github.com/repos/${BUILD_REPOSITORY}/$1" + } + RELEASE_RE='^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' + COMMIT_RE='^[0-9a-f]{40}$' + + # whether a release is newer than a commit: it includes the commit, or diverged from it and was + # committed after it, e.g. a commit of a pull request merged by a squash. A commit the repository + # doesn't have, e.g. a local commit synced with BUILD_SOURCE, is older than any release. + newer() { + local compare status + if ! compare=$(api "compare/$2...$1" 2> /dev/null); then + echo "unable to compare ${BUILD_REPOSITORY} $2 to $1" >&2 + return 0 + fi + status=$(jq -r .status <<< "$compare") + case "$status" in + ahead | identical) return 0 ;; + behind) return 1 ;; + diverged) + [[ "$(api "commits/$1" | jq -r .commit.committer.date)" > "$(jq -r .base_commit.commit.committer.date <<< "$compare")" ]] + ;; + *) + echo "unable to compare ${BUILD_REPOSITORY} $2 to $1, ${status}" >&2 + exit 1 + ;; + esac + } + + if [[ -z "$version" ]]; then + version=$(api releases/latest | jq -r .tag_name) + # the commit synced, e.g. of main, or from a checkout, which may be dirty + current=$(cat build/VERSION 2> /dev/null || true) + current="${current%+dirty}" + if [[ "$current" =~ $COMMIT_RE ]] && ! newer "$version" "$current"; then + echo "the build is ${BUILD_REPOSITORY} ${current}, newer than its latest release ${version}" + exit + fi + fi + if [[ "$version" =~ $RELEASE_RE ]]; then + archive="refs/tags/${version}" + else + # a branch, tag, commit or other ref, recorded as its commit, e.g. main or refs/pull/23/head + if [[ ! "$version" =~ ^[0-9A-Za-z._/-]+$ ]] || ! commit=$(api "commits/${version}" 2> /dev/null | jq -er .sha); then + echo "unable to find '${version}' in ${BUILD_REPOSITORY}, a release, e.g. v0.2.0, or a branch, tag, commit or ref, e.g. main" >&2 + exit 1 + fi + [[ "$commit" != "$version" ]] && echo "${version} is ${BUILD_REPOSITORY} ${commit}" + version="$commit" + archive="$commit" + fi + source="$work/source" + mkdir -p "$source" + echo "downloading ${BUILD_REPOSITORY} ${version}" + curl -fsSL "https://github.com/${BUILD_REPOSITORY}/archive/${archive}.tar.gz" | tar -xz --strip-components 1 -C "$source" +fi + +if [[ ! -f "$source/SYNC" ]]; then + echo "unable to find the SYNC file of ${BUILD_REPOSITORY} ${version}" >&2 + exit 1 +fi + +# the line of a synced file the repository keeps current, the default version of the bump-version +# workflow, e.g. `default: "0.1.0-dev" # the current version, kept current by +# build/scripts/bump-version.sh`. Its value is the repository's own, left out of the checksum. +CURRENT_VERSION_RE='"[^"]*"( # the current version, kept current by build/scripts/bump-version\.sh)$' +# the checksum of a synced file, without the value the repository keeps current +checksum() { + sed -E "s|${CURRENT_VERSION_RE}|\"\"\1|" "$1" | shasum -a 256 | cut -d ' ' -f 1 +} + +# the current version kept in a file, e.g. `0.1.0-dev`, also from a file of the build before it moved +# into build/, kept current by scripts/bump-version.sh +current_version() { + [[ -f "$1" ]] && sed -nE 's|.*"([^"]*)" # the current version, kept current by (build/)?scripts/bump-version\.sh$|\1|p' "$1" | head -n 1 +} + +# the repository's version, the version of its interface package, e.g. `package componentized:http@0.1.0-dev;` +interface_version=$(sed -n 's/^package [^@]*@\(.*\);$/\1/p' wit/worlds.wit 2> /dev/null | head -n 1 || true) + +# a path in the repository, relative and inside it, e.g. build/build.mk +check_path() { + if [[ "$1" == /* || "/$1/" == */../* ]]; then + echo "refusing to sync '$1', outside the repository" >&2 + exit 1 + fi +} + +# the files of the release, each path in SYNC is a file or a directory of files +synced="$work/synced" +: > "$synced" +while read -r path; do + [[ -z "$path" || "$path" == \#* ]] && continue + check_path "$path" + if [[ ! -e "$source/$path" ]]; then + echo "unable to find ${path}, listed in the SYNC file of ${BUILD_REPOSITORY} ${version}" >&2 + exit 1 + fi + # a checkout syncs only its tracked and unignored files + if git -C "$source" rev-parse --is-inside-work-tree > /dev/null 2>&1; then + git -C "$source" ls-files --cached --others --exclude-standard -- "$path" >> "$synced" + else + (cd "$source" && find "$path" -type f) >> "$synced" + fi +done < "$source/SYNC" +sort -u -o "$synced" "$synced" + +# the files synced from the previous version, a file the release no longer has is removed +if [[ -f build/MANIFEST ]]; then + while read -r _ path; do + check_path "$path" + if ! grep -qxF "$path" "$synced"; then + rm -f "$path" + echo "removed ${path}" + fi + done < build/MANIFEST +fi + +while read -r path; do + mkdir -p "$(dirname "$path")" + cp "$source/$path" "$path.tmp" + # the repository's current version rather than the build's, or its interface version for a file + # it didn't have yet + current=$(current_version "$path" || true) + current="${current:-$interface_version}" + if [[ -n "$current" ]]; then + sed -E "s|${CURRENT_VERSION_RE}|\"${current}\"\1|" "$path.tmp" > "$path.tmp.current" + mv "$path.tmp.current" "$path.tmp" + fi + if cmp -s "$path.tmp" "$path"; then + rm "$path.tmp" + else + # moved into place rather than overwritten, e.g. this script while it runs + mv "$path.tmp" "$path" + echo "updated ${path}" + fi + chmod "$( [[ -x "$source/$path" ]] && echo 755 || echo 644 )" "$path" +done < "$synced" + +echo "$version" > build/VERSION +while read -r path; do + echo "$(checksum "$path") ${path}" +done < "$synced" > build/MANIFEST + +# remove the overrides of the tools the build provides that the build has caught up with, pinned to +# the build's version or an older one, e.g. `wasm-tools = "=1.262.0"` when the build pins 1.263.0. A +# newer version stays, the repository is ahead of the build. The tool's dependency and its line in +# [package.metadata.bins] both start with its name, e.g. `wasm-tools = ["wasm-tools"]`. +if [[ -f tools/Cargo.toml ]]; then + while read -r tool provided; do + pinned=$(sed -n "s/^${tool} = \"=\(.*\)\"$/\1/p" tools/Cargo.toml) + [[ -z "$pinned" ]] && continue + if [[ "$(printf '%s\n%s\n' "$pinned" "$provided" | sort -V | tail -n 1)" == "$provided" ]]; then + perl -ni -e 'print unless /^\Q'"${tool}"'\E = /' tools/Cargo.toml + echo "removed ${tool} ${pinned} from tools/Cargo.toml, the build provides ${provided}" + fi + done < <(sed -n 's/^\([A-Za-z0-9_-]*\) = "=\(.*\)"$/\1 \2/p' build/tools/Cargo.toml) +fi + +echo "updated the build to ${BUILD_REPOSITORY} ${version}" +exit +} diff --git a/build/scripts/wac-deps.sh b/build/scripts/wac-deps.sh new file mode 100755 index 0000000..456a044 --- /dev/null +++ b/build/scripts/wac-deps.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Encode each WIT package of a wit/deps directory where `wac compose --deps-dir` looks for it, so a +# composition can name the interfaces of a package it does not instantiate, e.g. +# `import stderr: wasi:cli/stderr@0.3.0;`. +# +# WASM_TOOLS= scripts/wac-deps.sh +# +# wac looks for a versioned package at `//.wasm`, e.g. +# +# wit/deps/wasi-cli-0.3.0 -> /wasi/cli/0.3.0.wasm +# +# Each package is encoded with the other packages as its dependencies. + +set -euo pipefail + +deps=$1 +out=$2 +wasm_tools=${WASM_TOOLS:-wasm-tools} + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +rm -rf "$out" +mkdir -p "$out" + +# a missing directory, e.g. one without a wkg.toml to fetch it, has no packages +for package in "$deps"/*/; do + [[ -d "$package" ]] || continue + package=${package%/} + rm -rf "$work/package" + mkdir -p "$work/package/deps" + cp "$package"/*.wit "$work/package/" + for dep in "$deps"/*/; do + dep=${dep%/} + [[ "$dep" == "$package" ]] || cp -R "$dep" "$work/package/deps/" + done + "$wasm_tools" component wit "$work/package" --wasm -o "$work/package.wasm" + + # e.g. `package wasi:cli@0.3.0;` + id=$("$wasm_tools" component wit "$work/package.wasm" | sed -n 's/^package \(.*\);$/\1/p' | head -n 1) + namespace=${id%%:*} + name=${id#*:} + name=${name%%@*} + version=${id#*@} + mkdir -p "$out/$namespace/$name" + cp "$work/package.wasm" "$out/$namespace/$name/$version.wasm" +done diff --git a/build/scripts/wit-canonical.sh b/build/scripts/wit-canonical.sh new file mode 100755 index 0000000..073b829 --- /dev/null +++ b/build/scripts/wit-canonical.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Print the WIT of a component in a canonical form, to compare the WIT of two components, e.g. the +# release and debug build of a component. +# +# WASM_TOOLS= scripts/wit-canonical.sh +# +# `wasm-tools component wit` prints the items of a component's WIT in the order the component +# defines them, which differs between builds of the same sources, e.g. a build optimized by +# wasm-opt. Each line is printed with the items it's nested in, e.g. +# +# package wasi:http@0.3.0 > interface types > resource request > get-method: func() -> method; +# +# the names a `use` imports are sorted, and the lines are sorted. + +set -euo pipefail + +component=$1 +wasm_tools=${WASM_TOOLS:-wasm-tools} + +"$wasm_tools" component wit "$component" | perl -ne ' + s/^\s+|\s+$//g; + next unless length; + if ($_ eq "}") { pop @items; next } + s/\{([^{}]*)\}/"{" . join(", ", sort split(m{,\s*}, $1)) . "}"/e; + print join(" > ", @items, $_), "\n"; + push @items, $1 if /^(.*?)\s*\{$/; +' | LC_ALL=C sort diff --git a/build/scripts/wit-paths.sh b/build/scripts/wit-paths.sh new file mode 100755 index 0000000..2d29e47 --- /dev/null +++ b/build/scripts/wit-paths.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# Print the WIT paths each cargo component's bindings are generated from, as make variables, e.g. +# `WIT_BINDGEN_PATHS_greeter := components/greeter/../wit`, for target/wit-paths.mk, see +# build/components.mk. +# +# build/scripts/wit-paths.sh ... +# +# A component's paths are the `path` of each `wit_bindgen::generate!` in its sources and in those of +# the workspace crates it depends on by path, transitively, but for tests, e.g. a crate of bindings +# the component and others share. A path is relative to the manifest of the crate with the +# `generate!`, like wit-bindgen reads it, e.g. +# +# generate!({ path: "../wit", world: "greeter" }) ../wit +# generate!({ path: ["wit", "../wit"], world: ... }) wit and ../wit +# generate!("greeter" in "../wit") ../wit +# generate!("greeter") or generate!({ world: ... }) wit, wit-bindgen's default +# generate!({ inline: "...", world: ... }) nothing, the WIT is inline +# +# A component without a `generate!`, or that isn't a package of the workspace, has no paths. + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +[[ $# == 0 ]] && exit 0 + +# for each component, a line of its name, then the manifest directory and the source of each target of +# it and of the crates it depends on, tab separated, relative to the repository, e.g. +# `greeter components/greeter components/greeter/src`, a target in the crate's own directory, e.g. +# build.rs, is a file, others are their directory, e.g. src +cargo metadata --no-deps --format-version 1 | jq -r --args ' + .workspace_root as $root + | (.packages | map({key: .name, value: .}) | from_entries) as $packages + | def relative: if . == $root then "." else ltrimstr($root + "/") end; + def dir: sub("/[^/]*$"; ""); + # the workspace packages a package depends on by path, but for tests, cargo forbids cycles + def path_deps: .dependencies[] | select(.path != null and .kind != "dev") | $packages[.name] | select(. != null); + def sources: + (.manifest_path | dir) as $dir + | .targets[] | select(any(.kind[]; IN("lib", "rlib", "cdylib", "staticlib", "dylib", "bin", "proc-macro", "custom-build"))) + | .src_path | if dir == $dir then . else dir end + | [($dir | relative), relative] | join("\t"); + $ARGS.positional[] as $name + | $packages[$name] | select(. != null) + | [$name, ([recurse(path_deps)] | unique_by(.name) | .[] | sources)] | join("\t") +' "$@" | perl -ne ' + chomp; + my ($name, @fields) = split /\t/; + my %paths; + while (my ($crate, $source) = splice(@fields, 0, 2)) { + my @files = -d $source ? split /\0/, `find "$source" -name "*.rs" -not -path "*/target/*" -print0` : ($source); + for my $file (@files) { + open(my $fh, "<", $file) or next; + local $/; + my $text = <$fh>; + # the comments, which may mention a path or a macro + $text =~ s{//[^\n]*}{}g; + $text =~ s{/\*.*?\*/}{}gs; + # the arguments of each generate!, the parentheses balanced + while ($text =~ /\bgenerate!\s*(\((?:[^()]++|(?1))*\))/g) { + my $args = $1; + my @found; + if ($args =~ /\bpath\s*:\s*(\[[^\]]*\]|"[^"]*")/) { + @found = $1 =~ /"([^"]*)"/g; + } elsif ($args =~ /^\(\s*"[^"]*"\s+in\s+"([^"]*)"/) { + @found = ($1); + } elsif ($args !~ /\binline\s*:/) { + @found = ("wit"); + } + $paths{$crate eq "." ? $_ : "$crate/$_"} = 1 for @found; + } + } + } + print "WIT_BINDGEN_PATHS_$name := ", join(" ", sort keys %paths), "\n"; +' diff --git a/build/sync.mk b/build/sync.mk new file mode 100644 index 0000000..30b4fbe --- /dev/null +++ b/build/sync.mk @@ -0,0 +1,14 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# the release of componentized/build to update to, e.g. v0.2.0, or a branch, tag, commit or ref, e.g. +# main, the latest release by default, unless the build is of a newer commit +BUILD_VERSION ?= + +.PHONY: update-build ## Update the build to a release or commit of componentized/build, e.g. `make update-build BUILD_VERSION=v0.2.0` or `BUILD_VERSION=main` +update-build: + build/scripts/update-build.sh $(BUILD_VERSION) + +.PHONY: check-build ## Check the files synced from componentized/build are unchanged since `make update-build` +check-build: + build/scripts/check-build.sh diff --git a/build/tools.mk b/build/tools.mk new file mode 100644 index 0000000..8ef1e49 --- /dev/null +++ b/build/tools.mk @@ -0,0 +1,258 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +TOOLS_DIR := target/tools/$(shell rustc --print host-tuple) +# absolute, tools also run from other directories, e.g. `cd components && wkg fetch` +TOOLS_BIN := $(abspath $(TOOLS_DIR))/bin +# for the scripts and tests the recipes run, they look up the tools on the PATH +export PATH := $(TOOLS_BIN):$(PATH) + +# the tools the build provides, pinned in build/tools/Cargo.toml, and those the repository pins in +# its own tools/Cargo.toml, optional: a tool it pins overrides the build's, others it only uses +# itself. Generated when either changes, make restarts after generating it. Defines TOOLS, +# TOOLS_PINNED with the version of each tool, e.g. `wkg@0.16.1`, and a variable for each binary a +# tool installs, e.g. `WKG := $(TOOLS_BIN)/wkg`. Recipes run the pinned tools by path, make 3.81 runs +# a simple command without a shell and looks it up on its own PATH, before the export above, which +# would find a tool already on the system. A binary set on the command line is run in its place, +# e.g. `make WKG=../wkg/target/release/wkg`. +TOOLS_MANIFESTS := build/tools/Cargo.toml $(wildcard tools/Cargo.toml) +TOOLS_MK := target/tools/pinned.mk +include $(TOOLS_MK) +# generated again when tools/Cargo.toml is added or removed, it records the manifests it read +ifneq ($(strip $(TOOLS_MANIFESTS_PINNED)),$(strip $(TOOLS_MANIFESTS))) +$(TOOLS_MK): tools-manifests-changed +.PHONY: tools-manifests-changed +endif + +# the tools built from this repository rather than pinned, e.g. a cli the +# components are built with, `LOCAL_TOOLS := componentized-constants-cli`. Each is a package of the +# workspace, installed with the pinned tools, and installed again when its sources change, its own or +# those of the workspace packages it depends on. A local tool replaces a pinned tool of the same name, +# one the build provides too, e.g. componentized/constants builds its own constants cli. +# Generated when the workspace changes, defines LOCAL_TOOL_PATH_, LOCAL_TOOL_SOURCES_ +# and a variable for each binary the package installs, like the pinned tools, e.g. +# `CONSTANTS := $(TOOLS_BIN)/constants`. +LOCAL_TOOLS ?= +LOCAL_TOOLS_MK := target/tools/local.mk +ifneq ($(strip $(LOCAL_TOOLS)),) +# quietly, the first time make generates it before reading it +-include $(LOCAL_TOOLS_MK) +endif + +# the toolchain pinned in rust-toolchain.toml, named for `cargo install`, otherwise rustup warns that +# the toolchain file overrides the default +RUST_TOOLCHAIN := $(shell sed -n 's/^channel *= *"\(.*\)"/\1/p' rust-toolchain.toml 2> /dev/null) + + +.PHONY: clean-tools ## Remove the installed tools, installed again by `make tools` +clean-tools: + rm -rf ${TOOLS_DIR} + +# each tool is a dependency of a tools package, the binaries it installs are listed in +# [package.metadata.bins]. The repository's tools/Cargo.toml is read last, overriding the build's. +$(TOOLS_MK): $(TOOLS_MANIFESTS) build/pinned.jq + @mkdir -p $(@D) + @set -o pipefail; for manifest in $(TOOLS_MANIFESTS); do cargo metadata --manifest-path $$manifest --no-deps --format-version 1; done | jq -rs -f build/pinned.jq > $@.tmp + @echo "TOOLS_MANIFESTS_PINNED := $(TOOLS_MANIFESTS)" >> $@.tmp + @mv $@.tmp $@ + +# the binaries that print shell completions and their arguments, read by build/scripts/completions.sh +# as a shell starts, see [package.metadata.completions] in build/tools/Cargo.toml. Generated with the +# tools, the repository's tools/Cargo.toml is read last, overriding the build's. +TOOLS_COMPLETIONS := target/tools/completions + +tools: $(TOOLS_COMPLETIONS) + +$(TOOLS_COMPLETIONS): $(TOOLS_MANIFESTS) build/completions.jq + @mkdir -p $(@D) + @set -o pipefail; for manifest in $(TOOLS_MANIFESTS); do cargo metadata --manifest-path $$manifest --no-deps --format-version 1; done | jq -rs -f build/completions.jq > $@.tmp + @mv $@.tmp $@ + +# the packages of the workspace, generated again when LOCAL_TOOLS changes. The workspace's members may +# change without changing Cargo.toml or Cargo.lock, `make clean-tools` generates it again. +$(LOCAL_TOOLS_MK): Cargo.toml Cargo.lock $(filter-out $(TOOLS_MK) $(LOCAL_TOOLS_MK),$(MAKEFILE_LIST)) build/local.jq + @mkdir -p $(@D) + @set -o pipefail; cargo metadata --no-deps --format-version 1 | jq -r --arg tools "$(LOCAL_TOOLS)" -f build/local.jq > $@.tmp + @mv $@.tmp $@ + +tool_version = $(if $(filter $(1),$(LOCAL_TOOLS)),local,$(patsubst $(1)@%,%,$(filter $(1)@%,$(TOOLS_PINNED)))) +# a stamp naming the version of a tool installed in $(TOOLS_DIR)/bin, e.g. `wkg@0.16.1`, the binary +# does not say which version it is. Bumping the pinned version names a stamp that does not exist yet, +# so the tool is installed again. A local tool's stamp is `@local`. +tool = $(TOOLS_DIR)/.installed/$(1)@$(call tool_version,$(1)) + +# a tool a recipe runs: a local tool is a prerequisite, what's made with it is made again when it +# changes, a pinned tool only has to be installed first, e.g. `$(call tool_prerequisite,wkg)`. Last +# among the prerequisites, it may be order-only. +tool_prerequisite = $(if $(filter $(1),$(LOCAL_TOOLS)),$(call tool,$(1)),| $(call tool,$(1))) + +.PHONY: tools ## Install the cli tools the build provides, those pinned in tools/Cargo.toml, and those built from the workspace +tools: $(foreach name,$(sort $(TOOLS) $(LOCAL_TOOLS)),$(call tool,$(name))) + +.PHONY: tools-path ## Print the directory of the installed tools for this platform, to add to the PATH +tools-path: + @echo $(TOOLS_BIN) + +# installed first, it installs the others. The binary of the release for the host, see +# build/scripts/install-cargo-binstall.sh, or else, for a host without one, built with cargo install. +$(call tool,cargo-binstall): build/scripts/install-cargo-binstall.sh + build/scripts/install-cargo-binstall.sh $(call tool_version,cargo-binstall) $(abspath $(TOOLS_DIR)) $(notdir $(TOOLS_DIR)) \ + || cargo $(if $(RUST_TOOLCHAIN),+$(RUST_TOOLCHAIN)) install --locked --root $(TOOLS_DIR) --version $(call tool_version,cargo-binstall) cargo-binstall + @mkdir -p $(@D) + @rm -f $(@D)/cargo-binstall@* + @touch $@ + +define INSTALL_TOOL + +$(call tool,$1): | $(call tool,cargo-binstall) + $(CARGO_BINSTALL) --no-confirm --disable-telemetry --locked --root $(TOOLS_DIR) --version $(call tool_version,$1) $1 + @mkdir -p $$(@D) + @# only the installed version has a stamp, so going back to a previous version installs it again + @rm -f $$(@D)/$1@* + @touch $$@ + +endef + +$(foreach name,$(filter-out cargo-binstall $(LOCAL_TOOLS),$(TOOLS)),$(eval $(call INSTALL_TOOL,$(name)))) + +define INSTALL_LOCAL_TOOL + +$(call tool,$1): Cargo.toml Cargo.lock $(wildcard rust-toolchain.toml) $(if $(LOCAL_TOOL_SOURCES_$1),$(shell find $(LOCAL_TOOL_SOURCES_$1) -type f)) + @# forced, make only installs when the sources change, and the binary may belong to another package + cargo $(if $(RUST_TOOLCHAIN),+$(RUST_TOOLCHAIN)) install --force --locked --root $(TOOLS_DIR) --path $(LOCAL_TOOL_PATH_$1) + @mkdir -p $$(@D) + @# going back to the pinned version installs it again + @rm -f $$(@D)/$1@* + @touch $$@ + +endef + +$(foreach name,$(LOCAL_TOOLS),$(eval $(call INSTALL_LOCAL_TOOL,$(name)))) + +# cosign, which signs the published components and attests their SBOMs, see build/scripts/publish.sh, +# and verifies the SBOM attested to a component pulled with wkg, see build/scripts/sbom.sh. A binary +# of the release for the host, checked against the release's checksums, run as `$(COSIGN)`. +COSIGN_VERSION := 3.1.4 +COSIGN_HOST := $(or $(word 2,$(subst :, ,$(filter $(shell rustc --print host-tuple):%,aarch64-apple-darwin:darwin-arm64 x86_64-apple-darwin:darwin-amd64 aarch64-unknown-linux-gnu:linux-arm64 x86_64-unknown-linux-gnu:linux-amd64))),unsupported-host) +COSIGN := $(TOOLS_BIN)/cosign +COSIGN_INSTALLED := $(TOOLS_DIR)/.installed/cosign@$(COSIGN_VERSION) + +tools: $(COSIGN_INSTALLED) + +$(COSIGN_INSTALLED): + @mkdir -p $(TOOLS_BIN) $(@D) + @curl -fsSL -o $(COSIGN).download https://github.com/sigstore/cosign/releases/download/v$(COSIGN_VERSION)/cosign-$(COSIGN_HOST) + @expected=$$(curl -fsSL https://github.com/sigstore/cosign/releases/download/v$(COSIGN_VERSION)/cosign_checksums.txt | awk '$$2 == "cosign-$(COSIGN_HOST)" { print $$1 }'); \ + actual=$$( (sha256sum $(COSIGN).download 2> /dev/null || shasum -a 256 $(COSIGN).download) | cut -d' ' -f1); \ + if [ -z "$$expected" ] || [ "$$expected" != "$$actual" ]; then \ + rm -f $(COSIGN).download; \ + echo "cosign-$(COSIGN_HOST) $(COSIGN_VERSION) has the SHA-256 $$actual, not the $${expected:-unknown} of the release's checksums" >&2; \ + exit 1; \ + fi + @chmod +x $(COSIGN).download + @mv $(COSIGN).download $(COSIGN) + @rm -f $(@D)/cosign@* + @touch $@ + +ifneq ($(filter wasm32-wasip3,$(COMPONENT_TARGETS)),) + +# wasi-sdk, for its experimental sysroot with a wasi-libc built for component model cooperative +# threads, see build/components.mk. Installed with the tools, set WASI_SDK_PATH to use an existing install. +WASI_SDK_VERSION := 34.0 +WASI_SDK_HOST := $(or $(word 2,$(subst :, ,$(filter $(shell rustc --print host-tuple):%,aarch64-apple-darwin:arm64-macos x86_64-apple-darwin:x86_64-macos aarch64-unknown-linux-gnu:arm64-linux x86_64-unknown-linux-gnu:x86_64-linux))),unsupported-host) +WASI_SDK_DIR := $(abspath $(TOOLS_DIR))/wasi-sdk-$(WASI_SDK_VERSION) +WASI_SDK_PATH ?= $(WASI_SDK_DIR) +WASI_SDK := $(TOOLS_DIR)/.installed/wasi-sdk@$(WASI_SDK_VERSION) + +tools: $(WASI_SDK) + +$(WASI_SDK): + @mkdir -p $(WASI_SDK_DIR) $(@D) + @set -o pipefail; curl -fsSL https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-$(basename $(WASI_SDK_VERSION))/wasi-sdk-$(WASI_SDK_VERSION)-$(WASI_SDK_HOST).tar.gz | tar xz --strip-components 1 -C $(WASI_SDK_DIR) + @rm -f $(@D)/wasi-sdk@* + @touch $@ + +# a wasi-libc commit built for component model cooperative threads, in place of wasi-sdk's +# experimental sysroot, for fixes not yet in a wasi-sdk release, e.g. `WASI_LIBC_VERSION := +# f6e9006376e6f8e8f91ab84fc956be4e345588bc` for WebAssembly/wasi-libc#884. Empty uses wasi-sdk's. +WASI_LIBC_VERSION ?= +# the WASI 0.3 version the wasi-libc built from WASI_LIBC_VERSION imports, in place of the one it's +# generated for, e.g. `0.3.0` to match the WIT of the components. The WIT of the patch releases of +# WASI 0.3 is the same but for docs, only the versions in the generated bindings are replaced. +# Empty keeps wasi-libc's. +WASI_LIBC_WASI_VERSION ?= + +ifeq ($(WASI_LIBC_VERSION),) + +WASI_SYSROOT := $(WASI_SDK_PATH)/share/wasi-sysroot/experimental-coop-threads +WASI_LIBC := + +else + +WASI_LIBC_BUILD := $(WASI_LIBC_VERSION)$(if $(WASI_LIBC_WASI_VERSION),-wasi-$(WASI_LIBC_WASI_VERSION)) +WASI_SYSROOT := $(abspath $(TOOLS_DIR))/wasi-libc-$(WASI_LIBC_BUILD) +WASI_LIBC := $(TOOLS_DIR)/.installed/wasi-libc@$(WASI_LIBC_BUILD) + +# the bindings wasi-libc generates for WASI 0.3 from its WIT, checked in, and the version they're +# generated for +WASI_LIBC_WASIP3_BINDINGS := libc-bottom-half/headers/public/wasi/__generated_wasip3.h libc-bottom-half/sources/wasip3.c libc-bottom-half/sources/wasip3_component_type.o libc-bottom-half/crt/crt1-command.c +wasi_libc_wasip3_version = $$(sed -n 's/^set(wasip3-version \(.*\))$$/\1/p' $(1)/CMakeLists.txt) + +# cmake and ninja build wasi-libc, installed with the tools +CMAKE_VERSION := 4.4.4 +CMAKE_HOST := $(or $(word 2,$(subst :, ,$(filter $(shell rustc --print host-tuple):%,aarch64-apple-darwin:macos-universal x86_64-apple-darwin:macos-universal aarch64-unknown-linux-gnu:linux-aarch64 x86_64-unknown-linux-gnu:linux-x86_64))),unsupported-host) +CMAKE_DIR := $(abspath $(TOOLS_DIR))/cmake-$(CMAKE_VERSION) +# the macos archive holds an app bundle +CMAKE := $(CMAKE_DIR)/$(if $(filter macos-%,$(CMAKE_HOST)),CMake.app/Contents/)bin/cmake +CMAKE_INSTALLED := $(TOOLS_DIR)/.installed/cmake@$(CMAKE_VERSION) + +NINJA_VERSION := 1.13.2 +NINJA_HOST := $(or $(word 2,$(subst :, ,$(filter $(shell rustc --print host-tuple):%,aarch64-apple-darwin:mac x86_64-apple-darwin:mac aarch64-unknown-linux-gnu:linux-aarch64 x86_64-unknown-linux-gnu:linux))),unsupported-host) +NINJA_DIR := $(abspath $(TOOLS_DIR))/ninja-$(NINJA_VERSION) +NINJA := $(NINJA_DIR)/ninja +NINJA_INSTALLED := $(TOOLS_DIR)/.installed/ninja@$(NINJA_VERSION) + +tools: $(WASI_LIBC) + +$(CMAKE_INSTALLED): + @rm -rf $(CMAKE_DIR) + @mkdir -p $(CMAKE_DIR) $(@D) + @set -o pipefail; curl -fsSL https://github.com/Kitware/CMake/releases/download/v$(CMAKE_VERSION)/cmake-$(CMAKE_VERSION)-$(CMAKE_HOST).tar.gz | tar xz --strip-components 1 -C $(CMAKE_DIR) + @rm -f $(@D)/cmake@* + @touch $@ + +$(NINJA_INSTALLED): + @rm -rf $(NINJA_DIR) + @mkdir -p $(NINJA_DIR) $(@D) + @curl -fsSL https://github.com/ninja-build/ninja/releases/download/v$(NINJA_VERSION)/ninja-$(NINJA_HOST).zip -o $(NINJA_DIR)/ninja.zip + @unzip -q -o $(NINJA_DIR)/ninja.zip -d $(NINJA_DIR) + @rm $(NINJA_DIR)/ninja.zip + @rm -f $(@D)/ninja@* + @touch $@ + +# built with wasi-sdk's clang, static libraries only, rust links libc statically and wasi-sdk's +# compiler-rt builtins, which a shared libc links, aren't built for cooperative threads +$(WASI_LIBC): | $(WASI_SDK) $(CMAKE_INSTALLED) $(NINJA_INSTALLED) + @rm -rf $(WASI_SYSROOT) $(WASI_SYSROOT)-src + @mkdir -p $(WASI_SYSROOT)-src $(@D) + @set -o pipefail; curl -fsSL https://github.com/WebAssembly/wasi-libc/archive/$(WASI_LIBC_VERSION).tar.gz | tar xz --strip-components 1 -C $(WASI_SYSROOT)-src +ifneq ($(WASI_LIBC_WASI_VERSION),) + @# the type section of the bindings is binary, a version of the same length keeps it valid + @from=$(call wasi_libc_wasip3_version,$(WASI_SYSROOT)-src); to=$(WASI_LIBC_WASI_VERSION); \ + if [ -z "$$from" ] || [ $${#from} -ne $${#to} ]; then echo "can't replace WASI $$from of wasi-libc with $$to" >&2; exit 1; fi; \ + cd $(WASI_SYSROOT)-src && perl -0777 -pi -e "s/\@\Q$$from\E/\@$$to/g" $(WASI_LIBC_WASIP3_BINDINGS) +endif + $(CMAKE) -S $(WASI_SYSROOT)-src -B $(WASI_SYSROOT)-src/build -G Ninja -DCMAKE_MAKE_PROGRAM=$(NINJA) \ + -DCMAKE_C_COMPILER=$(WASI_SDK_PATH)/bin/clang -DCMAKE_AR=$(WASI_SDK_PATH)/bin/llvm-ar \ + -DCMAKE_NM=$(WASI_SDK_PATH)/bin/llvm-nm -DCMAKE_RANLIB=$(WASI_SDK_PATH)/bin/llvm-ranlib \ + -DTARGET_TRIPLE=wasm32-wasip3 -DENABLE_COOP_THREADS=ON -DBUILD_SHARED=OFF \ + -DBUILTINS_LIB=$$(ls $(WASI_SDK_PATH)/lib/clang/*/lib/wasm32-unknown-wasip3/libclang_rt.builtins.a) \ + -DCMAKE_INSTALL_PREFIX=$(WASI_SYSROOT) + $(NINJA) -C $(WASI_SYSROOT)-src/build install + @rm -rf $(WASI_SYSROOT)-src + @rm -f $(@D)/wasi-libc@* + @touch $@ + +endif + +endif diff --git a/build/tools/Cargo.toml b/build/tools/Cargo.toml new file mode 100644 index 0000000..527c4f1 --- /dev/null +++ b/build/tools/Cargo.toml @@ -0,0 +1,55 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# The versions of the cli tools the build provides, installed by `make tools` with cargo binstall. +# +# This package is never built, it lists the tools as dependencies so dependabot bumps them in +# componentized/build. Each tool is pinned to an exact version with `=`, the Makefile installs that +# version. A repository overrides a tool in its own tools/Cargo.toml, with a newer version, or builds +# it from its workspace with LOCAL_TOOLS, and adds the tools only it uses there, see build/tools.mk. +[package] +name = "build-tools" +version = "0.0.0" +edition = "2024" +license = "Apache-2.0" +publish = false + +[lib] +path = "lib.rs" + +# the binaries each tool installs, the Makefile runs each by path from a variable named after it, +# e.g. `$(WASM_TOOLS)` for `wasm-tools` +[package.metadata.bins] +cargo-binstall = ["cargo-binstall"] +cargo-cyclonedx = ["cargo-cyclonedx"] +componentized-build-cli = ["componentized-build"] +componentized-constants-cli = ["constants"] +componentized-static-config-cli = ["static-config"] +wac-cli = ["wac"] +wasm-opt = ["wasm-opt"] +wasm-tools = ["wasm-tools"] +wkg = ["wkg"] + +# the arguments of the binaries that print their shell completions, the shell's name is appended, +# e.g. `wasm-tools completion bash`, registered by build/scripts/completions.sh. A binary installed +# other than with cargo is listed too, e.g. cosign, see build/tools.mk. A repository adds its own +# in its tools/Cargo.toml, or overrides one with `[]`, e.g. for a tool it builds without them. +[package.metadata.completions] +cargo-binstall = ["--completions"] +componentized-build = ["completions"] +cosign = ["completion"] +wasm-tools = ["completion"] + +[dependencies] +cargo-binstall = "=1.27.0" +cargo-cyclonedx = "=0.5.10" +componentized-build-cli = "=0.1.6" +componentized-constants-cli = "=0.2.0" +componentized-static-config-cli = "=0.3.0" +wac-cli = "=0.12.0" +wasm-opt = "=0.116.1" +wasm-tools = "=1.263.0" +wkg = "=0.16.2" + +# not a member of the repository's workspace +[workspace] diff --git a/build/tools/lib.rs b/build/tools/lib.rs new file mode 100644 index 0000000..11df9c8 --- /dev/null +++ b/build/tools/lib.rs @@ -0,0 +1,4 @@ +// Managed by componentized/build and synced into each repository by `make update-build`. Change it +// in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +//! Never built, see `Cargo.toml`. diff --git a/build/wit.mk b/build/wit.mk new file mode 100644 index 0000000..c334e7c --- /dev/null +++ b/build/wit.mk @@ -0,0 +1,60 @@ +# Managed by componentized/build and synced into each repository by `make update-build`. Change it +# in https://github.com/componentized/build, `make check-build` fails when a copy is changed. + +# a path relative to the root of the repository, e.g. `wit` for `components/../wit` +relpath = $(if $(filter $(CURDIR),$(abspath $(1))),.,$(patsubst $(CURDIR)/%,%,$(abspath $(1)))) + +# directories with a wkg.toml, each fetches the dependencies of its wit directory into wit/deps, +# e.g. `.` and `components` +WKG_DIRS := $(sort $(patsubst ./%,%,$(patsubst %/,%,$(dir $(shell find . -name wkg.toml -not -path './target/*' -not -path '*/wit/deps/*'))))) + +# the wit/deps directory of a directory with a wkg.toml, e.g. `wit/deps` for `.` +wit_deps = $(patsubst ./%,%,$(1)/wit/deps) + +WIT_DEPS := $(foreach dir,$(WKG_DIRS),$(call wit_deps,$(dir))) + +# the prerequisites of what's made from WIT paths, relative to the repository, e.g. `components/wit`: +# a directory's deps, when a wkg.toml beside the directory fetches them, otherwise its files, e.g. a +# directory without a wkg.toml, implicitly up to date, or one updated by another tool. A path that +# doesn't exist has none. +wit_prerequisites = $(foreach path,$(1),$(if $(filter $(path)/deps,$(WIT_DEPS)),$(path)/deps,$(shell find $(path) -type f 2> /dev/null))) + +# the cache wkg fetches packages into, in place of the system cache. wkg caches a package by its +# version, so a dev version fetched again would come from the cache, stale, rather than the registry. +# Exported for every wkg the build runs, absolute as wkg also runs in other directories, e.g. +# `cd components && wkg fetch`. `make clean-wit` removes it. +export WKG_CACHE_DIR := $(abspath target/wkg-cache) + +# runs wkg with the arguments in the directory with a wkg.toml, e.g. `$(call wkg,components,fetch)`. +# wkg rewrites wkg.lock even when nothing changed, which would leave everything made from the lock +# looking out of date, so the lock is put back as it was, with its time, when its content is unchanged. A +# missing lock is tolerated, wkg writes it. +wkg = if [ -f $(1)/wkg.lock ]; then cp -p $(1)/wkg.lock $(1)/wkg.lock.orig; fi && \ + (cd $(1) && $(WKG) $(2)); status=$$?; \ + if [ -f $(1)/wkg.lock.orig ]; then \ + if cmp -s $(1)/wkg.lock.orig $(1)/wkg.lock; then mv $(1)/wkg.lock.orig $(1)/wkg.lock; else rm $(1)/wkg.lock.orig; fi; \ + fi; \ + exit $$status + +.PHONY: clean-wit ## Remove the fetched wit dependencies and the wkg cache, fetched again by `make wit` +clean-wit: + rm -rf $(WIT_DEPS) $(WKG_CACHE_DIR) + +.PHONY: wit ## Fetch the wit dependencies of each wkg.toml into its wit/deps +wit: $(WIT_DEPS) + +define FETCH_WIT + +# the dependencies are touched after fetching, newer than the lock they were fetched with even when +# the fetch changed nothing in them +# +# a package overridden with a local path, e.g. `{ path = "../wit" }`, has its dependencies fetched first, +# an override without dependencies of its own is skipped, e.g. `{ path = "./wit/overrides/wasi-muppets" }`. +# The lock is optional, the fetch writes it. +$(call wit_deps,$1): $1/wkg.toml $(wildcard $1/wkg.lock) $(shell find $1/wit -type f -name "*.wit" -not -path "*/deps/*") $(filter $(WIT_DEPS),$(foreach path,$(shell sed -n 's/.*path *= *"\(.*\)".*/\1/p' $1/wkg.toml),$(call relpath,$1/$(path))/deps)) | $(call tool,wkg) + $$(call wkg,$1,fetch) + @touch $(call wit_deps,$1) + +endef + +$(foreach dir,$(WKG_DIRS),$(eval $(call FETCH_WIT,$(dir)))) diff --git a/components/Cargo.lock b/components/Cargo.lock deleted file mode 100644 index fb0d87f..0000000 --- a/components/Cargo.lock +++ /dev/null @@ -1,935 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "clap" -version = "4.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "composable-factory" -version = "0.7.0" -source = "git+https://github.com/modulewise/composable-factory?branch=main#ba6b2ad09c4dc9489797989998b0dd1f73cb7247" -dependencies = [ - "anyhow", - "indexmap", - "serde_json", - "wasm-encoder 0.263.0", - "wasmparser 0.263.0", - "wit-component 0.263.0", - "wit-parser 0.263.0", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "function-adapter" -version = "0.3.1" -dependencies = [ - "anyhow", - "clap", - "composable-factory", - "wasm-encoder 0.263.0", - "wit-parser 0.263.0", -] - -[[package]] -name = "function-factory" -version = "0.5.1" -dependencies = [ - "composable-factory", - "function-adapter", - "wit-bindgen", -] - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-sink", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -dependencies = [ - "foldhash", - "serde", - "serde_core", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "http-client" -version = "0.4.0" -dependencies = [ - "url", - "wit-bindgen", -] - -[[package]] -name = "icu_collections" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" - -[[package]] -name = "icu_properties" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" - -[[package]] -name = "icu_provider" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", - "serde", - "serde_core", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "macro-string" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - -[[package]] -name = "prettyplease" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" -dependencies = [ - "proc-macro2", - "syn", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "foldhash", - "indexmap", - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinystr" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" -dependencies = [ - "utf_types", -] - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "utf_types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" - -[[package]] -name = "wasm-encoder" -version = "0.262.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" -dependencies = [ - "leb128fmt", - "wasmparser 0.262.0", -] - -[[package]] -name = "wasm-encoder" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" -dependencies = [ - "leb128fmt", - "wasmparser 0.263.0", -] - -[[package]] -name = "wasm-metadata" -version = "0.262.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder 0.262.0", - "wasmparser 0.262.0", -] - -[[package]] -name = "wasm-metadata" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8997a297f42413bee775d73a750def062ee1ec4a6d904703cb08046c0296774d" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder 0.263.0", - "wasmparser 0.263.0", -] - -[[package]] -name = "wasmparser" -version = "0.262.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" -dependencies = [ - "bitflags", - "hashbrown", - "indexmap", - "semver", -] - -[[package]] -name = "wasmparser" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" -dependencies = [ - "bitflags", - "hashbrown", - "indexmap", - "semver", - "serde", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "wit-bindgen" -version = "0.63.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" -dependencies = [ - "bitflags", - "futures", - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.63.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" -dependencies = [ - "anyhow", - "heck", - "wit-parser 0.262.0", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.63.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn", - "wasm-metadata 0.262.0", - "wit-bindgen-core", - "wit-component 0.262.0", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.63.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" -dependencies = [ - "anyhow", - "macro-string", - "prettyplease", - "proc-macro2", - "quote", - "syn", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.262.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder 0.262.0", - "wasm-metadata 0.262.0", - "wasmparser 0.262.0", - "wit-parser 0.262.0", -] - -[[package]] -name = "wit-component" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4189bd180353b942b788715519dff886517b540e648c6f6e5129f57429945bf7" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder 0.263.0", - "wasm-metadata 0.263.0", - "wasmparser 0.263.0", - "wit-parser 0.263.0", -] - -[[package]] -name = "wit-parser" -version = "0.262.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" -dependencies = [ - "anyhow", - "hashbrown", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-ident", - "wasmparser 0.262.0", -] - -[[package]] -name = "wit-parser" -version = "0.263.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "874d6ce9db4261cb66980ab14f3da066b24292497b6f46f988c0d1b9b27913f3" -dependencies = [ - "anyhow", - "hashbrown", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-ident", - "wasmparser 0.263.0", -] - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "yoke" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/components/Cargo.toml b/components/Cargo.toml deleted file mode 100644 index 932c24c..0000000 --- a/components/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[workspace] -members = [ - "function-factory", - "http/client", -] -resolver = "3" - -[workspace.dependencies] -wit-bindgen = "0.63" diff --git a/components/build.sh b/components/build.sh deleted file mode 100755 index b850441..0000000 --- a/components/build.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh - -PROJECTS=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[].name') - -for project in $PROJECTS; do - echo "Building $project..." - - target=wasm32-unknown-unknown - cargo build -p "$project" --target $target --release - - cargo_name=$(echo "$project" | tr '-' '_') - core_wasm="target/${target}/release/${cargo_name}.wasm" - wasm-tools component new "$core_wasm" -o "lib/${project}.wasm" - echo " -> lib/${project}.wasm" -done diff --git a/components/http-client/README.md b/components/http-client/README.md new file mode 100644 index 0000000..f4ef309 --- /dev/null +++ b/components/http-client/README.md @@ -0,0 +1,3 @@ +# http-client + +`componentized:http-client` component. diff --git a/components/http-client/http-client.wkg b/components/http-client/http-client.wkg new file mode 100644 index 0000000..2134461 --- /dev/null +++ b/components/http-client/http-client.wkg @@ -0,0 +1,2 @@ +ghcr.io/componentized/http/client:0.1.0@sha256:17dbb9bbd31e700bf690fc4eeb9cb1c8f920f87eb404fd3744d48de6020ee330 +ghcr.io/componentized/http/client:0.1.0_debug@sha256:0d1cbb52566e781385526c2656b734e44e53174add2897ea588a761b587fc906 diff --git a/components/http/README.md b/components/http/README.md deleted file mode 100644 index ab081a2..0000000 --- a/components/http/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# composable:http - -HTTP client support, including a WIT definition and a Wasm Component. - -(for hosting Wasm Components behind an HTTP server, see [`crates/http-server`](../../crates/http-server)) - -## The `composable:http/client` Interface - -Every function is `async` and returns `result`. -Request and response bodies are both `stream`. - -Functions that accept a request body: - -- `post(url, headers, body, options)` -- `put(url, headers, body, options)` -- `patch(url, headers, body, options)` -- `query(url, headers, body, options)` - -Functions without a request body: - -- `get(url, headers, options)` -- `delete(url, headers, options)` -- `head(url, headers, options)` -- `options(url, headers, options)` -- `trace(url, headers, options)` - -And each delegates to the underlying request function, whose `body` is optional -since its `method` is a parameter: -`request(method, url, headers, body, options)` - -An `http-response` carries `status` and `headers`. The response `body` streams, and `trailers` -resolve once the body stream is fully consumed. - -The `options` arg supplies per-request timeouts (`connect`, `first-byte`, `between-bytes`, all in -milliseconds). Any field left `none` falls through to the host default. - -See [`wit/package.wit`](wit/package.wit) for the full type definitions. - -## The `http-client` World - -- exports `composable:http/client` -- imports `wasi:http/client@0.3.0` - -That import can be satisfied by the `wasi:http` Capability which is available in the core runtime. - -## The `http-client` Component - -Implementation of the `http-client` world, with source code in the [client](client/) sub-directory. diff --git a/components/http/client/Cargo.toml b/components/http/client/Cargo.toml deleted file mode 100644 index 6f1fc9b..0000000 --- a/components/http/client/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "http-client" -version = "0.4.0" -edition = "2024" -description = "HTTP client component implementing the composable:http/client interface" -homepage = "https://github.com/modulewise/composable-runtime/tree/main/components/http" -license = "Apache-2.0" -repository = "https://github.com/modulewise/composable-runtime" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -url = "2.5" -wit-bindgen = { workspace = true, features = ["async-spawn"] } diff --git a/components/http/client/src/lib.rs b/components/http/client/src/lib.rs deleted file mode 100644 index 0a4dec6..0000000 --- a/components/http/client/src/lib.rs +++ /dev/null @@ -1,245 +0,0 @@ -use url::Url; - -wit_bindgen::generate!({ - path: "../wit", - generate_all, -}); - -use exports::composable::http::client::{ErrorCode, Guest, HttpResponse, Method, RequestOptions}; - -use wasi::http::types::{ - ErrorCode as WasiErrorCode, Fields, Method as WasiMethod, Request as WasiRequest, - RequestOptions as WasiRequestOptions, Response as WasiResponse, Scheme, Trailers, -}; -use wit_bindgen::rt::async_support::{FutureReader, StreamReader}; - -struct HttpClient; - -impl HttpClient { - async fn request( - method: WasiMethod, - url: String, - headers: Vec<(String, String)>, - body: Option>, - options: Option, - ) -> Result { - let request_headers = Fields::new(); - for (name, value) in &headers { - request_headers - .append(name, value.as_bytes()) - .map_err(|e| err(format!("Invalid request header {name:?}: {e:?}")))?; - } - - let parsed = Url::parse(&url).map_err(|e| err(format!("Invalid URL: {e}")))?; - let scheme = match parsed.scheme() { - "http" => Scheme::Http, - "https" => Scheme::Https, - other => return Err(err(format!("Unsupported URL scheme: {other}"))), - }; - let host = parsed - .host_str() - .ok_or_else(|| err("URL is missing a host".to_string()))?; - let authority = match parsed.port() { - Some(port) => format!("{host}:{port}"), - None => host.to_string(), - }; - let path_with_query = match parsed.query() { - Some(q) => format!("{}?{q}", parsed.path()), - None => parsed.path().to_string(), - }; - - let (trailers_tx, trailers_rx) = wit_future::new(|| Ok(None)); - trailers_tx.write(Ok(None)); - - let wasi_options = options.map(wasi_request_options).transpose()?; - let (request, send_result) = - WasiRequest::new(request_headers, body, trailers_rx, wasi_options); - request - .set_method(&method) - .map_err(|()| err("Failed to set request method".to_string()))?; - request - .set_scheme(Some(&scheme)) - .map_err(|()| err("Failed to set request scheme".to_string()))?; - request - .set_authority(Some(&authority)) - .map_err(|()| err("Failed to set request authority".to_string()))?; - request - .set_path_with_query(Some(&path_with_query)) - .map_err(|()| err("Failed to set request path".to_string()))?; - - let response = wasi::http::client::send(request) - .await - .map_err(|e| err(format!("HTTP request failed: {e:?}")))?; - - let status = response.get_status_code(); - let headers = read_fields(&response.get_headers()); - - let (body_stream, wasi_trailers) = WasiResponse::consume_body(response, send_result); - - Ok(HttpResponse { - status, - headers, - body: body_stream, - trailers: map_trailers(wasi_trailers), - }) - } -} - -fn err(message: String) -> ErrorCode { - ErrorCode::Other(Some(message)) -} - -fn read_fields(fields: &Fields) -> Vec<(String, String)> { - fields - .copy_all() - .into_iter() - .map(|(k, v)| (k, v.into_iter().map(|b| b as char).collect())) - .collect() -} - -fn map_trailers( - wasi: FutureReader, WasiErrorCode>>, -) -> FutureReader, ErrorCode>> { - let (tx, rx) = wit_future::new(|| Ok(Vec::new())); - wit_bindgen::rt::async_support::spawn_local(async move { - let resolved = match wasi.await { - Ok(Some(t)) => Ok(read_fields(&t)), - Ok(None) => Ok(Vec::new()), - Err(e) => Err(err(format!("wasi:http error: {e:?}"))), - }; - tx.write(resolved); - }); - rx -} - -fn wasi_request_options(opts: RequestOptions) -> Result { - let r = WasiRequestOptions::new(); - if let Some(ms) = opts.connect_timeout_ms { - r.set_connect_timeout(Some(ms_to_ns(ms))) - .map_err(|e| err(format!("connect-timeout: {e:?}")))?; - } - if let Some(ms) = opts.first_byte_timeout_ms { - r.set_first_byte_timeout(Some(ms_to_ns(ms))) - .map_err(|e| err(format!("first-byte-timeout: {e:?}")))?; - } - if let Some(ms) = opts.between_bytes_timeout_ms { - r.set_between_bytes_timeout(Some(ms_to_ns(ms))) - .map_err(|e| err(format!("between-bytes-timeout: {e:?}")))?; - } - Ok(r) -} - -fn ms_to_ns(ms: u32) -> u64 { - u64::from(ms) * 1_000_000 -} - -fn to_wasi_method(method: Method) -> WasiMethod { - match method { - Method::Get => WasiMethod::Get, - Method::Post => WasiMethod::Post, - Method::Put => WasiMethod::Put, - Method::Delete => WasiMethod::Delete, - Method::Patch => WasiMethod::Patch, - Method::Head => WasiMethod::Head, - Method::Options => WasiMethod::Options, - Method::Trace => WasiMethod::Trace, - Method::Query => WasiMethod::Other("QUERY".to_string()), - } -} - -impl Guest for HttpClient { - async fn request( - method: Method, - url: String, - headers: Vec<(String, String)>, - body: Option>, - options: Option, - ) -> Result { - Self::request(to_wasi_method(method), url, headers, body, options).await - } - - async fn get( - url: String, - headers: Vec<(String, String)>, - options: Option, - ) -> Result { - Self::request(WasiMethod::Get, url, headers, None, options).await - } - - async fn post( - url: String, - headers: Vec<(String, String)>, - body: StreamReader, - options: Option, - ) -> Result { - Self::request(WasiMethod::Post, url, headers, Some(body), options).await - } - - async fn put( - url: String, - headers: Vec<(String, String)>, - body: StreamReader, - options: Option, - ) -> Result { - Self::request(WasiMethod::Put, url, headers, Some(body), options).await - } - - async fn delete( - url: String, - headers: Vec<(String, String)>, - options: Option, - ) -> Result { - Self::request(WasiMethod::Delete, url, headers, None, options).await - } - - async fn patch( - url: String, - headers: Vec<(String, String)>, - body: StreamReader, - options: Option, - ) -> Result { - Self::request(WasiMethod::Patch, url, headers, Some(body), options).await - } - - async fn head( - url: String, - headers: Vec<(String, String)>, - options: Option, - ) -> Result { - Self::request(WasiMethod::Head, url, headers, None, options).await - } - - async fn options( - url: String, - headers: Vec<(String, String)>, - options: Option, - ) -> Result { - Self::request(WasiMethod::Options, url, headers, None, options).await - } - - async fn trace( - url: String, - headers: Vec<(String, String)>, - options: Option, - ) -> Result { - Self::request(WasiMethod::Trace, url, headers, None, options).await - } - - async fn query( - url: String, - headers: Vec<(String, String)>, - body: StreamReader, - options: Option, - ) -> Result { - Self::request( - to_wasi_method(Method::Query), - url, - headers, - Some(body), - options, - ) - .await - } -} - -export!(HttpClient); diff --git a/components/http/wit/deps/wasi-cli-0.3.0/package.wit b/components/http/wit/deps/wasi-cli-0.3.0/package.wit deleted file mode 100644 index d0b02bb..0000000 --- a/components/http/wit/deps/wasi-cli-0.3.0/package.wit +++ /dev/null @@ -1,28 +0,0 @@ -package wasi:cli@0.3.0; - -interface types { - enum error-code { - io, - illegal-byte-sequence, - pipe, - } -} - -interface stdout { - use types.{error-code}; - - write-via-stream: func(data: stream) -> future>; -} - -interface stderr { - use types.{error-code}; - - write-via-stream: func(data: stream) -> future>; -} - -interface stdin { - use types.{error-code}; - - read-via-stream: func() -> tuple, future>>; -} - diff --git a/components/http/wit/deps/wasi-clocks-0.3.0/package.wit b/components/http/wit/deps/wasi-clocks-0.3.0/package.wit deleted file mode 100644 index 871adf0..0000000 --- a/components/http/wit/deps/wasi-clocks-0.3.0/package.wit +++ /dev/null @@ -1,43 +0,0 @@ -package wasi:clocks@0.3.0; - -interface types { - type duration = u64; -} - -interface monotonic-clock { - use types.{duration}; - - type mark = u64; - - now: func() -> mark; - - get-resolution: func() -> duration; - - wait-until: async func(when: mark); - - wait-for: async func(how-long: duration); -} - -interface system-clock { - use types.{duration}; - - record instant { - seconds: s64, - nanoseconds: u32, - } - - now: func() -> instant; - - get-resolution: func() -> duration; -} - -interface timezone { - use system-clock.{instant}; - - iana-id: func() -> option; - - utc-offset: func(when: instant) -> option; - - to-debug-string: func() -> string; -} - diff --git a/components/http/wit/deps/wasi-http-0.3.0/package.wit b/components/http/wit/deps/wasi-http-0.3.0/package.wit deleted file mode 100644 index 08458f7..0000000 --- a/components/http/wit/deps/wasi-http-0.3.0/package.wit +++ /dev/null @@ -1,509 +0,0 @@ -package wasi:http@0.3.0; - -/// This interface defines all of the types and methods for implementing HTTP -/// Requests and Responses, as well as their headers, trailers, and bodies. -@since(version = 0.3.0) -interface types { - use wasi:clocks/types@0.3.0.{duration}; - - /// This type corresponds to HTTP standard Methods. - @since(version = 0.3.0) - variant method { - get, - head, - post, - put, - delete, - connect, - options, - trace, - patch, - other(string), - } - - /// This type corresponds to HTTP standard Related Schemes. - @since(version = 0.3.0) - variant scheme { - HTTP, - HTTPS, - other(string), - } - - /// Defines the case payload type for `DNS-error` above: - @since(version = 0.3.0) - record DNS-error-payload { - rcode: option, - info-code: option, - } - - /// Defines the case payload type for `TLS-alert-received` above: - @since(version = 0.3.0) - record TLS-alert-received-payload { - alert-id: option, - alert-message: option, - } - - /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - @since(version = 0.3.0) - record field-size-payload { - field-name: option, - field-size: option, - } - - /// These cases are inspired by the IANA HTTP Proxy Error Types: - /// - @since(version = 0.3.0) - variant error-code { - DNS-timeout, - DNS-error(DNS-error-payload), - destination-not-found, - destination-unavailable, - destination-IP-prohibited, - destination-IP-unroutable, - connection-refused, - connection-terminated, - connection-timeout, - connection-read-timeout, - connection-write-timeout, - connection-limit-reached, - TLS-protocol-error, - TLS-certificate-error, - TLS-alert-received(TLS-alert-received-payload), - HTTP-request-denied, - HTTP-request-length-required, - HTTP-request-body-size(option), - HTTP-request-method-invalid, - HTTP-request-URI-invalid, - HTTP-request-URI-too-long, - HTTP-request-header-section-size(option), - HTTP-request-header-size(option), - HTTP-request-trailer-section-size(option), - HTTP-request-trailer-size(field-size-payload), - HTTP-response-incomplete, - HTTP-response-header-section-size(option), - HTTP-response-header-size(field-size-payload), - HTTP-response-body-size(option), - HTTP-response-trailer-section-size(option), - HTTP-response-trailer-size(field-size-payload), - HTTP-response-transfer-coding(option), - HTTP-response-content-coding(option), - HTTP-response-timeout, - HTTP-upgrade-failed, - HTTP-protocol-error, - loop-detected, - configuration-error, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. It also includes an optional string for an - /// unstructured description of the error. Users should not depend on the - /// string for diagnosing errors, as it's not required to be consistent - /// between implementations. - internal-error(option), - } - - /// This type enumerates the different kinds of errors that may occur when - /// setting or appending to a `fields` resource. - @since(version = 0.3.0) - variant header-error { - /// This error indicates that a `field-name` or `field-value` was - /// syntactically invalid when used with an operation that sets headers in a - /// `fields`. - invalid-syntax, - /// This error indicates that a forbidden `field-name` was used when trying - /// to set a header in a `fields`. - forbidden, - /// This error indicates that the operation on the `fields` was not - /// permitted because the fields are immutable. - immutable, - /// This error indicates that the operation would exceed an - /// implementation-defined limit on field sizes. This may apply to - /// an individual `field-value`, a single `field-name` plus all its - /// values, or the total aggregate size of all fields. - size-exceeded, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. Implementations can use this to extend the error - /// type without breaking existing code. It also includes an optional - /// string for an unstructured description of the error. Users should not - /// depend on the string for diagnosing errors, as it's not required to be - /// consistent between implementations. - other(option), - } - - /// This type enumerates the different kinds of errors that may occur when - /// setting fields of a `request-options` resource. - @since(version = 0.3.0) - variant request-options-error { - /// Indicates the specified field is not supported by this implementation. - not-supported, - /// Indicates that the operation on the `request-options` was not permitted - /// because it is immutable. - immutable, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. Implementations can use this to extend the error - /// type without breaking existing code. It also includes an optional - /// string for an unstructured description of the error. Users should not - /// depend on the string for diagnosing errors, as it's not required to be - /// consistent between implementations. - other(option), - } - - /// Field names are always strings. - /// - /// Field names should always be treated as case insensitive by the `fields` - /// resource for the purposes of equality checking. - @since(version = 0.3.0) - type field-name = string; - - /// Field values should always be ASCII strings. However, in - /// reality, HTTP implementations often have to interpret malformed values, - /// so they are provided as a list of bytes. - @since(version = 0.3.0) - type field-value = list; - - /// This following block defines the `fields` resource which corresponds to - /// HTTP standard Fields. Fields are a common representation used for both - /// Headers and Trailers. - /// - /// A `fields` may be mutable or immutable. A `fields` created using the - /// constructor, `from-list`, or `clone` will be mutable, but a `fields` - /// resource given by other means (including, but not limited to, - /// `request.headers`) might be be immutable. In an immutable fields, the - /// `set`, `append`, and `delete` operations will fail with - /// `header-error.immutable`. - /// - /// A `fields` resource should store `field-name`s and `field-value`s in their - /// original casing used to construct or mutate the `fields` resource. The `fields` - /// resource should use that original casing when serializing the fields for - /// transport or when returning them from a method. - /// - /// Implementations may impose limits on individual field values and on total - /// aggregate field section size. Operations that would exceed these limits - /// fail with `header-error.size-exceeded` - @since(version = 0.3.0) - resource fields { - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - constructor(); - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each name-value pair in the Fields. Names - /// which have multiple values are represented by multiple entries in this - /// list with the same name. - /// - /// The tuple is a pair of the field name, represented as a string, and - /// Value, represented as a list of bytes. In a valid Fields, all names - /// and values are valid UTF-8 strings. However, values are not always - /// well-formed, so they are represented as a raw list of bytes. - /// - /// An error result will be returned if any header or value was - /// syntactically invalid, if a header was forbidden, or if the - /// entries would exceed an implementation size limit. - from-list: static func(entries: list>) -> result; - /// Get all of the values corresponding to a name. If the name is not present - /// in this `fields`, an empty list is returned. However, if the name is - /// present but empty, this is represented by a list with one or more - /// empty field-values present. - get: func(name: field-name) -> list; - /// Returns `true` when the name is present in this `fields`. If the name is - /// syntactically invalid, `false` is returned. - has: func(name: field-name) -> bool; - /// Set all of the values for a name. Clears any existing values for that - /// name, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.size-exceeded` if the name or values would - /// exceed an implementation-defined size limit. - set: func(name: field-name, value: list) -> result<_, header-error>; - /// Delete all values for a name. Does nothing if no values for the name - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - delete: func(name: field-name) -> result<_, header-error>; - /// Delete all values for a name. Does nothing if no values for the name - /// exist. - /// - /// Returns all values previously corresponding to the name, if any. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - get-and-delete: func(name: field-name) -> result, header-error>; - /// Append a value for a name. Does not change or delete any existing - /// values for that name. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.size-exceeded` if the value would exceed - /// an implementation-defined size limit. - append: func(name: field-name, value: field-value) -> result<_, header-error>; - /// Retrieve the full set of names and values in the Fields. Like the - /// constructor, the list represents each name-value pair. - /// - /// The outer list represents each name-value pair in the Fields. Names - /// which have multiple values are represented by multiple entries in this - /// list with the same name. - /// - /// The names and values are always returned in the original casing and in - /// the order in which they will be serialized for transport. - copy-all: func() -> list>; - /// Make a deep copy of the Fields. Equivalent in behavior to calling the - /// `fields` constructor on the return value of `copy-all`. The resulting - /// `fields` is mutable. - clone: func() -> fields; - } - - /// Headers is an alias for Fields. - @since(version = 0.3.0) - type headers = fields; - - /// Trailers is an alias for Fields. - @since(version = 0.3.0) - type trailers = fields; - - /// Represents an HTTP Request. - @since(version = 0.3.0) - resource request { - /// Construct a new `request` with a default `method` of `GET`, and - /// `none` values for `path-with-query`, `scheme`, and `authority`. - /// - /// `headers` is the HTTP Headers for the Request. - /// - /// `contents` is the optional body content stream with `none` - /// representing a zero-length content stream. - /// Once it is closed, `trailers` future must resolve to a result. - /// If `trailers` resolves to an error, underlying connection - /// will be closed immediately. - /// - /// `options` is optional `request-options` resource to be used - /// if the request is sent over a network connection. - /// - /// It is possible to construct, or manipulate with the accessor functions - /// below, a `request` with an invalid combination of `scheme` - /// and `authority`, or `headers` which are not permitted to be sent. - /// It is the obligation of the `handler.handle` implementation - /// to reject invalid constructions of `request`. - /// - /// The returned future resolves to result of transmission of this request. - new: static func(headers: headers, contents: option>, trailers: future, error-code>>, options: option) -> tuple>>; - /// Get the Method for the Request. - get-method: func() -> method; - /// Set the Method for the Request. Fails if the string present in a - /// `method.other` argument is not a syntactically valid method. - set-method: func(method: method) -> result; - /// Get the combination of the HTTP Path and Query for the Request. When - /// `none`, this represents an empty Path and empty Query. - get-path-with-query: func() -> option; - /// Set the combination of the HTTP Path and Query for the Request. When - /// `none`, this represents an empty Path and empty Query. Fails is the - /// string given is not a syntactically valid path and query uri component. - set-path-with-query: func(path-with-query: option) -> result; - /// Get the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. - get-scheme: func() -> option; - /// Set the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. Fails if the - /// string given is not a syntactically valid uri scheme. - set-scheme: func(scheme: option) -> result; - /// Get the authority of the Request's target URI. A value of `none` may be used - /// with Related Schemes which do not require an authority. The HTTP and - /// HTTPS schemes always require an authority. - get-authority: func() -> option; - /// Set the authority of the Request's target URI. A value of `none` may be used - /// with Related Schemes which do not require an authority. The HTTP and - /// HTTPS schemes always require an authority. Fails if the string given is - /// not a syntactically valid URI authority. - set-authority: func(authority: option) -> result; - /// Get the `request-options` to be associated with this request - /// - /// The returned `request-options` resource is immutable: `set-*` operations - /// will fail if invoked. - /// - /// This `request-options` resource is a child: it must be dropped before - /// the parent `request` is dropped, or its ownership is transferred to - /// another component by e.g. `handler.handle`. - get-options: func() -> option; - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - get-headers: func() -> headers; - /// Get body of the Request. - /// - /// Stream returned by this method represents the contents of the body. - /// Once the stream is reported as closed, callers should await the returned - /// future to determine whether the body was received successfully. - /// The future will only resolve after the stream is reported as closed. - /// - /// This function takes a `res` future as a parameter, which can be used to - /// communicate an error in handling of the request. - /// - /// Note that function will move the `request`, but references to headers or - /// request options acquired from it previously will remain valid. - consume-body: static func(this: request, res: future>) -> tuple, future, error-code>>>; - } - - /// Parameters for making an HTTP Request. Each of these parameters is - /// currently an optional timeout applicable to the transport layer of the - /// HTTP protocol. - /// - /// These timeouts are separate from any the user may use to bound an - /// asynchronous call. - @since(version = 0.3.0) - resource request-options { - /// Construct a default `request-options` value. - constructor(); - /// The timeout for the initial connect to the HTTP Server. - get-connect-timeout: func() -> option; - /// Set the timeout for the initial connect to the HTTP Server. An error - /// return value indicates that this timeout is not supported or that this - /// handle is immutable. - set-connect-timeout: func(duration: option) -> result<_, request-options-error>; - /// The timeout for receiving the first byte of the Response body. - get-first-byte-timeout: func() -> option; - /// Set the timeout for receiving the first byte of the Response body. An - /// error return value indicates that this timeout is not supported or that - /// this handle is immutable. - set-first-byte-timeout: func(duration: option) -> result<_, request-options-error>; - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - get-between-bytes-timeout: func() -> option; - /// Set the timeout for receiving subsequent chunks of bytes in the Response - /// body stream. An error return value indicates that this timeout is not - /// supported or that this handle is immutable. - set-between-bytes-timeout: func(duration: option) -> result<_, request-options-error>; - /// Make a deep copy of the `request-options`. - /// The resulting `request-options` is mutable. - clone: func() -> request-options; - } - - /// This type corresponds to the HTTP standard Status Code. - @since(version = 0.3.0) - type status-code = u16; - - /// Represents an HTTP Response. - @since(version = 0.3.0) - resource response { - /// Construct a new `response`, with a default `status-code` of `200`. - /// If a different `status-code` is needed, it must be set via the - /// `set-status-code` method. - /// - /// `headers` is the HTTP Headers for the Response. - /// - /// `contents` is the optional body content stream with `none` - /// representing a zero-length content stream. - /// Once it is closed, `trailers` future must resolve to a result. - /// If `trailers` resolves to an error, underlying connection - /// will be closed immediately. - /// - /// The returned future resolves to result of transmission of this response. - new: static func(headers: headers, contents: option>, trailers: future, error-code>>) -> tuple>>; - /// Get the HTTP Status Code for the Response. - get-status-code: func() -> status-code; - /// Set the HTTP Status Code for the Response. Fails if the status-code - /// given is not a valid http status code. - set-status-code: func(status-code: status-code) -> result; - /// Get the headers associated with the Response. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - get-headers: func() -> headers; - /// Get body of the Response. - /// - /// Stream returned by this method represents the contents of the body. - /// Once the stream is reported as closed, callers should await the returned - /// future to determine whether the body was received successfully. - /// The future will only resolve after the stream is reported as closed. - /// - /// This function takes a `res` future as a parameter, which can be used to - /// communicate an error in handling of the response. - /// - /// Note that function will move the `response`, but references to headers - /// acquired from it previously will remain valid. - consume-body: static func(this: response, res: future>) -> tuple, future, error-code>>>; - } -} - -/// This interface defines a handler of HTTP Requests. -/// -/// In a `wasi:http/service` this interface is exported to respond to an -/// incoming HTTP Request with a Response. -/// -/// In `wasi:http/middleware` this interface is both exported and imported as -/// the "downstream" and "upstream" directions of the middleware chain. -@since(version = 0.3.0) -interface handler { - use types.{request, response, error-code}; - - /// This function may be called with either an incoming request read from the - /// network or a request synthesized or forwarded by another component. - handle: async func(request: request) -> result; -} - -/// This interface defines an HTTP client for sending "outgoing" requests. -/// -/// Most components are expected to import this interface to provide the -/// capability to send HTTP requests to arbitrary destinations on a network. -/// -/// The type signature of `client.send` is the same as `handler.handle`. This -/// duplication is currently necessary because some Component Model tooling -/// (including WIT itself) is unable to represent a component importing two -/// instances of the same interface. A `client.send` import may be linked -/// directly to a `handler.handle` export to bypass the network. -@since(version = 0.3.0) -interface client { - use types.{request, response, error-code}; - - /// This function may be used to either send an outgoing request over the - /// network or to forward it to another component. - send: async func(request: request) -> result; -} - -/// The `wasi:http/service` world captures a broad category of HTTP services -/// including web applications, API servers, and proxies. It may be `include`d -/// in more specific worlds such as `wasi:http/middleware`. -@since(version = 0.3.0) -world service { - import wasi:cli/types@0.3.0; - import wasi:cli/stdout@0.3.0; - import wasi:cli/stderr@0.3.0; - import wasi:cli/stdin@0.3.0; - import wasi:clocks/types@0.3.0; - import types; - import client; - import wasi:clocks/monotonic-clock@0.3.0; - import wasi:clocks/system-clock@0.3.0; - @unstable(feature = clocks-timezone) - import wasi:clocks/timezone@0.3.0; - import wasi:random/random@0.3.0; - import wasi:random/insecure@0.3.0; - import wasi:random/insecure-seed@0.3.0; - - export handler; -} -/// The `wasi:http/middleware` world captures HTTP services that forward HTTP -/// Requests to another handler. -/// -/// Components may implement this world to allow them to participate in handler -/// "chains" where a `request` flows through handlers on its way to some terminal -/// `service` and corresponding `response` flows in the opposite direction. -@since(version = 0.3.0) -world middleware { - import wasi:clocks/types@0.3.0; - import types; - import handler; - import wasi:cli/types@0.3.0; - import wasi:cli/stdout@0.3.0; - import wasi:cli/stderr@0.3.0; - import wasi:cli/stdin@0.3.0; - import client; - import wasi:clocks/monotonic-clock@0.3.0; - import wasi:clocks/system-clock@0.3.0; - @unstable(feature = clocks-timezone) - import wasi:clocks/timezone@0.3.0; - import wasi:random/random@0.3.0; - import wasi:random/insecure@0.3.0; - import wasi:random/insecure-seed@0.3.0; - - export handler; -} diff --git a/components/http/wit/deps/wasi-random-0.3.0/package.wit b/components/http/wit/deps/wasi-random-0.3.0/package.wit deleted file mode 100644 index f6cfb81..0000000 --- a/components/http/wit/deps/wasi-random-0.3.0/package.wit +++ /dev/null @@ -1,18 +0,0 @@ -package wasi:random@0.3.0; - -interface random { - get-random-bytes: func(max-len: u64) -> list; - - get-random-u64: func() -> u64; -} - -interface insecure { - get-insecure-random-bytes: func(max-len: u64) -> list; - - get-insecure-random-u64: func() -> u64; -} - -interface insecure-seed { - get-insecure-seed: func() -> tuple; -} - diff --git a/components/http/wit/package.wit b/components/http/wit/package.wit deleted file mode 100644 index 63d35c4..0000000 --- a/components/http/wit/package.wit +++ /dev/null @@ -1,72 +0,0 @@ -package composable:http@0.4.0; - -interface client { - enum method { - get, - post, - put, - delete, - patch, - head, - options, - trace, - query, - } - - variant error-code { - other(option), - } - - /// Per-request options. None fields fall through to host defaults. - record request-options { - connect-timeout-ms: option, - first-byte-timeout-ms: option, - between-bytes-timeout-ms: option, - } - - /// A streaming HTTP response. The status and headers are available - /// immediately; the body streams as `body`, and trailers (if any) resolve - /// via `trailers` once the body stream is fully consumed. - record http-response { - status: u16, - headers: list>, - body: stream, - trailers: future>, error-code>>, - } - - /// Send an HTTP request with an explicit method. Both the request body and - /// the response body stream. - request: async func(method: method, url: string, headers: list>, body: option>, options: option) -> result; - - /// HTTP GET request. - get: async func(url: string, headers: list>, options: option) -> result; - - /// HTTP POST request. - post: async func(url: string, headers: list>, body: stream, options: option) -> result; - - /// HTTP PUT request. - put: async func(url: string, headers: list>, body: stream, options: option) -> result; - - /// HTTP DELETE request. - delete: async func(url: string, headers: list>, options: option) -> result; - - /// HTTP PATCH request. - patch: async func(url: string, headers: list>, body: stream, options: option) -> result; - - /// HTTP HEAD request. - head: async func(url: string, headers: list>, options: option) -> result; - - /// HTTP OPTIONS request. - options: async func(url: string, headers: list>, options: option) -> result; - - /// HTTP TRACE request. - trace: async func(url: string, headers: list>, options: option) -> result; - - /// HTTP QUERY request. - query: async func(url: string, headers: list>, body: stream, options: option) -> result; -} - -world http-client { - export client; - import wasi:http/client@0.3.0; -} diff --git a/components/http/wkg.lock b/components/http/wkg.lock deleted file mode 100644 index 1c6187c..0000000 --- a/components/http/wkg.lock +++ /dev/null @@ -1,12 +0,0 @@ -# This file is automatically generated. -# It is not intended for manual editing. -version = 1 - -[[packages]] -name = "wasi:http" -registry = "wasi.dev" - -[[packages.versions]] -requirement = "=0.3.0" -version = "0.3.0" -digest = "sha256:92cd8f3730c00226dc15626a2e7b21834dd187fc221f09818720d228585bbbf7" diff --git a/components/http/wkg.toml b/components/http/wkg.toml deleted file mode 100644 index e7030de..0000000 --- a/components/http/wkg.toml +++ /dev/null @@ -1,5 +0,0 @@ -[metadata] -description = "WIT package defining the composable:http interfaces" -license = "Apache-2.0" -homepage = "https://github.com/modulewise/composable-runtime/tree/main/components/http" -repository = "https://github.com/modulewise/composable-runtime" diff --git a/components/lib/.gitignore b/components/lib/.gitignore deleted file mode 100644 index 19e1bce..0000000 --- a/components/lib/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.wasm diff --git a/examples/filesystem/wkg.toml b/examples/filesystem/wkg.toml new file mode 100644 index 0000000..e69de29 diff --git a/examples/hello-world/wkg.toml b/examples/hello-world/wkg.toml new file mode 100644 index 0000000..e69de29 diff --git a/examples/host-capability/Cargo.lock b/examples/host-capability/Cargo.lock index 06007aa..89e9596 100644 --- a/examples/host-capability/Cargo.lock +++ b/examples/host-capability/Cargo.lock @@ -427,7 +427,6 @@ dependencies = [ "wasm-pkg-client", "wasmtime", "wasmtime-wasi", - "wasmtime-wasi-config", "wasmtime-wasi-http", "wasmtime-wasi-io", "wit-component 0.263.0", @@ -3919,15 +3918,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "wasmtime-wasi-config" -version = "50.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e444d377865760241b61371493efae6f03dbe135e33847a30ba5ec125925de19" -dependencies = [ - "wasmtime", -] - [[package]] name = "wasmtime-wasi-http" version = "50.0.2" diff --git a/examples/interceptor/wkg.lock b/examples/interceptor/wkg.lock new file mode 100644 index 0000000..5671fb9 --- /dev/null +++ b/examples/interceptor/wkg.lock @@ -0,0 +1,12 @@ +# This file is automatically generated. +# It is not intended for manual editing. +version = 1 + +[[packages]] +name = "wasi:logging" +registry = "wasi.dev" + +[[packages.versions]] +requirement = "=0.1.0-draft" +version = "0.1.0-draft" +digest = "sha256:09621a45b12b0a9cddc798517f778aac0e5ae4bd234077b3d70758d6cf625580" diff --git a/examples/interceptor/wkg.toml b/examples/interceptor/wkg.toml new file mode 100644 index 0000000..cc8374a --- /dev/null +++ b/examples/interceptor/wkg.toml @@ -0,0 +1,2 @@ +[overrides] +"modulewise:interceptor" = { path = "../../crates/interceptor/wit" } diff --git a/examples/named-imports/wkg.lock b/examples/named-imports/wkg.lock new file mode 100644 index 0000000..ef84337 --- /dev/null +++ b/examples/named-imports/wkg.lock @@ -0,0 +1,12 @@ +# This file is automatically generated. +# It is not intended for manual editing. +version = 1 + +[[packages]] +name = "wasi:config" +registry = "wasi.dev" + +[[packages.versions]] +requirement = "=0.2.0-rc.1" +version = "0.2.0-rc.1" +digest = "sha256:1b7f1b0fd07bb4cede16c6a6ec8852815dfb924639a78735fc7bdffdc164485d" diff --git a/examples/named-imports/wkg.toml b/examples/named-imports/wkg.toml new file mode 100644 index 0000000..e69de29 diff --git a/examples/otel-components/Cargo.lock b/examples/otel-components/Cargo.lock index 7661c29..d1486a2 100644 --- a/examples/otel-components/Cargo.lock +++ b/examples/otel-components/Cargo.lock @@ -470,7 +470,6 @@ dependencies = [ "wasm-pkg-client", "wasmtime", "wasmtime-wasi", - "wasmtime-wasi-config", "wasmtime-wasi-http", "wasmtime-wasi-io", "wit-component 0.263.0", @@ -4119,15 +4118,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "wasmtime-wasi-config" -version = "50.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e444d377865760241b61371493efae6f03dbe135e33847a30ba5ec125925de19" -dependencies = [ - "wasmtime", -] - [[package]] name = "wasmtime-wasi-http" version = "50.0.2" diff --git a/examples/otel-components/build.sh b/examples/otel-components/build.sh index e6bc838..bcbbeb8 100755 --- a/examples/otel-components/build.sh +++ b/examples/otel-components/build.sh @@ -8,7 +8,7 @@ wasm-tools component new \ -o lib/guest.wasm # opentelemetry depends on js-sys for any wasm32 target other than WASI. -cargo +nightly build -p otel-to-grpc --target wasm32-wasip3 --release +cargo build -p otel-to-grpc --target wasm32-wasip3 --release cp target/wasm32-wasip3/release/otel_to_grpc.wasm lib/otel-to-grpc.wasm cargo build -p grpc-to-http --target wasm32-unknown-unknown --release diff --git a/examples/otel-service/Cargo.lock b/examples/otel-service/Cargo.lock index f16680f..f2b3113 100644 --- a/examples/otel-service/Cargo.lock +++ b/examples/otel-service/Cargo.lock @@ -506,7 +506,6 @@ dependencies = [ "wasm-pkg-client", "wasmtime", "wasmtime-wasi", - "wasmtime-wasi-config", "wasmtime-wasi-http", "wasmtime-wasi-io", "wit-component 0.263.0", @@ -4564,15 +4563,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "wasmtime-wasi-config" -version = "50.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e444d377865760241b61371493efae6f03dbe135e33847a30ba5ec125925de19" -dependencies = [ - "wasmtime", -] - [[package]] name = "wasmtime-wasi-http" version = "50.0.2" diff --git a/examples/service/Cargo.lock b/examples/service/Cargo.lock index 2580fc2..85f3d39 100644 --- a/examples/service/Cargo.lock +++ b/examples/service/Cargo.lock @@ -427,7 +427,6 @@ dependencies = [ "wasm-pkg-client", "wasmtime", "wasmtime-wasi", - "wasmtime-wasi-config", "wasmtime-wasi-http", "wasmtime-wasi-io", "wit-component 0.263.0", @@ -3918,15 +3917,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "wasmtime-wasi-config" -version = "50.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e444d377865760241b61371493efae6f03dbe135e33847a30ba5ec125925de19" -dependencies = [ - "wasmtime", -] - [[package]] name = "wasmtime-wasi-http" version = "50.0.2" diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..5333879 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.100" +targets = ["wasm32-unknown-unknown", "wasm32-wasip2", "wasm32-wasip3"] diff --git a/scripts/smoke-test-cli.sh b/scripts/smoke-test-cli.sh new file mode 100755 index 0000000..1a7f204 --- /dev/null +++ b/scripts/smoke-test-cli.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# Smoke test the composable-runtime cli, run by the CI workflow with the cli unpacked from its +# archive, and by `make test-cli` with the cli installed with the tools. +# +# scripts/smoke-test-cli.sh + +set -euo pipefail + +cli=$1 + +cd "$(dirname "$0")/.." + +fail() { + echo "::error::$1" + exit 1 +} + +# without the carriage returns of windows +run() { + "$cli" "$@" | tr -d '\r' +} + +# TODO add tests to cover core behavior +run --help || fail "expected cli to report help" diff --git a/wkg.lock b/wkg.lock new file mode 100644 index 0000000..2ad4aa8 --- /dev/null +++ b/wkg.lock @@ -0,0 +1,4 @@ +# This file is automatically generated. +# It is not intended for manual editing. +version = 1 +packages = [] diff --git a/wkg.toml b/wkg.toml new file mode 100644 index 0000000..e69de29 From 90e96687ffd049ccdcb101934509ef2b45dc0c99 Mon Sep 17 00:00:00 2001 From: Scott Andrews Date: Mon, 23 Nov 2026 02:51:55 +0000 Subject: [PATCH 2/2] binstall is installed as a tool Signed-off-by: Scott Andrews --- .devcontainer/init.sh | 2 -- 1 file changed, 2 deletions(-) diff --git a/.devcontainer/init.sh b/.devcontainer/init.sh index cfe49cf..3b85521 100755 --- a/.devcontainer/init.sh +++ b/.devcontainer/init.sh @@ -4,8 +4,6 @@ set -euo pipefail -curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash - echo "PATH=\"\$(make -s tools-path):\${PATH}\"" | tee -a ~/.zshrc ~/.bashrc >/dev/null echo "source \"$(pwd)/build/scripts/completions.sh\"" | tee -a ~/.zshrc ~/.bashrc >/dev/null