Code Monkey home page Code Monkey logo

Comments (8)

nibanks avatar nibanks commented on June 3, 2024 1

So, I have come up with a solution. In the workflow that gets triggered, I have two separate jobs:

  1. Just has a special name that I can use to uniquely identify the run (via sha)
  2. A completion job that is run at the end.

Then I have this script that uses the gh CLI to find and wait on the workflow: https://github.com/microsoft/msquic/pull/3853/files#diff-45852c4dd2e80af80f14c6a831add8f04c7bf165c7e9d15deeb937c042811979.

from repository-dispatch.

nibanks avatar nibanks commented on June 3, 2024 1

Ultimately, I was able to refactor everything into one simple PowerShell script: run-workflow.ps1. I eliminated the need for the completion job, but still need the "name" job for identification. So, I'm not sure how feasible a "standard" solution will be.

from repository-dispatch.

peter-evans avatar peter-evans commented on June 3, 2024

Hi @nibanks

The way that GitHub have designed this API means that there is no response other than 200 Ok, which just means the dispatch message was sent. It doesn't even mean that a workflow was actually triggered. Whether or not the dispatch triggers a workflow or not is up to the user to make sure the workflow exists in the default branch of the target repo.

So, unfortunately, there is no simple way to wait for a response from the dispatch. If you need that kind of behaviour you would need to build it yourself, perhaps with some shared storage and polling the result.

from repository-dispatch.

nibanks avatar nibanks commented on June 3, 2024

Thanks for the quick response. How easy is it to use the GitHub rest API to try to find the workflow that should have been started from this trigger? And then poll its status?

from repository-dispatch.

peter-evans avatar peter-evans commented on June 3, 2024

Sorry, I don't know. If you come up with a good solution please let me know! 😄

from repository-dispatch.

ansonngch-Sephora avatar ansonngch-Sephora commented on June 3, 2024

Hello @peter-evans are we able to make this available in your repo please?

from repository-dispatch.

peter-evans avatar peter-evans commented on June 3, 2024

@ansonngch-Sephora At the moment I'm not interested in maintaining and supporting a solution for this. However, I can pin this issue so people can find @nibanks solution more easily.

from repository-dispatch.

pmerwin avatar pmerwin commented on June 3, 2024

I wrote this as POC, would you be interested in adding it?

I was thinking the ' Wait for Workflow Completion ' could be added to your action ?

` - name: Trigger Cypress Workflow
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.GH_TOKEN }}
repository: adept-at/lib-cypress-canary
event-type: trigger-skill-preview
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "repo": "${{ github.repository }}", "run_id": "${{ github.run_id }}", "run_attempt": "${{ github.run_attempt }}", "target_url": "${{ github.event.deployment_status.target_url }}"}'
# Wait for the Cypress workflow to complete
- name: Wait for Workflow Completion
run: |
echo "const https = require('https');
const MAX_ATTEMPTS = 8;
let attempt = 0;
const current_time = new Date();
console.log('Current Time: ', current_time.toISOString());
const thirtySecsLater = new Date(current_time.getTime() + 30000);

      async function checkWorkflowStatus() {
        const options = {
          hostname: 'api.github.com',
          path: '/repos/adept-at/lib-cypress-canary/actions/runs',
          method: 'GET',
          headers: {
            'Authorization': 'token ' + process.env.GITHUB_TOKEN,
            'Accept': 'application/vnd.github.v3+json',
            'User-Agent': 'Node.js Script'
          }
        };

        return new Promise((resolve, reject) => {
          https.get(options, (res) => {
            let data = '';
            res.on('data', (chunk) => {
              data += chunk;
            });
            res.on('end', () => {
              const response = JSON.parse(data);
              if (!response.workflow_runs) {
                console.error('Unexpected response structure:', response);
                reject('Invalid API response');
                return;
              }
              console.log('Response:', response.workflow_runs[0].status);
              const workflowRuns = response.workflow_runs.filter(run =>
                new Date(run.created_at) > new Date(current_time) &&
                new Date(run.created_at) < new Date(thirtySecsLater) &&
                run.event === 'repository_dispatch' &&
                run.display_title === 'trigger-skill-preview'
              );
              if (workflowRuns.length > 0) {
                const status = workflowRuns[0].status;
                const conclusion = workflowRuns[0].conclusion;
                console.log('Status of the matching workflow run: ', status);

                // Check if the workflow run is completed
                if (status === 'completed') {
                    console.log('Completed matching workflow run: ', status, conclusion);
                    resolve({ status, conclusion });  // Resolving both status and conclusion
                } else {
                    console.log('Workflow run is not completed yet');
                    resolve({ status, conclusion: null }); // Conclusion is null if not completed
                }
            } else {
                console.log('No workflow runs found');
                reject('No workflow runs found');  // Reject if no workflow runs are found
            }

            });
          }).on('error', (e) => {
            console.error(e);
            reject(e);
          });
        });
      }

      async function waitForWorkflowCompletion() {
        let res = {};
        while (attempt < MAX_ATTEMPTS) {
           try {
              res = await checkWorkflowStatus();
            } catch (error) {
              console.error('Error checking workflow status:', error);
            }
            // ... handle status and conclusion ...
          if (res && res.status === 'completed' && res.conclusion === 'success') {
            console.log('Workflow completed and test passed!');
            break
          } else if (res && res.status === 'completed' && res.conclusion === 'failure') {
            console.log('Workflow status is failed...');
            process.exit(1);
          } else if (res?.status !== '') {
            console.log('Workflow status is ' + res?.status + '. Waiting for completion...');
          } else {
            console.log('Workflow status is unknown. Waiting for completion...');
          }
          attempt++;
          console.log('Attempt: ' + attempt);
          await new Promise(resolve => setTimeout(resolve, 60000)); // 60 seconds
        }

        if (attempt === MAX_ATTEMPTS) {
          console.log('Max attempts reached without completion. Exiting.');
          process.exit(1);
        }
      }
      waitForWorkflowCompletion();" > script.js
      node script.js
env:
  GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}`

from repository-dispatch.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.