Skip to content

Commit eafd437

Browse files
fix: Improve code formatting and readability in fabric and simulator scripts
2 parents 752b87d + 9ee1ace commit eafd437

2 files changed

Lines changed: 366 additions & 121 deletions

File tree

infra/scripts/fabric/fabric_activator_definition.py

Lines changed: 159 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,22 @@
22
"""
33
Fabric Activator (Reflex) Definition Update Module
44
5-
This module provides activator definition update functionality for Microsoft Fabric operations.
6-
It loads activator configuration from a JSON file, transforms it with dynamic values, encodes it to Base64,
7-
and updates the activator using the Fabric API.
5+
This module provides activator definition update functionality for
6+
Microsoft Fabric operations. It loads activator configuration from a JSON
7+
file, transforms it with dynamic values, encodes it to Base64, and updates
8+
the activator using the Fabric API.
89
910
Usage:
10-
python fabric_activator_definition.py --workspace-id "workspace-id" --activator-id "activator-id" --activator-file "ReflexEntities.json"
11+
python fabric_activator_definition.py --workspace-id "workspace-id" \
12+
--activator-id "activator-id" \
13+
--activator-file "ReflexEntities.json"
1114
12-
Optional parameters can be provided to customize the activator configuration:
13-
python fabric_activator_definition.py --workspace-id "workspace-id" --activator-id "activator-id" --activator-file "ReflexEntities.json" --eventstream-id "eventstream-id" --activator-alerts-email "alerts@example.com"
15+
Optional parameters can be provided to customize the configuration:
16+
python fabric_activator_definition.py --workspace-id "workspace-id" \
17+
--activator-id "activator-id" \
18+
--activator-file "ReflexEntities.json" \
19+
--eventstream-id "eventstream-id" \
20+
--activator-alerts-email "alerts@example.com"
1421
1522
Requirements:
1623
- fabric_api.py module in the same directory
@@ -27,36 +34,53 @@
2734
import sys
2835
from typing import Dict, Any, Optional
2936

30-
from fabric_api import FabricApiClient, FabricWorkspaceApiClient, FabricApiError
37+
from fabric_api import (
38+
FabricApiClient,
39+
FabricWorkspaceApiClient,
40+
FabricApiError
41+
)
3142

32-
def transform_activator_config(activator_config: list,
33-
eventstream_id: str = None,
34-
eventstream_name: str = None,
35-
activator_alerts_email: str = None) -> list:
43+
def transform_activator_config(
44+
activator_config: list,
45+
eventstream_id: str = None,
46+
eventstream_name: str = None,
47+
activator_alerts_email: str = None
48+
) -> list:
3649
"""
3750
Transform activator configuration with dynamic values.
3851
3952
Args:
4053
activator_config: The original activator configuration list
41-
eventstream_id: ID of the eventhouse stream for the activator (optional)
54+
eventstream_id: ID of the eventhouse stream for the activator
55+
(optional)
4256
eventstream_name: Name for the event source (optional)
43-
activator_alerts_email: Email address to replace in alert configurations (optional)
57+
activator_alerts_email: Email address to replace in alert
58+
configurations (optional)
4459
4560
Returns:
4661
Transformed activator configuration list
4762
"""
48-
print(f"📝 Updating activator configuration with dynamic values...")
63+
print(
64+
"📝 Updating activator configuration with dynamic values..."
65+
)
4966

5067
if eventstream_id:
5168
# Update eventstreamSource entities with the new artifact ID
5269
for entity in activator_config:
5370
if entity.get('type') == 'eventstreamSource-v1':
5471
if 'payload' in entity and 'metadata' in entity['payload']:
55-
original_id = entity['payload']['metadata'].get('eventstreamArtifactId')
56-
entity['payload']['metadata']['eventstreamArtifactId'] = eventstream_id
57-
print(f" Updated eventstreamArtifactId from '{original_id}' to '{eventstream_id}'")
72+
metadata = entity['payload']['metadata']
73+
original_id = metadata.get('eventstreamArtifactId')
74+
metadata['eventstreamArtifactId'] = eventstream_id
75+
print(
76+
f" Updated eventstreamArtifactId from "
77+
f"'{original_id}' to '{eventstream_id}'"
78+
)
5879
else:
59-
print(f" Skipping eventstreamArtifactId updates (eventstream_id not provided)")
80+
print(
81+
" Skipping eventstreamArtifactId updates "
82+
"(eventstream_id not provided)"
83+
)
6084

6185
if eventstream_name:
6286
# Update event names for timeSeriesView-v1 entities with definition type "Event"
@@ -67,15 +91,23 @@ def transform_activator_config(activator_config: list,
6791
if definition.get('type') == 'Event' and 'name' in payload:
6892
original_name = payload['name']
6993
payload['name'] = eventstream_name
70-
print(f" Updated event definition name from '{original_name}' to '{eventstream_name}'")
94+
print(
95+
f" Updated event definition name from "
96+
f"'{original_name}' to '{eventstream_name}'"
97+
)
7198
else:
72-
print(f" Skipping event name updates (eventstream_name not provided)")
99+
print(
100+
" Skipping event name updates "
101+
"(eventstream_name not provided)"
102+
)
73103

74104
if activator_alerts_email:
75-
# Email token regex pattern - matches tokenized email format: __TOKEN_email_[counter]__
105+
# Email token regex pattern
106+
# Matches tokenized email format: __TOKEN_email_[counter]__
76107
email_token_pattern = r'__TOKEN_email_\d+__'
77108

78-
# Update tokenized email addresses in rule definitions using regex
109+
# Update tokenized email addresses in rule definitions
110+
# using regex
79111
emails_updated = 0
80112
found_email_tokens = set()
81113

@@ -87,16 +119,30 @@ def transform_activator_config(activator_config: list,
87119
instance_str = definition.get('instance', '')
88120
if instance_str:
89121
try:
90-
# Find all email tokens in the instance string using regex
91-
found_tokens_in_instance = re.findall(email_token_pattern, instance_str)
92-
found_email_tokens.update(found_tokens_in_instance)
122+
# Find all email tokens using regex
123+
found_tokens_in_instance = re.findall(
124+
email_token_pattern, instance_str
125+
)
126+
found_email_tokens.update(
127+
found_tokens_in_instance
128+
)
93129

94-
# Replace all found email tokens with the new email
130+
# Replace all found email tokens
131+
# with the new email
95132
updated_instance_str = instance_str
96133
for email_token in found_tokens_in_instance:
97-
updated_instance_str = updated_instance_str.replace(email_token, activator_alerts_email)
134+
updated_instance_str = (
135+
updated_instance_str.replace(
136+
email_token,
137+
activator_alerts_email
138+
)
139+
)
98140
emails_updated += 1
99-
print(f" Updated email token '{email_token}' to '{activator_alerts_email}'")
141+
print(
142+
f" Updated email token "
143+
f"'{email_token}' to "
144+
f"'{activator_alerts_email}'"
145+
)
100146

101147
# Update the instance string
102148
definition['instance'] = updated_instance_str
@@ -105,33 +151,49 @@ def transform_activator_config(activator_config: list,
105151
print(f" Warning: {e}")
106152

107153
if emails_updated > 0:
108-
print(f" Updated {emails_updated} email token(s) in activator rules")
109-
print(f" Found and replaced email tokens: {', '.join(found_email_tokens)}")
154+
print(
155+
f" Updated {emails_updated} email token(s) "
156+
"in activator rules"
157+
)
158+
print(
159+
f" Found and replaced email tokens: "
160+
f"{', '.join(found_email_tokens)}"
161+
)
110162
else:
111-
print(f" No email tokens found to update")
163+
print(" No email tokens found to update")
112164
else:
113-
print(f" Skipping email address updates (activator_alerts_email not provided)")
165+
print(
166+
" Skipping email address updates "
167+
"(activator_alerts_email not provided)"
168+
)
114169

115170
return activator_config
116171

117-
def setup_activator_definition(workspace_client: FabricWorkspaceApiClient,
118-
workspace_id: str,
119-
activator_id: str,
120-
activator_file_path: str,
121-
eventstream_id: str = None,
122-
eventstream_name: str = None,
123-
activator_alerts_email: str = None):
172+
def update_activator_definition(
173+
workspace_client: FabricWorkspaceApiClient,
174+
workspace_id: str,
175+
activator_id: str,
176+
activator_file_path: str,
177+
eventstream_id: str = None,
178+
eventstream_name: str = None,
179+
activator_alerts_email: str = None
180+
):
124181
"""
125-
Update the definition of an existing Activator (Reflex) in the specified workspace.
182+
Update the definition of an existing Activator (Reflex) in the
183+
specified workspace.
126184
127185
Args:
128186
workspace_client: Authenticated FabricWorkspaceApiClient instance
129-
workspace_id: ID of the workspace where the activator exists (required)
187+
workspace_id: ID of the workspace where the activator exists
188+
(required)
130189
activator_id: ID of the existing activator to update (required)
131-
activator_file_path: Path to the JSON file containing the activator configuration (required)
132-
eventstream_id: ID of the eventhouse stream for the activator (optional)
190+
activator_file_path: Path to the JSON file containing the
191+
activator configuration (required)
192+
eventstream_id: ID of the eventhouse stream for the activator
193+
(optional)
133194
eventstream_name: Name for the event source (optional)
134-
activator_alerts_email: Email address to replace in alert configurations (optional)
195+
activator_alerts_email: Email address to replace in alert
196+
configurations (optional)
135197
136198
Returns:
137199
Dictionary with activator information if successful
@@ -151,11 +213,21 @@ def setup_activator_definition(workspace_client: FabricWorkspaceApiClient,
151213
print("🔍 Using provided Fabric Workspace API client...")
152214

153215
# Verify the activator exists
154-
print(f"🔍 Verifying activator exists (ID: {activator_id})...")
155-
existing_activator = workspace_client.get_activator_by_id(activator_id)
216+
print(
217+
f"🔍 Verifying activator exists (ID: {activator_id})..."
218+
)
219+
existing_activator = workspace_client.get_activator_by_id(
220+
activator_id
221+
)
156222
if not existing_activator:
157-
print(f"❌ Activator with ID '{activator_id}' not found in workspace")
158-
raise ValueError(f"Activator with ID '{activator_id}' not found in workspace '{workspace_id}'")
223+
print(
224+
f"❌ Activator with ID '{activator_id}' "
225+
"not found in workspace"
226+
)
227+
raise ValueError(
228+
f"Activator with ID '{activator_id}' not found in "
229+
f"workspace '{workspace_id}'"
230+
)
159231

160232
activator_name = existing_activator.get('displayName', 'Unknown')
161233
print(f"✅ Found activator: {activator_name}")
@@ -166,7 +238,10 @@ def setup_activator_definition(workspace_client: FabricWorkspaceApiClient,
166238
raise FileNotFoundError(f"Activator file not found: {activator_file_path}")
167239

168240
# Load JSON configuration
169-
print(f"📄 Loading activator configuration from: {activator_file_path}")
241+
print(
242+
f"📄 Loading activator configuration from: "
243+
f"{activator_file_path}"
244+
)
170245
with open(activator_file_path, "r", encoding="utf-8") as json_file:
171246
activator_config = json.load(json_file)
172247

@@ -181,8 +256,13 @@ def setup_activator_definition(workspace_client: FabricWorkspaceApiClient,
181256
# Encode activator configuration to Base64
182257
print("🔄 Encoding activator configuration to Base64...")
183258
activator_json_str = json.dumps(activator_config)
184-
activator_base64 = base64.b64encode(activator_json_str.encode('utf-8')).decode('utf-8')
185-
print(f"✅ Activator configuration encoded ({len(activator_base64)} characters)")
259+
activator_base64 = base64.b64encode(
260+
activator_json_str.encode('utf-8')
261+
).decode('utf-8')
262+
print(
263+
f"✅ Activator configuration encoded "
264+
f"({len(activator_base64)} characters)"
265+
)
186266

187267
# Update the existing activator
188268
print(f"🔄 Updating activator definition (ID: {activator_id})...")
@@ -210,17 +290,29 @@ def setup_activator_definition(workspace_client: FabricWorkspaceApiClient,
210290
raise
211291

212292
def main():
213-
"""Main function to handle command line arguments and execute the activator definition update."""
293+
"""Main function to handle command line arguments and execute
294+
the activator definition update."""
214295
parser = argparse.ArgumentParser(
215-
description="Update the definition of an existing Activator (Reflex) in a Fabric workspace",
296+
description=(
297+
"Update the definition of an existing Activator (Reflex) "
298+
"in a Fabric workspace"
299+
),
216300
formatter_class=argparse.RawDescriptionHelpFormatter,
217301
epilog="""
218302
Examples:
219303
# Basic usage with required parameters:
220-
python fabric_activator_definition.py --workspace-id "12345678-1234-1234-1234-123456789012" --activator-id "87654321-4321-4321-4321-210987654321" --activator-file "ReflexEntities.json"
304+
python fabric_activator_definition.py \\
305+
--workspace-id "12345678-1234-1234-1234-123456789012" \\
306+
--activator-id "87654321-4321-4321-4321-210987654321" \\
307+
--activator-file "ReflexEntities.json"
221308
222309
# With custom parameters to override JSON values:
223-
python fabric_activator_definition.py --workspace-id "12345678-1234-1234-1234-123456789012" --activator-id "87654321-4321-4321-4321-210987654321" --activator-file "ReflexEntities.json" --eventstream-id "11111111-1111-1111-1111-111111111111" --activator-alerts-email "alerts@contoso.com"
310+
python fabric_activator_definition.py \\
311+
--workspace-id "12345678-1234-1234-1234-123456789012" \\
312+
--activator-id "87654321-4321-4321-4321-210987654321" \\
313+
--activator-file "ReflexEntities.json" \\
314+
--eventstream-id "11111111-1111-1111-1111-111111111111" \\
315+
--activator-alerts-email "alerts@contoso.com"
224316
"""
225317
)
226318

@@ -249,12 +341,18 @@ def main():
249341

250342
parser.add_argument(
251343
"--eventstream-name",
252-
help="Name for the eventstream (optional, preserves original if not provided)"
344+
help=(
345+
"Name for the eventstream "
346+
"(optional, preserves original if not provided)"
347+
)
253348
)
254349

255350
parser.add_argument(
256351
"--activator-alerts-email",
257-
help="Email address to replace in alert configurations (optional)"
352+
help=(
353+
"Email address to replace in alert configurations "
354+
"(optional)"
355+
)
258356
)
259357

260358
# Parse arguments
@@ -265,7 +363,10 @@ def main():
265363

266364
workspace_client = authenticate_workspace(args.workspace_id)
267365
if not workspace_client:
268-
print("❌ Failed to authenticate workspace-specific Fabric API client")
366+
print(
367+
"❌ Failed to authenticate workspace-specific "
368+
"Fabric API client"
369+
)
269370
sys.exit(1)
270371

271372
result = setup_activator_definition(

0 commit comments

Comments
 (0)