Build a robots.txt policy engine: environment segregation, disallow patterns QA, sitemap…
- User
Build a robots.txt policy engine: environment segregation, disallow patterns QA, sitemap pointers, testing sandboxes, and rollout approvals.
Assistant
Build a robots.txt policy engine: environment segregation, disallow patterns QA, sitemap pointers, testing sandboxes, and rollout approvals.
The user wants to build a "robots.txt policy engine." This implies a system or software architecture design, not just a simple static file. The request lists specific features:
Sitemap: directives.This sounds like a request for a high-level design, architecture, or a code implementation outline (likely Python/Go/Node) for a service that generates and manages robots.txt files across a fleet of websites or environments.
I will structure the response as a comprehensive design document and code prototype.
Core Concept:
Instead of editing raw text files on servers, users define policies (intent) in a database or configuration files. An engine compiles these into valid robots.txt files and deploys them via a pipeline.
Key Components:
example.com/sandbox/robots.txt that shows the proposed changes.Implementation Plan (Python Example): I'll use Python because it's readable and great for text processing.
Disallow: / on prod).Detailed Breakdown of Requirements:
Environment Segregation:
default_rules vs production_rules.Disallow: /. If env == 'prod', use specific paths.Disallow Patterns QA:
Sitemap pointers:
Sitemap: https://{domain}/sitemap.xml.Testing Sandboxes:
Rollout Approvals:
Structure of the Output:
Let's refine the Python code.
RobotsPolicyEngine.compile(env, domain).validate(content).fr-string or template for generation.Let's refine the Validation/QA.
Let's refine the Sandbox.
Let's refine Rollout.
Self-Correction/Refinement: The user might want a literal engine (code) or a conceptual design. Given the specific features ("engine"), code is better. I will provide a modular Python implementation that represents the backend logic of such a system.
I should emphasize Infrastructure as Code (IaC) approach.
Plan:
Let's write the code mentally.
policy = {
"global": {"crawl_delay": 10},
"staging": {"disallow_all": True},
"production": {"disallow": ["/admin", "/search"], "sitemap": "/sitemap.xml"}
}
This looks good.
Double check the "Rollout Approvals" requirement. Since this is code, "Approvals" usually happen in the version control system (VCS). I will explicitly mention using GitOps (Pull Requests) as the approval mechanism.
Final check on "Testing Sandboxes".
This implies a way to view the generated file before it goes live. I will suggest a CLI tool command: policy_engine build --env=prod --dry-run.
The response should be professional, structured, and provide actionable code/pseudo-code.
This is a design specification and implementation for a Robots.txt Policy Engine. This system moves away from static text files and treats robots.txt as a code object that requires compilation, validation, and deployment workflows.
We will implement this using an Infrastructure-as-Code (IaC) approach.
robots.txt strings.Instead of editing raw text, developers edit policies.yaml. This allows us to add metadata (like descriptions or expiry dates) that won't appear in the final file but help with governance.
# policies.yaml
global_settings:
crawl_delay: 10
sitemaps:
- "https://{env_domain}/sitemap.xml"
user_agents:
- name: "*"
rules:
- type: allow
path: /public/
- type: disallow
path: /api/
description: "Prevent indexing internal JSON endpoints"
- name: "Googlebot"
rules:
- type: disallow
path: /search
qa_check: "Ensure parameterized URLs aren't blocked in Prod"
# Environment Specific Overrides
environments:
staging:
global_disallow: "/" # Block everything by default on non-prod
append_rules:
- user_agent: "*"
type: disallow
path: "/"
production:
# Inherits only user_agents defined above
The engine compiles the YAML into the final text file based on the target environment.
engine.py
import yaml
class RobotsPolicyEngine:
def __init__(self, config_path):
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
self.environments = self.config.get('environments', {})
self.global_settings = self.config.get('global_settings', {})
self.user_agents = self.config.get('user_agents', [])
def compile(self, environment, domain):
"""
Generates the robots.txt content for a specific environment.
"""
lines = []
# 1. Environment Segregation (Global Lockdown for Non-Prod)
env_config = self.environments.get(environment, {})
if env_config.get('global_disallow'):
lines.append(f"User-agent: *")
lines.append(f"Disallow: {env_config['global_disallow']}")
lines.append("") # Newline
# 2. Process User Agent Rules
for agent in self.user_agents:
lines.append(f"User-agent: {agent['name']}")
for rule in agent['rules']:
directive = rule['type'].capitalize()
lines.append(f"{directive}: {rule['path']}")
if self.global_settings.get('crawl_delay'):
lines.append(f"Crawl-delay: {self.global_settings['crawl_delay']}")
lines.append("") # Newline separation
# 3. Sitemap Pointers (Dynamic Domain injection)
sitemaps = self.global_settings.get('sitemaps', [])
for sitemap in sitemaps:
# Replace placeholder with actual domain
url = sitemap.replace("{env_domain}", domain)
lines.append(f"Sitemap: {url}")
return "\n".join(lines)
def validate(self, content):
"""
QA Patterns: Ensure we aren't blocking critical assets accidentally.
"""
# Simple check: Ensure CSS/JS are allowed (Google rendering requirement)
if "Disallow: /assets/" in content or "Disallow: *.css" in content:
raise ValueError("QA FAIL: Blocking CSS/JS assets prevents Google rendering.")
# Check for conflicting rules (simplified logic)
if "Disallow: /" in content and "Allow: /" in content:
print("Warning: Mixed Allow/Disallow root rules detected.")
return True
Before deployment, the engine runs a "Dry Run" or Sandbox test. This generates the file locally and runs logic checks against it.
qa_validator.py
def run_qa_checks(compiled_content):
print("--- Running QA Sandbox Tests ---")
# Test 1: Pattern Logic
# Ensure we don't have overlapping regex that accidentally blocks the homepage
if "Disallow: /$" in compiled_content and "Allow: /" not in compiled_content:
print("CRITICAL: Homepage is explicitly blocked.")
return False
# Test 2: Asset Blocking
critical_assets = [".css", ".js", "/images/", "/static/"]
for asset in critical_assets:
# This is a naive check; real implementation would parse the file structure
if f"Disallow: {asset}" in compiled_content:
print(f"WARNING: Critical asset folder {asset} is blocked.")
# Test 3: Sitemap Presence
if "Sitemap:" not in compiled_content:
print("WARNING: No sitemap defined in policy.")
print("--- QA Complete ---")
return True
We control environment segregation and approvals using a CI/CD pipeline (e.g., GitHub Actions).
The Workflow Logic:
main triggers a build. The engine compiles with environment=staging. No approval needed. It deploys to dev.mysite.com/robots.txt.ci_pipeline.yaml (Conceptual GitHub Actions)
name: Deploy Robots Policy
on:
push:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.9
- name: Compile Staging Policy
run: |
python engine.py compile --env=staging --domain=staging.mysite.com --output=staging_robots.txt
- name: Run QA Sandbox
run: |
python qa_validator.py --file=staging_robots.txt
- name: Deploy to Staging
run: |
# AWS S3 upload example
aws s3 cp staging_robots.txt s3://my-staging-bucket/robots.txt
deploy-production:
needs: build-and-deploy
runs-on: ubuntu-latest
environment: Production # This creates the 'Rollout Approval' gate in GitHub UI
steps:
- name: Compile Production Policy
run: |
python engine.py compile --env=production --domain=www.mysite.com --output=prod_robots.txt
- name: Deploy to Production
run: |
aws s3 cp prod_robots.txt s3://my-prod-bucket/robots.txt
policies.yaml. We can explicitly global_disallow: / for staging/qa environments while leaving production open.qa_validator.py script runs logic checks (e.g., "Are we blocking CSS?") before the file is written.global_settings with dynamic domain injection, ensuring staging.mysite.com doesn't accidentally point to www.mysite.com sitemaps.compile command can be run locally or in a PR check to output the text file to stdout for visual inspection without deploying.