Repository navigation
Expand file tree
/
Copy pathhdctl
More file actions
executable file
·2695 lines (2266 loc) · 96.8 KB
/
Copy pathhdctl
File metadata and controls
executable file
·2695 lines (2266 loc) · 96.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
###############################################################################
# #
# hdctl #
# #
# Manage maintenance / devops tasks around hetida designer installations #
# #
# #
###############################################################################
#
# LICENSE
# Copyright © 2024 fuseki GmbH
#
# MIT License
# see https://github.com/hetida/hetida-designer/blob/release/LICENSE
#
# INTRODUCTION
# hdctl is a bash command line tool for managing typical maintenance /
# devops tasks around hetida designer installations.
#
# hdctl can export/import components and workflows from/to the backend api
# while taking care of authentication. A typical use case is syncing
# components / workflows from dev instances to test or prod instances.
#
# Another use case is running maintenance operations, e.g. as described in
# https://github.com/hetida/hetida-designer/blob/release/docs/cleanup.md
# from the command line only, i.e. without needing docker.
#
# hdctl is based on bash/coreutils + curl with the additional requirement
# of awk and jq for some tasks that involve json wrangling. This enables
# managing hetida designer instances from locations where no docker or
# python installation is available or installing arbitrary dependencies
# and software is difficult due to administrative / security restrictions.
#
# INSTALLATION
# Just copy this bash script to the environment where you want to run it
# from. There you need
# * modern/recent bash (version >4)
# * GNU coreutils
# * curl (ideally >= 7.87.0)
# * optionally awk and jq (https://stedolan.github.io/jq/) for some
# subcommands that involve json unpacking
#
# Notes:
# * hdctl should run under Git Bash on Windows. Recent versions of Git
# for Windows include curl >= 7.87.0 and gawk. jq must be installed
# separately. If you experience problems please open an issue.
# * Using nix, you can start an environment with all dependencies by
# running
# nix-shell \
# -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-unstable.tar.gz \
# -p bashInteractive jq gawk coreutils curl
# At least with the following fixed nixpkgs commit it should
# definitely work:
# nix-shell \
# -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/28319deb5ab05458d9cd5c7d99e1a24ec2e8fc4b.tar.gz \
# -p bashInteractive jq gawk coreutils curl
#
#
# USAGE
# Run
# hdctl usage
# to see detailed usage instructions and descriptions of all subcommands
# and arguments.
set -e
######################## Initialize mutable Global variables ##################
ACCESS_TOKEN=""
EXPIRATION_EPOCH=0
_JQ_AVAILABLE=true
###############################################################################
# #
# Logging functions #
# #
###############################################################################
_info() {
if [[ $SILENT = false ]]; then
echo "${@}" >&2
fi
}
_debug() {
if [[ $VERBOSITY == "debug" ]]; then
echo "${@}" >&2
fi
}
_log_error() {
echo "${@}" >&2
}
###############################################################################
# #
# System environment detection helper functions #
# #
###############################################################################
_detect_jq() {
if ! command -v jq 1>/dev/null; then
_info "WARNING: jq not available. Some parameters/options cannot be used."
_JQ_AVAILABLE=false
else
_info "Successfully detected jq in PATH."
fi
}
JQ_ENSURED=false
_ensure_jq() {
if ! command -v jq 1>/dev/null; then
_log_error "Called command needs jq command line tool, which was not found. Aborting."
exit 127
fi
JQ_ENSURED=true
}
_ensure_jq_once() {
if ! "$JQ_ENSURED"; then
_ensure_jq
fi
}
# outputs a certain value from env file
value_from_env_file() {
local var_name="$1"
local env_file_path="$2"
local env_file_entry
env_file_entry="$(grep -m 1 '^'"$var_name"= "$env_file_path")"
local str_after_equal="${env_file_entry#*=}" # may contain " or so
local actual_str
eval actual_str="$str_after_equal" # to get rid of enclosing ""
printf '%s' "$actual_str"
}
# shellcheck disable=SC2046
PYTEST_INI_CONTENT=$(
cat <<'END_HEREDOC'
[pytest]
python_files = *.py
addopts = --doctest-modules
END_HEREDOC
)
# shellcheck disable=SC2046
HDUTILS_PY_CONTENT=$(
cat <<'END_HEREDOC'
import datetime
import io
import json
import logging
import re
from collections import defaultdict
from enum import StrEnum
from types import NoneType, UnionType
from typing import Annotated, Any, Literal, TypedDict
from uuid import UUID
import msgspec
import numpy as np
import pandas as pd
import pytz
from hdhelpers.helpers import modify_timezone # noqa F401 # noqa F401 # noqa F401
from plotly.graph_objects import Figure
from pydantic import (
BaseModel,
BeforeValidator,
ConfigDict,
Field,
PlainSerializer,
PlainValidator,
ValidationError,
ValidatorFunctionWrapHandler,
WrapValidator,
create_model,
)
logger = logging.getLogger(__name__)
MULTITSFRAME_COLUMN_NAMES = ["timestamp", "metric", "value"]
SINGLETSFRAME_COLUMN_NAMES = ["timestamp", "value"]
class ComponentException(Exception):
"""Exception to re-raise exceptions with error code raised in the component code."""
__is_hetida_designer_exception__ = True
def __init__(
self,
*args: Any,
error_code: int | str = "",
extra_information: dict | None = None,
**kwargs: Any,
) -> None:
if not isinstance(error_code, int | str):
raise ValueError("The ComponentException.error_code must be int or string!")
self.error_code = error_code
self.extra_information = extra_information
super().__init__(*args, **kwargs)
class ComponentInputValidationException(ComponentException):
"""In code input validation failures"""
def __init__(
self,
*args: Any,
invalid_component_inputs: list[str],
error_code: int | str = "",
**kwargs: Any,
) -> None:
super().__init__(
*args,
error_code=error_code,
extra_information={"invalid_component_inputs": invalid_component_inputs},
**kwargs,
)
class InsufficientPlottingData(ComponentException):
"""A plot component has insufficient data to generate a meaningful plot
This exception class should be used when custom plots generated by hetida
designer are integrated in other frontends. This allows the frontend to
handle the case of e.g. no data to show in a sensible way, surpressing an
empty plot and showing an adequate message instead.
"""
class IntentionallyAbortedExecution(ComponentException):
"""Execution of this component or workflow is intentionally aborted
Often execution of a workflow should stop if a certain condition is not
fulfilled. This can of course be done by raising an exception. To communicate
this intention to 3rd party systems and make it clear that this is not an actual error
situation it is recommended to use this exception.
"""
class PlotTargetSettings(BaseModel):
"""Settings that plot components can/should use
Some Plotly settings like locale or the timezone of timestamps must be set
by Python and cannot easily be set by plotly.js in a frontend.
They can be provided to execution endpoints as part of the ExecByIdBase payload,
are made accessible to components using the execution context.
hdutils provides helper functions to access them at runtime.
"""
plot_target_timezone: str | None = Field(
None,
description=(
"The timezone plot components should use for datetime axes etc."
" Usually via"
" s.index=pd.to_datetime(s.index, utc=True).tz_convert(plot_target_timezone)"
),
examples=["Europe/Berlin"],
)
plot_target_locale: str | None = Field(
None,
description=(
"Locale to set for plots, e.g. to write weekdays in the user's language."
" This has to be set in the config of the plotly figure dict and the plotly.js "
"must have the associated plotly local scripts loaded."
),
)
target_darkmode: bool = Field(
False, description="Whether plots should be layouted/configured for darkmode"
)
datetime_tick_format: str | None = Field(
None, description="Tickformat to use for datetime axes", examples=["%H:%M<br>%d.%m.%Y"]
)
datetime_x_axes_range_start: datetime.datetime | None = Field(
None, description="datetime range start which plots should set as x axis range"
)
datetime_x_axes_range_end: datetime.datetime | None = Field(
None, description="datetime range end which plots should set as x axis range"
)
def get_plot_target_settings() -> PlotTargetSettings:
"""Obtain plot settings from runtime execution context.
If hetdesrun is not importable or this context field is not set,
return default values.
"""
try:
from hetdesrun.runtime.context import get_runtime_exec_context
return get_runtime_exec_context().plot_target_settings
except ImportError:
logger.warning("Could not load runtime exec context, import failed! Switch to defaults.")
# return defaults if hetdesrun is not available as import
return PlotTargetSettings()
def plot_output_needed(output_name: str) -> bool:
"""Whether a plot should be created for a PLOTLYJSON output of the current component
No plot is needed if the execution does not run plot operators (run_pure_plot_operators
is false) or if the output is discarded, e.g. because it is wired to the drop adapter.
Components with plot outputs and outputs of other types can use this to skip creating
plots and return {} instead.
If hetdesrun is not importable, plots are needed.
"""
try:
from hetdesrun.models.run import ConfigurationInput
from hetdesrun.runtime.configuration import execution_config
from hetdesrun.runtime.context import output_is_discarded
except ImportError:
return True
return execution_config.get(
ConfigurationInput()
).run_pure_plot_operators and not output_is_discarded(output_name)
class WrappedModelWithCustomObjects(BaseModel):
model: Any = None
custom_objects: dict[str, Any]
class MetaDataWrapped(BaseModel):
"""Allows to wrap pandas object data with metadata"""
hd_wrapped_data_object__: Literal["SERIES", "DATAFRAME"] = Field(
..., alias="__hd_wrapped_data_object__"
)
metadata__: dict[str, Any] = Field(
...,
alias="__metadata__",
description="Json serializable dictionary of metadata. Will be written"
"to the resulting pandas object's attrs attribute.",
)
data__: dict | list = Field(
...,
alias="__data__",
description="The actual data which constitutes the pandas object.",
)
data_parsing_options__: dict = Field(
{},
alias="__data_parsing_options__",
description=(
"Additional options for parsing the provided data."
" For example, setting orient to one of the allowed values for the respective"
" Pandas type allows to use different json representations for the actual data."
),
)
model_config = ConfigDict(
serialize_by_alias=True, validate_by_alias=True, validate_by_name=True
)
def try_parse_wrapped(
data: str | dict | list,
hd_wrapped_data_object: Literal["SERIES", "DATAFRAME"],
) -> MetaDataWrapped:
if isinstance(data, str):
wrapped_data = MetaDataWrapped.model_validate_json(data)
if wrapped_data.hd_wrapped_data_object__ != hd_wrapped_data_object:
msg = (
f"Unexpected hd model type: {wrapped_data.hd_wrapped_data_object__}."
f" Expected {hd_wrapped_data_object}"
)
logger.warning(msg)
raise TypeError(msg)
else:
wrapped_data = MetaDataWrapped.model_validate(data)
return wrapped_data
def parse_wrapped_content(
v: str | dict | list,
wrapped_data_object: Literal["SERIES", "DATAFRAME"],
) -> tuple[str | dict | list, None | dict[str, Any], dict[str, Any]]:
data_content: str | dict | list
try:
wrapped_object = try_parse_wrapped(v, wrapped_data_object)
parsed_metadata = wrapped_object.metadata__
data_content = wrapped_object.data__
parsing_options = wrapped_object.data_parsing_options__
except (ValidationError, TypeError) as e:
logger.debug("Data object is not wrapped: %s", str(e))
data_content = v
parsed_metadata = None
parsing_options = {}
return data_content, parsed_metadata, parsing_options
def wrap_metadata_as_attrs(
data_object: pd.Series | pd.DataFrame, metadata: None | dict[str, Any]
) -> pd.Series | pd.DataFrame: # TODO: make generic: input type = output type
if metadata is not None:
data_object.attrs = metadata
else:
data_object.attrs = {}
return data_object
def parse_pandas_data_content(
data_content: str | dict | list, typ: Literal["series", "frame"], parsing_options: dict
) -> pd.DataFrame | pd.Series:
try:
if isinstance(data_content, str):
parsed_pandas_object = pd.read_json(
io.StringIO(data_content), typ=typ, **parsing_options
)
else:
parsed_pandas_object = pd.read_json(data_content, typ=typ, **parsing_options)
except Exception: # noqa: BLE001
try:
parsed_pandas_object = pd.read_json(
io.StringIO(json.dumps(data_content)), typ=typ, **parsing_options
)
except Exception as read_json_exception: # noqa: BLE001
raise ValueError(
"Could not parse provided input as Pandas "
+ ("Series" if typ == "series" else "DataFrame")
) from read_json_exception
return parsed_pandas_object
class DataType(StrEnum):
"""hetida designer data types
These are the types available for component/workflow inputs/outputs.
"""
Integer = "INT"
Float = "FLOAT"
String = "STRING"
DataFrame = "DATAFRAME"
Series = "SERIES"
MultiTSFrame = "MULTITSFRAME"
SingleTSFrame = "SINGLETSFRAME"
Boolean = "BOOLEAN"
Any = "ANY"
PlotlyJson = "PLOTLYJSON"
def parse_pydantic_series(v: pd.Series | str | dict | list) -> pd.Series:
"""Custom pydantic Data Type for parsing Pandas Series
Parses either a json string according to pandas.read_json
with typ="series" and default arguments otherwise or
a Python dict-like data structure using the constructor
of the pandas.Series class with default arguments.
Also allows a wrapped variant where metadata can be provided.
Examples of valid input:
'{"0":1.0,"1":2.1,"2":3.2}'
{"0":1.0,"1":2.1,"2":3.2}
[1.2, 3.5, 2.9]
'[1.2, 3.5, 2.9]'
"""
if isinstance(v, pd.Series):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing Series: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "SERIES")
return wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "series", parsing_options), metadata
)
def serialize_series(s: pd.Series) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "SERIES",
"__metadata__": s.attrs,
"__data__": json.loads(
# double serialization/deserialization in order to serialize both NaN and NaT
# to null
s.to_json(
date_format="iso",
orient="split",
# orient="split" serialization is the only way pandas keeps duplicate index
# (with possibly different values) entries for Series objects!
)
),
"__data_parsing_options__": {"orient": "split"},
}
PydanticPandasSeries = Annotated[
pd.Series,
PlainSerializer(serialize_series),
BeforeValidator(parse_pydantic_series),
]
def parse_pydantic_pandas_data_frame(v: pd.DataFrame | str | dict | list) -> pd.DataFrame:
"""Custom pydantic Data Type for parsing Pandas DataFrames
Parses either a json string according to pandas.read_json
with typ="frame" and default arguments otherwise or
a Python dict-like data structure using the constructor
of the pandas.DataFrame class with default arguments.
Additionally a MetaDataWrapped variant of these can be parsed
and then is equipped with the provided metadata in the `attrs`
attribute (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.attrs.html
"""
if isinstance(v, pd.DataFrame):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing DataFrame: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "DATAFRAME")
return wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "frame", parsing_options), metadata
)
def serialize_dataframe(df: pd.DataFrame) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": df.attrs,
"__data__": json.loads(
df.to_json(date_format="iso") # in order to serialize both NaN and NaT to null
),
}
PydanticPandasDataFrame = Annotated[
pd.DataFrame,
PlainSerializer(serialize_dataframe),
BeforeValidator(parse_pydantic_pandas_data_frame),
]
def validate_multits_properties( # noqa:PLR0912
df: pd.DataFrame,
) -> pd.DataFrame:
if len(df.columns) == 0:
attrs = df.attrs
df = pd.DataFrame(columns=MULTITSFRAME_COLUMN_NAMES)
df.attrs = attrs
if len(df.columns) < 3:
raise ValueError(
"MultiTSFrame requires at least 3 columns: metric, timestamp"
f" and at least one additional columns. Only found {str(df.columns)}"
)
if not ({"metric", "timestamp"}.issubset(set(df.columns))):
column_names_string = ", ".join(df.columns)
raise ValueError(
f"The column names {column_names_string} don't contain required columns"
' "timestamp" and "metric" for a MultiTSFrame.'
)
if df["metric"].isna().any():
raise ValueError("No null values are allowed for the column 'metric' of a MulitTSFrame.")
df["metric"] = df["metric"].astype("string")
if df["timestamp"].isna().any():
raise ValueError("No null values are allowed for the column 'timestamp' of a MulitTSFrame.")
if len(df.index) == 0:
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
if not isinstance(df["timestamp"].dtype, pd.DatetimeTZDtype):
raise ValueError(
"Column 'timestamp' of MultiTSFrame does not have DatetimeTZDtype dtype. "
f"Got {str(df['timestamp'].dtype)} index dtype instead."
)
if df["timestamp"].dt.tz not in (pytz.UTC, datetime.timezone.utc):
raise ValueError(
"Column 'timestamp' of MultiTSFrame does not have UTC timezone. "
f"Got {str(df['timestamp'].dt.tz)} timezone instead."
)
return df.sort_values("timestamp")
def parse_pydantic_multi_timeseries_pandas_data_frame(
v: pd.DataFrame | str | dict | list,
) -> pd.DataFrame:
if isinstance(v, pd.DataFrame):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing MultiTsFrame: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "DATAFRAME")
new_df = wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "frame", parsing_options), metadata
)
return validate_multits_properties(new_df)
def serialize_multitsframe(df: pd.DataFrame) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": df.attrs,
"__data__": json.loads(
df.to_json(date_format="iso")
), # in order to serialize both NaN and NaT to null
}
PydanticMultiTimeseriesPandasDataFrame = Annotated[
pd.DataFrame,
PlainSerializer(serialize_multitsframe),
BeforeValidator(parse_pydantic_multi_timeseries_pandas_data_frame),
]
def validate_singlets_properties(
df: pd.DataFrame,
) -> pd.DataFrame:
"""Validate the conventions of a SingleTSFrame
A SingleTSFrame holds a single — possibly multi-dimensional — timeseries. It has the same
tabular representation as a MultiTSFrame, except that it has no "metric" column, since
the metric is unique for the whole frame. Every column besides "timestamp" is a value
dimension. This explicitly includes a column named "metric", which is treated like any
other value column here.
"""
if len(df.columns) == 0:
attrs = df.attrs
df = pd.DataFrame(columns=SINGLETSFRAME_COLUMN_NAMES)
df.attrs = attrs
if len(df.columns) < 2:
raise ValueError(
"SingleTSFrame requires at least 2 columns: timestamp"
f" and at least one value column. Only found {str(df.columns)}"
)
if "timestamp" not in df.columns:
column_names_string = ", ".join(df.columns)
raise ValueError(
f"The column names {column_names_string} don't contain the required column"
' "timestamp" for a SingleTSFrame.'
)
if df["timestamp"].isna().any():
raise ValueError(
"No null values are allowed for the column 'timestamp' of a SingleTSFrame."
)
if len(df.index) == 0:
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
if not isinstance(df["timestamp"].dtype, pd.DatetimeTZDtype):
raise ValueError(
"Column 'timestamp' of SingleTSFrame does not have DatetimeTZDtype dtype. "
f"Got {str(df['timestamp'].dtype)} index dtype instead."
)
if df["timestamp"].dt.tz not in (pytz.UTC, datetime.timezone.utc):
raise ValueError(
"Column 'timestamp' of SingleTSFrame does not have UTC timezone. "
f"Got {str(df['timestamp'].dt.tz)} timezone instead."
)
return df.sort_values("timestamp")
def parse_pydantic_single_timeseries_pandas_data_frame(
v: pd.DataFrame | str | dict | list,
) -> pd.DataFrame:
if isinstance(v, pd.DataFrame):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing SingleTsFrame: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "DATAFRAME")
new_df = wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "frame", parsing_options), metadata
)
return validate_singlets_properties(new_df)
def serialize_singletsframe(df: pd.DataFrame) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": df.attrs,
"__data__": json.loads(
df.to_json(date_format="iso")
), # in order to serialize both NaN and NaT to null
}
PydanticSingleTimeseriesPandasDataFrame = Annotated[
pd.DataFrame,
PlainSerializer(serialize_singletsframe),
BeforeValidator(parse_pydantic_single_timeseries_pandas_data_frame),
]
# "Raw" serializer variants: Previously we parsed pandas output JSON back with json.loads to
# ensure having a json serializable object at the service boundary later and avoiding having
# 5xx errors. At that boundary it was re-encoded leading to multiple serialization loops.
# Now msgspec.Raw is used to both ensure json serializability and keep the generated bytes
# avoiding further such loops
#
# A dict containing ``msgspec.Raw`` values MUST be encoded with msgspec directly; it cannot be
# routed through pydantic's ``model_dump(mode="json")`` (which does not understand ``Raw``).
def serialize_series_raw(s: pd.Series) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "SERIES",
# __metdata__ uncoerced on purpose; the msgspec enc_hook coerces exotic values
# (see hetdesrun.service.serialization_helpers):
"__metadata__": s.attrs,
"__data__": msgspec.Raw(
s.to_json(
date_format="iso",
orient="split",
# orient="split" is the only way pandas keeps duplicate index entries for Series
).encode()
),
"__data_parsing_options__": {"orient": "split"},
}
def serialize_dataframe_raw(df: pd.DataFrame) -> dict[str, Any]:
return {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": df.attrs,
"__data__": msgspec.Raw(df.to_json(date_format="iso").encode()),
}
# MultiTSFrames and SingleTSFrames use the same wrapper as ordinary DataFrames.
serialize_multitsframe_raw = serialize_dataframe_raw
serialize_singletsframe_raw = serialize_dataframe_raw
def parse_any(v: Any) -> Any:
"""Tries to parse Any objects somehow intelligently
Reason is that an object may be provided by the backend either as a proper json-object directly
in some cases (dict-like objects) or as json-encoded string (happens for example for lists).
Sometimes, if the frontend is involved, json strings get even double-string-encoded! This is a
known bug of frontend-backend-runtime interaction.
Sometimes adapter implementations deliver ANY-data directly as json objects and othertimes
string-encoded.
As a workaround for all these cases this class tries to json-parse a string if it receives one
and only if that does not work it yields the actual string value. If it works and the result is
itself a string again it tries to json-decode a second time and returns the result if that
works. Otherwise it returns the result string of the first parsing.
This workaround is justified by the argument that the user should really use a STRING input if
a string is expected and not an ANY input. Likewise, adapters should offer string data as STRING
data sources and not as ANY data sources.
"""
if isinstance(v, str):
# try to parse string as json
try:
parsed_json_object = json.loads(v)
except json.decoder.JSONDecodeError:
logger.info(
"Could not JSON-parse string %s in Any input."
" Therefore treating it as actual string value",
v[:30] + "..." if len(v) > 10 else v,
)
return v
if isinstance(
parsed_json_object, str
): # sometimes it even gets double-encoded for some reasons
try:
parsed_json_object = json.loads(parsed_json_object)
except json.decoder.JSONDecodeError:
logger.info(
"Could not JSON-parse string %s in Any input. "
" Therefore treating it as actual string value",
parsed_json_object[:30] + "..." if len(v) > 10 else v,
)
return parsed_json_object
return parsed_json_object
return v
ParsedAny = Annotated[
Any,
BeforeValidator(parse_any),
]
def parse_plotly_json_dict(v: dict) -> dict:
if isinstance(v, dict):
# TODO: check structure more thoroughly
return v
raise ValueError("Plotly JSON is not a dict object.")
ParsedPlotly = Annotated[dict, PlainValidator(parse_plotly_json_dict)]
def wrap_basic_type_parsing(
value: Any, handler: ValidatorFunctionWrapHandler, basic_type: type
) -> Any:
pydantic_parsed_basic_type = handler(value)
if isinstance(value, basic_type) and value == pydantic_parsed_basic_type:
return value # original value to preserve idempotency.
# Avoids pydantic attribute copying as well.
return pydantic_parsed_basic_type
ParsedFloat = Annotated[
float,
WrapValidator(lambda value, handler: wrap_basic_type_parsing(value, handler, basic_type=float)),
]
ParsedInt = Annotated[
int,
WrapValidator(lambda value, handler: wrap_basic_type_parsing(value, handler, basic_type=int)),
]
ParsedBool = Annotated[
bool,
WrapValidator(lambda value, handler: wrap_basic_type_parsing(value, handler, basic_type=bool)),
]
ParsedStr = Annotated[
str,
WrapValidator(lambda value, handler: wrap_basic_type_parsing(value, handler, basic_type=str)),
]
data_type_map: dict[DataType | None, type] = {
DataType.Integer: ParsedInt,
DataType.Float: ParsedFloat,
DataType.String: ParsedStr,
DataType.Series: PydanticPandasSeries,
DataType.MultiTSFrame: PydanticMultiTimeseriesPandasDataFrame,
DataType.SingleTSFrame: PydanticSingleTimeseriesPandasDataFrame,
DataType.DataFrame: PydanticPandasDataFrame,
DataType.Boolean: ParsedBool,
# Any as Type is the correct way to tell pydantic how to parse an arbitrary object:
DataType.Any: ParsedAny,
DataType.PlotlyJson: ParsedPlotly,
None: NoneType,
}
optional_data_type_map: dict[DataType | None, Any] = {
DataType.Integer: ParsedInt | None,
DataType.Float: ParsedFloat | None,
DataType.String: ParsedStr | None,
DataType.Series: PydanticPandasSeries | None,
DataType.MultiTSFrame: PydanticMultiTimeseriesPandasDataFrame | None,
DataType.SingleTSFrame: PydanticSingleTimeseriesPandasDataFrame | None,
DataType.DataFrame: PydanticPandasDataFrame | None,
DataType.Boolean: ParsedBool | None,
# Any as Type is the correct way to tell pydantic how to parse an arbitrary object:
DataType.Any: ParsedAny | None,
DataType.PlotlyJson: ParsedPlotly | None,
None: NoneType | None,
}
def serialize_plotly_fig(v: dict[str, Any] | Figure) -> Any:
if isinstance(v, dict):
return v
# possibly quite inefficient (multiple serialisation / deserialization) but
# guarantees that the PlotlyJSONEncoder is used and so the resulting Json
# should be definitely compatible with the plotly javascript library:
# Whats the difference using json.loads(json.dumps(fig_dict_obj, cls=PlotlyJSONEncoder))
# or employing fig.to_plotly_json()
return json.loads(v.to_json(validate=False))
serializer_funcs_by_type = {
pd.Series: serialize_series,
pd.DataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso") # in order to serialize both NaN and NaT to null
),
},
PydanticPandasSeries: serialize_series,
PydanticPandasDataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso") # in order to serialize both NaN and NaT to null
),
},
PydanticMultiTimeseriesPandasDataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso")
), # in order to serialize both NaN and NaT to null
},
PydanticSingleTimeseriesPandasDataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso")
), # in order to serialize both NaN and NaT to null
},
np.ndarray: lambda v: v.tolist(),
datetime.datetime: lambda v: v.isoformat(),
UUID: lambda v: str(v), # alternatively: v.hex
Figure: serialize_plotly_fig, # lambda v: json.loads(json.dumps(v.to_plotly_json(), cls=PlotlyJSONEncoder)),
NoneType: lambda x: x,
None: lambda x: x,
}
# Only the pandas payload types get the ``msgspec.Raw`` splicing treatment (they are the large ones
# and the only ones that paid the json.loads round-trip). Every other output type is left uncoerced
# and handed straight to the encoder, whose ``enc_hook`` (pydantic's ``to_jsonable_python``) coerces
# any exotic values in a single encode pass - so numpy scalars, plotly dicts, datetimes etc.
# serialize (and fail) exactly as pydantic's ``model_dump(mode="json")`` did.
raw_pandas_serializer_funcs_by_type = {
PydanticPandasSeries: serialize_series_raw,
PydanticPandasDataFrame: serialize_dataframe_raw,
PydanticMultiTimeseriesPandasDataFrame: serialize_multitsframe_raw,
PydanticSingleTimeseriesPandasDataFrame: serialize_singletsframe_raw,
}
def serialize_output_results_raw(
output_results_by_output_name: dict[str, Any],
output_types_by_output_name: dict[str, DataType | None],
) -> dict[str, Any]:
"""Raw-splicing counterpart of ``WorkflowExecutionInfo.serialize_output_result_dict``.
Dispatches by declared output data type: pandas payloads become the ``msgspec.Raw`` wrapper
(skipping the ``json.loads(df.to_json())`` round-trip), every other value is passed through
**uncoerced**. This is deliberate: a plotly (or ANY) output is arbitrary user-component code
output, so it must still be guarded/coerced - but that happens exactly once, inside the single
``enc_hook`` encode pass, instead of a separate pre-walk plus the encode.
The returned dict therefore contains ``Raw`` (and possibly uncoerced) values and must be encoded
with msgspec using ``enc_hook=to_jsonable_python`` - not dumped by pydantic. See
``hetdesrun.service.serialization_helpers.encode_workflow_execution_result``.
"""
result = {}
for outp_name, obj in output_results_by_output_name.items():
raw_serializer = raw_pandas_serializer_funcs_by_type.get(
data_type_map[output_types_by_output_name[outp_name]]
)
if raw_serializer is not None:
result[outp_name] = raw_serializer(obj)
else:
result[outp_name] = obj
return result