-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathservice.py
More file actions
322 lines (275 loc) · 13.1 KB
/
Copy pathservice.py
File metadata and controls
322 lines (275 loc) · 13.1 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
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Union, cast
from sift.common.type.v1.resource_identifier_pb2 import (
ClientKeys,
Ids,
NamedResources,
Names,
ResourceIdentifier,
ResourceIdentifiers,
)
from sift.rule_evaluation.v1.rule_evaluation_pb2 import (
AssetsTimeRange,
EvaluateRulesFromCurrentRuleVersions,
EvaluateRulesFromReportTemplate,
EvaluateRulesPreviewRequest,
EvaluateRulesPreviewResponse,
EvaluateRulesRequest,
EvaluateRulesResponse,
RunTimeRange,
)
from sift.rule_evaluation.v1.rule_evaluation_pb2_grpc import RuleEvaluationServiceStub
from sift_py._internal.time import to_timestamp_pb
from sift_py.grpc.transport import SiftChannel
from sift_py.report.service import ReportService
from sift_py.report_templates.config import ReportTemplateConfig
from sift_py.rule.config import RuleConfig
from sift_py.rule.service import RuleIdentifier, RuleService
class RuleEvaluationService:
"""
A service for evaluating rules. Provides methods to evaluate rules and perform dry-run evaluations.
Args:
enable_caching: Enable caching during rule evaluation. This is enabled by default.
This service is typically short lived in a workflows so assets, channels, and
users are unlikely to change during its lifetime to invalidate caches.
"""
_channel: SiftChannel
_rule_evaluation_stub: RuleEvaluationServiceStub
_rule_service: RuleService
def __init__(self, channel: SiftChannel, enable_caching: bool = True):
self._channel = channel
self._rule_evaluation_stub = RuleEvaluationServiceStub(channel)
self._rule_service = RuleService(channel, enable_caching=enable_caching)
def evaluate_against_run(
self,
run_id: str,
rules: Union[ReportTemplateConfig, List[RuleConfig], List[RuleIdentifier]],
report_name: str = "",
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> ReportService:
"""Evaluate a set of rules against a run.
Args:
run_id: The Run ID to run against.
rules: Either a ReportTemplateConfig, a list of RuleConfigs, or a list of
RuleIdentifiers (typically from `RuleService.create_external_rules`).
report_name: Optional report name.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
A ReportService object that can be use to get the status of the executed report.
"""
rules_kwargs = self._get_rules_kwargs(rules)
run_kwargs = self._get_run_kwargs(run_id, start_time, end_time)
req = EvaluateRulesRequest(
report_name=report_name,
**rules_kwargs,
**run_kwargs,
)
res = cast(EvaluateRulesResponse, self._rule_evaluation_stub.EvaluateRules(req))
return ReportService(self._channel, res.report_id)
def evaluate_against_assets(
self,
asset_names: List[str],
start_time: Union[datetime, str, int, float],
end_time: Union[datetime, str, int, float],
rules: Union[ReportTemplateConfig, List[RuleConfig], List[RuleIdentifier]],
report_name: str = "",
) -> ReportService:
"""Evaluate a set of rules against assets.
Args:
asset_names: The list of assets to run against.
start_time: The start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: The end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
rules: Either a ReportTemplateConfig, a list of RuleConfigs, or a list of
RuleIdentifiers (typically from `RuleService.create_external_rules`).
report_name: Optional report name.
Returns:
A Report object that can be use to get the status of the executed report.
"""
asset_time_range = AssetsTimeRange(
assets=NamedResources(names=Names(names=asset_names)),
start_time=to_timestamp_pb(start_time),
end_time=to_timestamp_pb(end_time),
)
rules_kwargs = self._get_rules_kwargs(rules)
req = EvaluateRulesRequest(
report_name=report_name,
assets=asset_time_range,
**rules_kwargs,
)
res = cast(EvaluateRulesResponse, self._rule_evaluation_stub.EvaluateRules(req))
return ReportService(self._channel, res.report_id)
def preview_against_run(
self,
run_id: str,
rules: Union[ReportTemplateConfig, List[RuleConfig], List[RuleIdentifier]],
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> EvaluateRulesPreviewResponse:
"""Preview the evaluation of a set of rules against a run.
Args:
run_id: The Run ID to run against.
rules: Either a ReportTemplateConfig, a list of RuleConfigs, or a list of
RuleIdentifiers (typically from `RuleService.create_external_rules`).
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
The EvaluateRulesPreviewResponse object.
"""
eval_kwargs = self._get_rules_kwargs(rules)
run_kwargs = self._get_run_kwargs(run_id, start_time, end_time)
req = EvaluateRulesPreviewRequest(
**eval_kwargs,
**run_kwargs,
)
return self._rule_evaluation_stub.EvaluateRulesPreview(req)
def evaluate_external_rules(
self,
run_id: str,
rules: List[RuleConfig],
report_name: str = "",
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> ReportService:
"""Evaluate a set of external rules against a run.
Args:
run_id: The Run ID to run against.
rules: A list of RuleConfigs. These must be external rules.
report_name: Optional report name.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
A Report object that can be use to get the status of the executed report.
"""
rule_ids = self._rule_service.create_external_rules(rules)
return self.evaluate_against_run(run_id, rule_ids, report_name, start_time, end_time)
def evaluate_external_rules_from_yaml(
self,
run_id: str,
paths: List[Path],
named_expressions: Optional[Dict[str, str]] = None,
report_name: str = "",
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> ReportService:
"""Evaluate a set of external rules from a YAML config against a run.
Args:
run_id: The Run ID to run against.
paths: The YAML paths to load rules from.
report_name: Optional report name.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
A Report object that can be use to get the status of the executed report.
"""
rule_ids = self._rule_service.create_external_rules_from_yaml(paths, named_expressions)
return self.evaluate_against_run(run_id, rule_ids, report_name, start_time, end_time)
def preview_external_rules(
self,
run_id: str,
rules: List[RuleConfig],
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> EvaluateRulesPreviewResponse:
"""Preview the evaluation a set of external rules against a run.
Args:
run_id: The Run ID to run against.
rules: A list of RuleConfigs. These must be external rules.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
The EvaluateRulesPreviewResponse object.
"""
rule_ids = self._rule_service.create_external_rules(rules)
return self.preview_against_run(run_id, rule_ids, start_time, end_time)
def preview_external_rules_from_yaml(
self,
run_id: str,
paths: List[Path],
named_expressions: Optional[Dict[str, str]] = None,
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> EvaluateRulesPreviewResponse:
"""Preview the evaluation a set of external rules from a YAML config against a run.
Args:
run_id: The Run ID to run against.
paths: The YAML paths to load rules from.
named_expressions: The named expressions to substitute in the rules.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
The EvaluateRulesPreviewResponse object.
"""
rule_ids = self._rule_service.create_external_rules_from_yaml(paths, named_expressions)
return self.preview_against_run(run_id, rule_ids, start_time, end_time)
def _get_rules_kwargs(
self, rules: Union[ReportTemplateConfig, List[RuleConfig], List[RuleIdentifier]]
) -> dict:
"""Returns the keyword arguments for a EvalutateRules request based on the input type.
Currently does not support evaluating rules from a specific version.
Args:
rules: Either the ReportTemplateConfig, list of RuleIdentifiers, or list of RuleConfigs.
Returns:
dict: The keyword argument.
"""
if isinstance(rules, ReportTemplateConfig):
if not rules.template_id:
raise ValueError("Invalid report template")
return {
"report_template": EvaluateRulesFromReportTemplate(
report_template=ResourceIdentifier(id=rules.template_id)
)
}
else:
if len(rules) == 0:
raise ValueError("Rule set is empty")
if isinstance(rules[0], RuleIdentifier):
rule_ids = cast(List[RuleIdentifier], rules)
return {
"rules": EvaluateRulesFromCurrentRuleVersions(
rules=ResourceIdentifiers(ids=Ids(ids=[r.rule_id for r in rule_ids])),
),
}
elif isinstance(rules[0], RuleConfig):
rule_configs = cast(List[RuleConfig], rules)
for config in rule_configs:
if not config.rule_client_key:
raise ValueError(f"Rule of name '{config.name}' requires a rule_client_key")
return {
"rules": EvaluateRulesFromCurrentRuleVersions(
rules=ResourceIdentifiers(
client_keys=ClientKeys(
client_keys=[r.rule_client_key for r in rule_configs] # type: ignore
),
),
),
}
raise ValueError("Invalid rules argument")
def _get_run_kwargs(
self,
run_id: str,
start_time: Optional[Union[datetime, str, int, float]] = None,
end_time: Optional[Union[datetime, str, int, float]] = None,
) -> dict:
"""Returns the Run specific keyword arguments for a EvalutateRules request based on the input type.
Args:
run_id: The Run ID to run against.
start_time: Optional start time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
end_time: Optional end time to evaluate (datetime, ISO 8601 formatted string, or POSIX timestamp).
Returns:
dict: The keyword arguments.
"""
run = ResourceIdentifier(id=run_id)
if start_time or end_time:
return {
"run_time_range": RunTimeRange(
run=run,
start_time=to_timestamp_pb(start_time) if start_time else None,
end_time=to_timestamp_pb(end_time) if end_time else None,
)
}
else:
return {"run": run}