Skip to content
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

Pydantic #331

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
290 commits
Select commit Hold shift + click to select a range
18711c3
@robertbartel confirmed in #239 that category and data_domain are not…
aaraney Jan 11, 2023
51992d2
remove commented out Dataset factory_init_from_deserialized_json
aaraney Jan 11, 2023
b4c1970
fix DataDomain's dict method. related to #245
aaraney Jan 18, 2023
8e3e61e
revert DataRequirement's __eq__ implimentation
aaraney Jan 19, 2023
1d4ad47
add note to remove DataDomain.custom_data_fields in future. relates n…
aaraney Jan 19, 2023
7fbd836
exclude custom_data_fields during serialization if empty T variant.
aaraney Jan 19, 2023
00b71c0
add field_serializers Config option to Serializable
aaraney Jan 23, 2023
084592f
fix type hints
aaraney Jan 23, 2023
352f0a6
test Serializable field_serializer Config option
aaraney Jan 23, 2023
269d672
simplify Dataset's dict override with config field_serializer
aaraney Jan 23, 2023
7cf07ea
refactor ContinuousRestriction to use config field_serializers
aaraney Jan 23, 2023
3b1a56a
DataDomain now factory inits continuous_restrictions
aaraney Jan 23, 2023
686926a
remove commented code
aaraney Jan 23, 2023
a2875f7
fix test that was failing for the right reason
aaraney Jan 23, 2023
4cdf4c0
bump dmod.core patch version to 0.7.1
aaraney Jan 26, 2023
3fbca45
fix comm setup.py merge conflict
aaraney Jan 24, 2023
02deff0
dmod.communication enum's now subclass PydanticEnum
aaraney Jan 11, 2023
0fc50a1
refactor Message
aaraney Jan 11, 2023
17b9084
remove unnessesary __init__ in AbstractInitRequest
aaraney Jan 11, 2023
b7e2407
refactor Response
aaraney Jan 11, 2023
e0fcc97
add TODO. fill in Union of data field types once refactored
aaraney Jan 11, 2023
4c04ea2
refactor InvalidMessage
aaraney Jan 11, 2023
f6da238
refactor Response and its subtypes
aaraney Jan 11, 2023
75be6ea
refactor MetadataMessage
aaraney Jan 11, 2023
937ab04
add MetadataSignal type
aaraney Jan 11, 2023
8f154cb
refactor metadata message and response
aaraney Jan 11, 2023
7a807c7
add generate_secret helper function
aaraney Jan 12, 2023
f32c4f1
refactor Sesssion
aaraney Jan 12, 2023
92c7e7e
refactor FullAuthSession
aaraney Jan 12, 2023
275c0d0
refactor SessionInitMessage
aaraney Jan 12, 2023
0c34ec1
refactor FailedSessionInitInfo
aaraney Jan 12, 2023
702ef14
refactor SessionInitResponse
aaraney Jan 12, 2023
22a03c4
refactor UnsupportedMessageTypeResponse
aaraney Jan 12, 2023
e358d3b
format unsupported_message module
aaraney Jan 12, 2023
f3c9b07
refactor UpdateMessage
aaraney Jan 12, 2023
a081599
add UpdateMessageData; inner type of UpdateMessageResponse
aaraney Jan 12, 2023
df8d2ca
refactor UpdateMessageResponse
aaraney Jan 12, 2023
5de7176
refactor SchedulerRequestMessage
aaraney Jan 12, 2023
60628d4
refactor parameter module
aaraney Jan 12, 2023
cb21f75
refactor DmodJobRequest
aaraney Jan 12, 2023
efdb86c
refactor distribution module
aaraney Jan 12, 2023
d7cfd8d
refactor ExternalRequestResponse
aaraney Jan 12, 2023
0f3ba96
refactor DatasetQuery
aaraney Jan 17, 2023
c5b93da
refactor DatasetManagementMessage
aaraney Jan 17, 2023
3548053
refactor MaaSDatasetManagementMessage
aaraney Jan 18, 2023
620ad1c
refactor PartitionRequest
aaraney Jan 18, 2023
44e7ec8
refactor PartitionExternalRequest
aaraney Jan 18, 2023
1d2ad17
fix bug in PartitionRequest __init__
aaraney Jan 18, 2023
eedb1b2
refactor EvaluationRequest
aaraney Jan 18, 2023
dbc1429
refactor EvaluationConnectionRequest
aaraney Jan 18, 2023
a6c03fc
fix typing hints, default value, and retrieval of action in Evaluatio…
aaraney Jan 18, 2023
909d4a1
add ActionParameters class. encapsulates evaluation_name and instruct…
aaraney Jan 18, 2023
40952cc
refactor StartEvaluationRequest
aaraney Jan 18, 2023
b2652c5
refactor DataTransmitMessage
aaraney Jan 18, 2023
5ec992a
refactor dict method logic to follow pattern foundelse where in the c…
aaraney Jan 18, 2023
befd444
complete refactor of UpdateMessageResponse
aaraney Jan 18, 2023
eb089b8
add missing parameters field to StartEvaluationRequest
aaraney Jan 18, 2023
39c2c23
fix bug in validating Sesssion dates
aaraney Jan 18, 2023
61aac6c
explicity cast from IPAddress type into str.
aaraney Jan 18, 2023
a07d348
fix validation of success
aaraney Jan 18, 2023
f6cc1ec
fix FailedSessionInitInfo's fail_time serialization formatting
aaraney Jan 18, 2023
68d65c8
try and coerce SessionInitResponse' data field in correct order
aaraney Jan 18, 2023
4360170
add NWMRequestBody and NWMInnerRequestBody
aaraney Jan 19, 2023
b71bf74
refactor NWMRequest
aaraney Jan 19, 2023
e820e50
adds ModelExecRequestBody. refactored abstract encapsulation of model…
aaraney Jan 19, 2023
32a290a
improve get_available_model type hints
aaraney Jan 19, 2023
39f268a
refactor ModelExecRequest.
aaraney Jan 19, 2023
c9c14c0
refactor NGENRequest
aaraney Jan 19, 2023
81259ce
refactor SchedulerRequestResponse. split it's data property into its …
aaraney Jan 20, 2023
3e26bcf
add NGENRequestBody. encapsulates NGENRequest's `model` field.
aaraney Jan 20, 2023
f23e366
add class var type hints to NGENRequestResponse
aaraney Jan 20, 2023
7d9aaa1
specify ExternalRequest aliases in Config class.
aaraney Jan 20, 2023
98f6ad7
remove, now, unncessary ExternalRequest initializer
aaraney Jan 20, 2023
1cc727e
add class that encapsulates a ModelExecRequestResponseBody
aaraney Jan 20, 2023
d5f3d65
refactor ModelExecRequestResponse
aaraney Jan 20, 2023
b516abd
add DataTransmitUUID class
aaraney Jan 20, 2023
289a92e
refactor DataTransmitMessage to use DataTransmitUUID
aaraney Jan 20, 2023
3d9d58e
refactor DataTransmitResponse
aaraney Jan 20, 2023
ea1607f
refactor DatasetManagementResponse. speperated its body into own data…
aaraney Jan 20, 2023
f901bcc
add type hints to MaaSDatasetManagementResponse class vars
aaraney Jan 20, 2023
8daf2f4
refactor PartitionResponse
aaraney Jan 21, 2023
54056d9
fix faulty logic in SchedulerRequestMessage dict method
aaraney Jan 23, 2023
916ee98
fix typo in DatasetQuery field name
aaraney Jan 23, 2023
32a451c
update dataset query tests
aaraney Jan 23, 2023
c7420ce
factory init model exec requests handles nwm and ngen cases. this sho…
aaraney Jan 23, 2023
2153e83
SchedulerRequestMessage factory inits ModelExecRequest correctly
aaraney Jan 23, 2023
f272847
allow SchedulerRequestResponse instances to be treated as dictionary
aaraney Jan 23, 2023
afccaa2
allow SchedulerRequestResponseBody to be treated like it is a dictionary
aaraney Jan 23, 2023
1e1d3e5
add missing required fields in decorated interface tests
aaraney Jan 23, 2023
52f4f98
add missing required fields to websocket interface tests
aaraney Jan 23, 2023
f20fba0
use relative imports in tests. this avoids, potentially unexpected be…
aaraney Jan 24, 2023
c9aa0bf
change assert eq types in ngen request response tests
aaraney Jan 24, 2023
a718caf
change assert eq types in nwn request response tests
aaraney Jan 24, 2023
b4348e4
add classvar type hints to FieldedMessage
aaraney Jan 24, 2023
d22f490
refactor Session dict override with Config field_serializers
aaraney Jan 24, 2023
83e96e5
refactor FailedSessionInitInfo dict override with Config field_serial…
aaraney Jan 24, 2023
662d19a
refactor DataTransmitUUID dict override with Config field_serializers
aaraney Jan 24, 2023
5aff189
remove unused imports
aaraney Jan 24, 2023
809598f
refactor UpdateMessage dict override with Config field_serializers
aaraney Jan 24, 2023
07397b8
bump minimum required version of dmod.core to 0.4.2
aaraney Jan 26, 2023
2a95186
dekabob (i.e. this-that) SchedulerRequestMessage allocation_paradigm …
aaraney Feb 1, 2023
4473aea
fix property name that does not exist
aaraney Feb 3, 2023
822efc7
fix instance where DataRequirement's init params were not specified a…
aaraney Feb 3, 2023
c8d97c4
fix NWMRequest get_model_name classmethod. see note
aaraney Feb 6, 2023
128579e
Response subtypes are now SerializableDict subtypes. This is more fle…
aaraney Feb 10, 2023
39bdd86
metadata_follows _defaults_ to False. This was pre-pydantic behavior
aaraney Feb 10, 2023
02ed2cb
remove, now, unnecessary PartitionResponseBody magic method overrides…
aaraney Feb 10, 2023
e850d6c
fix, could be none, error in SchedulerRequestResponse
aaraney Feb 10, 2023
78dcf1c
add session_secret validator. handles None as input. pre-pydantic han…
aaraney Feb 10, 2023
63bb60b
fix UpdateMessage object_type validator. _guards_ str types
aaraney Feb 10, 2023
a5746cc
add pydantic as dep to dmod.scheduler
aaraney Jan 27, 2023
4ca0404
refactor enum variants to use dmod.core.enum.PydanticEnum
aaraney Jan 27, 2023
21d246e
refactor JobStatus
aaraney Jan 31, 2023
bde84e4
resource enum's now are based on PydanticEnum
aaraney Jan 31, 2023
8a87c28
refactor AbstractProcessingAssetPool to use pydantic
aaraney Feb 1, 2023
495b115
refactor SingleHostProcessingAssetPool
aaraney Feb 1, 2023
3b3d885
refactor Resource
aaraney Feb 1, 2023
cfdb800
refactor ResourceAllocation
aaraney Feb 1, 2023
9baa403
resource fields accepted case insensitively
aaraney Feb 1, 2023
3dbe6f2
add accidentally remove total_cpu_count prop
aaraney Feb 1, 2023
5a364b1
validate that cpu and memory total cannot be larger than cpu and memory
aaraney Feb 1, 2023
5c3c6ee
refactor RsaKeyPair
aaraney Feb 2, 2023
ae16b44
add RsaKeyPair unit tests
aaraney Feb 2, 2023
b212ea7
restore unit test assertion condition
aaraney Feb 3, 2023
82737f5
validate RsaKeyPair property assignment. Required to retain previous …
aaraney Feb 3, 2023
66c7aef
testing: verify modifying RsaKeyPair directory through a setter behav…
aaraney Feb 3, 2023
c967e38
add class var type hint to JobStatus
aaraney Feb 6, 2023
88552b6
JobStatus `name` property now uses fstring
aaraney Feb 6, 2023
3fbb0cc
ignore type hints that static checker cannot catch
aaraney Feb 6, 2023
8ec3fcc
refactor Job to use pydantic
aaraney Feb 6, 2023
90eea5b
deprecate Job property setters. set through setter method instead.
aaraney Feb 6, 2023
9d2de62
import validator and cache
aaraney Feb 6, 2023
b7bf44a
refactor JobImp to use pydantic
aaraney Feb 6, 2023
bf75ea8
refactor RequestedJob to use pydantic
aaraney Feb 6, 2023
f387e3c
fix rsa test bug. was not cleaning up
aaraney Feb 6, 2023
370a7d8
add type hints to tests
aaraney Feb 6, 2023
82d7e30
fix missing field in test setup
aaraney Feb 6, 2023
a1816c8
cannot cache _setter_methods. if this becomes bottleneck, we can cach…
aaraney Feb 6, 2023
9767bd6
change Job's allocations field to optional tuple from optional list
aaraney Feb 6, 2023
bece729
Resource unit tests
aaraney Feb 6, 2023
924f3d7
add JobImpl setter tests
aaraney Feb 7, 2023
8667009
format modeldata's setup.py
aaraney Jan 26, 2023
aa1b408
add missing dep, gitpython to modeldata's setup.py
aaraney Jan 26, 2023
b27980a
add pydantic dep
aaraney Jan 26, 2023
57b36dd
refactor SubsetDefinition
aaraney Jan 26, 2023
8609f29
refactor Partition
aaraney Jan 26, 2023
e1fcc5d
refactor PartitionConfig
aaraney Jan 26, 2023
83369b2
add kwargs argument to SubsetDefinition initilizer
aaraney Jan 26, 2023
b581169
refactor HydrofabricSubset
aaraney Jan 26, 2023
76963cb
refactor SimpleHydrofabricSubset
aaraney Jan 26, 2023
04d16da
move HydrofabricSubset initializer
aaraney Jan 26, 2023
c21e9eb
add private attr class level declarations to SimpleHydrofabricSubset
aaraney Jan 26, 2023
1bd5bbd
update Tuple type hints to be variadic
aaraney Jan 26, 2023
c5fc58b
fix reference to non-existent field
aaraney Feb 7, 2023
70f0020
add missing PrivateAttr field to Partition
aaraney Feb 7, 2023
82e2a2b
typo in Partition's fields alias map
aaraney Feb 7, 2023
f5be90c
serialize Partition fields as list and fix it's intializer fn to allo…
aaraney Feb 7, 2023
acb9b5e
add Partition unit tests
aaraney Feb 7, 2023
4b0d20a
fix invalid reference
aaraney Feb 7, 2023
84216f9
add PartionConfig unittests. format with black
aaraney Feb 7, 2023
4f03651
add PartionConfig field_serializer
aaraney Feb 7, 2023
c26b455
override PartitionConfig dict method.
aaraney Feb 7, 2023
c48bc4a
replace private reference to Dataset field name
aaraney Feb 10, 2023
a4f0a99
replace private reference to Dataset field name in test
aaraney Feb 10, 2023
e09c291
no longer use a double wrapped classmethod property. is not supported…
aaraney Feb 10, 2023
a108342
Fix DmodJobRequest default CPU var for Pydantic.
robertbartel Apr 26, 2023
3358c00
Fix external_request.py spacing, per PEP 8.
robertbartel Apr 27, 2023
6495f32
Fix ExternalRequest for updated serial keys.
robertbartel May 3, 2023
99d5067
Fix bad use of SerializedDict in message.py.
robertbartel May 3, 2023
351ae11
Fix bad SerializedDict use in dataset mgr msgs.
robertbartel May 3, 2023
9c6abe7
Fix bad SerializedDict use in data transmit msgs.
robertbartel May 3, 2023
f8bb524
Fix bad SerializedDict use in metadata_message.py.
robertbartel May 3, 2023
9c881fc
Fix bad SerializedDict use in partition requests.
robertbartel May 3, 2023
5adfdf2
Fix bad use of SerializedDict in session.py.
robertbartel May 3, 2023
4b2c062
Fix bad SerializedDict use in update_message.py.
robertbartel May 3, 2023
813541b
Fix bad SerializedDict use in scheduler responses.
robertbartel May 3, 2023
07becd4
Fix test func to be consistent with descript.
robertbartel May 11, 2023
3b99cd1
Remove SerializedDict type.
robertbartel May 16, 2023
ebff645
Change parent of session types to Serializable.
robertbartel May 16, 2023
5a3f7e4
Change parent of message types to Serializable.
robertbartel May 16, 2023
0112215
Change parent of metadata_message to Serializable.
robertbartel May 16, 2023
c52b437
Change parent of UpdateMessageData to Serializable.
robertbartel May 16, 2023
dc5635b
Change parent of scheduler body to Serializable.
robertbartel May 16, 2023
fe1684f
Change parent of partition body to Serializable.
robertbartel May 16, 2023
7318a2e
Change data transmit body parent to Serializable.
robertbartel May 16, 2023
d74f186
Change data mgmt body parent to Serializable.
robertbartel May 16, 2023
96557d5
Update DmodJobRequest for Pydantic refactor.
robertbartel May 16, 2023
7e0c4ec
Refactor ModelExecRequest.
robertbartel May 16, 2023
1e44e55
Remove unneeded ModelExecRequestBody.
robertbartel May 16, 2023
75e90bb
Update AbstractNgenRequest for Pydantic changes.
robertbartel May 16, 2023
329617f
Update NGENRequestBody for Pydantic changes.
robertbartel May 16, 2023
1bd90bf
Update NGENRequest for Pydantic, upstream changes.
robertbartel May 16, 2023
80f9467
Update NWMInnerRequestBody for upstream changes.
robertbartel May 16, 2023
be4af4f
Update NWMRequest for Pydantic, upstream changes.
robertbartel May 16, 2023
7923aae
Add ngen-cal request inner config serializable.
robertbartel May 16, 2023
e76c25e
Update cal request for Pydantic, upstream changes.
robertbartel May 16, 2023
cb7a142
Update schdulr msg for Pydantic, upstream changes.
robertbartel May 16, 2023
ac73023
Add new tests for ModelExecRequest.
robertbartel May 16, 2023
321eb41
Update test_decorated_interface.py for changes.
robertbartel May 16, 2023
c82dafa
Update test_ngen_request.py for changes.
robertbartel May 16, 2023
7522fdf
Update test_nwm_request.py for changes.
robertbartel May 16, 2023
c8eb63a
Update test_scheduler_request for changes.
robertbartel May 16, 2023
ec4aebe
Update test_websocket_interface.py for changes.
robertbartel May 16, 2023
8db6d01
Add unit tests for data mgmt response.
robertbartel May 17, 2023
b446403
Fix bug in data mgmt msg affecting client.
robertbartel May 17, 2023
d893e38
Fix import/init bugs in data_transmit_message.py.
robertbartel May 17, 2023
e15438b
Fix bug in data request client.
robertbartel May 17, 2023
9754b0f
Fix test_job.py after serialization changes.
robertbartel May 25, 2023
cf3c388
Fix test_JobImpl.py after serialization changes.
robertbartel May 25, 2023
0443d43
Fix test_scheduler.py after serialization changes.
robertbartel May 25, 2023
987b61c
Fix spacing between class defs in job.py.
robertbartel May 25, 2023
7d946d0
Adjust ContinuousRestriction hash impl.
robertbartel May 25, 2023
cd4bea7
Fix hash unit test.
robertbartel May 25, 2023
2fd395b
update NGENRequest portion of testing data to fulfilled AbstractNGENR…
aaraney May 26, 2023
7c08924
export NGENRequestBody at package and submodule levels
aaraney May 26, 2023
414ae12
fill void model_request field
aaraney May 26, 2023
2a002af
change DataDomain restriction fields to dict[StandardDatasetIndex, so…
aaraney May 30, 2023
5fe2cc7
update DataDomain tests after restriction field type change
aaraney May 30, 2023
bebee31
update restriction default values in root validator
aaraney May 30, 2023
25d662a
fix ContinuousRestriction validator subtype search
aaraney May 30, 2023
c1281b8
subtype str for StandardDatasetIndex. Enables json encoding if key in…
aaraney May 30, 2023
0f872ee
update tests involving ContinuousRestriction and DiscreteRestriction
aaraney May 30, 2023
10d4ba6
add optional connection_id field to MetadataSignal
aaraney May 30, 2023
478e090
use property assignment rather than object subscription
aaraney May 30, 2023
427f597
Update model exec response funcs for consistency.
robertbartel Jun 5, 2023
f65ab33
Clean up NWMRequest.get_model_name func.
robertbartel Jun 5, 2023
19281c2
Remove deprecated TODOs in scheduler_request.py.
robertbartel Jun 5, 2023
296010a
change DataTransmitResponseBody subtype to type alias of DataTransmit…
aaraney Jun 5, 2023
ea0d10e
remove JobStatus Optional field constraints
aaraney Jun 5, 2023
4b4de7c
simplify key search logic
aaraney Jun 5, 2023
96d6492
Add context to JobImpl's __init__ method logic
aaraney Jun 5, 2023
54376c0
Remove obsolete Session attributes/functions.
robertbartel Jun 6, 2023
964340c
Remove obsolete getters in Session.
robertbartel Jun 6, 2023
704c262
Fix typo in DataDomain.__hash__.
robertbartel Jun 6, 2023
d8b0bec
Removing handled TODOs in job.py.
robertbartel Jun 6, 2023
c279a3e
re-add factory_init_from_request
aaraney Jun 6, 2023
6272e33
fix passing model_request by dictionary
aaraney Jun 6, 2023
fbbbabe
remove unnecessary Serializable inheritance
aaraney Jun 6, 2023
6cfe00d
remove Resource __init__ method. was not used in codebase
aaraney Jun 6, 2023
bc35dd9
update resource initializer in test
aaraney Jun 6, 2023
8b0808c
update __init__ type hints to match pydantic field declarations
aaraney Jun 6, 2023
c277ff7
remove unnecessary validator
aaraney Jun 6, 2023
7f7b795
improve readability
aaraney Jun 6, 2023
bc31ed3
lowercase function scoped constants
aaraney Jun 6, 2023
b534c3e
fix exclude_unset logic
aaraney Jun 6, 2023
85a31a8
Refactor hydrofabric_subset.py.
robertbartel Jun 7, 2023
295545e
improve type hint readability
aaraney Jun 7, 2023
875df9f
improve readability of dict override
aaraney Jun 7, 2023
85aa21a
format docstring
aaraney Jun 7, 2023
c4f0b81
improve readability
aaraney Jun 7, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions python/lib/client/dmod/client/request_clients.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
from abc import ABC, abstractmethod
from datetime import datetime
from dmod.core.execution import AllocationParadigm
from dmod.communication import DataServiceClient, ExternalRequestClient, ManagementAction, ModelExecRequestClient, \
NGENRequest, NGENRequestResponse, \
NgenCalibrationRequest, NgenCalibrationResponse
from dmod.communication.client import R
from dmod.communication.dataset_management_message import DatasetManagementMessage, DatasetManagementResponse, \
MaaSDatasetManagementMessage, MaaSDatasetManagementResponse, QueryType, DatasetQuery
from dmod.communication.data_transmit_message import DataTransmitMessage, DataTransmitResponse
from dmod.core.meta_data import DataCategory, DataDomain, TimeRange
from dmod.core.meta_data import DataCategory, DataDomain
from pathlib import Path
from typing import List, Optional, Tuple, Type, Union

Expand Down Expand Up @@ -86,10 +84,10 @@ def _parse_list_of_dataset_names_from_response(self, response: DatasetManagement
msg = "Can't parse list of datasets from non-{} (received a {} object)"
raise RuntimeError(msg.format(DatasetManagementResponse.__name__, response.__class__.__name__))
# Consider these as valid cases, and treat them as just not listing any datasets
elif not response.success or response.data is None or 'datasets' not in response.data:
elif not response.success or response.data is None or response.data.datasets is None:
return []
else:
return response.data['datasets']
return response.data.datasets

@abstractmethod
async def create_dataset(self, name: str, category: DataCategory, domain: DataDomain, **kwargs) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion python/lib/communication/dmod/communication/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from .maas_request import get_available_models, get_available_outputs, get_distribution_types, get_parameters, \
get_request, AbstractNgenRequest, Distribution, DmodJobRequest, ExternalRequest, ExternalRequestResponse,\
ModelExecRequest, ModelExecRequestResponse, NWMRequest, NWMRequestResponse, Scalar, NGENRequest, \
NGENRequestResponse, NgenCalibrationRequest, NgenCalibrationResponse
NGENRequestResponse, NgenCalibrationRequest, NgenCalibrationResponse, NGENRequestBody
from .message import AbstractInitRequest, MessageEventType, Message, Response, InvalidMessage, InvalidMessageResponse, \
InitRequestResponseReason
from .metadata_message import MetadataPurpose, MetadataMessage, MetadataResponse
Expand Down
125 changes: 36 additions & 89 deletions python/lib/communication/dmod/communication/data_transmit_message.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
from dmod.core.serializable import Serializable
from .message import AbstractInitRequest, MessageEventType, Response
from typing import Dict, Optional, Union
from numbers import Number
from pydantic import Field
from typing import ClassVar, Type, Union
from typing_extensions import TypeAlias
from uuid import UUID


class DataTransmitMessage(AbstractInitRequest):
class DataTransmitUUID(Serializable):
series_uuid: UUID = Field(description="A unique id for the collective series of transmission message this instance is a part of.")
"""
The expectation is that a larger amount of data will be broken up into multiple messages in a series.
"""

class Config:
field_serializers = {"series_uuid": lambda s: str(s)}


class DataTransmitMessage(DataTransmitUUID, AbstractInitRequest):
"""
Specialized message type for transmitting data.

Expand All @@ -18,64 +30,13 @@ class DataTransmitMessage(AbstractInitRequest):
::class:`str` object. However, instances can be initialized using either ::class:`str` or ::class:`bytes` data.
"""

_KEY_SERIES_UUID = 'series_uuid'
event_type: ClassVar[MessageEventType] = MessageEventType.DATA_TRANSMISSION

event_type: MessageEventType = MessageEventType.DATA_TRANSMISSION
data: str = Field(description="The data carried by this message, in decoded string form.")
is_last: bool = Field(False, description="Whether this is the last data transmission message in this series.")

@classmethod
def factory_init_from_deserialized_json(cls, json_obj: dict) -> Optional['DataTransmitMessage']:
try:
return cls(data=json_obj['data'], series_uuid=UUID(json_obj[cls._KEY_SERIES_UUID]),
is_last=json_obj['is_last'])
except Exception as e:
return None

def __init__(self, data: Union[str, bytes], series_uuid: UUID, is_last: bool = False, *args, **kwargs):
super(DataTransmitMessage, self).__init__(*args, **kwargs)
self._data: str = data if isinstance(data, str) else data.decode()
self._series_uuid = series_uuid
self._is_last: bool = is_last

@property
def data(self) -> str:
"""
The data carried by this message, in decoded string form.

Returns
-------
str
The data carried by this message, in decoded string form.
"""
return self._data

@property
def is_last(self) -> bool:
"""
Whether this is the last data transmission message in this series.

Returns
-------
bool
Whether this is the last data transmission message in this series.
"""
return self._is_last

@property
def series_uuid(self) -> UUID:
"""
A unique id for the collective series of transmission message this instance is a part of.

The expectation is that a larger amount of data will be broken up into multiple messages in a series.

Returns
-------
UUID
A unique id for the collective series of transmission message this instance is a part of.
"""
return self._series_uuid

def to_dict(self) -> Dict[str, Union[str, Number, dict, list]]:
return {'data': self.data, self._KEY_SERIES_UUID: str(self.series_uuid), 'is_last': self.is_last}
DataTransmitResponseBody: TypeAlias = DataTransmitUUID


class DataTransmitResponse(Response):
Expand All @@ -86,38 +47,24 @@ class DataTransmitResponse(Response):
series of which it is a part.
"""

response_to_type = DataTransmitMessage

_KEY_SERIES_UUID = response_to_type._KEY_SERIES_UUID

@classmethod
def factory_init_from_deserialized_json(cls, json_obj: dict) -> 'DataTransmitResponse':
"""
Factory create a new instance of this type based on a JSON object dictionary deserialized from received JSON.

Parameters
----------
json_obj

Returns
-------
response_obj : Response
A new object of this type instantiated from the deserialize JSON object dictionary, or none if the provided
parameter could not be used to instantiated a new object.
"""
try:
return cls(success=json_obj['success'], reason=json_obj['reason'], message=json_obj['message'],
series_uuid=json_obj['data'][cls._KEY_SERIES_UUID], data=json_obj['data'])
except Exception as e:
return None

def __init__(self, series_uuid: Union[str, UUID], *args, **kwargs):
if 'data' not in kwargs:
kwargs['data'] = dict()
kwargs['data'][self._KEY_SERIES_UUID] = str(series_uuid)
super(DataTransmitResponse, self).__init__(*args, **kwargs)
response_to_type: ClassVar[Type[AbstractInitRequest]] = DataTransmitMessage

data: DataTransmitResponseBody

# `series_uuid` required in prior version of code
def __init__(self, series_uuid: Union[str, UUID] = None, **kwargs):
# assume no need for backwards compatibility
if series_uuid is None:
super().__init__(**kwargs)
return

if "data" not in kwargs:
kwargs["data"] = dict()

kwargs["data"]["series_uuid"] = series_uuid
super().__init__(**kwargs)

@property
def series_uuid(self) -> UUID:
return UUID(self.data[self._KEY_SERIES_UUID])
return self.data.series_uuid

Loading