diff --git a/.env.example b/.env.example index 574ea81..eb24893 100644 --- a/.env.example +++ b/.env.example @@ -9,26 +9,24 @@ FLASK_ENV=development SECRET_KEY=change-me-to-a-random-string # --- Service ports (local mode) --- -MONOLITH_PORT=6000 -USER_SERVICE_PORT=5001 -PRODUCT_SERVICE_PORT=5002 -ORDER_SERVICE_PORT=5003 -BFF_PORT=8000 -FRONTEND_PORT=5173 +# Defaults live in scripts/service_table.py. Offset from the parent project +# (5001-5003, 8000, 5173) so both projects can run at the same time. +USER_SERVICE_PORT=5101 +CATALOG_SERVICE_PORT=5102 +ORDER_SERVICE_PORT=5103 +GATEWAY_PORT=8100 +FRONTEND_PORT=5273 -# --- Service base URLs (used by the BFF and by services calling each other) --- -MONOLITH_BASE_URL=http://127.0.0.1:6000 -USER_SERVICE_BASE_URL=http://127.0.0.1:5001 -PRODUCT_SERVICE_BASE_URL=http://127.0.0.1:5002 -ORDER_SERVICE_BASE_URL=http://127.0.0.1:5003 +# --- Service base URLs (used by the gateway and by services calling each other) --- +USER_SERVICE_BASE_URL=http://127.0.0.1:5101 +CATALOG_SERVICE_BASE_URL=http://127.0.0.1:5102 +ORDER_SERVICE_BASE_URL=http://127.0.0.1:5103 # --- SQLite (local mode, default) --- -# Optional overrides — each path is relative to that service's own directory -# (e.g. MONOLITH_DB_PATH is relative to monolith/). Leave unset to use the -# built-in default of instance/.sqlite3 inside each service folder. -# MONOLITH_DB_PATH=instance/monolith.sqlite3 +# Optional overrides — each path is relative to that service's own directory. +# Leave unset to use instance/.sqlite3 inside each service folder. # USER_DB_PATH=instance/user.sqlite3 -# PRODUCT_DB_PATH=instance/product.sqlite3 +# CATALOG_DB_PATH=instance/catalog.sqlite3 # ORDER_DB_PATH=instance/order.sqlite3 # --- Azure Database for MySQL Flexible Server (azure mode only) --- diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b24f362..48e41ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest strategy: fail-fast: false - # Each suite gets its own install: monolith/app, bff/app and every + # Each suite gets its own install: gateway/app and every # service's config.py share top-level module names, so they cannot # run in one interpreter (see CLAUDE.md, "collision note"). matrix: @@ -21,18 +21,18 @@ jobs: - suite: repo-root requirements: requirements-dev.txt tests: tests/unit - - suite: bff - requirements: bff/requirements.txt - tests: bff/tests - - suite: user-service - requirements: microservices/user-service/requirements.txt - tests: microservices/user-service/tests - - suite: product-service - requirements: microservices/product-service/requirements.txt - tests: microservices/product-service/tests - - suite: order-service - requirements: microservices/order-service/requirements.txt - tests: microservices/order-service/tests + - suite: gateway + requirements: gateway/requirements.txt + tests: gateway/tests + - suite: user + requirements: services/user/requirements.txt + tests: services/user/tests + - suite: catalog + requirements: services/catalog/requirements.txt + tests: services/catalog/tests + - suite: order + requirements: services/order/requirements.txt + tests: services/order/tests steps: - uses: actions/checkout@v4 diff --git a/CLAUDE.md b/CLAUDE.md index ddeb67c..faef0a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,25 +27,34 @@ history, monolith dropped). The full agreed plan is in [`docs/PLAN.md`](docs/PLA - Name prefix: `ms12p` (parent uses `flaskms`). Teardown deletes the whole resource group, so a shared name would delete the other project. -## Current state (M0) -The code is still the parent project's microservices + BFF + frontend, with the monolith -removed from setup, tests and CI only. Remaining monolith references in `bff/`, `frontend/`, -`scripts/run_local.py`, `scripts/benchmark.py` and `infra/` are replaced in M1, when `bff/` -becomes `gateway/`, services move to `services//`, and ports move to the new range -(gateway 8100, registry 8500, services 5101-5105, frontend 5273). +## Current state (M1a, layout) +- Folders: `services/{user,catalog,order}/` (Flask, one DB each), `gateway/` (FastAPI), + `frontend/`, `infra/`, `scripts/`, `tests/`. The monolith and the old migration engine are gone. +- **One service table**: `scripts/service_table.py` lists every local process, folder and port. + `setup.py`, `run_local.py`, `provision.py` and the smoke tests all read it. Add a service there. +- Ports: user 5101, catalog 5102, order 5103, gateway 8100, frontend 5273 (registry 8500 and + payment/inventory 5104-5105 arrive in later milestones). +- Gateway routes `/api/shop/` to `/api/` on the owning service by first path segment + (`gateway/app/config.py` `ROUTE_OWNERS`). No auth or aggregation yet (M1). +- The catalog service keeps the `product` resource name in its API (`/api/product(s)`) and its + `product_api` package. Only the service, its env vars (`CATALOG_*`) and its DB (`catalog_db`) are + named catalog. +- Azure: one Container App per service plus the gateway, all external ingress, images built with + `az acr build --platform linux/amd64`. ## Stack Python 3.12 (Flask 3.1 services, FastAPI gateway), Node 18+ (React 18, TypeScript 5, Vite 5), SQLite locally, Azure MySQL Flexible Server (one server, one DB per service) in Azure. ## Collision note (inherited) -Every Flask service has a top-level `config.py`/`application` package and the BFF has `app`. -Each runs in its own venv. `tests/conftest.py` adds only `infra/`, `scripts/`, `bff/` to +Every Flask service has a top-level `config.py`/`application` package and the gateway has `app`. +Each runs in its own venv. `tests/conftest.py` adds only `infra/`, `scripts/`, `gateway/` to `sys.path`. M1 fixes this with a shared `shop_common` package. ## How to run ```bash make setup # venvs per service + frontend npm deps, no Docker +make run # every service + gateway + frontend, health-gated make test # unit tests, each suite in its own venv make smoke # phased smoke tests, skip gracefully when not applicable ``` diff --git a/Makefile b/Makefile index a836f90..ad5d368 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: setup run run-all provision pause resume teardown verify test smoke benchmark clean +.PHONY: setup run provision pause resume teardown verify test smoke clean setup: python3.12 scripts/setup.py @@ -6,9 +6,6 @@ setup: run: python3.12 scripts/run_local.py -run-all: - python3.12 scripts/run_local.py --all - provision: python3.12 infra/provision.py --budget-email "$(BUDGET_EMAIL)" $(ARGS) @@ -26,17 +23,14 @@ verify: test: .venv/bin/python -m pytest tests/unit -v - microservices/user-service/.venv/bin/python -m pytest microservices/user-service/tests -v - microservices/product-service/.venv/bin/python -m pytest microservices/product-service/tests -v - microservices/order-service/.venv/bin/python -m pytest microservices/order-service/tests -v - bff/.venv/bin/python -m pytest bff/tests -v + services/user/.venv/bin/python -m pytest services/user/tests -v + services/catalog/.venv/bin/python -m pytest services/catalog/tests -v + services/order/.venv/bin/python -m pytest services/order/tests -v + gateway/.venv/bin/python -m pytest gateway/tests -v smoke: .venv/bin/python -m pytest tests/smoke -v -benchmark: - bff/.venv/bin/python scripts/benchmark.py - clean: find . -name "instance" -type d -exec rm -rf {} + 2>/dev/null || true find . -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true diff --git a/README.md b/README.md index 991b773..48d3865 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A small Contoso e-commerce system that shows **12 microservices patterns working Each pattern gets its own page with an explanation, when *not* to use it, and a live demo you can click. -> **Status: M0, bootstrap.** The foundation is copied from +> **Status: M1a, layout.** Three services, a gateway and the frontend run end to end. The foundation is copied from > [Azure-Ecommerce-Monolith-Microservices-Migration](https://github.com/MAOFILHO/Azure-Ecommerce-Monolith-Microservices-Migration). > The patterns arrive in 3 milestones. See [docs/PLAN.md](docs/PLAN.md). @@ -38,6 +38,7 @@ can click. ```bash make setup +make run # frontend http://127.0.0.1:5273, gateway http://127.0.0.1:8100 make test ``` diff --git a/bff/app/azure_traffic.py b/bff/app/azure_traffic.py deleted file mode 100644 index d40efe6..0000000 --- a/bff/app/azure_traffic.py +++ /dev/null @@ -1,166 +0,0 @@ -"""Real Azure Container Apps orchestration for the 'azure' migration mode. - -This module runs INSIDE the bff Container App once it's deployed to Azure — -it does not read infra/.state.json (that file only ever exists on whichever -machine ran `make provision`, never inside the running container). Instead -every value it needs was injected directly as an env var by -infra/bicep/main.bicep (plain values for non-secrets, secretRef for the ACR -and MySQL passwords), so the container is fully self-describing. - -The microservices' Container Apps (user-, product-, order-service) are -deliberately NOT part of the initial `make provision` deploy — this module -creates each one for real, for the first time, as the live migration reaches -its extraction step for that service. That's the whole "wow" of the demo: -watching real Azure resources appear as you migrate, not a pre-provisioned -stack where migration just flips a switch. - -Uses azure-mgmt-appcontainers + azure-identity (DefaultAzureCredential, which -picks up the bff Container App's own system-assigned managed identity when -running in Azure). provision.py grants that identity Contributor scoped to -just this one resource group. -""" -import asyncio -import os - -from azure.identity import DefaultAzureCredential -from azure.mgmt.appcontainers import ContainerAppsAPIClient -from azure.mgmt.appcontainers.models import ( - Configuration, - Container, - ContainerApp, - ContainerResources, - EnvironmentVar, - Ingress, - RegistryCredentials, - Scale, - Secret, - Template, -) - -STEP_TO_SERVICE = { - "extract_user": ("user-service", 5001), - "extract_product": ("product-service", 5002), - "extract_order_acl": ("order-service", 5003), -} - -_client: ContainerAppsAPIClient | None = None - - -def is_configured() -> bool: - """True once the bff is actually running inside the Azure deployment - (main.bicep injects AZURE_RESOURCE_GROUP) rather than locally, where - 'azure' migration mode has nothing real to do yet.""" - return bool(os.environ.get("AZURE_RESOURCE_GROUP")) - - -def _get_client() -> ContainerAppsAPIClient: - global _client - if _client is None: - _client = ContainerAppsAPIClient(DefaultAzureCredential(), os.environ["AZURE_SUBSCRIPTION_ID"]) - return _client - - -def _create_microservice_container_app(service_name: str, target_port: int) -> str: - """Creates one microservice's Container App for the first time — it - genuinely does not exist before this call. Blocks until the ARM - operation completes (a real 20-60 second operation), so the migration - engine's SSE-driven step status reflects real progress, not a canned - delay. Returns the app's FQDN.""" - resource_group = os.environ["AZURE_RESOURCE_GROUP"] - default_domain = os.environ["AZURE_CONTAINER_APPS_DEFAULT_DOMAIN"] - client = _get_client() - - env_vars = [ - EnvironmentVar(name="RUN_MODE", value="azure"), - EnvironmentVar(name="AZURE_MYSQL_HOST", value=os.environ["AZURE_MYSQL_HOST"]), - EnvironmentVar(name="AZURE_MYSQL_PORT", value="3306"), - EnvironmentVar(name="AZURE_MYSQL_ADMIN_USER", value=os.environ["AZURE_MYSQL_ADMIN_USER"]), - EnvironmentVar(name="AZURE_MYSQL_ADMIN_PASSWORD", secret_ref="mysql-password"), - ] - if service_name == "order-service": - user_service_fqdn = f"user-service.{default_domain}" - env_vars.append(EnvironmentVar(name="USER_SERVICE_BASE_URL", value=f"https://{user_service_fqdn}")) - - container_app = ContainerApp( - location=os.environ["AZURE_LOCATION"], - managed_environment_id=os.environ["AZURE_CONTAINER_APPS_ENV_ID"], - configuration=Configuration( - secrets=[ - Secret(name="acr-password", value=os.environ["AZURE_ACR_PASSWORD"]), - Secret(name="mysql-password", value=os.environ["AZURE_MYSQL_ADMIN_PASSWORD"]), - ], - ingress=Ingress(external=True, target_port=target_port, transport="auto"), - registries=[ - RegistryCredentials( - server=os.environ["AZURE_ACR_LOGIN_SERVER"], - username=os.environ["AZURE_ACR_NAME"], - password_secret_ref="acr-password", - ) - ], - ), - template=Template( - containers=[ - Container( - name=service_name, - image=f"{os.environ['AZURE_ACR_LOGIN_SERVER']}/{service_name}:latest", - resources=ContainerResources(cpu=0.25, memory="0.5Gi"), - env=env_vars, - ) - ], - scale=Scale(min_replicas=0, max_replicas=3), - ), - ) - - poller = client.container_apps.begin_create_or_update(resource_group, service_name, container_app) - result = poller.result() - return result.configuration.ingress.fqdn - - -def _scale_container_app(app_name: str, min_replicas: int, max_replicas: int) -> None: - """Scales an existing Container App. Used for the decommission step: the - monolith is retired to 0 replicas, not deleted — mirroring local mode's - 'restart monolith' undo path. - - revisionSuffix is explicitly reset to "" (let Azure auto-generate a new - one) — caught for real: this app had a manually-set suffix from earlier - debugging, and every update PATCH kept resubmitting that same stored - suffix, which fails once a revision with it already exists - (ContainerAppOperationError: 'revision with suffix ... already exists').""" - client = _get_client() - client.container_apps.begin_update( - os.environ["AZURE_RESOURCE_GROUP"], - app_name, - {"properties": {"template": { - "revisionSuffix": "", - "scale": {"minReplicas": min_replicas, "maxReplicas": max_replicas}, - }}}, - ).result() - - -async def scale_monolith(min_replicas: int, max_replicas: int) -> None: - """Public entry point for restart_monolith()'s undo path in - migration_engine.py — scales the monolith Container App back up from 0 - replicas, the inverse of what the decommission step does.""" - await asyncio.to_thread(_scale_container_app, "monolith", min_replicas, max_replicas) - - -async def shift_traffic_for_step(step_id: str) -> tuple[bool, str | None]: - """Returns (ok, new_base_url). new_base_url is set only when this step - just brought a new microservice online, so the caller (migration_engine) - can update its runtime URL registry — the BFF's proxy has nothing to - route to until that happens.""" - if step_id in STEP_TO_SERVICE: - service_name, target_port = STEP_TO_SERVICE[step_id] - fqdn = await asyncio.to_thread(_create_microservice_container_app, service_name, target_port) - return True, f"https://{fqdn}" - - if step_id == "decommission": - # Azure rejects maxReplicas=0 outright (ContainerAppInvalidScaleSpec: - # "MaxReplicas must be greater than 0") — caught for real running this - # migration against Azure. min=0/max=1 still retires it to 0 running - # replicas (nothing serves traffic until scale_monolith() undoes this), - # just within a range Azure accepts. - await asyncio.to_thread(_scale_container_app, "monolith", 0, 1) - return True, None - - return True, None # narrative-only step, nothing to do diff --git a/bff/app/config.py b/bff/app/config.py deleted file mode 100644 index 1680e8c..0000000 --- a/bff/app/config.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Environment-driven settings for the BFF. No secrets/API keys required.""" -import os -from pathlib import Path - -# Path(__file__).resolve().parents[2] gives the repo root when running from a -# checkout (bff/app/config.py -> bff -> repo root), but the Docker image -# flattens bff/'s own contents onto WORKDIR /app, one level shallower -# (/app/app/config.py -> /app, not the repo root) — REPO_ROOT_OVERRIDE lets -# the Dockerfile say explicitly what "repo root" means inside the container -# instead of relying on fragile parent-count arithmetic. -REPO_ROOT = ( - Path(os.environ["REPO_ROOT_OVERRIDE"]) - if os.environ.get("REPO_ROOT_OVERRIDE") - else Path(__file__).resolve().parents[2] -) - -RUN_MODE = os.environ.get("RUN_MODE", "local") - -MONOLITH_BASE_URL = os.environ.get("MONOLITH_BASE_URL", "http://127.0.0.1:6000") -USER_SERVICE_BASE_URL = os.environ.get("USER_SERVICE_BASE_URL", "http://127.0.0.1:5001") -PRODUCT_SERVICE_BASE_URL = os.environ.get("PRODUCT_SERVICE_BASE_URL", "http://127.0.0.1:5002") -ORDER_SERVICE_BASE_URL = os.environ.get("ORDER_SERVICE_BASE_URL", "http://127.0.0.1:5003") - -MONOLITH_PORT = int(os.environ.get("MONOLITH_PORT", 6000)) -USER_SERVICE_PORT = int(os.environ.get("USER_SERVICE_PORT", 5001)) -PRODUCT_SERVICE_PORT = int(os.environ.get("PRODUCT_SERVICE_PORT", 5002)) -ORDER_SERVICE_PORT = int(os.environ.get("ORDER_SERVICE_PORT", 5003)) - -FRONTEND_ORIGIN = os.environ.get("FRONTEND_ORIGIN", "http://127.0.0.1:5173") - -# Browsers treat 'localhost' and '127.0.0.1' as different origins for CORS -# purposes even though they resolve to the same machine. Vite's dev server -# binds to both (host: true), so a user visiting via either hostname must -# both be allowed — otherwise the browser blocks the BFF's response and -# fetch() fails with a generic "TypeError: Failed to fetch" that gives no -# hint it was a CORS issue. If FRONTEND_ORIGIN is overridden (e.g. for an -# Azure Static Web Apps hostname), only that exact origin is allowed. -if "FRONTEND_ORIGIN" in os.environ: - FRONTEND_ORIGINS = [FRONTEND_ORIGIN] -else: - _port = FRONTEND_ORIGIN.rsplit(":", 1)[-1] - FRONTEND_ORIGINS = [f"http://127.0.0.1:{_port}", f"http://localhost:{_port}"] - -RESULTS_DIR = REPO_ROOT / "results" -STATE_FILE = REPO_ROOT / "infra" / ".state.json" - -MICROSERVICES_ROOT = REPO_ROOT / "microservices" -MONOLITH_ROOT = REPO_ROOT / "monolith" - -SERVICE_ROUTE_PREFIXES = { - "user": (USER_SERVICE_BASE_URL, MICROSERVICES_ROOT / "user-service", USER_SERVICE_PORT), - "product": (PRODUCT_SERVICE_BASE_URL, MICROSERVICES_ROOT / "product-service", PRODUCT_SERVICE_PORT), - "order": (ORDER_SERVICE_BASE_URL, MICROSERVICES_ROOT / "order-service", ORDER_SERVICE_PORT), -} - -# Mutable — the shop proxy (routers/shop.py) reads from this instead of the -# static constants above. In local mode every backend's URL is already known -# (a fixed localhost port), so this is seeded fully at import time. In azure -# mode the microservices' Container Apps don't exist until the live -# migration creates them (bff/app/azure_traffic.py), so those three start out -# unset and migration_engine.py fills each one in the moment its Container -# App comes online — there is nothing to route to before that. -RUNTIME_BASE_URLS: dict[str, str | None] = { - "monolith": MONOLITH_BASE_URL, - "user": USER_SERVICE_BASE_URL if RUN_MODE == "local" else None, - "product": PRODUCT_SERVICE_BASE_URL if RUN_MODE == "local" else None, - "order": ORDER_SERVICE_BASE_URL if RUN_MODE == "local" else None, -} diff --git a/bff/app/content/learn_content.py b/bff/app/content/learn_content.py deleted file mode 100644 index 146e8bb..0000000 --- a/bff/app/content/learn_content.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Static content for the Learn page, extracted once from the three provided -study guides (Microservices Article.pdf, Senior Python Engineer's Guide to -Microservices Migration.pdf, Modernizing Architectures — Strangler Fig -Pattern.pdf). Not fetched at runtime — this is the source of truth.""" - -LEARN_CONTENT = { - "advantages": [ - { - "title": "Independent scaling", - "body": "Each service is deployed separately and scales horizontally based on its own " - "load profile — e.g. checkout or catalog under heavy traffic — without scaling " - "the whole system and wasting resources on idle components.", - }, - { - "title": "Faster, safer change cycles", - "body": "Teams deploy changes to one service without redeploying the entire system, " - "reducing blast radius and supporting real CI/CD.", - }, - { - "title": "Technology and data autonomy", - "body": "Different services can use different languages, frameworks, and databases " - "optimized for their workload (Polyglot Persistence).", - }, - { - "title": "Organizational alignment (Conway's Law)", - "body": "Software architecture tends to mirror the communication structure of the " - "organization that built it. Small, autonomous 'Two-Pizza Teams' can own a " - "service end-to-end — from creation to maintenance.", - }, - { - "title": "Resilience and fault isolation", - "body": "Failures are often localized to a single service; with retries, timeouts, and " - "circuit breakers, the system degrades gracefully instead of going down entirely.", - }, - ], - "strangler_fig_steps": [ - "Domain Assessment and Slicing — identify coherent business domains using Domain-Driven Design.", - "Introduction of the Proxy Layer — place an API Gateway/BFF in front of the monolith; 100% of traffic still goes to it.", - "Service Extraction — clone a high-value, well-isolated capability into a new independently deployable service.", - "Anti-Corruption Layer (ACL) — an adapter that lets the remaining monolith (or sibling services) call the new service without leaking legacy assumptions.", - "Traffic Redirection — update the proxy to route specific paths to the new microservice.", - "Data Synchronization and Ownership — move relevant data to a service-specific store; use a synchronizing agent if the legacy database still needs it.", - "Decommissioning — repeat extraction until the monolith is a skeleton, then retire it.", - ], - "anti_patterns": { - "technical": [ - {"name": "Shared Persistence", "why": "Multiple services reading/writing the same schema couples them at the data layer and removes team independence."}, - {"name": "Megaservice", "why": "A service that absorbs too many responsibilities becomes a 'mini-monolith'."}, - {"name": "Cyclic Dependency", "why": "A → B → C → A call chains make services impossible to deploy or test in isolation."}, - {"name": "Hardcoded Endpoints", "why": "Hardcoding IPs/ports instead of service discovery breaks the moment topology changes."}, - {"name": "Inappropriate Service Intimacy", "why": "Reaching into another service's private data instead of using its public API."}, - {"name": "Shared Libraries for business logic", "why": "Forces synchronized deployments across services that should be independent."}, - ], - "organizational": [ - {"name": "Microservices as the Goal", "why": "Adopting the architecture for its own sake, not for a concrete scale/velocity need."}, - {"name": "Legacy Organization", "why": "Rigid, siloed Dev/Ops teams and manual release schedules negate most microservices benefits."}, - {"name": "Magic Pixie Dust", "why": "The belief that the architecture alone fixes organizational problems."}, - ], - }, - "glossary": { - "Anti-Corruption Layer (ACL)": "A facade/adapter that translates calls between a legacy system and a new microservice during migration.", - "Bounded Context": "A DDD pattern defining the boundary within which a specific domain model applies.", - "Circuit Breaker": "Returns an immediate failure for an operation likely to fail, preventing cascading resource exhaustion.", - "Distributed Monolith": "Multiple services so tightly coupled they must be deployed/scaled together — the failure mode this migration avoids.", - "Polyglot Persistence": "Using different database technologies per service, matched to its needs.", - "Two-Pizza Team": "An autonomous team small enough to be fed by two pizzas, owning a service end-to-end.", - "Wrong Cuts": "Splitting services along technical layers (presentation vs. data) instead of business capabilities.", - "Synchronizing Agent": "A tactical bridge keeping a new microservice's data consistent with the legacy database during migration.", - }, - "faq": [ - { - "q": "Why not just rewrite the whole thing (\"Big Bang\")?", - "a": "A rewrite delivers no value until the very end and risks losing lost/rediscovered requirements. The Strangler Fig pattern delivers value incrementally and lets the business pause without losing all progress.", - }, - { - "q": "Do we need Kubernetes to do microservices?", - "a": "No — microservices are an architectural style; containers/Kubernetes are a common but not required packaging mechanism. This project itself proves it: it runs as plain Python processes locally and as Azure Container Apps in the cloud.", - }, - { - "q": "When is a monolith the better choice?", - "a": "When simplicity is the priority, domain boundaries aren't well understood yet (avoiding 'Wrong Cuts'), or the application is small enough that distributed-systems overhead outweighs the benefit.", - }, - ], -} diff --git a/bff/app/main.py b/bff/app/main.py deleted file mode 100644 index c75faf6..0000000 --- a/bff/app/main.py +++ /dev/null @@ -1,31 +0,0 @@ -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware - -from . import config -from .routers import learn, metrics, migration, services, shop - -app = FastAPI( - title="Flask Monolith → Microservices Migration BFF", - description="Backend-for-frontend orchestrating the monolith, the three microservices, " - "the live migration engine, benchmark metrics, and Learn page content.", - version="0.1.0", -) - -app.add_middleware( - CORSMiddleware, - allow_origins=config.FRONTEND_ORIGINS, - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -app.include_router(shop.router) -app.include_router(migration.router) -app.include_router(learn.router) -app.include_router(metrics.router) -app.include_router(services.router) - - -@app.get("/health") -async def health(): - return {"status": "ok", "service": "bff"} diff --git a/bff/app/migration_engine.py b/bff/app/migration_engine.py deleted file mode 100644 index 74c1705..0000000 --- a/bff/app/migration_engine.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Drives a REAL strangler-fig migration, not a canned animation. - -local mode: starts/stops the actual local Python subprocesses for each -microservice (and eventually the monolith) as each step completes, polling -their real /health endpoints — the UI reflects genuine process state. - -azure mode: `make provision` stands up only the foundation + monolith + bff. -The three microservices' Container Apps do not exist yet — each extraction -step here CREATES that Container App for the first time via the -azure-mgmt-appcontainers SDK (bff/app/azure_traffic.py), then updates -config.RUNTIME_BASE_URLS so the shop proxy has somewhere to route once that -service is live. If the bff isn't actually running inside the Azure -deployment yet, this mode reports that clearly instead of pretending to do -something. - -Steps mirror the 7-step Strangler Fig framework from the provided study -guides (domain slicing -> proxy layer -> service extraction -> ACL -> -traffic redirection -> data sync -> decommission), compressed into one pass -per real service in this repo. -""" -import asyncio -import subprocess -import sys -import time -from dataclasses import dataclass -from enum import Enum - -import httpx - -from . import config - -try: - import psutil -except ImportError: # psutil is optional; degrade gracefully - psutil = None - - -class StepStatus(str, Enum): - PENDING = "pending" - RUNNING = "running" - DONE = "done" - FAILED = "failed" - - -@dataclass -class Step: - id: str - title: str - description: str - status: StepStatus = StepStatus.PENDING - - -def _default_steps() -> list[Step]: - return [ - Step("assess", "Domain Assessment & Slicing", - "Identify bounded contexts: user accounts, product catalog, and orders. " - "Each becomes a candidate for extraction (Domain-Driven Design)."), - Step("proxy", "Introduce the Proxy Layer", - "The FastAPI BFF now sits between the frontend and the backend. " - "100% of traffic still routes to the monolith."), - Step("extract_user", "Extract user-service", - "Clone auth logic into an independently deployable user-service with its own database."), - Step("redirect_user", "Redirect auth traffic", - "The BFF now routes /api/user* and /api/users to user-service instead of the monolith."), - Step("extract_product", "Extract product-service", - "Clone catalog logic into product-service with its own database."), - Step("redirect_product", "Redirect catalog traffic", - "The BFF now routes /api/product* to product-service."), - Step("extract_order_acl", "Extract order-service + Anti-Corruption Layer", - "order-service owns orders but has no access to the user table — it calls user-service " - "over HTTP (UserClient) instead of joining the old shared schema."), - Step("redirect_order", "Redirect order traffic", - "The BFF now routes /api/order* to order-service. All three domains are now independent."), - Step("decommission", "Decommission the monolith", - "All functionality now lives in the microservices. The monolith process is stopped."), - ] - - -class MigrationEngine: - def __init__(self): - self.steps: list[Step] = _default_steps() - self.active_backend = "monolith" # or "microservices" - self.running = False - self.last_error: str | None = None - - def snapshot(self) -> dict: - return { - "mode": config.RUN_MODE, - "active_backend": self.active_backend, - "running": self.running, - "last_error": self.last_error, - "steps": [ - {"id": s.id, "title": s.title, "description": s.description, "status": s.status.value} - for s in self.steps - ], - } - - def reset(self): - for step in self.steps: - step.status = StepStatus.PENDING - self.active_backend = "monolith" - self.running = False - self.last_error = None - config.RUNTIME_BASE_URLS["monolith"] = config.MONOLITH_BASE_URL - - async def restart_monolith(self) -> bool: - """Undoes the decommission step for real, then resets the whole - migration state so the guided walkthrough can be re-run from scratch. - Without this, clicking 'Start Migration' just to see what happens is - a one-way trip — the monolith stays dead until manually restarted. - Local mode: respawns the actual process. Azure mode: scales the - monolith Container App back up from 0 replicas. Checks health first - so this is a no-op (besides the reset) if it was never actually - stopped.""" - already_up = await self._wait_for_health(config.MONOLITH_BASE_URL, timeout=1.0) - if not already_up: - if config.RUN_MODE == "local": - self._start_service_process(config.MONOLITH_ROOT, "MONOLITH_PORT", config.MONOLITH_PORT) - else: - from . import azure_traffic - - if not azure_traffic.is_configured(): - self.last_error = "Azure mode requires the bff to be running inside the Azure deployment." - return False - await azure_traffic.scale_monolith(1, 3) - already_up = await self._wait_for_health(config.MONOLITH_BASE_URL) - if already_up: - self.reset() - return already_up - - async def _wait_for_health(self, base_url: str, timeout: float = 15.0) -> bool: - deadline = time.monotonic() + timeout - async with httpx.AsyncClient(timeout=2) as client: - while time.monotonic() < deadline: - try: - r = await client.get(f"{base_url}/health") - if r.status_code == 200: - return True - except httpx.HTTPError: - pass - await asyncio.sleep(0.5) - return False - - def _start_service_process(self, service_dir, port_env_var: str, port: int): - venv_python = service_dir / ".venv" / "bin" / "python" - python_bin = str(venv_python) if venv_python.exists() else sys.executable - env = {"RUN_MODE": "local", "FLASK_ENV": "development", port_env_var: str(port)} - import os - full_env = {**os.environ, **env} - subprocess.Popen( - [python_bin, "run.py"], - cwd=str(service_dir), - env=full_env, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - - def _stop_process_on_port(self, port: int) -> bool: - """Finds the process listening on `port` and stops it. Deliberately - iterates psutil.Process(pid).net_connections() per-process rather - than the system-wide psutil.net_connections() — the latter raises - psutil.AccessDenied on macOS without root, which was caught here for - real: the decommission step hung forever in 'running' because that - exception wasn't handled and silently escaped run()'s loop.""" - if psutil is None: - return False - - stopped_any = False - for pid in psutil.pids(): - try: - proc = psutil.Process(pid) - conns = proc.net_connections(kind="inet") - except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): - continue - - if any(c.status == psutil.CONN_LISTEN and c.laddr and c.laddr.port == port for c in conns): - try: - proc.terminate() - proc.wait(timeout=5) - stopped_any = True - except (psutil.NoSuchProcess, psutil.TimeoutExpired): - pass - - return stopped_any - - async def run(self, mode: str): - """Advances self.steps in place. The SSE endpoint (routers/migration.py) - observes progress by polling self.snapshot() — no separate event bus - needed since this is the single source of truth for state.""" - if self.running: - return - - self.running = True - try: - for step in self.steps: - step.status = StepStatus.RUNNING - await asyncio.sleep(0.6) # let the UI show the transition - - try: - ok = await self._execute_step(step, mode) - except Exception as exc: # noqa: BLE001 — any failure must resolve the step, never leave it "running" forever - ok = False - self.last_error = f"Step '{step.id}' raised {type(exc).__name__}: {exc}" - step.status = StepStatus.DONE if ok else StepStatus.FAILED - if not ok: - break - finally: - self.running = False - - async def _execute_step(self, step: Step, mode: str) -> bool: - if step.id == "extract_user": - if mode == "local": - base_url, service_dir, port = config.SERVICE_ROUTE_PREFIXES["user"] - self._start_service_process(service_dir, "USER_SERVICE_PORT", port) - return await self._wait_for_health(base_url) - return await self._azure_step(step, "user") - - if step.id == "extract_product": - if mode == "local": - base_url, service_dir, port = config.SERVICE_ROUTE_PREFIXES["product"] - self._start_service_process(service_dir, "PRODUCT_SERVICE_PORT", port) - return await self._wait_for_health(base_url) - return await self._azure_step(step, "product") - - if step.id == "extract_order_acl": - if mode == "local": - base_url, service_dir, port = config.SERVICE_ROUTE_PREFIXES["order"] - self._start_service_process(service_dir, "ORDER_SERVICE_PORT", port) - return await self._wait_for_health(base_url) - return await self._azure_step(step, "order") - - if step.id in ("redirect_user", "redirect_product"): - return True # BFF routing already dispatches by prefix; nothing to flip physically - - if step.id == "redirect_order": - self.active_backend = "microservices" - return True - - if step.id == "decommission": - if mode == "local": - return self._stop_process_on_port(config.MONOLITH_PORT) or True # ok even if already stopped - ok = await self._azure_step(step, None) - if ok: - config.RUNTIME_BASE_URLS["monolith"] = None - return ok - - return True # assess / proxy steps are narrative-only - - async def _azure_step(self, step: Step, service_key: str | None) -> bool: - from . import azure_traffic - - if not azure_traffic.is_configured(): - self.last_error = ( - "Azure mode requires the bff to be running inside the Azure deployment created by " - "`make provision` (AZURE_RESOURCE_GROUP is not set) — switch to local mode to see the " - "live process-based migration instead." - ) - return False - try: - ok, new_base_url = await azure_traffic.shift_traffic_for_step(step.id) - if ok and service_key and new_base_url: - config.RUNTIME_BASE_URLS[service_key] = new_base_url - return ok - except Exception as exc: # pragma: no cover - defensive, reported to the UI - self.last_error = f"Azure step '{step.id}' failed: {exc}" - return False - - -engine = MigrationEngine() diff --git a/bff/app/routers/__init__.py b/bff/app/routers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/bff/app/routers/learn.py b/bff/app/routers/learn.py deleted file mode 100644 index b583ae6..0000000 --- a/bff/app/routers/learn.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import APIRouter - -from ..content.learn_content import LEARN_CONTENT -from ..schemas import LearnContent - -router = APIRouter(prefix="/api/learn", tags=["learn"]) - - -@router.get("/content", response_model=LearnContent) -async def get_learn_content(): - return LEARN_CONTENT diff --git a/bff/app/routers/metrics.py b/bff/app/routers/metrics.py deleted file mode 100644 index a478d6b..0000000 --- a/bff/app/routers/metrics.py +++ /dev/null @@ -1,89 +0,0 @@ -import asyncio -import json -import subprocess -import sys - -from fastapi import APIRouter, HTTPException -from pydantic import ValidationError - -from .. import config -from ..schemas import BenchmarkResult - -router = APIRouter(prefix="/api/metrics", tags=["metrics"]) - -NO_RESULTS_MESSAGE = "No benchmark results yet — run `make benchmark` or POST /api/metrics/run" - - -def _merged_latest_result() -> BenchmarkResult: - """Each run only measures whichever backend(s) are actually reachable - right now (see scripts/benchmark.py's run_all) — once the monolith is - decommissioned, a run can never measure it again. Naively returning the - single newest file would make the "before" bar vanish from the Metrics - page the instant someone migrates, even though that run is still sitting - on disk. Instead, walk newest-to-oldest and take the latest run that - measured "monolith" and the latest run that measured "microservices" - independently, then combine them — so the before/after comparison - survives even after the monolith is gone. Files that don't match the - current schema (e.g. saved before the `measured` field existed) are - skipped, same as if they weren't there.""" - files = sorted(config.RESULTS_DIR.glob("benchmark_*.json"), reverse=True) - monolith_ops = None - microservices_ops = None - latest_generated_at = None - - for path in files: - try: - data = BenchmarkResult.model_validate(json.loads(path.read_text())) - except (json.JSONDecodeError, ValidationError): - continue - if latest_generated_at is None: - latest_generated_at = data.generated_at - if monolith_ops is None and "monolith" in data.measured: - monolith_ops = data.monolith - if microservices_ops is None and "microservices" in data.measured: - microservices_ops = data.microservices - if monolith_ops is not None and microservices_ops is not None: - break - - if monolith_ops is None and microservices_ops is None: - raise HTTPException(404, NO_RESULTS_MESSAGE) - - measured = [name for name, ops in (("monolith", monolith_ops), ("microservices", microservices_ops)) if ops is not None] - return BenchmarkResult( - generated_at=latest_generated_at, - measured=measured, - monolith=monolith_ops or [], - microservices=microservices_ops or [], - ) - - -@router.get("/latest", response_model=BenchmarkResult) -async def latest_metrics(): - if not config.RESULTS_DIR.exists(): - raise HTTPException(404, NO_RESULTS_MESSAGE) - return _merged_latest_result() - - -@router.post("/run", response_model=BenchmarkResult) -async def run_benchmark(requests_per_target: int = 50, concurrency: int = 5): - script = config.REPO_ROOT / "scripts" / "benchmark.py" - # subprocess.run() is blocking — running it directly on this async def - # would freeze the event loop for the whole benchmark duration. That's - # not just slow: the benchmark subprocess itself calls back into this - # very server over loopback (GET /api/services) to discover live - # backend URLs, so a frozen event loop can never answer that request — - # a self-deadlock only broken by that call's 3s timeout, which silently - # falls back to bogus localhost URLs (caught for real running this - # against Azure). asyncio.to_thread keeps the loop free to serve it. - result = await asyncio.to_thread( - subprocess.run, - [sys.executable, str(script), "--requests", str(requests_per_target), "--concurrency", str(concurrency), - "--bff-url", "http://127.0.0.1:8000"], - capture_output=True, - text=True, - timeout=180, - ) - if result.returncode != 0: - raise HTTPException(500, f"Benchmark failed: {result.stderr[-2000:]}") - - return _merged_latest_result() diff --git a/bff/app/routers/migration.py b/bff/app/routers/migration.py deleted file mode 100644 index 9df67d1..0000000 --- a/bff/app/routers/migration.py +++ /dev/null @@ -1,65 +0,0 @@ -import asyncio - -from fastapi import APIRouter -from sse_starlette.sse import EventSourceResponse - -from ..migration_engine import engine -from ..schemas import MigrationSnapshot, MigrationStartResponse - -router = APIRouter(prefix="/api/migration", tags=["migration"]) - - -@router.get("/status", response_model=MigrationSnapshot) -async def status(): - return engine.snapshot() - - -@router.post("/reset", response_model=MigrationSnapshot) -async def reset(): - """Resets step state back to pending AND restarts the monolith process if - the last run decommissioned it — otherwise the UI would say 'monolith' - is the active backend again while the process is actually still dead. - This used to be two separate endpoints (/reset and /restart-monolith) - that called the exact same engine.restart_monolith() and differed only - in an error-message string — collapsed into one, since they were never - actually different actions.""" - if engine.running: - return engine.snapshot() - ok = await engine.restart_monolith() - if not ok: - engine.last_error = "Timed out waiting for the monolith to come back up." - return engine.snapshot() - - -@router.post("/start", response_model=MigrationStartResponse) -async def start(mode: str = "local"): - if engine.running: - return MigrationStartResponse(message="Migration already running") - - engine.last_error = None - asyncio.create_task(engine.run(mode)) - return MigrationStartResponse(message=f"Migration started in {mode} mode") - - -@router.get("/stream") -async def stream(): - """SSE endpoint. The engine is the single source of truth for state (see - migration_engine.py); this polls its snapshot rather than consuming an - event queue, so a browser tab refreshing mid-migration reconnects safely - and immediately sees the current state instead of missing past events.""" - - async def event_generator(): - last_snapshot = None - while True: - snapshot = MigrationSnapshot.model_validate(engine.snapshot()) - if snapshot != last_snapshot: - yield {"event": "state", "data": snapshot.model_dump_json()} - last_snapshot = snapshot - if not snapshot.running and last_snapshot is not None and all( - s.status in ("done", "failed") for s in snapshot.steps - ): - yield {"event": "complete", "data": snapshot.model_dump_json()} - break - await asyncio.sleep(0.5) - - return EventSourceResponse(event_generator()) diff --git a/bff/app/routers/services.py b/bff/app/routers/services.py deleted file mode 100644 index 87c310e..0000000 --- a/bff/app/routers/services.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Reports which backend URLs are currently live, straight from the BFF's -own runtime registry (config.RUNTIME_BASE_URLS) — the single source of -truth for what exists right now. scripts/benchmark.py uses this instead of -hardcoding localhost ports, so it works unchanged against Azure Container -Apps FQDNs once a live migration creates them, while still hitting each -backend directly (not through this BFF) to keep the monolith-vs-microservices -comparison fair.""" -from fastapi import APIRouter - -from .. import config - -router = APIRouter(prefix="/api/services", tags=["services"]) - - -@router.get("") -async def list_services() -> dict[str, str | None]: - return dict(config.RUNTIME_BASE_URLS) diff --git a/bff/app/routers/shop.py b/bff/app/routers/shop.py deleted file mode 100644 index 28eb2e1..0000000 --- a/bff/app/routers/shop.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Generic reverse proxy so the React Shop page can talk to either backend -(the monolith or the three microservices) through one client interface. - -/api/shop/monolith/{path} -> forwarded to the monolith -/api/shop/microservices/{path} -> forwarded to user-/product-/order-service - based on the path prefix (user, product, order) -""" -import json - -import httpx -from fastapi import APIRouter, Request, Response - -from .. import config - -router = APIRouter(prefix="/api/shop", tags=["shop"]) - - -def _microservice_base_url(path: str) -> str: - first_segment = path.split("/", 1)[0] - for prefix in config.SERVICE_ROUTE_PREFIXES: - if first_segment.startswith(prefix): - base_url = config.RUNTIME_BASE_URLS[prefix] - if base_url is None: - raise ValueError( - f"'{prefix}-service' doesn't exist yet — it's created live during migration, not before." - ) - return base_url - raise ValueError(f"No microservice owns path '{path}'") - - -async def _forward(base_url: str, path: str, request: Request) -> Response: - url = f"{base_url}/api/{path}" - headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length")} - body = await request.body() - - async with httpx.AsyncClient(timeout=10) as client: - upstream = await client.request( - request.method, url, headers=headers, params=request.query_params, content=body - ) - return Response(content=upstream.content, status_code=upstream.status_code, media_type=upstream.headers.get("content-type")) - - -@router.api_route("/monolith/{path:path}", methods=["GET", "POST"]) -async def proxy_monolith(path: str, request: Request): - base_url = config.RUNTIME_BASE_URLS["monolith"] - if base_url is None: - return Response(content=json.dumps({"message": "Monolith is not available."}), status_code=503, media_type="application/json") - return await _forward(base_url, path, request) - - -@router.api_route("/microservices/{path:path}", methods=["GET", "POST"]) -async def proxy_microservices(path: str, request: Request): - try: - base_url = _microservice_base_url(path) - except ValueError as exc: - return Response(content=json.dumps({"message": str(exc)}), status_code=503, media_type="application/json") - return await _forward(base_url, path, request) diff --git a/bff/app/schemas.py b/bff/app/schemas.py deleted file mode 100644 index 8260cf8..0000000 --- a/bff/app/schemas.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Pydantic schemas for the BFF's own first-class endpoints (migration, learn, -metrics). /api/shop/* is intentionally left as an untyped passthrough proxy — -it forwards arbitrary payloads to whichever backend is live, so imposing a -fixed schema there would defeat the point of a generic reverse proxy.""" -from typing import Literal - -from pydantic import BaseModel - -Backend = Literal["monolith", "microservices"] -StepStatus = Literal["pending", "running", "done", "failed"] - - -class MigrationStep(BaseModel): - id: str - title: str - description: str - status: StepStatus - - -class MigrationSnapshot(BaseModel): - mode: Literal["local", "azure"] - active_backend: Backend - running: bool - last_error: str | None - steps: list[MigrationStep] - - -class MigrationStartResponse(BaseModel): - message: str - - -class Advantage(BaseModel): - title: str - body: str - - -class AntiPattern(BaseModel): - name: str - why: str - - -class AntiPatterns(BaseModel): - technical: list[AntiPattern] - organizational: list[AntiPattern] - - -class FaqItem(BaseModel): - q: str - a: str - - -class LearnContent(BaseModel): - advantages: list[Advantage] - strangler_fig_steps: list[str] - anti_patterns: AntiPatterns - glossary: dict[str, str] - faq: list[FaqItem] - - -class BenchmarkOperationResult(BaseModel): - operation: str - requests: int - p50_ms: float - p95_ms: float - throughput_rps: float - errors: int - - -class BenchmarkResult(BaseModel): - generated_at: str - measured: list[Literal["monolith", "microservices"]] - monolith: list[BenchmarkOperationResult] - microservices: list[BenchmarkOperationResult] diff --git a/bff/requirements.txt b/bff/requirements.txt deleted file mode 100644 index 32b3e7c..0000000 --- a/bff/requirements.txt +++ /dev/null @@ -1,8 +0,0 @@ -fastapi==0.115.6 -uvicorn[standard]==0.32.1 -httpx==0.28.1 -sse-starlette==2.1.3 -psutil==6.1.0 -python-dotenv==1.0.1 -azure-identity==1.19.0 -azure-mgmt-appcontainers==3.1.0 diff --git a/bff/tests/test_api.py b/bff/tests/test_api.py deleted file mode 100644 index cf1dade..0000000 --- a/bff/tests/test_api.py +++ /dev/null @@ -1,123 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from app.main import app - -client = TestClient(app) - - -def test_health(): - r = client.get("/health") - assert r.status_code == 200 - assert r.json() == {"status": "ok", "service": "bff"} - - -def test_learn_content_matches_schema(): - r = client.get("/api/learn/content") - assert r.status_code == 200 - body = r.json() - assert "advantages" in body - assert "strangler_fig_steps" in body - assert len(body["strangler_fig_steps"]) == 7 - - -@pytest.mark.skip(reason="M0: monolith removed; migration engine is replaced by the gateway in M1") -def test_migration_status_initial_state(): - r = client.post("/api/migration/reset") - assert r.status_code == 200 - body = r.json() - assert body["active_backend"] == "monolith" - assert body["running"] is False - assert all(s["status"] == "pending" for s in body["steps"]) - - -def test_metrics_latest_404_when_no_results(tmp_path, monkeypatch): - from app import config - - monkeypatch.setattr(config, "RESULTS_DIR", tmp_path / "no-results-here") - r = client.get("/api/metrics/latest") - assert r.status_code == 404 - - -def test_metrics_latest_skips_legacy_file_missing_measured_field(tmp_path, monkeypatch): - """A result saved before the `measured` field existed must not crash this - endpoint with a validation error — it should be treated as unusable and - skipped, same as if no results existed at all.""" - import json - - from app import config - - results_dir = tmp_path / "results" - results_dir.mkdir() - legacy = { - "generated_at": "2026-01-01T00:00:00+00:00", - "monolith": [{"operation": "list_products", "requests": 10, "p50_ms": 1.0, "p95_ms": 2.0, "throughput_rps": 10.0, "errors": 0}], - "microservices": [], - } - (results_dir / "benchmark_20260101T000000Z.json").write_text(json.dumps(legacy)) - - monkeypatch.setattr(config, "RESULTS_DIR", results_dir) - r = client.get("/api/metrics/latest") - assert r.status_code == 404 - - -def test_metrics_latest_returns_valid_result_with_partial_measured(tmp_path, monkeypatch): - """A benchmark run while only one backend was up must be servable as-is — - no failure, no fabricated data for the missing side.""" - import json - - from app import config - - results_dir = tmp_path / "results" - results_dir.mkdir() - monolith_only = { - "generated_at": "2026-01-01T00:00:00+00:00", - "measured": ["monolith"], - "monolith": [{"operation": "list_products", "requests": 10, "p50_ms": 1.0, "p95_ms": 2.0, "throughput_rps": 10.0, "errors": 0}], - "microservices": [], - } - (results_dir / "benchmark_20260101T000000Z.json").write_text(json.dumps(monolith_only)) - - monkeypatch.setattr(config, "RESULTS_DIR", results_dir) - r = client.get("/api/metrics/latest") - assert r.status_code == 200 - body = r.json() - assert body["measured"] == ["monolith"] - assert body["microservices"] == [] - - -def test_metrics_latest_merges_monolith_run_with_later_microservices_run(tmp_path, monkeypatch): - """The real lifecycle: a benchmark runs once before migration (monolith - only reachable), then again after migration decommissions the monolith - (microservices only reachable). Naively returning just the newest file - would make the "before" bar disappear from the Metrics page the moment - someone migrates — caught for real running this against Azure. The two - runs must merge into one result with both sides populated.""" - import json - - from app import config - - results_dir = tmp_path / "results" - results_dir.mkdir() - monolith_run = { - "generated_at": "2026-01-01T00:00:00+00:00", - "measured": ["monolith"], - "monolith": [{"operation": "list_products", "requests": 10, "p50_ms": 1.0, "p95_ms": 2.0, "throughput_rps": 10.0, "errors": 0}], - "microservices": [], - } - microservices_run = { - "generated_at": "2026-01-02T00:00:00+00:00", - "measured": ["microservices"], - "monolith": [], - "microservices": [{"operation": "list_products", "requests": 10, "p50_ms": 3.0, "p95_ms": 4.0, "throughput_rps": 20.0, "errors": 0}], - } - (results_dir / "benchmark_20260101T000000Z.json").write_text(json.dumps(monolith_run)) - (results_dir / "benchmark_20260102T000000Z.json").write_text(json.dumps(microservices_run)) - - monkeypatch.setattr(config, "RESULTS_DIR", results_dir) - r = client.get("/api/metrics/latest") - assert r.status_code == 200 - body = r.json() - assert set(body["measured"]) == {"monolith", "microservices"} - assert body["monolith"][0]["p95_ms"] == 2.0 - assert body["microservices"][0]["p95_ms"] == 4.0 diff --git a/bff/tests/test_azure_migration.py b/bff/tests/test_azure_migration.py deleted file mode 100644 index 98b950c..0000000 --- a/bff/tests/test_azure_migration.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Unit coverage for the cloud on-demand Container App creation path. -Never touches real Azure — the SDK call itself is monkeypatched out, since -these are unit tests of the wiring (env var gating, registry updates), -not integration tests of azure-mgmt-appcontainers.""" -import asyncio - -from app import azure_traffic, config -from app.migration_engine import MigrationEngine - - -def test_is_configured_false_without_env(monkeypatch): - monkeypatch.delenv("AZURE_RESOURCE_GROUP", raising=False) - assert azure_traffic.is_configured() is False - - -def test_is_configured_true_with_env(monkeypatch): - monkeypatch.setenv("AZURE_RESOURCE_GROUP", "rg-test") - assert azure_traffic.is_configured() is True - - -def test_azure_step_creates_container_app_and_updates_registry(monkeypatch): - monkeypatch.setenv("AZURE_RESOURCE_GROUP", "rg-test") - - async def fake_shift(step_id): - assert step_id == "extract_user" - return True, "https://user-service.example.azurecontainerapps.io" - - monkeypatch.setattr(azure_traffic, "shift_traffic_for_step", fake_shift) - config.RUNTIME_BASE_URLS["user"] = None - - engine = MigrationEngine() - step = next(s for s in engine.steps if s.id == "extract_user") - ok = asyncio.run(engine._azure_step(step, "user")) - - assert ok is True - assert config.RUNTIME_BASE_URLS["user"] == "https://user-service.example.azurecontainerapps.io" - - -def test_azure_step_reports_clear_error_when_not_configured(monkeypatch): - monkeypatch.delenv("AZURE_RESOURCE_GROUP", raising=False) - - engine = MigrationEngine() - step = next(s for s in engine.steps if s.id == "extract_product") - ok = asyncio.run(engine._azure_step(step, "product")) - - assert ok is False - assert "make provision" in engine.last_error - - -def test_decommission_step_clears_monolith_registry_entry(monkeypatch): - monkeypatch.setenv("AZURE_RESOURCE_GROUP", "rg-test") - - async def fake_shift(step_id): - assert step_id == "decommission" - return True, None - - monkeypatch.setattr(azure_traffic, "shift_traffic_for_step", fake_shift) - config.RUNTIME_BASE_URLS["monolith"] = "https://monolith.example.azurecontainerapps.io" - - engine = MigrationEngine() - step = next(s for s in engine.steps if s.id == "decommission") - ok = asyncio.run(engine._execute_step(step, "azure")) - - assert ok is True - assert config.RUNTIME_BASE_URLS["monolith"] is None - - -def test_services_endpoint_reports_runtime_registry(): - from fastapi.testclient import TestClient - - from app.main import app - - config.RUNTIME_BASE_URLS["monolith"] = "http://127.0.0.1:6000" - config.RUNTIME_BASE_URLS["user"] = None - - client = TestClient(app) - r = client.get("/api/services") - - assert r.status_code == 200 - body = r.json() - assert body["monolith"] == "http://127.0.0.1:6000" - assert body["user"] is None - - -def test_migration_status_reports_mode(): - from fastapi.testclient import TestClient - - from app.main import app - - client = TestClient(app) - r = client.get("/api/migration/status") - - assert r.status_code == 200 - assert r.json()["mode"] == config.RUN_MODE diff --git a/frontend/.env.example b/frontend/.env.example index e3bc6ff..7b31409 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -1 +1 @@ -VITE_BFF_BASE_URL=http://127.0.0.1:8000 +VITE_GATEWAY_BASE_URL=http://127.0.0.1:8100 diff --git a/frontend/index.html b/frontend/index.html index c1f27b3..8201792 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,7 @@ - Contoso Migrate — Monolith to Microservices + Contoso — 12 Microservices Patterns
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index b9106fe..60f5656 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -10,8 +10,7 @@ "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1", - "react-router-dom": "^6.28.0", - "recharts": "^2.13.3" + "react-router-dom": "^6.28.0" }, "devDependencies": { "@types/react": "^18.3.12", @@ -255,15 +254,6 @@ "@babel/core": "^7.0.0-0" } }, - "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -1203,69 +1193,6 @@ "@babel/types": "^7.28.2" } }, - "node_modules/@types/d3-array": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", - "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", - "license": "MIT" - }, - "node_modules/@types/d3-color": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", - "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", - "license": "MIT" - }, - "node_modules/@types/d3-ease": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", - "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", - "license": "MIT" - }, - "node_modules/@types/d3-interpolate": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", - "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", - "license": "MIT", - "dependencies": { - "@types/d3-color": "*" - } - }, - "node_modules/@types/d3-path": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", - "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", - "license": "MIT" - }, - "node_modules/@types/d3-scale": { - "version": "4.0.9", - "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", - "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", - "license": "MIT", - "dependencies": { - "@types/d3-time": "*" - } - }, - "node_modules/@types/d3-shape": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz", - "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==", - "license": "MIT", - "dependencies": { - "@types/d3-path": "*" - } - }, - "node_modules/@types/d3-time": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", - "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", - "license": "MIT" - }, - "node_modules/@types/d3-timer": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", - "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", - "license": "MIT" - }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -1390,15 +1317,6 @@ ], "license": "CC-BY-4.0" }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1410,129 +1328,9 @@ "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, "license": "MIT" }, - "node_modules/d3-array": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", - "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", - "license": "ISC", - "dependencies": { - "internmap": "1 - 2" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-color": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", - "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-ease": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", - "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-format": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", - "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-interpolate": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", - "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-path": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", - "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-scale": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", - "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", - "license": "ISC", - "dependencies": { - "d3-array": "2.10.0 - 3", - "d3-format": "1 - 3", - "d3-interpolate": "1.2.0 - 3", - "d3-time": "2.1.1 - 3", - "d3-time-format": "2 - 4" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-shape": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", - "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", - "license": "ISC", - "dependencies": { - "d3-path": "^3.1.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-time": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", - "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", - "license": "ISC", - "dependencies": { - "d3-array": "2 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-time-format": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", - "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", - "license": "ISC", - "dependencies": { - "d3-time": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-timer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", - "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1551,22 +1349,6 @@ } } }, - "node_modules/decimal.js-light": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", - "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", - "license": "MIT" - }, - "node_modules/dom-helpers": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", - "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.8.7", - "csstype": "^3.0.2" - } - }, "node_modules/electron-to-chromium": { "version": "1.5.392", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.392.tgz", @@ -1623,21 +1405,6 @@ "node": ">=6" } }, - "node_modules/eventemitter3": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", - "license": "MIT" - }, - "node_modules/fast-equals": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.1.tgz", - "integrity": "sha512-DjlFSM5Pk9cGcL0q5QXl66eGzx0N6szNgaswwc5ZphlBohjTVJSnGgI+rJVOgOi65qUoQnDZN4nDqi33udtydQ==", - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1663,15 +1430,6 @@ "node": ">=6.9.0" } }, - "node_modules/internmap": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", - "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1704,12 +1462,6 @@ "node": ">=6" } }, - "node_modules/lodash": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", - "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", - "license": "MIT" - }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -1768,15 +1520,6 @@ "node": ">=18" } }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1813,23 +1556,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/prop-types": { - "version": "15.8.1", - "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", - "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", - "license": "MIT", - "dependencies": { - "loose-envify": "^1.4.0", - "object-assign": "^4.1.1", - "react-is": "^16.13.1" - } - }, - "node_modules/prop-types/node_modules/react-is": { - "version": "16.13.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", - "license": "MIT" - }, "node_modules/react": { "version": "18.3.1", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", @@ -1855,12 +1581,6 @@ "react": "^18.3.1" } }, - "node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "license": "MIT" - }, "node_modules/react-refresh": { "version": "0.17.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", @@ -1903,70 +1623,6 @@ "react-dom": ">=16.8" } }, - "node_modules/react-smooth": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz", - "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==", - "license": "MIT", - "dependencies": { - "fast-equals": "^5.0.1", - "prop-types": "^15.8.1", - "react-transition-group": "^4.4.5" - }, - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/react-transition-group": { - "version": "4.4.5", - "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", - "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", - "license": "BSD-3-Clause", - "dependencies": { - "@babel/runtime": "^7.5.5", - "dom-helpers": "^5.0.1", - "loose-envify": "^1.4.0", - "prop-types": "^15.6.2" - }, - "peerDependencies": { - "react": ">=16.6.0", - "react-dom": ">=16.6.0" - } - }, - "node_modules/recharts": { - "version": "2.15.4", - "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz", - "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==", - "deprecated": "1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide", - "license": "MIT", - "dependencies": { - "clsx": "^2.0.0", - "eventemitter3": "^4.0.1", - "lodash": "^4.17.21", - "react-is": "^18.3.1", - "react-smooth": "^4.0.4", - "recharts-scale": "^0.4.4", - "tiny-invariant": "^1.3.1", - "victory-vendor": "^36.6.8" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/recharts-scale": { - "version": "0.4.5", - "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz", - "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==", - "license": "MIT", - "dependencies": { - "decimal.js-light": "^2.4.1" - } - }, "node_modules/rollup": { "version": "4.62.2", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", @@ -2041,12 +1697,6 @@ "node": ">=0.10.0" } }, - "node_modules/tiny-invariant": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", - "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", - "license": "MIT" - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -2092,28 +1742,6 @@ "browserslist": ">= 4.21.0" } }, - "node_modules/victory-vendor": { - "version": "36.9.2", - "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz", - "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==", - "license": "MIT AND ISC", - "dependencies": { - "@types/d3-array": "^3.0.3", - "@types/d3-ease": "^3.0.0", - "@types/d3-interpolate": "^3.0.1", - "@types/d3-scale": "^4.0.2", - "@types/d3-shape": "^3.1.0", - "@types/d3-time": "^3.0.0", - "@types/d3-timer": "^3.0.0", - "d3-array": "^3.1.6", - "d3-ease": "^3.0.1", - "d3-interpolate": "^3.0.1", - "d3-scale": "^4.0.2", - "d3-shape": "^3.1.0", - "d3-time": "^3.0.0", - "d3-timer": "^3.0.1" - } - }, "node_modules/vite": { "version": "5.4.21", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", diff --git a/frontend/package.json b/frontend/package.json index ffa9b9e..c2a5963 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,8 +12,7 @@ "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1", - "react-router-dom": "^6.28.0", - "recharts": "^2.13.3" + "react-router-dom": "^6.28.0" }, "devDependencies": { "@types/react": "^18.3.12", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index e0db8ad..361b5d9 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,9 +2,7 @@ import { Route, Routes } from "react-router-dom"; import NavBar from "./components/NavBar"; import Home from "./pages/Home"; import Shop from "./pages/Shop"; -import Migrate from "./pages/Migrate"; -import Learn from "./pages/Learn"; -import Metrics from "./pages/Metrics"; +import Patterns from "./pages/Patterns"; export default function App() { return ( @@ -14,9 +12,7 @@ export default function App() { } /> } /> - } /> - } /> - } /> + } /> diff --git a/frontend/src/api/bffClient.ts b/frontend/src/api/bffClient.ts deleted file mode 100644 index a783005..0000000 --- a/frontend/src/api/bffClient.ts +++ /dev/null @@ -1,141 +0,0 @@ -const BFF_BASE_URL = import.meta.env.VITE_BFF_BASE_URL || "http://127.0.0.1:8000"; - -export type Backend = "monolith" | "microservices"; - -async function request(path: string, options: RequestInit = {}): Promise { - const response = await fetch(`${BFF_BASE_URL}${path}`, options); - if (!response.ok) { - const body = await response.text(); - throw new Error(`${response.status} ${response.statusText}: ${body}`); - } - return response.json() as Promise; -} - -function toForm(fields: Record): URLSearchParams { - const form = new URLSearchParams(); - for (const [key, value] of Object.entries(fields)) form.append(key, String(value)); - return form; -} - -function authHeaders(apiKey: string): HeadersInit { - return { Authorization: `Basic ${apiKey}` }; -} - -export interface Product { - id: number; - name: string; - slug: string; - price: number; - image: string | null; -} - -export interface OrderItem { - product_id: number; - quantity: number; -} - -export interface Order { - id?: number; - user_id?: number; - is_open: boolean; - items: OrderItem[]; -} - -export const shopApi = { - listProducts: (backend: Backend) => request<{ results: Product[] }>(`/api/shop/${backend}/products`), - - createProduct: (backend: Backend, name: string, slug: string, priceCents: number) => - request<{ product: Product }>(`/api/shop/${backend}/product/create`, { - method: "POST", - body: toForm({ name, slug, price: priceCents }), - }), - - register: (backend: Backend, username: string, email: string, password: string) => - request<{ result: { username: string } }>(`/api/shop/${backend}/user/create`, { - method: "POST", - body: toForm({ username, email, password }), - }), - - login: (backend: Backend, username: string, password: string) => - request<{ api_key: string }>(`/api/shop/${backend}/user/login`, { - method: "POST", - body: toForm({ username, password }), - }), - - addToCart: (backend: Backend, apiKey: string, productId: number, qty: number) => - request<{ result: Order }>(`/api/shop/${backend}/order/add-item`, { - method: "POST", - headers: authHeaders(apiKey), - body: toForm({ product_id: productId, qty }), - }), - - getCart: (backend: Backend, apiKey: string) => - request<{ result?: Order; message?: string }>(`/api/shop/${backend}/order`, { - headers: authHeaders(apiKey), - }), - - checkout: (backend: Backend, apiKey: string) => - request<{ result: Order }>(`/api/shop/${backend}/order/checkout`, { - method: "POST", - headers: authHeaders(apiKey), - }), -}; - -export interface MigrationStep { - id: string; - title: string; - description: string; - status: "pending" | "running" | "done" | "failed"; -} - -export interface MigrationSnapshot { - mode: "local" | "azure"; - active_backend: Backend; - running: boolean; - last_error: string | null; - steps: MigrationStep[]; -} - -export const migrationApi = { - status: () => request("/api/migration/status"), - start: (mode: "local" | "azure") => - request<{ message: string }>(`/api/migration/start?mode=${mode}`, { method: "POST" }), - reset: () => request("/api/migration/reset", { method: "POST" }), - streamUrl: () => `${BFF_BASE_URL}/api/migration/stream`, -}; - -export interface LearnContent { - advantages: { title: string; body: string }[]; - strangler_fig_steps: string[]; - anti_patterns: { - technical: { name: string; why: string }[]; - organizational: { name: string; why: string }[]; - }; - glossary: Record; - faq: { q: string; a: string }[]; -} - -export const learnApi = { - content: () => request("/api/learn/content"), -}; - -export interface BenchmarkOperationResult { - operation: string; - requests: number; - p50_ms: number; - p95_ms: number; - throughput_rps: number; - errors: number; -} - -export interface BenchmarkResult { - generated_at: string; - measured: Backend[]; - monolith: BenchmarkOperationResult[]; - microservices: BenchmarkOperationResult[]; -} - -export const metricsApi = { - latest: () => request("/api/metrics/latest"), - run: () => request("/api/metrics/run", { method: "POST" }), -}; diff --git a/frontend/src/api/gatewayClient.ts b/frontend/src/api/gatewayClient.ts new file mode 100644 index 0000000..8c63e34 --- /dev/null +++ b/frontend/src/api/gatewayClient.ts @@ -0,0 +1,81 @@ +// Every call goes through the API gateway (pattern 5), never straight to a service. +const GATEWAY_BASE_URL = import.meta.env.VITE_GATEWAY_BASE_URL || "http://127.0.0.1:8100"; + +async function request(path: string, options: RequestInit = {}): Promise { + const response = await fetch(`${GATEWAY_BASE_URL}${path}`, options); + if (!response.ok) { + const body = await response.text(); + throw new Error(`${response.status} ${response.statusText}: ${body}`); + } + return response.json() as Promise; +} + +function toForm(fields: Record): URLSearchParams { + const form = new URLSearchParams(); + for (const [key, value] of Object.entries(fields)) form.append(key, String(value)); + return form; +} + +function authHeaders(apiKey: string): HeadersInit { + return { Authorization: `Basic ${apiKey}` }; +} + +export interface Product { + id: number; + name: string; + slug: string; + price: number; + image: string | null; +} + +export interface OrderItem { + product_id: number; + quantity: number; +} + +export interface Order { + id?: number; + user_id?: number; + is_open: boolean; + items: OrderItem[]; +} + +export const shopApi = { + listProducts: () => request<{ results: Product[] }>(`/api/shop/products`), + + createProduct: (name: string, slug: string, priceCents: number) => + request<{ product: Product }>(`/api/shop/product/create`, { + method: "POST", + body: toForm({ name, slug, price: priceCents }), + }), + + register: (username: string, email: string, password: string) => + request<{ result: { username: string } }>(`/api/shop/user/create`, { + method: "POST", + body: toForm({ username, email, password }), + }), + + login: (username: string, password: string) => + request<{ api_key: string }>(`/api/shop/user/login`, { + method: "POST", + body: toForm({ username, password }), + }), + + addToCart: (apiKey: string, productId: number, qty: number) => + request<{ result: Order }>(`/api/shop/order/add-item`, { + method: "POST", + headers: authHeaders(apiKey), + body: toForm({ product_id: productId, qty }), + }), + + getCart: (apiKey: string) => + request<{ result?: Order; message?: string }>(`/api/shop/order`, { + headers: authHeaders(apiKey), + }), + + checkout: (apiKey: string) => + request<{ result: Order }>(`/api/shop/order/checkout`, { + method: "POST", + headers: authHeaders(apiKey), + }), +}; diff --git a/frontend/src/components/ArchitectureDiagram.tsx b/frontend/src/components/ArchitectureDiagram.tsx deleted file mode 100644 index b5091ea..0000000 --- a/frontend/src/components/ArchitectureDiagram.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { MigrationSnapshot } from "../api/bffClient"; - -type NodeState = "not-created" | "creating" | "live" | "retiring" | "retired" | "failed"; - -function stepState(steps: MigrationSnapshot["steps"], id: string): NodeState { - const step = steps.find((s) => s.id === id); - if (!step) return "not-created"; - if (step.status === "running") return "creating"; - if (step.status === "done") return "live"; - if (step.status === "failed") return "failed"; - return "not-created"; -} - -function monolithState(steps: MigrationSnapshot["steps"]): NodeState { - const step = steps.find((s) => s.id === "decommission"); - if (!step) return "live"; - if (step.status === "running") return "retiring"; - if (step.status === "done") return "retired"; - if (step.status === "failed") return "failed"; - return "live"; -} - -const STATE_STYLE: Record = { - "not-created": { border: "2px dashed var(--contoso-border)", background: "transparent", label: "not created yet" }, - creating: { border: "2px solid var(--contoso-warning)", background: "#fff3d6", label: "creating…" }, - live: { border: "2px solid var(--contoso-success)", background: "#dff6dd", label: "live" }, - retiring: { border: "2px solid var(--contoso-warning)", background: "#fff3d6", label: "retiring…" }, - retired: { border: "2px dashed var(--contoso-muted)", background: "transparent", label: "decommissioned" }, - failed: { border: "2px solid var(--contoso-danger)", background: "#fde7ea", label: "failed" }, -}; - -function ServiceBox({ name, dbName, state }: { name: string; dbName: string; state: NodeState }) { - const style = STATE_STYLE[state]; - const faded = state === "not-created" || state === "retired"; - return ( -
-
{name}
-
- {style.label} -
- {state !== "not-created" && ( -
- DB: {dbName} -
- )} -
- ); -} - -function Arrow({ active }: { active: boolean }) { - return ( -
- → -
- ); -} - -export default function ArchitectureDiagram({ snapshot }: { snapshot: MigrationSnapshot }) { - const monolith = monolithState(snapshot.steps); - const user = stepState(snapshot.steps, "extract_user"); - const product = stepState(snapshot.steps, "extract_product"); - const order = stepState(snapshot.steps, "extract_order_acl"); - const microservicesActive = snapshot.active_backend === "microservices"; - - return ( -
- - - - -
- - monolith path -
- - -
- - microservices path -
-
- - - -
-
- ); -} diff --git a/frontend/src/components/NavBar.tsx b/frontend/src/components/NavBar.tsx index edcfc3f..2e3183b 100644 --- a/frontend/src/components/NavBar.tsx +++ b/frontend/src/components/NavBar.tsx @@ -3,9 +3,7 @@ import { NavLink } from "react-router-dom"; const links = [ { to: "/", label: "Home", end: true }, { to: "/shop", label: "Shop" }, - { to: "/migrate", label: "Migrate" }, - { to: "/learn", label: "Learn" }, - { to: "/metrics", label: "Metrics" }, + { to: "/patterns", label: "Patterns" }, ]; export default function NavBar() { @@ -13,7 +11,7 @@ export default function NavBar() {
C - Contoso Migrate + Contoso · 12 Patterns