Make all requests return a RequestResponse

This commit is contained in:
Marek Wolan
2024-03-08 14:58:34 +00:00
parent d331224b45
commit beb51834f9
13 changed files with 275 additions and 136 deletions

View File

@@ -1,6 +1,9 @@
from typing import Dict, Literal
from typing import Dict, ForwardRef, Literal
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, validate_call
RequestResponse = ForwardRef("RequestResponse")
"""This makes it possible to type-hint RequestResponse.from_bool return type."""
class RequestResponse(BaseModel):
@@ -9,21 +12,33 @@ class RequestResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
"""Cannot have extra fields in the response. Anything custom goes into the data field."""
status: Literal["pending", "success", "failure"] = "pending"
status: Literal["pending", "success", "failure", "unreachable"] = "pending"
"""
What is the current status of the request:
- pending - the request has not been received yet, or it has been received but it's still being processed.
- success - the request has successfully been received and processed.
- failure - the request could not reach it's intended target or it was rejected.
Note that the failure status should only be used when the request cannot be processed, for instance when the
target SimComponent doesn't exist, or is in an OFF state that prevents it from accepting requests. If the
request is received by the target and the associated action is executed, but couldn't be completed due to
downstream factors, the request was still successfully received, it's just that the result wasn't what was
intended.
- success - the request has been received and executed successfully.
- failure - the request has been received and attempted, but execution failed.
- unreachable - the request could not reach it's intended target, either because it doesn't exist or the target
is off.
"""
data: Dict = {}
"""Catch-all place to provide any additional data that was generated as a response to the request."""
# TODO: currently, status and data have default values, because I don't want to interrupt existing functionality too
# much. However, in the future we might consider making them mandatory.
@classmethod
@validate_call
def from_bool(cls, status_bool: bool) -> RequestResponse:
"""
Construct a basic request response from a boolean.
True maps to a success status. False maps to a failure status.
:param status_bool: Whether to create a successful response
:type status_bool: bool
"""
if status_bool is True:
return cls(status="success", data={})
elif status_bool is False:
return cls(status="failure", data={})