|
| 1 | +from audit.models import AuditLog |
| 2 | +from audit.services import get_audited_instance_from_audit_log_record |
| 3 | +from features.models import ( |
| 4 | + Feature, |
| 5 | + FeatureSegment, |
| 6 | + FeatureState, |
| 7 | + FeatureStateValue, |
| 8 | +) |
| 9 | +from integrations.grafana.types import GrafanaAnnotation |
| 10 | +from segments.models import Segment |
| 11 | + |
| 12 | + |
| 13 | +def _get_feature_tags( |
| 14 | + feature: Feature, |
| 15 | +) -> list[str]: |
| 16 | + return list(feature.tags.values_list("label", flat=True)) |
| 17 | + |
| 18 | + |
| 19 | +def _get_instance_tags_from_audit_log_record( |
| 20 | + audit_log_record: AuditLog, |
| 21 | +) -> list[str]: |
| 22 | + if instance := get_audited_instance_from_audit_log_record(audit_log_record): |
| 23 | + if isinstance(instance, Feature): |
| 24 | + return [ |
| 25 | + f"feature:{instance.name}", |
| 26 | + *_get_feature_tags(instance), |
| 27 | + ] |
| 28 | + |
| 29 | + if isinstance(instance, FeatureState): |
| 30 | + return [ |
| 31 | + f"feature:{(feature := instance.feature).name}", |
| 32 | + f'flag:{"enabled" if instance.enabled else "disabled"}', |
| 33 | + *_get_feature_tags(feature), |
| 34 | + ] |
| 35 | + |
| 36 | + if isinstance(instance, FeatureStateValue): |
| 37 | + return [ |
| 38 | + f"feature:{(feature := instance.feature_state.feature).name}", |
| 39 | + *_get_feature_tags(feature), |
| 40 | + ] |
| 41 | + |
| 42 | + if isinstance(instance, Segment): |
| 43 | + return [f"segment:{instance.name}"] |
| 44 | + |
| 45 | + if isinstance(instance, FeatureSegment): |
| 46 | + return [ |
| 47 | + f"feature:{(feature := instance.feature).name}", |
| 48 | + f"segment:{instance.segment.name}", |
| 49 | + *_get_feature_tags(feature), |
| 50 | + ] |
| 51 | + |
| 52 | + return [] |
| 53 | + |
| 54 | + |
| 55 | +def map_audit_log_record_to_grafana_annotation( |
| 56 | + audit_log_record: AuditLog, |
| 57 | +) -> GrafanaAnnotation: |
| 58 | + tags = [ |
| 59 | + "flagsmith", |
| 60 | + f"project:{audit_log_record.project_name}", |
| 61 | + f"environment:{audit_log_record.environment_name}", |
| 62 | + f"by:{audit_log_record.author_identifier}", |
| 63 | + *_get_instance_tags_from_audit_log_record(audit_log_record), |
| 64 | + ] |
| 65 | + time = int(audit_log_record.created_date.timestamp() * 1000) # ms since epoch |
| 66 | + |
| 67 | + return { |
| 68 | + "tags": tags, |
| 69 | + "text": audit_log_record.log, |
| 70 | + "time": time, |
| 71 | + "timeEnd": time, |
| 72 | + } |
0 commit comments