sapiopycommons 2024.8.29a317__py3-none-any.whl → 2024.8.30a319__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of sapiopycommons might be problematic. Click here for more details.

Files changed (33) hide show
  1. sapiopycommons/callbacks/callback_util.py +133 -37
  2. sapiopycommons/customreport/__init__.py +0 -0
  3. sapiopycommons/customreport/column_builder.py +60 -0
  4. sapiopycommons/customreport/custom_report_builder.py +125 -0
  5. sapiopycommons/customreport/term_builder.py +299 -0
  6. sapiopycommons/datatype/attachment_util.py +11 -10
  7. sapiopycommons/eln/experiment_handler.py +209 -48
  8. sapiopycommons/eln/experiment_report_util.py +33 -129
  9. sapiopycommons/files/complex_data_loader.py +5 -4
  10. sapiopycommons/files/file_bridge.py +15 -14
  11. sapiopycommons/files/file_bridge_handler.py +27 -5
  12. sapiopycommons/files/file_data_handler.py +2 -5
  13. sapiopycommons/files/file_util.py +38 -5
  14. sapiopycommons/files/file_validator.py +26 -11
  15. sapiopycommons/files/file_writer.py +44 -15
  16. sapiopycommons/general/aliases.py +147 -3
  17. sapiopycommons/general/audit_log.py +196 -0
  18. sapiopycommons/general/custom_report_util.py +34 -32
  19. sapiopycommons/general/popup_util.py +17 -0
  20. sapiopycommons/general/sapio_links.py +50 -0
  21. sapiopycommons/general/time_util.py +40 -0
  22. sapiopycommons/multimodal/multimodal_data.py +0 -1
  23. sapiopycommons/processtracking/endpoints.py +22 -22
  24. sapiopycommons/recordmodel/record_handler.py +228 -77
  25. sapiopycommons/rules/eln_rule_handler.py +34 -25
  26. sapiopycommons/rules/on_save_rule_handler.py +34 -31
  27. sapiopycommons/webhook/webhook_handlers.py +90 -26
  28. sapiopycommons/webhook/webservice_handlers.py +67 -0
  29. {sapiopycommons-2024.8.29a317.dist-info → sapiopycommons-2024.8.30a319.dist-info}/METADATA +1 -1
  30. sapiopycommons-2024.8.30a319.dist-info/RECORD +50 -0
  31. sapiopycommons-2024.8.29a317.dist-info/RECORD +0 -43
  32. {sapiopycommons-2024.8.29a317.dist-info → sapiopycommons-2024.8.30a319.dist-info}/WHEEL +0 -0
  33. {sapiopycommons-2024.8.29a317.dist-info → sapiopycommons-2024.8.30a319.dist-info}/licenses/LICENSE +0 -0
@@ -1,10 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from weakref import WeakValueDictionary
4
+
5
+ from sapiopylib.rest.User import SapioUser
1
6
  from sapiopylib.rest.pojo.DataRecord import DataRecord
2
- from sapiopylib.rest.pojo.webhook.VeloxRules import VeloxRuleType, VeloxRuleParser
7
+ from sapiopylib.rest.pojo.eln.SapioELNEnums import ElnBaseDataType
3
8
  from sapiopylib.rest.pojo.webhook.WebhookContext import SapioWebhookContext
4
9
  from sapiopylib.rest.utils.recordmodel.RecordModelManager import RecordModelManager, RecordModelInstanceManager
5
10
  from sapiopylib.rest.utils.recordmodel.RecordModelWrapper import WrappedType
6
11
 
7
- from sapiopycommons.general.aliases import FieldMap
12
+ from sapiopycommons.general.aliases import FieldMap, AliasUtil, DataTypeIdentifier
8
13
  from sapiopycommons.general.exceptions import SapioException
9
14
 
10
15
 
@@ -12,7 +17,6 @@ from sapiopycommons.general.exceptions import SapioException
12
17
  class ElnRuleHandler:
13
18
  """
14
19
  A class which helps with the parsing and navigation of the ELN rule result map of a webhook context.
15
- TODO: Add functionality around the VeloxRuleType of the rule results.
16
20
  """
17
21
  __context: SapioWebhookContext
18
22
  """The context that this handler is working from."""
@@ -34,7 +38,25 @@ class ElnRuleHandler:
34
38
  """A mapping of entry name to the lists of field maps for that entry, each grouping of field maps being mapped by
35
39
  its data type."""
36
40
 
41
+ __instances: WeakValueDictionary[SapioUser, ElnRuleHandler] = WeakValueDictionary()
42
+ __initialized: bool
43
+
44
+ def __new__(cls, context: SapioWebhookContext):
45
+ if context.velox_eln_rule_result_map is None:
46
+ raise SapioException("No Velox ELN rule result map in context for ElnRuleHandler to parse.")
47
+ user = context if isinstance(context, SapioUser) else context.user
48
+ obj = cls.__instances.get(user)
49
+ if not obj:
50
+ obj = object.__new__(cls)
51
+ obj.__initialized = False
52
+ cls.__instances[user] = obj
53
+ return obj
54
+
37
55
  def __init__(self, context: SapioWebhookContext):
56
+ if self.__initialized:
57
+ return
58
+ self.__initialized = True
59
+
38
60
  if context.velox_eln_rule_result_map is None:
39
61
  raise SapioException("No Velox ELN rule result map in context for ElnRuleHandler to parse.")
40
62
  self.__context = context
@@ -64,13 +86,8 @@ class ElnRuleHandler:
64
86
  # Get the data type of this record. If this is an ELN type, ignore the digits.
65
87
  data_type: str = record.data_type_name
