#!/usr/bin/env bash
# 第六课示例项目 orders 一键生成脚本：bash orders-bootstrap-part6.sh  → 生成 ~/orders
set -euo pipefail
D=${1:-$HOME/orders}; mkdir -p "$D"; cd "$D"
cat > .env.example <<'ORDERS_EOF'
# 复制为 .env 并修改密码；.env 不要提交到 Git
DB_PASSWORD=change-me-db
MQ_PASSWORD=change-me-mq
# Azurite 的公开开发账户（文档公开的固定 key，只能用于本机）
AZURITE_CONN=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;
ORDERS_EOF
cat > .gitignore <<'ORDERS_EOF'
.env
gateway/certs/
__pycache__/
ORDERS_EOF
cat > README.md <<'ORDERS_EOF'
# orders — Docker 第六个 60 分钟示例项目

订单系统：SPA + nginx 网关（HTTPS/限流）+ Flask API（连接池、旁路缓存、幂等键）
+ PostgreSQL + Redis + RabbitMQ Worker（重试/死信/优雅停机）+ 迁移任务 + 定时报表 + Azurite（Blob + SAS）。

```bash
cp .env.example .env            # 修改密码
./gen-cert.sh                   # 自签名证书
docker compose up -d --build    # https://localhost:8443
docker compose run --rm report  # 定时任务（手动运行）
bash azure/deploy.sh            # 部署到 Azure（付费资源，用完 az group delete）
```

课程：docker-h6.html
ORDERS_EOF
cat > compose.yaml <<'ORDERS_EOF'
name: orders

x-app: &app
  image: orders:1.0
  build: ./app
  environment: &app-env
    DATABASE_URL: postgresql://orders:${DB_PASSWORD:?run cp .env.example .env}@postgres:5432/orders
    REDIS_URL: redis://redis:6379/0
    QUEUE_BACKEND: rabbitmq
    RABBITMQ_URL: amqp://orders:${MQ_PASSWORD:?run cp .env.example .env}@rabbitmq:5672/
    STORAGE_CONNECTION_STRING: ${AZURITE_CONN}
    BLOB_PUBLIC_BASE: https://localhost:8443/blob
    APP_VERSION: "1.0"
  restart: unless-stopped
  stop_grace_period: 30s

services:
  migrate:                       # 一次性任务：迁移成功后才启动 api / worker
    <<: *app
    command: ["orders-migrate"]
    restart: "no"
    depends_on:
      postgres: { condition: service_healthy }

  api:
    <<: *app
    depends_on:
      migrate:  { condition: service_completed_successfully }
      redis:    { condition: service_healthy }
      rabbitmq: { condition: service_healthy }
      azurite:  { condition: service_started }
    deploy:
      replicas: 2
      resources: { limits: { cpus: "0.5", memory: 256M } }

  worker:
    <<: *app
    command: ["orders-worker"]
    healthcheck: { disable: true }
    depends_on:
      migrate:  { condition: service_completed_successfully }
      rabbitmq: { condition: service_healthy }
    deploy:
      replicas: 2

  report:                        # 定时任务：docker compose run --rm report（由主机 cron / ACA Job 触发）
    <<: *app
    command: ["orders-report"]
    restart: "no"
    healthcheck: { disable: true }
    profiles: [jobs]
    depends_on:
      postgres: { condition: service_healthy }

  gateway:
    image: nginx:1.29-alpine
    ports: ["8443:443", "8080:80"]
    volumes:
      - ./gateway/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./gateway/certs:/etc/nginx/certs:ro
      - ./web:/usr/share/nginx/html:ro
    depends_on: [api]
    restart: unless-stopped

  postgres:
    image: postgres:17
    environment:
      POSTGRES_USER: orders
      POSTGRES_PASSWORD: ${DB_PASSWORD:?run cp .env.example .env}
      POSTGRES_DB: orders
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orders -d orders"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    command: ["redis-server", "--appendonly", "yes", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
    volumes: [redisdata:/data]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 10
    restart: unless-stopped

  rabbitmq:
    image: rabbitmq:4-management
    environment:
      RABBITMQ_DEFAULT_USER: orders
      RABBITMQ_DEFAULT_PASS: ${MQ_PASSWORD:?run cp .env.example .env}
    ports: ["127.0.0.1:15672:15672"]          # 管理界面只绑定本机
    volumes: [mqdata:/var/lib/rabbitmq]
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
      interval: 10s
      timeout: 5s
      retries: 12
    restart: unless-stopped

  azurite:
    image: mcr.microsoft.com/azure-storage/azurite
    command: ["azurite-blob", "--blobHost", "0.0.0.0", "--location", "/data", "--skipApiVersionCheck"]
    volumes: [blobdata:/data]
    restart: unless-stopped

volumes:
  pgdata:
  redisdata:
  mqdata:
  blobdata:
