python-eigen-ingenuity 0.5.35b2__py3-none-any.whl → 0.5.36b1__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.
@@ -14,36 +14,37 @@ h.listDataTags()
14
14
  """
15
15
 
16
16
  try:
17
- from importlib.metadata import version, PackageNotFoundError
17
+ from importlib.metadata import PackageNotFoundError, version
18
18
  except ImportError:
19
19
  from importlib_metadata import (
20
- version,
21
20
  PackageNotFoundError,
21
+ version,
22
22
  ) # backport for Python < 3.8
23
23
 
24
24
  from eigeningenuity.core import EigenServer
25
+ from eigeningenuity.alerts import alerts, get_alerts
26
+ from eigeningenuity.assetmodel import AssetModel, Neo4J, get_assetmodel, get_neo4j
27
+ from eigeningenuity.commonmenu import get_common_menu
28
+ from eigeningenuity.elastic import get_elastic
29
+ from eigeningenuity.events import get_eventlog
25
30
  from eigeningenuity.historian import (
26
31
  get_historian,
27
32
  list_historians,
28
33
  )
29
34
  from eigeningenuity.historianmulti import get_historian_multi
30
- from eigeningenuity.elastic import get_elastic
31
- from eigeningenuity.events import get_eventlog
32
- from eigeningenuity.assetmodel import get_assetmodel, AssetModel, get_neo4j, Neo4J
33
- from eigeningenuity.commonmenu import get_common_menu
34
- from eigeningenuity.sql import get_sql
35
+ from eigeningenuity.logformatter import setup_logging
35
36
  from eigeningenuity.settings import (
36
- set_azure_tenant_id,
37
- set_azure_client_id,
38
- set_azure_client_secret,
39
- disable_azure_auth,
40
- disable_auth_token_cache,
41
37
  clear_auth_token_cache,
38
+ disable_auth_token_cache,
39
+ disable_azure_auth,
42
40
  set_api_token,
43
41
  set_auth_scope,
42
+ set_azure_client_id,
43
+ set_azure_client_secret,
44
+ set_azure_tenant_id,
44
45
  )
46
+ from eigeningenuity.sql import get_sql
45
47
  from eigeningenuity.util import EigenException
46
- from eigeningenuity.logformatter import setup_logging
47
48
 
48
49
  __all__ = [
49
50
  "get_historian",
@@ -51,6 +52,8 @@ __all__ = [
51
52
  "get_assetmodel",
52
53
  "AssetModel",
53
54
  "get_neo4j",
55
+ "get_alerts",
56
+ "alerts",
54
57
  "Neo4J",
55
58
  "get_common_menu",
56
59
  "get_elastic",
@@ -0,0 +1,444 @@
1
+ """Create and list Ingenuity alerts through the eventscanner API.
2
+
3
+ Use :func:`alerts` (also available as ``get_alerts``) to construct a client
4
+ from an EigenServer, a base URL, or the configured default server.
5
+ """
6
+
7
+ import logging
8
+ from typing import Any, Literal, TypedDict
9
+ from urllib.error import URLError
10
+
11
+ import requests
12
+ from requests.exceptions import ConnectionError
13
+ from urllib3.exceptions import InsecureRequestWarning
14
+
15
+ from eigeningenuity.core import EigenServer, get_default_server
16
+ from eigeningenuity.util import (
17
+ _do_eigen_get_request,
18
+ _do_eigen_post_request,
19
+ force_list,
20
+ get_eigenserver,
21
+ )
22
+
23
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
24
+
25
+
26
+ Threshold = str | int | float | complex
27
+ ThresholdType = Literal["MIN", "MAX"]
28
+ AlertName = str | list[str] | None
29
+ EmailRecipients = str | list[str] | None
30
+
31
+
32
+ class AlertDefinition(TypedDict):
33
+ """Input for createAlerts; all keys are required, but name/email may be None."""
34
+
35
+ tag: str
36
+ threshold: Threshold
37
+ recovery_threshold: Threshold
38
+ threshold_type: ThresholdType
39
+ name: AlertName
40
+ email: EmailRecipients
41
+
42
+
43
+ class NotificationData(TypedDict):
44
+ """Recipient and delivery rule for an alert notification."""
45
+
46
+ notifyee: str
47
+ notifyrule: Literal["ONCHANGE"]
48
+
49
+
50
+ class NotificationAction(TypedDict):
51
+ """Notification action sent to the eventscanner API."""
52
+
53
+ type: Literal["notification"]
54
+ data: NotificationData
55
+
56
+
57
+ class ThresholdData(TypedDict):
58
+ """Threshold configuration sent to the eventscanner API."""
59
+
60
+ context: str
61
+ thresholdType: ThresholdType
62
+ threshold: Threshold
63
+ recoveryThreshold: Threshold
64
+ dataTag: str
65
+
66
+
67
+ class AlertPayload(TypedDict):
68
+ """Complete wire representation of a numeric threshold alert."""
69
+
70
+ checkId: AlertName
71
+ type: Literal["numberthreshold"]
72
+ data: ThresholdData
73
+ actions: list[NotificationAction]
74
+
75
+
76
+ class AlertResponse(TypedDict):
77
+ """Request result; response contains the parsed service body or raw text."""
78
+
79
+ success: bool
80
+ errors: str | None
81
+ response: Any
82
+
83
+
84
+ class Alerts(object):
85
+ """Manage Ingenuity alerts in a repository configured on the client.
86
+
87
+ Attributes:
88
+ repository: Repository used by all list, create, and delete operations.
89
+ Set during initialization and read when each request is made.
90
+ """
91
+
92
+ def __init__(
93
+ self, baseurl: str, repository: str = "default", auth: bool = False
94
+ ) -> None:
95
+ """Initialize a client for an eventscanner service URL.
96
+
97
+ Args:
98
+ baseurl: Eventscanner URL, including the ``eventscanner`` path.
99
+ repository: Repository used by this client's alert operations.
100
+ Defaults to "default" when constructing Alerts directly.
101
+ auth: Whether request helpers should attempt Azure authentication.
102
+ """
103
+ self.baseurl = baseurl
104
+ self.repository = repository
105
+ self.eigenserver = get_eigenserver(baseurl)
106
+ self.auth = auth
107
+
108
+ def _testConnection(self) -> None:
109
+ """Verify that the configured service URL is reachable.
110
+
111
+ HTTP error statuses alone do not cause this check to fail.
112
+
113
+ Raises:
114
+ ConnectionError: If the endpoint cannot be reached.
115
+
116
+ Docs:
117
+ https://docs.eigeningenuity.co/developing-with-eigen/python-library/alerts/get-alerts
118
+ """
119
+ try:
120
+ requests.get(self.baseurl, verify=False)
121
+ except (URLError, ConnectionError):
122
+ raise ConnectionError(
123
+ "Failed to connect to ingenuity instance at "
124
+ + self.baseurl
125
+ + ". Please check the url is correct and the instance is up."
126
+ )
127
+
128
+ def _doGetRequest(self, relative_url: str) -> AlertResponse:
129
+ """GET a service-relative URL and return the shared response envelope.
130
+
131
+ HTTP failures are reported by ``success`` and ``errors``; transport
132
+ failures propagate as requests exceptions.
133
+ """
134
+ # self._testConnection()
135
+ url = f"{self.baseurl}/{relative_url}"
136
+ return _do_eigen_get_request(url, self.auth)
137
+
138
+ def _doPostRequest(self, relative_url: str, payload: dict) -> AlertResponse:
139
+ """POST a service-relative URL and return the shared response envelope.
140
+
141
+ HTTP failures are reported by ``success`` and ``errors``; transport
142
+ failures propagate as requests exceptions.
143
+ """
144
+ # self._testConnection()
145
+ url = f"{self.baseurl}/{relative_url}"
146
+ return _do_eigen_post_request(url, payload, self.auth)
147
+
148
+ def _createAlerts(self, data: AlertPayload | list[AlertPayload]) -> AlertResponse:
149
+ """POST one or more wire-format checks to the client's repository."""
150
+ relative_url = f"/repository/{self.repository}/save"
151
+
152
+ data = force_list(data)
153
+ payload = {"checks": data}
154
+
155
+ return self._doPostRequest(relative_url, payload)
156
+
157
+ def _construct_alert_body(
158
+ self,
159
+ tag: str,
160
+ threshold: Threshold,
161
+ recovery_threshold: Threshold,
162
+ threshold_type: ThresholdType,
163
+ name: AlertName,
164
+ email: EmailRecipients,
165
+ ) -> AlertPayload:
166
+ """Build a numeric threshold check with ONCHANGE email notifications."""
167
+ actions: list[NotificationAction] = []
168
+ email = force_list(email)
169
+ for address in email:
170
+ if address is None:
171
+ continue
172
+ actions.append(
173
+ {
174
+ "type": "notification",
175
+ "data": {
176
+ "notifyee": address,
177
+ "notifyrule": "ONCHANGE",
178
+ },
179
+ }
180
+ )
181
+
182
+ return {
183
+ "checkId": name,
184
+ "type": "numberthreshold",
185
+ "data": {
186
+ # FIXME: Currently only alerts with context boxhill show in FE.
187
+ # Ideally this should be python and be filterable on FE. But for now must be boxhill
188
+ "context": "boxhill",
189
+ "thresholdType": threshold_type,
190
+ "threshold": threshold,
191
+ "recoveryThreshold": recovery_threshold,
192
+ "dataTag": tag,
193
+ },
194
+ "actions": actions,
195
+ }
196
+
197
+ def _validate_alert_inputs(
198
+ self,
199
+ tag: object,
200
+ threshold: object,
201
+ recovery_threshold: object,
202
+ threshold_type: object,
203
+ name: object,
204
+ email: object,
205
+ ) -> bool:
206
+ """Check runtime inputs without raising for ordinary invalid values.
207
+
208
+ Tags and string thresholds must contain ``/``. Numeric thresholds
209
+ include complex values for legacy compatibility, although those cannot
210
+ be encoded by the JSON request helper. Names may be strings, lists of
211
+ strings, or None. Email addresses must contain ``@``.
212
+ """
213
+ # Check tag includes a historian
214
+ if type(tag) is not str or "/" not in tag:
215
+ return False
216
+
217
+ # Check thresholds are numeric of historian/tag format
218
+ for x in [threshold, recovery_threshold]:
219
+ if not isinstance(x, (int, float, complex, str)):
220
+ return False
221
+
222
+ if isinstance(x, str) and "/" not in x:
223
+ return False
224
+
225
+ # Check threshold type is valid
226
+ allowed_threshold_types = {"MIN", "MAX"}
227
+ if (
228
+ not isinstance(threshold_type, str)
229
+ or threshold_type not in allowed_threshold_types
230
+ ):
231
+ return False
232
+
233
+ if not (
234
+ isinstance(name, str)
235
+ or (
236
+ (isinstance(name, list) and all(isinstance(x, str) for x in name))
237
+ or name is None
238
+ )
239
+ ):
240
+ return False
241
+
242
+ if not (
243
+ (isinstance(email, str) and "@" in email)
244
+ or (
245
+ (
246
+ isinstance(email, list)
247
+ and all(isinstance(x, str) and "@" in x for x in email)
248
+ )
249
+ or email is None
250
+ )
251
+ ):
252
+ return False
253
+
254
+ # TODO: Implement mobile number validation to enabled sms
255
+ # if not (
256
+ # isinstance(sms, str)
257
+ # or not (
258
+ # (isinstance(sms, list) and all(isinstance(x, str) for x in sms))
259
+ # or sms is None
260
+ # )
261
+ # ):
262
+ # return False
263
+
264
+ return True
265
+
266
+ def listAlerts(self) -> AlertResponse:
267
+ """Return alerts from the client's repository in the response envelope.
268
+
269
+ Returns:
270
+ Request status, error text, and the parsed service response.
271
+ """
272
+ return self._doGetRequest(f"/repository/{self.repository}/list")
273
+
274
+ def deleteAlerts(self, event_ids: str | list[str]):
275
+ """Delete checks by ID from the client's repository.
276
+
277
+ Args:
278
+ event_ids: Check identifier or list of identifiers to delete.
279
+
280
+ Returns:
281
+ Request status, error text, and the parsed service response.
282
+
283
+ Raises:
284
+ requests.exceptions.RequestException: A transport error occurs.
285
+ """
286
+ relative_url = f"/repository/{self.repository}/delete"
287
+ event_ids = force_list(event_ids)
288
+ payload = {"eventCheckIds": event_ids}
289
+ return self._doPostRequest(relative_url, payload)
290
+
291
+ # TODO: Implement mobile number validation to enabled sms
292
+ def createAlert(
293
+ self,
294
+ tag: str,
295
+ threshold: Threshold,
296
+ recovery_threshold: Threshold,
297
+ threshold_type: ThresholdType = "MAX",
298
+ name: AlertName = None,
299
+ email: EmailRecipients = None,
300
+ ) -> AlertResponse:
301
+ """Validate and create one numeric threshold alert in the client's repository.
302
+
303
+ Args:
304
+ tag: Data source reference in ``historian/tag`` form.
305
+ threshold: Numeric trigger value or ``historian/tag`` reference.
306
+ recovery_threshold: Numeric recovery value or data source reference.
307
+ threshold_type: MIN for a lower limit or MAX for an upper limit.
308
+ name: Check identifier, legacy list of identifiers, or None.
309
+ email: Notification address, list of addresses, or None. The current
310
+ validation rejects None after recipient list normalization;
311
+ pass an empty list to create an alert without notifications.
312
+
313
+ Returns:
314
+ Request status, error text, and the parsed save response.
315
+
316
+ Raises:
317
+ ValueError: An input fails local validation.
318
+ TypeError: A value cannot be JSON encoded (for example, complex).
319
+ """
320
+
321
+ email = force_list(email)
322
+
323
+ valid = self._validate_alert_inputs(
324
+ tag, threshold, recovery_threshold, threshold_type, name, email
325
+ )
326
+
327
+ if not valid:
328
+ raise ValueError("Inputs failed to validate, could not create alert.")
329
+
330
+ payload = self._construct_alert_body(
331
+ tag, threshold, recovery_threshold, threshold_type, name, email
332
+ )
333
+ return self._createAlerts(payload)
334
+
335
+ def createAlerts(
336
+ self,
337
+ alerts: list[AlertDefinition] | None = None,
338
+ ) -> AlertResponse:
339
+ """Validate definitions and save valid alerts in the client's repository.
340
+
341
+ Args:
342
+ alerts: Definitions containing tag, threshold, recovery_threshold,
343
+ threshold_type, name, and email. None submits an empty batch.
344
+
345
+ Returns:
346
+ Request status, error text, and the parsed save response. Invalid
347
+ definitions are skipped with a warning; an empty batch is still sent.
348
+
349
+ Raises:
350
+ KeyError: A definition omits a required key.
351
+ TypeError: A submitted value cannot be JSON encoded.
352
+ """
353
+
354
+ validAlerts: list[AlertPayload] = []
355
+
356
+ for alert in alerts or []:
357
+ tag = alert["tag"]
358
+ threshold = alert["threshold"]
359
+ recovery_threshold = alert["recovery_threshold"]
360
+ threshold_type = alert["threshold_type"]
361
+ name = alert["name"] or None
362
+ email = alert["email"] or None
363
+
364
+ valid = self._validate_alert_inputs(
365
+ tag, threshold, recovery_threshold, threshold_type, name, email
366
+ )
367
+
368
+ if valid:
369
+ validAlerts.append(
370
+ self._construct_alert_body(
371
+ tag, threshold, recovery_threshold, threshold_type, name, email
372
+ )
373
+ )
374
+ else:
375
+ logging.warning(f"Skipping alert {name} as inputs failed to validate.")
376
+ resp = self._createAlerts(validAlerts)
377
+ return resp
378
+
379
+ def createAlertBatch(
380
+ self,
381
+ alerts: list[AlertPayload],
382
+ ) -> AlertResponse:
383
+ """Save wire-format checks in the client's repository without local validation.
384
+
385
+ Args:
386
+ alerts: Complete checks, including checkId, type, data, and actions.
387
+
388
+ Returns:
389
+ Request status, error text, and the parsed save response.
390
+ """
391
+ return self._createAlerts(alerts)
392
+
393
+
394
+ def alerts(
395
+ eigenserver: EigenServer | str | None = None,
396
+ repository: str = "eventcheckrepository",
397
+ ) -> Alerts:
398
+ """Construct an alerts client using the server's URL and authentication.
399
+
400
+ Args:
401
+ eigenserver: Server instance or base URL. None uses get_default_server().
402
+ repository: Repository used by all operations on the returned client.
403
+ Defaults to "eventcheckrepository".
404
+
405
+ Returns:
406
+ Client configured for the server's eventscanner endpoint and repository.
407
+ """
408
+ if eigenserver is None:
409
+ eigenserver = get_default_server()
410
+ elif isinstance(eigenserver, str):
411
+ eigenserver = EigenServer(eigenserver)
412
+
413
+ return Alerts(
414
+ eigenserver.getEigenServerUrl() + "eventscanner",
415
+ repository,
416
+ eigenserver.auth,
417
+ )
418
+
419
+
420
+ def listRepositories(eigenserver) -> AlertResponse:
421
+ """List available repositories independently of a client's repository setting.
422
+
423
+ Args:
424
+ eigenserver: Server instance or base URL. Pass None to use
425
+ get_default_server().
426
+
427
+ Returns:
428
+ Repository descriptors inside the response envelope.
429
+
430
+ The result contains ``success``, ``errors``, and ``response``. HTTP
431
+ failures populate ``errors``; transport exceptions propagate.
432
+ """
433
+ if eigenserver is None:
434
+ eigenserver = get_default_server()
435
+ elif isinstance(eigenserver, str):
436
+ eigenserver = EigenServer(eigenserver)
437
+
438
+ url = eigenserver.getEigenServerUrl() + "eventscanner/repositories"
439
+
440
+ return _do_eigen_get_request(url, eigenserver.auth)
441
+
442
+
443
+ # Alias to legacy style call
444
+ get_alerts = alerts
@@ -595,7 +595,7 @@ def get_assetmodel(
595
595
  elif isinstance(eigenserver, str):
596
596
  eigenserver = EigenServer(eigenserver)
597
597
 
598
- return AssetModel(eigenserver.getEigenServerUrl() + "/", eigenserver.auth, instance)
598
+ return AssetModel(eigenserver.getEigenServerUrl().rstrip("/") + "/", eigenserver.auth, instance)
599
599
 
600
600
 
601
601
  # Aliases
@@ -556,7 +556,7 @@ class HistorianMulti(object):
556
556
  """
557
557
  metadata = self.getMetaData(historian, limit, match)
558
558
 
559
- tags = [tag["tagName"] for tag in metadata]
559
+ tags = [tag["tagName"] for tag in metadata.values()]
560
560
 
561
561
  return tags
562
562
 
@@ -586,12 +586,12 @@ class HistorianMulti(object):
586
586
  Docs:
587
587
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/getmetadata
588
588
  """
589
- if "/" in historian and match == "":
589
+ if historian is None:
590
+ historian = self.historian[0:-1]
591
+ elif "/" in historian and match == "":
590
592
  split_hist = historian.split("/")
591
593
  match = split_hist[1]
592
594
  historian = split_hist[0]
593
- elif historian is None:
594
- historian = self.historian[0:-1]
595
595
 
596
596
  resp = _do_historian_multi_request(
597
597
  self.searchurl + f"?historian={historian}&limit={limit}&search={match}",