66
88
  # PR-46331: Ensure that all ELN types are converted to their base data type name.
67
- # TODO: Use ElnBaseDataType.is_eln_type when it is no longer bugged in sapiopylib.
68
- if data_type.startswith("ELNExperiment_"):
69
- data_type = "ELNExperiment"
70
- elif data_type.startswith("ELNExperimentDetail_"):
71
- data_type = "ELNExperimentDetail"
72
- elif data_type.startswith("ELNSampleDetail_"):
73
- data_type = "ELNSampleDetail"
89
+ if ElnBaseDataType.is_eln_type(data_type):
90
+ data_type = ElnBaseDataType.get_base_type(data_type).data_type_name
74
91
  # Update the list of records of this type that exist so far globally.
75
92
  self.__records.setdefault(data_type, set()).add(record)
76
93
  # Do the same for the list of records of this type for this specific entry.
@@ -85,19 +102,9 @@ class ElnRuleHandler:
85
102
  entry_dict: dict[str, dict[int, FieldMap]] = {}
86
103
  for record_result in entry_results:
87
104
  for result in record_result.velox_type_rule_field_map_result_list:
88
- # TODO: sapiopylib currently has a bug where this velox_type_pojo variable is stored as a dict instead
89
- # of as the intended VeloxRuleType object. Parse that dict as a VeloxRuleType before use.
90
- velox_type: VeloxRuleType | dict = result.velox_type_pojo
91
- if isinstance(velox_type, dict):
92
- velox_type: VeloxRuleType = VeloxRuleParser.parse_velox_rule_type(velox_type)
93
- data_type: str = velox_type.data_type_name
94
- # TODO: Use ElnBaseDataType.is_eln_type when it is no longer bugged in sapiopylib.
95
- if data_type.startswith("ELNExperiment_"):
96
- data_type = "ELNExperiment"
97
- elif data_type.startswith("ELNExperimentDetail_"):
98
- data_type = "ELNExperimentDetail"
99
- elif data_type.startswith("ELNSampleDetail_"):
100
- data_type = "ELNSampleDetail"
105
+ data_type: str = result.velox_type_pojo.data_type_name
106
+ if ElnBaseDataType.is_eln_type(data_type):
107
+ data_type = ElnBaseDataType.get_base_type(data_type).data_type_name
101
108
  for field_map in result.field_map_list:
102
109
  rec_id: int = field_map.get("RecordId")
103
110
  self.__field_maps.setdefault(data_type, {}).update({rec_id: field_map})
@@ -118,7 +125,7 @@ class ElnRuleHandler:
118
125
  """
119
126
  return list(self.__entry_to_field_maps.keys())
120
127
 
121
- def get_records(self, data_type: str, entry: str | None = None) -> list[DataRecord]:
128
+ def get_records(self, data_type: DataTypeIdentifier, entry: str | None = None) -> list[DataRecord]:
122
129
  """
123
130
  Get records from the cached context with the given data type. Capable of being filtered to searching within
124
131
  the context of an entry name. If the given data type or entry does not exist in the context,
@@ -129,11 +136,12 @@ class ElnRuleHandler:
129
136
  type from every entry. If an entry is provided, but it does not exist in the context, returns an empty list.
130
137
  :return: The records from the context that match the input parameters.
131
138
  """
139
+ data_type: str = AliasUtil.to_data_type_name(data_type)
132
140
  records: dict[str, set[DataRecord]] = self.__entry_to_records.get(entry, {}) if entry else self.__records
133
141
  return list(records.get(data_type, []))
134
142
 
135
143
  # FR-46701: Add functions to the rule handlers for accessing the field maps of inaccessible records in the context.
136
- def get_field_maps(self, data_type: str, entry: str | None = None) -> list[FieldMap]:
144
+ def get_field_maps(self, data_type: DataTypeIdentifier, entry: str | None = None) -> list[FieldMap]:
137
145
  """
138
146
  Get field maps from the cached context with the given data type. Capable of being filtered to searching within
139
147
  the context of an entry name. If the given data type or entry does not exist in the context,
@@ -149,6 +157,7 @@ class ElnRuleHandler:
149
157
  list.
150
158
  :return: The field maps from the context that match the input parameters.
151
159
  """
160
+ data_type: str = AliasUtil.to_data_type_name(data_type)
152
161
  field_maps: dict[str, dict[int, FieldMap]] = self.__entry_to_field_maps.get(entry, {}) if entry else self.__field_maps
153
162
  return list(field_maps.get(data_type, {}).values())
154
163
 
@@ -1,10 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from weakref import WeakValueDictionary
4
+
5
+ from sapiopylib.rest.User import SapioUser
1
6
  from sapiopylib.rest.pojo.DataRecord import DataRecord
2
- from sapiopylib.rest.pojo.webhook.VeloxRules import VeloxRuleType, VeloxRuleParser
7
+ from sapiopylib.rest.pojo.eln.SapioELNEnums import ElnBaseDataType
3
8
  from sapiopylib.rest.pojo.webhook.WebhookContext import SapioWebhookContext
4
9
  from sapiopylib.rest.utils.recordmodel.RecordModelManager import RecordModelManager, RecordModelInstanceManager
5
10
  from sapiopylib.rest.utils.recordmodel.RecordModelWrapper import WrappedType
6
11
 
7
- from sapiopycommons.general.aliases import FieldMap
12
+ from sapiopycommons.general.aliases import FieldMap, DataTypeIdentifier, AliasUtil
8
13
  from sapiopycommons.general.exceptions import SapioException
9
14
 
10
15
 
@@ -12,7 +17,6 @@ from sapiopycommons.general.exceptions import SapioException
12
17
  class OnSaveRuleHandler:
13
18
  """
