user  root;
worker_processes  auto;
worker_cpu_affinity auto; 
worker_rlimit_nofile 65535;

error_log logs/error.log error;

env SERVER_ID;
env SERVER_COLO;
env SERVER_NAME;
# 节点类型 edge or origin
env NODE_TYPE;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
}

http {
	# Log settings
	log_format custom_format '$remote_addr [$time_local] '
    					'"$request" $zone_id $status $body_bytes_sent '
    					'"$http_referer" "$http_user_agent" '
    					'$host $upstream_addr $upstream_response_length '
    					'$request_time $upstream_response_time '
    					'$upstream_cache_status '
    					'$upstream_status '
    					'$scheme $ssl_protocol $bytes_sent';
	access_log logs/access.log custom_format;

	# Basic nginx settings
	include mime.types;
	default_type application/octet-stream;
	sendfile on;
	server_tokens off;

	# Timeout Settings
	client_body_timeout 100s;
	keepalive_timeout  75s;
	send_timeout 60s;

	# GeoIP module configs
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        auto_reload 5m;
        $geoip2_data_country_code default=US source=$remote_addr country iso_code;
    }
    geoip2 /usr/share/GeoIP/GeoLite2-ASN.mmdb {
        auto_reload 5m;
        $geoip2_data_asn_number autonomous_system_number;
    }
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

	include gzip.conf;
    include brotli.conf;
    include zstd.conf;
    include cache.conf;
    include server.conf;
	include /usr/local/openresty/nginx/conf.d/*.conf;

	resolver 8.8.8.8 8.8.4.4 1.1.1.1 1.0.0.1 208.67.222.222 208.67.220.220 valid=5s;
    resolver_timeout 30s;

	# Path to lua library
	lua_package_path "/usr/local/openresty/lualib/?.lua;/usr/local/openresty/site/lualib/?.lua;";

	# Turn on in production
	lua_code_cache on;
	lua_http10_buffering on;

	# Shared dictionaries
	lua_shared_dict mlcache_1 100m;
	lua_shared_dict mlcache_2 100m;
	lua_shared_dict mlcache_hit_1 100m;
	lua_shared_dict mlcache_miss_1 100m;
	lua_shared_dict mlcache_hit_2 100m;
	lua_shared_dict mlcache_miss_2 100m;
	lua_shared_dict mlcache_lock 100m;
	lua_shared_dict cache_stats 100m;
	lua_shared_dict cache_meta 100m;

	# Initialize modules for better performance
	init_by_lua_file /usr/local/openresty/lualib/sm/init.lua;

	# Upstream settings
	upstream dynamic_proxy {
		server 0.0.0.1;
		zone dynamic_proxy 100m;
		balancer_by_lua_file /usr/local/openresty/lualib/sm/service/balancer.lua;
		keepalive_timeout 120s;
		keepalive 100;
	}

	# Cache storage settings
	proxy_cache_path /data/cache/ levels=1:2 keys_zone=global_cache:100m max_size=10g inactive=7d use_temp_path=off;

	server {
		listen 80;
		listen 443 ssl;
		http2 on;
		server_name _;

		# Default fallback SSL
		ssl_certificate_by_lua_file /usr/local/openresty/lualib/sm/service/ssl.lua;
		ssl_certificate /usr/local/openresty/nginx/certs/server.crt;
		ssl_certificate_key /usr/local/openresty/nginx/certs/server.key;


		# DNS resolver
		resolver 1.1.1.1;
		# resolver 127.0.0.11 ipv6=off;
		vhost_traffic_status_filter_by_set_key $zone_id;

		# Nginx var scrope variables
		set_by_lua_block $server_id { return os.getenv('SERVER_ID') }
		set_by_lua_block $server_colo { return os.getenv('SERVER_COLO') }
		set_by_lua_block $node_type { return os.getenv('NODE_TYPE') }
		set $template_root /usr/local/openresty/lualib/sm/templates;
		set $cache_key '';
		set $backend_protocol 'https://';
		set $upstream_proxy 'dynamic_proxy';
		set $zone_id '';
		set $site '';
		set $sources '';
		set $origin_request_headers '';
		set $origin_response_headers '';
		set $cache_config '';
		set $gzip_config 'off';
		set $trim_flag 'off';
		set $trim_js 'off';
		set $trim_css 'off';
		set $zstd_flag 'off';
		set $brotli_flag 'off';
		set $gzip_flag 'off';
		set $proxy_host $host;

		# SSL Certificate
		lua_ssl_verify_depth 2;
		lua_ssl_trusted_certificate /usr/local/openresty/nginx/certs/server.crt;

		# Set default headers
		header_filter_by_lua_file /usr/local/openresty/lualib/sm/service/headers.lua;
		body_filter_by_lua_file /usr/local/openresty/lualib/sm/service/body_filter.lua;

		# Log requests
		# log_by_lua_file /usr/local/openresty/lualib/sm/service/log.lua;

		# Cache settings
		proxy_cache_min_uses 1;
		proxy_buffering on;
	 	proxy_http_version 1.1;
	 	proxy_connect_timeout 60;
	 	proxy_intercept_errors on;

	 	# Ignore special headers
	 	proxy_ignore_headers X-Accel-Expires X-Accel-Redirect X-Accel-Limit-Rate X-Accel-Buffering X-Accel-Charset;

	 	# Set headers to proxy
	 	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_set_header Connection '';
		proxy_set_header Host $proxy_host;

		# WebSocket
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection $connection_upgrade;

		proxy_ssl_server_name on;
        proxy_ssl_verify off;

  		# Set CDN specific headers to proxy
	 	proxy_set_header X-Server-ID $server_id;
	 	proxy_set_header X-Server-Colo $server_colo;
	 	proxy_set_header X-Request-ID $request_id;
	 	proxy_set_header X-Request-Country $geoip2_data_country_code;

		# Disable etag
		etag off;
	 	proxy_hide_header etag;

		# prefetch
		trim $trim_flag;
		trim_js $trim_js;
		trim_css $trim_css;
        zstd $zstd_flag;
		brotli $brotli_flag;
		gzip $gzip_flag;

		# Proxy Error Pages
		error_page 500 502 503 504 /error5xx;
		location = /error5xx {
			internal;
			content_by_lua_file /usr/local/openresty/lualib/sm/service/errors.lua;
		}
		location /service-monitor/a7k2x9m4 {
    		access_log off;
    		return 200 "OK\n";
    		add_header Content-Type text/plain;
    	}
		# 火山证书验证
		location /.well-known/acme-challenge/ {
			proxy_pass http://43.157.243.236:80;
		}


		location /@proxy/ {
			rewrite_by_lua_block {
                require("sm.service.proxy").rewrite()
            }
			access_by_lua_block {
                require("sm.service.access").access()
            }
			proxy_cache global_cache;
			proxy_cache_key $cache_key;
			proxy_cache_valid 200 302 304 307 365d;
			proxy_pass $backend_protocol$upstream_proxy;
		}

        location / {
            rewrite_by_lua_block {
                require("sm.service.rewrite").rewrite()
            }
			access_by_lua_block {
                require("sm.service.access").access()
            }
			proxy_cache global_cache;
			proxy_cache_key $cache_key;
			proxy_pass $backend_protocol$upstream_proxy;            
        }
	}
}