# nginx.conf - API Gateway 配置示例
# 适用于 OpenResty / lua-nginx-module

# 加载 Lua 模块（OpenResty 已内置）
load_module modules/ndk.so;
load_module modules/ngx_http_lua_module.so;

user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    multi_accept        on;
}

http {
    include       mime.types;
    default_type  application/json;

    # ---- Lua 全局配置 ----
    lua_package_path "/etc/nginx/lua/?.lua;/usr/local/openresty/lualib/?.lua;;";
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
    lua_code_cache    on;                    # 生产环境务必开启
    lua_max_pending_timers 1024;
    lua_max_running_timers 256;

    # ---- 共享字典 ----
    # 限流计数器
    lua_shared_dict rate_limit 10m;
    # 上游健康状态
    lua_shared_dict upstream_health 1m;
    # API Key 缓存
    lua_shared_dict api_keys 1m;

    # ---- 日志格式 ----
    log_format api_gateway
        '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $body_bytes_sent '
        '"$http_referer" "$http_user_agent" '
        'route=$arg_route upstream=$upstream_addr '
        'rt=$request_time';

    access_log /var/log/nginx/access.log api_gateway;

    # ---- 基础优化 ----
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    client_max_body_size 10m;

    # ---- 上游服务器组（由 Lua 动态选择） ----
    upstream default_backend {
        server 127.0.0.1:8080;
        keepalive 32;
    }

    server {
        listen       80;
        server_name  api.example.com;

        # ---- 健康检查端点 ----
        location /health {
            access_log off;
            default_type application/json;
            return 200 '{"status":"ok"}';
        }

        # ---- 网关统计信息 ----
        location /gateway/stats {
            internal;
            default_type application/json;
            content_by_lua_block {
                local upstream = require("upstream")
                ngx.say(upstream.stats_json())
            }
        }

        # ---- 网关主入口 ----
        location / {
            default_type application/json;

            # ---- 阶段 1: 路由匹配 ----
            access_by_lua_block {
                local gateway = require("gateway")
                gateway.handle()
            }

            # ---- 阶段 2: 请求体处理 ----
            body_filter_by_lua_block {
                local gateway = require("gateway")
                gateway.filter_response()
            }

            # ---- 阶段 3: 日志统计 ----
            log_by_lua_block {
                local gateway = require("gateway")
                gateway.log_request()
            }

            # ---- 代理到动态选择的上游 ----
            proxy_pass http://default_backend;
            proxy_set_header Host              $host;
            proxy_set_header X-Real-IP         $remote_addr;
            proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # 超时设置
            proxy_connect_timeout 5s;
            proxy_read_timeout    30s;
            proxy_send_timeout    15s;
        }

        # ---- 静态资源 ----
        location /static/ {
            alias /usr/share/nginx/html/;
            expires 30d;
            add_header Cache-Control "public, immutable";
        }

        # ---- 错误页 ----
        error_page 502 503 504 /50x.json;
        location = /50x.json {
            internal;
            default_type application/json;
            return 502 '{"error":"bad_gateway","message":"上游服务不可用"}';
        }
    }
}
