1
0

Manager.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2023 Marcel Klehr <mklehr@gmx.net>
  5. *
  6. * @author Marcel Klehr <mklehr@gmx.net>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. namespace OC\TextProcessing;
  24. use OC\AppFramework\Bootstrap\Coordinator;
  25. use OC\TextProcessing\Db\Task as DbTask;
  26. use OC\TextProcessing\Db\TaskMapper;
  27. use OCP\AppFramework\Db\DoesNotExistException;
  28. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  29. use OCP\BackgroundJob\IJobList;
  30. use OCP\Common\Exception\NotFoundException;
  31. use OCP\DB\Exception;
  32. use OCP\IConfig;
  33. use OCP\IServerContainer;
  34. use OCP\PreConditionNotMetException;
  35. use OCP\TextProcessing\Exception\TaskFailureException;
  36. use OCP\TextProcessing\IManager;
  37. use OCP\TextProcessing\IProvider;
  38. use OCP\TextProcessing\IProviderWithExpectedRuntime;
  39. use OCP\TextProcessing\Task;
  40. use OCP\TextProcessing\Task as OCPTask;
  41. use Psr\Log\LoggerInterface;
  42. use RuntimeException;
  43. use Throwable;
  44. class Manager implements IManager {
  45. /** @var ?IProvider[] */
  46. private ?array $providers = null;
  47. public function __construct(
  48. private IServerContainer $serverContainer,
  49. private Coordinator $coordinator,
  50. private LoggerInterface $logger,
  51. private IJobList $jobList,
  52. private TaskMapper $taskMapper,
  53. private IConfig $config,
  54. ) {
  55. }
  56. public function getProviders(): array {
  57. $context = $this->coordinator->getRegistrationContext();
  58. if ($context === null) {
  59. return [];
  60. }
  61. if ($this->providers !== null) {
  62. return $this->providers;
  63. }
  64. $this->providers = [];
  65. foreach ($context->getTextProcessingProviders() as $providerServiceRegistration) {
  66. $class = $providerServiceRegistration->getService();
  67. try {
  68. $this->providers[$class] = $this->serverContainer->get($class);
  69. } catch (Throwable $e) {
  70. $this->logger->error('Failed to load Text processing provider ' . $class, [
  71. 'exception' => $e,
  72. ]);
  73. }
  74. }
  75. return $this->providers;
  76. }
  77. public function hasProviders(): bool {
  78. $context = $this->coordinator->getRegistrationContext();
  79. if ($context === null) {
  80. return false;
  81. }
  82. return count($context->getTextProcessingProviders()) > 0;
  83. }
  84. /**
  85. * @inheritDoc
  86. */
  87. public function getAvailableTaskTypes(): array {
  88. $tasks = [];
  89. foreach ($this->getProviders() as $provider) {
  90. $tasks[$provider->getTaskType()] = true;
  91. }
  92. return array_keys($tasks);
  93. }
  94. public function canHandleTask(OCPTask $task): bool {
  95. return in_array($task->getType(), $this->getAvailableTaskTypes());
  96. }
  97. /**
  98. * @inheritDoc
  99. */
  100. public function runTask(OCPTask $task): string {
  101. if (!$this->canHandleTask($task)) {
  102. throw new PreConditionNotMetException('No text processing provider is installed that can handle this task');
  103. }
  104. $providers = $this->getPreferredProviders($task);
  105. foreach ($providers as $provider) {
  106. try {
  107. $task->setStatus(OCPTask::STATUS_RUNNING);
  108. if ($provider instanceof IProviderWithExpectedRuntime) {
  109. $completionExpectedAt = new \DateTime('now');
  110. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  111. $task->setCompletionExpectedAt($completionExpectedAt);
  112. }
  113. if ($task->getId() === null) {
  114. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  115. $task->setId($taskEntity->getId());
  116. } else {
  117. $this->taskMapper->update(DbTask::fromPublicTask($task));
  118. }
  119. $output = $task->visitProvider($provider);
  120. $task->setOutput($output);
  121. $task->setStatus(OCPTask::STATUS_SUCCESSFUL);
  122. $this->taskMapper->update(DbTask::fromPublicTask($task));
  123. return $output;
  124. } catch (\Throwable $e) {
  125. $this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
  126. $task->setStatus(OCPTask::STATUS_FAILED);
  127. $this->taskMapper->update(DbTask::fromPublicTask($task));
  128. throw new TaskFailureException('LanguageModel call using provider ' . $provider->getName() . ' failed: ' . $e->getMessage(), 0, $e);
  129. }
  130. }
  131. $task->setStatus(OCPTask::STATUS_FAILED);
  132. $this->taskMapper->update(DbTask::fromPublicTask($task));
  133. throw new TaskFailureException('Could not run task');
  134. }
  135. /**
  136. * @inheritDoc
  137. */
  138. public function scheduleTask(OCPTask $task): void {
  139. if (!$this->canHandleTask($task)) {
  140. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  141. }
  142. $task->setStatus(OCPTask::STATUS_SCHEDULED);
  143. $providers = $this->getPreferredProviders($task);
  144. if (count($providers) === 0) {
  145. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  146. }
  147. [$provider,] = $providers;
  148. if ($provider instanceof IProviderWithExpectedRuntime) {
  149. $completionExpectedAt = new \DateTime('now');
  150. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  151. $task->setCompletionExpectedAt($completionExpectedAt);
  152. }
  153. $taskEntity = DbTask::fromPublicTask($task);
  154. $this->taskMapper->insert($taskEntity);
  155. $task->setId($taskEntity->getId());
  156. $this->jobList->add(TaskBackgroundJob::class, [
  157. 'taskId' => $task->getId()
  158. ]);
  159. }
  160. /**
  161. * @inheritDoc
  162. */
  163. public function runOrScheduleTask(OCPTask $task): bool {
  164. if (!$this->canHandleTask($task)) {
  165. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  166. }
  167. [$provider,] = $this->getPreferredProviders($task);
  168. $maxExecutionTime = (int) ini_get('max_execution_time');
  169. // Offload the task to a background job if the expected runtime of the likely provider is longer than 80% of our max execution time
  170. // or if the provider doesn't provide a getExpectedRuntime() method
  171. if (!$provider instanceof IProviderWithExpectedRuntime || $provider->getExpectedRuntime() > $maxExecutionTime * 0.8) {
  172. $this->scheduleTask($task);
  173. return false;
  174. }
  175. $this->runTask($task);
  176. return true;
  177. }
  178. /**
  179. * @inheritDoc
  180. */
  181. public function deleteTask(Task $task): void {
  182. $taskEntity = DbTask::fromPublicTask($task);
  183. $this->taskMapper->delete($taskEntity);
  184. $this->jobList->remove(TaskBackgroundJob::class, [
  185. 'taskId' => $task->getId()
  186. ]);
  187. }
  188. /**
  189. * Get a task from its id
  190. *
  191. * @param int $id The id of the task
  192. * @return OCPTask
  193. * @throws RuntimeException If the query failed
  194. * @throws NotFoundException If the task could not be found
  195. */
  196. public function getTask(int $id): OCPTask {
  197. try {
  198. $taskEntity = $this->taskMapper->find($id);
  199. return $taskEntity->toPublicTask();
  200. } catch (DoesNotExistException $e) {
  201. throw new NotFoundException('Could not find task with the provided id');
  202. } catch (MultipleObjectsReturnedException $e) {
  203. throw new RuntimeException('Could not uniquely identify task with given id', 0, $e);
  204. } catch (Exception $e) {
  205. throw new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);
  206. }
  207. }
  208. /**
  209. * Get a task from its user id and task id
  210. * If userId is null, this can only get a task that was scheduled anonymously
  211. *
  212. * @param int $id The id of the task
  213. * @param string|null $userId The user id that scheduled the task
  214. * @return OCPTask
  215. * @throws RuntimeException If the query failed
  216. * @throws NotFoundException If the task could not be found
  217. */
  218. public function getUserTask(int $id, ?string $userId): OCPTask {
  219. try {
  220. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  221. return $taskEntity->toPublicTask();
  222. } catch (DoesNotExistException $e) {
  223. throw new NotFoundException('Could not find task with the provided id and user id');
  224. } catch (MultipleObjectsReturnedException $e) {
  225. throw new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);
  226. } catch (Exception $e) {
  227. throw new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);
  228. }
  229. }
  230. /**
  231. * Get a list of tasks scheduled by a specific user for a specific app
  232. * and optionally with a specific identifier.
  233. * This cannot be used to get anonymously scheduled tasks
  234. *
  235. * @param string $userId
  236. * @param string $appId
  237. * @param string|null $identifier
  238. * @return array
  239. */
  240. public function getUserTasksByApp(string $userId, string $appId, ?string $identifier = null): array {
  241. try {
  242. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $identifier);
  243. return array_map(static function (DbTask $taskEntity) {
  244. return $taskEntity->toPublicTask();
  245. }, $taskEntities);
  246. } catch (Exception $e) {
  247. throw new RuntimeException('Failure while trying to find tasks by appId and identifier: ' . $e->getMessage(), 0, $e);
  248. }
  249. }
  250. /**
  251. * @param OCPTask $task
  252. * @return IProvider[]
  253. */
  254. public function getPreferredProviders(OCPTask $task): array {
  255. $providers = $this->getProviders();
  256. $json = $this->config->getAppValue('core', 'ai.textprocessing_provider_preferences', '');
  257. if ($json !== '') {
  258. $preferences = json_decode($json, true);
  259. if (isset($preferences[$task->getType()])) {
  260. // If a preference for this task type is set, move the preferred provider to the start
  261. $provider = current(array_values(array_filter($providers, fn ($provider) => $provider::class === $preferences[$task->getType()])));
  262. if ($provider !== false) {
  263. $providers = array_filter($providers, fn ($p) => $p !== $provider);
  264. array_unshift($providers, $provider);
  265. }
  266. }
  267. }
  268. $providers = array_values(array_filter($providers, fn (IProvider $provider) => $task->canUseProvider($provider)));
  269. return $providers;
  270. }
  271. }