ORDERS_EOF
cat > gen-cert.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# 生成本机自签名证书（仅开发用；生产用 ACA 托管证书 / Let's Encrypt / Key Vault 证书）
set -euo pipefail
mkdir -p gateway/certs
openssl req -x509 -newkey rsa:2048 -nodes -days 30 \
  -keyout gateway/certs/tls.key -out gateway/certs/tls.crt \
  -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
chmod 644 gateway/certs/tls.key   # 容器内 nginx master 以 root 读取；勿在生产这样做
echo "证书已生成：gateway/certs/"
ORDERS_EOF
mkdir -p app
cat > app/.dockerignore <<'ORDERS_EOF'
__pycache__
*.pyc
.git
migrations-contract
ORDERS_EOF
mkdir -p app
cat > app/Dockerfile <<'ORDERS_EOF'
# syntax=docker/dockerfile:1
# check=error=true
ARG PYTHON_VERSION=3.13

FROM python:${PYTHON_VERSION}-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

FROM python:${PYTHON_VERSION}-slim AS runtime
LABEL org.opencontainers.image.source="https://github.com/yourname/orders" \
      org.opencontainers.image.title="orders"
RUN useradd --uid 10001 --create-home app
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY --chown=10001:10001 orders ./orders
COPY --chown=10001:10001 migrations ./migrations
COPY --chmod=755 bin/ /usr/local/bin/
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
  CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
# 同一个镜像，多种进程类型（12-Factor）：api（默认）、orders-worker、orders-migrate、orders-report
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--graceful-timeout", "20", "--access-logfile", "-", "orders.api:app"]
ORDERS_EOF
mkdir -p app
cat > app/requirements.txt <<'ORDERS_EOF'
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.2.*
psycopg-pool==3.2.*
redis==5.*
pika==1.3.*
azure-storage-blob==12.*
azure-identity==1.*
azure-servicebus==7.*
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-migrate <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.migrate "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-report <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.report "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-worker <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.worker "$@"
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/001_init.sql <<'ORDERS_EOF'
CREATE TABLE IF NOT EXISTS orders (
    id              bigserial PRIMARY KEY,
    item            text        NOT NULL,
    qty             integer     NOT NULL CHECK (qty > 0),
    status          text        NOT NULL DEFAULT 'pending',
    idempotency_key text        UNIQUE,
    created_at      timestamptz NOT NULL DEFAULT now(),
    processed_at    timestamptz
);
CREATE TABLE IF NOT EXISTS daily_reports (
    day          date PRIMARY KEY,
    orders       integer NOT NULL,
    items        integer NOT NULL,
    generated_at timestamptz NOT NULL
);
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/002_expand_customer_email.sql <<'ORDERS_EOF'
-- 扩展（expand）阶段：只新增可空列，旧版本应用不受影响
ALTER TABLE orders ADD COLUMN IF NOT EXISTS customer_email text;
CREATE INDEX IF NOT EXISTS ix_orders_created_at ON orders (created_at);
ORDERS_EOF
mkdir -p app/migrations-contract
cat > app/migrations-contract/003_contract_customer_email.sql <<'ORDERS_EOF'
-- 收缩（contract）阶段：确认所有运行中的版本都会写 customer_email 之后，才移动到 migrations/ 执行
UPDATE orders SET customer_email = 'unknown@example.com' WHERE customer_email IS NULL;
ALTER TABLE orders ALTER COLUMN customer_email SET NOT NULL;
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/__init__.py <<'ORDERS_EOF'

ORDERS_EOF
mkdir -p app/orders
cat > app/orders/api.py <<'ORDERS_EOF'
"""订单 API：旁路缓存、幂等创建、异步处理、文件上传。"""
import json, os, socket, uuid
from flask import Flask, jsonify, request, abort
import psycopg
import redis as redislib
from . import config, db, queueing, storage
from .log import get_logger, info

log = get_logger("api")
app = Flask(__name__)
cache = redislib.Redis.from_url(config.REDIS_URL, socket_timeout=0.5, socket_connect_timeout=0.5)
db.ensure_open()

def cache_get(key):
    try:
        v = cache.get(key)
        return json.loads(v) if v else None
    except redislib.RedisError:
        log.warning("cache unavailable, falling back to database")   # 缓存故障不影响正确性
        return None

def cache_set(key, value, ttl=config.CACHE_TTL):
    try:
        cache.setex(key, ttl, json.dumps(value, default=str))
    except redislib.RedisError:
        pass

def cache_del(*keys):
    try:
        cache.delete(*keys)
    except redislib.RedisError:
        pass

@app.get("/healthz")
def healthz():                       # 存活：只检查进程自身
    return "ok"

@app.get("/readyz")
def readyz():
    """就绪：依赖可用才接流量。用独立的短连接 + connect_timeout，
    避免探针在“数据库无响应”时卡在池中的连接上（连接池的 timeout 只管“借连接”，不管查询）。"""
    try:
        with psycopg.connect(config.DATABASE_URL, connect_timeout=2) as conn:
            conn.execute("SELECT 1")
    except Exception as e:
        log.warning("not ready: %s", e)
        return "database unavailable", 503
    return "ready"

