<?php


namespace Mainto\RpcServer\RpcServer\Connection;


use Mainto\RpcServer\RpcServer\BaseRpcConnection;
use Mainto\RpcServer\RpcServer\ConnectionHandler;
use Mainto\RpcServer\Util\Net\Net;
use Throwable;

class RpcFastMqConnection extends BaseRpcConnection {
    /**
     * RpcFastMqConnection constructor.
     * @param $name
     * @param ConnectionHandler $handler
     */
    private function __construct ($name, ConnectionHandler $handler) {
        parent::__construct(Net::dial("fastmq", $name), $name, $handler);
    }

    public static function tryNewInstance ($address, ConnectionHandler $handler) {
        return new static($address, $handler);
    }

    /**
     * @param $address
     * @param ConnectionHandler $handler
     * @param $second
     * @return RpcFastMqConnection
     * @throws Throwable
     */
    public static function mustNewInstance ($address, ConnectionHandler $handler, $second) {
        $times = $second / 0.3;
        $i = 0;
        while (true) {
            try {
                return static::tryNewInstance($address, $handler);
            } catch (Throwable $exception) {
                if ($i++ > $times) {
                    throw $exception;
                }
                usleep(1000 * 300);
            }
        }
    }
}