# Code-First Visualizations with Structurizr

This directory contains examples of code-first visualization tools using Structurizr DSL (Domain Specific Language).

## Structurizr Diagrams

Structurizr is a tool for creating software architecture diagrams based on the C4 model (Context, Containers, Components, and Code). It allows you to create diagrams as code using a simple DSL.

### System Context Diagram Example

```structurizr
workspace {
    model {
        user = person "User" "A user of the system"
        
        softwareSystem = softwareSystem "Software System" "The main software system" {
            webApp = container "Web Application" "Delivers content to users" "React"
            api = container "API" "Provides functionality via JSON/REST API" "Node.js"
            database = container "Database" "Stores user data" "PostgreSQL"
            cache = container "Cache" "Caches frequently accessed data" "Redis"
        }
        
        emailSystem = softwareSystem "Email System" "External email service" "External"
        
        user -> webApp "Uses" "HTTPS"
        webApp -> api "Makes API calls to" "JSON/HTTPS"
        api -> database "Reads from and writes to" "TCP/IP"
        api -> cache "Reads from and writes to" "TCP/IP"
        api -> emailSystem "Sends emails using" "SMTP"
    }
    
    views {
        systemContext softwareSystem "SystemContext" {
            include *
            autoLayout
        }
        
        container softwareSystem "Containers" {
            include *
            autoLayout
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
                color #000000
            }
            element "Software System" {
                background #1E90FF
                color #ffffff
            }
            element "Container" {
                background #E6F3FF
                color #000000
            }
            element "External" {
                background #999999
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Enterprise Context Example

```structurizr
workspace "Enterprise Architecture" {
    model {
        customer = person "Customer" "A customer of the company"
        employee = person "Employee" "An employee of the company"
        admin = person "Administrator" "System administrator"
        
        group "Tech Company" {
            crm = softwareSystem "CRM System" "Manages customer relationships"
            erp = softwareSystem "ERP System" "Manages business processes"
            analytics = softwareSystem "Analytics Platform" "Provides business insights"
        }
        
        paymentGateway = softwareSystem "Payment Gateway" "Processes payments" "External"
        cloudStorage = softwareSystem "Cloud Storage" "Stores files" "External"
        
        customer -> crm "Interacts with"
        employee -> erp "Uses"
        admin -> analytics "Configures"
        
        crm -> paymentGateway "Processes payments via"
        erp -> cloudStorage "Stores documents in"
        analytics -> crm "Reads data from"
        analytics -> erp "Reads data from"
    }
    
    views {
        systemLandscape "SystemLandscape" {
            include *
            autoLayout
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
                color #000000
            }
            element "Software System" {
                background #1E90FF
                color #ffffff
            }
            element "External" {
                background #999999
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Component Diagram Example

```structurizr
workspace {
    model {
        user = person "User"
        
        webApp = softwareSystem "Web Application" {
            spa = container "Single-Page App" "React application" "React" {
                authComponent = component "Authentication" "Handles user login/logout"
                dashboardComponent = component "Dashboard" "Main user interface"
                settingsComponent = component "Settings" "User preferences"
            }
            
            apiGateway = container "API Gateway" "Routes requests" "Express.js" {
                routerComponent = component "Router" "Routes HTTP requests"
                authMiddleware = component "Auth Middleware" "Validates tokens"
                rateLimiter = component "Rate Limiter" "Limits request rate"
            }
            
            authService = container "Auth Service" "Handles authentication" "Node.js" {
                loginController = component "Login Controller"
                tokenService = component "Token Service"
                userRepository = component "User Repository"
            }
            
            database = container "Database" "PostgreSQL"
        }
        
        user -> spa "Uses"
        spa -> apiGateway "Makes API calls"
        apiGateway -> authService "Authenticates via"
        authService -> database "Reads/writes"
        
        authComponent -> routerComponent "Calls"
        dashboardComponent -> routerComponent "Calls"
        routerComponent -> authMiddleware "Uses"
        routerComponent -> rateLimiter "Uses"
        authMiddleware -> loginController "Validates with"
        loginController -> tokenService "Uses"
        loginController -> userRepository "Queries"
        userRepository -> database "Reads from"
    }
    
    views {
        component spa "SPAComponents" {
            include *
            autoLayout
        }
        
        component apiGateway "APIComponents" {
            include *
            autoLayout
        }
        
        component authService "AuthComponents" {
            include *
            autoLayout
        }
        
        styles {
            element "Container" {
                background #E6F3FF
                color #000000
            }
            element "Component" {
                background #1E90FF
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Deployment Diagram Example

```structurizr
workspace {
    model {
        user = person "User"
        
        webApp = softwareSystem "Web Application" {
            spa = container "Single-Page App" "React"
            api = container "API" "Node.js"
            database = container "Database" "PostgreSQL"
        }
        
        production = deploymentEnvironment "Production" {
            deploymentNode "Amazon Web Services" {
                deploymentNode "US-East-1" {
                    route53 = infrastructureNode "Route 53" "DNS service"
                    
                    deploymentNode "CloudFront CDN" {
                        cdnInstance = infrastructureNode "CDN" "Content delivery"
                    }
                    
                    deploymentNode "EC2" {
                        deploymentNode "Web Server" {
                            webServerInstance = infrastructureNode "Nginx"
                            spaInstance = containerInstance spa
                        }
                        
                        deploymentNode "API Server" {
                            apiInstance = containerInstance api
                        }
                    }
                    
                    deploymentNode "RDS" {
                        databaseInstance = containerInstance database
                    }
                    
                    s3 = infrastructureNode "S3" "Object storage"
                }
            }
        }
    }
    
    views {
        deployment webApp production "ProductionDeployment" {
            include *
            autoLayout
        }
        
        styles {
            element "Infrastructure Node" {
                shape roundedbox
                background #999999
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Dynamic Diagram Example (User Registration Flow)

```structurizr
workspace {
    model {
        user = person "User"
        
        system = softwareSystem "Royalty System" {
            frontEnd = container "FrontEnd Royalties" "React"
            graphqlApi = container "GraphQL API" "Node.js"
            db = container "Database" "PostgreSQL"
        }
        
        user -> frontEnd "Click button"
        frontEnd -> graphqlApi "POST /api/data"
        graphqlApi -> db "Query data"
        db -> graphqlApi "Return results"
        graphqlApi -> frontEnd "JSON response"
        frontEnd -> user "Display results"
    }
    
    views {
        dynamic system "DataQuery" "User data query flow" {
            user -> frontEnd "1. Click button"
            frontEnd -> graphqlApi "2. POST /api/data"
            graphqlApi -> db "3. Query data"
            db -> graphqlApi "4. Return results"
            graphqlApi -> frontEnd "5. JSON response"
            frontEnd -> user "6. Display results"
            autoLayout
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
            }
            element "Container" {
                background #1E90FF
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Entity Relationship Diagram Example

Note: Structurizr doesn't have a dedicated ERD diagram type as it focuses on the C4 model. However, we can model the same data architecture using containers to represent database entities and their relationships.

```structurizr
workspace "Data Model" {
    model {
        dataSystem = softwareSystem "Royalty Data System" "Manages accounts, contracts, products and transactions" {
            account = container "Account" "Account entity" "Database Table" {
                description "Stores account information including account_id, name, email, phone"
            }
            
            contract = container "Contract" "Contract entity" "Database Table" {
                description "Stores contract information including contract_id, name, status"
            }
            
            contractLifecycle = container "Contract Lifecycle" "Contract lifecycle entity" "Database Table" {
                description "Stores lifecycle data including contract_lifecycle_id, start_date, end_date"
            }
            
            product = container "Product" "Product entity" "Database Table" {
                description "Stores product data including product_id, upc_code, isrc, description"
            }
            
            saleTransaction = container "Sale Transaction" "Transaction entity" "Database Table" {
                description "Stores transaction data including txn_id, currency, store_id, amount, meom"
            }
        }
        
        account -> contract "has many" "One-to-Many"
        contract -> contractLifecycle "contains" "One-to-Many"
        product -> contract "includes" "Many-to-Many"
        product -> saleTransaction "generates" "One-to-Many"
    }
    
    views {
        container dataSystem "DataModel" {
            include *
            autoLayout
        }
        
        styles {
            element "Database Table" {
                shape cylinder
                background #E6F3FF
                color #000000
            }
            relationship "One-to-Many" {
                color #1E90FF
                thickness 2
            }
            relationship "Many-to-Many" {
                color #1E90FF
                thickness 2
                style dashed
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

### Organization Structure Example (C4 Model)

```structurizr
workspace "Organization Chart" {
    model {
        enterprise "Tech Company" {
            ceo = person "Alice Johnson" "CEO & Chairman"
            coo = person "Michael Chen" "COO"
            cto = person "Sarah Martinez" "CTO"
            
            vpProduct = person "David Williams" "VP of Product"
            svpEng1 = person "Emma Davis" "SVP Engineering"
            
            dirProduct = person "James Anderson" "Director of Product"
            vpEng = person "Sofia Rodriguez" "VP Engineering"
            svpEng2 = person "Marcus Thompson" "SVP Engineering"
            
            # Relationships represent reporting structure
            ceo -> coo "Manages"
            coo -> cto "Manages"
            cto -> vpProduct "Manages"
            cto -> svpEng1 "Manages"
            vpProduct -> dirProduct "Manages"
            svpEng1 -> vpEng "Manages"
            svpEng1 -> svpEng2 "Manages"
        }
    }
    
    views {
        systemLandscape "OrgChart" {
            include *
            autoLayout tb
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
                color #000000
                fontSize 20
            }
            relationship "Relationship" {
                color #1E90FF
                thickness 2
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

## Benefits of Structurizr

- **C4 Model**: Built specifically for the C4 model (Context, Containers, Components, Code)
- **Multiple Views**: Create different views from a single model
- **Deployment Diagrams**: First-class support for deployment and infrastructure
- **Dynamic Diagrams**: Show sequence of interactions over time
- **Version Control**: Text-based DSL can be versioned in Git
- **Automatic Layout**: Auto-layout feature for quick diagram creation
- **Workspace as Code**: Define entire architecture as code
- **Documentation**: Link diagrams to documentation
- **Team Collaboration**: Share workspaces with your team
- **Export Options**: Export to PlantUML, Mermaid, or images

## Rendering Structurizr

There are several ways to render Structurizr diagrams:

### 1. Structurizr Cloud (SaaS)
- **URL**: https://structurizr.com
- **Free Tier**: Available for public workspaces
- **Paid Plans**: For private workspaces and teams

### 2. Structurizr Lite (Self-Hosted)
```bash
# Run locally with Docker
docker run -it --rm -p 8080:8080 \
  -v $(pwd):/usr/local/structurizr \
  structurizr/lite
```

Then open http://localhost:8080 and place your `.dsl` files in the mounted directory.

### 3. Structurizr CLI
```bash
# Install via npm
npm install -g @structurizr/cli

# Export to PlantUML
structurizr export -workspace workspace.dsl -format plantuml

# Export to Mermaid
structurizr export -workspace workspace.dsl -format mermaid

# Export to PNG
structurizr export -workspace workspace.dsl -format png
```

### 4. Structurizr Site Generatr
Generate a static HTML site from your workspace:
```bash
docker run -it --rm \
  -v $(pwd):/usr/local/structurizr \
  structurizr/site-generatr
```

### 5. IDE Extensions
- **VS Code**: Structurizr DSL extension with live preview
- **IntelliJ IDEA**: Structurizr plugin

## Example Workflow

1. **Create your architecture** as code in a `.dsl` file
2. **Version control** the DSL file in Git
3. **Render locally** using Structurizr Lite during development
4. **Export to images** for documentation or presentations
5. **Share workspace** with team via Structurizr Cloud or self-hosted instance
6. **Update diagrams** by editing the DSL file and committing changes

## Comparison with Other Tools

| Feature | Structurizr | PlantUML | Mermaid |
|---------|-------------|----------|---------|
| C4 Model Support | ✅ Native | ⚠️ Manual | ⚠️ Manual |
| Multiple Views from One Model | ✅ Yes | ❌ No | ❌ No |
| Deployment Diagrams | ✅ First-class | ✅ Yes | ❌ Limited |
| Dynamic/Sequence | ✅ Yes | ✅ Yes | ✅ Yes |
| GitHub Native Rendering | ❌ No | ❌ No | ✅ Yes |
| Auto Layout | ✅ Yes | ⚠️ Limited | ✅ Yes |
| Learning Curve | Medium | Medium | Low |
| Export Options | ✅ Many | ✅ Many | ⚠️ Limited |

## Resources

- **Official Site**: https://structurizr.com
- **Documentation**: https://docs.structurizr.com
- **DSL Reference**: https://github.com/structurizr/dsl
- **Examples**: https://structurizr.com/share
- **C4 Model**: https://c4model.com
