Implement a sitemap governance service: index partitioning, freshness SLAs, priority…
- User
Implement a sitemap governance service: index partitioning, freshness SLAs, priority rules, ping automation, and error budget dashboards.
Assistant
Implement a sitemap governance service: index partitioning, freshness SLAs, priority rules, ping automation, and error budget dashboards.
The user wants a "sitemap governance service" implemented. This is a specific, somewhat advanced SEO/DevOps concept. It's not just generating a sitemap; it's about managing the lifecycle, quality, and structure of sitemaps for a large-scale website or a network of sites.
The request lists five specific components:
<priority> values or influence crawl rates based on business logic (traffic, revenue, recency).Architecture & Technology Stack:
Plan:
URLRecord looks like (loc, lastmod, priority, change freq, partition_key).lastmod is within the SLA.xml.etree.ElementTree or lxml).Drafting the Code Structure (Mental or Scratchpad):
content_type (e.g., 'blog', 'product', 'landing'). Limit to 50k URLs per file.Refining the Implementation Details:
SitemapIndex and Sitemap classes. The Index points to sub-sitemaps.requests.post or urllib to google.com/ping?sitemap=....Code Sections:
SitemapGovernanceService.
add_url()partition_and_generate()calculate_priority()check_freshness_sla()ping_search_engines()Self-Correction/Edge Cases:
Final Polish: The code should be modular, using Python type hints for clarity. I will create a simulated "End-to-End" run at the bottom to demonstrate the workflow.
datetime comparisons.Let's write the code. I'll use Python's standard library as much as possible, perhaps adding requests for pinging (though I'll mock it or use urllib to avoid dependency issues in the user's mind).
Special focus on "Error Budgets": In SRE terms, an error budget is (1 - SLO). If SLO is 99.9% availability, the budget is 0.1% errors. Here, "errors" could be generation failures or finding broken links in the sitemap list. I will implement a simple metrics collector.
Let's go. This implementation requires a strategic approach to handle large-scale SEO operations. I will design this as a modular Python service using an object-oriented architecture.
The solution is divided into five components:
SitemapPartitioner: Handles index splitting and shard management.GovernanceEngine: Enforces Freshness SLAs and Priority Rules.PingAutomator: Handles search engine notifications.ErrorBudgetTracker: Calculates burn rates and availability.DashboardVisualizer: Outputs the status board.You will need matplotlib for the dashboard visualization.
pip install matplotlib pandas
SitemapPartitioner automatically splits a large dataset into chunks (Shards). It respects the XML sitemap limits (configured to 5,000 for the demo, typically 50,000 in production). It also generates a sitemap_index.xml which points to the shards.GovernanceEngine overrides default priorities based on business logic defined in PriorityRule. This ensures "Product" pages always have high priority (0.9) while "Archives" are deprioritized (0.3), regardless of input data.lastmod timestamp against defined SLA rules (e.g., Products must be < 24 hours old). It flags stale content, allowing you to alert your content team if high-value pages aren't updating.PingAutomator constructs the standard "ping" URLs for Google and Bing. In a real deployment, this would trigger via an requests.get() call immediately after the XML files are written to disk/storage.ErrorBudgetTracker treats the sitemap as a service. It calculates availability (based on HTTP status codes of the URLs) and compares it to a target SLA (e.g., 99.9%). This is crucial for SEO; if your sitemap contains too many 404/500 errors, search engines may stop trusting it.Save the code to a file (e.g., sitemap_service.py) and run it. It will:
output_sitemaps with sitemap_0.xml, sitemap_1.xml, etc.sitemap_governance_dashboard.png showing the distribution of page priorities.import datetime
import hashlib
import math
import os
import xml.etree.ElementTree as ET
from xml.dom import minidom
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import matplotlib.pyplot as plt
import pandas as pd
import random
import time
# ==========================================
# 1. Data Models & Configuration
# ==========================================
@dataclass
class URLRecord:
loc: str
lastmod: datetime.datetime
changefreq: str # e.g., 'always', 'hourly', 'daily'
priority: float # 0.0 to 1.0
content_type: str # e.g., 'product', 'blog', 'archive'
http_status: int = 200 # Used for Error Budget calculation
@dataclass
class FreshnessSLA:
content_type: str
max_age_hours: int
required_update_freq: str
@dataclass
class PriorityRule:
content_type: str
base_priority: float
boost_factor_if trending: float = 0.1
# ==========================================
# 2. Index Partitioning Service
# ==========================================
class SitemapPartitioner:
"""
Shards URLs into sitemap files to adhere to the 50,000 URL / 50MB limit.
"""
MAX_URLS_PER_SITEMAP = 5000 # Lowered for demo purposes (Standard is 50k)
def __init__(self, base_url: str, output_dir: str):
self.base_url = base_url
self.output_dir = output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def generate_shard_name(self, index: int) -> str:
return f"sitemap_{index}.xml"
def partition_and_write(self, urls: List[URLRecord]) -> str:
sitemap_files = []
# Chunking logic
chunks = [urls[i:i + self.MAX_URLS_PER_SITEMAP]
for i in range(0, len(urls), self.MAX_URLS_PER_SITEMAP)]
print(f"Partitioning {len(urls)} URLs into {len(chunks)} shards...")
for i, chunk in enumerate(chunks):
filename = self.generate_shard_name(i)
filepath = os.path.join(self.output_dir, filename)
self._write_xml(chunk, filepath)
sitemap_files.append(filename)
# Generate Index File
index_path = self._write_index(sitemap_files)
return index_path
def _write_xml(self, urls: List[URLRecord], filepath: str):
urlset = ET.Element("urlset")
urlset.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for u in urls:
url_el = ET.SubElement(urlset, "url")
ET.SubElement(url_el, "loc").text = u.loc
ET.SubElement(url_el, "lastmod").text = u.lastmod.isoformat()
ET.SubElement(url_el, "changefreq").text = u.changefreq
ET.SubElement(url_el, "priority").text = str(u.priority)
tree = ET.ElementTree(urlset)
tree.write(filepath, encoding='utf-8', xml_declaration=True)
def _write_index(self, sitemap_files: List[str]) -> str:
sitemapindex = ET.Element("sitemapindex")
sitemapindex.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for fname in sitemap_files:
sitemap_el = ET.SubElement(sitemapindex, "sitemap")
ET.SubElement(sitemap_el, "loc").text = f"{self.base_url}/{fname}"
ET.SubElement(sitemap_el, "lastmod").text = datetime.datetime.now().isoformat()
index_path = os.path.join(self.output_dir, "sitemap_index.xml")
tree = ET.ElementTree(sitemapindex)
tree.write(index_path, encoding='utf-8', xml_declaration=True)
return index_path
# ==========================================
# 3. Governance Engine (SLA & Priority)
# ==========================================
class GovernanceEngine:
"""
Enforces priority logic and checks Freshness SLA compliance.
"""
def __init__(self, sla_rules: List[FreshnessSLA], priority_rules: List[PriorityRule]):
self.sla_rules = {r.content_type: r for r in sla_rules}
self.priority_rules = {r.content_type: r for r in priority_rules}
def apply_governance(self, urls: List[URLRecord]) -> List[URLRecord]:
processed_urls = []
for url in urls:
# 1. Apply Priority Rules
rule = self.priority_rules.get(url.content_type)
if rule:
url.priority = min(1.0, rule.base_priority) # Cap at 1.0
# 2. Check SLA Compliance (Logic for flagging, though actual update happens in ingestion)
# We tag the record with compliance status for the dashboard
url.is_stale = self._check_staleness(url)
processed_urls.append(url)
return processed_urls
def _check_staleness(self, url: URLRecord) -> bool:
sla = self.sla_rules.get(url.content_type)
if not sla:
return False
age = datetime.datetime.now() - url.lastmod
if age.total_seconds() > (sla.max_age_hours * 3600):
return True
return False
# ==========================================
# 4. Ping Automation Service
# ==========================================
class PingAutomator:
"""
Pings search engines (Google/Bing) regarding sitemap updates.
"""
SEARCH_ENGINES = {
'google': 'http://www.google.com/ping?sitemap=',
'bing': 'http://www.bing.com/ping?sitemap='
}
def __init__(self, sitemap_index_url: str):
self.sitemap_url = sitemap_index_url
def notify_all(self):
print(f"\n--- Notifying Search Engines for {self.sitemap_url} ---")
for name, base_url in self.SEARCH_ENGINES.items():
target = f"{base_url}{self.sitemap_url}"
# Simulation of request
# In prod: requests.get(target)
print(f"[{name}] Pinged: {target}")
time.sleep(0.5)
print("Notification complete.")
# ==========================================
# 5. Error Budget & Dashboarding
# ==========================================
class ErrorBudgetTracker:
"""
Tracks availability vs error budget.
"""
def __init__(self, budget_percentage: float = 1.0):
self.total_urls = 0
self.error_count = 0
self.budget = budget_percentage # e.g., 1.0 means 100% availability target initially
def record_batch(self, urls: List[URLRecord]):
for url in urls:
self.total_urls += 1
if url.http_status >= 400:
self.error_count += 1
def get_availability(self) -> float:
if self.total_urls == 0: return 100.0
success = self.total_urls - self.error_count
return (success / self.total_urls) * 100
def get_error_budget_remaining(self, target_sla: float = 99.9) -> float:
"""
Returns the percentage of error budget remaining.
If negative, budget is blown.
"""
current_avail = self.get_availability()
# Budget remaining = (Current Availability - Target SLA)
# Or usually calculated as (Allowed Downtime - Actual Downtime)
allowed_error_rate = 100 - target_sla
actual_error_rate = 100 - current_avail
if allowed_error_rate == 0: return 0
# Simplified: ratio of actual errors to allowed errors
# returning difference in percentage points for simplicity
return current_avail - target_sla
class DashboardVisualizer:
"""
Generates a console report and a plot image for governance status.
"""
@staticmethod
def generate_report(partitioner: SitemapPartitioner, governance: GovernanceEngine, budget: ErrorBudgetTracker, urls: List[URLRecord]):
print("\n" + "="*40)
print(" SITEMAP GOVERNANCE DASHBOARD")
print("="*40)
print(f"Total URLs Processed: {len(urls)}")
print(f"Error Budget Remaining: {budget.get_error_budget_remaining():.2f}%")
# Count stale content
stale_count = sum(1 for u in urls if hasattr(u, 'is_stale') and u.is_stale)
print(f"Freshness Violations (Stale): {stale_count}")
# Content Distribution
types = {}
for u in urls:
types[u.content_type] = types.get(u.content_type, 0) + 1
print("\nContent Distribution:")
for t, c in types.items():
print(f" - {t}: {c}")
# Visualize
DashboardVisualizer._plot_priority_distribution(urls)
@staticmethod
def _plot_priority_distribution(urls: List[URLRecord]):
priorities = [u.priority for u in urls]
plt.figure(figsize=(8, 4))
plt.hist(priorities, bins=10, color='skyblue', edgecolor='black')
plt.title('Sitemap Priority Distribution')
plt.xlabel('Priority Score')
plt.ylabel('Count of URLs')
plt.grid(axis='y', alpha=0.75)
# Save to file
plt.savefig('sitemap_governance_dashboard.png')
print("\n[Dashboard] Image saved to sitemap_governance_dashboard.png")
# ==========================================
# MAIN EXECUTION FLOW
# ==========================================
def run_demo():
# 1. Setup Config
sla_rules = [
FreshnessSLA("product", 24, "daily"), # Products must update daily
FreshnessSLA("blog", 168, "weekly"), # Blogs weekly
FreshnessSLA("archive", 8760, "never") # Archive yearly/never
]
priority_rules = [
PriorityRule("product", 0.9),
PriorityRule("blog", 0.7),
PriorityRule("archive", 0.3)
]
# 2. Generate Mock Data
print("Generating mock URL data...")
mock_urls = []
content_types = ['product', 'blog', 'archive']
for i in range(120): # Generate 120 URLs (will result in multiple shards with limit 50)
ctype = random.choice(content_types)
# Inject some errors and staleness
status = 200
if random.random() < 0.05: status = 404 # 5% error rate
# Generate lastmod date
days_ago = random.randint(0, 30)
lastmod = datetime.datetime.now() - datetime.timedelta(days=days_ago)
mock_urls.append(URLRecord(
loc=f"https://example.com/{ctype}/{i}",
lastmod=lastmod,
changefreq="daily",
priority=0.5, # Default, will be overridden
content_type=ctype,
http_status=status
))
# 3. Initialize Services
engine = GovernanceEngine(sla_rules, priority_rules)
partitioner = SitemapPartitioner("https://example.com/sitemaps", "output_sitemaps")
budget_tracker = ErrorBudgetTracker()
# 4. Process Governance
governed_urls = engine.apply_governance(mock_urls)
# 5. Record Metrics for Dashboard
budget_tracker.record_batch(governed_urls)
# 6. Partition and Write
index_file = partitioner.partition_and_write(governed_urls)
# 7. Ping Automation
pinger = PingAutomator("https://example.com/sitemaps/sitemap_index.xml")
pinger.notify_all()
# 8. Render Dashboard
DashboardVisualizer.generate_report(partitioner, engine, budget_tracker, governed_urls)
if __name__ == "__main__":
run_demo()