14
19
  A class which helps with the parsing and navigation of the on save rule result map of a webhook context.
15
- TODO: Add functionality around the VeloxRuleType of the rule results.
16
20
  """
17
21
  __context: SapioWebhookContext
18
22
  """The context that this handler is working from."""
@@ -34,7 +38,25 @@ class OnSaveRuleHandler:
34
38
  """A mapping of record IDs of records in the context.data_record_list to the field maps related to that
35
39
  record, each grouping of field maps being mapped by its data type."""
36
40
 
41
+ __instances: WeakValueDictionary[SapioUser, OnSaveRuleHandler] = WeakValueDictionary()
42
+ __initialized: bool
43
+
44
+ def __new__(cls, context: SapioWebhookContext):
45
+ if context.velox_on_save_result_map is None:
46
+ raise SapioException("No Velox on save rule result map in context for OnSaveRuleHandler to parse.")
47
+ user = context if isinstance(context, SapioUser) else context.user
48
+ obj = cls.__instances.get(user)
49
+ if not obj:
50
+ obj = object.__new__(cls)
51
+ obj.__initialized = False
52
+ cls.__instances[user] = obj
53
+ return obj
54
+
37
55
  def __init__(self, context: SapioWebhookContext):
56
+ if self.__initialized:
57
+ return
58
+ self.__initialized = True
59
+
38
60
  if context.velox_on_save_result_map is None:
39
61
  raise SapioException("No Velox on save rule result map in context for OnSaveRuleHandler to parse.")
40
62
  self.__context = context
@@ -51,9 +73,6 @@ class OnSaveRuleHandler:
51
73
  self.__base_id_to_records = {}
52
74
  # Each record ID in the context has a list of results for that record.
53
75
  for record_id, rule_results in self.__context.velox_on_save_result_map.items():
54
- # TODO: Record IDs are currently being stored in the map as strings instead of ints. This can be removed
55
- # once sapiopylib is fixed.
56
- record_id = int(record_id)
57
76
  # Keep track of the records for this specific record ID.
58
77
  id_dict: dict[str, set[DataRecord]] = {}
59
78
  # The list of results for a record consist of a list of data records and a VeloxType that specifies
@@ -64,13 +83,8 @@ class OnSaveRuleHandler:
64
83
  # Get the data type of this record. If this is an ELN type, ignore the digits.
65
84
  data_type: str = record.data_type_name
66
85
  # PR-46331: Ensure that all ELN types are converted to their base data type name.
67
- # TODO: Use ElnBaseDataType.is_eln_type when it is no longer bugged in sapiopylib.
68
- if data_type.startswith("ELNExperiment_"):
69
- data_type = "ELNExperiment"
70
- elif data_type.startswith("ELNExperimentDetail_"):
71
- data_type = "ELNExperimentDetail"
72
- elif data_type.startswith("ELNSampleDetail_"):
73
- data_type = "ELNSampleDetail"
86
+ if ElnBaseDataType.is_eln_type(data_type):
87
+ data_type = ElnBaseDataType.get_base_type(data_type).data_type_name
74
88
  # Update the list of records of this type that exist so far globally.
75
89
  self.__records.setdefault(data_type, set()).add(record)
76
90
  # Do the same for the list of records of this type that relate to this record ID.
@@ -82,24 +96,11 @@ class OnSaveRuleHandler:
82
96
  self.__base_id_to_field_maps = {}
83
97
  # Repeat the same thing for the field map results.
84
98
  for record_id, rule_results in self.__context.velox_on_save_field_map_result_map.items():
85
- # TODO: Record IDs are currently being stored in the map as strings instead of ints. This can be removed
86
- # once sapiopylib is fixed.
87
- record_id = int(record_id)
88
99
  id_dict: dict[str, dict[int, FieldMap]] = {}
89
100
  for record_result in rule_results:
90
- # TODO: sapiopylib currently has a bug where this velox_type_pojo variable is stored as a dict instead
91
- # of as the intended VeloxRuleType object. Parse that dict as a VeloxRuleType before use.
92
- velox_type: VeloxRuleType | dict = record_result.velox_type_pojo
93
- if isinstance(velox_type, dict):
94
- velox_type: VeloxRuleType = VeloxRuleParser.parse_velox_rule_type(velox_type)
95
- data_type: str = velox_type.data_type_name
96
- # TODO: Use ElnBaseDataType.is_eln_type when it is no longer bugged in sapiopylib.
97
- if data_type.startswith("ELNExperiment_"):
98
- data_type = "ELNExperiment"
99
- elif data_type.startswith("ELNExperimentDetail_"):
100
- data_type = "ELNExperimentDetail"
101
- elif data_type.startswith("ELNSampleDetail_"):
102
- data_type = "ELNSampleDetail"
101
+ data_type: str = record_result.velox_type_pojo.data_type_name
102
+ if ElnBaseDataType.is_eln_type(data_type):
103
+ data_type = ElnBaseDataType.get_base_type(data_type).data_type_name
103
104
  for field_map in record_result.field_map_list:
104
105
  rec_id: int = field_map.get("RecordId")
105
106
  self.__field_maps.setdefault(data_type, {}).update({rec_id: field_map})
@@ -120,7 +121,7 @@ class OnSaveRuleHandler:
120
121
  """
121
122
  return list(self.__base_id_to_field_maps.keys())
122
123
 
