From 576526d5455b1c1fe89dd70de1d3acc5cc43dbd2 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sat, 6 Jul 2024 21:21:18 +0000 Subject: [PATCH 01/12] chore: remove cli::error from core/error.rs --- src/cli/error.rs | 5 ++++- src/cli/javascript/runtime.rs | 8 ++++---- src/cli/tc/run.rs | 2 +- src/cli/tc/start.rs | 2 +- src/core/error.rs | 14 +++++++------- src/main.rs | 1 + 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/cli/error.rs b/src/cli/error.rs index 77b48bf25f..01febfc672 100644 --- a/src/cli/error.rs +++ b/src/cli/error.rs @@ -7,8 +7,8 @@ use opentelemetry::metrics::MetricsError; use opentelemetry::trace::TraceError; use tokio::task::JoinError; -use crate::core::rest; use crate::core::valid::ValidationError; +use crate::core::{error, rest}; #[derive(From, thiserror::Error, Debug)] pub enum Error { @@ -95,6 +95,9 @@ pub enum Error { #[error("Validation Error : {0}")] Validation(ValidationError), + + #[error("Core Error")] + CoreError(error::Error), } pub type Result = std::result::Result; diff --git a/src/cli/javascript/runtime.rs b/src/cli/javascript/runtime.rs index 3f8d6d8b57..c0fde15c87 100644 --- a/src/cli/javascript/runtime.rs +++ b/src/cli/javascript/runtime.rs @@ -94,8 +94,8 @@ impl WorkerIO for Runtime { if let Some(runtime) = &self.tokio_runtime { runtime .spawn(async move { - init_rt(script)?; - call(name, event).map_err(worker::Error::from) + let _ = init_rt(script).map_err(|e| worker::Error::CLI(e.to_string())); + call(name, event).map_err(|e| worker::Error::CLI(e.to_string())) }) .await .map_err(|_| worker::Error::ExecutionFailed)? @@ -118,10 +118,10 @@ impl WorkerIO for Runtime { if let Some(runtime) = &self.tokio_runtime { runtime .spawn(async move { - init_rt(script)?; + let _ = init_rt(script).map_err(|e| worker::Error::CLI(e.to_string())); execute_inner(name, value) .map(Some) - .map_err(worker::Error::from) + .map_err(|e| worker::Error::CLI(e.to_string())) }) .await .map_err(|_| worker::Error::ExecutionFailed)? diff --git a/src/cli/tc/run.rs b/src/cli/tc/run.rs index 0b4cf8fb4c..7e6414808c 100644 --- a/src/cli/tc/run.rs +++ b/src/cli/tc/run.rs @@ -5,10 +5,10 @@ use dotenvy::dotenv; use super::helpers::TRACKER; use super::{check, gen, init, start}; use crate::cli::command::{Cli, Command}; +use crate::cli::error::Error; use crate::cli::{self, update_checker}; use crate::core::blueprint::Blueprint; use crate::core::config::reader::ConfigReader; -use crate::core::error::Error; use crate::core::runtime::TargetRuntime; pub async fn run() -> Result<(), Error> { diff --git a/src/cli/tc/start.rs b/src/cli/tc/start.rs index 27bc0f2a0e..57ad8cbfb9 100644 --- a/src/cli/tc/start.rs +++ b/src/cli/tc/start.rs @@ -1,8 +1,8 @@ use super::helpers::log_endpoint_set; +use crate::cli::error::Error; use crate::cli::fmt::Fmt; use crate::cli::server::Server; use crate::core::config::reader::ConfigReader; -use crate::core::error::Error; pub(super) async fn start_command( file_paths: Vec, diff --git a/src/core/error.rs b/src/core/error.rs index b45c73fc72..2240becb90 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -13,7 +13,6 @@ use super::grpc::error::Error as GrpcError; use super::ir; use super::rest::error::Error as RestError; use super::valid::ValidationError; -use crate::cli::error::Error as CLIError; use crate::cli::generator::source::UnsupportedFileFormat; #[derive(From, thiserror::Error, Debug)] @@ -114,9 +113,6 @@ pub enum Error { #[error("Worker Error")] Worker(worker::Error), - #[error("CLI Error")] - CLI(CLIError), - #[error("Inquire Error")] Inquire(InquireError), @@ -179,6 +175,10 @@ pub enum Error { #[error("Failed to find corresponding type for value")] MissingTypeForValue, + + #[error("CLI Error : {0}")] + #[from(ignore)] + CLI(String), } pub mod file { @@ -329,11 +329,11 @@ pub mod worker { #[error("Hyper Header To Str Error")] HyperHeaderStr(hyper::header::ToStrError), - #[error("CLI Error")] - CLI(crate::cli::error::Error), - #[error("JS Runtime Stopped Error")] JsRuntimeStopped, + + #[error("CLI Error : {0}")] + CLI(String), } } diff --git a/src/main.rs b/src/main.rs index 0f832973f5..1ee6d3f799 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ fn run_blocking() -> Result<(), Error> { .enable_all() .build()?; rt.block_on(async { tailcall::cli::run().await }) + .map_err(|e| Error::CLI(e.to_string())) } fn main() -> Result<(), Error> { From abd241d9733cf97afb5f2e787b9f574573981b03 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sat, 6 Jul 2024 21:37:05 +0000 Subject: [PATCH 02/12] test: need to run ci on stack PR [will revert later] --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 326441520a..a561163f10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,7 +5,6 @@ on: branches: - main pull_request: - branches: [main] types: [opened, reopened, synchronize] permissions: contents: read From 7930e47cb6637ca817ed46ac016ea292cbc0293c Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sat, 6 Jul 2024 21:49:41 +0000 Subject: [PATCH 03/12] chore: commented out ci jobs that aren't required --- .github/workflows/ci.yml | 550 +++++++++++++++++++-------------------- 1 file changed, 275 insertions(+), 275 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a561163f10..ab960a76ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -180,280 +180,280 @@ jobs: - name: Check all examples run: ./examples/lint.sh - draft_release: - name: Draft Release - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - steps: - - name: Checkout Current Branch (Fast) - uses: actions/checkout@v4 - - - id: create_release - uses: release-drafter/release-drafter@v6 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - config-name: release-drafter.yml - - - name: Set Output for Later Jobs - id: set_output - run: | - echo "create_release_name=${{ steps.create_release.outputs.name }}" >> $GITHUB_OUTPUT - echo "create_release_id=${{ steps.create_release.outputs.id }}" >> $GITHUB_OUTPUT - outputs: - create_release_name: ${{ steps.set_output.outputs.create_release_name }} - create_release_id: ${{ steps.set_output.outputs.create_release_id }} + # draft_release: + # name: Draft Release + # if: github.event_name == 'push' && github.ref == 'refs/heads/main' + # runs-on: ubuntu-latest + # permissions: + # contents: write + # pull-requests: write + # steps: + # - name: Checkout Current Branch (Fast) + # uses: actions/checkout@v4 + + # - id: create_release + # uses: release-drafter/release-drafter@v6 + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # with: + # config-name: release-drafter.yml + + # - name: Set Output for Later Jobs + # id: set_output + # run: | + # echo "create_release_name=${{ steps.create_release.outputs.name }}" >> $GITHUB_OUTPUT + # echo "create_release_id=${{ steps.create_release.outputs.id }}" >> $GITHUB_OUTPUT + # outputs: + # create_release_name: ${{ steps.set_output.outputs.create_release_name }} + # create_release_id: ${{ steps.set_output.outputs.create_release_id }} # TODO: move to separate file to separate responsibilities - release: - name: Release - needs: [setup_build_matrix, test, draft_release, check_if_build, test_cf] - # TODO: put a condition to separate job that other will depend on to remove duplication? - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') - runs-on: ${{ matrix.os || 'ubuntu-latest' }} - strategy: - fail-fast: false - matrix: ${{ fromJson(needs.setup_build_matrix.outputs.matrix) }} - permissions: - contents: write - pull-requests: write - env: - GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} - APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - - steps: - - name: Checkout Current Branch (Fast) - uses: actions/checkout@v4 - - - name: Install Rust Toolchain - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - target: ${{ matrix.target }} - - - name: Build - env: - APP_VERSION: ${{ needs.draft_release.outputs.create_release_name}} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - uses: ClementTsang/cargo-action@v0.0.6 - with: - use-cross: ${{ matrix.cross }} - command: build - args: ${{matrix.features}} --release --target ${{ matrix.target }} - - - name: Install Node.js - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - uses: actions/setup-node@v4 - with: - node-version: 20.11.0 - registry-url: https://registry.npmjs.org - - - name: Install dependencies - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - run: | - cd npm - npm install - - - name: Run generate.js script - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - run: | - cd npm - npm run gen -- --target ${{matrix.target}} --version ${{ env.APP_VERSION }} --build ${{matrix.build}} --ext ${{ matrix.ext || '' }} --libc ${{ matrix.libc }} - - name: Setup .npmrc file to publish to npm - run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc - - - name: NPM Publish - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - uses: JS-DevTools/npm-publish@main - with: - token: ${{ secrets.NPM_TOKEN }} - package: npm/@tailcallhq/core-${{matrix.build}} - access: public - - - name: Rename Binary with Target Name - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - run: | - pwd - cp target/${{ matrix.target }}/release/tailcall${{ matrix.ext }} target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} - - - name: Upload ${{ matrix.target }} Binary - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - uses: xresloader/upload-to-github-release@v1 - with: - release_id: ${{ needs.draft_release.outputs.create_release_id }} - file: target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} - overwrite: true - release_lambda: - name: Release (AWS Lambda) - needs: [test, draft_release, check_if_build, test_cf] - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - env: - GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} - APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - - steps: - - name: Checkout Current Branch (Fast) - uses: actions/checkout@v4 - - - name: Install Correct Toolchain - uses: actions-rust-lang/setup-rust-toolchain@v1 - - - name: Install Python - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - - name: Install cargo-lambda - run: pip install cargo-lambda - - - name: Build - env: - APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - run: cargo lambda build -p tailcall-aws-lambda --release --target x86_64-unknown-linux-musl - - - name: Rename Binary with Target Name - run: | - pwd - cp target/lambda/tailcall-aws-lambda/bootstrap target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap - - - name: Upload AWS Lambda Bootstrap Binary - uses: xresloader/upload-to-github-release@v1 - with: - release_id: ${{ needs.draft_release.outputs.create_release_id }} - file: target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap - overwrite: true - semantic_release: - name: Semantic Release - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - needs: [draft_release, release, release_lambda] - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - steps: - - name: Publish Release - uses: test-room-7/action-publish-release-drafts@v0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - tag-name: ${{needs.draft_release.outputs.create_release_name }} - - publish_npm_root: - name: Publish NPM main package - needs: [draft_release, release] - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - runs-on: ubuntu-latest - steps: - - name: Checkout Current Branch (Fast) - uses: actions/checkout@v4 - - name: Install Node - uses: actions/setup-node@v4 - with: - node-version: 20.11.0 - registry-url: https://registry.npmjs.org - - name: Install dependencies - run: | - cd npm - npm install - - name: Run generate-root.js script - env: - APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - run: | - cd npm - npm run gen-root -- --version ${{ env.APP_VERSION }} --name @tailcallhq/tailcall - - name: Setup .npmrc file to publish to npm - run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc - - name: Publish packages - uses: JS-DevTools/npm-publish@main - with: - token: ${{ secrets.NPM_TOKEN }} - package: npm/@tailcallhq/tailcall - access: public - - env: - APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - - build-and-push-image: - env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }}/tc-server - APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} # Ensure APP_VERSION is set correctly - needs: [draft_release, release] - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - runs-on: ubuntu-latest - # Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job. - permissions: - contents: read - packages: write - # - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. - - name: Log in to the Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUBTOKEN }} - # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. - - name: Extract Metadata (tags, labels) for Docker - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=raw,value=${{ env.APP_VERSION }} - type=raw,value=latest,enable=${{ endsWith(env.APP_VERSION, '-SNAPSHOT') == false }} - # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. - # It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository. - # It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step. - - name: Build and Push the Docker Image - uses: docker/build-push-action@v6 - with: - context: . - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - - homebrew-release: - name: Homebrew Release - needs: [draft_release, release, semantic_release] - if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - permissions: - contents: write - pull-requests: write - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - repository: tailcallhq/homebrew-tailcall - ref: main - token: ${{ secrets.HOMEBREW_ACCESS }} - - - name: Update Homebrew Formula - run: ./update-formula.sh ${{needs.draft_release.outputs.create_release_name }} - - failure-notification: - runs-on: ubuntu-latest - steps: - - name: Notify failure on Discord - if: ${{ always() && contains(needs.*.result, 'failure') }} - uses: discord-actions/message@v2 - with: - webhookUrl: ${{ secrets.DISCORD_WEBHOOK_URL }} - message: | - Build failed on branch: ${{ github.ref }} - Link: ${{ github.repository }}/actions/runs/${{ github.run_id }} + # release: + # name: Release + # needs: [setup_build_matrix, test, draft_release, check_if_build, test_cf] + # # TODO: put a condition to separate job that other will depend on to remove duplication? + # if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') + # runs-on: ${{ matrix.os || 'ubuntu-latest' }} + # strategy: + # fail-fast: false + # matrix: ${{ fromJson(needs.setup_build_matrix.outputs.matrix) }} + # permissions: + # contents: write + # pull-requests: write + # env: + # GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} + # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + + # steps: + # - name: Checkout Current Branch (Fast) + # uses: actions/checkout@v4 + + # - name: Install Rust Toolchain + # uses: actions-rust-lang/setup-rust-toolchain@v1 + # with: + # target: ${{ matrix.target }} + + # - name: Build + # env: + # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name}} + # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + # uses: ClementTsang/cargo-action@v0.0.6 + # with: + # use-cross: ${{ matrix.cross }} + # command: build + # args: ${{matrix.features}} --release --target ${{ matrix.target }} + + # - name: Install Node.js + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # uses: actions/setup-node@v4 + # with: + # node-version: 20.11.0 + # registry-url: https://registry.npmjs.org + + # - name: Install dependencies + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # run: | + # cd npm + # npm install + + # - name: Run generate.js script + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # run: | + # cd npm + # npm run gen -- --target ${{matrix.target}} --version ${{ env.APP_VERSION }} --build ${{matrix.build}} --ext ${{ matrix.ext || '' }} --libc ${{ matrix.libc }} + # - name: Setup .npmrc file to publish to npm + # run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc + + # - name: NPM Publish + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # uses: JS-DevTools/npm-publish@main + # with: + # token: ${{ secrets.NPM_TOKEN }} + # package: npm/@tailcallhq/core-${{matrix.build}} + # access: public + + # - name: Rename Binary with Target Name + # if: github.event_name == 'push' && github.ref == 'refs/heads/main' + # run: | + # pwd + # cp target/${{ matrix.target }}/release/tailcall${{ matrix.ext }} target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} + + # - name: Upload ${{ matrix.target }} Binary + # if: github.event_name == 'push' && github.ref == 'refs/heads/main' + # uses: xresloader/upload-to-github-release@v1 + # with: + # release_id: ${{ needs.draft_release.outputs.create_release_id }} + # file: target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} + # overwrite: true + # release_lambda: + # name: Release (AWS Lambda) + # needs: [test, draft_release, check_if_build, test_cf] + # if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') + # runs-on: ubuntu-latest + # permissions: + # contents: write + # pull-requests: write + # env: + # GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} + # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + + # steps: + # - name: Checkout Current Branch (Fast) + # uses: actions/checkout@v4 + + # - name: Install Correct Toolchain + # uses: actions-rust-lang/setup-rust-toolchain@v1 + + # - name: Install Python + # uses: actions/setup-python@v5 + # with: + # python-version: "3.12" + + # - name: Install cargo-lambda + # run: pip install cargo-lambda + + # - name: Build + # env: + # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + # run: cargo lambda build -p tailcall-aws-lambda --release --target x86_64-unknown-linux-musl + + # - name: Rename Binary with Target Name + # run: | + # pwd + # cp target/lambda/tailcall-aws-lambda/bootstrap target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap + + # - name: Upload AWS Lambda Bootstrap Binary + # uses: xresloader/upload-to-github-release@v1 + # with: + # release_id: ${{ needs.draft_release.outputs.create_release_id }} + # file: target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap + # overwrite: true + # semantic_release: + # name: Semantic Release + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # needs: [draft_release, release, release_lambda] + # runs-on: ubuntu-latest + # permissions: + # contents: write + # pull-requests: write + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + # steps: + # - name: Publish Release + # uses: test-room-7/action-publish-release-drafts@v0 + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # with: + # github-token: ${{ secrets.GITHUB_TOKEN }} + # tag-name: ${{needs.draft_release.outputs.create_release_name }} + + # publish_npm_root: + # name: Publish NPM main package + # needs: [draft_release, release] + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # runs-on: ubuntu-latest + # steps: + # - name: Checkout Current Branch (Fast) + # uses: actions/checkout@v4 + # - name: Install Node + # uses: actions/setup-node@v4 + # with: + # node-version: 20.11.0 + # registry-url: https://registry.npmjs.org + # - name: Install dependencies + # run: | + # cd npm + # npm install + # - name: Run generate-root.js script + # env: + # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + # run: | + # cd npm + # npm run gen-root -- --version ${{ env.APP_VERSION }} --name @tailcallhq/tailcall + # - name: Setup .npmrc file to publish to npm + # run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc + # - name: Publish packages + # uses: JS-DevTools/npm-publish@main + # with: + # token: ${{ secrets.NPM_TOKEN }} + # package: npm/@tailcallhq/tailcall + # access: public + + # env: + # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + # build-and-push-image: + # env: + # REGISTRY: ghcr.io + # IMAGE_NAME: ${{ github.repository }}/tc-server + # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} # Ensure APP_VERSION is set correctly + # needs: [draft_release, release] + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # runs-on: ubuntu-latest + # # Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job. + # permissions: + # contents: read + # packages: write + # # + # steps: + # - name: Checkout Repository + # uses: actions/checkout@v4 + # # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. + # - name: Log in to the Container Registry + # uses: docker/login-action@v3 + # with: + # registry: ${{ env.REGISTRY }} + # username: ${{ github.actor }} + # password: ${{ secrets.GITHUBTOKEN }} + # # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. + # - name: Extract Metadata (tags, labels) for Docker + # id: meta + # uses: docker/metadata-action@v5 + # with: + # images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + # tags: | + # type=raw,value=${{ env.APP_VERSION }} + # type=raw,value=latest,enable=${{ endsWith(env.APP_VERSION, '-SNAPSHOT') == false }} + # # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. + # # It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository. + # # It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step. + # - name: Build and Push the Docker Image + # uses: docker/build-push-action@v6 + # with: + # context: . + # push: true + # tags: ${{ steps.meta.outputs.tags }} + # labels: ${{ steps.meta.outputs.labels }} + + # homebrew-release: + # name: Homebrew Release + # needs: [draft_release, release, semantic_release] + # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + # permissions: + # contents: write + # pull-requests: write + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@v4 + # with: + # repository: tailcallhq/homebrew-tailcall + # ref: main + # token: ${{ secrets.HOMEBREW_ACCESS }} + + # - name: Update Homebrew Formula + # run: ./update-formula.sh ${{needs.draft_release.outputs.create_release_name }} + + # failure-notification: + # runs-on: ubuntu-latest + # steps: + # - name: Notify failure on Discord + # if: ${{ always() && contains(needs.*.result, 'failure') }} + # uses: discord-actions/message@v2 + # with: + # webhookUrl: ${{ secrets.DISCORD_WEBHOOK_URL }} + # message: | + # Build failed on branch: ${{ github.ref }} + # Link: ${{ github.repository }}/actions/runs/${{ github.run_id }} From 4470b302470ed1c5d4d0ec8efe8f29db3372ceac Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sat, 6 Jul 2024 22:08:50 +0000 Subject: [PATCH 04/12] chore: remove inquire error from core --- src/cli/generator/generator.rs | 4 ++-- src/cli/runtime/mod.rs | 6 +++--- src/core/error.rs | 17 ++++++++--------- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/cli/generator/generator.rs b/src/cli/generator/generator.rs index 8c4c884ece..cd8732972b 100644 --- a/src/cli/generator/generator.rs +++ b/src/cli/generator/generator.rs @@ -61,7 +61,7 @@ impl Generator { .as_str(), ) .with_default(false) - .prompt()?; + .prompt().map_err(|e| Error::Inquire(e.to_string()))?; if !should_overwrite { return Ok(false); } @@ -71,7 +71,7 @@ impl Generator { async fn read(&self) -> Result, Error> { let config_path = &self.config_path; - let source = ConfigSource::detect(config_path)?; + let source = ConfigSource::detect(config_path).map_err(|_|Error::UnsupportedFileFormat)?; let config_content = self.runtime.file.read(config_path).await?; let config: Config = match source { diff --git a/src/cli/runtime/mod.rs b/src/cli/runtime/mod.rs index 70a97100f4..94def4616e 100644 --- a/src/cli/runtime/mod.rs +++ b/src/cli/runtime/mod.rs @@ -95,7 +95,7 @@ pub async fn confirm_and_write( if file_exists { let confirm = Confirm::new(&format!("Do you want to overwrite the file {path}?")) .with_default(false) - .prompt()?; + .prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?; if !confirm { return Ok(()); @@ -116,7 +116,7 @@ pub async fn create_directory(folder_path: &str) -> Result<(), error::file::Erro folder_path )) .with_default(false) - .prompt()?; + .prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?; if confirm { fs::create_dir_all(folder_path)?; @@ -132,5 +132,5 @@ pub fn select_prompt( message: &str, options: Vec, ) -> Result { - Ok(Select::new(message, options).prompt()?) + Ok(Select::new(message, options).prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?) } diff --git a/src/core/error.rs b/src/core/error.rs index 2240becb90..61092087dc 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -2,7 +2,6 @@ use std::str::Utf8Error; use std::string::FromUtf8Error; use derive_more::From; -use inquire::InquireError; use opentelemetry::metrics::MetricsError; use opentelemetry::trace::TraceError; use prost_reflect::DescriptorError; @@ -13,7 +12,6 @@ use super::grpc::error::Error as GrpcError; use super::ir; use super::rest::error::Error as RestError; use super::valid::ValidationError; -use crate::cli::generator::source::UnsupportedFileFormat; #[derive(From, thiserror::Error, Debug)] pub enum Error { @@ -113,9 +111,6 @@ pub enum Error { #[error("Worker Error")] Worker(worker::Error), - #[error("Inquire Error")] - Inquire(InquireError), - #[error("IRError {0}")] IRError(ir::Error), @@ -165,7 +160,7 @@ pub enum Error { Headers(headers::Error), #[error("Unsupported File Format")] - UnsupportedFileFormat(UnsupportedFileFormat), + UnsupportedFileFormat, #[error("Failed to match type_name")] TypenameMatchFailed, @@ -179,13 +174,16 @@ pub enum Error { #[error("CLI Error : {0}")] #[from(ignore)] CLI(String), + + #[error("Inquire Error : {0}")] + #[from(ignore)] + Inquire(String), } pub mod file { use std::string::FromUtf8Error; use derive_more::From; - use inquire::InquireError; #[derive(From, thiserror::Error, Debug)] pub enum Error { @@ -230,8 +228,9 @@ pub mod file { #[from(ignore)] Cloudflare(String), - #[error("Inquire Error")] - Inquire(InquireError), + #[error("Inquire Error : {0}")] + #[from(ignore)] + Inquire(String), #[error("Serde yaml Error")] SerdeYaml(serde_yaml::Error), From 6fc6ae2ced3a44eb20e04b26f92b94fd85926afc Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 06:17:17 +0000 Subject: [PATCH 05/12] refactor: added debug_custom & removed thisError --- src/cli/error.rs | 69 ++++---- src/cli/generator/generator.rs | 5 +- src/cli/runtime/mod.rs | 10 +- src/core/error.rs | 261 ++++++++++++++++------------ src/core/grpc/error.rs | 36 ++-- src/core/rest/error.rs | 40 +++-- tailcall-cloudflare/src/error.rs | 28 +-- tailcall-fixtures/error.rs | 18 +- tailcall-prettier/src/error.rs | 24 ++- tailcall-tracker/src/error.rs | 20 ++- tailcall-upstream-grpc/src/error.rs | 24 ++- tests/core/error.rs | 47 ++--- 12 files changed, 345 insertions(+), 237 deletions(-) diff --git a/src/cli/error.rs b/src/cli/error.rs index 01febfc672..b8b361e119 100644 --- a/src/cli/error.rs +++ b/src/cli/error.rs @@ -1,6 +1,7 @@ +use std::fmt::Display; use std::string::FromUtf8Error; -use derive_more::From; +use derive_more::{From, DebugCustom}; use inquire::InquireError; use opentelemetry::logs::LogError; use opentelemetry::metrics::MetricsError; @@ -10,94 +11,100 @@ use tokio::task::JoinError; use crate::core::valid::ValidationError; use crate::core::{error, rest}; -#[derive(From, thiserror::Error, Debug)] +#[derive(From, DebugCustom)] pub enum Error { - #[error("Metrics Error")] + #[debug(fmt = "Metrics Error")] Metrics(MetricsError), - #[error("Rest Error")] + #[debug(fmt = "Rest Error")] Rest(rest::error::Error), - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("IO Error")] + #[debug(fmt = "IO Error")] IO(std::io::Error), - #[error("Telemetry Trace Error : {0}")] + #[debug(fmt = "Telemetry Trace Error : {}", _0)] TelemetryTrace(String), - #[error("Failed to send message")] + #[debug(fmt = "Failed to send message")] MessageSendFailure, - #[error("Hyper Error")] + #[debug(fmt = "Hyper Error")] Hyper(hyper::Error), - #[error("Rustls Error")] + #[debug(fmt = "Rustls Error")] Rustls(rustls::Error), - #[error("Join Error")] + #[debug(fmt = "Join Error")] Join(JoinError), - #[error("Opentelemetry Global Error")] + #[debug(fmt = "Opentelemetry Global Error")] OpentelemetryGlobal(opentelemetry::global::Error), - #[error("Trace Error")] + #[debug(fmt = "Trace Error")] Trace(TraceError), - #[error("Log Error")] + #[debug(fmt = "Log Error")] Log(LogError), - #[error("Utf8 Error")] + #[debug(fmt = "Utf8 Error")] Utf8(FromUtf8Error), - #[error("Inquire Error")] + #[debug(fmt = "Inquire Error")] Inquire(InquireError), - #[error("Serde Yaml Error")] + #[debug(fmt = "Serde Yaml Error")] SerdeYaml(serde_yaml::Error), - #[error("Invalid Header Name")] + #[debug(fmt = "Invalid Header Name")] InvalidHeaderName(hyper::header::InvalidHeaderName), - #[error("Invalid Header Value")] + #[debug(fmt = "Invalid Header Value")] InvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[error("rquickjs Error")] + #[debug(fmt = "rquickjs Error")] RQuickjs(rquickjs::Error), - #[error("Trying to reinitialize an already initialized QuickJS runtime")] + #[debug(fmt = "Trying to reinitialize an already initialized QuickJS runtime")] ReinitializeQuickjsRuntime, - #[error("Runtime not initialized")] + #[debug(fmt = "Runtime not initialized")] RuntimeNotInitialized, - #[error("Deserialize Failed")] + #[debug(fmt = "Deserialize Failed")] DeserializeFailed, - #[error("Not a function error")] + #[debug(fmt = "Not a function error")] InvalidFunction, - #[error("Init Process Observer Error")] + #[debug(fmt = "Init Process Observer Error")] InitProcessObserver, - #[error("JS Runtime is stopped")] + #[debug(fmt = "JS Runtime is stopped")] JsRuntimeStopped, - #[error("Rustls internal error")] + #[debug(fmt = "Rustls internal error")] RustlsInternal, - #[error("Reqwest middleware error")] + #[debug(fmt = "Reqwest middleware error")] ReqwestMiddleware(reqwest_middleware::Error), - #[error("Reqwest error")] + #[debug(fmt = "Reqwest error")] Reqwest(reqwest::Error), - #[error("Validation Error : {0}")] + #[debug(fmt = "Validation Error : {}", _0)] Validation(ValidationError), - #[error("Core Error")] + #[debug(fmt = "Core Error")] CoreError(error::Error), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/src/cli/generator/generator.rs b/src/cli/generator/generator.rs index cd8732972b..dc7c29d738 100644 --- a/src/cli/generator/generator.rs +++ b/src/cli/generator/generator.rs @@ -61,7 +61,8 @@ impl Generator { .as_str(), ) .with_default(false) - .prompt().map_err(|e| Error::Inquire(e.to_string()))?; + .prompt() + .map_err(|e| Error::Inquire(e.to_string()))?; if !should_overwrite { return Ok(false); } @@ -71,7 +72,7 @@ impl Generator { async fn read(&self) -> Result, Error> { let config_path = &self.config_path; - let source = ConfigSource::detect(config_path).map_err(|_|Error::UnsupportedFileFormat)?; + let source = ConfigSource::detect(config_path).map_err(|_| Error::UnsupportedFileFormat)?; let config_content = self.runtime.file.read(config_path).await?; let config: Config = match source { diff --git a/src/cli/runtime/mod.rs b/src/cli/runtime/mod.rs index 94def4616e..e2066a6cdc 100644 --- a/src/cli/runtime/mod.rs +++ b/src/cli/runtime/mod.rs @@ -95,7 +95,8 @@ pub async fn confirm_and_write( if file_exists { let confirm = Confirm::new(&format!("Do you want to overwrite the file {path}?")) .with_default(false) - .prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?; + .prompt() + .map_err(|e| error::file::Error::Inquire(e.to_string()))?; if !confirm { return Ok(()); @@ -116,7 +117,8 @@ pub async fn create_directory(folder_path: &str) -> Result<(), error::file::Erro folder_path )) .with_default(false) - .prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?; + .prompt() + .map_err(|e| error::file::Error::Inquire(e.to_string()))?; if confirm { fs::create_dir_all(folder_path)?; @@ -132,5 +134,7 @@ pub fn select_prompt( message: &str, options: Vec, ) -> Result { - Ok(Select::new(message, options).prompt().map_err(|e| error::file::Error::Inquire(e.to_string()))?) + Ok(Select::new(message, options) + .prompt() + .map_err(|e| error::file::Error::Inquire(e.to_string()))?) } diff --git a/src/core/error.rs b/src/core/error.rs index 61092087dc..743dc4b93f 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -1,7 +1,8 @@ +use std::fmt::Display; use std::str::Utf8Error; use std::string::FromUtf8Error; -use derive_more::From; +use derive_more::{From, DebugCustom}; use opentelemetry::metrics::MetricsError; use opentelemetry::trace::TraceError; use prost_reflect::DescriptorError; @@ -13,169 +14,169 @@ use super::ir; use super::rest::error::Error as RestError; use super::valid::ValidationError; -#[derive(From, thiserror::Error, Debug)] +#[derive(From, DebugCustom)] pub enum Error { - #[error("Std IO Error")] + #[debug(fmt = "Std IO Error")] StdIO(std::io::Error), - #[error("Utf8 Error")] + #[debug(fmt = "Utf8 Error")] FromUtf8(FromUtf8Error), - #[error("Validation Error : {0}")] + #[debug(fmt = "Validation Error : {}", _0)] Validation(ValidationError), - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("Serde Yaml Error")] + #[debug(fmt = "Serde Yaml Error")] SerdeYaml(serde_yaml::Error), - #[error("Descriptor Error")] + #[debug(fmt = "Descriptor Error")] Descriptor(DescriptorError), - #[error("Expected fully-qualified name for reference type but got {0}")] + #[debug(fmt = "Expected fully-qualified name for reference type but got {}", _0)] InvalidReferenceTypeName(String), - #[error("Package name is required")] + #[debug(fmt = "Package name is required")] PackageNameNotFound, - #[error("Protox Parse Error")] + #[debug(fmt = "Protox Parse Error")] ProtoxParse(protox_parse::ParseError), - #[error("URL Parse Error")] + #[debug(fmt = "URL Parse Error")] UrlParse(url::ParseError), - #[error("Unable to extract content of google well-known proto file")] + #[debug(fmt = "Unable to extract content of google well-known proto file")] GoogleProtoFileContentNotExtracted, - #[error("Unsupported Config Format")] + #[debug(fmt = "Unsupported Config Format")] UnsupportedConfigFormat(UnsupportedConfigFormat), - #[error("Couldn't find definitions for service ServerReflection")] + #[debug(fmt = "Couldn't find definitions for service ServerReflection")] MissingServerReflectionDefinitions, - #[error("Grpc Error")] + #[debug(fmt = "Grpc Error")] Grpc(GrpcError), - #[error("Serde Path To Error")] + #[debug(fmt = "Serde Path To Error")] SerdePath(serde_path_to_error::Error), - #[error("Rest Error")] + #[debug(fmt = "Rest Error")] Rest(RestError), - #[error("Expected fileDescriptorResponse but found none")] + #[debug(fmt = "Expected fileDescriptorResponse but found none")] MissingFileDescriptorResponse, - #[error("Prost Decode Error")] + #[debug(fmt = "Prost Decode Error")] ProstDecode(prost::DecodeError), - #[error("Received empty fileDescriptorProto")] + #[debug(fmt = "Received empty fileDescriptorProto")] EmptyFileDescriptorProto, - #[error("Failed to decode fileDescriptorProto from BASE64")] + #[debug(fmt = "Failed to decode fileDescriptorProto from BASE64")] FileDescriptorProtoDecodeFailed, - #[error("Invalid header value")] + #[debug(fmt = "Invalid header value")] HyperInvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[error("Invalid header name")] + #[debug(fmt = "Invalid header name")] HyperInvalidHeaderName(hyper::header::InvalidHeaderName), - #[error("Hyper HTTP Error")] + #[debug(fmt = "Hyper HTTP Error")] HyperHttpError(hyper::http::Error), - #[error("Prometheus Error")] + #[debug(fmt = "Prometheus Error")] Prometheus(prometheus::Error), - #[error("Hyper Error")] + #[debug(fmt = "Hyper Error")] Hyper(hyper::Error), - #[error("Invalid URI")] + #[debug(fmt = "Invalid URI")] InvalidUri(hyper::http::uri::InvalidUri), - #[error("Mustache cannot be converted to const value")] + #[debug(fmt = "Mustache cannot be converted to const value")] InvalidMustacheConstConversion, - #[error("Protox Error")] + #[debug(fmt = "Protox Error")] Protox(protox::Error), - #[error("Failed to execute request")] + #[debug(fmt = "Failed to execute request")] RequestExecutionFailed, - #[error("File Error: {0}")] + #[debug(fmt = "File Error: {}", _0)] File(file::Error), - #[error("Http Error")] + #[debug(fmt = "Http Error")] Http(http::Error), - #[error("Worker Error")] + #[debug(fmt = "Worker Error")] Worker(worker::Error), - #[error("IRError {0}")] + #[debug(fmt = "IRError {}", _0)] IRError(ir::Error), - #[error("Serde URL Encoded Error")] + #[debug(fmt = "Serde URL Encoded Error")] SerdeUrlEncoded(serde_urlencoded::ser::Error), - #[error("Hyper Header ToStr Error")] + #[debug(fmt = "Hyper Header ToStr Error")] HyperHeaderToStr(hyper::header::ToStrError), - #[error("Utf8 Error")] + #[debug(fmt = "Utf8 Error")] Utf8(Utf8Error), - #[error("Rand Error")] + #[debug(fmt = "Rand Error")] Rand(rand::Error), - #[error("Trace Error")] + #[debug(fmt = "Trace Error")] Trace(TraceError), - #[error("Join Error")] + #[debug(fmt = "Join Error")] Join(JoinError), - #[error("Metrics Error")] + #[debug(fmt = "Metrics Error")] Metrics(MetricsError), - #[error("Reqwest Error")] + #[debug(fmt = "Reqwest Error")] Reqwest(reqwest::Error), - #[error("Unable to determine path")] + #[debug(fmt = "Unable to determine path")] PathDeterminationFailed, - #[error("Schema mismatch Error")] + #[debug(fmt = "Schema mismatch Error")] SchemaMismatch, - #[error("Failed to resolve parent value")] + #[debug(fmt = "Failed to resolve parent value")] ParentValueNotResolved, - #[error("Expected parent list index")] + #[debug(fmt = "Expected parent list index")] ExpectedParentListIndex, - #[error("Can't resolve value for field")] + #[debug(fmt = "Can't resolve value for field")] FieldValueNotResolved, - #[error("Expected list value")] + #[debug(fmt = "Expected list value")] ExpectedListValue, - #[error("Headers Error")] + #[debug(fmt = "Headers Error")] Headers(headers::Error), - #[error("Unsupported File Format")] + #[debug(fmt = "Unsupported File Format")] UnsupportedFileFormat, - #[error("Failed to match type_name")] + #[debug(fmt = "Failed to match type_name")] TypenameMatchFailed, - #[error("Value expected to be object")] + #[debug(fmt = "Value expected to be object")] ObjectExpected, - #[error("Failed to find corresponding type for value")] + #[debug(fmt = "Failed to find corresponding type for value")] MissingTypeForValue, - #[error("CLI Error : {0}")] + #[debug(fmt = "CLI Error : {}", _0)] #[from(ignore)] CLI(String), - #[error("Inquire Error : {0}")] + #[debug(fmt = "Inquire Error : {}", _0)] #[from(ignore)] Inquire(String), } @@ -183,56 +184,56 @@ pub enum Error { pub mod file { use std::string::FromUtf8Error; - use derive_more::From; + use derive_more::{From, DebugCustom}; - #[derive(From, thiserror::Error, Debug)] + #[derive(From, DebugCustom)] pub enum Error { - #[error("No such file or directory (os error 2)")] + #[debug(fmt = "No such file or directory (os error 2)")] NotFound, - #[error("No permission to access the file")] + #[debug(fmt = "No permission to access the file")] NoPermission, - #[error("Access denied")] + #[debug(fmt = "Access denied")] AccessDenied, - #[error("Invalid file format")] + #[debug(fmt = "Invalid file format")] InvalidFormat, - #[error("Invalid file path")] + #[debug(fmt = "Invalid file path")] InvalidFilePath, - #[error("Invalid OS string")] + #[debug(fmt = "Invalid OS string")] InvalidOsString, - #[error("Failed to read file : {0}")] + #[debug(fmt = "Failed to read file : {}", _0)] FileReadFailed(String), - #[error("Failed to write file : {0}")] + #[debug(fmt = "Failed to write file : {}", _0)] #[from(ignore)] FileWriteFailed(String), - #[error("Std IO Error")] + #[debug(fmt = "Std IO Error")] StdIO(std::io::Error), - #[error("Utf8 Error")] + #[debug(fmt = "Utf8 Error")] Utf8(FromUtf8Error), - #[error("File writing not supported on Lambda.")] + #[debug(fmt = "File writing not supported on Lambda.")] LambdaFileWriteNotSupported, - #[error("Cannot write to a file in an execution spec")] + #[debug(fmt = "Cannot write to a file in an execution spec")] ExecutionSpecFileWriteFailed, - #[error("Cloudflare Worker Execution Error : {0}")] + #[debug(fmt = "Cloudflare Worker Execution Error : {}", _0)] #[from(ignore)] Cloudflare(String), - #[error("Inquire Error : {0}")] + #[debug(fmt = "Inquire Error : {}", _0)] #[from(ignore)] Inquire(String), - #[error("Serde yaml Error")] + #[debug(fmt = "Serde yaml Error")] SerdeYaml(serde_yaml::Error), } } @@ -240,132 +241,168 @@ pub mod file { pub mod http { use std::string::FromUtf8Error; - use derive_more::From; + use derive_more::{From, DebugCustom}; - #[derive(From, thiserror::Error, Debug)] + #[derive(From, DebugCustom)] pub enum Error { - #[error("HTTP request failed with status code: {status_code}")] + #[debug(fmt = "HTTP request failed with status code: {status_code}")] RequestFailed { status_code: u16 }, - #[error("Timeout occurred while making the HTTP request")] + #[debug(fmt = "Timeout occurred while making the HTTP request")] Timeout, - #[error("Failed to parse the response body")] + #[debug(fmt = "Failed to parse the response body")] ResponseParse, - #[error("Invalid URL: {url}")] + #[debug(fmt = "Invalid URL: {url}")] InvalidUrl { url: String }, - #[error("Reqwest Middleware Error")] + #[debug(fmt = "Reqwest Middleware Error")] ReqwestMiddleware(reqwest_middleware::Error), - #[error("Tonic Status Error")] + #[debug(fmt = "Tonic Status Error")] TonicStatus(tonic::Status), - #[error("Reqwest Error")] + #[debug(fmt = "Reqwest Error")] Reqwest(reqwest::Error), - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("Unable to find key {0} in query params")] + #[debug(fmt = "Unable to find key {} in query params", _0)] #[from(ignore)] KeyNotFound(String), - #[error("Invalid Status Code")] + #[debug(fmt = "Invalid Status Code")] InvalidStatusCode(hyper::http::status::InvalidStatusCode), - #[error("Status Code error")] + #[debug(fmt = "Status Code error")] StatusCode, - #[error("Invalid Header Value")] + #[debug(fmt = "Invalid Header Value")] InvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[error("Invalid Header Name")] + #[debug(fmt = "Invalid Header Name")] InvalidHeaderName(hyper::header::InvalidHeaderName), - #[error("No mock found for request: {method} {url} in {spec_path}")] + #[debug(fmt = "No mock found for request: {method} {url} in {spec_path}")] NoMockFound { method: String, url: String, spec_path: String, }, - #[error("Hyper HTTP Error")] + #[debug(fmt = "Hyper HTTP Error")] Hyper(hyper::Error), - #[error("Utf8 Error")] + #[debug(fmt = "Utf8 Error")] Utf8(FromUtf8Error), - #[error("Invalid request host")] + #[debug(fmt = "Invalid request host")] InvalidRequestHost, - #[error("Hyper Http Error")] + #[debug(fmt = "Hyper Http Error")] HyperHttp(hyper::http::Error), } } pub mod worker { - use derive_more::From; + use derive_more::{From, DebugCustom}; - #[derive(From, thiserror::Error, Debug)] + #[derive(From, DebugCustom)] pub enum Error { - #[error("Failed to initialize worker")] + #[debug(fmt = "Failed to initialize worker")] InitializationFailed, - #[error("Worker execution error")] + #[debug(fmt = "Worker execution error")] ExecutionFailed, - #[error("Worker communication error")] + #[debug(fmt = "Worker communication error")] Communication, - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("Request Clone Failed")] + #[debug(fmt = "Request Clone Failed")] RequestCloneFailed, - #[error("Hyper Header To Str Error")] + #[debug(fmt = "Hyper Header To Str Error")] HyperHeaderStr(hyper::header::ToStrError), - #[error("JS Runtime Stopped Error")] + #[debug(fmt = "JS Runtime Stopped Error")] JsRuntimeStopped, - #[error("CLI Error : {0}")] + #[debug(fmt = "CLI Error : {}", _0)] CLI(String), } } pub mod graphql { - use derive_more::From; + use derive_more::{From, DebugCustom}; use super::http; - #[derive(From, thiserror::Error, Debug)] + #[derive(From, DebugCustom)] pub enum Error { - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("HTTP Error")] + #[debug(fmt = "HTTP Error")] Http(http::Error), } } pub mod cache { - use derive_more::From; + use derive_more::{From, DebugCustom}; - #[derive(From, thiserror::Error, Debug)] + #[derive(From, DebugCustom)] pub enum Error { - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJson(serde_json::Error), - #[error("Worker Error : {0}")] + #[debug(fmt = "Worker Error : {}", _0)] Worker(String), - #[error("Kv Error : {0}")] + #[debug(fmt = "Kv Error : {}", _0)] #[from(ignore)] Kv(String), } } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + +impl Display for file::Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + +impl Display for http::Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + +impl Display for worker::Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + +impl Display for graphql::Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + +impl Display for cache::Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/src/core/grpc/error.rs b/src/core/grpc/error.rs index 4b642e2417..086b0bdc5a 100644 --- a/src/core/grpc/error.rs +++ b/src/core/grpc/error.rs @@ -1,49 +1,57 @@ -use derive_more::From; +use std::fmt::Display; + +use derive_more::{From, DebugCustom}; use prost_reflect::DescriptorError; use serde_json; use crate::core::blueprint::GrpcMethod; -#[derive(From, thiserror::Error, Debug)] +#[derive(From, DebugCustom)] pub enum Error { - #[error("Serde Json Error : {0}")] + #[debug(fmt = "Serde Json Error : {}", _0)] SerdeJsonError(serde_json::Error), - #[error("Prost Encode Error")] + #[debug(fmt = "Prost Encode Error")] ProstEncodeError(prost::EncodeError), - #[error("Prost Decode Error")] + #[debug(fmt = "Prost Decode Error")] ProstDecodeError(prost::DecodeError), - #[error("Empty Response")] + #[debug(fmt = "Empty Response")] EmptyResponse, - #[error("Couldn't resolve message")] + #[debug(fmt = "Couldn't resolve message")] MessageNotResolved, - #[error("Descriptor pool error")] + #[debug(fmt = "Descriptor pool error")] DescriptorPoolError(DescriptorError), - #[error("Protox Parse Error")] + #[debug(fmt = "Protox Parse Error")] ProtoxParseError(protox_parse::ParseError), - #[error("Couldn't find method {}", ._0.name)] + #[debug(fmt = "Couldn't find method {}", ._0.name)] MissingMethod(GrpcMethod), - #[error("Unable to find list field on type")] + #[debug(fmt = "Unable to find list field on type")] MissingListField, - #[error("Field not found : {0}")] + #[debug(fmt = "Field not found : {}", _0)] #[from(ignore)] MissingField(String), - #[error("Couldn't find definitions for service {0}")] + #[debug(fmt = "Couldn't find definitions for service {}", _0)] #[from(ignore)] MissingService(String), - #[error("Failed to parse input according to type {0}")] + #[debug(fmt = "Failed to parse input according to type {}", _0)] #[from(ignore)] InputParsingFailed(String), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/src/core/rest/error.rs b/src/core/rest/error.rs index 2404cbe248..9bef48067d 100644 --- a/src/core/rest/error.rs +++ b/src/core/rest/error.rs @@ -7,65 +7,69 @@ use derive_more::{DebugCustom, From}; use serde_json; use crate::core::valid::ValidationError; +use std::fmt::Display; -#[derive(From, thiserror::Error, DebugCustom)] + +#[derive(From, DebugCustom)] pub enum Error { - #[error("Unexpected Named Type: {}", 0.to_string())] + #[debug(fmt = "Unexpected Named Type: {}", 0.to_string())] #[from(ignore)] UnexpectedNamedType(Name), - #[error("Unexpected Type: {}, expected a named type like String, Float, Boolean etc.", 0.to_string())] + #[debug(fmt = "Unexpected Type: {}, expected a named type like String, Float, Boolean etc.", 0.to_string())] UnexpectedType(Type), - #[error("Serde Json Error")] + #[debug(fmt = "Serde Json Error")] SerdeJsonError(serde_json::Error), - #[error("{msg}: {directive:?}")] #[debug(fmt = "{msg}: {directive:?}")] Missing { msg: String, directive: Directive }, - #[error("Method not provided in the directive")] #[debug(fmt = "Method not provided in the directive")] MissingMethod, - #[error("Path not provided in the directive")] #[debug(fmt = "Path not provided in the directive")] MissingPath, - #[error("Undefined query param: {0}")] + #[debug(fmt = "Undefined query param: {}", _0)] UndefinedQueryParam(String), - #[error("Parse Integer Error")] + #[debug(fmt = "Parse Integer Error")] ParseIntegerError(ParseIntError), - #[error("Parse Float Error")] + #[debug(fmt = "Parse Float Error")] ParseFloatingPointError(ParseFloatError), - #[error("Parse Boolean Error")] + #[debug(fmt = "Parse Boolean Error")] ParseBooleanError(ParseBoolError), - #[error("Undefined param : {key} in {input}")] #[debug(fmt = "Undefined param : {key} in {input}")] UndefinedParam { key: String, input: String }, - #[error("Validation Error : {0}")] + #[debug(fmt = "Validation Error : {}", _0)] ValidationError(ValidationError), - #[error("Async Graphql Parser Error")] + #[debug(fmt = "Async Graphql Parser Error")] AsyncgraphqlParserError(async_graphql::parser::Error), - #[error("Hyper HTTP Invalid URI Error")] + #[debug(fmt = "Hyper HTTP Invalid URI Error")] HyperHttpInvalidUri(hyper::http::uri::InvalidUri), - #[error("Hyper HTTP Error")] + #[debug(fmt = "Hyper HTTP Error")] HyperHttpError(hyper::http::Error), - #[error("Hyper Error")] + #[debug(fmt = "Hyper Error")] HyperError(hyper::Error), - #[error("Server Error")] + #[debug(fmt = "Server Error")] #[from(ignore)] ServerError(String), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/tailcall-cloudflare/src/error.rs b/tailcall-cloudflare/src/error.rs index 626ad51ccd..b26bf40914 100644 --- a/tailcall-cloudflare/src/error.rs +++ b/tailcall-cloudflare/src/error.rs @@ -1,34 +1,42 @@ use std::string::FromUtf8Error; -use derive_more::From; +use derive_more::{From, DebugCustom}; use tailcall::core::error; +use std::fmt::Display; -#[derive(From, thiserror::Error, Debug)] + +#[derive(From, DebugCustom)] pub enum Error { - #[error("Worker Error")] + #[debug(fmt = "Worker Error")] Worker(worker::Error), - #[error("File {0} was not found in bucket")] + #[debug(fmt = "File {} was not found in bucket", _0)] MissingFileInBucket(String), - #[error("BUCKET var is not set")] + #[debug(fmt = "BUCKET var is not set")] BucketVarNotSet, - #[error("Hyper Error")] + #[debug(fmt = "Hyper Error")] Hyper(hyper::Error), - #[error("FromUtf8 Error")] + #[debug(fmt = "FromUtf8 Error")] FromUtf8(FromUtf8Error), - #[error("Unsupported HTTP method: {0}")] + #[debug(fmt = "Unsupported HTTP method: {}", _0)] #[from(ignore)] UnsupportedHttpMethod(String), - #[error("Hyper HTTP Error")] + #[debug(fmt = "Hyper HTTP Error")] HyperHttp(hyper::http::Error), - #[error("Core Error")] + #[debug(fmt = "Core Error")] Core(error::Error), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/tailcall-fixtures/error.rs b/tailcall-fixtures/error.rs index 826aee4059..580288fc96 100644 --- a/tailcall-fixtures/error.rs +++ b/tailcall-fixtures/error.rs @@ -1,15 +1,23 @@ -use derive_more::From; +use derive_more::{From, DebugCustom}; +use std::fmt::Display; -#[derive(From, thiserror::Error, Debug)] + +#[derive(From, DebugCustom)] pub enum Error { - #[error("Std Fmt Error")] + #[debug(fmt = "Std Fmt Error")] StdFmt(std::fmt::Error), - #[error("Std IO Error")] + #[debug(fmt = "Std IO Error")] IO(std::io::Error), - #[error("Failed to resolve filename")] + #[debug(fmt = "Failed to resolve filename")] FilenameNotResolved, } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/tailcall-prettier/src/error.rs b/tailcall-prettier/src/error.rs index 51017c9026..018f531f78 100644 --- a/tailcall-prettier/src/error.rs +++ b/tailcall-prettier/src/error.rs @@ -1,27 +1,35 @@ use std::string::FromUtf8Error; -use derive_more::From; +use derive_more::{From, DebugCustom}; use tokio::task::JoinError; +use std::fmt::Display; -#[derive(From, thiserror::Error, Debug)] + +#[derive(From, DebugCustom)] pub enum Error { - #[error("Std IO Error")] + #[debug(fmt = "Std IO Error")] IO(std::io::Error), - #[error("Join Error")] + #[debug(fmt = "Join Error")] Join(JoinError), - #[error("From Utf8 Error")] + #[debug(fmt = "From Utf8 Error")] FromUtf8(FromUtf8Error), - #[error("Prettier formatting failed: {0}")] + #[debug(fmt = "Prettier formatting failed: {}", _0)] PrettierFormattingFailed(String), - #[error("No file extension found")] + #[debug(fmt = "No file extension found")] FileExtensionNotFound, - #[error("Unsupported file type")] + #[debug(fmt = "Unsupported file type")] UnsupportedFiletype, } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/tailcall-tracker/src/error.rs b/tailcall-tracker/src/error.rs index 2b06930378..9315a91be3 100644 --- a/tailcall-tracker/src/error.rs +++ b/tailcall-tracker/src/error.rs @@ -1,19 +1,27 @@ -use derive_more::From; +use derive_more::{From, DebugCustom}; use reqwest::header::InvalidHeaderValue; +use std::fmt::Display; -#[derive(From, thiserror::Error, Debug)] + +#[derive(From, DebugCustom)] pub enum Error { - #[error("Reqwest Error")] + #[debug(fmt = "Reqwest Error")] Reqwest(reqwest::Error), - #[error("Invalid Header Value")] + #[debug(fmt = "Invalid Header Value")] InvalidHeaderValue(InvalidHeaderValue), - #[error("Serde JSON Error")] + #[debug(fmt = "Serde JSON Error")] SerdeJson(serde_json::Error), - #[error("Url Parser Error")] + #[debug(fmt = "Url Parser Error")] UrlParser(url::ParseError), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; diff --git a/tailcall-upstream-grpc/src/error.rs b/tailcall-upstream-grpc/src/error.rs index dadf04bb76..fd216c9381 100644 --- a/tailcall-upstream-grpc/src/error.rs +++ b/tailcall-upstream-grpc/src/error.rs @@ -1,27 +1,35 @@ use std::env::VarError; +use std::fmt::Display; -use derive_more::From; + +use derive_more::{From, DebugCustom}; use hyper::header::InvalidHeaderValue; use opentelemetry::trace::TraceError; use tracing::subscriber::SetGlobalDefaultError; -#[derive(From, thiserror::Error, Debug)] +#[derive(From, DebugCustom)] pub enum Error { - #[error("Hyper Error")] + #[debug(fmt = "Hyper Error")] Hyper(hyper::Error), - #[error("Set Global Default Error")] + #[debug(fmt = "Set Global Default Error")] SetGlobalDefault(SetGlobalDefaultError), - #[error("Trace Error")] + #[debug(fmt = "Trace Error")] Trace(TraceError), - #[error("Failed to instantiate OTLP provider")] + #[debug(fmt = "Failed to instantiate OTLP provider")] OltpProviderInstantiationFailed, - #[error("Var Error")] + #[debug(fmt = "Var Error")] Var(VarError), - #[error("Invalid header value")] + #[debug(fmt = "Invalid header value")] InvalidHeaderValue(InvalidHeaderValue), } + +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} diff --git a/tests/core/error.rs b/tests/core/error.rs index a819a130e7..9843004fcd 100644 --- a/tests/core/error.rs +++ b/tests/core/error.rs @@ -1,77 +1,84 @@ use std::path::Path; +use std::fmt::Display; -use derive_more::From; +use derive_more::{From, DebugCustom}; use markdown::mdast::{Heading, Node}; use tailcall::core::config::UnsupportedConfigFormat; -#[derive(From, thiserror::Error, Debug)] +#[derive(From, DebugCustom)] pub enum Error { - #[error("Unexpected code block with no specific language in {:?}", _0)] + #[debug(fmt = "Unexpected code block with no specific language in {:?}", _0)] NoSpecificLanguage(Box), - #[error("Unexpected number of {0} blocks in {:?} (only one is allowed)", _1)] + #[debug(fmt = "Unexpected number of {0} blocks in {:?} (only one is allowed)", _1)] UnexpectedNumberOfBlocks(String, Box), - #[error( + #[debug(fmt = "Unexpected language in {0} block in {:?} (only JSON and YAML are supported)", _1 )] #[from(ignore)] UnexpectedLanguage(String, Box), - #[error("Serde JSON Error")] + #[debug(fmt = "Serde JSON Error")] SerdeJson(serde_json::Error), - #[error("Serde YAML Error")] + #[debug(fmt = "Serde YAML Error")] SerdeYaml(serde_yaml::Error), - #[error("Unexpected content of level {0} heading in {:?}: {:#?}", _1, _2)] + #[debug(fmt = "Unexpected content of level {0} heading in {:?}: {:#?}", _1, _2)] UnexpectedHeadingContent(String, Box, Heading), - #[error("Unexpected content of code in {:?}: {:#?}", _0, _1)] + #[debug(fmt = "Unexpected content of code in {:?}: {:#?}", _0, _1)] UnexpectedCodeContent(Box, Option), - #[error("Unexpected double-declaration of {0} in {:?}", _1)] + #[debug(fmt = "Unexpected double-declaration of {0} in {:?}", _1)] #[from(ignore)] UnexpectedDoubleDeclaration(String, Box), - #[error("Unexpected {0} annotation {:?} in {:?}", _1, _2)] + #[debug(fmt = "Unexpected {0} annotation {:?} in {:?}", _1, _2)] UnexpectedAnnotation(String, String, Box), - #[error("Unexpected level {0} heading in {:?}: {:#?}", _1, _2)] + #[debug(fmt = "Unexpected level {0} heading in {:?}: {:#?}", _1, _2)] #[from(ignore)] UnexpectedHeadingLevel(String, Box, Heading), - #[error("Unsupported Config Format {:?}", _0)] + #[debug(fmt = "Unsupported Config Format {:?}", _0)] UnsupportedConfigFormat(UnsupportedConfigFormat), - #[error("Unexpected component {:?} in {:?}: {:#?}", _0, _1, _2)] + #[debug(fmt = "Unexpected component {:?} in {:?}: {:#?}", _0, _1, _2)] UnexpectedComponent(String, Box, Option), - #[error("Unexpected node in {:?}: {:#?}", _0, _1)] + #[debug(fmt = "Unexpected node in {:?}: {:#?}", _0, _1)] #[from(ignore)] UnexpectedNode(Box, Node), - #[error( + #[debug(fmt = "Unexpected blocks in {:?}: You must define a GraphQL Config in an execution test.", _0 )] #[from(ignore)] UnexpectedBlocks(Box), - #[error("{0}")] + #[debug(fmt = "{0}")] TailcallPrettier(String), - #[error("{0}")] + #[debug(fmt = "{0}")] #[from(ignore)] Execution(String), - #[error("{0}")] + #[debug(fmt = "{0}")] #[from(ignore)] Validation(String), - #[error("Std IO Error")] + #[debug(fmt = "Std IO Error")] StdIO(std::io::Error), } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } +} + pub type Result = std::result::Result; From 9856868914a850528c30702942c25d0e23821ae7 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 06:42:57 +0000 Subject: [PATCH 06/12] chore: implemented std::error::Error for some Error enums --- src/cli/error.rs | 2 ++ src/core/error.rs | 2 ++ tailcall-upstream-grpc/src/error.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/src/cli/error.rs b/src/cli/error.rs index b8b361e119..c3f7d4bbe3 100644 --- a/src/cli/error.rs +++ b/src/cli/error.rs @@ -107,4 +107,6 @@ impl Display for Error { } } +impl std::error::Error for Error {} + pub type Result = std::result::Result; diff --git a/src/core/error.rs b/src/core/error.rs index 743dc4b93f..e2e8682095 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -405,4 +405,6 @@ impl Display for cache::Error { } } +impl std::error::Error for Error {} + pub type Result = std::result::Result; diff --git a/tailcall-upstream-grpc/src/error.rs b/tailcall-upstream-grpc/src/error.rs index fd216c9381..beb405bf1d 100644 --- a/tailcall-upstream-grpc/src/error.rs +++ b/tailcall-upstream-grpc/src/error.rs @@ -33,3 +33,5 @@ impl Display for Error { write!(f, "{:?}", self) } } + +impl std::error::Error for Error {} \ No newline at end of file From 79c54d8c7da76645c9c71ff5e632c310a86d2235 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 08:49:27 +0000 Subject: [PATCH 07/12] refactor: implemented thisError for some error enums --- src/cli/error.rs | 71 +++++------- src/cli/runtime/mod.rs | 4 +- src/core/error.rs | 174 +++++++++++++--------------- src/core/grpc/error.rs | 2 +- src/core/rest/error.rs | 46 +++----- tailcall-cloudflare/src/error.rs | 28 ++--- tailcall-fixtures/error.rs | 2 +- tailcall-prettier/src/error.rs | 5 +- tailcall-tracker/src/error.rs | 4 +- tailcall-upstream-grpc/src/error.rs | 26 ++--- tests/core/error.rs | 47 ++++---- 11 files changed, 176 insertions(+), 233 deletions(-) diff --git a/src/cli/error.rs b/src/cli/error.rs index c3f7d4bbe3..c7b921b7ff 100644 --- a/src/cli/error.rs +++ b/src/cli/error.rs @@ -1,7 +1,6 @@ -use std::fmt::Display; use std::string::FromUtf8Error; -use derive_more::{From, DebugCustom}; +use derive_more::From; use inquire::InquireError; use opentelemetry::logs::LogError; use opentelemetry::metrics::MetricsError; @@ -11,102 +10,94 @@ use tokio::task::JoinError; use crate::core::valid::ValidationError; use crate::core::{error, rest}; -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Metrics Error")] + #[error("Metrics Error")] Metrics(MetricsError), - #[debug(fmt = "Rest Error")] + #[error("Rest Error")] Rest(rest::error::Error), - #[debug(fmt = "Serde Json Error")] + #[error("Serde Json Error")] SerdeJson(serde_json::Error), - #[debug(fmt = "IO Error")] + #[error("IO Error")] IO(std::io::Error), - #[debug(fmt = "Telemetry Trace Error : {}", _0)] + #[error("Telemetry Trace Error : {}", _0)] TelemetryTrace(String), - #[debug(fmt = "Failed to send message")] + #[error("Failed to send message")] MessageSendFailure, - #[debug(fmt = "Hyper Error")] + #[error("Hyper Error")] Hyper(hyper::Error), - #[debug(fmt = "Rustls Error")] + #[error("Rustls Error")] Rustls(rustls::Error), - #[debug(fmt = "Join Error")] + #[error("Join Error")] Join(JoinError), - #[debug(fmt = "Opentelemetry Global Error")] + #[error("Opentelemetry Global Error")] OpentelemetryGlobal(opentelemetry::global::Error), - #[debug(fmt = "Trace Error")] + #[error("Trace Error")] Trace(TraceError), - #[debug(fmt = "Log Error")] + #[error("Log Error")] Log(LogError), - #[debug(fmt = "Utf8 Error")] + #[error("Utf8 Error")] Utf8(FromUtf8Error), - #[debug(fmt = "Inquire Error")] + #[error("Inquire Error")] Inquire(InquireError), - #[debug(fmt = "Serde Yaml Error")] + #[error("Serde Yaml Error")] SerdeYaml(serde_yaml::Error), - #[debug(fmt = "Invalid Header Name")] + #[error("Invalid Header Name")] InvalidHeaderName(hyper::header::InvalidHeaderName), - #[debug(fmt = "Invalid Header Value")] + #[error("Invalid Header Value")] InvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[debug(fmt = "rquickjs Error")] + #[error("rquickjs Error")] RQuickjs(rquickjs::Error), - #[debug(fmt = "Trying to reinitialize an already initialized QuickJS runtime")] + #[error("Trying to reinitialize an already initialized QuickJS runtime")] ReinitializeQuickjsRuntime, - #[debug(fmt = "Runtime not initialized")] + #[error("Runtime not initialized")] RuntimeNotInitialized, - #[debug(fmt = "Deserialize Failed")] + #[error("Deserialize Failed")] DeserializeFailed, - #[debug(fmt = "Not a function error")] + #[error("Not a function error")] InvalidFunction, - #[debug(fmt = "Init Process Observer Error")] + #[error("Init Process Observer Error")] InitProcessObserver, - #[debug(fmt = "JS Runtime is stopped")] + #[error("JS Runtime is stopped")] JsRuntimeStopped, - #[debug(fmt = "Rustls internal error")] + #[error("Rustls internal error")] RustlsInternal, - #[debug(fmt = "Reqwest middleware error")] + #[error("Reqwest middleware error")] ReqwestMiddleware(reqwest_middleware::Error), - #[debug(fmt = "Reqwest error")] + #[error("Reqwest error")] Reqwest(reqwest::Error), - #[debug(fmt = "Validation Error : {}", _0)] + #[error("Validation Error : {}", _0)] Validation(ValidationError), - #[debug(fmt = "Core Error")] + #[error("Core Error")] CoreError(error::Error), } -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl std::error::Error for Error {} - pub type Result = std::result::Result; diff --git a/src/cli/runtime/mod.rs b/src/cli/runtime/mod.rs index e2066a6cdc..f2721be5e4 100644 --- a/src/cli/runtime/mod.rs +++ b/src/cli/runtime/mod.rs @@ -134,7 +134,7 @@ pub fn select_prompt( message: &str, options: Vec, ) -> Result { - Ok(Select::new(message, options) + Select::new(message, options) .prompt() - .map_err(|e| error::file::Error::Inquire(e.to_string()))?) + .map_err(|e| error::file::Error::Inquire(e.to_string())) } diff --git a/src/core/error.rs b/src/core/error.rs index e2e8682095..f7a8a156a4 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -2,7 +2,7 @@ use std::fmt::Display; use std::str::Utf8Error; use std::string::FromUtf8Error; -use derive_more::{From, DebugCustom}; +use derive_more::From; use opentelemetry::metrics::MetricsError; use opentelemetry::trace::TraceError; use prost_reflect::DescriptorError; @@ -14,169 +14,169 @@ use super::ir; use super::rest::error::Error as RestError; use super::valid::ValidationError; -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Std IO Error")] + #[error("Std IO Error")] StdIO(std::io::Error), - #[debug(fmt = "Utf8 Error")] + #[error("Utf8 Error")] FromUtf8(FromUtf8Error), - #[debug(fmt = "Validation Error : {}", _0)] + #[error("Validation Error : {}", _0)] Validation(ValidationError), - #[debug(fmt = "Serde Json Error")] + #[error("Serde Json Error")] SerdeJson(serde_json::Error), - #[debug(fmt = "Serde Yaml Error")] + #[error("Serde Yaml Error")] SerdeYaml(serde_yaml::Error), - #[debug(fmt = "Descriptor Error")] + #[error("Descriptor Error")] Descriptor(DescriptorError), - #[debug(fmt = "Expected fully-qualified name for reference type but got {}", _0)] + #[error("Expected fully-qualified name for reference type but got {}", _0)] InvalidReferenceTypeName(String), - #[debug(fmt = "Package name is required")] + #[error("Package name is required")] PackageNameNotFound, - #[debug(fmt = "Protox Parse Error")] + #[error("Protox Parse Error")] ProtoxParse(protox_parse::ParseError), - #[debug(fmt = "URL Parse Error")] + #[error("URL Parse Error")] UrlParse(url::ParseError), - #[debug(fmt = "Unable to extract content of google well-known proto file")] + #[error("Unable to extract content of google well-known proto file")] GoogleProtoFileContentNotExtracted, - #[debug(fmt = "Unsupported Config Format")] + #[error("Unsupported Config Format")] UnsupportedConfigFormat(UnsupportedConfigFormat), - #[debug(fmt = "Couldn't find definitions for service ServerReflection")] + #[error("Couldn't find definitions for service ServerReflection")] MissingServerReflectionDefinitions, - #[debug(fmt = "Grpc Error")] + #[error("Grpc Error")] Grpc(GrpcError), - #[debug(fmt = "Serde Path To Error")] + #[error("Serde Path To Error")] SerdePath(serde_path_to_error::Error), - #[debug(fmt = "Rest Error")] + #[error("Rest Error")] Rest(RestError), - #[debug(fmt = "Expected fileDescriptorResponse but found none")] + #[error("Expected fileDescriptorResponse but found none")] MissingFileDescriptorResponse, - #[debug(fmt = "Prost Decode Error")] + #[error("Prost Decode Error")] ProstDecode(prost::DecodeError), - #[debug(fmt = "Received empty fileDescriptorProto")] + #[error("Received empty fileDescriptorProto")] EmptyFileDescriptorProto, - #[debug(fmt = "Failed to decode fileDescriptorProto from BASE64")] + #[error("Failed to decode fileDescriptorProto from BASE64")] FileDescriptorProtoDecodeFailed, - #[debug(fmt = "Invalid header value")] + #[error("Invalid header value")] HyperInvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[debug(fmt = "Invalid header name")] + #[error("Invalid header name")] HyperInvalidHeaderName(hyper::header::InvalidHeaderName), - #[debug(fmt = "Hyper HTTP Error")] + #[error("Hyper HTTP Error")] HyperHttpError(hyper::http::Error), - #[debug(fmt = "Prometheus Error")] + #[error("Prometheus Error")] Prometheus(prometheus::Error), - #[debug(fmt = "Hyper Error")] + #[error("Hyper Error")] Hyper(hyper::Error), - #[debug(fmt = "Invalid URI")] + #[error("Invalid URI")] InvalidUri(hyper::http::uri::InvalidUri), - #[debug(fmt = "Mustache cannot be converted to const value")] + #[error("Mustache cannot be converted to const value")] InvalidMustacheConstConversion, - #[debug(fmt = "Protox Error")] + #[error("Protox Error")] Protox(protox::Error), - #[debug(fmt = "Failed to execute request")] + #[error("Failed to execute request")] RequestExecutionFailed, - #[debug(fmt = "File Error: {}", _0)] + #[error("File Error: {}", _0)] File(file::Error), - #[debug(fmt = "Http Error")] + #[error("Http Error")] Http(http::Error), - #[debug(fmt = "Worker Error")] + #[error("Worker Error")] Worker(worker::Error), - #[debug(fmt = "IRError {}", _0)] + #[error("IRError {}", _0)] IRError(ir::Error), - #[debug(fmt = "Serde URL Encoded Error")] + #[error("Serde URL Encoded Error")] SerdeUrlEncoded(serde_urlencoded::ser::Error), - #[debug(fmt = "Hyper Header ToStr Error")] + #[error("Hyper Header ToStr Error")] HyperHeaderToStr(hyper::header::ToStrError), - #[debug(fmt = "Utf8 Error")] + #[error("Utf8 Error")] Utf8(Utf8Error), - #[debug(fmt = "Rand Error")] + #[error("Rand Error")] Rand(rand::Error), - #[debug(fmt = "Trace Error")] + #[error("Trace Error")] Trace(TraceError), - #[debug(fmt = "Join Error")] + #[error("Join Error")] Join(JoinError), - #[debug(fmt = "Metrics Error")] + #[error("Metrics Error")] Metrics(MetricsError), - #[debug(fmt = "Reqwest Error")] + #[error("Reqwest Error")] Reqwest(reqwest::Error), - #[debug(fmt = "Unable to determine path")] + #[error("Unable to determine path")] PathDeterminationFailed, - #[debug(fmt = "Schema mismatch Error")] + #[error("Schema mismatch Error")] SchemaMismatch, - #[debug(fmt = "Failed to resolve parent value")] + #[error("Failed to resolve parent value")] ParentValueNotResolved, - #[debug(fmt = "Expected parent list index")] + #[error("Expected parent list index")] ExpectedParentListIndex, - #[debug(fmt = "Can't resolve value for field")] + #[error("Can't resolve value for field")] FieldValueNotResolved, - #[debug(fmt = "Expected list value")] + #[error("Expected list value")] ExpectedListValue, - #[debug(fmt = "Headers Error")] + #[error("Headers Error")] Headers(headers::Error), - #[debug(fmt = "Unsupported File Format")] + #[error("Unsupported File Format")] UnsupportedFileFormat, - #[debug(fmt = "Failed to match type_name")] + #[error("Failed to match type_name")] TypenameMatchFailed, - #[debug(fmt = "Value expected to be object")] + #[error("Value expected to be object")] ObjectExpected, - #[debug(fmt = "Failed to find corresponding type for value")] + #[error("Failed to find corresponding type for value")] MissingTypeForValue, - #[debug(fmt = "CLI Error : {}", _0)] + #[error("CLI Error : {}", _0)] #[from(ignore)] CLI(String), - #[debug(fmt = "Inquire Error : {}", _0)] + #[error("Inquire Error : {}", _0)] #[from(ignore)] Inquire(String), } @@ -184,7 +184,7 @@ pub enum Error { pub mod file { use std::string::FromUtf8Error; - use derive_more::{From, DebugCustom}; + use derive_more::{DebugCustom, From}; #[derive(From, DebugCustom)] pub enum Error { @@ -241,73 +241,73 @@ pub mod file { pub mod http { use std::string::FromUtf8Error; - use derive_more::{From, DebugCustom}; + use derive_more::From; - #[derive(From, DebugCustom)] + #[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "HTTP request failed with status code: {status_code}")] + #[error("HTTP request failed with status code: {status_code}")] RequestFailed { status_code: u16 }, - #[debug(fmt = "Timeout occurred while making the HTTP request")] + #[error("Timeout occurred while making the HTTP request")] Timeout, - #[debug(fmt = "Failed to parse the response body")] + #[error("Failed to parse the response body")] ResponseParse, - #[debug(fmt = "Invalid URL: {url}")] + #[error("Invalid URL: {url}")] InvalidUrl { url: String }, - #[debug(fmt = "Reqwest Middleware Error")] + #[error("Reqwest Middleware Error")] ReqwestMiddleware(reqwest_middleware::Error), - #[debug(fmt = "Tonic Status Error")] + #[error("Tonic Status Error")] TonicStatus(tonic::Status), - #[debug(fmt = "Reqwest Error")] + #[error("Reqwest Error")] Reqwest(reqwest::Error), - #[debug(fmt = "Serde Json Error")] + #[error("Serde Json Error")] SerdeJson(serde_json::Error), - #[debug(fmt = "Unable to find key {} in query params", _0)] + #[error("Unable to find key {} in query params", _0)] #[from(ignore)] KeyNotFound(String), - #[debug(fmt = "Invalid Status Code")] + #[error("Invalid Status Code")] InvalidStatusCode(hyper::http::status::InvalidStatusCode), - #[debug(fmt = "Status Code error")] + #[error("Status Code error")] StatusCode, - #[debug(fmt = "Invalid Header Value")] + #[error("Invalid Header Value")] InvalidHeaderValue(hyper::header::InvalidHeaderValue), - #[debug(fmt = "Invalid Header Name")] + #[error("Invalid Header Name")] InvalidHeaderName(hyper::header::InvalidHeaderName), - #[debug(fmt = "No mock found for request: {method} {url} in {spec_path}")] + #[error("No mock found for request: {method} {url} in {spec_path}")] NoMockFound { method: String, url: String, spec_path: String, }, - #[debug(fmt = "Hyper HTTP Error")] + #[error("Hyper HTTP Error")] Hyper(hyper::Error), - #[debug(fmt = "Utf8 Error")] + #[error("Utf8 Error")] Utf8(FromUtf8Error), - #[debug(fmt = "Invalid request host")] + #[error("Invalid request host")] InvalidRequestHost, - #[debug(fmt = "Hyper Http Error")] + #[error("Hyper Http Error")] HyperHttp(hyper::http::Error), } } pub mod worker { - use derive_more::{From, DebugCustom}; + use derive_more::{DebugCustom, From}; #[derive(From, DebugCustom)] pub enum Error { @@ -338,7 +338,7 @@ pub mod worker { } pub mod graphql { - use derive_more::{From, DebugCustom}; + use derive_more::{DebugCustom, From}; use super::http; @@ -353,7 +353,7 @@ pub mod graphql { } pub mod cache { - use derive_more::{From, DebugCustom}; + use derive_more::{DebugCustom, From}; #[derive(From, DebugCustom)] pub enum Error { @@ -369,24 +369,12 @@ pub mod cache { } } -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - impl Display for file::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } -impl Display for http::Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - impl Display for worker::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) @@ -405,6 +393,4 @@ impl Display for cache::Error { } } -impl std::error::Error for Error {} - pub type Result = std::result::Result; diff --git a/src/core/grpc/error.rs b/src/core/grpc/error.rs index 086b0bdc5a..af5484748d 100644 --- a/src/core/grpc/error.rs +++ b/src/core/grpc/error.rs @@ -1,6 +1,6 @@ use std::fmt::Display; -use derive_more::{From, DebugCustom}; +use derive_more::{DebugCustom, From}; use prost_reflect::DescriptorError; use serde_json; diff --git a/src/core/rest/error.rs b/src/core/rest/error.rs index 9bef48067d..a55fdce0e0 100644 --- a/src/core/rest/error.rs +++ b/src/core/rest/error.rs @@ -3,73 +3,65 @@ use std::str::ParseBoolError; use async_graphql::parser::types::{Directive, Type}; use async_graphql::Name; -use derive_more::{DebugCustom, From}; +use derive_more::From; use serde_json; use crate::core::valid::ValidationError; -use std::fmt::Display; - -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Unexpected Named Type: {}", 0.to_string())] + #[error("Unexpected Named Type: {}", 0.to_string())] #[from(ignore)] UnexpectedNamedType(Name), - #[debug(fmt = "Unexpected Type: {}, expected a named type like String, Float, Boolean etc.", 0.to_string())] + #[error("Unexpected Type: {}, expected a named type like String, Float, Boolean etc.", 0.to_string())] UnexpectedType(Type), - #[debug(fmt = "Serde Json Error")] + #[error("Serde Json Error")] SerdeJsonError(serde_json::Error), - #[debug(fmt = "{msg}: {directive:?}")] + #[error("{msg}: {directive:?}")] Missing { msg: String, directive: Directive }, - #[debug(fmt = "Method not provided in the directive")] + #[error("Method not provided in the directive")] MissingMethod, - #[debug(fmt = "Path not provided in the directive")] + #[error("Path not provided in the directive")] MissingPath, - #[debug(fmt = "Undefined query param: {}", _0)] + #[error("Undefined query param: {}", _0)] UndefinedQueryParam(String), - #[debug(fmt = "Parse Integer Error")] + #[error("Parse Integer Error")] ParseIntegerError(ParseIntError), - #[debug(fmt = "Parse Float Error")] + #[error("Parse Float Error")] ParseFloatingPointError(ParseFloatError), - #[debug(fmt = "Parse Boolean Error")] + #[error("Parse Boolean Error")] ParseBooleanError(ParseBoolError), - #[debug(fmt = "Undefined param : {key} in {input}")] + #[error("Undefined param : {key} in {input}")] UndefinedParam { key: String, input: String }, - #[debug(fmt = "Validation Error : {}", _0)] + #[error("Validation Error : {}", _0)] ValidationError(ValidationError), - #[debug(fmt = "Async Graphql Parser Error")] + #[error("Async Graphql Parser Error")] AsyncgraphqlParserError(async_graphql::parser::Error), - #[debug(fmt = "Hyper HTTP Invalid URI Error")] + #[error("Hyper HTTP Invalid URI Error")] HyperHttpInvalidUri(hyper::http::uri::InvalidUri), - #[debug(fmt = "Hyper HTTP Error")] + #[error("Hyper HTTP Error")] HyperHttpError(hyper::http::Error), - #[debug(fmt = "Hyper Error")] + #[error("Hyper Error")] HyperError(hyper::Error), - #[debug(fmt = "Server Error")] + #[error("Server Error")] #[from(ignore)] ServerError(String), } -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - pub type Result = std::result::Result; diff --git a/tailcall-cloudflare/src/error.rs b/tailcall-cloudflare/src/error.rs index b26bf40914..40252c4056 100644 --- a/tailcall-cloudflare/src/error.rs +++ b/tailcall-cloudflare/src/error.rs @@ -1,42 +1,34 @@ use std::string::FromUtf8Error; -use derive_more::{From, DebugCustom}; +use derive_more::From; use tailcall::core::error; -use std::fmt::Display; - -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Worker Error")] + #[error("Worker Error")] Worker(worker::Error), - #[debug(fmt = "File {} was not found in bucket", _0)] + #[error("File {} was not found in bucket", _0)] MissingFileInBucket(String), - #[debug(fmt = "BUCKET var is not set")] + #[error("BUCKET var is not set")] BucketVarNotSet, - #[debug(fmt = "Hyper Error")] + #[error("Hyper Error")] Hyper(hyper::Error), - #[debug(fmt = "FromUtf8 Error")] + #[error("FromUtf8 Error")] FromUtf8(FromUtf8Error), - #[debug(fmt = "Unsupported HTTP method: {}", _0)] + #[error("Unsupported HTTP method: {}", _0)] #[from(ignore)] UnsupportedHttpMethod(String), - #[debug(fmt = "Hyper HTTP Error")] + #[error("Hyper HTTP Error")] HyperHttp(hyper::http::Error), - #[debug(fmt = "Core Error")] + #[error("Core Error")] Core(error::Error), } -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - pub type Result = std::result::Result; diff --git a/tailcall-fixtures/error.rs b/tailcall-fixtures/error.rs index 580288fc96..92715cb797 100644 --- a/tailcall-fixtures/error.rs +++ b/tailcall-fixtures/error.rs @@ -1,6 +1,6 @@ -use derive_more::{From, DebugCustom}; use std::fmt::Display; +use derive_more::{DebugCustom, From}; #[derive(From, DebugCustom)] pub enum Error { diff --git a/tailcall-prettier/src/error.rs b/tailcall-prettier/src/error.rs index 018f531f78..e75601b45d 100644 --- a/tailcall-prettier/src/error.rs +++ b/tailcall-prettier/src/error.rs @@ -1,9 +1,8 @@ +use std::fmt::Display; use std::string::FromUtf8Error; -use derive_more::{From, DebugCustom}; +use derive_more::{DebugCustom, From}; use tokio::task::JoinError; -use std::fmt::Display; - #[derive(From, DebugCustom)] pub enum Error { diff --git a/tailcall-tracker/src/error.rs b/tailcall-tracker/src/error.rs index 9315a91be3..424da67492 100644 --- a/tailcall-tracker/src/error.rs +++ b/tailcall-tracker/src/error.rs @@ -1,7 +1,7 @@ -use derive_more::{From, DebugCustom}; -use reqwest::header::InvalidHeaderValue; use std::fmt::Display; +use derive_more::{DebugCustom, From}; +use reqwest::header::InvalidHeaderValue; #[derive(From, DebugCustom)] pub enum Error { diff --git a/tailcall-upstream-grpc/src/error.rs b/tailcall-upstream-grpc/src/error.rs index beb405bf1d..dadf04bb76 100644 --- a/tailcall-upstream-grpc/src/error.rs +++ b/tailcall-upstream-grpc/src/error.rs @@ -1,37 +1,27 @@ use std::env::VarError; -use std::fmt::Display; - -use derive_more::{From, DebugCustom}; +use derive_more::From; use hyper::header::InvalidHeaderValue; use opentelemetry::trace::TraceError; use tracing::subscriber::SetGlobalDefaultError; -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Hyper Error")] + #[error("Hyper Error")] Hyper(hyper::Error), - #[debug(fmt = "Set Global Default Error")] + #[error("Set Global Default Error")] SetGlobalDefault(SetGlobalDefaultError), - #[debug(fmt = "Trace Error")] + #[error("Trace Error")] Trace(TraceError), - #[debug(fmt = "Failed to instantiate OTLP provider")] + #[error("Failed to instantiate OTLP provider")] OltpProviderInstantiationFailed, - #[debug(fmt = "Var Error")] + #[error("Var Error")] Var(VarError), - #[debug(fmt = "Invalid header value")] + #[error("Invalid header value")] InvalidHeaderValue(InvalidHeaderValue), } - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl std::error::Error for Error {} \ No newline at end of file diff --git a/tests/core/error.rs b/tests/core/error.rs index 9843004fcd..a819a130e7 100644 --- a/tests/core/error.rs +++ b/tests/core/error.rs @@ -1,84 +1,77 @@ use std::path::Path; -use std::fmt::Display; -use derive_more::{From, DebugCustom}; +use derive_more::From; use markdown::mdast::{Heading, Node}; use tailcall::core::config::UnsupportedConfigFormat; -#[derive(From, DebugCustom)] +#[derive(From, thiserror::Error, Debug)] pub enum Error { - #[debug(fmt = "Unexpected code block with no specific language in {:?}", _0)] + #[error("Unexpected code block with no specific language in {:?}", _0)] NoSpecificLanguage(Box), - #[debug(fmt = "Unexpected number of {0} blocks in {:?} (only one is allowed)", _1)] + #[error("Unexpected number of {0} blocks in {:?} (only one is allowed)", _1)] UnexpectedNumberOfBlocks(String, Box), - #[debug(fmt = + #[error( "Unexpected language in {0} block in {:?} (only JSON and YAML are supported)", _1 )] #[from(ignore)] UnexpectedLanguage(String, Box), - #[debug(fmt = "Serde JSON Error")] + #[error("Serde JSON Error")] SerdeJson(serde_json::Error), - #[debug(fmt = "Serde YAML Error")] + #[error("Serde YAML Error")] SerdeYaml(serde_yaml::Error), - #[debug(fmt = "Unexpected content of level {0} heading in {:?}: {:#?}", _1, _2)] + #[error("Unexpected content of level {0} heading in {:?}: {:#?}", _1, _2)] UnexpectedHeadingContent(String, Box, Heading), - #[debug(fmt = "Unexpected content of code in {:?}: {:#?}", _0, _1)] + #[error("Unexpected content of code in {:?}: {:#?}", _0, _1)] UnexpectedCodeContent(Box, Option), - #[debug(fmt = "Unexpected double-declaration of {0} in {:?}", _1)] + #[error("Unexpected double-declaration of {0} in {:?}", _1)] #[from(ignore)] UnexpectedDoubleDeclaration(String, Box), - #[debug(fmt = "Unexpected {0} annotation {:?} in {:?}", _1, _2)] + #[error("Unexpected {0} annotation {:?} in {:?}", _1, _2)] UnexpectedAnnotation(String, String, Box), - #[debug(fmt = "Unexpected level {0} heading in {:?}: {:#?}", _1, _2)] + #[error("Unexpected level {0} heading in {:?}: {:#?}", _1, _2)] #[from(ignore)] UnexpectedHeadingLevel(String, Box, Heading), - #[debug(fmt = "Unsupported Config Format {:?}", _0)] + #[error("Unsupported Config Format {:?}", _0)] UnsupportedConfigFormat(UnsupportedConfigFormat), - #[debug(fmt = "Unexpected component {:?} in {:?}: {:#?}", _0, _1, _2)] + #[error("Unexpected component {:?} in {:?}: {:#?}", _0, _1, _2)] UnexpectedComponent(String, Box, Option), - #[debug(fmt = "Unexpected node in {:?}: {:#?}", _0, _1)] + #[error("Unexpected node in {:?}: {:#?}", _0, _1)] #[from(ignore)] UnexpectedNode(Box, Node), - #[debug(fmt = + #[error( "Unexpected blocks in {:?}: You must define a GraphQL Config in an execution test.", _0 )] #[from(ignore)] UnexpectedBlocks(Box), - #[debug(fmt = "{0}")] + #[error("{0}")] TailcallPrettier(String), - #[debug(fmt = "{0}")] + #[error("{0}")] #[from(ignore)] Execution(String), - #[debug(fmt = "{0}")] + #[error("{0}")] #[from(ignore)] Validation(String), - #[debug(fmt = "Std IO Error")] + #[error("Std IO Error")] StdIO(std::io::Error), } -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - pub type Result = std::result::Result; From 05b5efcfa8fd9d840f887a5921589111cf99fca9 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 09:06:52 +0000 Subject: [PATCH 08/12] fix: error formatting --- src/core/error.rs | 8 ++++---- src/core/grpc/error.rs | 2 +- tailcall-fixtures/error.rs | 2 +- tailcall-prettier/src/error.rs | 2 +- tailcall-tracker/src/error.rs | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/error.rs b/src/core/error.rs index f7a8a156a4..7e3be4e7fb 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -371,25 +371,25 @@ pub mod cache { impl Display for file::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } impl Display for worker::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } impl Display for graphql::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } impl Display for cache::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } diff --git a/src/core/grpc/error.rs b/src/core/grpc/error.rs index af5484748d..01c3acc5c3 100644 --- a/src/core/grpc/error.rs +++ b/src/core/grpc/error.rs @@ -50,7 +50,7 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } diff --git a/tailcall-fixtures/error.rs b/tailcall-fixtures/error.rs index 92715cb797..4934642938 100644 --- a/tailcall-fixtures/error.rs +++ b/tailcall-fixtures/error.rs @@ -16,7 +16,7 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } diff --git a/tailcall-prettier/src/error.rs b/tailcall-prettier/src/error.rs index e75601b45d..2dfe5e4680 100644 --- a/tailcall-prettier/src/error.rs +++ b/tailcall-prettier/src/error.rs @@ -27,7 +27,7 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } diff --git a/tailcall-tracker/src/error.rs b/tailcall-tracker/src/error.rs index 424da67492..d6d458cc4a 100644 --- a/tailcall-tracker/src/error.rs +++ b/tailcall-tracker/src/error.rs @@ -20,7 +20,7 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{:?}", self.to_string()) } } From d5c96295b9123e7d2d46976933293ade4d602b1d Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 18:02:50 +0000 Subject: [PATCH 09/12] chore: display imps for error enums --- src/core/error.rs | 46 +++++++++++++++++++++++++++++++--- src/core/grpc/error.rs | 19 +++++++++++++- tailcall-fixtures/error.rs | 6 ++++- tailcall-prettier/src/error.rs | 11 +++++++- tailcall-tracker/src/error.rs | 7 +++++- 5 files changed, 81 insertions(+), 8 deletions(-) diff --git a/src/core/error.rs b/src/core/error.rs index 7e3be4e7fb..06f48205d1 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -371,25 +371,63 @@ pub mod cache { impl Display for file::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + file::Error::NotFound => write!(f, "No such file or directory (os error 2)"), + file::Error::NoPermission => write!(f, "No permission to access the file"), + file::Error::AccessDenied => write!(f, "Access denied"), + file::Error::InvalidFormat => write!(f, "Invalid file format"), + file::Error::InvalidFilePath => write!(f, "Invalid file path"), + file::Error::InvalidOsString => write!(f, "Invalid OS string"), + file::Error::FileReadFailed(path) => write!(f, "Failed to read file: {}", path), + file::Error::FileWriteFailed(path) => write!(f, "Failed to write file: {}", path), + file::Error::StdIO(_) => write!(f, "Std IO Error"), + file::Error::Utf8(_) => write!(f, "Utf8 Error"), + file::Error::LambdaFileWriteNotSupported => { + write!(f, "File writing not supported on Lambda.") + } + file::Error::ExecutionSpecFileWriteFailed => { + write!(f, "Cannot write to a file in an execution spec") + } + file::Error::Cloudflare(error) => { + write!(f, "Cloudflare Worker Execution Error: {}", error) + } + file::Error::Inquire(error) => write!(f, "Inquire Error: {}", error), + file::Error::SerdeYaml(_) => write!(f, "Serde yaml Error"), + } } } impl Display for worker::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + worker::Error::InitializationFailed => write!(f, "Failed to initialize worker"), + worker::Error::ExecutionFailed => write!(f, "Worker execution error"), + worker::Error::Communication => write!(f, "Worker communication error"), + worker::Error::SerdeJson(_) => write!(f, "Serde Json Error"), + worker::Error::RequestCloneFailed => write!(f, "Request Clone Failed"), + worker::Error::HyperHeaderStr(_) => write!(f, "Hyper Header To Str Error"), + worker::Error::JsRuntimeStopped => write!(f, "JS Runtime Stopped Error"), + worker::Error::CLI(msg) => write!(f, "CLI Error: {}", msg), + } } } impl Display for graphql::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + graphql::Error::SerdeJson(_) => write!(f, "Serde Json Error"), + graphql::Error::Http(_) => write!(f, "HTTP Error"), + } } } impl Display for cache::Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + cache::Error::SerdeJson(_) => write!(f, "Serde Json Error"), + cache::Error::Worker(error) => write!(f, "Worker Error: {}", error), + cache::Error::Kv(error) => write!(f, "Kv Error: {}", error), + } } } diff --git a/src/core/grpc/error.rs b/src/core/grpc/error.rs index 01c3acc5c3..68660f5371 100644 --- a/src/core/grpc/error.rs +++ b/src/core/grpc/error.rs @@ -50,7 +50,24 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + Error::SerdeJsonError(e) => write!(f, "Serde Json Error: {}", e), + Error::ProstEncodeError(_) => write!(f, "Prost Encode Error"), + Error::ProstDecodeError(_) => write!(f, "Prost Decode Error"), + Error::EmptyResponse => write!(f, "Empty Response"), + Error::MessageNotResolved => write!(f, "Couldn't resolve message"), + Error::DescriptorPoolError(_) => write!(f, "Descriptor pool error"), + Error::ProtoxParseError(_) => write!(f, "Protox Parse Error"), + Error::MissingMethod(method) => write!(f, "Couldn't find method {}", method.name), + Error::MissingListField => write!(f, "Unable to find list field on type"), + Error::MissingField(field) => write!(f, "Field not found : {}", field), + Error::MissingService(service) => { + write!(f, "Couldn't find definitions for service {}", service) + } + Error::InputParsingFailed(input_type) => { + write!(f, "Failed to parse input according to type {}", input_type) + } + } } } diff --git a/tailcall-fixtures/error.rs b/tailcall-fixtures/error.rs index 4934642938..763e4392a1 100644 --- a/tailcall-fixtures/error.rs +++ b/tailcall-fixtures/error.rs @@ -16,7 +16,11 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + Error::StdFmt(_) => write!(f, "Std Fmt Error"), + Error::IO(_) => write!(f, "Std IO Error"), + Error::FilenameNotResolved => write!(f, "Failed to resolve filename"), + } } } diff --git a/tailcall-prettier/src/error.rs b/tailcall-prettier/src/error.rs index 2dfe5e4680..87d8591951 100644 --- a/tailcall-prettier/src/error.rs +++ b/tailcall-prettier/src/error.rs @@ -27,7 +27,16 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + Error::IO(_) => write!(f, "Std IO Error"), + Error::Join(_) => write!(f, "Join Error"), + Error::FromUtf8(_) => write!(f, "From Utf8 Error"), + Error::PrettierFormattingFailed(msg) => { + write!(f, "Prettier formatting failed: {}", msg) + } + Error::FileExtensionNotFound => write!(f, "No file extension found"), + Error::UnsupportedFiletype => write!(f, "Unsupported file type"), + } } } diff --git a/tailcall-tracker/src/error.rs b/tailcall-tracker/src/error.rs index d6d458cc4a..c41cec9f39 100644 --- a/tailcall-tracker/src/error.rs +++ b/tailcall-tracker/src/error.rs @@ -20,7 +20,12 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.to_string()) + match self { + Error::Reqwest(_) => write!(f, "Reqwest Error"), + Error::InvalidHeaderValue(_) => write!(f, "Invalid Header Value"), + Error::SerdeJson(_) => write!(f, "Serde JSON Error"), + Error::UrlParser(_) => write!(f, "Url Parser Error"), + } } } From 2aaf3e344ea0f17b63de802cad1c0ea59bf9cfd9 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 18:10:06 +0000 Subject: [PATCH 10/12] fix: failing tests --- src/core/rest/directive.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/core/rest/directive.rs b/src/core/rest/directive.rs index f489a960db..d7992438d8 100644 --- a/src/core/rest/directive.rs +++ b/src/core/rest/directive.rs @@ -215,7 +215,10 @@ mod tests { let query = generate_query_with_directive(&query, DEFAULT_QUERY_PARAM); let directive = query_to_directive(&query); // Will panic - Rest::try_from(&directive).unwrap(); + match Rest::try_from(&directive) { + Ok(_) => panic!("Test should have failed but it succeeded"), + Err(e) => panic!("{}", e), + } } #[test] @@ -226,6 +229,9 @@ mod tests { let query = generate_query_with_directive(&query, DEFAULT_QUERY_PARAM); let directive = query_to_directive(&query); // Will panic - Rest::try_from(&directive).unwrap(); + match Rest::try_from(&directive) { + Ok(_) => panic!("Test should have failed but it succeeded"), + Err(e) => panic!("{}", e), + } } } From 1313fcb64f4fe4e687ab2a8cb77631fb58212e58 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 18:20:19 +0000 Subject: [PATCH 11/12] revert: ci changes --- .github/workflows/ci.yml | 551 ++++++++++++++++++++------------------- 1 file changed, 276 insertions(+), 275 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab960a76ba..5fbacee37c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,7 @@ on: branches: - main pull_request: + branches: [main] types: [opened, reopened, synchronize] permissions: contents: read @@ -180,280 +181,280 @@ jobs: - name: Check all examples run: ./examples/lint.sh - # draft_release: - # name: Draft Release - # if: github.event_name == 'push' && github.ref == 'refs/heads/main' - # runs-on: ubuntu-latest - # permissions: - # contents: write - # pull-requests: write - # steps: - # - name: Checkout Current Branch (Fast) - # uses: actions/checkout@v4 - - # - id: create_release - # uses: release-drafter/release-drafter@v6 - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # with: - # config-name: release-drafter.yml - - # - name: Set Output for Later Jobs - # id: set_output - # run: | - # echo "create_release_name=${{ steps.create_release.outputs.name }}" >> $GITHUB_OUTPUT - # echo "create_release_id=${{ steps.create_release.outputs.id }}" >> $GITHUB_OUTPUT - # outputs: - # create_release_name: ${{ steps.set_output.outputs.create_release_name }} - # create_release_id: ${{ steps.set_output.outputs.create_release_id }} + draft_release: + name: Draft Release + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout Current Branch (Fast) + uses: actions/checkout@v4 + + - id: create_release + uses: release-drafter/release-drafter@v6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + config-name: release-drafter.yml + + - name: Set Output for Later Jobs + id: set_output + run: | + echo "create_release_name=${{ steps.create_release.outputs.name }}" >> $GITHUB_OUTPUT + echo "create_release_id=${{ steps.create_release.outputs.id }}" >> $GITHUB_OUTPUT + outputs: + create_release_name: ${{ steps.set_output.outputs.create_release_name }} + create_release_id: ${{ steps.set_output.outputs.create_release_id }} # TODO: move to separate file to separate responsibilities - # release: - # name: Release - # needs: [setup_build_matrix, test, draft_release, check_if_build, test_cf] - # # TODO: put a condition to separate job that other will depend on to remove duplication? - # if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') - # runs-on: ${{ matrix.os || 'ubuntu-latest' }} - # strategy: - # fail-fast: false - # matrix: ${{ fromJson(needs.setup_build_matrix.outputs.matrix) }} - # permissions: - # contents: write - # pull-requests: write - # env: - # GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} - # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - - # steps: - # - name: Checkout Current Branch (Fast) - # uses: actions/checkout@v4 - - # - name: Install Rust Toolchain - # uses: actions-rust-lang/setup-rust-toolchain@v1 - # with: - # target: ${{ matrix.target }} - - # - name: Build - # env: - # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name}} - # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - # uses: ClementTsang/cargo-action@v0.0.6 - # with: - # use-cross: ${{ matrix.cross }} - # command: build - # args: ${{matrix.features}} --release --target ${{ matrix.target }} - - # - name: Install Node.js - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # uses: actions/setup-node@v4 - # with: - # node-version: 20.11.0 - # registry-url: https://registry.npmjs.org - - # - name: Install dependencies - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # run: | - # cd npm - # npm install - - # - name: Run generate.js script - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # run: | - # cd npm - # npm run gen -- --target ${{matrix.target}} --version ${{ env.APP_VERSION }} --build ${{matrix.build}} --ext ${{ matrix.ext || '' }} --libc ${{ matrix.libc }} - # - name: Setup .npmrc file to publish to npm - # run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc - - # - name: NPM Publish - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # uses: JS-DevTools/npm-publish@main - # with: - # token: ${{ secrets.NPM_TOKEN }} - # package: npm/@tailcallhq/core-${{matrix.build}} - # access: public - - # - name: Rename Binary with Target Name - # if: github.event_name == 'push' && github.ref == 'refs/heads/main' - # run: | - # pwd - # cp target/${{ matrix.target }}/release/tailcall${{ matrix.ext }} target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} - - # - name: Upload ${{ matrix.target }} Binary - # if: github.event_name == 'push' && github.ref == 'refs/heads/main' - # uses: xresloader/upload-to-github-release@v1 - # with: - # release_id: ${{ needs.draft_release.outputs.create_release_id }} - # file: target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} - # overwrite: true - # release_lambda: - # name: Release (AWS Lambda) - # needs: [test, draft_release, check_if_build, test_cf] - # if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') - # runs-on: ubuntu-latest - # permissions: - # contents: write - # pull-requests: write - # env: - # GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} - # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - - # steps: - # - name: Checkout Current Branch (Fast) - # uses: actions/checkout@v4 - - # - name: Install Correct Toolchain - # uses: actions-rust-lang/setup-rust-toolchain@v1 - - # - name: Install Python - # uses: actions/setup-python@v5 - # with: - # python-version: "3.12" - - # - name: Install cargo-lambda - # run: pip install cargo-lambda - - # - name: Build - # env: - # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} - # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - # run: cargo lambda build -p tailcall-aws-lambda --release --target x86_64-unknown-linux-musl - - # - name: Rename Binary with Target Name - # run: | - # pwd - # cp target/lambda/tailcall-aws-lambda/bootstrap target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap - - # - name: Upload AWS Lambda Bootstrap Binary - # uses: xresloader/upload-to-github-release@v1 - # with: - # release_id: ${{ needs.draft_release.outputs.create_release_id }} - # file: target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap - # overwrite: true - # semantic_release: - # name: Semantic Release - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # needs: [draft_release, release, release_lambda] - # runs-on: ubuntu-latest - # permissions: - # contents: write - # pull-requests: write - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - # steps: - # - name: Publish Release - # uses: test-room-7/action-publish-release-drafts@v0 - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # with: - # github-token: ${{ secrets.GITHUB_TOKEN }} - # tag-name: ${{needs.draft_release.outputs.create_release_name }} - - # publish_npm_root: - # name: Publish NPM main package - # needs: [draft_release, release] - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # runs-on: ubuntu-latest - # steps: - # - name: Checkout Current Branch (Fast) - # uses: actions/checkout@v4 - # - name: Install Node - # uses: actions/setup-node@v4 - # with: - # node-version: 20.11.0 - # registry-url: https://registry.npmjs.org - # - name: Install dependencies - # run: | - # cd npm - # npm install - # - name: Run generate-root.js script - # env: - # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - # run: | - # cd npm - # npm run gen-root -- --version ${{ env.APP_VERSION }} --name @tailcallhq/tailcall - # - name: Setup .npmrc file to publish to npm - # run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc - # - name: Publish packages - # uses: JS-DevTools/npm-publish@main - # with: - # token: ${{ secrets.NPM_TOKEN }} - # package: npm/@tailcallhq/tailcall - # access: public - - # env: - # APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} - # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - - # build-and-push-image: - # env: - # REGISTRY: ghcr.io - # IMAGE_NAME: ${{ github.repository }}/tc-server - # APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} # Ensure APP_VERSION is set correctly - # needs: [draft_release, release] - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # runs-on: ubuntu-latest - # # Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job. - # permissions: - # contents: read - # packages: write - # # - # steps: - # - name: Checkout Repository - # uses: actions/checkout@v4 - # # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. - # - name: Log in to the Container Registry - # uses: docker/login-action@v3 - # with: - # registry: ${{ env.REGISTRY }} - # username: ${{ github.actor }} - # password: ${{ secrets.GITHUBTOKEN }} - # # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. - # - name: Extract Metadata (tags, labels) for Docker - # id: meta - # uses: docker/metadata-action@v5 - # with: - # images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - # tags: | - # type=raw,value=${{ env.APP_VERSION }} - # type=raw,value=latest,enable=${{ endsWith(env.APP_VERSION, '-SNAPSHOT') == false }} - # # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. - # # It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository. - # # It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step. - # - name: Build and Push the Docker Image - # uses: docker/build-push-action@v6 - # with: - # context: . - # push: true - # tags: ${{ steps.meta.outputs.tags }} - # labels: ${{ steps.meta.outputs.labels }} - - # homebrew-release: - # name: Homebrew Release - # needs: [draft_release, release, semantic_release] - # if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') - # permissions: - # contents: write - # pull-requests: write - # runs-on: ubuntu-latest - # steps: - # - uses: actions/checkout@v4 - # with: - # repository: tailcallhq/homebrew-tailcall - # ref: main - # token: ${{ secrets.HOMEBREW_ACCESS }} - - # - name: Update Homebrew Formula - # run: ./update-formula.sh ${{needs.draft_release.outputs.create_release_name }} - - # failure-notification: - # runs-on: ubuntu-latest - # steps: - # - name: Notify failure on Discord - # if: ${{ always() && contains(needs.*.result, 'failure') }} - # uses: discord-actions/message@v2 - # with: - # webhookUrl: ${{ secrets.DISCORD_WEBHOOK_URL }} - # message: | - # Build failed on branch: ${{ github.ref }} - # Link: ${{ github.repository }}/actions/runs/${{ github.run_id }} + release: + name: Release + needs: [setup_build_matrix, test, draft_release, check_if_build, test_cf] + # TODO: put a condition to separate job that other will depend on to remove duplication? + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') + runs-on: ${{ matrix.os || 'ubuntu-latest' }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.setup_build_matrix.outputs.matrix) }} + permissions: + contents: write + pull-requests: write + env: + GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} + APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + + steps: + - name: Checkout Current Branch (Fast) + uses: actions/checkout@v4 + + - name: Install Rust Toolchain + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + target: ${{ matrix.target }} + + - name: Build + env: + APP_VERSION: ${{ needs.draft_release.outputs.create_release_name}} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + uses: ClementTsang/cargo-action@v0.0.6 + with: + use-cross: ${{ matrix.cross }} + command: build + args: ${{matrix.features}} --release --target ${{ matrix.target }} + + - name: Install Node.js + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + uses: actions/setup-node@v4 + with: + node-version: 20.11.0 + registry-url: https://registry.npmjs.org + + - name: Install dependencies + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + run: | + cd npm + npm install + + - name: Run generate.js script + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + run: | + cd npm + npm run gen -- --target ${{matrix.target}} --version ${{ env.APP_VERSION }} --build ${{matrix.build}} --ext ${{ matrix.ext || '' }} --libc ${{ matrix.libc }} + - name: Setup .npmrc file to publish to npm + run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc + + - name: NPM Publish + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + uses: JS-DevTools/npm-publish@main + with: + token: ${{ secrets.NPM_TOKEN }} + package: npm/@tailcallhq/core-${{matrix.build}} + access: public + + - name: Rename Binary with Target Name + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + run: | + pwd + cp target/${{ matrix.target }}/release/tailcall${{ matrix.ext }} target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} + + - name: Upload ${{ matrix.target }} Binary + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + uses: xresloader/upload-to-github-release@v1 + with: + release_id: ${{ needs.draft_release.outputs.create_release_id }} + file: target/${{ matrix.target }}/release/tailcall-${{ matrix.target }}${{ matrix.ext }} + overwrite: true + release_lambda: + name: Release (AWS Lambda) + needs: [test, draft_release, check_if_build, test_cf] + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && (needs.check_if_build.outputs.check_if_build == 'true') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + env: + GITHUB_TOKEN: ${{secrets.GITHUBTOKEN}} + APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + + steps: + - name: Checkout Current Branch (Fast) + uses: actions/checkout@v4 + + - name: Install Correct Toolchain + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install cargo-lambda + run: pip install cargo-lambda + + - name: Build + env: + APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: cargo lambda build -p tailcall-aws-lambda --release --target x86_64-unknown-linux-musl + + - name: Rename Binary with Target Name + run: | + pwd + cp target/lambda/tailcall-aws-lambda/bootstrap target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap + + - name: Upload AWS Lambda Bootstrap Binary + uses: xresloader/upload-to-github-release@v1 + with: + release_id: ${{ needs.draft_release.outputs.create_release_id }} + file: target/lambda/tailcall-aws-lambda/tailcall-aws-lambda-bootstrap + overwrite: true + semantic_release: + name: Semantic Release + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + needs: [draft_release, release, release_lambda] + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + steps: + - name: Publish Release + uses: test-room-7/action-publish-release-drafts@v0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + tag-name: ${{needs.draft_release.outputs.create_release_name }} + + publish_npm_root: + name: Publish NPM main package + needs: [draft_release, release] + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + runs-on: ubuntu-latest + steps: + - name: Checkout Current Branch (Fast) + uses: actions/checkout@v4 + - name: Install Node + uses: actions/setup-node@v4 + with: + node-version: 20.11.0 + registry-url: https://registry.npmjs.org + - name: Install dependencies + run: | + cd npm + npm install + - name: Run generate-root.js script + env: + APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + run: | + cd npm + npm run gen-root -- --version ${{ env.APP_VERSION }} --name @tailcallhq/tailcall + - name: Setup .npmrc file to publish to npm + run: echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc + - name: Publish packages + uses: JS-DevTools/npm-publish@main + with: + token: ${{ secrets.NPM_TOKEN }} + package: npm/@tailcallhq/tailcall + access: public + + env: + APP_VERSION: ${{needs.draft_release.outputs.create_release_name }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + build-and-push-image: + env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }}/tc-server + APP_VERSION: ${{ needs.draft_release.outputs.create_release_name }} # Ensure APP_VERSION is set correctly + needs: [draft_release, release] + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + runs-on: ubuntu-latest + # Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job. + permissions: + contents: read + packages: write + # + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. + - name: Log in to the Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUBTOKEN }} + # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. + - name: Extract Metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=raw,value=${{ env.APP_VERSION }} + type=raw,value=latest,enable=${{ endsWith(env.APP_VERSION, '-SNAPSHOT') == false }} + # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. + # It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository. + # It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step. + - name: Build and Push the Docker Image + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + + homebrew-release: + name: Homebrew Release + needs: [draft_release, release, semantic_release] + if: (startsWith(github.event.head_commit.message, 'feat') || startsWith(github.event.head_commit.message, 'fix')) && (github.event_name == 'push' && github.ref == 'refs/heads/main') + permissions: + contents: write + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + repository: tailcallhq/homebrew-tailcall + ref: main + token: ${{ secrets.HOMEBREW_ACCESS }} + + - name: Update Homebrew Formula + run: ./update-formula.sh ${{needs.draft_release.outputs.create_release_name }} + + failure-notification: + runs-on: ubuntu-latest + steps: + - name: Notify failure on Discord + if: ${{ always() && contains(needs.*.result, 'failure') }} + uses: discord-actions/message@v2 + with: + webhookUrl: ${{ secrets.DISCORD_WEBHOOK_URL }} + message: | + Build failed on branch: ${{ github.ref }} + Link: ${{ github.repository }}/actions/runs/${{ github.run_id }} \ No newline at end of file From 536ab8a613d25414df439be911f6d7c10ad1fa06 Mon Sep 17 00:00:00 2001 From: Mehul Mathur Date: Sun, 7 Jul 2024 18:30:42 +0000 Subject: [PATCH 12/12] fix: lint --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5fbacee37c..326441520a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -457,4 +457,4 @@ jobs: webhookUrl: ${{ secrets.DISCORD_WEBHOOK_URL }} message: | Build failed on branch: ${{ github.ref }} - Link: ${{ github.repository }}/actions/runs/${{ github.run_id }} \ No newline at end of file + Link: ${{ github.repository }}/actions/runs/${{ github.run_id }}