Skip to content

Add a wait option for jobs dispatched #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

randy-coburn-zeam
Copy link

@randy-coburn-zeam randy-coburn-zeam commented Jul 28, 2025

https://github.com/convictional/trigger-workflow-and-wait

This repo has a similar function but fails to correctly identify the jobs that have been created by the dispatch request. However what it does do is wait for the job to be finished and possibly propagate the outcome of the job.

I have added this feature in.

image

Summary by CodeRabbit

  • New Features

    • Added options to wait for workflow run completion and control retry behavior, including maximum attempts, interval, and whether to propagate failures.
    • Introduced a mechanism to monitor workflow progress and handle different completion outcomes based on user configuration.
  • Bug Fixes

    • Improved input handling for timeout and retry parameters.
  • Tests

    • Expanded test coverage for new input options and workflow completion monitoring features.

Copy link

coderabbitai bot commented Jul 28, 2025

Walkthrough

The changes introduce new configuration options to control waiting for workflow completion, retry intervals, and failure propagation in a GitHub Action. The implementation adds input parameters, extends configuration interfaces, introduces a polling function to monitor workflow completion, and updates tests to cover these new behaviors. Conditional logic in the main workflow now optionally waits for completion.

Changes

Cohort / File(s) Change Summary
Action Inputs
action.yml
Added new inputs: wait_for_run_completed, max_completed_fetch_attempts, max_completed_fetch_interval, propagate_failures. Changed defaults for workflow_timeout_seconds and workflow_job_steps_retry_seconds from integers to strings.
Configuration & Utilities
src/action.ts
Extended ActionConfig with new properties, added getBoolFromValue utility, updated getConfig to handle new inputs.
Configuration Tests
src/action.spec.ts
Updated tests to mock and verify new input parameters in configuration.
API Implementation
src/api.ts
Added waitForDispatch function to poll workflow run status, handle retries, and propagate failures based on configuration.
API Tests
src/api.spec.ts
Added comprehensive tests for waitForDispatch, covering success, failure, cancellation, timeout, and error propagation scenarios.
Main Workflow Logic
src/main.ts
Added conditional logic to optionally wait for workflow completion using waitForDispatch based on configuration.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GitHub Action (main.ts)
    participant Config (action.ts)
    participant API (api.ts)
    participant GitHub API

    User->>GitHub Action (main.ts): Trigger Action
    GitHub Action (main.ts)->>Config (action.ts): getConfig()
    Config (action.ts)-->>GitHub Action (main.ts): ActionConfig
    GitHub Action (main.ts)->>GitHub API: Dispatch Workflow
    GitHub API-->>GitHub Action (main.ts): runId, url
    alt waitForRunCompleted = true
        GitHub Action (main.ts)->>API (api.ts): waitForDispatch(runId, url)
        loop up to maxCompletedFetchAttempts
            API (api.ts)->>GitHub API: Get workflow run status
            GitHub API-->>API (api.ts): status, conclusion
            alt status == "completed"
                alt conclusion == "success"
                    API (api.ts)-->>GitHub Action (main.ts): Success
                else conclusion == "failure" or "cancelled"
                    alt propagateFailures = true
                        API (api.ts)-->>GitHub Action (main.ts): Throw error
                    else
                        API (api.ts)-->>GitHub Action (main.ts): Return
                    end
                end
            else
                API (api.ts)->>API (api.ts): Sleep interval
            end
        end
    else
        GitHub Action (main.ts)->>GitHub Action (main.ts): handleActionSuccess()
    end
    GitHub Action (main.ts)-->>User: Done
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit waits by workflow’s gate,
Watching jobs complete, not late.
With retries set and failures caught,
Each hop is careful, never fraught.
Now patience blooms in YAML fields—
Success or fail, the Action yields!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/action.ts (1)

7-9: Remove redundant type annotations.

TypeScript can infer these types from the literal values, making the explicit type annotations unnecessary.

-const WORKFLOW_JOB_COMPLETE_RETRY_SECONDS: number = 10;
-const WORKFLOW_JOB_COMPLETE_CHECK_MAX_ATTEMPTS: number = 30; // 5 minutes with default 10 seconds between attempts
-const WORKFLOW_JOB_COMPLETE_CHECK_PROPAGATE_FAILURES: boolean = false;
+const WORKFLOW_JOB_COMPLETE_RETRY_SECONDS = 10;
+const WORKFLOW_JOB_COMPLETE_CHECK_MAX_ATTEMPTS = 30; // 5 minutes with default 10 seconds between attempts
+const WORKFLOW_JOB_COMPLETE_CHECK_PROPAGATE_FAILURES = false;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5022e2e and 2f6afa7.