@app.post("/api/orders")
def create_order():
    body = request.get_json(silent=True) or {}
    item, qty = body.get("item"), body.get("qty")
    if not item or not isinstance(qty, int) or qty <= 0:
        abort(400, "item 与正整数 qty 为必填项")
    key = request.headers.get("Idempotency-Key") or str(uuid.uuid4())
    with db.pool.connection() as conn:
        row = conn.execute(
            """INSERT INTO orders (item, qty, customer_email, idempotency_key)
               VALUES (%s, %s, %s, %s)
               ON CONFLICT (idempotency_key) DO NOTHING
               RETURNING id, status""",
            (item, qty, body.get("email"), key)).fetchone()
        created = row is not None
        if not created:     # 客户端重试：返回第一次创建的订单，不重复下单
            row = conn.execute("SELECT id, status FROM orders WHERE idempotency_key=%s", (key,)).fetchone()
    if created:
        queueing.publish({"order_id": row["id"]})   # 生产中可用“发件箱”模式保证写库与发消息的一致性
        cache_del("stats")
    info(log, "order accepted", order_id=row["id"], created=created)
    return jsonify(id=row["id"], status=row["status"], created=created), 202 if created else 200

@app.get("/api/orders/<int:order_id>")
def get_order(order_id):
    key = f"order:{order_id}"
    hit = cache_get(key)
    if hit:
        return jsonify(hit | {"cache": "hit"})
    with db.pool.connection() as conn:
        row = conn.execute("SELECT * FROM orders WHERE id=%s", (order_id,)).fetchone()
    if not row:
        abort(404)
    if row["status"] != "pending":           # 只缓存“稳定”的数据，待处理订单状态会变化
        cache_set(key, row)
    return jsonify(row | {"cache": "miss"})

@app.get("/api/orders")
def list_orders():
    with db.pool.connection() as conn:
        rows = conn.execute("SELECT id, item, qty, status, created_at FROM orders ORDER BY id DESC LIMIT 20").fetchall()
    return jsonify(rows)

@app.get("/api/stats")
def stats():
    hit = cache_get("stats")
    if hit:
        return jsonify(hit | {"cache": "hit", "served_by": socket.gethostname(), "version": config.APP_VERSION})
    with db.pool.connection() as conn:
        row = conn.execute("""SELECT count(*) AS orders, coalesce(sum(qty),0) AS items,
                              count(*) FILTER (WHERE status='processed') AS processed FROM orders""").fetchone()
    cache_set("stats", row, ttl=10)
    return jsonify(row | {"cache": "miss", "served_by": socket.gethostname(), "version": config.APP_VERSION})

@app.post("/api/files")
def upload_file():
    f = request.files.get("file")
    if not f:
        abort(400, "缺少 file")
    name = f"{uuid.uuid4().hex}-{os.path.basename(f.filename or 'upload.bin')}"
    storage.upload(name, f.stream, f.mimetype or "application/octet-stream")
    info(log, "file uploaded", blob=name)
    return jsonify(name=name, url=storage.download_url(name)), 201

@app.get("/api/files/<name>/url")
def file_url(name):
    return jsonify(url=storage.download_url(name))
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/config.py <<'ORDERS_EOF'
"""12-Factor：所有配置都来自环境变量。"""
import os

DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://orders:orders@localhost:5432/orders")
DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", "5"))
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
CACHE_TTL = int(os.getenv("CACHE_TTL", "60"))

QUEUE_BACKEND = os.getenv("QUEUE_BACKEND", "none")          # rabbitmq | servicebus | none
QUEUE_NAME = os.getenv("QUEUE_NAME", "orders")
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@localhost:5672/")
SERVICEBUS_NAMESPACE = os.getenv("SERVICEBUS_NAMESPACE", "")  # <ns>.servicebus.windows.net
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))

STORAGE_CONNECTION_STRING = os.getenv("STORAGE_CONNECTION_STRING", "")  # 本机 Azurite
STORAGE_ACCOUNT_URL = os.getenv("STORAGE_ACCOUNT_URL", "")              # Azure：https://<acct>.blob.core.windows.net
BLOB_CONTAINER = os.getenv("BLOB_CONTAINER", "files")
BLOB_PUBLIC_BASE = os.getenv("BLOB_PUBLIC_BASE", "")                    # 本机经网关访问 Azurite 时改写 URL
APP_VERSION = os.getenv("APP_VERSION", "dev")
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/db.py <<'ORDERS_EOF'
"""数据库连接池：每个进程一个池，池大小 × 进程数 × 副本数 必须小于数据库 max_connections。"""
from psycopg_pool import ConnectionPool
from psycopg.rows import dict_row
from . import config

pool = ConnectionPool(config.DATABASE_URL, min_size=1, max_size=config.DB_POOL_SIZE,
                      kwargs={"row_factory": dict_row,
                              "options": "-c statement_timeout=5000"},   # 服务端：单条语句最长 5 秒
                      open=False)