123
- def get_records(self, data_type: str, record_id: int | None = None) -> list[DataRecord]:
124
+ def get_records(self, data_type: DataTypeIdentifier, record_id: int | None = None) -> list[DataRecord]:
124
125
  """
125
126
  Get records from the cached context with the given data type. Capable of being filtered to searching within
126
127
  the context of a record ID. If the given data type or record ID does not exist in the context,
@@ -131,11 +132,12 @@ class OnSaveRuleHandler:
131
132
  data type from every ID. If an ID is provided, but it does not exist in the context, returns an empty list.
132
133
  :return: The records from the context that match the input parameters.
133
134
  """
135
+ data_type: str = AliasUtil.to_data_type_name(data_type)
134
136
  records: dict[str, set[DataRecord]] = self.__base_id_to_records.get(record_id, {}) if record_id else self.__records
135
137
  return list(records.get(data_type, []))
136
138
 
137
139
  # FR-46701: Add functions to the rule handlers for accessing the field maps of inaccessible records in the context.
138
- def get_field_maps(self, data_type: str, record_id: int | None = None) -> list[FieldMap]:
140
+ def get_field_maps(self, data_type: DataTypeIdentifier, record_id: int | None = None) -> list[FieldMap]:
139
141
  """
140
142
  Get field maps from the cached context with the given data type. Capable of being filtered to searching within
141
143
  the context of a record ID. If the given data type or record ID does not exist in the context,
@@ -151,6 +153,7 @@ class OnSaveRuleHandler:
151
153
  list.
152
154
  :return: The field maps from the context that match the input parameters.
153
155
  """
156
+ data_type: str = AliasUtil.to_data_type_name(data_type)
154
157
  field_maps: dict[str, dict[int, FieldMap]] = self.__base_id_to_field_maps.get(record_id, {}) if record_id else self.__field_maps
155
158
  return list(field_maps.get(data_type, {}).values())
156
159
 
@@ -4,16 +4,25 @@ from logging import Logger
4
4
 
5
5
  from sapiopylib.rest.DataMgmtService import DataMgmtServer
6
6
  from sapiopylib.rest.DataRecordManagerService import DataRecordManager
7
+ from sapiopylib.rest.User import SapioUser
7
8
  from sapiopylib.rest.WebhookService import AbstractWebhookHandler
9
+ from sapiopylib.rest.pojo.Message import VeloxLogMessage, VeloxLogLevel
8
10
  from sapiopylib.rest.pojo.webhook.WebhookContext import SapioWebhookContext
9
11
  from sapiopylib.rest.pojo.webhook.WebhookEnums import WebhookEndpointType
10
12
  from sapiopylib.rest.pojo.webhook.WebhookResult import SapioWebhookResult
13
+ from sapiopylib.rest.utils.DataTypeCacheManager import DataTypeCacheManager
11
14
  from sapiopylib.rest.utils.recordmodel.RecordModelManager import RecordModelManager, RecordModelInstanceManager, \
12
15
  RecordModelRelationshipManager
13
16
  from sapiopylib.rest.utils.recordmodel.ancestry import RecordModelAncestorManager
14
17
 
18
+ from sapiopycommons.callbacks.callback_util import CallbackUtil
19
+ from sapiopycommons.eln.experiment_handler import ExperimentHandler
15
20
  from sapiopycommons.general.exceptions import SapioUserErrorException, SapioCriticalErrorException, \
16
- SapioUserCancelledException
21
+ SapioUserCancelledException, SapioException
22
+ from sapiopycommons.general.sapio_links import SapioNavigationLinker
23
+ from sapiopycommons.recordmodel.record_handler import RecordHandler
24
+ from sapiopycommons.rules.eln_rule_handler import ElnRuleHandler
25
+ from sapiopycommons.rules.on_save_rule_handler import OnSaveRuleHandler
17
26
 
18
27
 
19
28
  # FR-46064 - Initial port of PyWebhookUtils to sapiopycommons.
