diff --git a/src/Client.php b/src/Client.php index d6e0222..7e1ad75 100644 --- a/src/Client.php +++ b/src/Client.php @@ -3,6 +3,8 @@ namespace OramaCloud; use GuzzleHttp\Client as HttpClient; +use GuzzleHttp\Exception\RequestException; +use Psr\Http\Message\ResponseInterface; use OramaCloud\Client\Cache; use OramaCloud\Client\Query; use OramaCloud\Manager\Endpoints; @@ -22,7 +24,7 @@ public function __construct(array $params) { $params = $this->validate($params); - $this->id = uniqid('p', true); + $this->id = str_replace('.', '', uniqid('p', true)); $this->http = new HttpClient(); $this->apiKey = $params['api_key']; $this->endpoint = $params['endpoint']; @@ -40,7 +42,7 @@ public function __construct(array $params) } // Cache is enabled by default - if ($this->cache) { + if ($this->cache !== false) { $this->cache = new Cache(); } @@ -115,6 +117,41 @@ private function validate($params) private function init() { - // + $promise = $this->fetch('init', 'POST'); + $promise->then( + function (ResponseInterface $response) { + if ($this->collector !== null) { + $this->collector->setParams([ + 'endpoint' => $response->collectUrl, + 'deploymentID' => $response->deploymentID, + 'index' => $response->index + ]); + } + }, + function (RequestException $e) { + throw new \RuntimeException('Failed to initialize client'); + } + ); + } + + private function fetch($path, $method, $body = []) + { + $endpoint = "{$this->endpoint}/{$path}?api-key={$this->apiKey}"; + + $requestOptions = [ + 'headers' => [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ] + ]; + + if ($method === 'POST' && $body !== []) { + $b = $body; + $b['version'] = 'php-sdk-1.0.0'; + $b['id'] = $this->id; + + $requestOptions['body'] = http_build_query($b); + } + + return $this->http->requestAsync('POST', $endpoint, $requestOptions); } } diff --git a/src/Telemetry/Collector.php b/src/Telemetry/Collector.php index 32d9658..adcf871 100644 --- a/src/Telemetry/Collector.php +++ b/src/Telemetry/Collector.php @@ -3,7 +3,6 @@ namespace OramaCloud\Telemetry; use GuzzleHttp\Client; -use GuzzleHttp\Promise\Promise; class Collector { @@ -31,7 +30,7 @@ public function setParams($params) public static function create($config) { - $collector = new Collector($config['id'], $config['api_key']); + $collector = new Collector($config['id'], $config['api_key'], $config['flushInterval'], $config['flushSize']); $collector->start(); return $collector; @@ -41,9 +40,10 @@ public function add($data) { $this->data[] = $data; - if ($this->params != null && count($this->data) >= $this->config['flushSize']) { - $this->flush(); - } + // if ($this->params != null && count($this->data) >= $this->config['flushSize']) { + // $this->flush(); + //} + $this->flush(); } public function flush()