def ensure_open():
    if pool.closed:
        pool.open(wait=True, timeout=10)
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/log.py <<'ORDERS_EOF'
"""结构化（JSON）日志输出到 stdout。"""
import json, logging, sys, time

class JsonFormatter(logging.Formatter):
    def format(self, record):
        d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "level": record.levelname,
             "logger": record.name, "msg": record.getMessage()}
        d.update(getattr(record, "extra_fields", {}))
        if record.exc_info:
            d["exc"] = self.formatException(record.exc_info)
        return json.dumps(d, ensure_ascii=False)

def get_logger(name):
    log = logging.getLogger(name)
    if not log.handlers:
        h = logging.StreamHandler(sys.stdout)
        h.setFormatter(JsonFormatter())
        log.addHandler(h)
        log.setLevel(logging.INFO)
        log.propagate = False
    return log

def info(log, msg, **fields):
    log.info(msg, extra={"extra_fields": fields})
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/migrate.py <<'ORDERS_EOF'
"""极简迁移工具：按文件名顺序执行 migrations/*.sql，每个文件一个事务；
用 PostgreSQL 咨询锁保证多个副本同时启动时只有一个在迁移。生产中可用 Alembic / Flyway。"""
import glob, os, sys
import psycopg
from . import config
from .log import get_logger, info

log = get_logger("migrate")
LOCK_ID = 727274
DIR = os.getenv("MIGRATIONS_DIR", os.path.join(os.path.dirname(__file__), "..", "migrations"))