@@ -25,6 +34,7 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
25
34
  """
26
35
  logger: Logger
27
36
 
37
+ user: SapioUser
28
38
  context: SapioWebhookContext
29
39
 
30
40
  dr_man: DataRecordManager
@@ -34,21 +44,46 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
34
44
  # FR-46329: Add the ancestor manager to CommonsWebhookHandler.
35
45
  an_man: RecordModelAncestorManager
36
46
 
47
+ dt_cache: DataTypeCacheManager
48
+ rec_handler: RecordHandler
49
+ callback: CallbackUtil
50
+ exp_handler: ExperimentHandler | None
51
+ rule_handler: OnSaveRuleHandler | ElnRuleHandler | None
52
+
37
53
  def run(self, context: SapioWebhookContext) -> SapioWebhookResult:
54
+ self.user = context.user
38
55
  self.context = context
39
- self.logger = context.user.logger
56
+
57
+ self.logger = self.user.logger
40
58
 
41
59
  self.dr_man = context.data_record_manager
42
- self.rec_man = RecordModelManager(context.user)
60
+ self.rec_man = RecordModelManager(self.user)
43
61
  self.inst_man = self.rec_man.instance_manager
44
62
  self.rel_man = self.rec_man.relationship_manager
45
63
  self.an_man = RecordModelAncestorManager(self.rec_man)
46
64
 
65
+ self.dt_cache = DataTypeCacheManager(self.user)
66
+ self.rec_handler = RecordHandler(context)
67
+ self.callback = CallbackUtil(context)
68
+ if context.eln_experiment is not None:
69
+ self.exp_handler = ExperimentHandler(context)
70
+ else:
71
+ self.exp_handler = None
72
+ if self.is_on_save_rule():
73
+ self.rule_handler = OnSaveRuleHandler(context)
74
+ elif self.is_eln_rule():
75
+ self.rule_handler = ElnRuleHandler(context)
76
+ else:
77
+ self.rule_handler = None
78
+
47
79
  # Wrap the execution of each webhook in a try/catch. If an exception occurs, handle any special sapiopycommons
48
80
  # exceptions. Otherwise, return a generic message stating that an error occurred.
49
81
  try:
50
82
  self.initialize(context)
51
- return self.execute(context)
83
+ result = self.execute(context)
84
+ if result is None:
85
+ raise SapioException("Your execute function returned a None result! Don't forget your return statement!")
86
+ return result
52
87
  except SapioUserErrorException as e:
53
88
  return self.handle_user_error_exception(e)
54
89
  except SapioCriticalErrorException as e:
@@ -100,7 +135,7 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
100
135
  return result
101
136
  self.log_error(traceback.format_exc())
102
137
  if self.can_send_client_callback():
103
- DataMgmtServer.get_client_callback(self.context.user).display_error(e.args[0])
138
+ DataMgmtServer.get_client_callback(self.user).display_error(e.args[0])
104
139
  return SapioWebhookResult(False)
105
140
 
106
141
  def handle_unexpected_exception(self, e: Exception) -> SapioWebhookResult:
@@ -114,7 +149,10 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
114
149
  result: SapioWebhookResult | None = self.handle_any_exception(e)
115
150
  if result is not None:
116
151
  return result
117
- self.log_error(traceback.format_exc())
152
+ msg: str = traceback.format_exc()
153
+ self.log_error(msg)
154
+ # FR-47079: Also log all unexpected exception messages to the webhook execution log within the platform.
155
+ self.log_error_to_webhook_execution_log(msg)
118
156
  return SapioWebhookResult(False, display_text="Unexpected error occurred during webhook execution. "
119
157
  "Please contact Sapio support.")
120
158
 
@@ -129,7 +167,7 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
129
167
  result: SapioWebhookResult | None = self.handle_any_exception(e)
130
168
  if result is not None:
131
169
  return result
132
- return SapioWebhookResult(False, display_text="User cancelled.")
170
+ return SapioWebhookResult(False)
133
171
 
134
172
  # noinspection PyMethodMayBeStatic,PyUnusedLocal
135
173
  def handle_any_exception(self, e: Exception) -> SapioWebhookResult | None:
@@ -145,32 +183,58 @@ class CommonsWebhookHandler(AbstractWebhookHandler):
145
183
 
146
184
  def log_info(self, msg: str) -> None:
147
185
  """
148
- Write an info message to the log. Log destination is stdout. This message will be prepended with the user's
149
- username and the experiment ID of the experiment they are in, if any.
186
+ Write an info message to the webhook server log. Log destination is stdout. This message will be prepended with
187
+ the user's username and the experiment ID of the experiment they are in, if any.
150
188
  """
151
- exp_id = None
152
- if self.context.eln_experiment is not None:
153
- exp_id = self.context.eln_experiment.notebook_experiment_id
154
- # CR-46333: Add the user's group to the logging message.
155
- user = self.context.user
156
- username = user.username
157
- group_name = user.session_additional_data.current_group_name
158
- self.logger.info(f"(User: {username}, Group: {group_name}, Experiment: {exp_id}):\n{msg}")
189
+ self.logger.info(self._format_log(msg, "log_info call"))
159
190
 
160
191
  def log_error(self, msg: str) -> None:
161
192
  """
162
- Write an error message to the log. Log destination is stderr. This message will be prepended with the user's
163
- username and the experiment ID of the experiment they are in, if any.
193
+ Write an error message to the webhook server log. Log destination is stderr. This message will be prepended with
194
+ the user's username and the experiment ID of the experiment they are in, if any.
164
195
  """
165
- exp_id = None
196
+ # PR-46209: Use logger.error instead of logger.info when logging errors.
197
+ self.logger.error(self._format_log(msg, "log_error call"))
198
+
199
+ def log_error_to_webhook_execution_log(self, msg: str) -> None:
200
+ """
201
+ Write an error message to the platform's webhook execution log. This can be reviewed by navigating to the
202
+ webhook configuration where the webhook that called this function is defined and clicking the "View Log"
203
+ button. From there, select one of the rows for the webhook executions and click "Download Log" from the right
204
+ side table.
205
+ """
206
+ messenger = DataMgmtServer.get_messenger(self.user)
207
+ messenger.log_message(VeloxLogMessage(message=self._format_log(msg, "Error occurred during webhook execution."),
208
+ log_level=VeloxLogLevel.ERROR,
209
+ originating_class=self.__class__.__name__))
210
+
211
+ def _format_log(self, msg: str, prefix: str | None = None) -> str:
212
+ """
213
+ Given a message to log, populate it with some metadata about this particular webhook execution, including
214
+ the group of the user and the invocation type of the webhook call.
215
+ """
216
+ # If we're able to, provide a link to the location that the error occurred at.
217
+ navigator = SapioNavigationLinker(self.context)
166
218
  if self.context.eln_experiment is not None:
167
- exp_id = self.context.eln_experiment.notebook_experiment_id
219
+ link = navigator.experiment(self.context.eln_experiment)
220
+ elif self.context.data_record and not self.context.data_record_list:
221
+ link = navigator.data_record(self.context.data_record)
222
+ elif self.context.base_data_record:
223
+ link = navigator.data_record(self.context.base_data_record)
224
+ else:
225
+ link = None
226
+
227
+ message: str = ""
228
+ if prefix:
229
+ message += prefix + "\n"
230
+ message += f"Webhook invocation type: {self.context.end_point_type.display_name}\n"
231
+ message += f"Username: {self.user.username}\n"
168
232
  # CR-46333: Add the user's group to the logging message.
169
- user = self.context.user
170
- username = user.username
171
- group_name = user.session_additional_data.current_group_name
172
- # PR-46209: Use logger.error instead of logger.info when logging errors.
173
- self.logger.error(f"(User: {username}, Group: {group_name}, Experiment: {exp_id}):\n{msg}")
233
+ message += f"User group: {self.user.session_additional_data.current_group_name}\n"
234
+ if link:
235
+ message += f"User location: {link}\n"
236
+ message += msg
237
+ return message
174
238
 
175
239
  def is_main_toolbar(self) -> bool:
176
240
  """
