python
#!/usr/bin/env python3
"""
Data Mesh Policy Simulator
==========================
A simulator to preview the impact of access policy changes on downstream domains,
SLAs, and compliance commitments in a data mesh architecture.
Key Concepts:
- Domains: Own data products and consume others.
- Data Products: Assets with access policies, SLAs (availability, freshness), and compliance labels.
- Dependencies: Directed graph of consumption (Domain A -> Data Product of Domain B).
- Policy Changes: Grant/revoke access to a data product for a specific domain.
- Impacts:
- Downstream Domains: Propagation of access loss (e.g., pipeline breaks).
- SLAs: Simulated breach if access lost (e.g., availability drops from 99.9% to 0%).
- Compliance: Violations based on rules (e.g., PII access requires certification).
Usage:
1. Define your data mesh model (domains, products, deps, policies, SLAs, compliance).
2. Propose a policy change.
3. Run simulation and review impact report.
Extensible: Add custom rules, metrics, or integrations (e.g., with GraphDB).
"""
import json
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict
from collections import defaultdict, deque
import networkx as nx
from networkx.drawing.nx_agraph import to_agraph # Optional: for Graphviz export
@dataclass
class DataProduct:
"""Represents a data product in the mesh."""
name: str
owner_domain: str
sla_availability: float = 99.9 # % uptime
sla_freshness_hours: int = 24 # Max staleness
compliance_labels: List[str] = None # e.g., ['PII', 'GDPR', 'HIPAA']
def __post_init__(self):
if self.compliance_labels is None:
self.compliance_labels = []
@dataclass
class Domain:
"""Represents a domain with its data products and certifications."""
name: str
data_products: Dict[str, DataProduct] = None
certifications: List[str] = None # e.g., ['GDPR-Compliant', 'SOC2']
def __post_init__(self):
if self.data_products is None:
self.data_products = {}
if self.certifications is None:
self.certifications = []
@dataclass
class PolicyChange:
"""Proposed access change."""
action: str # 'grant' or 'revoke'
consumer_domain: str
data_product_name: str
provider_domain: Optional[str] = None # Optional if inferred from product
@dataclass
class Impact:
"""Simulated impact on a domain or product."""
domain: str
affected_products: List[str]
sla_breaches: Dict[str, float] # product -> breach severity (0-1)
compliance_violations: List[str]
severity: str # 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'
class DataMeshPolicySimulator:
"""Core simulator class."""
def __init__(self):
self.domains: Dict[str, Domain] = {}
self.access_policies: Dict[tuple[str, str], bool] = {} # (consumer_domain, product_name) -> allowed
self.dependency_graph = nx.DiGraph() # consumer_domain -> product_name
self.compliance_rules = {
'PII': 'GDPR-Compliant', # Must have cert to access PII
'GDPR': 'GDPR-Compliant',
'HIPAA': 'HIPAA-Certified',
}
def load_mesh(self, mesh_config: Dict[str, Any]):
"""Load data mesh from config dict."""
# Load domains and products
for domain_name, domain_data in mesh_config['domains'].items():
domain = Domain(name=domain_name, **domain_data)
self.domains[domain_name] = domain
for prod_name, prod_data in domain.data_products.items():
prod = DataProduct(name=prod_name, owner_domain=domain_name, **prod_data)
domain.data_products[prod_name] = prod
# Load initial policies
for policy in mesh_config.get('policies', []):
consumer = policy['consumer_domain']
product = policy['data_product']
allowed = policy['allowed']
self.access_policies[(consumer, product)] = allowed
# Build dependency graph (assume all policies imply deps; extend as needed)
for (consumer, product), allowed in self.access_policies.items():
if allowed:
self.dependency_graph.add_edge(consumer, product)
def apply_policy_change(self, change: PolicyChange) -> None:
"""Apply a single policy change (mutates simulator state)."""
key = (change.consumer_domain, change.data_product_name)
if change.action == 'grant':
self.access_policies[key] = True
self.dependency_graph.add_edge(change.consumer_domain, change.data_product_name)
elif change.action == 'revoke':
self.access_policies[key] = False
if self.dependency_graph.has_edge(change.consumer_domain, change.data_product_name):
self.dependency_graph.remove_edge(change.consumer_domain, change.data_product_name)
else:
raise ValueError("Action must be 'grant' or 'revoke'")
def simulate_preview(self, change: PolicyChange) -> List[Impact]:
"""Preview impacts WITHOUT mutating state. Returns list of impacts."""
# Deep copy graph and policies for simulation
sim_graph = self.dependency_graph.copy()
sim_policies = self.access_policies.copy()
# Apply change in sim
key = (change.consumer_domain, change.data_product_name)
if change.action == 'grant':
sim_policies[key] = True
sim_graph.add_edge(change.consumer_domain, change.data_product_name)
elif change.action == 'revoke':
sim_policies[key] = False
if sim_graph.has_edge(change.consumer_domain, change.data_product_name):
sim_graph.remove_edge(change.consumer_domain, change.data_product_name)
# Propagate impacts: BFS from affected consumers
impacted_domains = set()
if change.action == 'revoke':
impacted_domains.add(change.consumer_domain)
elif change.action == 'grant':
# Grant might enable new paths, but focus on access gains (less risky)
impacts = []
queue = deque(impacted_domains)
visited = set(queue)
while queue:
current_domain = queue.popleft()
domain_impacts = self._compute_domain_impacts(current_domain, sim_policies, sim_graph)
if domain_impacts.sla_breaches or domain_impacts.compliance_violations:
impacts.append(domain_impacts)
# Propagate to downstream dependents
downstream = list(sim_graph.successors(current_domain))
for dep in downstream:
if dep not in visited:
visited.add(dep)
queue.append(dep)
return impacts
def _compute_domain_impacts(self, domain_name: str, policies: Dict, graph: nx.DiGraph) -> Impact:
"""Compute detailed impacts for a single domain."""
domain = self.domains.get(domain_name)
if not domain:
return Impact(domain=domain_name, affected_products=[], sla_breaches={}, compliance_violations=[], severity='LOW')
affected_products = []
sla_breaches = {}
compliance_violations = []
for upstream_prod in graph.predecessors(domain_name):
key = (domain_name, upstream_prod)
access_lost = key not in policies or not policies[key]
if access_lost:
affected_products.append(upstream_prod)
# Simulate SLA breach: full loss -> 100% breach
prod = self._get_product(upstream_prod)
if prod:
breach_severity = 1.0 - (prod.sla_availability / 100)
sla_breaches[upstream_prod] = breach_severity
# Compliance check
prod_labels = prod.compliance_labels
domain_certs = domain.certifications
for label in prod_labels:
required_cert = self.compliance_rules.get(label)
if required_cert and required_cert not in domain_certs:
compliance_violations.append(f"Missing cert '{required_cert}' for '{label}' in {upstream_prod}")
severity = self._assess_severity(sla_breaches, compliance_violations)
return Impact(
domain=domain_name,
affected_products=affected_products,
sla_breaches=sla_breaches,
compliance_violations=compliance_violations,
severity=severity
)
def _get_product(self, prod_name: str) -> Optional[DataProduct]:
"""Find product by name across domains."""
for domain in self.domains.values():
if prod_name in domain.data_products:
return domain.data_products[prod_name]
return None
def _assess_severity(self, sla_breaches: Dict, violations: List) -> str:
"""Simple severity scoring."""
num_breaches = len(sla_breaches)
num_violations = len(violations)
if num_violations > 0:
return 'CRITICAL'
elif num_breaches > 2:
return 'HIGH'
elif num_breaches > 0:
return 'MEDIUM'
return 'LOW'
def export_graph(self, filename: str = 'datamesh_impact.gv'):
"""Export current dependency graph to Graphviz DOT file."""
dot = to_agraph(self.dependency_graph)
dot.write(filename)
print(f"Graph exported to {filename}")
# Example Usage & Demo
def demo():
"""Run a demo simulation."""
simulator = DataMeshPolicySimulator()
# Sample mesh config (in real use, load from YAML/JSON/DB)
mesh_config = {
'domains': {
'Finance': {
'data_products': {
'RevenueData': {'sla_availability': 99.99, 'compliance_labels': ['GDPR']},
},
'certifications': ['GDPR-Compliant']
},
'Marketing': {
'data_products': {
'CustomerProfiles': {'sla_availability': 99.5, 'compliance_labels': ['PII']},
},
'certifications': []
},
'Sales': {
'data_products': {},
'certifications': ['GDPR-Compliant']
},
'Analytics': {
'data_products': {},
'certifications': ['GDPR-Compliant']
}
},
'policies': [
{'consumer_domain': 'Sales', 'data_product': 'RevenueData', 'allowed': True},
{'consumer_domain': 'Sales', 'data_product': 'CustomerProfiles', 'allowed': True},
{'consumer_domain': 'Analytics', 'data_product': 'RevenueData', 'allowed': True},
{'consumer_domain': 'Analytics', 'data_product': 'CustomerProfiles', 'allowed': True},
]
}
simulator.load_mesh(mesh_config)
# Preview revoking Marketing's CustomerProfiles access to Sales
change = PolicyChange(action='revoke', consumer_domain='Sales', data_product_name='CustomerProfiles')
impacts = simulator.simulate_preview(change)
print("=== Data Mesh Policy Simulator Demo ===")
print(json.dumps(asdict(change), indent=2))
print("\nSimulated Impacts:")
for impact in impacts:
print(json.dumps(asdict(impact), indent=2, default=str))
# Optionally apply and export
# simulator.apply_policy_change(change)
# simulator.export_graph()
if __name__ == "__main__":
demo()
This self-contained tool provides a realistic preview of policy ripple effects. Extend as needed for your data mesh! 🕵️♂️