src/Services/Aws/AwsEventBridge.php line 245

Open in your IDE?
  1. <?php
  2. namespace EADPlataforma\Services\Aws;
  3. use Aws\EventBridge\EventBridgeClient;
  4. use Aws\Exception\AwsException;
  5. use EADPlataforma\Services\Aws\Aws;
  6. use EADPlataforma\Services\GeneralService;
  7. use EADPlataforma\Enum\ServicesEnum;
  8. /**
  9.  * AwsEventBridge
  10.  */
  11. class AwsEventBridge extends Aws
  12. {
  13.     /**
  14.      * @var Aws\EventBridge\EventBridgeClient
  15.      */
  16.     protected $eventBridgeClient = [];
  17.     /**
  18.      * @var GeneralService
  19.      */
  20.     protected $generalService;
  21.     /**
  22.      * @var AwsIAM
  23.      */
  24.     protected $awsIam;
  25.     /**
  26.      * @var ConfigurationService
  27.      */
  28.     protected $configuration;
  29.     /**
  30.      * @var string
  31.      */
  32.     protected $connection;
  33.     /**
  34.      * @var Client
  35.      */
  36.     protected $client;
  37.     /**
  38.      * @var string
  39.      */
  40.     protected $clientHash;
  41.     /**
  42.      * @var object
  43.      */
  44.     protected $info;
  45.     /**
  46.      * Constructor
  47.      *
  48.      * @param GeneralService $generalService
  49.      */
  50.     public function __construct(GeneralService $generalService)
  51.     {   
  52.         $this->generalService $generalService;
  53.         $info $this->generalService->getServiceAccess(ServicesEnum::AWS_EVENT_BRIDGE);
  54.         $this->info $info;
  55.         $this->connection $this->info->connection;
  56.         $this->awsIam $this->generalService->getService('Aws\\AwsIAM');
  57.         $this->configuration $this->generalService->getService('ConfigurationService');
  58.         $this->client $this->configuration->getClient();
  59.         $this->clientHash "client-{$this->client->getClientId()}-cron";
  60.     }
  61.     public function setClientHash(string $clientHash)
  62.     {
  63.         $this->clientHash $clientHash;
  64.         return $this;
  65.     }
  66.     public function getRegion()
  67.     {
  68.         $clientConfig $this->configuration->getClientConfiguration();
  69.         $region $clientConfig->getServiceCronRegion();
  70.         return (!empty($region) ? $region "us-east-1");
  71.     }
  72.     public function getEventBridgeClient()
  73.     {
  74.         if(!isset($this->eventBridgeClient[$this->getRegion()])){
  75.             $this->eventBridgeClient[$this->getRegion()] = new EventBridgeClient(
  76.                 $this->getCredentials(
  77.                     $this->getRegion(), 
  78.                     $this->info->key
  79.                     $this->info->secret
  80.                 )
  81.             );
  82.         }
  83.         return $this->eventBridgeClient[$this->getRegion()];
  84.     }
  85.     public function createByTypeApiDestination(int $cronType)
  86.     {
  87.         $arnTypeSave $this->configuration->get("config_cron_arn_destination_{$cronType}");
  88.         if(!empty($arnTypeSave)){
  89.             return;
  90.         }
  91.         $arrUrl = [
  92.             ServicesEnum::CRON_GENERAL => "/general/",
  93.             ServicesEnum::CRON_QUEUE => "/email/queue/",
  94.             ServicesEnum::CRON_PROCCESS_SUBSCRIPTION => "/user/subscription/",
  95.             ServicesEnum::CRON_WEBHOOK_QUEUE => "/webhook/queue/send/",
  96.             ServicesEnum::CRON_TRASH => "/delete/trash/all/",
  97.         ];
  98.         $horaGeneral rand(5,7);
  99.         $minGeneral rand(10,59);
  100.         $horaSub rand(5,7);
  101.         $minSub rand(10,59);
  102.         $horaTrash rand(5,7);
  103.         $minTrash rand(10,59);
  104.         $arrTime = [
  105.             ServicesEnum::CRON_GENERAL => "cron({$horaGeneral} {$minGeneral} * * ? *)",
  106.             ServicesEnum::CRON_QUEUE => "rate(1 minute)",
  107.             ServicesEnum::CRON_PROCCESS_SUBSCRIPTION => "cron({$horaSub} {$minSub} * * ? *)",
  108.             ServicesEnum::CRON_WEBHOOK_QUEUE => "rate(1 minute)",
  109.             ServicesEnum::CRON_TRASH => "cron({$horaTrash} {$minTrash} * * ? *)",
  110.         ];
  111.         $clientConfiguration $this->configuration->getClientConfiguration();
  112.         $token $clientConfiguration->getToken();
  113.         $this->createApiDestination(
  114.             $cronType
  115.             "https://{$this->client->getDomainPrimary()}{$arrUrl[$cronType]}{$token}",
  116.             $arrTime[$cronType]
  117.         );
  118.     }
  119.     public function createApiDestination(int $cronTypestring $urlstring $time)
  120.     {
  121.         $cronName "{$this->clientHash}-{$cronType}";
  122.         $idConn $this->connection->{$this->getRegion()};
  123.         $awsId $this->info->awsAccountId;
  124.         $arnConn "arn:aws:events:{$this->getRegion()}:{$awsId}:connection/{$idConn}";
  125.         try{
  126.             $result $this->getEventBridgeClient()->createApiDestination([
  127.                 'ConnectionArn' => $arnConn// REQUIRED
  128.                 'HttpMethod' => 'GET'// REQUIRED
  129.                 'InvocationEndpoint' => $url// REQUIRED
  130.                 'InvocationRateLimitPerSecond' => 1,
  131.                 'Name' => $cronName// REQUIRED
  132.             ]);
  133.             $this->putRule($cronName$result['ApiDestinationArn'], $cronType$time);
  134.         }catch(Exception $e){
  135.             print_r($e->getMessage());
  136.         }
  137.     }
  138.     public function putRule(string $cronNamestring $arnDestination
  139.                             int $cronTypestring $time)
  140.     {
  141.         try{
  142.             $arnPolicy $this->awsIam->createPolicyApiDestination(
  143.                 "policy-{$cronName}"
  144.                 $arnDestination
  145.             );
  146.             $arnRole $this->awsIam->createRole(
  147.                 "role-{$cronName}"
  148.                 $arnDestination
  149.                 $arnPolicy
  150.             );
  151.             $result $this->getEventBridgeClient()->putRule([
  152.                 'EventBusName' => 'default',
  153.                 'Name' => "rule-{$cronName}"// REQUIRED
  154.                 'ScheduleExpression' => $time,
  155.                 'State' => 'ENABLED',
  156.             ]);
  157.             $this->getEventBridgeClient()->putTargets([
  158.                 'EventBusName' => 'default',
  159.                 'Rule' => "rule-{$cronName}",
  160.                 'Targets' => [
  161.                     [
  162.                         "Arn" => $arnDestination,
  163.                         "Id" => "id-{$cronName}",
  164.                         "RoleArn" => $arnRole,
  165.                     ]
  166.                 ]
  167.             ]);
  168.             $this->configuration->setMany([
  169.                 "config_cron_arn_destination_{$cronType}=> $arnDestination,
  170.                 "config_cron_arn_policy_{$cronType}=> $arnPolicy,
  171.                 "config_cron_arn_role_{$cronType}=> $arnRole,
  172.                 "config_cron_arn_rule_{$cronType}=> $result['RuleArn']
  173.             ]);
  174.         }catch(AwsException $e){
  175.             print_r($e->getMessage());
  176.         }
  177.     }
  178.     public function deleteRule(string $ruleNamestring $targetId){
  179.         try{
  180.             $this->getEventBridgeClient()->removeTargets([
  181.                 'EventBusName' => 'default',
  182.                 'Force' => true,
  183.                 'Ids' => [ $targetId ], // REQUIRED
  184.                 'Rule' => $ruleName// REQUIRED
  185.             ]);
  186.             $this->getEventBridgeClient()->deleteRule([
  187.                 'EventBusName' => 'default',
  188.                 'Force' => true,
  189.                 'Name' => $ruleName// REQUIRED
  190.             ]);
  191.         }catch(AwsException $e){
  192.             
  193.         }
  194.     }
  195.     public function deleteApiDestination(int $cronType)
  196.     {
  197.         $arnPolicy $this->configuration->get("config_cron_arn_policy_{$cronType}");
  198.         if(empty($arnPolicy)){
  199.             return;
  200.         }
  201.         if($this->deleteApiDestinationByCronName($cronType)){
  202.             $this->configuration->setMany([
  203.                 "config_cron_arn_destination_{$cronType}=> "",
  204.                 "config_cron_arn_policy_{$cronType}=> "",
  205.                 "config_cron_arn_role_{$cronType}=> "",
  206.                 "config_cron_arn_rule_{$cronType}=> ""
  207.             ]);
  208.         }
  209.     }
  210.     public function deleteApiDestinationByCronName(int $cronType)
  211.     {
  212.         if(empty($cronType)){
  213.             return false;
  214.         }
  215.         $clientHash $this->clientHash;
  216.         if($cronType == ServicesEnum::CRON_GENERAL){
  217.             $clientId = (int)$this->client->getClientId();
  218.             $clientId str_pad($clientId6'0'STR_PAD_LEFT);
  219.             $clientHash "client-{$clientId}-cron";
  220.         }
  221.         $cronName "{$clientHash}-{$cronType}";
  222.         try{
  223.             $this->deleteRule("rule-{$cronName}""id-{$cronName}");
  224.         }catch(AwsException $e){
  225.             if(
  226.                 !strpos($e->getMessage(), 'does not exist') && 
  227.                 !strpos($e->getMessage(), 'cannot be found') &&
  228.                 !strpos($e->getMessage(), 'was not found')
  229.             ){
  230.                 return false;
  231.             }
  232.         }
  233.         try{
  234.             $this->getEventBridgeClient()->deleteApiDestination([
  235.                 'Name' => $cronName// REQUIRED
  236.             ]);
  237.         }catch(AwsException $e){
  238.             if(
  239.                 !strpos($e->getMessage(), 'does not exist') && 
  240.                 !strpos($e->getMessage(), 'cannot be found') &&
  241.                 !strpos($e->getMessage(), 'was not found')
  242.             ){
  243.                 return false;
  244.             }
  245.         }
  246.         $arnPolicy "arn:aws:iam::{$this->info->awsAccountId}:policy/policy-{$cronName}";
  247.         try{
  248.             $this->awsIam->deleteRole("role-{$cronName}"$arnPolicy);
  249.         }catch(AwsException $e){
  250.             if(
  251.                 !strpos($e->getMessage(), 'does not exist') && 
  252.                 !strpos($e->getMessage(), 'cannot be found') &&
  253.                 !strpos($e->getMessage(), 'was not found')
  254.             ){
  255.                 return false;
  256.             }
  257.         }
  258.         
  259.         try{
  260.             $this->awsIam->deletePolicy($arnPolicy);
  261.         }catch(AwsException $e){
  262.             if(
  263.                 !strpos($e->getMessage(), 'does not exist') && 
  264.                 !strpos($e->getMessage(), 'cannot be found') &&
  265.                 !strpos($e->getMessage(), 'was not found')
  266.             ){
  267.                 return false;
  268.             }
  269.         }
  270.         return true;
  271.     }
  272.     public function updateApiDestinationNewDomain($newDomain)
  273.     {
  274.         $clientConfiguration $this->configuration->getClientConfiguration();
  275.         $clientToken $clientConfiguration->getToken();
  276.         $newDomain str_replace('http://'''$newDomain);
  277.         $newDomain str_replace('https://'''$newDomain);
  278.         $newDomain str_replace('/'''$newDomain);
  279.         $arrUrl = [
  280.             ServicesEnum::CRON_GENERAL => "/general/",
  281.             ServicesEnum::CRON_QUEUE => "/email/queue/",
  282.             ServicesEnum::CRON_PROCCESS_SUBSCRIPTION => "/user/subscription/",
  283.             ServicesEnum::CRON_WEBHOOK_QUEUE => "/webhook/queue/send/",
  284.             ServicesEnum::CRON_TRASH => "/delete/trash/all/",
  285.         ];
  286.         foreach ($arrUrl as $type => $action) {
  287.             try {
  288.                 $cronName "{$this->clientHash}-{$type}";
  289.                 $awsId $this->info->awsAccountId;
  290.                 $idConn $this->connection->{$this->getRegion()};
  291.                 $arnConn "arn:aws:events:{$this->getRegion()}:{$awsId}:connection/{$idConn}";
  292.                 $this->getEventBridgeClient()->updateApiDestination([
  293.                     'ConnectionArn' => $arnConn// REQUIRED
  294.                     'HttpMethod' => 'GET'// REQUIRED
  295.                     'InvocationEndpoint' => "https://{$newDomain}{$action}{$clientToken}",
  296.                     'InvocationRateLimitPerSecond' => 1,
  297.                     'Name' => $cronName// REQUIRED
  298.                 ]);
  299.             } catch (\Exception $e) {
  300.             }
  301.         }
  302.     }
  303. }