@@ -0,0 +1,67 @@
1
+ import sys
2
+ import traceback
3
+ from abc import abstractmethod
4
+ from typing import Any
5
+
6
+ from flask import request
7
+ from sapiopylib.rest.User import SapioUser
8
+ from sapiopylib.rest.WebhookService import AbstractWebhookHandler
9
+ from sapiopylib.rest.pojo.webhook.WebhookResult import SapioWebhookResult
10
+
11
+
12
+ class AbstractWebserviceHandler(AbstractWebhookHandler):
13
+ """
14
+ A base class for constructing "webservice" endpoints on your webhook server. These are endpoints that can be
15
+ communicated with by external sources without needing to format the payload JSON in the webhook context format that
16
+ webhook handlers expect.
17
+
18
+ The entire payload JSON is sent to the run method of this class. It is up to the run method to determine how
19
+ this JSON should be parsed. In order to communicate with a Sapio system, a SapioUser object must be able to be
20
+ defined using the payload. Functions have been provided for constructing users with various authentication methods.
21
+
22
+ Since this extends AbstractWebhookHandler, you can still register endpoints from this class in the same way you
23
+ would normal webhook endpoints.
24
+ """
25
+ def post(self) -> dict[str, Any]:
26
+ """
27
+ Internal method to be executed to translate incoming requests.
28
+ """
29
+ # noinspection PyBroadException
30
+ try:
31
+ return self.run(request.json).to_json()
32
+ except Exception:
33
+ print('Error occurred while running webservice custom logic. See traceback.', file=sys.stderr)
34
+ traceback.print_exc()
35
+ return SapioWebhookResult(False, display_text="Error occurred during webservice execution.").to_json()
36
+
37
+ @abstractmethod
38
+ def run(self, payload: dict[str, Any]) -> SapioWebhookResult:
39
+ pass
40
+
41
+ def basic_auth(self, url: str, username: str, password: str) -> SapioUser:
42
+ """
43
+ :param url: The URL of the Sapio system that requests from this user will be sent to.
44
+ Must end in /webservice/api
45
+ :param username: The username to authenticate requests with.
46
+ :param password: The password to authenticate requests with.
47
+ :return: A SapioUser that will authenticate requests using basic auth.
48
+ """
49
+ return SapioUser(url, self.verify_sapio_cert, self.client_timeout_seconds, username=username, password=password)
50
+
51
+ def api_token_auth(self, url: str, api_token: str) -> SapioUser:
52
+ """
53
+ :param url: The URL of the Sapio system that requests from this user will be sent to.
54
+ Must end in /webservice/api
55
+ :param api_token: The API token to authenticate requests with.
56
+ :return: A SapioUser that will authenticate requests using an API token.
57
+ """
58
+ return SapioUser(url, self.verify_sapio_cert, self.client_timeout_seconds, api_token=api_token)
59
+
60
+ def bearer_token_auth(self, url: str, bearer_token: str) -> SapioUser:
61
+ """
62
+ :param url: The URL of the Sapio system that requests from this user will be sent to.
63
+ Must end in /webservice/api
64
+ :param bearer_token: The bearer token to authenticate requests with.
65
+ :return: A SapioUser that will authenticate requests using a bearer token.
66
+ """
67
+ return SapioUser(url, self.verify_sapio_cert, self.client_timeout_seconds, bearer_token=bearer_token)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: sapiopycommons
3
- Version: 2024.8.29a317
3
+ Version: 2024.8.30a319
4
4
  Summary: Official Sapio Python API Utilities Package
5
5
  Project-URL: Homepage, https://github.com/sapiosciences
6
6
  Author-email: Jonathan Steck <jsteck@sapiosciences.com>, Yechen Qiao <yqiao@sapiosciences.com>
