keboola / notification-api-php-client
Client for Notification API
Package info
github.com/keboola/notification-api-php-client
pkg:composer/keboola/notification-api-php-client
Requires
- php: ^8.2
- ext-json: *
- guzzlehttp/guzzle: ^7.8
- keboola/php-api-client-base: ^1.0
- psr/log: ^2|^3
Requires (Dev)
- infection/infection: ^0.26
- keboola/coding-standard: >=14.0
- monolog/monolog: ^3.9
- phpstan/phpstan: ^1.8
- phpstan/phpstan-phpunit: ^1.1
- phpunit/phpunit: ^9.5
- symfony/dotenv: ^5.2|^6.0
README
PHP client for the Notification API (API docs).
Usage
The client is built on keboola/php-api-client-base.
Each client takes the already-resolved Notification API base URL (resolve it yourself, e.g. with
keboola/service-client's getNotificationServiceUrl()).
Authorization:
SubscriptionClient— Storage API token (required).EventsClient(scopenotifications:push-event) andNotificationsClient(scopenotifications:send-notification) — Manage API Application token. Passnullinstead of a token to authenticate via the projected Kubernetes ServiceAccount token (seeKeboolaServiceAccountAuthenticatorin the base package).
composer require keboola/notification-api-php-client
use DateTimeImmutable; use Keboola\NotificationClient\EventsClient; use Keboola\NotificationClient\Requests\Event; use Keboola\NotificationClient\Requests\PostEvent\JobData; use Keboola\NotificationClient\Requests\PostEvent\JobFailedEventData; $client = new EventsClient( 'https://notification.connection.keboola.com/', 'xxx-xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // or null to use the ServiceAccount token backoffMaxTries: 3, userAgent: 'my-service', ); $client->postEvent( new Event( new JobFailedEventData( '123', 'My Project', 'branch-id', 'Job finished with error', new JobData( '456', 'http://someUrl', new DateTimeImmutable('2020-01-01T11:11:00+00:00'), new DateTimeImmutable('2020-01-01T11:12:00+00:00'), 'keboola.orchestrator', 'Orchestrator', 'my-configuration', 'My configuration', ), ) ) );
Subscription client
use Keboola\NotificationClient\Requests\PostSubscription\EmailRecipient; use Keboola\NotificationClient\Requests\PostSubscription\Filter; use Keboola\NotificationClient\Requests\Subscription; use Keboola\NotificationClient\SubscriptionClient; $subscriptionClient = new SubscriptionClient( 'https://notification.connection.keboola.com/', 'xxx-storage-api-token', ); // create a subscription $created = $subscriptionClient->createSubscription(new Subscription( 'job-failed', new EmailRecipient('you@example.com'), [new Filter('project.id', '123')], )); // list all subscriptions for the project (returned by token) $subscriptions = $subscriptionClient->listSubscriptions(); foreach ($subscriptions as $subscription) { echo $subscription->getId() . ': ' . $subscription->getEvent() . "\n"; } // fetch a single subscription by ID $subscription = $subscriptionClient->getSubscription($created->getId()); // delete a subscription $subscriptionClient->deleteSubscription($created->getId());
Responses\Filter::getValue() returns int|float|bool|string|null — the
value type matches whatever the API returns (for example
durationOvertimePercentage returns float).
Subscription response recipients
Responses\Subscription exposes the recipient as a polymorphic Value Object via getRecipient(): RecipientInterface. Two concrete types live under Keboola\NotificationClient\Responses\Recipient:
EmailRecipient—getChannel()returns'email',getAddress(): stringWebhookRecipient—getChannel()returns'webhook',getUrl(): string
Use instanceof to narrow:
use Keboola\NotificationClient\Responses\Recipient\EmailRecipient; use Keboola\NotificationClient\Responses\Recipient\WebhookRecipient; $recipient = $subscription->getRecipient(); if ($recipient instanceof EmailRecipient) { $email = $recipient->getAddress(); } elseif ($recipient instanceof WebhookRecipient) { $url = $recipient->getUrl(); }
Development
-
Create an Azure service principal to download the required images and login:
SERVICE_PRINCIPAL_NAME=[USERNAME]-notification-api-pull ACR_REGISTRY_ID=$(az acr show --name keboolapes --query id --output tsv --subscription c5182964-8dca-42c8-a77a-fa2a3c6946ea) SP_PASSWORD=$(az ad sp create-for-rbac --name http://$SERVICE_PRINCIPAL_NAME --scopes $ACR_REGISTRY_ID --role acrpull --query password --output tsv) SP_APP_ID=$(az ad sp show --id http://$SERVICE_PRINCIPAL_NAME --query appId --output tsv) -
Login and check that you can pull the image:
docker login keboolapes.azurecr.io --username $SP_APP_ID --password $SP_PASSWORD docker pull keboolapes.azurecr.io/notification-service:latest
-
Add the credentials to the k8s cluster:
kubectl create secret docker-registry regcred --docker-server="https://keboolapes.azurecr.io" --docker-username="$SP_APP_ID" --docker-password="$SP_PASSWORD" --namespace dev-notification-client kubectl patch serviceaccount default -p "{\"imagePullSecrets\":[{\"name\":\"regcred\"}]}" --namespace dev-notification-client
-
Set the following environment variables in
set-env.shfile (useset-env.template.shas sample):TEST_STORAGE_API_TOKEN- Token to a test project.TEST_STORAGE_API_PROJECT_ID- Project ID of the test project.TEST_MANAGE_API_APPLICATION_TOKEN- Application token with scopenotifications:push-event.
-
Set one of Azure or AWS resources (or both, but only one is needed).
AWS Setup
- Create a user (
NotificationUser) for local development using theprovisioning/aws.jsonCF template.- Create AWS key for the created user.
- Set the following environment variables in
set-env.shfile (useset-env.template.shas sample):TEST_AWS_ACCESS_KEY- The created security credentials for theJobQueueApiPhpClientuser.TEST_AWS_SECRET_ACCESS_KEY- The created security credentials for theJobQueueApiPhpClientuser.AWS_REGION-Regionoutput of the above stack.
Azure Setup
-
Create a resource group:
az account set --subscription "Keboola DEV PS Team CI" az group create --name testing-notification-api-php-client --location "East US"
-
Create a service principal:
az ad sp create-for-rbac --name testing-notification-api-php-client
-
Use the response to set values
TEST_AZURE_CLIENT_ID,TEST_AZURE_CLIENT_SECRETandTEST_AZURE_TENANT_IDin theset-env.shfile:{ "appId": "268a6f05-xxxxxxxxxxxxxxxxxxxxxxxxxxx", //-> TEST_AZURE_CLIENT_ID "displayName": "testing-notification-api-php-client", "name": "http://testing-notification-api-php-client", "password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //-> TEST_AZURE_CLIENT_SECRET "tenant": "9b85ee6f-xxxxxxxxxxxxxxxxxxxxxxxxxxx" //-> TEST_AZURE_TENANT_ID } -
Get ID of the service principal:
SERVICE_PRINCIPAL_ID=$(az ad sp list --display-name testing-notification-api-php-client --query "[0].objectId" --output tsv) -
Deploy the Storage Account for logs, provide tenant ID, service principal ID and group ID from the previous commands:
az deployment group create --resource-group testing-notification-api-php-client --template-file provisioning/azure.json --parameters vault_name=test-notification-client tenant_id=$TEST_AZURE_TENANT_ID service_principal_object_id=$SERVICE_PRINCIPAL_ID
-
Get the connection string
az storage account show-connection-string -g testing-notification-api-php-client -n mirontfcnacc2 --query "connectionString" --output tsv
Generate environment configuration
export DATABASE_URL_BASE64=$(printf "mysql://root:root@dev-mysql-service:3310/notifications?serverVersion=8.0" | base64 --wrap=0) export DATABASE_PASSWORD_BASE64=$(printf "root" | base64 --wrap=0) export TEST_AZURE_CLIENT_SECRET_BASE64=$(printf "%s" "$TEST_AZURE_CLIENT_SECRET"| base64 --wrap=0) export TEST_AWS_SECRET_ACCESS_KEY_BASE64=$(printf "%s" "$TEST_AWS_SECRET_ACCESS_KEY"| base64 --wrap=0) ./set-env.sh envsubst < provisioning/environments.yaml.template > provisioning/environments.yaml kubectl apply -f provisioning/environments.yaml kubectl apply -f provisioning/notification.yaml TEST_NOTIFICATION_API_IP=`kubectl get svc --output jsonpath --template "{.items[?(@.metadata.name==\"dev-notification-service\")].status.loadBalancer.ingress[].ip}" --namespace=dev-notification-client` printf "TEST_NOTIFICATION_API_URL: http://%s:8181" "$TEST_NOTIFICATION_API_IP"
Store the result TEST_NOTIFICATION_API_URL in set-env.sh.
Run tests
-
With the above setup, you can run tests:
docker compose build source ./set-env.sh && docker compose run tests
-
To run tests with local code use:
docker compose run tests-local composer install source ./set-env.sh && docker compose run tests-local
License
MIT licensed, see LICENSE file.