def main():
    with psycopg.connect(config.DATABASE_URL, autocommit=True) as conn:
        conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
        try:
            conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations
                            (version text PRIMARY KEY, applied_at timestamptz DEFAULT now())""")
            done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}
            for path in sorted(glob.glob(os.path.join(DIR, "*.sql"))):
                ver = os.path.basename(path)
                if ver in done:
                    continue
                with conn.transaction():
                    conn.execute(open(path, encoding="utf-8").read())
                    conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (ver,))
                info(log, "applied", version=ver)
            info(log, "up to date", applied=len(done))
        finally:
            conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))

if __name__ == "__main__":
    sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/queueing.py <<'ORDERS_EOF'
"""消息队列抽象：本机 RabbitMQ，Azure 上 Service Bus；业务代码不感知差异。"""
import json, signal
from . import config
from .log import get_logger, info

log = get_logger("queue")

# ---------------- RabbitMQ ----------------
def _rabbit_channel():
    import pika
    conn = pika.BlockingConnection(pika.URLParameters(config.RABBITMQ_URL))
    ch = conn.channel()
    # 死信：失败超过重试次数的消息进入 orders.dlq
    ch.exchange_declare("orders.dlx", "fanout", durable=True)
    ch.queue_declare(f"{config.QUEUE_NAME}.dlq", durable=True)
    ch.queue_bind(f"{config.QUEUE_NAME}.dlq", "orders.dlx")
    ch.queue_declare(config.QUEUE_NAME, durable=True,
                     arguments={"x-dead-letter-exchange": "orders.dlx"})
    return conn, ch

def publish(message: dict):
    body = json.dumps(message)
    if config.QUEUE_BACKEND == "rabbitmq":
        import pika
        conn, ch = _rabbit_channel()
        try:
            ch.basic_publish("", config.QUEUE_NAME, body,
                             pika.BasicProperties(delivery_mode=2, content_type="application/json"))
        finally:
            conn.close()
    elif config.QUEUE_BACKEND == "servicebus":
        from azure.identity import DefaultAzureCredential
        from azure.servicebus import ServiceBusClient, ServiceBusMessage
        with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
            with sb.get_queue_sender(config.QUEUE_NAME) as sender:
                sender.send_messages(ServiceBusMessage(body, content_type="application/json"))
    info(log, "published", backend=config.QUEUE_BACKEND, message=message)

def consume(handler):
    """handler(dict) 抛出异常表示处理失败。收到 SIGTERM 后处理完当前消息再退出（优雅停机）。"""
    stopping = {"flag": False}
    def _stop(signum, frame):
        stopping["flag"] = True
        info(log, "SIGTERM received, finishing current message")
    signal.signal(signal.SIGTERM, _stop)

    if config.QUEUE_BACKEND == "rabbitmq":
        import pika
        conn, ch = _rabbit_channel()
        ch.basic_qos(prefetch_count=1)
        for method, props, body in ch.consume(config.QUEUE_NAME, inactivity_timeout=1):
            if stopping["flag"]:
                break
            if method is None:
                continue
            retries = int((props.headers or {}).get("x-retry", 0))
            try:
                handler(json.loads(body))
                ch.basic_ack(method.delivery_tag)            # 处理成功后才确认
            except Exception:
                log.exception("handler failed")
                if retries + 1 >= config.MAX_RETRIES:
                    ch.basic_nack(method.delivery_tag, requeue=False)   # → 死信队列
                    info(log, "dead-lettered", retries=retries + 1)
                else:
                    ch.basic_publish("", config.QUEUE_NAME, body, pika.BasicProperties(
                        delivery_mode=2, headers={"x-retry": retries + 1}))
                    ch.basic_ack(method.delivery_tag)
        ch.cancel(); conn.close()
    elif config.QUEUE_BACKEND == "servicebus":
        from azure.identity import DefaultAzureCredential
        from azure.servicebus import ServiceBusClient
        with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
            with sb.get_queue_receiver(config.QUEUE_NAME, max_wait_time=5) as receiver:
                while not stopping["flag"]:
                    for msg in receiver.receive_messages(max_message_count=1, max_wait_time=5):
                        try:
                            handler(json.loads(str(msg)))
                            receiver.complete_message(msg)
                        except Exception:
                            log.exception("handler failed")
                            # 放弃后 Service Bus 自动重投，超过 MaxDeliveryCount 进入死信子队列
                            receiver.abandon_message(msg)
    else:
        raise SystemExit("QUEUE_BACKEND=none：没有可消费的队列")
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/report.py <<'ORDERS_EOF'
"""定时任务：生成某天的订单日报（写入数据库并上传 CSV）。可重复运行（幂等 upsert）。"""
import csv, io, os, sys
from datetime import date, timedelta
from . import db, storage
from .log import get_logger, info

log = get_logger("report")

def main():
    day = date.fromisoformat(os.getenv("REPORT_DAY")) if os.getenv("REPORT_DAY") else date.today() - timedelta(days=1)
    db.ensure_open()
    with db.pool.connection() as conn:
        rows = conn.execute("""SELECT item, count(*) AS orders, sum(qty) AS items FROM orders
                               WHERE created_at::date = %s GROUP BY item ORDER BY item""", (day,)).fetchall()
        total_o = sum(r["orders"] for r in rows); total_i = sum(r["items"] for r in rows)
        conn.execute("""INSERT INTO daily_reports (day, orders, items, generated_at) VALUES (%s,%s,%s,now())
                        ON CONFLICT (day) DO UPDATE SET orders=EXCLUDED.orders, items=EXCLUDED.items,
                        generated_at=now()""", (day, total_o, total_i))
    buf = io.StringIO(); w = csv.writer(buf); w.writerow(["item", "orders", "items"])
    for r in rows:
        w.writerow([r["item"], r["orders"], r["items"]])
    name = f"reports/{day.isoformat()}.csv"
    storage.container().upload_blob(name, buf.getvalue().encode(), overwrite=True)
    info(log, "report generated", day=str(day), orders=total_o, blob=name)
    db.pool.close()

if __name__ == "__main__":
    sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/storage.py <<'ORDERS_EOF'
"""对象存储：本机 Azurite（连接字符串），Azure 上 Blob Storage + 托管标识（用户委托 SAS）。"""
from datetime import datetime, timedelta, timezone
from azure.storage.blob import (BlobServiceClient, BlobSasPermissions, generate_blob_sas)
from . import config

_client = None

def client() -> BlobServiceClient:
    global _client
    if _client is None:
        if config.STORAGE_CONNECTION_STRING:
            _client = BlobServiceClient.from_connection_string(config.STORAGE_CONNECTION_STRING)
        else:
            from azure.identity import DefaultAzureCredential
            _client = BlobServiceClient(config.STORAGE_ACCOUNT_URL, credential=DefaultAzureCredential())
    return _client

def container():
    c = client().get_container_client(config.BLOB_CONTAINER)
    if not c.exists():
        c.create_container()
    return c

def upload(name: str, data, content_type: str):
    from azure.storage.blob import ContentSettings
    container().upload_blob(name, data, overwrite=False,
                            content_settings=ContentSettings(content_type=content_type))

def download_url(name: str, minutes: int = 10) -> str:
    """生成短期只读 SAS：浏览器直接从存储下载，不经过 API。"""
    svc = client()
    start = datetime.now(timezone.utc) - timedelta(minutes=1)
    expiry = datetime.now(timezone.utc) + timedelta(minutes=minutes)
    kwargs = dict(account_name=svc.account_name, container_name=config.BLOB_CONTAINER,
                  blob_name=name, permission=BlobSasPermissions(read=True), expiry=expiry, start=start)
    if config.STORAGE_CONNECTION_STRING:
        kwargs["account_key"] = svc.credential.account_key          # 本机 Azurite：账户密钥 SAS
    else:
        kwargs["user_delegation_key"] = svc.get_user_delegation_key(start, expiry)  # Azure：用户委托 SAS
    sas = generate_blob_sas(**kwargs)
    if config.BLOB_PUBLIC_BASE:   # 本机：Azurite 使用路径式地址，经网关 /blob/ 转发
        return f"{config.BLOB_PUBLIC_BASE.rstrip('/')}/{svc.account_name}/{config.BLOB_CONTAINER}/{name}?{sas}"
    return f"{svc.url.rstrip('/')}/{config.BLOB_CONTAINER}/{name}?{sas}"
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/worker.py <<'ORDERS_EOF'
"""后台 Worker：消费订单消息并处理。处理逻辑是幂等的——同一消息被投递两次也只处理一次。"""
import time
from . import db, queueing
from .log import get_logger, info

log = get_logger("worker")

def handle(msg):
    order_id = msg["order_id"]
    with db.pool.connection() as conn:
        row = conn.execute("SELECT item FROM orders WHERE id=%s", (order_id,)).fetchone()
        if row and row["item"] == "poison":
            raise ValueError("模拟无法处理的“毒消息”")
        time.sleep(0.5)                                   # 模拟耗时处理
        cur = conn.execute("""UPDATE orders SET status='processed', processed_at=now()
                              WHERE id=%s AND status='pending'""", (order_id,))
    info(log, "order processed", order_id=order_id, changed=cur.rowcount)

def main():
    db.ensure_open()
    info(log, "worker started")
    queueing.consume(handle)
    db.pool.close()
    info(log, "worker stopped gracefully")

if __name__ == "__main__":
    main()
ORDERS_EOF
mkdir -p azure
cat > azure/deploy.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# 第六课：把 orders 部署到 Azure（Container Apps + PostgreSQL 灵活服务器 + Azure Managed Redis
#        + Service Bus + Blob Storage + Key Vault），全部通过用户分配托管标识访问，无连接字符串中的长期密钥（Redis/PG 密码存 Key Vault）。
# 用法：bash azure/deploy.sh    清理：az group delete -n $RG --yes --no-wait
set -euo pipefail
: "${LOC:=canadacentral}"; : "${RG:=rg-docker-hour6}"
SUFFIX=${SUFFIX:-$(openssl rand -hex 3)}
ACR=acrorders$SUFFIX; ENV=cae-orders; ID=id-orders; KV=kv-orders-$SUFFIX
PG=pg-orders-$SUFFIX; REDIS=redis-orders-$SUFFIX; SB=sb-orders-$SUFFIX; ST=storders$SUFFIX
DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')
echo "RG=$RG LOC=$LOC SUFFIX=$SUFFIX" | tee ~/hour6.env

az extension add -n containerapp --upgrade -y -o none
az extension add -n redisenterprise --upgrade -y -o none
az group create -n $RG -l $LOC -o none

# ---------- 身份 ----------
az identity create -g $RG -n $ID -o none
ID_RID=$(az identity show -g $RG -n $ID --query id -o tsv)
ID_PID=$(az identity show -g $RG -n $ID --query principalId -o tsv)
ID_CID=$(az identity show -g $RG -n $ID --query clientId -o tsv)

# ---------- 镜像 ----------
az acr create -g $RG -n $ACR --sku Basic -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
  --role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az acr build -r $ACR -t orders:1.0 ./app --no-logs
az acr build -r $ACR -t orders-web:1.0 ./web --no-logs

# ---------- 数据：PostgreSQL 灵活服务器 ----------
az postgres flexible-server create -g $RG -n $PG -l $LOC --version 17 \
  --tier Burstable --sku-name Standard_B1ms --storage-size 32 \
  --admin-user orders --admin-password "$DB_PASSWORD" \
  --public-access 0.0.0.0 --yes -o none          # 0.0.0.0 = 允许 Azure 内部服务访问；生产用 VNet 集成/私有终结点
az postgres flexible-server db create -g $RG -s $PG -d orders -o none
PG_HOST=$(az postgres flexible-server show -g $RG -n $PG --query fullyQualifiedDomainName -o tsv)

# ---------- 缓存：Azure Managed Redis ----------
az redisenterprise create -g $RG --cluster-name $REDIS -l $LOC --sku Balanced_B0 \
  --clustering-policy EnterpriseCluster --access-keys-auth Enabled -o none
REDIS_HOST=$(az redisenterprise show -g $RG --cluster-name $REDIS --query hostName -o tsv)
REDIS_KEY=$(az redisenterprise database list-keys -g $RG --cluster-name $REDIS --query primaryKey -o tsv)

# ---------- 队列：Service Bus ----------
az servicebus namespace create -g $RG -n $SB -l $LOC --sku Standard -o none
az servicebus queue create -g $RG --namespace-name $SB -n orders --max-delivery-count 5 -o none
SB_ID=$(az servicebus namespace show -g $RG -n $SB --query id -o tsv)
for r in "Azure Service Bus Data Sender" "Azure Service Bus Data Receiver"; do
  az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "$r" --scope $SB_ID -o none
done

# ---------- 对象存储：Blob ----------
az storage account create -g $RG -n $ST -l $LOC --sku Standard_LRS --kind StorageV2 \
  --allow-blob-public-access false --allow-shared-key-access false --min-tls-version TLS1_2 -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
  --role "Storage Blob Data Contributor" --scope $(az storage account show -g $RG -n $ST --query id -o tsv) -o none

# ---------- 机密：Key Vault（RBAC 模式） ----------
az keyvault create -g $RG -n $KV -l $LOC --enable-rbac-authorization true -o none
KV_ID=$(az keyvault show -n $KV --query id -o tsv)
az role assignment create --assignee $(az ad signed-in-user show --query id -o tsv) --role "Key Vault Secrets Officer" --scope $KV_ID -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $KV_ID -o none
sleep 30   # 等待 RBAC 生效
az keyvault secret set --vault-name $KV -n database-url -o none \
  --value "postgresql://orders:${DB_PASSWORD}@${PG_HOST}:5432/orders?sslmode=require"
az keyvault secret set --vault-name $KV -n redis-url -o none --value "rediss://:${REDIS_KEY}@${REDIS_HOST}:10000/0"
KV_URI=https://$KV.vault.azure.net/secrets

# ---------- 运行：Container Apps ----------
# 连接预算（B1ms 只有 35 个用户连接，且 Burstable 不支持内置 PgBouncer）：
#   api 5 副本 × 2 gunicorn 进程 × 池 2 = 20；worker 4 × 1 × 2 = 8；两个作业各 ≤ 2 → 合计 ≤ 32 < 35
az containerapp env create -g $RG -n $ENV -l $LOC -o none
IMG=$ACR.azurecr.io/orders:1.0
SECRETS="database-url=keyvaultref:$KV_URI/database-url,identityref:$ID_RID redis-url=keyvaultref:$KV_URI/redis-url,identityref:$ID_RID"
COMMON_ENV="DATABASE_URL=secretref:database-url REDIS_URL=secretref:redis-url AZURE_CLIENT_ID=$ID_CID \
 QUEUE_BACKEND=servicebus SERVICEBUS_NAMESPACE=$SB.servicebus.windows.net \
 STORAGE_ACCOUNT_URL=https://$ST.blob.core.windows.net APP_VERSION=1.0 DB_POOL_SIZE=2"

# 1) 迁移作业（手动触发，每次发布前执行一次）
az containerapp job create -g $RG -n job-migrate --environment $ENV --trigger-type Manual \
  --replica-timeout 600 --replica-retry-limit 1 --parallelism 1 --replica-completion-count 1 \
  --image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
  --secrets $SECRETS --env-vars $COMMON_ENV --command orders-migrate \
  --cpu 0.25 --memory 0.5Gi -o none
az containerapp job start -g $RG -n job-migrate -o none
echo "等待迁移完成…"; sleep 60
az containerapp job execution list -g $RG -n job-migrate --query "[0].properties.status" -o tsv

# 2) API（内部入口：只允许同一环境内的 web 访问）
az containerapp create -g $RG -n ca-orders-api --environment $ENV --image $IMG \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --ingress internal --target-port 8000 --min-replicas 1 --max-replicas 5 \
  --cpu 0.5 --memory 1Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none

# 3) Worker（无入口；按 Service Bus 队列长度用 KEDA 扩缩，可缩到 0）
az containerapp create -g $RG -n ca-orders-worker --environment $ENV --image $IMG \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --command orders-worker --min-replicas 0 --max-replicas 4 \
  --scale-rule-name sb-orders --scale-rule-type azure-servicebus \
  --scale-rule-metadata "queueName=orders" "namespace=$SB" "messageCount=5" \
  --scale-rule-identity $ID_RID \
  --cpu 0.25 --memory 0.5Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none

# 4) 每日报表（定时作业，cron 为 UTC）
az containerapp job create -g $RG -n job-report --environment $ENV --trigger-type Schedule \
  --cron-expression "15 6 * * *" --replica-timeout 900 --replica-retry-limit 2 \
  --parallelism 1 --replica-completion-count 1 \
  --image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
  --secrets $SECRETS --env-vars $COMMON_ENV --command orders-report \
  --cpu 0.25 --memory 0.5Gi -o none

# 5) Web（外部入口，ACA 托管 HTTPS；/api 反向代理到内部 API）
az containerapp create -g $RG -n ca-orders-web --environment $ENV --image $ACR.azurecr.io/orders-web:1.0 \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --ingress external --target-port 8080 --min-replicas 1 --max-replicas 3 \
  --cpu 0.25 --memory 0.5Gi --env-vars API_UPSTREAM=http://ca-orders-api -o none

FQDN=$(az containerapp show -g $RG -n ca-orders-web --query properties.configuration.ingress.fqdn -o tsv)
cat >> ~/hour6.env <<EOV
ACR=$ACR ENV=$ENV KV=$KV PG=$PG REDIS=$REDIS SB=$SB ST=$ST FQDN=$FQDN
EOV
echo "完成：https://$FQDN"
ORDERS_EOF
mkdir -p gateway
cat > gateway/nginx.conf <<'ORDERS_EOF'
# 网关：HTTPS 终止、HTTP→HTTPS 跳转、限流、静态 SPA、反向代理 API 与 Blob
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
log_format json escape=json '{"time":"$time_iso8601","remote":"$remote_addr","method":"$request_method",'
  '"uri":"$request_uri","status":$status,"bytes":$body_bytes_sent,"rt":$request_time,'
  '"upstream":"$upstream_addr","urt":"$upstream_response_time","rid":"$request_id"}';

server {
    listen 80;
    return 301 https://$host:8443$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    ssl_certificate     /etc/nginx/certs/tls.crt;
    ssl_certificate_key /etc/nginx/certs/tls.key;
    ssl_protocols       TLSv1.2 TLSv1.3;

    access_log /dev/stdout json;
    client_max_body_size 10m;
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Content-Type-Options nosniff always;

    resolver 127.0.0.11 valid=10s ipv6=off;     # Docker 内嵌 DNS：每 10 秒重新解析，发现扩缩后的副本
    set $api  http://api:8000;
    set $blob http://azurite:10000;

    location / {
        root /usr/share/nginx/html;
        try_files $uri /index.html;
    }
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        proxy_set_header Host $host;
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_connect_timeout 3s;
        proxy_read_timeout 30s;
        proxy_pass $api;
    }
    location /blob/ {                              # 仅本机演示：Azure 上浏览器直连 Blob 端点
        rewrite ^/blob/(.*)$ /$1 break;
        proxy_set_header Host azurite:10000;       # SAS 签名与 Host 无关，但 Azurite 按路径识别账户
        proxy_pass $blob;
    }
}
ORDERS_EOF
mkdir -p web
cat > web/.dockerignore <<'ORDERS_EOF'
Dockerfile
ORDERS_EOF
mkdir -p web
cat > web/Dockerfile <<'ORDERS_EOF'
# Azure 上的前端 + 反向代理（ACA 负责 HTTPS 终止，所以这里只监听 8080 的 HTTP）
FROM nginx:1.29-alpine
COPY nginx-aca.conf.template /etc/nginx/templates/default.conf.template
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 8080
ORDERS_EOF
mkdir -p web
cat > web/index.html <<'ORDERS_EOF'
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>Orders Demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem}
fieldset{margin:1rem 0}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccc;padding:4px 8px}
.pending{color:#b45309}.processed{color:#047857}pre{background:#f4f4f5;padding:.5rem;overflow:auto}</style></head>
<body>
<h1>Orders Demo</h1>
<fieldset><legend>下单（带 Idempotency-Key）</legend>
 <input id="item" value="book"> × <input id="qty" type="number" value="1" min="1" style="width:4em">
 <button onclick="order()">下单</button> <button onclick="order(true)">重复提交同一请求</button></fieldset>
<fieldset><legend>统计（Redis 缓存 10 秒）</legend><button onclick="stats()">刷新</button><pre id="stats"></pre></fieldset>
<fieldset><legend>上传文件（Blob + 短期 SAS）</legend><input type="file" id="file"> <button onclick="upload()">上传</button> <span id="link"></span></fieldset>
<h2>最近订单</h2><table><thead><tr><th>ID</th><th>商品</th><th>数量</th><th>状态</th></tr></thead><tbody id="rows"></tbody></table>
<script>
let lastKey = null;
async function order(repeat){
  const key = repeat && lastKey ? lastKey : crypto.randomUUID(); lastKey = key;
  const r = await fetch('/api/orders',{method:'POST',headers:{'Content-Type':'application/json','Idempotency-Key':key},
    body:JSON.stringify({item:item.value,qty:+qty.value})});
  alertBox(await r.json()); load();
}
function alertBox(o){ stats_.textContent = JSON.stringify(o,null,2) }
const stats_ = document.getElementById('stats');
async function stats(){ alertBox(await (await fetch('/api/stats')).json()) }
async function load(){
  const rows = await (await fetch('/api/orders')).json();
  document.getElementById('rows').innerHTML = rows.map(o=>`<tr><td>${o.id}</td><td>${o.item}</td><td>${o.qty}</td><td class="${o.status}">${o.status}</td></tr>`).join('');
}
async function upload(){
  const fd = new FormData(); fd.append('file', file.files[0]);
  const j = await (await fetch('/api/files',{method:'POST',body:fd})).json();
  link.innerHTML = `<a href="${j.url}" target="_blank">下载（10 分钟内有效）</a>`;
}
load(); setInterval(load, 2000);
</script></body></html>
ORDERS_EOF
mkdir -p web
cat > web/nginx-aca.conf.template <<'ORDERS_EOF'
# nginx 官方镜像启动时用 envsubst 把 ${API_UPSTREAM} 替换为环境变量（只替换已定义的变量）
server {
    listen 8080;
    client_max_body_size 10m;
    add_header X-Content-Type-Options nosniff always;

    location = /healthz { return 200 "ok\n"; }
    location / {
        root /usr/share/nginx/html;
        try_files $uri /index.html;
    }
    location /api/ {
        proxy_pass ${API_UPSTREAM};          # 例如 http://ca-orders-api（同一 ACA 环境内的内部入口）
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_read_timeout 30s;
    }
}
ORDERS_EOF
chmod +x gen-cert.sh azure/deploy.sh app/bin/*
echo "已生成 $D：$(find . -type f | wc -l) 个文件"
