RetryJob.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\FederatedFileSharing\BackgroundJob;
  8. use OCA\FederatedFileSharing\Notifications;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\Job;
  12. /**
  13. * Class RetryJob
  14. *
  15. * Background job to re-send update of federated re-shares to the remote server in
  16. * case the server was not available on the first try
  17. *
  18. * @package OCA\FederatedFileSharing\BackgroundJob
  19. */
  20. class RetryJob extends Job {
  21. private bool $retainJob = true;
  22. private Notifications $notifications;
  23. /** @var int max number of attempts to send the request */
  24. private int $maxTry = 20;
  25. /** @var int how much time should be between two tries (10 minutes) */
  26. private int $interval = 600;
  27. public function __construct(Notifications $notifications,
  28. ITimeFactory $time) {
  29. parent::__construct($time);
  30. $this->notifications = $notifications;
  31. }
  32. /**
  33. * Run the job, then remove it from the jobList
  34. */
  35. public function start(IJobList $jobList): void {
  36. if ($this->shouldRun($this->argument)) {
  37. parent::start($jobList);
  38. $jobList->remove($this, $this->argument);
  39. if ($this->retainJob) {
  40. $this->reAddJob($jobList, $this->argument);
  41. }
  42. }
  43. }
  44. protected function run($argument) {
  45. $remote = $argument['remote'];
  46. $remoteId = $argument['remoteId'];
  47. $token = $argument['token'];
  48. $action = $argument['action'];
  49. $data = json_decode($argument['data'], true);
  50. $try = (int)$argument['try'] + 1;
  51. $result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
  52. if ($result === true || $try > $this->maxTry) {
  53. $this->retainJob = false;
  54. }
  55. }
  56. /**
  57. * Re-add background job with new arguments
  58. */
  59. protected function reAddJob(IJobList $jobList, array $argument): void {
  60. $jobList->add(RetryJob::class,
  61. [
  62. 'remote' => $argument['remote'],
  63. 'remoteId' => $argument['remoteId'],
  64. 'token' => $argument['token'],
  65. 'data' => $argument['data'],
  66. 'action' => $argument['action'],
  67. 'try' => (int)$argument['try'] + 1,
  68. 'lastRun' => $this->time->getTime()
  69. ]
  70. );
  71. }
  72. /**
  73. * Test if it is time for the next run
  74. */
  75. protected function shouldRun(array $argument): bool {
  76. $lastRun = (int)$argument['lastRun'];
  77. return (($this->time->getTime() - $lastRun) > $this->interval);
  78. }
  79. }