-
Notifications
You must be signed in to change notification settings - Fork 6
Add poll_async_job helper #185
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
f543ae1
Add poll_async_job helper
c-fang a6123b0
Check deadline before next poll
c-fang 6de3056
Use poll_async_job in Report.save_report
c-fang c6766fb
Cap sleep to remaining poll_time; yapf
c-fang 9209b86
Add extra_params kwarg to Report.request and save_report
c-fang f473c95
Treat COMPLETED as terminal in initial request response
c-fang 47671a6
Use mock.patch for time.monotonic to avoid leaking state
c-fang e82b079
Raise immediately on terminal error from initial request
c-fang 42a6233
Reject report_type override in extra_params
c-fang babe9b1
Document save_report as the recommended entry point
c-fang 76169a8
Fold initial request into poll loop
c-fang 2d1eed6
Collapse AsyncJobTimeoutError into AsyncJobError
c-fang dc487df
Add initial_status parameter to poll_async_job
c-fang 7d214ef
yapf
c-fang be2bae6
Address review nits: frozenset constants, simpler poll loop
c-fang a5d1270
Clarify poll_time as a between-polls waiting budget
c-fang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| """Polling helper for async-job status endpoints.""" | ||
|
|
||
| import time | ||
|
|
||
| DEFAULT_IN_PROGRESS_STATUSES = frozenset({"IN_PROGRESS", "CREATING"}) | ||
| DEFAULT_COMPLETED_STATUSES = frozenset({"COMPLETED", "READY"}) | ||
| DEFAULT_ERROR_STATUSES = frozenset({"ERROR", "FAILED"}) | ||
|
|
||
|
|
||
| class AsyncJobError(Exception): | ||
| """Raised when an async job fails or times out. | ||
|
|
||
| The ``status`` dict carries the underlying error; timeouts use the | ||
| synthetic ``status="TIMEOUT"`` sentinel so callers can distinguish | ||
| them from server-side failures. | ||
| """ | ||
|
|
||
| def __init__(self, status): | ||
| self.status = status | ||
| error = status.get("error") or status.get("type") or "async job failed" | ||
| super().__init__(error) | ||
|
|
||
|
|
||
| def poll_async_job( | ||
| check_status, | ||
| *, | ||
| poll_time, | ||
| poll_interval, | ||
| initial_status=None, | ||
| in_progress_statuses=DEFAULT_IN_PROGRESS_STATUSES, | ||
| completed_statuses=DEFAULT_COMPLETED_STATUSES, | ||
| error_statuses=DEFAULT_ERROR_STATUSES, | ||
| ): | ||
| """Poll ``check_status()`` until it returns a terminal status. | ||
|
|
||
| Arguments: | ||
| check_status: zero-arg callable returning a dict with a ``status`` key. | ||
| poll_time: seconds budgeted for waiting between polls; when exhausted, | ||
| AsyncJobError is raised with the synthetic ``status="TIMEOUT"`` | ||
| sentinel. | ||
| poll_interval: seconds to sleep between polls. | ||
| initial_status: optional status dict consumed in place of the first | ||
| ``check_status()`` call — useful when the caller already has the | ||
| response from a kick-off endpoint. | ||
| in_progress_statuses: status strings that mean "keep polling". | ||
| completed_statuses: status strings that mean "return the status dict". | ||
| error_statuses: status strings that mean "raise AsyncJobError". | ||
|
|
||
| Returns the terminal status dict. | ||
| """ | ||
| deadline = time.monotonic() + poll_time | ||
| status = initial_status if initial_status is not None else check_status() | ||
| while True: | ||
| value = status.get("status") | ||
| if value in completed_statuses: | ||
| return status | ||
| if value in error_statuses: | ||
| raise AsyncJobError(status) | ||
| if value not in in_progress_statuses: | ||
| message = f"unexpected status {value!r}" | ||
| raise AsyncJobError({**status, "error": message}) | ||
| remaining = deadline - time.monotonic() | ||
| if remaining <= 0: | ||
| message = f"async job did not complete within {poll_time} seconds" | ||
| raise AsyncJobError({"status": "TIMEOUT", "error": message}) | ||
| time.sleep(min(poll_interval, remaining)) | ||
| status = check_status() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a poll response arrives after
poll_timehas already elapsed, this branch still returns it as successful because the deadline is only checked later for in-progress statuses. For example, with an initialIN_PROGRESS,poll_time=1, and a delayed/overslept nextcheck_status()returningCOMPLETEDafter the deadline, callers get success despite the documented maximum wait; the fresh evidence is that this revision still returns completed statuses before any post-poll deadline check.Useful? React with 👍 / 👎.