<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Protocols\Http\Response;
use Workerman\Protocols\Http;

define('WORKERNAME', 'WebServer');

// #### http worker ####
$http_worker = new Worker("http://0.0.0.0:8285");
$workerCount = defined('GATEWAY_PROCESSES_COUNT') ? GATEWAY_PROCESSES_COUNT : WEBSERVER_PROCESSES_COUNT;
//// 4 processes
$http_worker->count = $workerCount;
$http_worker->name = 'crazy_god_API_gateway';
// Emitted when data received

$http_worker->onWorkerStart= function($worker){
        global $dbs;
        global $rediss;
        $dbs = oo::commonOprDb('common');
        $dbs->connect();
        $redisArr =['common','statistics'];
        foreach ($redisArr as $v){
            $rediss[$v] = oo::commonOprRedis($v);
        }
        $time_id = Timer::add(5, function () use (&$time_id,$redisArr) {
            global $dbs;
            global $rediss;
            if(!$dbs->ping()){//失败释放内存，重连
                echo date('Y-m-d H:i:s').'close-mysql'."\r\n";
                $dbs->close();
                oo::$objDb =[];
                $dbs = oo::commonOprDb('common');
            }
            foreach ($redisArr as $v){
                if(!$rediss[$v]->ping()){//失败释放内存，重连
                    echo date('Y-m-d H:i:s').'close-redis'."\r\n";
                    $rediss[$v]->close();
                    oo::$objRedis =[];
                    $rediss[$v] = oo::commonOprRedis('common');
                }
            }
        });
        require_once WWWROOT . "lib/ProtocolsEvent.php";//解码
        require_once WWWROOT . 'api/gateway_new.php';
        require_once WWWROOT . 'api/config_new.php';
};

/**
 * Notes:
 * User: wsc
 * Time: 2021/1/19 16:29
 * @param $connection
 * @param $request Workerman\Protocols\Http\Request
 */
$http_worker->onMessage = function($connection, $request)
{
    $gets =$request->get();
    $posts =$request->post();
    $uri = $request->path();
    $ips = $request->header('x-forwarded-for');
    $ip ='';
    if(!empty($ips)){
       $ips = explode(',',$ips);
       $ip=$ips?$ips[0]:'';
    }
    $host = $request->header('host');
    //get请求
    if (isset($gets)&&!empty($gets)) {
        $getParams = $gets;
    }
    //post请求
    if (isset($posts)&&!empty($posts)) {
        $getParams = $posts;
    }
    //加密则重置请求参数
    if(isset($getParams['param'])&&!empty($getParams['param'])){
        $getParams =  ProtocolsEvent::apiDecodeNew($getParams['param']);
    }

    $getParams['from_ip']   = $ip;
    $getParams['from_host'] = $host;

    if(in_array($uri, ['/api/config.php', '/api/config_crazy.php'])){
        $ret = (new ConfigNew)->start($getParams);
    }else{
        $ret = (new GatewayNew)->start($getParams);
    }
    if(is_array($ret)){
        $ret = json_encode($ret,32);
    }
    $response = new Response(200, [
        'Access-Control-Allow-Origin'  => '*',
        'Access-Control-Allow-Method'  => '*',
        'Access-Control-Allow-Headers' => 'Content-Type',
        'Content-Type'                 => 'text/plain;charset=UTF-8',
        //'Connection'                   => 'keep-alive',
        //'Keep-Alive'                   => 'timeout=5, max=100',
    ], $ret);
    $connection->send($response);
};
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}


