-
Notifications
You must be signed in to change notification settings - Fork 178
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
feat(robot server): add a POST method on the analyses endpoint #14828
Merged
y3rsh
merged 2 commits into
edge
from
AUTH-255-robot-server-create-a-new-analysis-endpoint
Apr 8, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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 |
---|---|---|
|
@@ -4,8 +4,9 @@ | |
from textwrap import dedent | ||
from datetime import datetime | ||
from pathlib import Path | ||
from typing import List, Optional, Union | ||
from typing import List, Optional, Union, Tuple | ||
|
||
from opentrons.protocol_engine.types import RunTimeParamValuesType | ||
from opentrons_shared_data.robot import user_facing_robot_type | ||
from typing_extensions import Literal | ||
|
||
|
@@ -32,13 +33,14 @@ | |
SimpleEmptyBody, | ||
MultiBodyMeta, | ||
PydanticResponse, | ||
RequestModel, | ||
) | ||
|
||
from .protocol_auto_deleter import ProtocolAutoDeleter | ||
from .protocol_models import Protocol, ProtocolFile, Metadata | ||
from .protocol_analyzer import ProtocolAnalyzer | ||
from .analysis_store import AnalysisStore, AnalysisNotFoundError, AnalysisIsPendingError | ||
from .analysis_models import ProtocolAnalysis | ||
from .analysis_models import ProtocolAnalysis, AnalysisRequest, AnalysisSummary | ||
from .protocol_store import ( | ||
ProtocolStore, | ||
ProtocolResource, | ||
|
@@ -162,7 +164,7 @@ class ProtocolLinks(BaseModel): | |
status.HTTP_503_SERVICE_UNAVAILABLE: {"model": ErrorBody[LastAnalysisPending]}, | ||
}, | ||
) | ||
async def create_protocol( # noqa: C901 | ||
async def create_protocol( | ||
files: List[UploadFile] = File(...), | ||
# use Form because request is multipart/form-data | ||
# https://fastapi.tiangolo.com/tutorial/request-forms-and-files/ | ||
|
@@ -238,35 +240,18 @@ async def create_protocol( # noqa: C901 | |
|
||
if cached_protocol_id is not None: | ||
resource = protocol_store.get(protocol_id=cached_protocol_id) | ||
analyses = analysis_store.get_summaries_by_protocol( | ||
protocol_id=cached_protocol_id | ||
) | ||
|
||
try: | ||
if ( | ||
# Unexpected situations, like powering off the robot after a protocol upload | ||
# but before the analysis is complete, can leave the protocol resource | ||
# without an associated analysis. | ||
len(analyses) == 0 | ||
or | ||
# The most recent analysis was done using different RTP values | ||
not await analysis_store.matching_rtp_values_in_analysis( | ||
analysis_summary=analyses[-1], new_rtp_values=parsed_rtp | ||
) | ||
): | ||
# This protocol exists in database but needs to be (re)analyzed | ||
task_runner.run( | ||
protocol_analyzer.analyze, | ||
protocol_resource=resource, | ||
analysis_id=analysis_id, | ||
run_time_param_values=parsed_rtp, | ||
) | ||
analyses.append( | ||
analysis_store.add_pending( | ||
protocol_id=cached_protocol_id, | ||
analysis_id=analysis_id, | ||
) | ||
) | ||
analysis_summaries, _ = await _start_new_analysis_if_necessary( | ||
protocol_id=cached_protocol_id, | ||
analysis_id=analysis_id, | ||
rtp_values=parsed_rtp, | ||
force_reanalyze=False, | ||
protocol_store=protocol_store, | ||
analysis_store=analysis_store, | ||
protocol_analyzer=protocol_analyzer, | ||
task_runner=task_runner, | ||
) | ||
except AnalysisIsPendingError as error: | ||
raise LastAnalysisPending(detail=str(error)).as_error( | ||
status.HTTP_503_SERVICE_UNAVAILABLE | ||
|
@@ -278,7 +263,7 @@ async def create_protocol( # noqa: C901 | |
protocolType=resource.source.config.protocol_type, | ||
robotType=resource.source.robot_type, | ||
metadata=Metadata.parse_obj(resource.source.metadata), | ||
analysisSummaries=analyses, | ||
analysisSummaries=analysis_summaries, | ||
key=resource.protocol_key, | ||
files=[ | ||
ProtocolFile(name=f.path.name, role=f.role) | ||
|
@@ -357,6 +342,53 @@ async def create_protocol( # noqa: C901 | |
) | ||
|
||
|
||
async def _start_new_analysis_if_necessary( | ||
protocol_id: str, | ||
analysis_id: str, | ||
force_reanalyze: bool, | ||
rtp_values: RunTimeParamValuesType, | ||
protocol_store: ProtocolStore, | ||
analysis_store: AnalysisStore, | ||
protocol_analyzer: ProtocolAnalyzer, | ||
task_runner: TaskRunner, | ||
) -> Tuple[List[AnalysisSummary], bool]: | ||
"""Check RTP values and start a new analysis if necessary. | ||
|
||
Returns a tuple of the latest list of analysis summaries (including any newly | ||
started analysis) and whether a new analysis was started. | ||
""" | ||
resource = protocol_store.get(protocol_id=protocol_id) | ||
analyses = analysis_store.get_summaries_by_protocol(protocol_id=protocol_id) | ||
started_new_analysis = False | ||
if ( | ||
force_reanalyze | ||
or | ||
# Unexpected situations, like powering off the robot after a protocol upload | ||
# but before the analysis is complete, can leave the protocol resource | ||
# without an associated analysis. | ||
len(analyses) == 0 | ||
or | ||
# The most recent analysis was done using different RTP values | ||
not await analysis_store.matching_rtp_values_in_analysis( | ||
analysis_summary=analyses[-1], new_rtp_values=rtp_values | ||
) | ||
): | ||
task_runner.run( | ||
protocol_analyzer.analyze, | ||
protocol_resource=resource, | ||
analysis_id=analysis_id, | ||
run_time_param_values=rtp_values, | ||
) | ||
started_new_analysis = True | ||
analyses.append( | ||
analysis_store.add_pending( | ||
protocol_id=protocol_id, | ||
analysis_id=analysis_id, | ||
) | ||
) | ||
return analyses, started_new_analysis | ||
|
||
|
||
@PydanticResponse.wrap_route( | ||
protocols_router.get, | ||
path="/protocols", | ||
|
@@ -519,6 +551,78 @@ async def delete_protocol_by_id( | |
) | ||
|
||
|
||
@PydanticResponse.wrap_route( | ||
protocols_router.post, | ||
path="/protocols/{protocolId}/analyses", | ||
summary="Analyze the protocol", | ||
description=dedent( | ||
""" | ||
Generate an analysis for the protocol, based on last analysis and current request data. | ||
""" | ||
), | ||
status_code=status.HTTP_201_CREATED, | ||
responses={ | ||
status.HTTP_200_OK: {"model": SimpleMultiBody[AnalysisSummary]}, | ||
status.HTTP_201_CREATED: {"model": SimpleMultiBody[AnalysisSummary]}, | ||
status.HTTP_404_NOT_FOUND: {"model": ErrorBody[ProtocolNotFound]}, | ||
status.HTTP_503_SERVICE_UNAVAILABLE: {"model": ErrorBody[LastAnalysisPending]}, | ||
}, | ||
) | ||
async def create_protocol_analysis( | ||
protocolId: str, | ||
request_body: Optional[RequestModel[AnalysisRequest]] = None, | ||
protocol_store: ProtocolStore = Depends(get_protocol_store), | ||
analysis_store: AnalysisStore = Depends(get_analysis_store), | ||
protocol_analyzer: ProtocolAnalyzer = Depends(get_protocol_analyzer), | ||
task_runner: TaskRunner = Depends(get_task_runner), | ||
analysis_id: str = Depends(get_unique_id, use_cache=False), | ||
) -> PydanticResponse[SimpleMultiBody[AnalysisSummary]]: | ||
"""Start a new analysis for the given existing protocol. | ||
|
||
Starts a new analysis for the protocol along with the provided run-time parameter | ||
values (if any), and appends it to the existing analyses. | ||
|
||
If the last analysis in the existing analyses used the same RTP values, then a new | ||
analysis is not created. | ||
|
||
If `forceAnalyze` is True, this will always start a new analysis. | ||
|
||
Returns: List of analysis summaries available for the protocol, ordered as | ||
most recently started analysis last. | ||
""" | ||
Comment on lines
+580
to
+592
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure if this is intentional, but FYI, none of this docstring will show up in the HTTP API docs—it gets overridden by the |
||
if not protocol_store.has(protocolId): | ||
raise ProtocolNotFound(detail=f"Protocol {protocolId} not found").as_error( | ||
status.HTTP_404_NOT_FOUND | ||
) | ||
try: | ||
( | ||
analysis_summaries, | ||
started_new_analysis, | ||
) = await _start_new_analysis_if_necessary( | ||
protocol_id=protocolId, | ||
analysis_id=analysis_id, | ||
rtp_values=request_body.data.runTimeParameterValues if request_body else {}, | ||
force_reanalyze=request_body.data.forceReAnalyze if request_body else False, | ||
protocol_store=protocol_store, | ||
analysis_store=analysis_store, | ||
protocol_analyzer=protocol_analyzer, | ||
task_runner=task_runner, | ||
) | ||
except AnalysisIsPendingError as error: | ||
raise LastAnalysisPending(detail=str(error)).as_error( | ||
status.HTTP_503_SERVICE_UNAVAILABLE | ||
) from error | ||
return await PydanticResponse.create( | ||
content=SimpleMultiBody.construct( | ||
data=analysis_summaries, | ||
meta=MultiBodyMeta(cursor=0, totalLength=len(analysis_summaries)), | ||
), | ||
status_code=status.HTTP_201_CREATED | ||
if started_new_analysis | ||
else status.HTTP_200_OK, | ||
) | ||
|
||
|
||
@PydanticResponse.wrap_route( | ||
protocols_router.get, | ||
path="/protocols/{protocolId}/analyses", | ||
|
This file contains 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 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.
FYI this doesn't quite match the name you have in the method docstring.
forceReAnalyze
vs.forceAnalyze
.