⛔ Files ignored due to path filters (2)
  • dist/index.mjs is excluded by !**/dist/**
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • action.yml (1 hunks)
  • src/action.spec.ts (2 hunks)
  • src/action.ts (3 hunks)
  • src/api.spec.ts (3 hunks)
  • src/api.ts (1 hunks)
  • src/main.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/api.ts (1)
src/utils.ts (1)
  • sleep (64-66)
🪛 ESLint
src/action.ts

[error] 7-7: Type number trivially inferred from a number literal, remove type annotation.

(@typescript-eslint/no-inferrable-types)


[error] 8-8: Type number trivially inferred from a number literal, remove type annotation.

(@typescript-eslint/no-inferrable-types)


[error] 9-9: Type boolean trivially inferred from a boolean literal, remove type annotation.

(@typescript-eslint/no-inferrable-types)

🔇 Additional comments (23)
action.yml (2)

32-32: LGTM! Consistent string defaults for GitHub Actions.

The change to string defaults for workflow_timeout_seconds and workflow_job_steps_retry_seconds is appropriate as GitHub Actions inputs are always strings and need to be parsed.

Also applies to: 37-37


40-51: LGTM! Well-designed configuration inputs for wait functionality.

The new inputs provide comprehensive control over the wait behavior with sensible defaults:

  • wait_for_run_completed: Enables the feature
  • max_completed_fetch_attempts: Reasonable 30 attempts default
  • max_completed_fetch_interval: 10-second intervals balance responsiveness vs API rate limits
  • propagate_failures: Disabled by default for backwards compatibility
src/action.spec.ts (1)

33-36: LGTM! Appropriate test mock extensions.

The test modifications correctly extend the mock infrastructure to support the new configuration inputs without changing the core test logic. This maintains test coverage for the expanded configuration parsing.

Also applies to: 60-67

src/main.ts (1)

50-59: LGTM! Clean conditional integration of wait functionality.

The implementation properly branches the execution flow based on the waitForRunCompleted configuration. When enabled, it calls the new waitForDispatch function; otherwise, it maintains the original behavior. The logic is clear and preserves backwards compatibility.

src/action.ts (3)

60-77: LGTM! Well-structured interface extensions.

The new properties are properly documented and typed, providing clear configuration options for the wait functionality.


105-115: LGTM! Consistent configuration parsing.

The new configuration parsing follows the established pattern and provides appropriate fallbacks to the constants.


119-132: LGTM! Robust boolean parsing utility.

The getBoolFromValue function provides proper validation and error handling for boolean string inputs, with clear error messages for invalid values.

src/api.ts (4)

301-310: LGTM! Good user experience with monitoring URL.

The function starts by logging the monitoring URL and provides periodic reminders every 30 attempts (5 minutes), which helps users track progress externally.


312-345: LGTM! Comprehensive polling logic with proper state handling.

The polling implementation correctly:

  • Fetches workflow run status using the GitHub API
  • Handles all completion conclusions (success, failure, cancelled, timed_out, etc.)
  • Respects the propagateFailures configuration for error propagation
  • Implements configurable sleep intervals between attempts
  • Provides informative logging for each state

347-356: LGTM! Appropriate timeout handling.

The timeout logic properly handles the case when the workflow doesn't complete within the maximum attempts, with behavior controlled by the propagateFailures flag.


357-367: LGTM! Robust error handling.

The error handling catches both Error instances and unexpected error types, with appropriate logging and conditional re-throwing based on the propagateFailures configuration.

src/api.spec.ts (12)

22-22: LGTM!

The import of waitForDispatch is correctly added to support the new test suite.


30-36: Well-structured mock setup for testing.

The mock preserves the actual implementation while only mocking the sleep function to prevent delays during tests. This is a good practice for unit testing asynchronous operations.


361-364: LGTM!

The configuration is appropriately extended with the new properties needed for testing the wait functionality.


1059-1078: Well-configured test setup.

The test configuration uses appropriate values for testing:

  • Smaller retry attempts (3) and intervals (1s) for faster test execution
  • Enables waitForRunCompleted which is necessary for testing this functionality
  • Maintains consistency with other test configurations

1080-1099: Comprehensive success case test.

The test correctly validates the happy path scenario with proper mocking of the GitHub API response and appropriate assertions.


1101-1120: LGTM!

This test correctly verifies that failures are handled gracefully when propagateFailures is false, which is an important behavior to validate.


1122-1143: Good test coverage for failure propagation.

The test correctly validates that errors are thrown when propagateFailures is true and the workflow fails, with an appropriate error message.


1145-1166: LGTM!

This test covers the cancelled workflow scenario well, ensuring that cancellation is treated as a failure when propagateFailures is enabled.


1168-1184: Excellent timeout behavior validation.

This test correctly verifies the retry logic by ensuring the API is called exactly maxCompletedFetchAttempts times (3) when the workflow remains in a non-terminal state.


1186-1207: Good timeout error propagation test.

The test correctly validates that timeout scenarios throw appropriate errors when propagateFailures is enabled, with a clear error message indicating the number of attempts.


1209-1218: LGTM!

This test ensures that API errors are handled gracefully when propagateFailures is false, which is important for robust error handling.


1220-1235: Comprehensive API error propagation test.

The test correctly validates that API errors are properly propagated when propagateFailures is true, ensuring consistent error handling behavior.

@Codex-
Copy link
Owner

Codex- commented Jul 28, 2025

Thanks for the submission.

Awaiting the completion of a job was intentionally left split into a second action I author, see: https://github.com/Codex-/await-remote-run

This is not currently obvious if you only encounter this action in isolation, though, so I will update the readme

Is there anything here that is not covered by the usage of await-remote-run?

@Codex-
Copy link
Owner

Codex- commented Aug 10, 2025

@randy-coburn-zeam please see the above, awaiting your response before proceeding

@randy-coburn-zeam
Copy link
Author

@Codex- I had a question on the issue that I raised to match this PR to.

https://github.com/Codex-/return-dispatch/issues/302

I just wanted to know why these 2 things are split over 2 actions. I would like to know if I am missing something as in my head I don't understand why it would need 2 actions?

I suspect that you can just close and reject this PR since you seem to have made a choice to split these jobs into 2 actions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants