Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable telemetry php sdk #276

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/Checkout/AbstractCheckoutSdkBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ abstract class AbstractCheckoutSdkBuilder
protected $environmentSubdomain;
protected $httpClientBuilder;
protected $logger;
protected $enableTelemetry;

public function __construct()
{
$this->environment = Environment::sandbox();
$this->httpClientBuilder = new DefaultHttpClientBuilder([]);
$this->setDefaultLogger();
$this->enableTelemetry = true;
}

/**
Expand Down Expand Up @@ -50,6 +52,15 @@ public function httpClientBuilder(HttpClientBuilderInterface $httpClientBuilder)
$this->httpClientBuilder = $httpClientBuilder;
return $this;
}
/**
* @param bool $enableTelemetry
* @return $this
*/
public function enableTelemetry($enableTelemetry)
{
$this->enableTelemetry = $enableTelemetry;
return $this;
}

/**
* @param LoggerInterface $logger
Expand All @@ -70,7 +81,8 @@ protected function getCheckoutConfiguration()
$this->getSdkCredentials(),
$this->environment,
$this->httpClientBuilder,
$this->logger
$this->logger,
$this->enableTelemetry
);
}

Expand Down
131 changes: 94 additions & 37 deletions lib/Checkout/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace Checkout;

use Checkout\Common\AbstractQueryFilter;
use Checkout\Common\RequestMetrics;
use Checkout\Files\FileRequest;
use Checkout\Common\TelemetryQueue;
use Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
Expand All @@ -21,13 +23,19 @@ class ApiClient

private $baseUri;

private $enableTelemetry;

private $requestMetricsQueue;

public function __construct(CheckoutConfiguration $configuration, $baseUri = null)
{
$this->configuration = $configuration;
$this->client = $configuration->getHttpClientBuilder()->getClient();
$this->jsonSerializer = new JsonSerializer();
$this->logger = $this->configuration->getLogger();
$this->baseUri = $baseUri != null ? $baseUri : $this->configuration->getEnvironment()->getBaseUri();
$this->enableTelemetry = $this->configuration->isEnableTelemetry();
$this->requestMetricsQueue = new TelemetryQueue();
}

/**
Expand Down Expand Up @@ -133,31 +141,49 @@ public function submitFileFilesApi($path, FileRequest $fileRequest, SdkAuthoriza
}

/**
* Summary of handleRequest
* @param $method
* @param $path
* @param FileRequest $fileRequest
* @param SdkAuthorization $authorization
* @param $multipart
* @param \Checkout\SdkAuthorization $authorization
* @param array $requestOptions
* @throws \Checkout\CheckoutApiException
* @return array
* @throws CheckoutApiException
*/
private function submit($path, FileRequest $fileRequest, SdkAuthorization $authorization, $multipart)
private function handleRequest($method, $path, SdkAuthorization $authorization, array $requestOptions)
{
try {
$this->logger->info("POST " . $path . " file: " . $fileRequest->file);
$headers = $this->getHeaders($authorization, null, null);
$response = $this->client->request("POST", $this->getRequestUrl($path), [
"verify" => false,
"headers" => $headers,
"multipart" => [
[
"name" => $multipart,
"contents" => fopen($fileRequest->file, "r")
],
[
"name" => "purpose",
"contents" => $fileRequest->purpose
]
]]);
$headers = $requestOptions['headers'];

if ($this->enableTelemetry) {
$currentRequestId = uniqid();
$lastRequestMetric = new RequestMetrics();
$dequeuedMetric = $this->requestMetricsQueue->dequeue();


if ($dequeuedMetric !== null) {
$lastRequestMetric->requestId = $currentRequestId;
$headers["Cko-Sdk-Telemetry"] = base64_encode(json_encode([
'prev-request-id' => $lastRequestMetric->prevRequestId,
'prev-request-duration' => $lastRequestMetric->prevRequestDuration
]));
}

$startTime = microtime(true);
$response = $this->client->request($method, $this->getRequestUrl($path), array_merge(
$requestOptions,
['headers' => $headers]
));
$duration = (int)((microtime(true) - $startTime) * 1000);

$lastRequestMetric->prevRequestDuration = $duration;
$lastRequestMetric->prevRequestId = $currentRequestId;
$this->requestMetricsQueue->enqueue($lastRequestMetric);
} else {
$response = $this->client->request($method, $this->getRequestUrl($path), array_merge(
$requestOptions,
['headers' => $headers]
));
}
return $this->getResponseContents($response);
} catch (Exception $e) {
$this->logger->error($path . " error: " . $e->getMessage());
Expand All @@ -168,6 +194,38 @@ private function submit($path, FileRequest $fileRequest, SdkAuthorization $autho
}
}

/**
* @param $path
* @param FileRequest $fileRequest
* @param SdkAuthorization $authorization
* @param $multipart
* @return array
* @throws CheckoutApiException
*/
private function submit($path, FileRequest $fileRequest, SdkAuthorization $authorization, $multipart)
{
// Keep specific logging in submit
$this->logger->info("POST " . $path . " file: " . $fileRequest->file);

$headers = $this->getHeaders($authorization, null, null, null);
$requestOptions = [
"verify" => false,
"headers" => $headers,
"multipart" => [
[
"name" => $multipart,
"contents" => fopen($fileRequest->file, "r")
],
[
"name" => "purpose",
"contents" => $fileRequest->purpose
]
]
];

return $this->handleRequest("POST", $path, $authorization, $requestOptions);
}

/**
* @param string $method
* @param string $path
Expand All @@ -179,22 +237,17 @@ private function submit($path, FileRequest $fileRequest, SdkAuthorization $autho
*/
private function invoke($method, $path, $body, SdkAuthorization $authorization, $idempotencyKey = null)
{
try {
$this->logger->info($method . " " . $path);
$headers = $this->getHeaders($authorization, "application/json", $idempotencyKey);
$response = $this->client->request($method, $this->getRequestUrl($path), [
"verify" => false,
"body" => $body,
"headers" => $headers
]);
return $this->getResponseContents($response);
} catch (Exception $e) {
$this->logger->error($path . " error: " . $e->getMessage());
if ($e instanceof RequestException) {
throw CheckoutApiException::from($e);
}
throw new CheckoutApiException($e);
}
// Keep specific logging in invoke
$this->logger->info($method . " " . $path);

$headers = $this->getHeaders($authorization, "application/json", $idempotencyKey, null);
$requestOptions = [
"verify" => false,
"body" => $body,
"headers" => $headers
];

return $this->handleRequest($method, $path, $authorization, $requestOptions);
}

/**
Expand All @@ -210,10 +263,11 @@ private function getRequestUrl($path)
* @param SdkAuthorization $authorization
* @param string|null $contentType
* @param string|null $idempotencyKey
* @param string|null $telemetryData
* @return array
* @throws CheckoutAuthorizationException
*/
private function getHeaders(SdkAuthorization $authorization, $contentType, $idempotencyKey)
private function getHeaders(SdkAuthorization $authorization, $contentType, $idempotencyKey, $telemetryData)
{
$headers = [
"User-agent" => CheckoutUtils::PROJECT_NAME . "/" . CheckoutUtils::PROJECT_VERSION,
Expand All @@ -226,6 +280,9 @@ private function getHeaders(SdkAuthorization $authorization, $contentType, $idem
if (!empty($idempotencyKey)) {
$headers["Cko-Idempotency-Key"] = $idempotencyKey;
}
if (!empty($telemetryData)) {
$headers["Cko-Sdk-Telemetry"] = base64_encode(json_encode($telemetryData));
}
return $headers;
}

Expand Down
15 changes: 14 additions & 1 deletion lib/Checkout/CheckoutConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,29 @@ final class CheckoutConfiguration
private $httpClientBuilder;

private $logger;

private $enableTelemetry;

/**
* @param SdkCredentialsInterface $sdkCredentials
* @param Environment $environment
* @param HttpClientBuilderInterface $httpClientBuilder
* @param LoggerInterface $logger
* @param bool $enableTelemetry
*/
public function __construct(
SdkCredentialsInterface $sdkCredentials,
Environment $environment,
HttpClientBuilderInterface $httpClientBuilder,
LoggerInterface $logger
LoggerInterface $logger,
$enableTelemetry = true
) {
$this->sdkCredentials = $sdkCredentials;
$this->environment = $environment;
$this->httpClientBuilder = $httpClientBuilder;
$this->logger = $logger;
$this->environmentSubdomain = null;
$this ->enableTelemetry = $enableTelemetry;
}

/**
Expand Down Expand Up @@ -79,4 +84,12 @@ public function getLogger()
{
return $this->logger;
}

/**
* @return bool
*/
public function isEnableTelemetry()
{
return $this->enableTelemetry;
}
}
4 changes: 3 additions & 1 deletion lib/Checkout/CheckoutOAuthSdkBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ public function build()
$this->getSdkCredentials(),
$this->environment,
$this->httpClientBuilder,
$this->logger
$this->logger,
$this->enableTelemetry
);
// $configuration = $this->getCheckoutConfiguration();
if ($this->environmentSubdomain !== null) {
$configuration->setEnvironmentSubdomain($this->environmentSubdomain);
}
Expand Down
4 changes: 3 additions & 1 deletion lib/Checkout/CheckoutStaticKeysSdkBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ public function build()
$this->getSdkCredentials(),
$this->environment,
$this->httpClientBuilder,
$this->logger
$this->logger,
$this->enableTelemetry
);
// $configuration = $this->getCheckoutConfiguration();
if ($this->environmentSubdomain !== null) {
$configuration->setEnvironmentSubdomain($this->environmentSubdomain);
}
Expand Down
17 changes: 17 additions & 0 deletions lib/Checkout/Common/RequestMetrics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Checkout\Common;