@@ -0,0 +1,50 @@
1
+ sapiopycommons/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ sapiopycommons/callbacks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ sapiopycommons/callbacks/callback_util.py,sha256=UmjRehMkg44LZB-qgOefQogJEcho2xKtHlICegCHe4I,63454
4
+ sapiopycommons/chem/IndigoMolecules.py,sha256=QqFDi9CKERj6sn_ZwVcS2xZq4imlkaTeCrpq1iNcEJA,1992
5
+ sapiopycommons/chem/Molecules.py,sha256=t80IsQBPJ9mwE8ZxnWomAGrZDhdsOuPvLaTPb_N6jGU,8639
6
+ sapiopycommons/chem/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ sapiopycommons/customreport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ sapiopycommons/customreport/column_builder.py,sha256=sS_wZYOR72rs3syTNjwCVP4h8M8N0b0burkTxFQItVU,3019
9
+ sapiopycommons/customreport/custom_report_builder.py,sha256=o2O89OrWPm0OYS8Ux6EKZTg6hcUzfz3ZxAgnzJg1wEw,6601
10
+ sapiopycommons/customreport/term_builder.py,sha256=oVsr7iFPnug2TrZUCcAMhyps-b62kDodPcBxyQeneUY,16763
11
+ sapiopycommons/datatype/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ sapiopycommons/datatype/attachment_util.py,sha256=_l2swuP8noIGAl4bwzBUEhr6YlN_OVZl3-gi1XqFHYA,3364
13
+ sapiopycommons/eln/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ sapiopycommons/eln/experiment_handler.py,sha256=NoHBthxuXqxdmIj57KEYNqC_t2mArbOkIbcemJkw08U,66683
15
+ sapiopycommons/eln/experiment_report_util.py,sha256=B55hXbTGndCEI19LiqhjvO46_chujZUK0qDTWHjzfcU,6398
16
+ sapiopycommons/eln/plate_designer.py,sha256=FYJfhhNq8hdfuXgDYOYHy6g0m2zNwQXZWF_MTPzElDg,7184
17
+ sapiopycommons/files/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ sapiopycommons/files/complex_data_loader.py,sha256=T39veNhvYl6j_uZjIIJ8Mk5Aa7otR5RB-g8XlAdkksA,1421
19
+ sapiopycommons/files/file_bridge.py,sha256=WwCVegk0OGA8eqho8chsOsLlqg1nXctO75zfh-rHF-g,5950
20
+ sapiopycommons/files/file_bridge_handler.py,sha256=bt2IfIsxJ4lcJYo_NHvCQ17ZV6C4fSAEa8Zcgixh7B4,14263
21
+ sapiopycommons/files/file_data_handler.py,sha256=SCsjODMJIPEBSsahzXUeOM7CfSCmYwPPoGAM6aOfelo,36743
22
+ sapiopycommons/files/file_util.py,sha256=ZrgoGwHHfPdL5KHkGwlrEHJqGpttmZzRkGQCXdLjra8,28284
23
+ sapiopycommons/files/file_validator.py,sha256=4OvY98ueJWPJdpndwnKv2nqVvLP9S2W7Il_dM0Y0ojo,28709
24
+ sapiopycommons/files/file_writer.py,sha256=96Xl8TTT46Krxe_J8rmmlEMtel4nzZB961f5Yqtl1-I,17616
25
+ sapiopycommons/general/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ sapiopycommons/general/accession_service.py,sha256=HYgyOsH_UaoRnoury-c2yTW8SeG4OtjLemdpCzoV4R8,13484
27
+ sapiopycommons/general/aliases.py,sha256=SEC7g218fWkYEcydneAtISgVpP_22YhlI88cM8calWY,10307
28
+ sapiopycommons/general/audit_log.py,sha256=tJi4uU4qRY2WWcK4ItkjRvoCHCwwiU9LwCNv4lP5-QQ,8713
29
+ sapiopycommons/general/custom_report_util.py,sha256=6Vr3itz5Bav9yBIlblnWMMSc0Mc-HPeVfnpymdLf6fU,15629
30
+ sapiopycommons/general/exceptions.py,sha256=DOlLKnpCatxQF-lVCToa8ryJgusWLvip6N_1ALN00QE,1679
31
+ sapiopycommons/general/popup_util.py,sha256=vqLSiCry4YClSKIdnk56CIKioBOtawGVmPi2iS1LOIc,31763
32
+ sapiopycommons/general/sapio_links.py,sha256=o9Z-8y2rz6AI0Cy6tq58ElPge9RBnisGc9NyccbaJxs,2610
33
+ sapiopycommons/general/storage_util.py,sha256=ovmK_jN7v09BoX07XxwShpBUC5WYQOM7dbKV_VeLXJU,8892
34
+ sapiopycommons/general/time_util.py,sha256=sXThADCRAQDWYDD9C5CdhcKYIt3qOaVNyZfGBR7HW9A,8701
35
+ sapiopycommons/multimodal/multimodal.py,sha256=A1QsC8QTPmgZyPr7KtMbPRedn2Ie4WIErodUvQ9otgU,6724
36
+ sapiopycommons/multimodal/multimodal_data.py,sha256=p_caXW0vrURkzDHHspUptEI7lVFpZUrmyF7foz2fAvA,14983
37
+ sapiopycommons/processtracking/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
38
+ sapiopycommons/processtracking/endpoints.py,sha256=w5bziI2xC7450M95rCF8JpRwkoni1kEDibyAux9B12Q,10848
39
+ sapiopycommons/recordmodel/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
40
+ sapiopycommons/recordmodel/record_handler.py,sha256=Uxjrq6f_cWFbqi7KRLySdOvmQGtbIBrCNyStRewqzx8,64751
41
+ sapiopycommons/rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
42
+ sapiopycommons/rules/eln_rule_handler.py,sha256=JYzDA_14D2nLnlqwbpIxVOrfKWzbOS27AYf4TQfGr4Q,10469
43
+ sapiopycommons/rules/on_save_rule_handler.py,sha256=Rkqvph20RbNq6m-RF4fbvCP-YfD2CZYBM2iTr3nl0eY,10236
44
+ sapiopycommons/webhook/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
45
+ sapiopycommons/webhook/webhook_handlers.py,sha256=jwc4xu-wwl8haS5k1dENZ1UIYK9GQk74TAo3CGxMW9U,16583
46
+ sapiopycommons/webhook/webservice_handlers.py,sha256=1J56zFI0pWl5MHoNTznvcZumITXgAHJMluj8-2BqYEw,3315
47
+ sapiopycommons-2024.8.30a319.dist-info/METADATA,sha256=exQLbwLoue10TdonQeMBPv3PjcgY_lIXHSSe-8gdbcc,3176
48
+ sapiopycommons-2024.8.30a319.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
49
+ sapiopycommons-2024.8.30a319.dist-info/licenses/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
50
+ sapiopycommons-2024.8.30a319.dist-info/RECORD,,
@@ -1,43 +0,0 @@
1
- sapiopycommons/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- sapiopycommons/callbacks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- sapiopycommons/callbacks/callback_util.py,sha256=caeIWCHvK33jDs3TRskpJv0kDe7W8NPK4MyJPjgztwo,58012
4
- sapiopycommons/chem/IndigoMolecules.py,sha256=QqFDi9CKERj6sn_ZwVcS2xZq4imlkaTeCrpq1iNcEJA,1992
5
- sapiopycommons/chem/Molecules.py,sha256=t80IsQBPJ9mwE8ZxnWomAGrZDhdsOuPvLaTPb_N6jGU,8639
6
- sapiopycommons/chem/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- sapiopycommons/datatype/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- sapiopycommons/datatype/attachment_util.py,sha256=YlnMprj5IGBbAZDLG2khS1P7JIYTw_NYfpJAfRZfP3M,3219
9
- sapiopycommons/eln/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- sapiopycommons/eln/experiment_handler.py,sha256=v1pG4qtZb8OSNWfKtFo6NjnEkReqnu5R9i_hqWh_xxg,57198
11
- sapiopycommons/eln/experiment_report_util.py,sha256=FTLw-6SLAMeoWTOO-qhGROE9g54pZdyoQJIhiIzlwGw,7848
12
- sapiopycommons/eln/plate_designer.py,sha256=FYJfhhNq8hdfuXgDYOYHy6g0m2zNwQXZWF_MTPzElDg,7184
13
- sapiopycommons/files/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- sapiopycommons/files/complex_data_loader.py,sha256=XSJOl676mIklJo78v07-70u1b015a5DI4sqZPI3C-Tw,1475
15
- sapiopycommons/files/file_bridge.py,sha256=GI3-gWFzcL0q0c8jKOxTevbzJqtUpiElmkXfTnMsaOo,6224
16
- sapiopycommons/files/file_bridge_handler.py,sha256=MU2wZR4VY606yx6Bnv8-LzG3mGCeuXeRBn914WNRFCo,13601
17
- sapiopycommons/files/file_data_handler.py,sha256=3-guAdhJdeJWAFq1a27ijspkO7uMMZ6CapMCD_6o4jA,36746
18
- sapiopycommons/files/file_util.py,sha256=44mzhn3M_QltoncBB-ooX7_yO6u5k-XU_bzUXHGxUiw,26299
19
- sapiopycommons/files/file_validator.py,sha256=BhXB2XnoNEzdBXuwul1s2RNoj-3ZoiMmephUCU_0o3Y,28113
20
- sapiopycommons/files/file_writer.py,sha256=5u_iZXTQvuUU7ceHZr8Q001_tvgJhOqBwAnB_pxcAbQ,16027
21
- sapiopycommons/general/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- sapiopycommons/general/accession_service.py,sha256=HYgyOsH_UaoRnoury-c2yTW8SeG4OtjLemdpCzoV4R8,13484
23
- sapiopycommons/general/aliases.py,sha256=i6af5o2oVFGNcyk7GkvTWXQs0H9xTbFKc_GIah8NKVU,3594
24
- sapiopycommons/general/custom_report_util.py,sha256=cLgIR5Fn3M9uyAtgfTYRv3JRk2SKNevnsb_R5zidSYs,15557
25
- sapiopycommons/general/exceptions.py,sha256=DOlLKnpCatxQF-lVCToa8ryJgusWLvip6N_1ALN00QE,1679
26
- sapiopycommons/general/popup_util.py,sha256=-mN5IgYPrLrOEHJ4CHPi2rec4_WAN6X0yMxHwD5h3Bs,30126
27
- sapiopycommons/general/storage_util.py,sha256=ovmK_jN7v09BoX07XxwShpBUC5WYQOM7dbKV_VeLXJU,8892
28
- sapiopycommons/general/time_util.py,sha256=jiJUh7jc1ZRCOem880S3HaLPZ4RboBtSl4_U9sqAQuM,7290
29
- sapiopycommons/multimodal/multimodal.py,sha256=A1QsC8QTPmgZyPr7KtMbPRedn2Ie4WIErodUvQ9otgU,6724
30
- sapiopycommons/multimodal/multimodal_data.py,sha256=zqgYHO-ULaPKV0POFWZVY9N-Sfm1RQWwdsfwFxe5DjI,15038
31
- sapiopycommons/processtracking/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
- sapiopycommons/processtracking/endpoints.py,sha256=g5h_uCVByqacYm9zWAz8TyAdRsGfaO2o0b5RSJdOaSA,10926
33
- sapiopycommons/recordmodel/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
- sapiopycommons/recordmodel/record_handler.py,sha256=AyK1H3x-g1eu1Mt9XD1h57yRrZp_TJjZlEaQ2kPP4Dc,54432
35
- sapiopycommons/rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
- sapiopycommons/rules/eln_rule_handler.py,sha256=qfkBZtck0KK1i9s9Xe2UZqkzQOgPCzDxRkhxE8Si1xk,10671
37
- sapiopycommons/rules/on_save_rule_handler.py,sha256=JY9F30IcHwFVdgPAMQtTYuRastV1jeezhVktyrzNASU,10763
38
- sapiopycommons/webhook/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
39
- sapiopycommons/webhook/webhook_handlers.py,sha256=ibpBY3Sk3Eij919bIdW0awzlogYoQSWYDDOg--NwsQE,13431
40
- sapiopycommons-2024.8.29a317.dist-info/METADATA,sha256=Pgj3R0rfc31rPqz3voTIjd6r1axXbXfCSfwXI3eCZGQ,3176
41
- sapiopycommons-2024.8.29a317.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
42
- sapiopycommons-2024.8.29a317.dist-info/licenses/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
43
- sapiopycommons-2024.8.29a317.dist-info/RECORD,,