Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Update reingestion workflows to load and report data (#618)
Staci Cooper4a9c008a150b
diff --git a/DAGs.md b/DAGs.mdindex bae0c526d..741f405c5 100644--- a/DAGs.md+++ b/DAGs.md@@ -102,9 +102,9 @@ The following are DAGs grouped by their primary tag:| DAG ID | Schedule Interval || --- | --- |-| `europeana_ingestion_workflow` | `@daily` |-| `flickr_ingestion_workflow` | `@daily` |-| `wikimedia_ingestion_workflow` | `@daily` |+| [`europeana_reingestion_workflow`](#europeana_reingestion_workflow) | `@weekly` |+| [`flickr_reingestion_workflow`](#flickr_reingestion_workflow) | `@weekly` |+| [`wikimedia_reingestion_workflow`](#wikimedia_reingestion_workflow) | `@weekly` |# DAG documentation@@ -114,7 +114,9 @@ The following is documentation associated with each DAG (where available):1. [`airflow_log_cleanup`](#airflow_log_cleanup)1. [`audio_data_refresh`](#audio_data_refresh)1. [`check_silenced_dags`](#check_silenced_dags)+ 1. [`europeana_reingestion_workflow`](#europeana_reingestion_workflow)1. [`europeana_workflow`](#europeana_workflow)+ 1. [`flickr_reingestion_workflow`](#flickr_reingestion_workflow)1. [`flickr_workflow`](#flickr_workflow)1. [`freesound_workflow`](#freesound_workflow)1. [`image_data_refresh`](#image_data_refresh)@@ -133,6 +135,7 @@ The following is documentation associated with each DAG (where available):1. [`tsv_to_postgres_loader`](#tsv_to_postgres_loader)1. [`walters_workflow`](#walters_workflow)1. [`wikimedia_commons_workflow`](#wikimedia_commons_workflow)+ 1. [`wikimedia_reingestion_workflow`](#wikimedia_reingestion_workflow)1. [`wordpress_workflow`](#wordpress_workflow)@@ -215,6 +218,20 @@ The DAG runs weekly.+## `europeana_reingestion_workflow`+++Content Provider: Europeana++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the+ respective meta-data.++Notes: https://www.europeana.eu/api/v2/search.json+++## `europeana_workflow`@@ -229,6 +246,21 @@ Notes: https://www.europeana.eu/api/v2/search.json+## `flickr_reingestion_workflow`+++Content Provider: Flickr++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the+ respective meta-data.++Notes: https://www.flickr.com/help/terms/api+ Rate limit: 3600 requests per hour.+++## `flickr_workflow`@@ -599,6 +631,21 @@ Notes: https://commons.wikimedia.org/wiki/API:Main_page+## `wikimedia_reingestion_workflow`+++Content Provider: Wikimedia Commons++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective+ meta-data.++Notes: https://commons.wikimedia.org/wiki/API:Main_page+ No rate limit specified.+++## `wordpress_workflow`diff --git a/openverse_catalog/dags/common/helpers.py b/openverse_catalog/dags/common/helpers.pyindex fee1e0c08..b79a52aca 100644--- a/openverse_catalog/dags/common/helpers.py+++ b/openverse_catalog/dags/common/helpers.py@@ -6,13 +6,13 @@ class IngestionInput(NamedTuple):repeats: int-def get_reingestion_day_list_list(inputs: List[IngestionInput]):+def get_partitioned_reingestion_days(inputs: List[IngestionInput]):"""This method calculates day-shift lists for Provider API workflows.The input should be a list of pairs of integers:- `get_reingestion_day_list_list((x_0, y_0), ..., (x_n, y_n))`+ `get_partitioned_reingestion_days((x_0, y_0), ..., (x_n, y_n))`The return will be a list of lists of integers. The zeroth innerlist will be a list of integers counting by x_0, of length y_0. The@@ -23,7 +23,7 @@ def get_reingestion_day_list_list(inputs: List[IngestionInput]):list.For example,- get_reingestion_day_list_list((1, 2), (2, 3), (3, 2))+ get_partitioned_reingestion_days((1, 2), (2, 3), (3, 2))returns[[1, 2], [4, 6, 8], [11, 14]]"""diff --git a/openverse_catalog/dags/common/loader/reporting.py b/openverse_catalog/dags/common/loader/reporting.pyindex 600717313..57d273152 100644--- a/openverse_catalog/dags/common/loader/reporting.py+++ b/openverse_catalog/dags/common/loader/reporting.py@@ -1,7 +1,7 @@from __future__ import annotationsimport logging-from typing import NamedTuple, Optional+from typing import NamedTuple, Optional, Sequencefrom common.slack import send_message@@ -26,11 +26,24 @@ class RecordMetrics(NamedTuple):foreign_id_dup: Optional[int]url_dup: Optional[int]+ def _add_counts(self, a, b):+ return (a or 0) + (b or 0)++ def __add__(self, other):+ if other is None:+ return self+ return RecordMetrics(+ self._add_counts(self.upserted, other.upserted),+ self._add_counts(self.missing_columns, other.missing_columns),+ self._add_counts(self.foreign_id_dup, other.foreign_id_dup),+ self._add_counts(self.url_dup, other.url_dup),+ )+MediaTypeRecordMetrics = dict[str, RecordMetrics]-def humanize_time_duration(seconds: float) -> str:+def humanize_time_duration(seconds: float | int) -> str:if seconds == 0:return "inf"elif seconds < 1:@@ -43,10 +56,39 @@ def humanize_time_duration(seconds: float) -> str:return ", ".join(parts)+def clean_duration(duration: float | list[float]):+ # If a list of duration values is provided, get the sum of all non-None values+ if isinstance(duration, list):+ duration = sum([x for x in duration if x])++ # Truncate the duration value if it's provided+ if isinstance(duration, float) or isinstance(duration, int):+ duration = humanize_time_duration(duration)++ return duration+++def clean_record_counts(+ record_counts_by_media_type: MediaTypeRecordMetrics | list[MediaTypeRecordMetrics],+ media_types: Sequence[str],+):+ # If a list of record_counts dicts is provided, sum all of the individual values+ if isinstance(record_counts_by_media_type, list):+ return {+ media_type: sum(+ [x[media_type] for x in record_counts_by_media_type],+ RecordMetrics(0, 0, 0, 0),+ )+ for media_type in media_types+ }+ return record_counts_by_media_type++def report_completion(- provider_name: str,- duration: float | str | None,- record_counts_by_media_type: MediaTypeRecordMetrics,+ dag_id: str,+ media_types: Sequence[str],+ duration: float | str | list[float] | None,+ record_counts_by_media_type: MediaTypeRecordMetrics | list[MediaTypeRecordMetrics],dated: bool = False,date_range_start: str | None = None,date_range_end: str | None = None,@@ -72,9 +114,12 @@ def report_completion(- `date_range`: The range of time this ingestion covers. If the ingestion coversthe entire provided dataset, "all" is provided"""- # Truncate the duration value if it's provided- if isinstance(duration, float):- duration = humanize_time_duration(duration)+ is_aggregate_duration = isinstance(duration, list)++ duration = clean_duration(duration)+ record_counts_by_media_type = clean_record_counts(+ record_counts_by_media_type, media_types+ )# List record count per media typemedia_type_reports = ""@@ -104,10 +149,19 @@ def report_completion(# Collect data into a single messagemessage = f"""-*Provider*: `{provider_name}`+*DAG*: `{dag_id}`*Date range*: {date_range}-*Duration of data pull task*: {duration or '_No data_'}+*Duration of data pull tasks*: {duration or '_No data_'}*Number of records upserted per media type*:{media_type_reports}"""++ if is_aggregate_duration:+ # Add disclaimer about duration for aggregate data+ message += (+ "\n_Duration is the sum of the duration for each data pull task."+ " It does not include loading time and does not account for data"+ " pulls that may happen concurrently."+ )+send_message(message, username="Airflow DAG Load Data Complete")return messagediff --git a/openverse_catalog/dags/common/storage/audio.py b/openverse_catalog/dags/common/storage/audio.pyindex 40980e0f3..b98890fb1 100644--- a/openverse_catalog/dags/common/storage/audio.py+++ b/openverse_catalog/dags/common/storage/audio.py@@ -18,6 +18,9 @@ class AudioStore(MediaStore):Optional init arguments:provider: String marking the provider in the `audio` table of the DB.+ date: Date String in the form YYYY-MM-DD. This is the date for+ which data is being stored. If provided, it will be appended to+ the tsv filename.output_file: String giving a temporary .tsv filename (*not* thefull path) where the audio info should be stored.output_dir: String giving a path where `output_file` should be placed.diff --git a/openverse_catalog/dags/common/storage/image.py b/openverse_catalog/dags/common/storage/image.pyindex fafff07c3..b3f54d454 100644--- a/openverse_catalog/dags/common/storage/image.py+++ b/openverse_catalog/dags/common/storage/image.py@@ -18,6 +18,9 @@ class ImageStore(MediaStore):Optional init arguments:provider: String marking the provider in the `image` table of the DB.+ date: Date String in the form YYYY-MM-DD. This is the date for+ which data is being stored. If provided, it will be appended to+ the tsv filename.output_file: String giving a temporary .tsv filename (*not* thefull path) where the image info should be stored.output_dir: String giving a path where `output_file` should be placed.diff --git a/openverse_catalog/dags/common/storage/media.py b/openverse_catalog/dags/common/storage/media.pyindex 09537c32d..d73073ad4 100644--- a/openverse_catalog/dags/common/storage/media.py+++ b/openverse_catalog/dags/common/storage/media.py@@ -46,6 +46,9 @@ class MediaStore(metaclass=abc.ABCMeta):Optional init arguments:provider: String marking the provider in the `media`(`image`, `audio` etc) table of the DB.+ date: Date String in the form YYYY-MM-DD. This is the date for+ which data is being stored. If provided, it will be appended to+ the tsv filename.output_file: String giving a temporary .tsv filename (*not* thefull path) where the media info should be stored.output_dir: String giving a path where `output_file` should be placed.@@ -66,9 +69,7 @@ class MediaStore(metaclass=abc.ABCMeta):self.provider = providerself.buffer_length = buffer_lengthself.output_path = self._initialize_output_path(- output_dir,- output_file,- provider,+ output_dir, output_file, provider)self.columns = Noneself._media_buffer = []@@ -158,7 +159,7 @@ class MediaStore(metaclass=abc.ABCMeta):self,output_dir: Optional[str],output_file: Optional[str],- provider: str,+ provider: Optional[str],version: Optional[str] = None,) -> str:"""Creates the path for the tsv file.diff --git a/openverse_catalog/dags/providers/factory_utils.py b/openverse_catalog/dags/providers/factory_utils.pyindex a54df3714..f717926dd 100644--- a/openverse_catalog/dags/providers/factory_utils.py+++ b/openverse_catalog/dags/providers/factory_utils.py@@ -147,7 +147,9 @@ def pull_media_wrapper(def date_partition_for_prefix(- schedule_interval: str | None, logical_date: datetime+ schedule_interval: str | None,+ logical_date: datetime,+ reingestion_date: datetime,) -> str:"""Given a schedule interval and the logical date for a DAG run, determine an@@ -158,6 +160,14 @@ def date_partition_for_prefix(- Hourly -> `year=YYYY/month=MM/day=DD`- Daily -> `year=YYYY/month=MM`- None/yearly/monthly/weekly/other -> `year=YYYY`++ If a reingestion_date is supplied, it is further partitioned by the reingestion+ date itself to avoid filename collisions.++ Example:+ - Hourly -> `year=YYYY/month=MM/day=DD/reingestion=YYYY-MM-DD`+ - Daily -> `year=YYYY/month=MM/reingestion=YYYY-MM-DD`+ - None/yearly/monthly/weekly/other -> `year=YYYY/reingestion=YYYY-MM-DD`"""hourly_airflow = "@hourly"hourly_cron = cron_presets[hourly_airflow]@@ -175,4 +185,8 @@ def date_partition_for_prefix(if schedule_interval in {hourly_airflow, hourly_cron}:prefix += f"/day={logical_date.day:02}"+ # Further partition by reingestion date if supplied+ if reingestion_date is not None:+ prefix += f"/reingestion={reingestion_date}"+return prefixdiff --git a/openverse_catalog/dags/providers/provider_dag_factory.py b/openverse_catalog/dags/providers/provider_dag_factory.pyindex 80d020641..b3edf6f51 100644--- a/openverse_catalog/dags/providers/provider_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_dag_factory.py@@ -64,11 +64,9 @@ https://github.com/creativecommons/cccatalog/issues/334)"""import loggingimport os-from datetime import datetime, timedelta-from typing import Callable, Dict, Optional, Sequence+from string import Templatefrom airflow import DAG-from airflow.models.baseoperator import cross_downstreamfrom airflow.operators.empty import EmptyOperatorfrom airflow.operators.python import PythonOperatorfrom airflow.utils.task_group import TaskGroup@@ -80,6 +78,8 @@ from providers.factory_utils import (generate_tsv_filenames,pull_media_wrapper,)+from providers.provider_reingestion_workflows import ProviderReingestionWorkflow+from providers.provider_workflows import ProviderWorkflowlogger = logging.getLogger(__name__)@@ -89,109 +89,55 @@ DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")AWS_CONN_ID = os.getenv("AWS_CONN_ID", "no_aws_conn_id")OPENVERSE_BUCKET = os.getenv("OPENVERSE_BUCKET")OUTPUT_DIR_PATH = os.path.realpath(os.getenv("OUTPUT_DIR", "/tmp/"))-DATE_RANGE_ARG_TEMPLATE = "{{{{ macros.ds_add(ds, -{}) }}}}"-DATE_PARTITION_ARG_TEMPLATE = "{media_type}/{provider_name}/{{{{ date_partition_for_prefix(dag.schedule_interval, dag_run.logical_date) }}}}" # noqa---def create_provider_api_workflow(- dag_id: str,- ingestion_callable: Callable,- default_args: Optional[Dict] = None,- start_date: datetime = datetime(1970, 1, 1),- max_active_runs: int = 1,- max_active_tasks: int = 1,- schedule_string: str = "@daily",- dated: bool = True,- day_shift: int = 0,- pull_timeout: timedelta = timedelta(hours=12),- load_timeout: timedelta = timedelta(hours=1),- doc_md: Optional[str] = "",- media_types: Sequence[str] = ("image",),- create_preingestion_tasks: Optional[Callable] = None,- create_postingestion_tasks: Optional[Callable] = None,+_DATE_RANGE_INNER_TEMPLATE = "macros.ds_add(ds, -{} )"+DATE_RANGE_ARG_TEMPLATE = "{{{{" + _DATE_RANGE_INNER_TEMPLATE + "}}}}"+DATE_PARTITION_ARG_TEMPLATE = Template(+ "$media_type/$provider_name/{{ date_partition_for_prefix(dag.schedule_interval, dag_run.logical_date, $reingestion_date ) }}" # noqa+)+++def create_ingestion_workflow(+ conf: ProviderWorkflow, day_shift: int = 0, is_reingestion: bool = False):"""- This factory method instantiates a DAG that will run the given- `main_function`.+ Creates a TaskGroup that performs the ingestion tasks, first pulling and then+ loading data. Returns the TaskGroup, and a dictionary of reporting metrics.Required Arguments:- dag_id: string giving a unique id of the DAG to be created.- ingestion_callable: python function to be run, or a ProviderDataIngester class- whose `ingest_records` method is to be run. If the optional- argument `dated` is True, then the function must take a- single parameter (date) which will be a string of- the form 'YYYY-MM-DD'.+ conf: ProviderWorkflow configuration object.Optional Arguments:- default_args: dictionary which is passed to the airflow.dag.DAG- __init__ method and used to optionally override the- DAG_DEFAULT_ARGS.- start_date: datetime.datetime giving the first valid execution- date of the DAG.- max_active_runs: integer that sets the number of dagruns for this DAG- which can be run in parallel.- max_active_tasks: integer that sets the number of tasks which can- run simultaneously for this DAG.- It's important to keep the rate limits of the- Provider API in mind when setting this parameter.- schedule_string: string giving the schedule on which the DAG should- be run. Passed to the airflow.dag.DAG __init__- method.- dated: boolean giving whether the `main_function` takes a- string parameter giving a date (i.e., the date for- which data should be ingested).- day_shift: integer giving the number of days before the- current execution date the `main_function` should- be run (if `dated=True`).- pull_timeout: datetime.timedelta giving the amount of time a given data- pull may take.- load_timeout: datetime.timedelta giving the amount of time a given load_data- task may take.- doc_md: string which should be used for the DAG's documentation markdown- media_types: list describing the media type(s) that this provider handles- (e.g. `["audio"]`, `["image", "audio"]`, etc.)- create_preingestion_tasks and create_postingestion_tasks: callable which creates a- task or task group to be run before or after (respectively) the- rest of the provider workflow. Loading and dropping temporary- tables is one example.+ day_shift: integer giving the number of days before the current execution date+ for which ingestion should run (if `conf.dated==True`).+ is_reingestion: is this workflow a reingestion workflow"""- default_args = {**DAG_DEFAULT_ARGS, **(default_args or {})}- media_type_name = "mixed" if len(media_types) > 1 else media_types[0]- provider_name = dag_id.replace("_workflow", "")- identifier = f"{provider_name}_{{{{ ts_nodash }}}}"- dag = DAG(- dag_id=dag_id,- default_args={**default_args, "start_date": start_date},- max_active_tasks=max_active_tasks,- max_active_runs=max_active_runs,- start_date=start_date,- schedule_interval=schedule_string,- catchup=dated, # catchup is turned on for dated DAGs to allow backfilling- doc_md=doc_md,- tags=["provider"] + [f"provider: {media_type}" for media_type in media_types],- render_template_as_native_obj=True,- user_defined_macros={"date_partition_for_prefix": date_partition_for_prefix},- )+ def append_day_shift(id_str):+ # Appends the day_shift to an id if it is non-zero+ return f"{id_str}{f'_day_shift_{day_shift}' if day_shift else ''}"++ with TaskGroup(group_id=append_day_shift("ingest_data")) as ingest_data:+ media_type_name = "mixed" if len(conf.media_types) > 1 else conf.media_types[0]+ provider_name = conf.dag_id.replace("_workflow", "")+ identifier = f"{provider_name}_{{{{ ts_nodash }}}}_{day_shift}"- with dag:ingestion_kwargs = {- "ingestion_callable": ingestion_callable,- "media_types": media_types,+ "ingestion_callable": conf.ingestion_callable,+ "media_types": conf.media_types,}- if dated:+ if conf.dated:ingestion_kwargs["args"] = [DATE_RANGE_ARG_TEMPLATE.format(day_shift)]generate_filenames = PythonOperator(- task_id=f"generate_{media_type_name}_filename",+ task_id=append_day_shift(f"generate_{media_type_name}_filename"),python_callable=generate_tsv_filenames,op_kwargs=ingestion_kwargs,)pull_data = PythonOperator(- task_id=f"pull_{media_type_name}_data",+ task_id=append_day_shift(f"pull_{media_type_name}_data"),python_callable=pull_media_wrapper,op_kwargs={**ingestion_kwargs,@@ -200,11 +146,11 @@ def create_provider_api_workflow(XCOM_PULL_TEMPLATE.format(generate_filenames.task_id, f"{media_type}_tsv")- for media_type in media_types+ for media_type in conf.media_types],},depends_on_past=False,- execution_timeout=pull_timeout,+ execution_timeout=conf.pull_timeout,# If the data pull fails, we want to load all data that's been retrieved# thus far before we attempt againretries=0,@@ -212,10 +158,12 @@ def create_provider_api_workflow(load_tasks = []record_counts_by_media_type: reporting.MediaTypeRecordMetrics = {}- for media_type in media_types:- with TaskGroup(group_id=f"load_{media_type}_data") as load_data:+ for media_type in conf.media_types:+ with TaskGroup(+ group_id=append_day_shift(f"load_{media_type}_data")+ ) as load_data:create_loading_table = PythonOperator(- task_id="create_loading_table",+ task_id=append_day_shift("create_loading_table"),python_callable=sql.create_loading_table,op_kwargs={"postgres_conn_id": DB_CONN_ID,@@ -227,24 +175,29 @@ def create_provider_api_workflow(f"ingesting {media_type} data from a TSV",)copy_to_s3 = PythonOperator(- task_id="copy_to_s3",+ task_id=append_day_shift("copy_to_s3"),python_callable=s3.copy_file_to_s3,op_kwargs={"tsv_file_path": XCOM_PULL_TEMPLATE.format(generate_filenames.task_id, f"{media_type}_tsv"),"s3_bucket": OPENVERSE_BUCKET,- "s3_prefix": DATE_PARTITION_ARG_TEMPLATE.format(+ "s3_prefix": DATE_PARTITION_ARG_TEMPLATE.substitute(media_type=media_type,provider_name=provider_name,+ reingestion_date=_DATE_RANGE_INNER_TEMPLATE.format(+ day_shift+ )+ if is_reingestion+ else None,),"aws_conn_id": AWS_CONN_ID,},trigger_rule=TriggerRule.NONE_SKIPPED,)load_from_s3 = PythonOperator(- task_id="load_from_s3",- execution_timeout=load_timeout,+ task_id=append_day_shift("load_from_s3"),+ execution_timeout=conf.load_timeout,retries=1,python_callable=loader.load_from_s3,op_kwargs={@@ -259,7 +212,7 @@ def create_provider_api_workflow(},)drop_loading_table = PythonOperator(- task_id="drop_loading_table",+ task_id=append_day_shift("drop_loading_table"),python_callable=sql.drop_load_table,op_kwargs={"postgres_conn_id": DB_CONN_ID,@@ -276,86 +229,107 @@ def create_provider_api_workflow()load_tasks.append(load_data)- report_load_completion = PythonOperator(- task_id="report_load_completion",- python_callable=reporting.report_completion,- op_kwargs={- "provider_name": provider_name,- "duration": XCOM_PULL_TEMPLATE.format(pull_data.task_id, "duration"),- "record_counts_by_media_type": record_counts_by_media_type,- "dated": dated,- "date_range_start": "{{ data_interval_start | ds }}",- "date_range_end": "{{ data_interval_end | ds }}",- },- trigger_rule=TriggerRule.ALL_DONE,- )-- generate_filenames >> pull_data >> load_tasks >> report_load_completion+ generate_filenames >> pull_data >> load_tasks- if create_preingestion_tasks:- preingestion_tasks = create_preingestion_tasks()+ if conf.create_preingestion_tasks:+ preingestion_tasks = conf.create_preingestion_tasks()preingestion_tasks >> pull_data- if create_postingestion_tasks:- postingestion_tasks = create_postingestion_tasks()+ if conf.create_postingestion_tasks:+ postingestion_tasks = conf.create_postingestion_tasks()pull_data >> postingestion_tasks- return dag+ ingestion_metrics = {+ "duration": XCOM_PULL_TEMPLATE.format(pull_data.task_id, "duration"),+ "record_counts_by_media_type": record_counts_by_media_type,+ }++ return ingest_data, ingestion_metrics-def create_day_partitioned_ingestion_dag(- dag_id: str,- main_function: Callable,- reingestion_day_list_list: list[list[int]],- start_date: datetime = datetime(1970, 1, 1),- max_active_runs: int = 1,- max_active_tasks: int = 1,- default_args: Optional[Dict] = None,- dagrun_timeout: timedelta = timedelta(hours=23),- ingestion_task_timeout: timedelta = timedelta(hours=2),+def create_report_load_completion(+ dag_id,+ media_types,+ ingestion_metrics,+ dated,):+ return PythonOperator(+ task_id="report_load_completion",+ python_callable=reporting.report_completion,+ op_kwargs={+ "dag_id": dag_id,+ "media_types": media_types,+ "duration": ingestion_metrics["duration"],+ "record_counts_by_media_type": ingestion_metrics[+ "record_counts_by_media_type"+ ],+ "dated": dated,+ "date_range_start": "{{ data_interval_start | ds }}",+ "date_range_end": "{{ data_interval_end | ds }}",+ },+ trigger_rule=TriggerRule.ALL_DONE,+ )+++def create_provider_api_workflow_dag(conf: ProviderWorkflow):"""- Given a `main_function` and `reingestion_day_list_list`, this- factory method instantiates a DAG that will run the given- `main_function`, parameterized by a number of dates, whose- calculation is described below.+ This factory method instantiates a DAG that will run the given+ `main_function`.Required Arguments:- dag_id: string giving a unique id of the DAG to- be created.- main_function: python function to be run. The- function must take a single parameter- (date) which will be a string of the- form 'YYYY-MM-DD'.- reingestion_day_list_list: list of lists of integers. It gives the- set of days before the current execution- date of the DAG for which the- `main_function` should be run, and- describes how the calls to the function- should be prioritized.+ conf: ProviderWorkflow configuration object.+ """+ default_args = {**DAG_DEFAULT_ARGS, **(conf.default_args or {})}- Optional Arguments:+ dag = DAG(+ dag_id=conf.dag_id,+ default_args={**default_args, "start_date": conf.start_date},+ max_active_tasks=conf.max_active_tasks,+ max_active_runs=conf.max_active_runs,+ start_date=conf.start_date,+ schedule_interval=conf.schedule_string,+ catchup=conf.dated, # catchup is turned on for dated DAGs to allow backfilling+ doc_md=conf.doc_md,+ tags=["provider"]+ + [f"provider: {media_type}" for media_type in conf.media_types],+ render_template_as_native_obj=True,+ user_defined_macros={"date_partition_for_prefix": date_partition_for_prefix},+ )++ with dag:+ ingest_data, ingestion_metrics = create_ingestion_workflow(conf)++ report_load_completion = create_report_load_completion(+ conf.dag_id, conf.media_types, ingestion_metrics, conf.dated+ )- start_date: datetime.datetime giving the- first valid execution_date of the DAG.- max_active_tasks: integer that sets the number of tasks which- can run simultaneously for this DAG. It's- important to keep the rate limits of the- Provider API in mind when setting this- parameter.- default_args: dictionary which is passed to the- airflow.dag.DAG __init__ method and used to- optionally override the DAG_DEFAULT_ARGS.- dagrun_timeout: datetime.timedelta giving the total amount- of time a given dagrun may take.- ingestion_task_timeout: datetime.timedelta giving the amount of- time a call to the `main_function` is- allowed to take.+ ingest_data >> report_load_completion++ return dag+++def _build_partitioned_ingest_workflows(+ partitioned_reingestion_days: list[list[int]], conf: ProviderReingestionWorkflow+):+ """+ Builds a list of lists of ingestion tasks, parameterized by the given+ dag conf and a list of day shifts. Calculation is explained below.++ Required Arguments:++ conf: ProviderReingestionWorkflow configuration+ object used to configure the ingestion tasks.+ partitioned_reingestion_days: list of lists of integers. It gives the+ set of days before the current execution+ date of the DAG for which the+ `main_function` should be run, and+ describes how the calls to the function+ should be prioritized.Calculation of ingestion dates:- The `reingestion_day_list_list` should have the form+ The `partitioned_reingestion_days` should have the form[[int, ..., int],[int, ..., int],@@ -363,12 +337,12 @@ def create_day_partitioned_ingestion_dag([int, ..., int]]It's not necessary for the inner lists to be the same length. The- DAG instantiated by this factory method will first run the- `main_function` for the current execution_date, then for the current+ task groups instantiated by this factory method will first run+ ingestion for the current execution_date, then for the currentdate minus the number of days given by integers in the first list(in an arbitrary order, and possibly in parallel if so configured),then for the dates calculated from the second list, and so on. For- example, given the `reingestion_day_list_list`+ example, given the `partitioned_reingestion_days`[[1, 2, 3],[8, 13, 18],@@ -388,48 +362,100 @@ def create_day_partitioned_ingestion_dag(executions of the `main_function` allowed; that is set by the`max_active_tasks` parameter."""- default_args = {**DAG_DEFAULT_ARGS, **(default_args or {})}+ if partitioned_reingestion_days[0] != [0]:+ partitioned_reingestion_days = [[0]] + partitioned_reingestion_days++ partitioned_workflows = []+ duration_list = []+ record_counts_by_media_type_list = []++ for partition in partitioned_reingestion_days:+ workflow_list = []+ for day_shift in partition:+ ingest_data, ingestion_metrics = create_ingestion_workflow(+ conf, day_shift, is_reingestion=True+ )+ workflow_list.append(ingest_data)+ duration_list.append(ingestion_metrics["duration"])+ record_counts_by_media_type_list.append(+ ingestion_metrics["record_counts_by_media_type"]+ )++ partitioned_workflows.append(workflow_list)++ total_ingestion_metrics = {+ "duration": duration_list,+ "record_counts_by_media_type": record_counts_by_media_type_list,+ }++ return partitioned_workflows, total_ingestion_metrics+++def create_day_partitioned_reingestion_dag(+ conf: ProviderReingestionWorkflow, partitioned_reingestion_days: list[list[int]]+):+ """+ Given a `conf` object and `reingestion_day_list_list`, this+ factory method instantiates a DAG that will run ingestion using the+ given configuration, parameterized by a number of dates calculated+ using the reingestion day list.++ Required Arguments:++ conf: ProviderReingestionWorkflow configuration+ object used to configure the ingestion tasks.+ reingestion_day_list_list: list of lists of integers. It gives the+ set of days before the current execution+ date of the DAG for which the+ `main_function` should be run, and+ describes how the calls to the function+ should be prioritized.+ """+ default_args = {**DAG_DEFAULT_ARGS, **(conf.default_args or {})}dag = DAG(- dag_id=dag_id,- default_args={**default_args, "start_date": start_date},- max_active_tasks=max_active_tasks,- max_active_runs=max_active_runs,- dagrun_timeout=dagrun_timeout,- schedule_interval="@daily",- start_date=start_date,+ dag_id=conf.dag_id,+ default_args={**default_args, "start_date": conf.start_date},+ max_active_tasks=conf.max_active_tasks,+ max_active_runs=conf.max_active_runs,+ dagrun_timeout=conf.dagrun_timeout,+ schedule_interval=conf.schedule_string,+ start_date=conf.start_date,catchup=False,- tags=["provider-reingestion"],+ doc_md=conf.doc_md,+ tags=["provider-reingestion"]+ + [f"provider-reingestion: {media_type}" for media_type in conf.media_types],+ render_template_as_native_obj=True,+ user_defined_macros={"date_partition_for_prefix": date_partition_for_prefix},)with dag:- ingest_operator_list_list = _build_ingest_operator_list_list(- reingestion_day_list_list, main_function, ingestion_task_timeout- )- for i in range(len(ingest_operator_list_list) - 1):- wait_operator = EmptyOperator(- task_id=f"wait_L{i}", trigger_rule=TriggerRule.ALL_DONE+ # Generate a list of lists of ingestion TaskGroups for each day of reingestion.+ (+ partitioned_ingest_workflows,+ ingestion_metrics,+ ) = _build_partitioned_ingest_workflows(partitioned_reingestion_days, conf)++ # For each 'level', make a gather task that waits for all of the reingestion+ # tasks at that level to complete.+ for i in range(len(partitioned_ingest_workflows) - 1):+ gather_operator = EmptyOperator(+ task_id=f"gather_partition_{i}", trigger_rule=TriggerRule.ALL_DONE)- cross_downstream(ingest_operator_list_list[i], [wait_operator])- wait_operator >> ingest_operator_list_list[i + 1]- ingest_operator_list_list[-1]- return dag+ # Set gather task downstream of all ingestion TaskGroups in the ith list.+ partitioned_ingest_workflows[i] >> gather_operator+ # Set gather task upstream of all ingestion TaskGroups in the i+1th list.+ # This gates the tasks at each level.+ gather_operator >> partitioned_ingest_workflows[i + 1]-def _build_ingest_operator_list_list(- reingestion_day_list_list, main_function, ingestion_task_timeout-):- if reingestion_day_list_list[0] != [0]:- reingestion_day_list_list = [[0]] + reingestion_day_list_list- return [- [- PythonOperator(- task_id=f"ingest_{d}",- python_callable=main_function,- op_args=[DATE_RANGE_ARG_TEMPLATE.format(d)],- execution_timeout=ingestion_task_timeout,- depends_on_past=False,- )- for d in L- ]- for L in reingestion_day_list_list- ]+ # Create a single report_load_completion task, passing in the list of duration+ # and counts data for each completed task.+ report_load_completion = create_report_load_completion(+ conf.dag_id, conf.media_types, ingestion_metrics, conf.dated+ )++ # report_load_completion is downstream of all the ingestion TaskGroups in the+ # final list.+ partitioned_ingest_workflows[-1] >> report_load_completion++ return dagdiff --git a/openverse_catalog/dags/providers/provider_ingestion_workflow_dag_factory.py b/openverse_catalog/dags/providers/provider_reingestion_workflow_dag_factory.pysimilarity index 56%rename from openverse_catalog/dags/providers/provider_ingestion_workflow_dag_factory.pyrename to openverse_catalog/dags/providers/provider_reingestion_workflow_dag_factory.pyindex 67e399ab2..85d9bd209 100644--- a/openverse_catalog/dags/providers/provider_ingestion_workflow_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_reingestion_workflow_dag_factory.py@@ -10,19 +10,13 @@ this will only pull data for each of the given days and create the tsv; theloading step is not yet wired up."""-import importlib+from common.helpers import IngestionInput, get_partitioned_reingestion_days+from providers.provider_dag_factory import create_day_partitioned_reingestion_dag+from providers.provider_reingestion_workflows import PROVIDER_REINGESTION_WORKFLOWS-from common.helpers import IngestionInput, get_reingestion_day_list_list-from providers.provider_dag_factory import create_day_partitioned_ingestion_dag-from providers.provider_ingestion_workflows import PROVIDER_INGESTION_WORKFLOWS--for config in PROVIDER_INGESTION_WORKFLOWS:- provider_script = importlib.import_module(- f"providers.provider_api_scripts.{config.provider_script}"- )-- reingestion_days = get_reingestion_day_list_list(+for config in PROVIDER_REINGESTION_WORKFLOWS:+ partitioned_reingestion_days = get_partitioned_reingestion_days([IngestionInput(1, config.daily_list_length),IngestionInput(7, config.weekly_list_length),@@ -33,14 +27,6 @@ for config in PROVIDER_INGESTION_WORKFLOWS:])- globals()[config.dag_id] = create_day_partitioned_ingestion_dag(- config.dag_id,- provider_script.main,- reingestion_days,- config.start_date,- config.max_active_runs,- config.max_active_tasks,- config.default_args,- config.dagrun_timeout,- config.pull_timeout,+ globals()[config.dag_id] = create_day_partitioned_reingestion_dag(+ config, partitioned_reingestion_days)diff --git a/openverse_catalog/dags/providers/provider_ingestion_workflows.py b/openverse_catalog/dags/providers/provider_reingestion_workflows.pysimilarity index 80%rename from openverse_catalog/dags/providers/provider_ingestion_workflows.pyrename to openverse_catalog/dags/providers/provider_reingestion_workflows.pyindex 1f544a3d9..16859766e 100644--- a/openverse_catalog/dags/providers/provider_ingestion_workflows.py+++ b/openverse_catalog/dags/providers/provider_reingestion_workflows.py@@ -1,11 +1,14 @@from dataclasses import dataclassfrom datetime import datetime, timedelta+from providers.provider_api_scripts.wikimedia_commons import (+ WikimediaCommonsDataIngester,+)from providers.provider_workflows import ProviderWorkflow@dataclass-class ProviderIngestionWorkflow(ProviderWorkflow):+class ProviderReingestionWorkflow(ProviderWorkflow):"""Extends the ProviderWorkflow with configuration options used to set upa day-partitioned ingestion workflow DAG.@@ -35,13 +38,13 @@ class ProviderIngestionWorkflow(ProviderWorkflow):dagrun_timeout: timedelta = timedelta(hours=23)# Override default ProviderWorkflow configurations- schedule_string: str = "@daily"- dated = True+ schedule_string: str = "@weekly"+ dated: bool = True-PROVIDER_INGESTION_WORKFLOWS = [- ProviderIngestionWorkflow(- dag_id="europeana_ingestion_workflow",+PROVIDER_REINGESTION_WORKFLOWS = [+ ProviderReingestionWorkflow(+ dag_id="europeana_reingestion_workflow",provider_script="europeana",start_date=datetime(2013, 11, 21),max_active_tasks=3,@@ -50,8 +53,8 @@ PROVIDER_INGESTION_WORKFLOWS = [one_month_list_length=12,three_month_list_length=40,),- ProviderIngestionWorkflow(- dag_id="flickr_ingestion_workflow",+ ProviderReingestionWorkflow(+ dag_id="flickr_reingestion_workflow",provider_script="flickr",pull_timeout=timedelta(minutes=30),daily_list_length=7,@@ -61,9 +64,10 @@ PROVIDER_INGESTION_WORKFLOWS = [three_month_list_length=24,six_month_list_length=40,),- ProviderIngestionWorkflow(- dag_id="wikimedia_ingestion_workflow",+ ProviderReingestionWorkflow(+ dag_id="wikimedia_reingestion_workflow",provider_script="wikimedia_commons",+ ingestion_callable=WikimediaCommonsDataIngester,pull_timeout=timedelta(minutes=90),media_types=("image", "audio"),max_active_tasks=2,diff --git a/openverse_catalog/dags/providers/provider_workflow_dag_factory.py b/openverse_catalog/dags/providers/provider_workflow_dag_factory.pyindex 5ebdba20d..7f242f0f2 100644--- a/openverse_catalog/dags/providers/provider_workflow_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_workflow_dag_factory.py@@ -5,34 +5,11 @@ This file iterates over the configurations defined in PROVIDER_WORKFLOWSand generates a provider workflow DAG in Airflow for each."""-import importlib--from providers.provider_dag_factory import create_provider_api_workflow+from providers.provider_dag_factory import create_provider_api_workflow_dagfrom providers.provider_workflows import PROVIDER_WORKFLOWSfor provider_workflow in PROVIDER_WORKFLOWS:- provider_script = importlib.import_module(- f"providers.provider_api_scripts.{provider_workflow.provider_script}"- )-- # Use the ingester class if it exists, or fall back to the `main` method- ingestion_callable = provider_workflow.ingester_class or provider_script.main-- globals()[provider_workflow.dag_id] = create_provider_api_workflow(- provider_workflow.dag_id,- ingestion_callable,- provider_workflow.default_args,- provider_workflow.start_date,- provider_workflow.max_active_runs,- provider_workflow.max_active_tasks,- provider_workflow.schedule_string,- provider_workflow.dated,- provider_workflow.day_shift,- provider_workflow.pull_timeout,- provider_workflow.load_timeout,- provider_script.__doc__,- provider_workflow.media_types,- provider_workflow.preingestion_task_creator,- provider_workflow.postingestion_task_creator,+ globals()[provider_workflow.dag_id] = create_provider_api_workflow_dag(+ provider_workflow)diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.pyindex 0a38eb01b..c646b52c2 100644--- a/openverse_catalog/dags/providers/provider_workflows.py+++ b/openverse_catalog/dags/providers/provider_workflows.py@@ -1,3 +1,4 @@+import importlibfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import Dict, Optional, Sequence, Type@@ -30,46 +31,49 @@ class ProviderWorkflow:Optional Arguments:- dag_id: string giving a unique id of the DAG to be created. By- default this will be set to the name of the provider_script,- appended with 'workflow'.- default_args: dictionary which is passed to the airflow.dag.DAG- __init__ method and used to optionally override the- DAG_DEFAULT_ARGS.- start_date: datetime.datetime giving the first valid execution- date of the DAG.- max_active_runs: integer that sets the number of dagruns of this DAG- which can be run in parallel.- max_active_tasks: integer that sets the number of tasks which can- run simultaneously for this DAG.- It's important to keep the rate limits of the- Provider API in mind when setting this parameter.- schedule_string: string giving the schedule on which the DAG should- be run. Passed to the airflow.dag.DAG __init__- method.- dated: boolean giving whether the `main_function` takes a- string parameter giving a date (i.e., the date for- which data should be ingested).- day_shift: integer giving the number of days before the- current execution date the `main_function` should- be run (if `dated=True`).- pull_timeout: datetime.timedelta giving the amount of time a given data- pull may take.- load_timeout: datetime.timedelta giving the amount of time the load_data- task may take.- doc_md: string which should be used for the DAG's documentation markdown- media_types: list describing the media type(s) that this provider handles- (e.g. `["audio"]`, `["image", "audio"]`, etc.)- preingestion_task_creator: callable that returns an airflow task or task group to+ dag_id: string giving a unique id of the DAG to be created. By+ default this will be set to the name of the provider_script,+ appended with 'workflow'.+ ingestion_callable: ProviderDataIngester class whose `ingest_records` method is+ to be run. Temporarily, may also be a `main` function for+ providers that have not yet been refactored. TODO: Remove this+ comment when refactors are completed.+ default_args: dictionary which is passed to the airflow.dag.DAG+ __init__ method and used to optionally override the+ DAG_DEFAULT_ARGS.+ start_date: datetime.datetime giving the first valid execution+ date of the DAG.+ max_active_runs: integer that sets the number of dagruns of this DAG+ which can be run in parallel.+ max_active_tasks: integer that sets the number of tasks which can+ run simultaneously for this DAG.+ It's important to keep the rate limits of the+ Provider API in mind when setting this parameter.+ schedule_string: string giving the schedule on which the DAG should+ be run. Passed to the airflow.dag.DAG __init__+ method.+ dated: boolean giving whether the `main_function` takes a+ string parameter giving a date (i.e., the date for+ which data should be ingested).+ pull_timeout: datetime.timedelta giving the amount of time a given data+ pull may take.+ load_timeout: datetime.timedelta giving the amount of time the load_data+ task may take.+ doc_md: string which should be used for the DAG's documentation markdown+ media_types: list describing the media type(s) that this provider handles+ (e.g. `["audio"]`, `["image", "audio"]`, etc.)+ create_preingestion_tasks: callable that returns an airflow task or task group toto run any necessary pre-ingestion tasks, such as loading bulkdata from S3- postingestion_task_creator: callable that returns an airflow task or task group to+ create_postingestion_tasks: callable that returns an airflow task or task group toto run any necessary post-ingestion tasks, such as dropping dataloaded during pre-ingestion"""provider_script: str- ingester_class: Optional[Type[ProviderDataIngester]] = None+ # TODO: update the ingestion_callable to only accept ProviderDataIngester classes+ # when all provider scripts have been refactored.+ ingestion_callable: Type[ProviderDataIngester] | callable = Nonedag_id: str = ""default_args: Optional[Dict] = Nonestart_date: datetime = datetime(1970, 1, 1)@@ -77,28 +81,37 @@ class ProviderWorkflow:max_active_tasks: int = 1schedule_string: str = "@monthly"dated: bool = False- day_shift: int = 0pull_timeout: timedelta = timedelta(hours=24)load_timeout: timedelta = timedelta(hours=1)doc_md: str = ""media_types: Sequence[str] = ("image",)- preingestion_task_creator: Optional[callable] = None- postingestion_task_creator: Optional[callable] = None+ create_preingestion_tasks: Optional[callable] = None+ create_postingestion_tasks: Optional[callable] = Nonedef __post_init__(self):if not self.dag_id:self.dag_id = f"{self.provider_script}_workflow"+ provider_script = importlib.import_module(+ f"providers.provider_api_scripts.{self.provider_script}"+ )++ if not self.ingestion_callable:+ self.ingestion_callable = provider_script.main++ if not self.doc_md:+ self.doc_md = provider_script.__doc__+PROVIDER_WORKFLOWS = [ProviderWorkflow(provider_script="brooklyn_museum",start_date=datetime(2020, 1, 1),- ingester_class=BrooklynMuseumDataIngester,+ ingestion_callable=BrooklynMuseumDataIngester,),ProviderWorkflow(provider_script="cleveland_museum",- ingester_class=ClevelandDataIngester,+ ingestion_callable=ClevelandDataIngester,start_date=datetime(2020, 1, 15),pull_timeout=timedelta(hours=12),),@@ -110,7 +123,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="finnish_museums",- ingester_class=FinnishMuseumsDataIngester,+ ingestion_callable=FinnishMuseumsDataIngester,start_date=datetime(2020, 9, 1),pull_timeout=timedelta(days=5),load_timeout=timedelta(days=5),@@ -123,9 +136,9 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="inaturalist",- ingester_class=INaturalistDataIngester,- preingestion_task_creator=INaturalistDataIngester.create_preingestion_tasks,- postingestion_task_creator=INaturalistDataIngester.create_postingestion_tasks,+ ingestion_callable=INaturalistDataIngester,+ create_preingestion_tasks=INaturalistDataIngester.create_preingestion_tasks,+ create_postingestion_tasks=INaturalistDataIngester.create_postingestion_tasks,schedule_string="@monthly",pull_timeout=timedelta(days=5),load_timeout=timedelta(days=5),@@ -140,7 +153,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="metropolitan_museum",- ingester_class=MetMuseumDataIngester,+ ingestion_callable=MetMuseumDataIngester,start_date=datetime(2016, 9, 1),schedule_string="@daily",dated=True,@@ -148,7 +161,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="museum_victoria",- ingester_class=VictoriaDataIngester,+ ingestion_callable=VictoriaDataIngester,start_date=datetime(2020, 1, 1),),ProviderWorkflow(@@ -168,7 +181,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="science_museum",- ingester_class=ScienceMuseumDataIngester,+ ingestion_callable=ScienceMuseumDataIngester,start_date=datetime(2020, 1, 1),),ProviderWorkflow(@@ -183,7 +196,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="stocksnap",- ingester_class=StockSnapDataIngester,+ ingestion_callable=StockSnapDataIngester,),ProviderWorkflow(provider_script="walters",@@ -191,7 +204,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="wikimedia_commons",- ingester_class=WikimediaCommonsDataIngester,+ ingestion_callable=WikimediaCommonsDataIngester,start_date=datetime(2020, 11, 1),schedule_string="@daily",dated=True,diff --git a/tests/dags/common/loader/test_reporting.py b/tests/dags/common/loader/test_reporting.pyindex d604656ee..81ca2c610 100644--- a/tests/dags/common/loader/test_reporting.py+++ b/tests/dags/common/loader/test_reporting.py@@ -3,7 +3,8 @@ from unittest import mockimport pytestfrom common.loader.reporting import (RecordMetrics,- humanize_time_duration,+ clean_duration,+ clean_record_counts,report_completion,)@@ -22,7 +23,14 @@ def test_report_completion(should_send_message):with mock.patch("common.slack.should_send_message", return_value=should_send_message):- report_completion("Jamendo", None, {"audio": RecordMetrics(100, 0, 0, 0)})+ report_completion(+ "Jamendo",+ [+ "audio",+ ],+ None,+ {"audio": RecordMetrics(100, 0, 0, 0)},+ )# Send message is only called if `should_send_message` is True.send_message_mock.called = should_send_message@@ -87,6 +95,34 @@ def _make_report_completion_contents_data(media_type: str):]+def _make_report_completion_contents_list_data(media_type: str):+ return [+ # List of RecordMetrics should be summed and handle Nones+ (+ [+ {media_type: RecordMetrics(100, 10, 10, 10)},+ {media_type: RecordMetrics(200, 20, 0, 0)},+ {media_type: None},+ {media_type: RecordMetrics(None, None, None, None)},+ {media_type: RecordMetrics(100, None, 100, 200)},+ ],+ f" - `{media_type}`: 400 _(30 missing columns, 110 duplicate foreign"+ f" IDs, 210 duplicate URLs)_",+ ),+ # List of RecordMetrics that sum to no data+ (+ [+ {media_type: RecordMetrics(0, 0, 0, 0)},+ {media_type: None},+ {media_type: RecordMetrics(None, None, None, None)},+ {media_type: RecordMetrics(0, None, None, 0)},+ {media_type: RecordMetrics(None, 0, 0, 0)},+ ],+ f" - `{media_type}`: _No data_",+ ),+ ]++# This sets up parameterizations for both audio and image simultaneously, in order# to test that the statistics are reported accurately independent of each other.@pytest.mark.parametrize(@@ -119,6 +155,7 @@ def test_report_completion_contents(with mock.patch("common.loader.reporting.send_message"):message = report_completion("Jamendo",+ ["audio", "image"],None,{**audio_data, **image_data},dated,@@ -136,6 +173,62 @@ def test_report_completion_contents(assert expected_date_range in date_part+# This sets up parameterizations for both audio and image simultaneously, in order+# to test that the statistics are reported accurately independent of each other.+ "audio_data, audio_expected", _make_report_completion_contents_list_data("audio")+)+ "image_data, image_expected", _make_report_completion_contents_list_data("image")+)+ "dated, date_range_start, date_range_end, expected_date_range",+ [+ # Not dated, no date range+ (False, None, None, "all"),+ # Not dated, but date range supplied+ (False, "2022-01-01", "2022-05-01", "all"),+ # Schedule interval and date range supplied+ (True, "2022-01-01", "2022-01-02", "2022-01-01 -> 2022-01-02"),+ ],+)+def test_report_completion_contents_with_lists(+ audio_data,+ audio_expected,+ image_data,+ image_expected,+ dated,+ date_range_start,+ date_range_end,+ expected_date_range,+):+ with mock.patch("common.loader.reporting.send_message"):+ # Build record_counts_by_media_type+ record_counts_by_media_type = [+ {**audio, **image} for audio, image in zip(audio_data, image_data)+ ]++ message = report_completion(+ "Jamendo",+ ["audio", "image"],+ None,+ record_counts_by_media_type,+ dated,+ date_range_start,+ date_range_end,+ )++ for expected in [audio_expected, image_expected]:+ assert (+ expected in message+ ), "Completion message doesn't contain expected text"+ # Split message into "sections"+ parts = message.strip().split("\n")+ # Get the date section+ date_part = parts[1]+ assert expected_date_range in date_part++@pytest.mark.parametrize("seconds, expected",[@@ -148,8 +241,60 @@ def test_report_completion_contents((100000, "1 day, 3 hours, 46 mins, 40 secs"),(1000000, "1 week, 4 days, 13 hours, 46 mins, 40 secs"),(10000000, "16 weeks, 3 days, 17 hours, 46 mins, 40 secs"),+ # Lists of durations+ ([0.1, 0.2, 0.1], "less than 1 sec"),+ ([0.2, 0.2, 0.6], "1 sec"),+ ([3, 7], "10 secs"),+ ([4, 6, 40, 50], "1 min, 40 secs"),+ ([150, 150, 300, 300, 100], "16 mins, 40 secs"),+ ([2000, 5000, 3000], "2 hours, 46 mins, 40 secs"),+ ],+)+def test_clean_time_duration(seconds, expected):+ actual = clean_duration(seconds)+ assert actual == expected+++ "record_counts_by_media_type, media_types, expected",+ [+ # Single, one media type+ (+ {"image": RecordMetrics(1, 2, 3, 4)},+ [+ "image",+ ],+ {"image": RecordMetrics(1, 2, 3, 4)},+ ),+ # Single, multiple media types+ (+ {"image": RecordMetrics(1, 2, 3, 4), "audio": RecordMetrics(1, 2, 0, 0)},+ ["image", "audio"],+ {"image": RecordMetrics(1, 2, 3, 4), "audio": RecordMetrics(1, 2, 0, 0)},+ ),+ # Multiple+ (+ [+ {+ "image": RecordMetrics(1, 2, 3, 4),+ "audio": RecordMetrics(1, 2, 0, 0),+ },+ {"image": None, "audio": RecordMetrics(0, None, 0, 0)},+ {"image": RecordMetrics(0, 0, None, 0), "audio": None},+ {+ "image": RecordMetrics(None, None, None, None),+ "audio": RecordMetrics(1, 2, 0, 0),+ },+ {+ "image": RecordMetrics(4, 3, 2, 1),+ "audio": RecordMetrics(10, 1, 7, 2),+ },+ ],+ ["image", "audio"],+ {"image": RecordMetrics(5, 5, 5, 5), "audio": RecordMetrics(12, 5, 7, 2)},+ ),],)-def test_humanize_time_duration(seconds, expected):- actual = humanize_time_duration(seconds)+def test_clean_record_counts(record_counts_by_media_type, media_types, expected):+ actual = clean_record_counts(record_counts_by_media_type, media_types)assert actual == expecteddiff --git a/tests/dags/common/test_helpers.py b/tests/dags/common/test_helpers.pyindex 4f07c1020..1012eac20 100644--- a/tests/dags/common/test_helpers.py+++ b/tests/dags/common/test_helpers.py@@ -1,17 +1,17 @@-from common.helpers import IngestionInput, get_reingestion_day_list_list+from common.helpers import IngestionInput, get_partitioned_reingestion_days-def test_get_reingestion_day_list_list_handles_single_tuple():+def test_get_partitioned_reingestion_days_handles_single_tuple():input_list = [IngestionInput(2, 3),]- actual_dll = get_reingestion_day_list_list(input_list)+ actual_dll = get_partitioned_reingestion_days(input_list)expect_dll = [[2, 4, 6]]assert actual_dll == expect_dll-def test_get_reingestion_day_list_list_handles_multiple_tuples():- actual_dll = get_reingestion_day_list_list(+def test_get_partitioned_reingestion_days_handles_multiple_tuples():+ actual_dll = get_partitioned_reingestion_days([IngestionInput(2, 3), IngestionInput(3, 2), IngestionInput(4, 4)])expect_dll = [[2, 4, 6], [9, 12], [16, 20, 24, 28]]diff --git a/tests/dags/providers/test_factory_utils.py b/tests/dags/providers/test_factory_utils.pyindex e0e768f1b..c657dcda1 100644--- a/tests/dags/providers/test_factory_utils.py+++ b/tests/dags/providers/test_factory_utils.py@@ -247,8 +247,10 @@ def test_pull_media_wrapper_always_pushes_duration(func, ti_mock, dagrun_mock):assert duration > 0+# Set up parametrizations for the schedule_interval and reingestion_date,+# which result in different components of the path@pytest.mark.parametrize(- "schedule_interval, expected",+ "schedule_interval, expected_schedule_prefix",[# Hourly should have year/month/day("@hourly", "year=2022/month=02/day=03"),@@ -266,9 +268,21 @@ def test_pull_media_wrapper_always_pushes_duration(func, ti_mock, dagrun_mock):(None, "year=2022"),],)-def test_date_partition_for_prefix(schedule_interval, expected):+ "reingestion_date, expected_reingestion_prefix",+ [+ # No reingestion date provided+ (None, ""),+ ("2022-01-01", "/reingestion=2022-01-01"),+ ],+)+def test_date_partition_for_prefix(+ schedule_interval,+ expected_schedule_prefix,+ reingestion_date,+ expected_reingestion_prefix,+):actual = factory_utils.date_partition_for_prefix(- schedule_interval,- datetime(2022, 2, 3),+ schedule_interval, datetime(2022, 2, 3), reingestion_date)- assert actual == expected+ assert actual == expected_schedule_prefix + expected_reingestion_prefixdiff --git a/tests/dags/providers/test_provider_dag_factory.py b/tests/dags/providers/test_provider_dag_factory.pyindex 691e0256f..aa9c0620a 100644--- a/tests/dags/providers/test_provider_dag_factory.py+++ b/tests/dags/providers/test_provider_dag_factory.py@@ -7,6 +7,8 @@ from airflow.models import DagRun, TaskInstancefrom airflow.utils.session import create_sessionfrom pendulum import nowfrom providers import provider_dag_factory+from providers.provider_reingestion_workflows import ProviderReingestionWorkflow+from providers.provider_workflows import ProviderWorkflowfrom tests.conftest import mark_extended@@ -57,59 +59,71 @@ def test_skipped_pull_data_runs_successfully(side_effect, clean_db):) as pull_media_mock:generate_filenames_mock.side_effect = _generate_tsv_mockpull_media_mock.side_effect = side_effect- dag = provider_dag_factory.create_provider_api_workflow(- dag_id=DAG_ID,- ingestion_callable=None,- default_args={"retries": 0, "on_failure_callback": None},- schedule_string="@once",- dated=False,+ dag = provider_dag_factory.create_provider_api_workflow_dag(+ ProviderWorkflow(+ provider_script="provider_data_ingester",+ ingestion_callable=print,+ dag_id=DAG_ID,+ default_args={"retries": 0, "on_failure_callback": None},+ schedule_string="@once",+ ))# Pendulum must be used here in order for Airflow to run this successfullydag.run(start_date=now(), executor=DebugExecutor())def test_create_day_partitioned_ingestion_dag_with_single_layer_dependencies():- dag = provider_dag_factory.create_day_partitioned_ingestion_dag(- "test_dag",- print,+ dag = provider_dag_factory.create_day_partitioned_reingestion_dag(+ ProviderReingestionWorkflow(+ dag_id="test_dag",+ provider_script="provider_data_ingester",+ ingestion_callable=print,+ ),[[1, 2]],)- today_id = "ingest_0"- wait0_id = "wait_L0"- ingest1_id = "ingest_1"- ingest2_id = "ingest_2"- today_task = dag.get_task(today_id)- assert today_task.upstream_task_ids == set()- assert today_task.downstream_task_ids == {wait0_id}+ # First task in the ingestion step for today+ today_pull_data_id = "ingest_data.generate_image_filename"+ # Last task in the ingestion step for today+ today_drop_table_id = "ingest_data.load_image_data.drop_loading_table"+ gather0_id = "gather_partition_0"+ ingest1_id = "ingest_data_day_shift_1.generate_image_filename_day_shift_1"+ ingest2_id = "ingest_data_day_shift_2.generate_image_filename_day_shift_2"+ today_pull_task = dag.get_task(today_pull_data_id)+ assert today_pull_task.upstream_task_ids == set()+ gather_task = dag.get_task(gather0_id)+ assert gather_task.upstream_task_ids == {today_drop_table_id}ingest1_task = dag.get_task(ingest1_id)- assert ingest1_task.upstream_task_ids == {wait0_id}+ assert ingest1_task.upstream_task_ids == {gather0_id}ingest2_task = dag.get_task(ingest2_id)- assert ingest2_task.upstream_task_ids == {wait0_id}+ assert ingest2_task.upstream_task_ids == {gather0_id}def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():- dag = provider_dag_factory.create_day_partitioned_ingestion_dag(- "test_dag",- print,+ dag = provider_dag_factory.create_day_partitioned_reingestion_dag(+ ProviderReingestionWorkflow(+ dag_id="test_dag",+ provider_script="provider_data_ingester",+ ingestion_callable=print,+ ),[[1, 2], [3, 4, 5]],)- today_id = "ingest_0"- wait0_id = "wait_L0"- ingest1_id = "ingest_1"- ingest2_id = "ingest_2"- wait1_id = "wait_L1"- ingest3_id = "ingest_3"- ingest4_id = "ingest_4"- ingest5_id = "ingest_5"+ today_id = "ingest_data.generate_image_filename"+ gather0_id = "gather_partition_0"+ ingest1_id = "ingest_data_day_shift_1.generate_image_filename_day_shift_1"+ ingest2_id = "ingest_data_day_shift_2.generate_image_filename_day_shift_2"+ gather1_id = "gather_partition_1"+ ingest3_id = "ingest_data_day_shift_3.generate_image_filename_day_shift_3"+ ingest4_id = "ingest_data_day_shift_4.generate_image_filename_day_shift_4"+ ingest5_id = "ingest_data_day_shift_5.generate_image_filename_day_shift_5"today_task = dag.get_task(today_id)assert today_task.upstream_task_ids == set()ingest1_task = dag.get_task(ingest1_id)- assert ingest1_task.upstream_task_ids == {wait0_id}+ assert ingest1_task.upstream_task_ids == {gather0_id}ingest2_task = dag.get_task(ingest2_id)- assert ingest2_task.upstream_task_ids == {wait0_id}+ assert ingest2_task.upstream_task_ids == {gather0_id}ingest3_task = dag.get_task(ingest3_id)- assert ingest3_task.upstream_task_ids == {wait1_id}+ assert ingest3_task.upstream_task_ids == {gather1_id}ingest4_task = dag.get_task(ingest4_id)- assert ingest4_task.upstream_task_ids == {wait1_id}+ assert ingest4_task.upstream_task_ids == {gather1_id}ingest5_task = dag.get_task(ingest5_id)- assert ingest5_task.upstream_task_ids == {wait1_id}+ assert ingest5_task.upstream_task_ids == {gather1_id}diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.pyindex ad148209b..d6bfcfdaa 100644--- a/tests/dags/test_dag_parsing.py+++ b/tests/dags/test_dag_parsing.py@@ -3,8 +3,8 @@ from pathlib import Pathimport pytestfrom airflow.models import DagBagfrom common.constants import MEDIA_TYPES-from providers.provider_ingestion_workflows import (- PROVIDER_INGESTION_WORKFLOWS as INGESTION_WORKFLOW_CONFIGS,+from providers.provider_reingestion_workflows import (+ PROVIDER_REINGESTION_WORKFLOWS as REINGESTION_WORKFLOW_CONFIGS,)from providers.provider_workflows import PROVIDER_WORKFLOWS as PROVIDER_WORKFLOW_CONFIGS@@ -32,7 +32,7 @@ DAG_PATHS = [EXPECTED_COUNT = {"providers/provider_workflow_dag_factory.py": len(PROVIDER_WORKFLOW_CONFIGS),"providers/provider_ingestion_workflow_dag_factory.py": len(- INGESTION_WORKFLOW_CONFIGS+ REINGESTION_WORKFLOW_CONFIGS),"database/recreate_popularity_calculation_dag_factory.py": len(MEDIA_TYPES),"data_refresh/dag_factory.py": len(MEDIA_TYPES),