diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index b46b2fb..0000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM mcr.microsoft.com/devcontainers/rust:2-1-trixie -RUN sudo apt update && sudo apt upgrade -y -RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash -RUN cargo binstall -y wasm-tools -RUN cargo binstall -y wkg -RUN cargo binstall -y wac-cli -RUN cargo binstall -y wasmtime-cli diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 3ea03d3..c699171 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,10 +1,8 @@ // 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": "component", - "build": { - "dockerfile": "Dockerfile" - }, + "name": "componentized-component", + "image": "mcr.microsoft.com/devcontainers/rust", // Use 'mounts' to make the cargo cache persistent in a Docker Volume. "mounts": [ { @@ -23,7 +21,7 @@ "ghcr.io/devcontainers/features/github-cli:1": {} }, // Use 'postCreateCommand' to run commands after the container is created. - "postCreateCommand": "cargo check", + "postCreateCommand": "./scripts/init-devcontainer.sh", // Configure tool-specific properties. "customizations": { // Configure properties specific to VS Code. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 53f1af5..41823bc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -19,6 +19,10 @@ updates: - wat - wit-component - wit-parser + - package-ecosystem: cargo + directory: "/tools" + schedule: + interval: daily - package-ecosystem: rust-toolchain directory: "/" schedule: diff --git a/.github/workflows/bump-version.yaml b/.github/workflows/bump-version.yaml new file mode 100644 index 0000000..058f124 --- /dev/null +++ b/.github/workflows/bump-version.yaml @@ -0,0 +1,159 @@ +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 + default: "0.0.0-dev" # the current version, kept current by scripts/bump-version.sh + +jobs: + # bumps the version with read only access, the changes are handed to the pull-request 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 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Install cargo binstall + uses: cargo-bins/cargo-binstall@main + - name: Install tools + run: | + make tools + make -s tools-path >> "${GITHUB_PATH}" + - name: Bump version + # also fetches the wit dependencies for the new version, and builds and tests the components + run: scripts/bump-version.sh "${VERSION}" + env: + VERSION: ${{ inputs.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 + + # opens the pull request using only first party actions and the gh cli + pull-request: + needs: + - bump + 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 + env: + VERSION: ${{ inputs.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 + permission-pull-requests: write + # the bump changes the default version in this workflow + permission-workflows: 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: Read current version + # the checkout is before the bump, the crates' workspace version is the current version + run: | + current=$( sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"$/\1/p' Cargo.toml ) + echo "CURRENT_VERSION=${current}" >> "${GITHUB_ENV}" + - name: Commit changes + # the commit is created with the REST API, as the app's token can't push. The patch is applied + # locally only to find the changed files and their modes. + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + run: | + branch="bump-version/${VERSION}" + api="repos/${GITHUB_REPOSITORY}" + base=$( git rev-parse HEAD ) + git apply --index "${RUNNER_TEMP}/bump-version.patch" + + # a blob for each changed file, or a null sha for a deleted file + entries="${RUNNER_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}" + 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 ) + + # authored and signed off (DCO) by the user who triggered the workflow, with their GitHub + # noreply email so the commit is attributed to them without exposing their email address. + # Committed by the custodian app's bot, which made the commit on their behalf. The commit is + # unsigned, GitHub only signs commits it attributes entirely to the app. + name=$( gh api "users/${GITHUB_ACTOR}" --jq '.name // .login' ) + name="${name:-${GITHUB_ACTOR}}" + email="${GITHUB_ACTOR_ID}+${GITHUB_ACTOR}@users.noreply.github.com" + bot="${APP_SLUG}[bot]" + bot_email="$( gh api "users/${bot}" --jq .id )+${bot}@users.noreply.github.com" + commit=$( jq -n \ + --arg message "$( printf 'Bump version from %s to %s\n\nSigned-off-by: %s <%s>' "${CURRENT_VERSION}" "${VERSION}" "${name}" "${email}" )" \ + --arg tree "${tree}" --arg parent "${base}" --arg name "${name}" --arg email "${email}" \ + --arg bot "${bot}" --arg bot_email "${bot_email}" \ + '{message: $message, tree: $tree, parents: [$parent], author: {name: $name, email: $email}, committer: {name: $bot, email: $bot_email}}' \ + | gh api --method POST "${api}/git/commits" --input - --jq .sha ) + echo "created commit ${commit}" + + # points the branch at the commit, replacing the branch left by an earlier run for the same version + if gh api "${api}/git/ref/heads/${branch}" --silent 2> /dev/null ; then + gh api --method PATCH "${api}/git/refs/heads/${branch}" -f sha="${commit}" -F force=true --silent + else + gh api --method POST "${api}/git/refs" -f ref="refs/heads/${branch}" -f sha="${commit}" --silent + fi + - name: Open pull request + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + run: | + branch="bump-version/${VERSION}" + if [ -n "$( gh pr list --head "${branch}" --state open --json number --jq '.[].number' )" ] ; then + echo "A pull request for ${branch} is already open, updated by the new commit" + exit 0 + fi + gh pr create \ + --base "${GITHUB_REF_NAME}" \ + --head "${branch}" \ + --title "Bump version from \`${CURRENT_VERSION}\` to \`${VERSION}\`" \ + --body "Bumps the wit package and crates from \`${CURRENT_VERSION}\` to \`${VERSION}\`. + + Triggered by @${GITHUB_ACTOR} from the [Bump version](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}) workflow." diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8cf9672..cd547f3 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -17,12 +17,11 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v2 - name: Install cargo binstall uses: cargo-bins/cargo-binstall@main - - name: Install wasmtime - run: cargo binstall --force wasmtime-cli - - name: Install wkg - run: cargo binstall --force wkg - - name: Install wasm-tools - run: cargo binstall --force wasm-tools + - name: Install tools + # the versions pinned in tools/Cargo.toml, on the path for later steps + run: | + make tools + make -s tools-path >> "${GITHUB_PATH}" - name: Sync wit run: make wit - name: Check for drift in generated wit @@ -30,8 +29,8 @@ jobs: - name: Build components run: make components - name: Collect components.tar - run: tar -cvf ../components.tar *.wasm* - working-directory: ./lib + run: tar -cvf ../../components.tar . + working-directory: ./target/components - name: Upload components.tar uses: actions/upload-artifact@v7 with: @@ -41,12 +40,20 @@ jobs: - name: Test run: make test - name: Capture WIT - working-directory: ./lib + working-directory: ./target/components run: | - for component in *.wasm ; do - echo "::group::${component} ($(du -h ${component} | cut -f1 ))" - wasm-tools component wit "${component}" - echo "::endgroup::" + 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 publish: @@ -63,10 +70,10 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v2 - name: Install cargo binstall uses: cargo-bins/cargo-binstall@main - - name: Install wkg - run: cargo binstall --force wkg - - name: Install wasm-tools - run: cargo binstall --force wasm-tools + - name: Install tools + run: | + make tools + make -s tools-path >> "${GITHUB_PATH}" - name: Install cosign uses: sigstore/cosign-installer@v4.1.2 - name: Download components.tar @@ -74,10 +81,10 @@ jobs: with: name: components.tar - name: Extract components - run: tar -xvf components.tar -C lib + 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 lib/interface.wasm --json | jq -r "[.packages[] | select(.name | contains(\"${GITHUB_REPOSITORY/\//:}@\"))][0].name" | cut -d'@' -f2 )" >> $GITHUB_OUTPUT + 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 @@ -101,7 +108,8 @@ jobs: with: draft: true files: | - lib/*.wasm + target/components/*.wasm + target/components/*/*.wasm components.tar fail_on_unmatched_files: true token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index b546111..f3027d2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ /components.tar /target .DS_Store +/tools/Cargo.lock +# wit dependencies, fetched by `make wit` from the wkg.toml and wkg.lock files +**/wit/deps/ diff --git a/Cargo.toml b/Cargo.toml index 6bc315b..3a87500 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,10 +1,10 @@ [workspace] resolver = "2" members = [ - "components/*", -] -exclude = [ - "components/wit", + "components/extract-wit", + "components/filesystem-loader", + "components/http-loader", + "components/wac-loader", ] [workspace.dependencies] diff --git a/Makefile b/Makefile index 1b3db27..1f92290 100644 --- a/Makefile +++ b/Makefile @@ -2,73 +2,185 @@ SHELL := /bin/bash export RUST_BACKTRACE ?= 1 export WASMTIME_BACKTRACE_DETAILS ?= 1 -WKG_CONFIG_FILE ?= $(dir $(abspath $(lastword $(MAKEFILE_LIST)))).config/wasm-pkg/config.toml -COMPONENTS = $(sort $(notdir $(patsubst %/,%,$(dir $(wildcard components/*/Cargo.toml))))) +COMPONENTS_DIR := target/components +TOOLS_DIR := target/tools/$(shell rustc --print host-tuple) +# absolute, tools also run from other directories, e.g. `cd components && wkg fetch` +export PATH := $(abspath $(TOOLS_DIR))/bin:$(PATH) + +# cargo binstall downloads prebuilt binaries, without it the tools are built with cargo install +CARGO_INSTALL := $(if $(shell command -v cargo-binstall 2> /dev/null),cargo binstall --no-confirm --disable-telemetry,cargo install) + +COMPONENTS = $(sort $(foreach file,$(wildcard $(addprefix components/*/,wit/*.constants.wit *.properties *.wac *.wkg Cargo.toml)),$(word 2,$(subst /, ,$(file))))) +TOOLS := componentized-constants-cli static-config wac-cli wasm-tools wasmtime-cli wkg + +export WKG_CONFIG_FILE := $(abspath .config/wasm-pkg/config.toml) + +# 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)))) + .PHONY: all all: components .PHONY: clean -clean: +clean: clean-wit cargo clean - rm -rf lib/*.wasm - rm -rf lib/*.wasm.md + +.PHONY: clean-components +clean-components: clean-wit + rm -rf ${COMPONENTS_DIR} + +.PHONY: clean-wit ## Remove the fetched wit dependencies, fetched again by `make wit` +clean-wit: + rm -rf $(WIT_DEPS) .PHONY: test -test: - @echo "TODO add tests" +test: components + cargo test --workspace + + +tool_version = $(shell sed -n 's/^$(1) = "=\(.*\)"$$/\1/p' tools/Cargo.toml) +# 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. +tool = $(TOOLS_DIR)/.installed/$(1)@$(call tool_version,$(1)) + +.PHONY: tools ## Install the cli tools pinned in tools/Cargo.toml +tools: $(foreach name,$(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 $(abspath $(TOOLS_DIR))/bin + +define INSTALL_TOOL + +$(call tool,$1): + $(CARGO_INSTALL) --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,$(TOOLS),$(eval $(call INSTALL_TOOL,$(name)))) + +# the target a cargo component is built for, the package's `default-target`, e.g. `wasm32-wasip3`. +# wasm32-unknown-unknown builds a core module that is wrapped as a component, a wasi target builds +# a component. +cargo_target = $(or $(shell sed -n 's/^default-target = "\(.*\)"$$/\1/p' components/$(1)/Cargo.toml),wasm32-unknown-unknown) .PHONY: components -components: lib/interface.wasm $(foreach component,$(COMPONENTS),lib/$(component).wasm lib/$(component).debug.wasm) +components: ${COMPONENTS_DIR}/interface.wasm $(foreach component,$(COMPONENTS),${COMPONENTS_DIR}/$(component)/$(component).wasm ${COMPONENTS_DIR}/$(component)/$(component).debug.wasm) define BUILD_COMPONENT .PHONY: components/$1 -components/$1: lib/$1.wasm lib/$1.debug.wasm +components/$1: ${COMPONENTS_DIR}/$1/$1.wasm ${COMPONENTS_DIR}/$1/$1.debug.wasm + +ifneq ($(wildcard components/$1/wit/$1.constants.wit),) + +${COMPONENTS_DIR}/$1/$1.wasm: components/$1/wit/deps ${COMPONENTS_DIR}/$1/README.md | $(call tool,componentized-constants-cli) + constants --wit components/$1/wit -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: components/$1/wit/deps ${COMPONENTS_DIR}/$1/README.md | $(call tool,componentized-constants-cli) + constants --wit components/$1/wit -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +else ifneq ($(wildcard components/$1/$1.properties),) -lib/$1.wasm: Cargo.toml Cargo.lock components/wit/deps $(shell find components/$1 -type f) - @$(eval target := $(shell yq -r '.package.default-target // "wasm32-unknown-unknown"' components/$1/Cargo.toml)) - cargo build -p $1 --target $(target) --release -ifeq ($(target),wasm32-unknown-unknown) - wasm-tools component new target/$(target)/release/$(subst -,_,$1).wasm -o lib/$1.wasm +${COMPONENTS_DIR}/$1/$1.wasm: components/$1/$1.properties ${COMPONENTS_DIR}/$1/README.md | $(call tool,static-config) + static-config -f components/$1/$1.properties -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: components/$1/$1.properties ${COMPONENTS_DIR}/$1/README.md | $(call tool,static-config) + static-config -f components/$1/$1.properties -o ${COMPONENTS_DIR}/$1/$1.debug.wasm + +else ifneq ($(wildcard components/$1/$1.wac),) + +# the local packages the composition instantiates, e.g. `new local:latch-n2 { ... }` +WAC_DEPS_$1 := $$(shell grep -v '^\s*//' components/$1/$1.wac | grep -oE 'local:[a-z0-9-]+' | sed 's/^local://' | sort -u) + +${COMPONENTS_DIR}/$1/$1.wasm: components/$1/$1.wac $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).wasm) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wac-cli) + wac compose $$(foreach component,$$(WAC_DEPS_$1),-d local:$$(component)=$${COMPONENTS_DIR}/$$(component)/$$(component).wasm) -o ${COMPONENTS_DIR}/$1/$1.wasm components/$1/$1.wac + +${COMPONENTS_DIR}/$1/$1.debug.wasm: components/$1/$1.wac $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wac-cli) + wac compose $$(foreach component,$$(WAC_DEPS_$1),-d local:$$(component)=$${COMPONENTS_DIR}/$$(component)/$$(component).debug.wasm) -o ${COMPONENTS_DIR}/$1/$1.debug.wasm components/$1/$1.wac + +else ifneq ($(wildcard components/$1/$1.wkg),) + +${COMPONENTS_DIR}/$1/$1.wasm: components/$1/$1.wkg ${COMPONENTS_DIR}/$1/README.md | $(call tool,wkg) + wkg oci pull $(shell cat components/$1/$1.wkg 2> /dev/null | head -1) -o ${COMPONENTS_DIR}/$1/$1.wasm + +${COMPONENTS_DIR}/$1/$1.debug.wasm: components/$1/$1.wkg ${COMPONENTS_DIR}/$1/README.md | $(call tool,wkg) + wkg oci pull $(shell cat components/$1/$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 components/$1/Cargo.toml),) + +${COMPONENTS_DIR}/$1/$1.wasm: Cargo.toml Cargo.lock components/wit/deps $(shell find components/$1 -type f) $(shell find crates -type f 2> /dev/null) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wasm-tools) + cargo build -p $1 --target $(call cargo_target,$1) --release +ifeq ($(call cargo_target,$1),wasm32-unknown-unknown) + wasm-tools component new target/wasm32-unknown-unknown/release/$(subst -,_,$1).wasm -o ${COMPONENTS_DIR}/$1/$1.wasm else - cp target/$(target)/release/$(subst -,_,$1).wasm lib/$1.wasm + cp target/$(call cargo_target,$1)/release/$(subst -,_,$1).wasm ${COMPONENTS_DIR}/$1/$1.wasm endif - cp components/$1/README.md lib/$1.wasm.md -lib/$1.debug.wasm: Cargo.toml Cargo.lock components/wit/deps $(shell find components/$1 -type f) - @$(eval target := $(shell yq -r '.package.default-target // "wasm32-unknown-unknown"' components/$1/Cargo.toml)) - cargo build --target $(target) -p $1 -ifeq ($(target),wasm32-unknown-unknown) - wasm-tools component new target/$(target)/debug/$(subst -,_,$1).wasm -o lib/$1.debug.wasm +${COMPONENTS_DIR}/$1/$1.debug.wasm: Cargo.toml Cargo.lock components/wit/deps $(shell find components/$1 -type f) $(shell find crates -type f 2> /dev/null) ${COMPONENTS_DIR}/$1/README.md | $(call tool,wasm-tools) + cargo build --target $(call cargo_target,$1) -p $1 +ifeq ($(call cargo_target,$1),wasm32-unknown-unknown) + wasm-tools component new target/wasm32-unknown-unknown/debug/$(subst -,_,$1).wasm -o ${COMPONENTS_DIR}/$1/$1.debug.wasm else - cp target/$(target)/debug/$(subst -,_,$1).wasm lib/$1.debug.wasm + cp target/$(call cargo_target,$1)/debug/$(subst -,_,$1).wasm ${COMPONENTS_DIR}/$1/$1.debug.wasm endif - cp components/$1/README.md lib/$1.debug.wasm.md + +endif + +${COMPONENTS_DIR}/$1/README.md: components/$1/README.md + @mkdir -p ${COMPONENTS_DIR}/$1 + @cp components/$1/README.md ${COMPONENTS_DIR}/$1/README.md endef $(foreach component,$(COMPONENTS),$(eval $(call BUILD_COMPONENT,$(component)))) -lib/interface.wasm: wit/deps README.md - wkg build -o lib/interface.wasm - cp README.md lib/interface.wasm.md +${COMPONENTS_DIR}/interface.wasm: wit/deps README.md | $(call tool,wkg) + @mkdir -p ${COMPONENTS_DIR} + wkg build -o ${COMPONENTS_DIR}/interface.wasm + @cp README.md ${COMPONENTS_DIR}/README.md + +# 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 '*/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))) .PHONY: wit -wit: wit/deps components/wit/deps +wit: $(WIT_DEPS) + +define FETCH_WIT + +# a package overridden with a local path, e.g. `{ path = "../wit" }`, has its dependencies fetched first +$(call wit_deps,$1): $1/wkg.toml $1/wkg.lock $(shell find $1/wit -type f -name "*.wit" -not -path "*/deps/*") $(foreach path,$(shell sed -n 's/.*path *= *"\(.*\)".*/\1/p' $1/wkg.toml),$(call relpath,$1/$(path))/deps) | $(call tool,wkg) + $(if $(filter .,$1),,cd $1 && )wkg fetch + +endef + +$(foreach dir,$(WKG_DIRS),$(eval $(call FETCH_WIT,$(dir)))) -wit/deps: wkg.toml $(WKG_CONFIG_FILE) $(shell find wit -type f -name "*.wit" -not -path "deps") - wkg fetch --config $(WKG_CONFIG_FILE) +# sign published components with cosign, `SIGN=false` to push without signing, e.g. to a local registry +SIGN ?= true -components/wit/deps: wit/deps components/wkg.toml $(WKG_CONFIG_FILE) $(shell find components/wit -type f -name "*.wit" -not -path "deps") - ( cd components && wkg fetch --config $(WKG_CONFIG_FILE) ) +# the files that can be published, e.g. gate.wasm, published from target/components/gate/gate.wasm +PUBLISH_FILES := interface.wasm $(foreach component,$(filter-out dep-% test-%,$(COMPONENTS)),$(component).wasm $(component).debug.wasm) -.PHONY: publish ## Publish each component in the lib directory -publish: $(shell find lib -maxdepth 1 -type f -name "*.wasm" | sed -e 's:^lib/:publish-:g') +.PHONY: publish ## Publish each component in the target/components directory +publish: $(addprefix publish-,$(PUBLISH_FILES)) -.PHONY: publish-% -publish-%: +.PHONY: $(addprefix publish-,$(PUBLISH_FILES)) +$(addprefix publish-,$(PUBLISH_FILES)): publish-%: | $(call tool,wkg) ifndef VERSION $(error VERSION is undefined) endif @@ -76,28 +188,36 @@ ifndef REPOSITORY $(error REPOSITORY is undefined) endif @$(eval FILE := $(@:publish-%=%)) - @$(eval COMPONENT := $(if $(filter %.debug.wasm,$(FILE)),$(FILE:%.debug.wasm=%),$(FILE:%.wasm=%))) - @$(eval TITLE := $(if $(filter %.debug.wasm,$(FILE)),$(COMPONENT) (debug),$(COMPONENT))) - @$(eval DESCRIPTION := $(shell head -n 3 "lib/${FILE}.md" | tail -n 1)) - @$(eval REVISION := $(shell git rev-parse HEAD)$(shell git diff --quiet HEAD && echo "+dirty")) + @$(eval COMPONENT := $(patsubst %.wasm,%,$(patsubst %.debug.wasm,%,$(FILE)))) +# components are in a directory of their own, the interface is not, e.g. gate/gate.wasm and interface.wasm + @$(eval COMPONENT_FILE := $(if $(filter interface.wasm,$(FILE)),$(FILE),$(COMPONENT)/$(FILE))) + @$(eval README := ${COMPONENTS_DIR}/$(dir $(COMPONENT_FILE))README.md) + @$(eval TITLE := $(subst /,:,$(GITHUB_REPOSITORY))$(if $(filter interface,$(COMPONENT)),,-$(COMPONENT))$(if $(filter %.debug.wasm,$(FILE)), (debug))) + @$(eval DESCRIPTION := $(shell head -n 3 "$(README)" | tail -n 1)) + @$(eval COMMIT := $(shell git rev-parse HEAD)) + @$(eval README_DIR := $(if $(wildcard components/$(COMPONENT)/README.md),/components/$(COMPONENT))) + @$(eval URL := https://github.com/${GITHUB_REPOSITORY}/tree/${COMMIT}${README_DIR}) + @$(eval REVISION := ${COMMIT}$(shell git diff --quiet HEAD || echo "+dirty")) @$(eval COMPONENT_VERSION := $(if $(filter %.debug.wasm,$(FILE)),${VERSION}+debug,${VERSION})) @$(eval TAG := $(patsubst v%,%,$(subst +,_,$(COMPONENT_VERSION)))) @$(eval IMAGE := $(if $(filter interface.wasm,$(FILE)),${REPOSITORY}:${TAG},${REPOSITORY}/${COMPONENT}:${TAG})) @echo "::group::${FILE} -> ${IMAGE}" - @DIGEST=$$( \ + @set -o pipefail ; \ + DIGEST=$$( \ wkg oci push \ --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" \ "${IMAGE}" \ - "lib/${FILE}" \ + "${COMPONENTS_DIR}/${COMPONENT_FILE}" \ 2>&1 \ | tee /dev/stderr \ | grep -o 'sha256:[a-f0-9]\{64\}' \ - ) ; \ - cosign sign --yes "${IMAGE}@$${DIGEST}" + ) && \ + $(if $(filter true,$(SIGN)),cosign sign --yes "${IMAGE}@$${DIGEST}",echo "Not signing ${IMAGE}@$${DIGEST}, SIGN=${SIGN}") @echo "::endgroup::" diff --git a/README.md b/README.md index 7f2a5d5..593c717 100644 --- a/README.md +++ b/README.md @@ -18,14 +18,16 @@ A [dev container](https://containers.dev) is available that contains the necessa Prereqs: - a rust toolchain -- [`wasm-tools`](https://github.com/bytecodealliance/wasm-tools) -- [`wkg`](https://github.com/bytecodealliance/wasm-pkg-tools) -- [`yq`](https://github.com/mikefarah/yq) +- [`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall), optional, to download prebuilt tools instead of building them ```sh make components ``` +The build creates each component in [`components`](./components) into `target/components`, e.g. the WAC loader at `target/components/wac-loader/wac-loader.wasm`, along with `target/components/interface.wasm`, the `componentized:component` WIT package. Each component is also built with debug info, e.g. `target/components/wac-loader/wac-loader.debug.wasm`. + +The cli tools the build uses, [`wasm-tools`](https://github.com/bytecodealliance/wasm-tools), [`wac`](https://github.com/bytecodealliance/wac), [`wasmtime`](https://github.com/bytecodealliance/wasmtime) and [`wkg`](https://github.com/bytecodealliance/wasm-pkg-tools), are pinned in [`tools/Cargo.toml`](./tools/Cargo.toml) and installed into `target/tools/`, e.g. `target/tools/aarch64-apple-darwin`, as needed, or ahead of time with `make tools`. Dependabot bumps the pinned versions. + ### Components - [`extract-wit`](./components/extract-wit/) diff --git a/components/extract-wit/Cargo.toml b/components/extract-wit/Cargo.toml index a4beb48..e1797bb 100644 --- a/components/extract-wit/Cargo.toml +++ b/components/extract-wit/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "extract-wit" version = "0.1.0" -edition = "2021" +edition = "2024" license = "Apache-2.0" [lib] diff --git a/components/extract-wit/src/lib.rs b/components/extract-wit/src/lib.rs index 06b86ca..3b2dcd0 100644 --- a/components/extract-wit/src/lib.rs +++ b/components/extract-wit/src/lib.rs @@ -1,5 +1,3 @@ -#![no_main] - use std::{collections::BTreeMap, fmt::Display}; use crate::{ diff --git a/components/filesystem-loader/Cargo.toml b/components/filesystem-loader/Cargo.toml index f5808c3..ce7f056 100644 --- a/components/filesystem-loader/Cargo.toml +++ b/components/filesystem-loader/Cargo.toml @@ -3,13 +3,15 @@ cargo-features = ["per-package-target"] [package] name = "filesystem-loader" version = "0.1.0" -edition = "2021" +edition = "2024" license = "Apache-2.0" default-target = "wasm32-wasip3" [lib] crate-type = ["cdylib"] +# built for the default-target, a wasm test binary is unable to run on the host +test = false [dependencies] wit-bindgen = { workspace = true } diff --git a/components/filesystem-loader/src/lib.rs b/components/filesystem-loader/src/lib.rs index 6c71a6b..dc46eb2 100644 --- a/components/filesystem-loader/src/lib.rs +++ b/components/filesystem-loader/src/lib.rs @@ -1,5 +1,3 @@ -#![no_main] - use std::{fs, io}; use crate::{ diff --git a/components/http-loader/Cargo.toml b/components/http-loader/Cargo.toml index 80eae6e..102a25a 100644 --- a/components/http-loader/Cargo.toml +++ b/components/http-loader/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "http-loader" version = "0.1.0" -edition = "2021" +edition = "2024" license = "Apache-2.0" [lib] diff --git a/components/http-loader/src/lib.rs b/components/http-loader/src/lib.rs index 4a8abd7..5d4602a 100644 --- a/components/http-loader/src/lib.rs +++ b/components/http-loader/src/lib.rs @@ -1,5 +1,3 @@ -#![no_main] - use crate::{ componentized::http::client::{self as http}, exports::componentized::component::path_loader::Guest, @@ -17,6 +15,20 @@ impl Guest for HttpLoader { } } +impl From for Error { + fn from(value: http::ErrorCode) -> Self { + match value { + http::ErrorCode::RedirectLimitExceeded((_, count)) => { + Self::Other(Some(format!("too many redirects, stopped after {count}"))) + } + http::ErrorCode::RedirectRequiresBody(_) => Self::Other(Some( + "redirect requires resending the request body".to_string(), + )), + http::ErrorCode::Other(message) => Self::Other(message), + } + } +} + wit_bindgen::generate!({ path: "../wit", world: "http-loader", diff --git a/components/wac-loader/Cargo.toml b/components/wac-loader/Cargo.toml index 61757c1..a5fb403 100644 --- a/components/wac-loader/Cargo.toml +++ b/components/wac-loader/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "wac-loader" version = "0.1.0" -edition = "2021" +edition = "2024" license = "Apache-2.0" [lib] diff --git a/components/wac-loader/src/lib.rs b/components/wac-loader/src/lib.rs index 454e58c..ef5d866 100644 --- a/components/wac-loader/src/lib.rs +++ b/components/wac-loader/src/lib.rs @@ -1,9 +1,7 @@ -#![no_main] - use indexmap::IndexMap; use wac_graph::{ - types::{BorrowedPackageKey, Package}, CompositionGraph, EncodeOptions, + types::{BorrowedPackageKey, Package}, }; use wac_parser::Document; diff --git a/components/wit/deps/componentized-component-0.0.0-dev/package.wit b/components/wit/deps/componentized-component-0.0.0-dev/package.wit deleted file mode 100644 index 2ad93ac..0000000 --- a/components/wit/deps/componentized-component-0.0.0-dev/package.wit +++ /dev/null @@ -1,300 +0,0 @@ -package componentized:component@0.0.0-dev; - -interface types { - variant error { - other(option), - } - - type component = list; -} - -interface path-loader { - use types.{component, error}; - - load: async func(path: string) -> result; -} - -interface wac-loader { - use types.{component, error}; - - type %package = string; - - type dependency = tuple<%package, component>; - - variant plan { - wac(string), - } - - plug: async func(socket: component, plugs: list) -> result; - - compose: async func(plan: plan, dependencies: list) -> result; -} - -interface wit { - use types.{component, error}; - - type type-id = string; - - variant %type { - %bool, - %s8, - %s16, - %s32, - %s64, - %u8, - %u16, - %u32, - %u64, - %f32, - %f64, - %char, - %string, - %error-context, - id(type-id), - } - - variant handle { - %own(type-id), - %borrow(type-id), - } - - record %tuple { - types: list<%type>, - } - - record %result { - ok: option<%type>, - err: option<%type>, - } - - record %list { - %type: %type, - fixed-length: option, - } - - record %map { - key: %type, - value: %type, - } - - variant function-kind { - freestanding, - async-freestanding, - method(type-id), - async-method(type-id), - %static(type-id), - async-static(type-id), - %constructor(type-id), - } - - record param { - name: string, - %type: %type, - } - - record docs { - contents: option, - } - - record record-field { - name: string, - %type: %type, - docs: docs, - } - - record %record { - fields: list, - } - - record flag { - name: string, - docs: docs, - } - - record %flags { - %flags: list, - } - - record variant-case { - name: string, - %type: option<%type>, - docs: docs, - } - - record %variant { - cases: list, - } - - record enum-case { - name: string, - docs: docs, - } - - record %enum { - cases: list, - } - - variant type-def-kind { - %record(%record), - %resource, - handle(handle), - %flags(%flags), - %tuple(%tuple), - %variant(%variant), - %enum(%enum), - %option(%type), - %result(%result), - %list(%list), - %map(%map), - %future(option<%type>), - %stream(option<%type>), - %type(%type), - unknown, - } - - variant version-identifier { - %string(string), - numeric(u64), - } - - record version { - major: u64, - minor: u64, - patch: u64, - prerelease: option>, - build-metadata: option>, - } - - record unstable { - feature: string, - deprecated: option, - } - - record stable { - since: version, - deprecated: option, - } - - variant stability { - unknown, - unstable(unstable), - stable(stable), - } - - record function { - name: string, - kind: function-kind, - params: list, - %result: option<%type>, - docs: docs, - stability: stability, - external-id: option, - } - - type interface-id = string; - - type world-id = string; - - variant type-owner { - %world(world-id), - %interface(interface-id), - none, - } - - record type-def { - name: option, - kind: type-def-kind, - owner: type-owner, - docs: docs, - stability: stability, - external-id: option, - } - - record world-item-interface { - id: interface-id, - stability: stability, - external-id: option, - docs: docs, - } - - variant world-item { - %interface(world-item-interface), - function(function), - %type(type-id), - } - - record include-name { - name: string, - %as: string, - } - - record world-include { - stability: stability, - id: world-id, - names: list, - } - - variant world-key { - name(string), - %interface(interface-id), - } - - type package-id = string; - - record %interface { - name: option, - types: list>, - functions: list>, - docs: docs, - stability: stability, - %package: option, - } - - record %world { - name: string, - imports: list>, - exports: list>, - %package: option, - docs: docs, - stability: stability, - includes: list, - } - - record package-name { - namespace: string, - name: string, - version: option, - } - - record %package { - name: package-name, - docs: docs, - interfaces: list>, - worlds: list>, - } - - record wit { - interfaces: map, - packages: map, - types: map, - worlds: map, - default-package: package-id, - component-world: option, - } - - record world-summary { - imports: list, - exports: list, - } - - extract: async func(component: component) -> result; - - summarize-world: async func(component: component) -> result; -} - -world imports { - import types; - import path-loader; - import wac-loader; - import wit; -} diff --git a/components/wit/deps/componentized-http-0.1.0-dev/package.wit b/components/wit/deps/componentized-http-0.1.0-dev/package.wit deleted file mode 100644 index 38d3bb1..0000000 --- a/components/wit/deps/componentized-http-0.1.0-dev/package.wit +++ /dev/null @@ -1,71 +0,0 @@ -package componentized:http@0.1.0-dev; - -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 imports { - import client; -} diff --git a/components/wit/deps/wasi-clocks-0.3.0/package.wit b/components/wit/deps/wasi-clocks-0.3.0/package.wit deleted file mode 100644 index 2594e02..0000000 --- a/components/wit/deps/wasi-clocks-0.3.0/package.wit +++ /dev/null @@ -1,19 +0,0 @@ -package wasi:clocks@0.3.0; - -interface types { - type duration = u64; -} - -interface system-clock { - use types.{duration}; - - record instant { - seconds: s64, - nanoseconds: u32, - } - - now: func() -> instant; - - get-resolution: func() -> duration; -} - diff --git a/components/wit/deps/wasi-filesystem-0.3.0/package.wit b/components/wit/deps/wasi-filesystem-0.3.0/package.wit deleted file mode 100644 index e4a778f..0000000 --- a/components/wit/deps/wasi-filesystem-0.3.0/package.wit +++ /dev/null @@ -1,575 +0,0 @@ -package wasi:filesystem@0.3.0; - -/// WASI filesystem is a filesystem API primarily intended to let users run WASI -/// programs that access their files on their existing filesystems, without -/// significant overhead. -/// -/// Paths are passed as interface-type `string`s, meaning they must consist of -/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain -/// paths which are not accessible by this API. -/// -/// The directory separator in WASI is always the forward-slash (`/`). -/// -/// All paths in WASI are relative paths, and are interpreted relative to a -/// `descriptor` referring to a base directory. If a `path` argument to any WASI -/// function starts with `/`, or if any step of resolving a `path`, including -/// `..` and symbolic link steps, reaches a directory outside of the base -/// directory, or reaches a symlink to an absolute or rooted path in the -/// underlying filesystem, the function fails with `error-code::not-permitted`. -/// -/// For more information about WASI path resolution and sandboxing, see -/// [WASI filesystem path resolution]. -/// -/// Though this package presents a portable interface modelled on POSIX, it -/// prioritizes compatibility over portability: allowing users to access their -/// files on their machine is more important than exposing a single semantics -/// across all platforms. Notably, depending on the underlying operating system -/// and file system: -/// * Paths may be case-folded or not. -/// * Deleting (unlinking) a file may fail if there are other file descriptors -/// open. -/// * Durability and atomicity of changes to underlying files when there are -/// concurrent writers. -/// -/// Users that need well-defined, portable semantics should use a key-value -/// store or a database instead. -/// -/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md -@since(version = 0.3.0) -interface types { - @since(version = 0.3.0) - use wasi:clocks/system-clock@0.3.0.{instant}; - - /// File size or length of a region within a file. - @since(version = 0.3.0) - type filesize = u64; - - /// The type of a filesystem object referenced by a descriptor. - /// - /// Note: This was called `filetype` in earlier versions of WASI. - @since(version = 0.3.0) - variant descriptor-type { - /// The descriptor refers to a block device inode. - block-device, - /// The descriptor refers to a character device inode. - character-device, - /// The descriptor refers to a directory inode. - directory, - /// The descriptor refers to a named pipe. - fifo, - /// The file refers to a symbolic link inode. - symbolic-link, - /// The descriptor refers to a regular file inode. - regular-file, - /// The descriptor refers to a socket. - socket, - /// The type of the descriptor or file is different from any of the - /// other types specified. - other(option), - } - - /// Descriptor flags. - /// - /// Note: This was called `fdflags` in earlier versions of WASI. - @since(version = 0.3.0) - flags descriptor-flags { - /// Read mode: Data can be read. - read, - /// Write mode: Data can be written to. - write, - /// Request that writes be performed according to synchronized I/O file - /// integrity completion. The data stored in the file and the file's - /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - file-integrity-sync, - /// Request that writes be performed according to synchronized I/O data - /// integrity completion. Only the data stored in the file is - /// synchronized. This is similar to `O_DSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - data-integrity-sync, - /// Requests that reads be performed at the same level of integrity - /// requested for writes. This is similar to `O_RSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - requested-write-sync, - /// Mutating directories mode: Directory contents may be mutated. - /// - /// When this flag is unset on a descriptor, operations using the - /// descriptor which would create, rename, delete, modify the data or - /// metadata of filesystem objects, or obtain another handle which - /// would permit any of those, shall fail with `error-code::read-only` if - /// they would otherwise succeed. - /// - /// This may only be set on directories. - mutate-directory, - } - - /// Flags determining the method of how paths are resolved. - @since(version = 0.3.0) - flags path-flags { - /// As long as the resolved path corresponds to a symbolic link, it is - /// expanded. - symlink-follow, - } - - /// Open flags used by `open-at`. - @since(version = 0.3.0) - flags open-flags { - /// Create file if it does not exist, similar to `O_CREAT` in POSIX. - create, - /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. - directory, - /// Fail if file already exists, similar to `O_EXCL` in POSIX. - exclusive, - /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. - truncate, - } - - /// Number of hard links to an inode. - @since(version = 0.3.0) - type link-count = u64; - - /// File attributes. - /// - /// Note: This was called `filestat` in earlier versions of WASI. - @since(version = 0.3.0) - record descriptor-stat { - /// File type. - %type: descriptor-type, - /// Number of hard links to the file. - link-count: link-count, - /// For regular files, the file size in bytes. For symbolic links, the - /// length in bytes of the pathname contained in the symbolic link. - size: filesize, - /// Last data access timestamp. - /// - /// If the `option` is none, the platform doesn't maintain an access - /// timestamp for this file. - data-access-timestamp: option, - /// Last data modification timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// modification timestamp for this file. - data-modification-timestamp: option, - /// Last file status-change timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// status-change timestamp for this file. - status-change-timestamp: option, - } - - /// When setting a timestamp, this gives the value to set it to. - @since(version = 0.3.0) - variant new-timestamp { - /// Leave the timestamp set to its previous value. - no-change, - /// Set the timestamp to the current time of the system clock associated - /// with the filesystem. - now, - /// Set the timestamp to the given value. - timestamp(instant), - } - - /// A directory entry. - @since(version = 0.3.0) - record directory-entry { - /// The type of the file referred to by this directory entry. - %type: descriptor-type, - /// The name of the object. - name: string, - } - - /// Error codes returned by functions, similar to `errno` in POSIX. - /// Not all of these error codes are returned by the functions provided by this - /// API; some are used in higher-level library layers, and others are provided - /// merely for alignment with POSIX. - @since(version = 0.3.0) - variant error-code { - /// Permission denied, similar to `EACCES` in POSIX. - access, - /// Connection already in progress, similar to `EALREADY` in POSIX. - already, - /// Bad descriptor, similar to `EBADF` in POSIX. - bad-descriptor, - /// Device or resource busy, similar to `EBUSY` in POSIX. - busy, - /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. - deadlock, - /// Storage quota exceeded, similar to `EDQUOT` in POSIX. - quota, - /// File exists, similar to `EEXIST` in POSIX. - exist, - /// File too large, similar to `EFBIG` in POSIX. - file-too-large, - /// Illegal byte sequence, similar to `EILSEQ` in POSIX. - illegal-byte-sequence, - /// Operation in progress, similar to `EINPROGRESS` in POSIX. - in-progress, - /// Interrupted function, similar to `EINTR` in POSIX. - interrupted, - /// Invalid argument, similar to `EINVAL` in POSIX. - invalid, - /// I/O error, similar to `EIO` in POSIX. - io, - /// Is a directory, similar to `EISDIR` in POSIX. - is-directory, - /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. - loop, - /// Too many links, similar to `EMLINK` in POSIX. - too-many-links, - /// Message too large, similar to `EMSGSIZE` in POSIX. - message-size, - /// Filename too long, similar to `ENAMETOOLONG` in POSIX. - name-too-long, - /// No such device, similar to `ENODEV` in POSIX. - no-device, - /// No such file or directory, similar to `ENOENT` in POSIX. - no-entry, - /// No locks available, similar to `ENOLCK` in POSIX. - no-lock, - /// Not enough space, similar to `ENOMEM` in POSIX. - insufficient-memory, - /// No space left on device, similar to `ENOSPC` in POSIX. - insufficient-space, - /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. - not-directory, - /// Directory not empty, similar to `ENOTEMPTY` in POSIX. - not-empty, - /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. - not-recoverable, - /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. - unsupported, - /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. - no-tty, - /// No such device or address, similar to `ENXIO` in POSIX. - no-such-device, - /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. - overflow, - /// Operation not permitted, similar to `EPERM` in POSIX. - not-permitted, - /// Broken pipe, similar to `EPIPE` in POSIX. - pipe, - /// Read-only file system, similar to `EROFS` in POSIX. - read-only, - /// Invalid seek, similar to `ESPIPE` in POSIX. - invalid-seek, - /// Text file busy, similar to `ETXTBSY` in POSIX. - text-file-busy, - /// Cross-device link, similar to `EXDEV` in POSIX. - cross-device, - /// A catch-all for errors not captured by the existing variants. - /// Implementations can use this to extend the error type without - /// breaking existing code. - other(option), - } - - /// File or memory access pattern advisory information. - @since(version = 0.3.0) - enum advice { - /// The application has no advice to give on its behavior with respect - /// to the specified data. - normal, - /// The application expects to access the specified data sequentially - /// from lower offsets to higher offsets. - sequential, - /// The application expects to access the specified data in a random - /// order. - random, - /// The application expects to access the specified data in the near - /// future. - will-need, - /// The application expects that it will not access the specified data - /// in the near future. - dont-need, - /// The application expects to access the specified data once and then - /// not reuse it thereafter. - no-reuse, - } - - /// A 128-bit hash value, split into parts because wasm doesn't have a - /// 128-bit integer type. - @since(version = 0.3.0) - record metadata-hash-value { - /// 64 bits of a 128-bit hash value. - lower: u64, - /// Another 64 bits of a 128-bit hash value. - upper: u64, - } - - /// A descriptor is a reference to a filesystem object, which may be a file, - /// directory, named pipe, special file, or other object on which filesystem - /// calls may be made. - @since(version = 0.3.0) - resource descriptor { - /// Return a stream for reading from a file. - /// - /// Multiple read, write, and append streams may be active on the same open - /// file and they do not interfere with each other. - /// - /// This function returns a `stream` which provides the data received from the - /// file, and a `future` providing additional error information in case an - /// error is encountered. - /// - /// If no error is encountered, `stream.read` on the `stream` will return - /// `read-status::closed` with no `error-context` and the future resolves to - /// the value `ok`. If an error is encountered, `stream.read` on the - /// `stream` returns `read-status::closed` with an `error-context` and the future - /// resolves to `err` with an `error-code`. - /// - /// Note: This is similar to `pread` in POSIX. - @since(version = 0.3.0) - read-via-stream: func(offset: filesize) -> tuple, future>>; - /// Return a stream for writing to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be written. - /// - /// It is valid to write past the end of a file; the file is extended to the - /// extent of the write, with bytes between the previous end and the start of - /// the write set to zero. - /// - /// This function returns once either full contents of the stream are - /// written or an error is encountered. - /// - /// Note: This is similar to `pwrite` in POSIX. - @since(version = 0.3.0) - write-via-stream: func(data: stream, offset: filesize) -> future>; - /// Return a stream for appending to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be appended. - /// - /// This function returns once either full contents of the stream are - /// written or an error is encountered. - /// - /// Note: This is similar to `write` with `O_APPEND` in POSIX. - @since(version = 0.3.0) - append-via-stream: func(data: stream) -> future>; - /// Provide file advisory information on a descriptor. - /// - /// This is similar to `posix_fadvise` in POSIX. - @since(version = 0.3.0) - advise: async func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; - /// Synchronize the data of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fdatasync` in POSIX. - @since(version = 0.3.0) - sync-data: async func() -> result<_, error-code>; - /// Get flags associated with a descriptor. - /// - /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. - /// - /// Note: This returns the value that was the `fs_flags` value returned - /// from `fdstat_get` in earlier versions of WASI. - @since(version = 0.3.0) - get-flags: async func() -> result; - /// Get the dynamic type of a descriptor. - /// - /// Note: This returns the same value as the `type` field of the `fd-stat` - /// returned by `stat`, `stat-at` and similar. - /// - /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided - /// by `fstat` in POSIX. - /// - /// Note: This returns the value that was the `fs_filetype` value returned - /// from `fdstat_get` in earlier versions of WASI. - @since(version = 0.3.0) - get-type: async func() -> result; - /// Adjust the size of an open file. If this increases the file's size, the - /// extra bytes are filled with zeros. - /// - /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. - @since(version = 0.3.0) - set-size: async func(size: filesize) -> result<_, error-code>; - /// Adjust the timestamps of an open file or directory. - /// - /// Note: This is similar to `futimens` in POSIX. - /// - /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. - @since(version = 0.3.0) - set-times: async func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; - /// Read directory entries from a directory. - /// - /// On filesystems where directories contain entries referring to themselves - /// and their parents, often named `.` and `..` respectively, these entries - /// are omitted. - /// - /// This always returns a new stream which starts at the beginning of the - /// directory. Multiple streams may be active on the same directory, and they - /// do not interfere with each other. - /// - /// This function returns a future, which will resolve to an error code if - /// reading full contents of the directory fails. - @since(version = 0.3.0) - read-directory: func() -> tuple, future>>; - /// Synchronize the data and metadata of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fsync` in POSIX. - @since(version = 0.3.0) - sync: async func() -> result<_, error-code>; - /// Create a directory. - /// - /// Note: This is similar to `mkdirat` in POSIX. - @since(version = 0.3.0) - create-directory-at: async func(path: string) -> result<_, error-code>; - /// Return the attributes of an open file or directory. - /// - /// Note: This is similar to `fstat` in POSIX, except that it does not return - /// device and inode information. For testing whether two descriptors refer to - /// the same underlying filesystem object, use `is-same-object`. To obtain - /// additional data that can be used do determine whether a file has been - /// modified, use `metadata-hash`. - /// - /// Note: This was called `fd_filestat_get` in earlier versions of WASI. - @since(version = 0.3.0) - stat: async func() -> result; - /// Return the attributes of a file or directory. - /// - /// Note: This is similar to `fstatat` in POSIX, except that it does not - /// return device and inode information. See the `stat` description for a - /// discussion of alternatives. - /// - /// Note: This was called `path_filestat_get` in earlier versions of WASI. - @since(version = 0.3.0) - stat-at: async func(path-flags: path-flags, path: string) -> result; - /// Adjust the timestamps of a file or directory. - /// - /// Note: This is similar to `utimensat` in POSIX. - /// - /// Note: This was called `path_filestat_set_times` in earlier versions of - /// WASI. - @since(version = 0.3.0) - set-times-at: async func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; - /// Create a hard link. - /// - /// Fails with `error-code::no-entry` if the old path does not exist, - /// with `error-code::exist` if the new path already exists, and - /// `error-code::not-permitted` if the old path is not a file. - /// - /// Note: This is similar to `linkat` in POSIX. - @since(version = 0.3.0) - link-at: async func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; - /// Open a file or directory. - /// - /// If `flags` contains `descriptor-flags::mutate-directory`, and the base - /// descriptor doesn't have `descriptor-flags::mutate-directory` set, - /// `open-at` fails with `error-code::read-only`. - /// - /// If `flags` contains `write` or `mutate-directory`, or `open-flags` - /// contains `truncate` or `create`, and the base descriptor doesn't have - /// `descriptor-flags::mutate-directory` set, `open-at` fails with - /// `error-code::read-only`. - /// - /// Note: This is similar to `openat` in POSIX. - @since(version = 0.3.0) - open-at: async func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; - /// Read the contents of a symbolic link. - /// - /// If the contents contain an absolute or rooted path in the underlying - /// filesystem, this function fails with `error-code::not-permitted`. - /// - /// Note: This is similar to `readlinkat` in POSIX. - @since(version = 0.3.0) - readlink-at: async func(path: string) -> result; - /// Remove a directory. - /// - /// Return `error-code::not-empty` if the directory is not empty. - /// - /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - @since(version = 0.3.0) - remove-directory-at: async func(path: string) -> result<_, error-code>; - /// Rename a filesystem object. - /// - /// Note: This is similar to `renameat` in POSIX. - @since(version = 0.3.0) - rename-at: async func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; - /// Create a symbolic link (also known as a "symlink"). - /// - /// If `old-path` starts with `/`, the function fails with - /// `error-code::not-permitted`. - /// - /// Note: This is similar to `symlinkat` in POSIX. - @since(version = 0.3.0) - symlink-at: async func(old-path: string, new-path: string) -> result<_, error-code>; - /// Unlink a filesystem object that is not a directory. - /// - /// This is similar to `unlinkat(fd, path, 0)` in POSIX. - /// - /// Error returns are as specified by POSIX. - /// - /// If the filesystem object is a directory, `error-code::access` or - /// `error-code::is-directory` may be returned instead of the - /// POSIX-specified `error-code::not-permitted`. - @since(version = 0.3.0) - unlink-file-at: async func(path: string) -> result<_, error-code>; - /// Test whether two descriptors refer to the same filesystem object. - /// - /// In POSIX, this corresponds to testing whether the two descriptors have the - /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. - /// wasi-filesystem does not expose device and inode numbers, so this function - /// may be used instead. - @since(version = 0.3.0) - is-same-object: async func(other: borrow) -> bool; - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a descriptor. - /// - /// This returns a hash of the last-modification timestamp and file size, and - /// may also include the inode number, device number, birth timestamp, and - /// other metadata fields that may change when the file is modified or - /// replaced. It may also include a secret value chosen by the - /// implementation and not otherwise exposed. - /// - /// Implementations are encouraged to provide the following properties: - /// - /// - If the file is not modified or replaced, the computed hash value should - /// usually not change. - /// - If the object is modified or replaced, the computed hash value should - /// usually change. - /// - The inputs to the hash should not be easily computable from the - /// computed hash. - /// - /// However, none of these is required. - @since(version = 0.3.0) - metadata-hash: async func() -> result; - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a directory descriptor and a relative path. - /// - /// This performs the same hash computation as `metadata-hash`. - @since(version = 0.3.0) - metadata-hash-at: async func(path-flags: path-flags, path: string) -> result; - } -} - -@since(version = 0.3.0) -interface preopens { - @since(version = 0.3.0) - use types.{descriptor}; - - /// Return the set of preopened directories, and their paths. - @since(version = 0.3.0) - get-directories: func() -> list>; -} - -@since(version = 0.3.0) -world imports { - @since(version = 0.3.0) - import wasi:clocks/types@0.3.0; - @since(version = 0.3.0) - import wasi:clocks/system-clock@0.3.0; - @since(version = 0.3.0) - import types; - @since(version = 0.3.0) - import preopens; -} diff --git a/components/wkg.lock b/components/wkg.lock index 57c4824..3de086b 100644 --- a/components/wkg.lock +++ b/components/wkg.lock @@ -9,7 +9,7 @@ registry = "componentized.dev" [[packages.versions]] requirement = "=0.1.0-dev" version = "0.1.0-dev" -digest = "sha256:1c43656521dfd238a67af2288f7abcf67e2ebd950352a90c396dcf11b25c4440" +digest = "sha256:f74b53af4b5ecb4c77e8bd47887920e0626efb2e45e8a9386f2519910faf5e5c" [[packages]] name = "wasi:filesystem" diff --git a/lib/.gitignore b/lib/.gitignore deleted file mode 100644 index ac4a381..0000000 --- a/lib/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.wasm -*.md diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh new file mode 100755 index 0000000..a3a9666 --- /dev/null +++ b/scripts/bump-version.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +# Bump the version of the wit interface package, and of the crates. +# +# 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 requirement on the library, move to the +# new version too. 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 + +set -euo pipefail + +cd "$(dirname "$0")/.." + +PACKAGE="${PACKAGE:-componentized:$(basename $(git rev-parse --show-toplevel))}" +# the library crate, the workspace's requirement on it moves to the new version +LIBRARY="${LIBRARY:-componentized-constants}" +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=. + 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 + +# 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 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 + +old_re="${old//./\\.}" +# references to the package or one of its interfaces, an interface named for a keyword is escaped +# with `%`, e.g. `componentized:constants/%u8@0.1.0` +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 +files=$(git grep --untracked -l -E "${ref_re}@${old_re}" -- ':(exclude,glob)**/wit/deps/**' ':(exclude,glob)**/wkg.lock' || 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 + +# the version in the [workspace.package] section, inherited by the crates +perl -pi -e 'if (/^\[workspace\.package\]/ .. /^\[(?!workspace\.package\])/) { s/^version = "[^"]*"/version = "'"${new}"'"/ }' Cargo.toml +echo "updated the workspace version in Cargo.toml" +perl -pi -e 's/^(\Q'"${LIBRARY}"'\E = \{.*\bversion = ")[^"]*(")/${1}'"${new}"'${2}/' Cargo.toml +echo "updated the ${LIBRARY} requirement in Cargo.toml" + +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 wit components test + +echo "bumped ${PACKAGE} from ${old} to ${new}" \ No newline at end of file diff --git a/scripts/init-devcontainer.sh b/scripts/init-devcontainer.sh new file mode 100755 index 0000000..59f0186 --- /dev/null +++ b/scripts/init-devcontainer.sh @@ -0,0 +1,12 @@ +#!/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 + +cargo check + +echo "export \"PATH=$(make -s tools-path):${PATH}\"" >> ~/.bashrc +make tools diff --git a/tools/Cargo.toml b/tools/Cargo.toml new file mode 100644 index 0000000..ce7848a --- /dev/null +++ b/tools/Cargo.toml @@ -0,0 +1,24 @@ +# The versions of the cli tools the build uses, installed by `make tools` with cargo binstall. +# +# This package is never built, it lists the tools as dependencies so dependabot bumps them. Each +# tool is pinned to an exact version with `=`, the Makefile installs that version. +[package] +name = "tools" +version = "0.0.0" +edition = "2024" +license = "Apache-2.0" +publish = false + +[lib] +path = "lib.rs" + +[dependencies] +componentized-constants-cli = "=0.1.0-dev" +static-config = "=0.2.0" +wac-cli = "=0.12.0" +wasm-tools = "=1.260.0" +wasmtime-cli = "=49.0.2" +wkg = "=0.16.1" + +# not a member of the repository's workspace +[workspace] diff --git a/tools/lib.rs b/tools/lib.rs new file mode 100644 index 0000000..d3769d7 --- /dev/null +++ b/tools/lib.rs @@ -0,0 +1 @@ +//! Never built, see `Cargo.toml`.