# Tech Demo: Backend Code Reviewer Skill (DSA)

An automated code analysis rule engine designed for enterprise backend systems. This utility intercepts structural anti-patterns, performance bottlenecks, architectural drift, and security hazards within the developer's local CLI or continuous integration workflows (PR Gates). It focuses on universal architectural concepts independent of any single programming language or framework.

---

## Rule Engine & Scope (Expanded & Language-Agnostic)

### 1. Database & Persistence Performance
*   **The N+1 Query Problem:** Intercepts database fetch execution inside loop structures (`for`, `foreach`, `while`) caused by missing eager loading, joins, or batching mechanisms (e.g., EF Core, Hibernate, Prisma, TypeORM, SQLAlchemy).
*   **Unindexed Queries on Filtered Columns:** Flags queries filtering, joining, or sorting (`WHERE`, `JOIN`, `GROUP BY`, `ORDER BY`) by database columns that do not have an explicitly defined index.
*   **Missing Read-Only Optimization (No-Tracking/Read-Replica):** Identifies read-only API endpoints or service queries fetching records without bypassing persistence tracking or memory allocation overhead (e.g., missing `.AsNoTracking()` or not using a read-replica context).
*   **Unbounded Result Sets (Missing Pagination):** Flags database queries executing select statements without explicit limits (`LIMIT`, `TAKE`), risking system out-of-memory errors as data grows.
*   **In-Memory/Client-Side Evaluation:** Detects queries mapping complex application-layer code or custom functions inside data queries, forcing the application layer to stream the entire table data into memory to perform filtering.

### 2. Concurrency, Async, & Resource Control
*   **Dangling / Unawaited Async Executions:** Detects methods declared asynchronous but missing the proper synchronization or orchestration keywords (e.g., missing `await`, `yield`), causing accidental fire-and-forget loops or orphaned threads.
*   **Missing Request/Context Propagation (Cancellation Tokens):** Scans execution paths and flags missing propagation of context timers or cancellation tokens down to HTTP clients or database drivers, preventing resource leakage on disconnected client requests.
*   **Sync-Over-Async & Thread Blocking:** Catches asynchronous calls forced to run synchronously (e.g., using `.Result`, `.get()`, or blocking execution primitives), risking thread-pool starvation and application deadlocks under load.

### 3. Reliability & Error Resiliency
*   **Swallowed & Blind Exceptions:** Flags empty error handling catch blocks (`catch {}`, `except:`) or rethrowing structures that reset the call-stack trace, destroying operational context.
*   **Missing Network/Database Retry Policies:** Checks if outbound network requests (HTTP client calls) or core database configurations lack circuit breakers or back-off retry logic to handle transient cloud infrastructure faults.

### 4. Security & Compliance
*   **Hardcoded Secrets & Token Entropy:** Scans configuration files (`.json`, `.yml`, `.env`) and application code for hardcoded secrets, connection strings, API private keys, or raw crypto tokens using entropy-based scanner algorithms.
*   **Dynamic Command/SQL Injections:** Flags arbitrary execution lines dynamically concatenating external inputs directly into SQL queries, shell arguments, or OS command strings instead of enforcing parameterized boundaries.

### 5. Architectural Boundaries & State
*   **Stateful Components in Stateless Environments:** Identifies shared mutable state (e.g., non-thread-safe global variables, in-memory singleton caches) within request scopes, breaking safety guidelines across horizontally scaled instances.
*   **Database Migrations Without Structural Rollbacks:** Validates that structural schema migrations require a clear reverse/down fallback script instead of missing routines, allowing deployments to roll back safely during live failures.
*   **Domain Entity Leaking (API Layer):** Flags internal data models or database entity classes directly serving as API response data contracts, breaking abstraction barriers and risking unintended data exposure.

---

## Platforms & Pipeline Integrations

### Generic CLI Command (Local Development)
Developers can trigger this utility locally inside any language stack runtime using native container or package binary executors before opening a pull request.

```bash
# Run the agnostic architectural scanner locally against the workspace directory
dsa-reviewer analyze --directory ./src/backend --ruleset standard-backend --fail-on critical
```

### GitHub Actions Workflow (`.github/workflows/backend-review.yml`)
Blocks integration into main branches if any critical rule violation is detected during a Pull Request.

```yaml
name: Universal Backend PR Gate (DSA)

on:
  pull_request:
    branches: [ main, develop ]
    paths:
      - 'src/**'

jobs:
  review:
    name: Architecture & Pattern Analysis
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Install DSA Reviewer CLI
        run: curl -sSL https://dsa-reviewer.dev | sh

      - name: Execute Pull Request Quality Gates
        run: |
          dsa-reviewer analyze \
            --directory ./src \
            --engine rules/backend.json \
            --output github-pr-annotations
```

### GitLab CI/CD Pipeline (`.gitlab-ci.yml`)
Integrates natively with GitLab's Code Quality dashboard widget via code-climate formatting report artifacts.

```yaml
stages:
  - quality

backend_review_job:
  stage: quality
  image: dsa/reviewer-engine:latest
  only:
    - merge_requests
  script:
    - dsa-reviewer analyze --directory ./src --output codeclimate > gl-code-quality-report.json
  artifacts:
    name: code-quality-report
    expire_in: 1 week
    reports:
      codequality: gl-code-quality-report.json
```
