|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# Copyright (C) 2022 CERN. |
| 4 | +# |
| 5 | +# Invenio-Records-Resources is free software; you can redistribute it and/or |
| 6 | +# modify it under the terms of the MIT License; see LICENSE file for more |
| 7 | +# details. |
| 8 | + |
| 9 | +"""Event handlers module.""" |
| 10 | + |
| 11 | +from dataclasses import asdict |
| 12 | +from datetime import datetime |
| 13 | + |
| 14 | +from celery import shared_task |
| 15 | +from flask import current_app |
| 16 | + |
| 17 | +from .bus import EventBus |
| 18 | + |
| 19 | + |
| 20 | +def _handlers_for_key(key): |
| 21 | + """Returns the handlers for a key.""" |
| 22 | + config_handlers = current_app.config["RECORDS_RESOURCES_EVENTS_HANDLERS"] |
| 23 | + keys_parts = key.split(".") |
| 24 | + |
| 25 | + event_handlers = [] |
| 26 | + curr_key = "" |
| 27 | + for part in keys_parts: |
| 28 | + curr_key = f"{curr_key}.{part}" |
| 29 | + try: |
| 30 | + event_handlers.expand(config_handlers[curr_key]) |
| 31 | + except KeyError: |
| 32 | + current_app.logger.warning(f"No handler for key {curr_key}") |
| 33 | + |
| 34 | + return event_handlers |
| 35 | + |
| 36 | + |
| 37 | +def _handle_event(event, handler=None): |
| 38 | + """Executes the handlers configured for an event.""" |
| 39 | + handlers = _handlers_for_key(event.handling_key) |
| 40 | + |
| 41 | + for handler in handlers: |
| 42 | + func = handler |
| 43 | + async_ = True |
| 44 | + if isinstance(handler, tuple): |
| 45 | + func = handler[0] |
| 46 | + async_ = handler[1] |
| 47 | + |
| 48 | + if async_: |
| 49 | + func.delay(**asdict(event)) |
| 50 | + else: |
| 51 | + func(**asdict(event)) |
| 52 | + |
| 53 | + # audit logging |
| 54 | + current_app.logger.info( |
| 55 | + f"{event.type}-{event.action} handled successfully." |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +@shared_task(ignore_result=True) |
| 60 | +def handle_events(queue_name=None, max_events=1000, ttl=300): |
| 61 | + """Handle events queue. |
| 62 | +
|
| 63 | + :param max_events: maximum number of events to process by the task. |
| 64 | + :param ttl: time to live (in seconds) for the task. |
| 65 | + """ |
| 66 | + bus = EventBus(queue_name) |
| 67 | + start = datetime.timestamp(datetime.now()) |
| 68 | + end = start |
| 69 | + spawn_new = False |
| 70 | + with bus.active_consumer() as consumer: |
| 71 | + while max_events > 0 and (start + ttl) > end: |
| 72 | + spawn_new = False |
| 73 | + event = consumer.consume() # blocking |
| 74 | + _handle_event(event) # execute all handlers |
| 75 | + end = datetime.timestamp(datetime.now()) |
| 76 | + spawn_new = True |
| 77 | + |
| 78 | + if spawn_new: |
| 79 | + handle_events.delay( |
| 80 | + queue_name=queue_name, max_events=max_events, ttl=ttl |
| 81 | + ) |
0 commit comments