class RequestMetrics
{
public $prevRequestId;
public $requestId;
public $prevRequestDuration;

public function __construct($prevRequestId = null, $requestId = null, $prevRequestDuration = null)
{
$this->prevRequestId = $prevRequestId;
$this->requestId = $requestId;
$this->prevRequestDuration = $prevRequestDuration;
}
}
48 changes: 48 additions & 0 deletions lib/Checkout/Common/TelemetryQueue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Checkout\Common;

class TelemetryQueue
{
const MAX_COUNT_IN_TELEMETRY_QUEUE = 10;
private $queue;
private $mutex;

public function __construct()
{
$this->queue = [];
$this->mutex = fopen(sys_get_temp_dir() . '/telemetry_queue.lock', 'w+');
}

public function __destruct()
{
if ($this->mutex) {
fclose($this->mutex);
}
}

public function enqueue($metrics)
{
flock($this->mutex, LOCK_EX);
try {
if (count($this->queue) < self::MAX_COUNT_IN_TELEMETRY_QUEUE) {
$this->queue[] = $metrics;
}
} finally {
flock($this->mutex, LOCK_UN);
}
}

public function dequeue()
{
flock($this->mutex, LOCK_EX);
try {
if (empty($this->queue)) {
return null;
}
return array_shift($this->queue);
} finally {
flock($this->mutex, LOCK_UN);
}
}
}
7 changes: 7 additions & 0 deletions lib/Checkout/OAuthSdkCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,14 @@ public function getAuthorization($authorizationType)
*/
private function getAccessToken()
{
printf("ClientId: %s\n", $this->clientId);
printf("ClientSecret: %s\n", $this->clientSecret);

if (!is_null($this->accessToken) && $this->accessToken->isValid()) {
return $this->accessToken;
}
try {
printf("Scope string: %s\n", implode(" ", $this->scopes));
$response = $this->client->request("POST", $this->authorizationUri, [
"verify" => false,
"headers" => [
Expand All @@ -101,7 +105,10 @@ private function getAccessToken()
"scope" => implode(" ", $this->scopes)
]
]);
printf($response);
$body = json_decode($response->getBody(), true);
printf("This is a body!");
print_r($body);
$expirationDate = new DateTime();
$expirationDate->add(new DateInterval("PT" . $body["expires_in"] . "S"));
$this->accessToken = new OAuthAccessToken($body["access_token"], $expirationDate);
Expand Down
Loading