Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
datashaman committed Oct 25, 2024
1 parent 39e2528 commit 08259ad
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 159 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/.envrc
/.idea/
/.phpunit.cache/
/.phpunit.result.cache
/composer.lock
/vendor
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
"ext-pcre": "*",
"ext-simplexml": "*",
"illuminate/notifications": "^9 || ^10 || ^11",
"illuminate/support": "^9 || ^10 || ^11"
"illuminate/support": "^9 || ^10 || ^11",
"guzzlehttp/guzzle": "^7",
"guzzlehttp/promises": "^2",
"guzzlehttp/psr7": "^1 || ^2"
},
"require-dev": {
"ext-dom": "*",
Expand Down
25 changes: 6 additions & 19 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,23 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
</coverage>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd" bootstrap="vendor/autoload.php" backupGlobals="false" colors="true" processIsolation="false" stopOnFailure="false" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<testsuites>
<testsuite name="RIMU Service Bus Test Suite">
<directory suffix="Test.php">tests</directory>
Expand All @@ -30,4 +12,9 @@
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
</php>
<source>
<include>
<directory suffix=".php">src/</directory>
</include>
</source>
</phpunit>
183 changes: 106 additions & 77 deletions src/ServiceBusChannel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

namespace Ringierimu\ServiceBusNotificationsChannel;

use Illuminate\Http\Client\RequestException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Ringierimu\ServiceBusNotificationsChannel\Exceptions\CouldNotSendNotification;
use Throwable;

/**
* Class ServiceBusChannel.
Expand All @@ -29,8 +31,13 @@ class ServiceBusChannel
*/
public function __construct(array $config = [])
{
$this->config = $config ?: config("services.service_bus");
$this->client = Http::baseUrl(Arr::get($this->config, "endpoint"));
$this->config = $config ?: config('services.service_bus');

$this->client = new Client(
[
'base_uri' => Arr::get($this->config, 'endpoint'),
]
);
}

/**
Expand All @@ -40,22 +47,29 @@ public function __construct(array $config = [])
* @param Notification $notification
*
* @throws CouldNotSendNotification
* @throws GuzzleException
* @throws Throwable
*/
public function send($notifiable, Notification $notification)
{
/** @var ServiceBusEvent $event */
$event = $notification->toServiceBus($notifiable);
$eventType = $event->getEventType();
$params = $event->getParams();
$dontReport = Arr::get($this->config, "dont_report", []);
$dontReport = Arr::get($this->config, 'dont_report', []);

if (Arr::get($this->config, "enabled") == false) {
if (Arr::get($this->config, 'enabled') == false) {
if (!in_array($eventType, $dontReport)) {
Log::debug("$eventType service bus notification [disabled]", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
]);
Log::debug(
"$eventType service bus notification [disabled]",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
]
);
}

return;
Expand All @@ -64,32 +78,46 @@ public function send($notifiable, Notification $notification)
$token = $this->getToken();

$headers = [
"Accept" => "application/json",
"Content-type" => "application/json",
"x-api-key" => $token,
'Accept' => 'application/json',
'Content-type' => 'application/json',
'x-api-key' => $token,
];

try {
$response = $this->client
->withHeaders($headers)
->post($this->getUrl("events"), [$params])
->throw();

Log::info("$eventType service bus notification", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
"status" => $response->status(),
]);
} catch (RequestException $exception) {
$status = $exception->response->status();
$response = $this->client->request(
'POST',
$this->getUrl('events'),
[
'headers' => $headers,
'json' => [$params],
]
);

if (in_array($status, [401, 403])) {
Log::info("{$status} received. Logging in and retrying.", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
]);
Log::info(
"$eventType service bus notification",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
'status' => $response->getStatusCode(),
]
);
} catch (RequestException $exception) {
$code = $exception->getCode();

if (in_array($code, [401, 403])) {
Log::info(
"$code received. Logging in and retrying.",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
]
);

// clear the invalid token //
Cache::forget($this->generateTokenKey());
Expand All @@ -111,53 +139,51 @@ public function send($notifiable, Notification $notification)

/**
* @throws CouldNotSendNotification
* @throws GuzzleException
*
* @return string
*/
private function getToken(): string
{
return Cache::rememberForever($this->generateTokenKey(), function () {
try {
$version = intval($this->config["version"]);

if ($version < 2) {
$response = $this->client
->post(
$this->getUrl("login"),
Arr::only($this->config, [
"username",
"password",
"venture_config_id",
])
)
->throw();
} else {
$response = $this->client
->post(
$this->getUrl("login"),
Arr::only($this->config, [
"username",
"password",
"node_id",
])
)
->throw();
return Cache::rememberForever(
$this->generateTokenKey(),
function () {
try {
$version = intval($this->config['version']);

if ($version < 2) {
$response = $this->client->request(
'POST',
$this->getUrl('login'),
[
'json' => Arr::only($this->config, ['username', 'password', 'venture_config_id']),
]
);
} else {
$response = $this->client->request(
'POST',
$this->getUrl('login'),
[
'json' => Arr::only($this->config, ['username', 'password', 'node_id']),
]
);
}

$body = json_decode((string) $response->getBody(), true);

$code = (int) Arr::get($body, 'code', $response->getStatusCode());

switch ($code) {
case 200:
return $body['token'];
default:
throw CouldNotSendNotification::loginFailed($response);
}
} catch (RequestException $exception) {
throw CouldNotSendNotification::requestFailed($exception);
}

$body = $response->json();

$code = (int) Arr::get($body, "code", $response->status());

switch ($code) {
case 200:
return $body["token"];
default:
throw CouldNotSendNotification::loginFailed($response);
}
} catch (RequestException $exception) {
throw CouldNotSendNotification::requestFailed($exception);
}
});
);
}

/**
Expand All @@ -172,15 +198,18 @@ private function getUrl(string $endpoint): string

public function generateTokenKey()
{
$version = intval($this->config["version"]);
$version = intval($this->config['version']);

if ($version < 2) {
return md5(
"service-bus-token" .
Arr::get($this->config, "venture_config_id")
'service-bus-token' .
Arr::get($this->config, 'venture_config_id')
);
}

return md5("service-bus-token" . Arr::get($this->config, "node_id"));
return md5(
'service-bus-token' .
Arr::get($this->config, 'node_id')
);
}
}
Loading

0 comments on commit 08259ad

Please sign in to comment.