fix: Cache webhooks listened events for 5min

Signed-off-by: Côme Chilliet <come.chilliet@nextcloud.com>
This commit is contained in:
Côme Chilliet 2024-06-06 16:23:28 +02:00 committed by Côme Chilliet
parent e111d2e26c
commit 98f3ea657c
2 changed files with 29 additions and 7 deletions

View file

@ -16,14 +16,25 @@ use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICache;
use OCP\ICacheFactory;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
class Application extends App implements IBootstrap {
public const APP_ID = 'webhooks';
public function __construct() {
private ?ICache $cache = null;
private const CACHE_KEY = 'eventsUsedInWebhooks';
public function __construct(
ICacheFactory $cacheFactory,
) {
parent::__construct(self::APP_ID);
if ($cacheFactory->isAvailable()) {
$this->cache = $cacheFactory->createDistributed();
}
}
public function register(IRegistrationContext $context): void {
@ -38,13 +49,10 @@ class Application extends App implements IBootstrap {
ContainerInterface $container,
LoggerInterface $logger,
): void {
/** @var WebhookListenerMapper */
$mapper = $container->get(WebhookListenerMapper::class);
/* Listen to all events with at least one webhook configured */
$configuredEvents = $mapper->getAllConfiguredEvents();
$configuredEvents = $this->getAllConfiguredEvents($container);
foreach ($configuredEvents as $eventName) {
// $logger->error($eventName.' '.\OCP\Files\Events\Node\NodeWrittenEvent::class, ['exception' => new \Exception('coucou')]);
$logger->debug("Listening to {$eventName}");
$dispatcher->addServiceListener(
$eventName,
WebhooksEventListener::class,
@ -52,4 +60,19 @@ class Application extends App implements IBootstrap {
);
}
}
/**
* List all events with at least one webhook configured, with cache
*/
private function getAllConfiguredEvents(ContainerInterface $container) {
$events = $this->cache?->get(self::CACHE_KEY);
if ($events !== null) {
return json_decode($events);
}
/** @var WebhookListenerMapper */
$mapper = $container->get(WebhookListenerMapper::class);
$events = $mapper->getAllConfiguredEvents();
// cache for 5 minutes
$this->cache?->set(self::CACHE_KEY, json_encode($events), 300);
}
}

View file

@ -138,7 +138,6 @@ class WebhookListenerMapper extends QBMapper {
/**
* @throws Exception
* @return list<string>
* TODO cache
*/
public function getAllConfiguredEvents(): array {
$qb = $this->db->getQueryBuilder();