Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add new data refresh factory (#4259)

Staci Mullinsbc457c020d40
diff --git a/catalog/dags/common/constants.py b/catalog/dags/common/constants.py
index 39c318bc5..f2b1f45a4 100644
--- a/catalog/dags/common/constants.py
+++ b/catalog/dags/common/constants.py
@@ -39,6 +39,11 @@ XCOM_PULL_TEMPLATE = "{{{{ ti.xcom_pull(task_ids='{}', key='{}') }}}}"
POSTGRES_CONN_ID = "postgres_openledger_upstream"
OPENLEDGER_API_CONN_ID = "postgres_openledger_api"
POSTGRES_API_STAGING_CONN_ID = "postgres_openledger_api_staging"
+POSTGRES_API_CONN_IDS = {
+ STAGING: POSTGRES_API_STAGING_CONN_ID,
+ PRODUCTION: OPENLEDGER_API_CONN_ID,
+}
+
AWS_CONN_ID = "aws_default"
AWS_CLOUDWATCH_CONN_ID = os.environ.get("AWS_CLOUDWATCH_CONN_ID", AWS_CONN_ID)
AWS_RDS_CONN_ID = os.environ.get("AWS_RDS_CONN_ID", AWS_CONN_ID)
@@ -49,7 +54,7 @@ REFRESH_POKE_INTERVAL = int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30))
@dataclass
class SQLInfo:
"""
- Configuration object for a media type's popularity SQL info.
+ Configuration object for a media type's SQL info.
Required Constructor Arguments:
diff --git a/catalog/dags/data_refresh/copy_data.py b/catalog/dags/data_refresh/copy_data.py
new file mode 100644
index 000000000..dea6a2cc7
--- /dev/null
+++ b/catalog/dags/data_refresh/copy_data.py
@@ -0,0 +1,323 @@
+"""
+# Copy Data TaskGroup
+
+This module contains the Airflow tasks used for copying upstream (Catalog)
+tables into new temporary tables in the downstream (API) database. This
+is one of the initial steps of the data refresh. These temporary tables
+will later be used to create new Elasticsearch indices, and ultimately
+will be promoted to the live media tables in the API.
+
+"""
+
+import logging
+from dataclasses import asdict
+from datetime import timedelta
+from textwrap import dedent
+
+from airflow.decorators import task, task_group
+from airflow.models import Variable
+from airflow.models.abstractoperator import AbstractOperator
+from airflow.models.connection import Connection
+
+from common.constants import (
+ POSTGRES_API_CONN_IDS,
+ POSTGRES_CONN_ID,
+ PRODUCTION,
+ Environment,
+)
+from common.sql import RETURN_ROW_COUNT, PostgresHook
+from data_refresh import queries
+from data_refresh.data_refresh_types import DataRefreshConfig
+
+
+logger = logging.getLogger(__name__)
+
+
+DEFAULT_DATA_REFRESH_LIMIT = 10_000
+
+
+@task
+def _run_sql(
+ postgres_conn_id: str,
+ sql_template: str,
+ task: AbstractOperator = None,
+ timeout: float = None,
+ handler: callable = RETURN_ROW_COUNT,
+ **kwargs,
+):
+ query = sql_template.format(**kwargs)
+
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=(
+ timeout if timeout else PostgresHook.get_execution_timeout(task)
+ ),
+ )
+
+ return postgres.run(query, handler=handler)
+
+
+@task
+def initialize_fdw(
+ upstream_conn_id: str,
+ downstream_conn_id: str,
+ task: AbstractOperator = None,
+):
+ """Create the FDW and prepare it for copying."""
+ upstream_connection = Connection.get_connection_from_secrets(upstream_conn_id)
+
+ _run_sql.function(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.CREATE_FDW_QUERY,
+ task=task,
+ host=upstream_connection.host,
+ port=upstream_connection.port,
+ dbname=upstream_connection.schema,
+ user=upstream_connection.login,
+ password=upstream_connection.password,
+ )
+
+
+@task(map_index_template="{{ task.op_kwargs['upstream_table_name'] }}")
+def create_schema(downstream_conn_id: str, upstream_table_name: str) -> str:
+ """
+ Create a new schema in the downstream DB through which the upstream table
+ can be accessed. Returns the schema name.
+ """
+ downstream_pg = PostgresHook(
+ postgres_conn_id=downstream_conn_id, default_statement_timeout=10.0
+ )
+
+ schema_name = f"upstream_{upstream_table_name}_schema"
+ downstream_pg.run(
+ queries.CREATE_SCHEMA_QUERY.format(
+ schema_name=schema_name, upstream_table_name=upstream_table_name
+ )
+ )
+ return schema_name
+
+
+@task
+def get_record_limit() -> int | None:
+ """
+ Check and retrieve the limit of records to ingest for the environment in which
+ Airflow is running.
+
+ If a limit is explicitly configured, it is always used. Otherwise, production
+ defaults to no limit, and all other environments default to 100,000.
+ """
+ try:
+ # If a limit is explicitly configured, always use it.
+ return Variable.get("DATA_REFRESH_LIMIT", deserialize_json=True)
+ except KeyError:
+ # Defaults when no limit is explicitly configured.
+ # Note `environment` differs from the target env of the data refresh DAG;
+ # instead, it is the environment in which Airflow is running (local testing
+ # vs the production catalog).
+ environment = Variable.get("ENVIRONMENT", default_var="local")
+ if environment == PRODUCTION:
+ # Never limit the record count in production.
+ return None
+
+ return DEFAULT_DATA_REFRESH_LIMIT
+
+
+@task(map_index_template="{{ task.op_kwargs['upstream_table_name'] }}")
+def get_shared_columns(
+ upstream_conn_id: str,
+ downstream_conn_id: str,
+ upstream_table_name: str,
+ downstream_table_name: str,
+) -> list[str]:
+ """Get a list of column identifiers shared between two tables."""
+ upstream_pg = PostgresHook(
+ postgres_conn_id=upstream_conn_id, default_statement_timeout=10.0
+ )
+ downstream_pg = PostgresHook(
+ postgres_conn_id=downstream_conn_id, default_statement_timeout=10.0
+ )
+
+ query = "SELECT * FROM {table} LIMIT 0;"
+ handler = lambda cursor: {desc[0] for desc in cursor.description} # noqa: E731
+
+ upstream_cols = upstream_pg.run(
+ query.format(table=upstream_table_name), handler=handler
+ )
+
+ downstream_cols = downstream_pg.run(
+ query.format(table=downstream_table_name), handler=handler
+ )
+
+ return list(upstream_cols.intersection(downstream_cols))
+
+
+@task(
+ # Ensure that only one table is being copied at a time.
+ max_active_tis_per_dagrun=1,
+ map_index_template="{{ task.op_kwargs['upstream_table_name'] }}",
+)
+def copy_data(
+ postgres_conn_id: str,
+ limit: int | None,
+ sql_template: str,
+ temp_table_name: str,
+ schema_name: str,
+ upstream_table_name: str,
+ deleted_table_name: str,
+ columns: list[str],
+ task: AbstractOperator = None,
+):
+ """Copy data from the upstream table into the downstream temp table."""
+ # If a limit is configured, add the appropriate conditions onto the
+ # select/insert
+ if limit:
+ if "identifier" in columns:
+ sql_template += dedent(
+ """
+ ORDER BY identifier"""
+ )
+ sql_template += dedent(
+ """
+ LIMIT {limit};"""
+ )
+
+ return _run_sql.function(
+ postgres_conn_id=postgres_conn_id,
+ sql_template=sql_template,
+ task=task,
+ temp_table_name=temp_table_name,
+ columns=", ".join(columns),
+ schema_name=schema_name,
+ upstream_table_name=upstream_table_name,
+ deleted_table_name=deleted_table_name,
+ limit=limit,
+ )
+
+
+@task_group(group_id="copy_upstream_table")
+def copy_upstream_table(
+ upstream_conn_id: str,
+ downstream_conn_id: str,
+ environment: Environment,
+ timeout: timedelta,
+ limit: int,
+ upstream_table_name: str,
+ downstream_table_name: str,
+ tertiary_column_query: str,
+ copy_data_query: str,
+ temp_table_name: str,
+ deleted_table_name: str,
+):
+ """
+ Copy an individual table from the upstream DB into a new temporary table
+ in the downstream DB.
+ """
+ shared_cols = get_shared_columns(
+ upstream_conn_id=upstream_conn_id,
+ downstream_conn_id=downstream_conn_id,
+ upstream_table_name=upstream_table_name,
+ downstream_table_name=downstream_table_name,
+ )
+
+ schema = create_schema(
+ downstream_conn_id=downstream_conn_id,
+ upstream_table_name=upstream_table_name,
+ )
+
+ create_temp_table = _run_sql.override(
+ task_id="create_temp_table",
+ map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
+ )(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.CREATE_TEMP_TABLE_QUERY,
+ temp_table_name=temp_table_name,
+ downstream_table_name=downstream_table_name,
+ )
+
+ setup_id_columns = _run_sql.override(
+ task_id="setup_id_columns",
+ map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
+ )(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.ID_COLUMN_SETUP_QUERY,
+ temp_table_name=temp_table_name,
+ )
+
+ setup_tertiary_columns = _run_sql.override(
+ task_id="setup_tertiary_columns",
+ map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
+ )(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=tertiary_column_query,
+ temp_table_name=temp_table_name,
+ )
+
+ copy = copy_data.override(execution_timeout=timeout)(
+ postgres_conn_id=downstream_conn_id,
+ limit=limit,
+ sql_template=copy_data_query,
+ temp_table_name=temp_table_name,
+ schema_name=schema,
+ upstream_table_name=upstream_table_name,
+ deleted_table_name=deleted_table_name,
+ columns=shared_cols,
+ )
+
+ add_primary_key = _run_sql.override(
+ task_id="add_primary_key",
+ map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
+ )(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.ADD_PRIMARY_KEY_QUERY,
+ temp_table_name=temp_table_name,
+ )
+
+ create_temp_table >> setup_id_columns >> setup_tertiary_columns
+ setup_tertiary_columns >> copy
+ copy >> add_primary_key
+ return
+
+
+@task_group(group_id="copy_upstream_tables")
+def copy_upstream_tables(
+ environment: Environment, data_refresh_config: DataRefreshConfig
+):
+ """
+ For each upstream table associated with the given media type, create a new
+ temp table in the downstream DB and copy all the upstream data into it.
+ These temp tables will later replace the main media tables in the API.
+
+ This task does _not_ apply all indices and constraints, merely copies
+ the data.
+ """
+ downstream_conn_id = POSTGRES_API_CONN_IDS.get(environment)
+ upstream_conn_id = POSTGRES_CONN_ID
+
+ create_fdw = _run_sql.override(task_id="create_fdw")(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.CREATE_FDW_EXTENSION_QUERY,
+ )
+
+ init_fdw = initialize_fdw(
+ upstream_conn_id=upstream_conn_id,
+ downstream_conn_id=downstream_conn_id,
+ )
+
+ limit = get_record_limit()
+
+ # Copy all tables mapped for this media type
+ copy_tables = copy_upstream_table.partial(
+ upstream_conn_id=upstream_conn_id,
+ downstream_conn_id=downstream_conn_id,
+ environment=environment,
+ timeout=data_refresh_config.copy_data_timeout,
+ limit=limit,
+ ).expand_kwargs([asdict(tm) for tm in data_refresh_config.table_mappings])
+
+ drop_fdw = _run_sql.override(task_id="drop_fdw")(
+ postgres_conn_id=downstream_conn_id,
+ sql_template=queries.DROP_SERVER_QUERY,
+ )
+
+ # Set up dependencies
+ create_fdw >> init_fdw >> copy_tables >> drop_fdw
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
new file mode 100644
index 000000000..474c57545
--- /dev/null
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -0,0 +1,222 @@
+"""
+# Data Refresh DAG Factory
+
+This file generates our data refresh DAGs for each media type and environment using a factory function. The data refresh is a process which makes new content added to the Catalog by our provider DAGs available to the API.
+
+The data refresh has the following high level steps:
+
+* Copy Data: An FDW extension is used to connect the API database to the upstream (catalog) database. The entire contents of the upstream media table are copied into a new temp table in the API database. This temp table will later replace the main media table in the API.
+* Create Index: Create a new Elasticsearch index, matching the configuration of the existing media index.
+* Distributed Reindex: Convert each record from the new temp table to the format required by an Elasticsearch document, and then reindex them into the newly created index.
+* Create and Populate Filtered Index: Create a new Elasticsearch index matching the configuration of the existing filtered index, and then reindex documents into it from the new media index, applying appropriate filtering for sensitive terms.
+* Reapply Constraints: Recreate indices and constraints from the original API tables on the new temp tables.
+* Promote Table: Drop the old media table in the API and rename the temp table and its indices, which has the effect of promoting them/replacing the old table.
+* Promote Index: Promote the new Elasticsearch index by unlinking the given alias from the existing index and moving it to the new one. (Used for both the main and filtered indices.)
+* Delete Index: Delete the old Elasticsearch index. (Used for both the main and filtered indices.)
+
+Importantly, the data refresh DAGs are also configured to handle concurrency
+requirements of the reindexing steps.
+
+You can find more background information on this process in the following
+issues and related PRs:
+
+- [[Implementation Plan] Ingestion Server Removal](
+https://docs.openverse.org/projects/proposals/ingestion_server_removal/20240328-implementation_plan_ingestion_server_removal.html)
+- [[Feature] Merge popularity calculations and data refresh into a single DAG](
+https://github.com/WordPress/openverse-catalog/issues/453)
+"""
+
+import logging
+import os
+from collections.abc import Sequence
+from itertools import product
+
+from airflow import DAG
+from airflow.decorators import task_group
+from airflow.operators.python import PythonOperator
+from airflow.utils.trigger_rule import TriggerRule
+
+from common import cloudwatch
+from common import elasticsearch as es
+from common.constants import DAG_DEFAULT_ARGS, ENVIRONMENTS, Environment
+from common.sensors.constants import ES_CONCURRENCY_TAGS
+from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor
+from common.sensors.utils import wait_for_external_dags_with_tag
+from data_refresh.copy_data import copy_upstream_tables
+from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshConfig
+from data_refresh.reporting import report_record_difference
+
+
+logger = logging.getLogger(__name__)
+
+
+DATA_REFRESH_POOL = os.getenv("DATA_REFRESH_POOL", "data_refresh")
+
+
+@task_group(group_id="wait_for_conflicting_dags")
+def wait_for_conflicting_dags(
+ data_refresh_config: DataRefreshConfig,
+ external_dag_ids: list[str],
+ concurrency_tag: str,
+):
+ # Wait to ensure that no other Data Refresh DAGs are running.
+ SingleRunExternalDAGsSensor(
+ task_id="wait_for_data_refresh",
+ external_dag_ids=external_dag_ids,
+ check_existence=True,
+ poke_interval=data_refresh_config.data_refresh_poke_interval,
+ mode="reschedule",
+ pool=DATA_REFRESH_POOL,
+ )
+
+ # Wait for other DAGs that operate on this ES cluster. If a new or filtered index
+ # is being created by one of these DAGs, we need to wait for it to finish or else
+ # the data refresh might destroy the index being used as the source index.
+ # Realistically the data refresh is too slow to beat the index creation process,
+ # even if it was triggered immediately after one of these DAGs; however, it is
+ # always safer to avoid the possibility of the race condition altogether.
+ wait_for_external_dags_with_tag.override(group_id="wait_for_es_dags")(
+ tag=concurrency_tag,
+ # Exclude the other data refresh DAG ids for this environment, as waiting on these
+ # was handled in the previous task.
+ excluded_dag_ids=external_dag_ids,
+ )
+
+
+def create_data_refresh_dag(
+ data_refresh_config: DataRefreshConfig,
+ environment: Environment,
+ external_dag_ids: Sequence[str],
+):
+ """
+ Instantiate a DAG for a data refresh.
+
+ This DAG will run the data refresh for the given `media_type`.
+
+ Required Arguments:
+
+ data_refresh: dataclass containing configuration information for the
+ DAG
+ environment: the environment in which the data refresh is performed
+ external_dag_ids: list of ids of the other data refresh DAGs. The data refresh step
+ of this DAG will not run concurrently with the corresponding step
+ of any dependent DAG.
+ """
+ default_args = {
+ **DAG_DEFAULT_ARGS,
+ **data_refresh_config.default_args,
+ }
+
+ concurrency_tag = ES_CONCURRENCY_TAGS.get(environment)
+
+ dag = DAG(
+ dag_id=f"{environment}_{data_refresh_config.dag_id}",
+ dagrun_timeout=data_refresh_config.dag_timeout,
+ default_args=default_args,
+ start_date=data_refresh_config.start_date,
+ schedule=data_refresh_config.schedule,
+ max_active_runs=1,
+ catchup=False,
+ doc_md=__doc__,
+ tags=[
+ "data_refresh",
+ f"{environment}_data_refresh",
+ concurrency_tag,
+ ],
+ )
+
+ with dag:
+ # Connect to the appropriate Elasticsearch cluster
+ es_host = es.get_es_host(environment=environment)
+
+ # Get the current number of records in the target API table
+ before_record_count = es.get_record_count_group_by_sources.override(
+ task_id="get_before_record_count"
+ )(
+ es_host=es_host,
+ index=data_refresh_config.media_type,
+ )
+
+ wait_for_dags = wait_for_conflicting_dags(
+ data_refresh_config, external_dag_ids, concurrency_tag
+ )
+
+ copy_data = copy_upstream_tables(
+ environment=environment, data_refresh_config=data_refresh_config
+ )
+
+ # TODO Cleaning steps
+
+ # Disable Cloudwatch alarms that are noisy during the reindexing steps of a
+ # data refresh.
+ disable_alarms = PythonOperator(
+ task_id="disable_sensitive_cloudwatch_alarms",
+ python_callable=cloudwatch.enable_or_disable_alarms,
+ op_kwargs={
+ "enable": False,
+ },
+ )
+
+ # TODO create_and_populate_index
+ # (TaskGroup that creates index, triggers and waits for reindexing)
+
+ # TODO create_and_populate_filtered_index
+
+ # Re-enable Cloudwatch alarms once reindexing is complete, even if it
+ # failed.
+ enable_alarms = PythonOperator(
+ task_id="enable_sensitive_cloudwatch_alarms",
+ python_callable=cloudwatch.enable_or_disable_alarms,
+ op_kwargs={
+ "enable": True,
+ },
+ trigger_rule=TriggerRule.ALL_DONE,
+ )
+
+ # TODO Promote
+ # (TaskGroup that reapplies constraints, promotes new tables and indices,
+ # deletes old ones)
+
+ # Get the final number of records in the API table after the refresh
+ after_record_count = es.get_record_count_group_by_sources.override(
+ task_id="get_after_record_count", trigger_rule=TriggerRule.NONE_FAILED
+ )(
+ es_host=es_host,
+ index=data_refresh_config.media_type,
+ )
+
+ # Report the count difference to Slack
+ report_counts = PythonOperator(
+ task_id="report_record_counts",
+ python_callable=report_record_difference,
+ op_kwargs={
+ "before": before_record_count,
+ "after": after_record_count,
+ "media_type": data_refresh_config.media_type,
+ "dag_id": data_refresh_config.dag_id,
+ },
+ )
+
+ # Set up task dependencies
+ before_record_count >> wait_for_dags >> copy_data >> disable_alarms
+ # TODO: this will include reindex/etc once added
+ disable_alarms >> [enable_alarms, after_record_count]
+ after_record_count >> report_counts
+
+ return dag
+
+
+# Generate data refresh DAGs for each DATA_REFRESH_CONFIG, per environment.
+all_data_refresh_dag_ids = {refresh.dag_id for refresh in DATA_REFRESH_CONFIGS.values()}
+
+for data_refresh_config, environment in product(
+ DATA_REFRESH_CONFIGS.values(), ENVIRONMENTS
+):
+ # Construct a set of all data refresh DAG ids other than the current DAG
+ other_dag_ids = all_data_refresh_dag_ids - {data_refresh_config.dag_id}
+
+ globals()[data_refresh_config.dag_id] = create_data_refresh_dag(
+ data_refresh_config,
+ environment,
+ [f"{environment}_{dag_id}" for dag_id in other_dag_ids],
+ )
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
new file mode 100644
index 000000000..94523c18e
--- /dev/null
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -0,0 +1,127 @@
+"""
+# Data Refresh DAG Configuration
+This file defines the type for the `DataRefresh`, a dataclass containing
+configuration for a Data Refresh DAG, and defines the actual `DATA_REFRESH_CONFIGS`.
+This configuration information is used to generate the dynamic Data Refresh dags.
+"""
+
+import os
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+
+from common.constants import AUDIO, IMAGE, REFRESH_POKE_INTERVAL
+from data_refresh import queries
+
+
+@dataclass
+class TableMapping:
+ """
+ Configuration object describing how a particular table in the upstream (catalog)
+ database should be mapped to its downstream (API) counterpart.
+
+ Required Constructor Arguments:
+
+ upstream_table_name: Name of the table in the upstream (catalog) database.
+ downstream_table_name: Name of the table in the downstream (API) database.
+ tertiary_column_query: Query for setting up tertiary columns in the temporary
+ table.
+ copy_data_query: Query to use when copying data from the upstream table
+ into the downstream table.
+ """
+
+ upstream_table_name: str
+ downstream_table_name: str
+ tertiary_column_query: str = queries.METRIC_COLUMN_SETUP_QUERY
+ copy_data_query: str = queries.ADVANCED_COPY_DATA_QUERY
+ temp_table_name: str = field(init=False)
+ deleted_table_name: str = field(init=False)
+
+ def __post_init__(self):
+ self.temp_table_name = f"temp_import_{self.downstream_table_name}"
+ self.deleted_table_name = f"api_deleted{self.downstream_table_name}"
+
+
+@dataclass
+class DataRefreshConfig:
+ """
+ Configuration object for a data refresh DAG.
+
+ Required Constructor Arguments:
+
+ media_type: str describing the media type to be refreshed.
+ table_mappings: list of TableMapping information for all tables that should be
+ refreshed as part of a data refresh for this media type.
+
+ Optional Constructor Arguments:
+
+ default_args: dictionary which is passed to the
+ airflow.dag.DAG __init__ method.
+ start_date: datetime.datetime giving the
+ first valid logical date of the DAG.
+ schedule: string giving the schedule on which the DAG
+ should be run. Passed to the
+ airflow.dag.DAG __init__ method.
+ dag_timeout: timedelta expressing the amount of time the entire
+ data refresh may take.
+ copy_data_timeout: timedelta expressing the amount of time it may take to
+ copy the upstream table into the downstream DB
+ index_readiness_timeout: timedelta expressing amount of time it may take
+ to await a healthy ES index after reindexing
+ data_refresh_poke_interval: int number of seconds to wait between
+ checks to see if conflicting DAGs are running.
+ doc_md: str used for the DAG's documentation markdown
+ """
+
+ dag_id: str = field(init=False)
+ filtered_index_dag_id: str = field(init=False)
+ media_type: str
+ table_mappings: list[TableMapping]
+ start_date: datetime = datetime(2020, 1, 1)
+ schedule: str | None = "0 0 * * 1" # Mondays 00:00 UTC
+ default_args: dict = field(default_factory=dict)
+ dag_timeout: timedelta = timedelta(days=1)
+ copy_data_timeout: timedelta = timedelta(hours=1)
+ index_readiness_timeout: timedelta = timedelta(days=1)
+ data_refresh_poke_interval: int = REFRESH_POKE_INTERVAL
+
+ def __post_init__(self):
+ self.dag_id = f"{self.media_type}_data_refresh"
+ self.filtered_index_dag_id = f"create_filtered_{self.media_type}_index"
+
+
+DATA_REFRESH_CONFIGS = {
+ IMAGE: DataRefreshConfig(
+ media_type=IMAGE,
+ table_mappings=[
+ TableMapping(
+ upstream_table_name=IMAGE,
+ downstream_table_name=IMAGE,
+ tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,
+ )
+ ],
+ dag_timeout=timedelta(days=4),
+ copy_data_timeout=timedelta(hours=12),
+ data_refresh_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),
+ ),
+ AUDIO: DataRefreshConfig(
+ media_type=AUDIO,
+ table_mappings=[
+ TableMapping(
+ upstream_table_name=AUDIO,
+ downstream_table_name=AUDIO,
+ tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,
+ ),
+ TableMapping(
+ upstream_table_name="audioset_view",
+ downstream_table_name="audioset",
+ # Do not set up standardized popularity column for audioset_view
+ tertiary_column_query=queries.TIMESTAMP_COLUMN_SETUP_QUERY,
+ # Do not check for entries in the DeletedMedia table for audioset_view
+ copy_data_query=queries.BASIC_COPY_DATA_QUERY,
+ ),
+ ],
+ data_refresh_poke_interval=int(
+ os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30)
+ ),
+ ),
+}
diff --git a/catalog/dags/data_refresh/queries.py b/catalog/dags/data_refresh/queries.py
new file mode 100644
index 000000000..6a53fe674
--- /dev/null
+++ b/catalog/dags/data_refresh/queries.py
@@ -0,0 +1,82 @@
+from textwrap import dedent
+
+
+CREATE_FDW_EXTENSION_QUERY = "CREATE EXTENSION IF NOT EXISTS postgres_fdw"
+
+CREATE_FDW_QUERY = dedent(
+ """
+ DROP SERVER IF EXISTS upstream CASCADE;
+ CREATE SERVER upstream FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (host '{host}', dbname '{dbname}', port '{port}');
+
+ CREATE USER MAPPING IF NOT EXISTS FOR deploy SERVER upstream
+ OPTIONS (user '{user}', password '{password}');
+ """
+)
+
+CREATE_SCHEMA_QUERY = dedent(
+ """
+ DROP SCHEMA IF EXISTS {schema_name} CASCADE;
+ CREATE SCHEMA {schema_name} AUTHORIZATION deploy;
+
+ IMPORT FOREIGN SCHEMA public LIMIT TO ({upstream_table_name})
+ FROM SERVER upstream INTO {schema_name};
+ """
+)
+
+CREATE_TEMP_TABLE_QUERY = dedent(
+ """
+ DROP TABLE IF EXISTS {temp_table_name};
+ CREATE TABLE {temp_table_name} (LIKE {downstream_table_name} INCLUDING DEFAULTS
+ INCLUDING CONSTRAINTS);
+ """
+)
+
+ID_COLUMN_SETUP_QUERY = dedent(
+ """
+ ALTER TABLE {temp_table_name} ADD COLUMN IF NOT EXISTS
+ id serial;
+ CREATE SEQUENCE IF NOT EXISTS id_{temp_table_name}_seq;
+ ALTER TABLE {temp_table_name} ALTER COLUMN
+ id SET DEFAULT nextval('id_{temp_table_name}_seq'::regclass);
+ """
+)
+
+TIMESTAMP_COLUMN_SETUP_QUERY = dedent(
+ """
+ ALTER TABLE {temp_table_name} ALTER COLUMN
+ created_on SET DEFAULT CURRENT_TIMESTAMP;
+ ALTER TABLE {temp_table_name} ALTER COLUMN
+ updated_on SET DEFAULT CURRENT_TIMESTAMP;
+ """
+)
+
+METRIC_COLUMN_SETUP_QUERY = dedent(
+ """
+ ALTER TABLE {temp_table_name} ADD COLUMN IF NOT EXISTS
+ standardized_popularity double precision;
+ ALTER TABLE {temp_table_name} ALTER COLUMN
+ view_count SET DEFAULT 0;
+ """
+)
+
+BASIC_COPY_DATA_QUERY = dedent(
+ """
+ INSERT INTO {temp_table_name} ({columns})
+ SELECT {columns} FROM {schema_name}.{upstream_table_name}
+ """
+)
+
+ADVANCED_COPY_DATA_QUERY = dedent(
+ """
+ INSERT INTO {temp_table_name} ({columns})
+ SELECT {columns} from {schema_name}.{upstream_table_name} AS u
+ WHERE NOT EXISTS(
+ SELECT FROM {deleted_table_name} WHERE identifier = u.identifier
+ )
+ """
+)
+
+ADD_PRIMARY_KEY_QUERY = "ALTER TABLE {temp_table_name} ADD PRIMARY KEY (id);"
+
+DROP_SERVER_QUERY = "DROP SERVER upstream CASCADE;"
diff --git a/catalog/dags/data_refresh/reporting.py b/catalog/dags/data_refresh/reporting.py
new file mode 100644
index 000000000..a9e46c81e
--- /dev/null
+++ b/catalog/dags/data_refresh/reporting.py
@@ -0,0 +1,51 @@
+import logging
+from textwrap import dedent
+
+from common import slack
+
+
+log = logging.getLogger(__name__)
+
+
+def report_status(media_type: str, message: str, dag_id: str):
+ message = f"`{media_type}`: {message}"
+ slack.send_message(
+ text=message,
+ dag_id=dag_id,
+ username=f"{dag_id.replace('_', ' ').title()} Notification",
+ icon_emoji="arrows_counterclockwise",
+ )
+ return message
+
+
+def report_record_difference(before: dict, after: dict, media_type: str, dag_id: str):
+ all_keys = before.keys() | after.keys()
+ total_before = sum(before.values())
+ total_after = sum(after.values())
+ count_diff = total_after - total_before
+ if total_before > 0:
+ percent_diff = (count_diff / total_before) * 100
+ else:
+ percent_diff = float("inf")
+ breakdown_diff = {k: after.get(k, 0) - before.get(k, 0) for k in all_keys}
+ if breakdown_diff:
+ breakdown_message = "\n".join(
+ f"`{k}`:{v:+,}" for k, v in breakdown_diff.items()
+ )
+ else:
+ breakdown_message = "Both indices missing? No breakdown to show"
+
+ message = dedent(
+ f"""
+ Data refresh for {media_type} complete! :tada:
+ _Note: All values are retrieved from elasticsearch_
+ *Record count difference for `{media_type}`*: {total_before:,} → {total_after:,}
+ *Change*: {count_diff:+,} ({percent_diff:+}% Δ)
+ *Breakdown of changes*:
+ """
+ )
+ message += breakdown_message
+ slack.send_message(
+ text=message, dag_id=dag_id, username="Data refresh record difference"
+ )
+ return message
diff --git a/catalog/dags/legacy_data_refresh/data_refresh_types.py b/catalog/dags/legacy_data_refresh/data_refresh_types.py
index 27d2cc0ca..3a5238a0b 100644
--- a/catalog/dags/legacy_data_refresh/data_refresh_types.py
+++ b/catalog/dags/legacy_data_refresh/data_refresh_types.py
@@ -58,7 +58,7 @@ class DataRefresh:
media_type: str
start_date: datetime = datetime(2020, 1, 1)
schedule: str | None = "0 0 * * 1" # Mondays 00:00 UTC
- default_args: dict | None = field(default_factory=dict)
+ default_args: dict = field(default_factory=dict)
data_refresh_timeout: timedelta = timedelta(days=1)
refresh_metrics_timeout: timedelta = timedelta(hours=1)
refresh_matview_timeout: timedelta = timedelta(hours=1)
diff --git a/catalog/tests/dags/data_refresh/test_copy_data.py b/catalog/tests/dags/data_refresh/test_copy_data.py
new file mode 100644
index 000000000..890ca903e
--- /dev/null
+++ b/catalog/tests/dags/data_refresh/test_copy_data.py
@@ -0,0 +1,47 @@
+import logging
+from unittest import mock
+
+import pytest
+
+from common.constants import PRODUCTION
+from data_refresh.copy_data import DEFAULT_DATA_REFRESH_LIMIT, get_record_limit
+
+
+logger = logging.getLogger(__name__)
+
+
[email protected]("configured_limit", [None, 0, 10, 10_000])
+def test_get_record_limit_always_respects_configured_limit(configured_limit):
+ with mock.patch("data_refresh.copy_data.Variable") as MockVariable:
+ # Mock the calls to Variable.get, in order
+ MockVariable.get.side_effect = [
+ configured_limit,
+ # Mock is not called a second time to get the environment,
+ # because configured_limit is returned immediately
+ ]
+
+ actual_limit = get_record_limit.function()
+ assert actual_limit == configured_limit
+
+
+ "environment, expected_limit",
+ [
+ (PRODUCTION, None),
+ ("local", DEFAULT_DATA_REFRESH_LIMIT),
+ ("foo", DEFAULT_DATA_REFRESH_LIMIT),
+ ],
+)
+def test_get_record_limit_defaults_accoring_to_environment(environment, expected_limit):
+ with mock.patch("data_refresh.copy_data.Variable") as MockVariable:
+ # Mock the calls to Variable.get, in order
+ MockVariable.get.side_effect = [
+ # Raise KeyError when trying to get the configured limit,
+ # simulating the variable not being defined
+ KeyError,
+ # Return the environment on the second call
+ environment,
+ ]
+
+ actual_limit = get_record_limit.function()
+ assert actual_limit == expected_limit
diff --git a/documentation/catalog/reference/DAGs.md b/documentation/catalog/reference/DAGs.md
index f91f763b1..f4c841d1d 100644
--- a/documentation/catalog/reference/DAGs.md
+++ b/documentation/catalog/reference/DAGs.md
@@ -32,12 +32,16 @@ The following are DAGs grouped by their primary tag:
### Data Refresh
-| DAG ID | Schedule Interval |
-| ------------------------------------------------------------------ | ----------------- |
-| [`create_filtered_audio_index`](#create_filtered_media_type_index) | `None` |
-| [`create_filtered_image_index`](#create_filtered_media_type_index) | `None` |
-| [`audio_data_refresh`](#media_type_data_refresh) | `0 0 * * 1` |
-| [`image_data_refresh`](#media_type_data_refresh) | `0 0 * * 1` |
+| DAG ID | Schedule Interval |
+| ----------------------------------------------------------------------- | ----------------- |
+| [`create_filtered_audio_index`](#create_filtered_media_type_index) | `None` |
+| [`create_filtered_image_index`](#create_filtered_media_type_index) | `None` |
+| [`production_audio_data_refresh`](#environment_media_type_data_refresh) | `0 0 * * 1` |
+| [`production_image_data_refresh`](#environment_media_type_data_refresh) | `0 0 * * 1` |
+| [`staging_audio_data_refresh`](#environment_media_type_data_refresh) | `0 0 * * 1` |
+| [`staging_image_data_refresh`](#environment_media_type_data_refresh) | `0 0 * * 1` |
+| [`audio_data_refresh`](#media_type_data_refresh) | `0 0 * * 1` |
+| [`image_data_refresh`](#media_type_data_refresh) | `0 0 * * 1` |
### Database
@@ -175,6 +179,10 @@ The following is documentation associated with each DAG (where available):
1. [`wordpress_workflow`](#wordpress_workflow)
1. [`production_elasticsearch_cluster_healthcheck`](#environment_elasticsearch_cluster_healthcheck)
1. [`staging_elasticsearch_cluster_healthcheck`](#environment_elasticsearch_cluster_healthcheck)
+1. [`production_audio_data_refresh`](#environment_media_type_data_refresh)
+1. [`production_image_data_refresh`](#environment_media_type_data_refresh)
+1. [`staging_audio_data_refresh`](#environment_media_type_data_refresh)
+1. [`staging_image_data_refresh`](#environment_media_type_data_refresh)
1. [`audio_data_refresh`](#media_type_data_refresh)
1. [`image_data_refresh`](#media_type_data_refresh)
1. [`audio_popularity_refresh`](#media_type_popularity_refresh)
@@ -1208,6 +1216,51 @@ during data refresh or other similar operations.
----
+### `{environment}_{media_type}_data_refresh`
+
+#### Data Refresh DAG Factory
+
+This file generates our data refresh DAGs for each media type and environment
+using a factory function. The data refresh is a process which makes new content
+added to the Catalog by our provider DAGs available to the API.
+
+The data refresh has the following high level steps:
+
+- Copy Data: An FDW extension is used to connect the API database to the
+ upstream (catalog) database. The entire contents of the upstream media table
+ are copied into a new temp table in the API database. This temp table will
+ later replace the main media table in the API.
+- Create Index: Create a new Elasticsearch index, matching the configuration of
+ the existing media index.
+- Distributed Reindex: Convert each record from the new temp table to the format
+ required by an Elasticsearch document, and then reindex them into the newly
+ created index.
+- Create and Populate Filtered Index: Create a new Elasticsearch index matching
+ the configuration of the existing filtered index, and then reindex documents
+ into it from the new media index, applying appropriate filtering for sensitive
+ terms.
+- Reapply Constraints: Recreate indices and constraints from the original API
+ tables on the new temp tables.
+- Promote Table: Drop the old media table in the API and rename the temp table
+ and its indices, which has the effect of promoting them/replacing the old
+ table.
+- Promote Index: Promote the new Elasticsearch index by unlinking the given
+ alias from the existing index and moving it to the new one. (Used for both the
+ main and filtered indices.)
+- Delete Index: Delete the old Elasticsearch index. (Used for both the main and
+ filtered indices.)
+
+Importantly, the data refresh DAGs are also configured to handle concurrency
+requirements of the reindexing steps.
+
+You can find more background information on this process in the following issues
+and related PRs:
+
+- [[Implementation Plan] Ingestion Server Removal](https://docs.openverse.org/projects/proposals/ingestion_server_removal/20240328-implementation_plan_ingestion_server_removal.html)
+- [[Feature] Merge popularity calculations and data refresh into a single DAG](https://github.com/WordPress/openverse-catalog/issues/453)
+
+----
+
### `{media_type}_data_refresh`
#### Data Refresh DAG Factory