"""Function Logic.""" from content_utils.exceptions import IndexingFailedError from src.config import app_logger from src.logic import indexing from src.logic import sqs from src.logic import metadata_lookup def sync_products(items, existing_items, add_products, update_products=False): """Remove or add products from index if they are not in the existing list.""" failed_products = [] existing_item_ids = [item['reviewQueueId'] for item in existing_items] for item in items: review_queue_id = item['reviewQueueId'] if review_queue_id in existing_item_ids: if add_products and update_products: sqs.update_product(item['reviewQueueId'], item['productId']) continue try: if add_products: sqs.add_product(item['reviewQueueId'], item['productId']) else: sqs.delete_product(item['productId']) except Exception as e: # for reindexing we want to continue even if there's one failure error_message = { 'productId': item['productId'], 'reviewQueueId': item['reviewQueueId'], 'error': e } failed_products.append(item['productId']) app_logger.error(error_message) return failed_products def processing_logic(clear_index, update_products): """Single event handling logic.""" review_queue_items = metadata_lookup.get_review_queue_products() # no need to get items if you're just going to clear the index index_items = [] if clear_index else indexing.get_all_items() if clear_index: indexing.drop_index() failed_deleting_products = sync_products(index_items, review_queue_items, False) failed_adding_products = sync_products(review_queue_items, index_items, True, update_products) if len(failed_adding_products) or len(failed_deleting_products): raise IndexingFailedError( f'failed to index products: {failed_adding_products} \n' f'failed to remove products: {failed_deleting_products}' )