diff --git a/backend/src/baserow/api/jobs/serializers.py b/backend/src/baserow/api/jobs/serializers.py index 76d767c125..61ec6651f8 100644 --- a/backend/src/baserow/api/jobs/serializers.py +++ b/backend/src/baserow/api/jobs/serializers.py @@ -3,7 +3,7 @@ from django.utils.functional import lazy from drf_spectacular.extensions import OpenApiSerializerExtension from drf_spectacular.plumbing import force_instance from drf_spectacular.types import OpenApiTypes -from drf_spectacular.utils import extend_schema_field +from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field from rest_framework import serializers from baserow.core.jobs.constants import ( @@ -56,6 +56,33 @@ class JobSerializer(serializers.ModelSerializer): return job_type_registry.get_by_model(instance.specific_class).type +def get_job_response_serializer_mapping(): + """ + Builds the response serializer mapping lazily because job types are registered + while Django applications are being initialized. + """ + + return { + job_type.type: job_type.response_serializer_class + for job_type in job_type_registry.registry.values() + } + + +class ListJobsResponseSerializer(serializers.Serializer): + jobs = PolymorphicProxySerializer( + component_name="PolymorphicJobResponse", + serializers=get_job_response_serializer_mapping, + resource_type_field_name="type", + many=True, + ) + count = serializers.IntegerField( + allow_null=True, + help_text=( + "The number of matching jobs, or null when polling explicit job IDs." + ), + ) + + class CreateJobSerializer(serializers.Serializer): type = serializers.ChoiceField( choices=lazy(job_type_registry.get_types, list)(), diff --git a/backend/src/baserow/api/jobs/views.py b/backend/src/baserow/api/jobs/views.py index eaa0993303..aeea8d08d5 100644 --- a/backend/src/baserow/api/jobs/views.py +++ b/backend/src/baserow/api/jobs/views.py @@ -27,7 +27,12 @@ from .errors import ( ERROR_JOB_NOT_CANCELLABLE, ERROR_MAX_JOB_COUNT_EXCEEDED, ) -from .serializers import CreateJobSerializer, JobSerializer, ListJobQuerySerializer +from .serializers import ( + CreateJobSerializer, + JobSerializer, + ListJobQuerySerializer, + ListJobsResponseSerializer, +) class JobsView(APIView): @@ -44,11 +49,7 @@ class JobsView(APIView): "selected via the `type` parameter. Each job type may support additional " "type-specific filter parameters." ), - responses={ - 200: DiscriminatorCustomFieldsMappingSerializer( - job_type_registry, JobSerializer, many=True - ) - }, + responses={200: ListJobsResponseSerializer}, ) @validate_query_parameters(ListJobQuerySerializer, return_validated=True) def get(self, request, query_params): @@ -66,13 +67,20 @@ class JobsView(APIView): job_type = job_type_registry.get(job_type_name) base_model = job_type.model_class - jobs = JobHandler.get_jobs_for_user( + queryset = JobHandler.get_jobs_for_user( request.user, filter_states=states, filter_ids=job_ids, base_model=base_model, type_filters=type_filters if type_filters else None, - )[offset : offset + limit] + ) + # No count on the job_ids polling path to keep the hot path cheap. + count = None if job_ids else queryset.count() + jobs = queryset[offset : offset + limit] + + def enhance_specific_queryset(model, queryset): + job_type = job_type_registry.get_by_model(model) + return job_type.enhance_queryset(queryset) serialized_jobs = [ job_type_registry.get_serializer( @@ -80,9 +88,12 @@ class JobsView(APIView): JobSerializer, context={"request": request}, ).data - for job in specific_iterator(jobs) + for job in specific_iterator( + jobs, + per_content_type_queryset_hook=enhance_specific_queryset, + ) ] - return Response({"jobs": serialized_jobs}) + return Response({"jobs": serialized_jobs, "count": count}) @extend_schema( tags=["Jobs"], diff --git a/backend/src/baserow/contrib/database/api/data_sync/serializers.py b/backend/src/baserow/contrib/database/api/data_sync/serializers.py index 60f5be2137..911bd53a02 100644 --- a/backend/src/baserow/contrib/database/api/data_sync/serializers.py +++ b/backend/src/baserow/contrib/database/api/data_sync/serializers.py @@ -100,3 +100,15 @@ class ListDataSyncPropertySerializer(serializers.Serializer): def get_field_type(self, instance): field_type = field_type_registry.get_by_model(instance.to_baserow_field()) return field_type.type + + +class SyncDataSyncTableJobFiltersSerializer(serializers.Serializer): + """ + Adds the ability to filter SyncDataSyncTableJob by data sync ID. + """ + + sync_data_sync_table_data_sync_id = serializers.IntegerField( + min_value=1, + required=False, + help_text="Filter by the data sync ID.", + ) diff --git a/backend/src/baserow/contrib/database/apps.py b/backend/src/baserow/contrib/database/apps.py index 88dcfb4c4f..b95ec8c238 100755 --- a/backend/src/baserow/contrib/database/apps.py +++ b/backend/src/baserow/contrib/database/apps.py @@ -804,6 +804,7 @@ class DatabaseConfig(AppConfig): from .airtable.operations import RunAirtableImportJobOperationType from .data_sync.operations import ( GetIncludingPublicValuesOperationType, + ListDataSyncJobsOperationType, ListPropertiesOperationType, SyncTableOperationType, ) @@ -1025,6 +1026,7 @@ class DatabaseConfig(AppConfig): operation_type_registry.register(DeleteViewFilterGroupOperationType()) operation_type_registry.register(ReadViewFilterGroupOperationType()) operation_type_registry.register(SyncTableOperationType()) + operation_type_registry.register(ListDataSyncJobsOperationType()) operation_type_registry.register(ListPropertiesOperationType()) operation_type_registry.register(GetIncludingPublicValuesOperationType()) diff --git a/backend/src/baserow/contrib/database/data_sync/job_types.py b/backend/src/baserow/contrib/database/data_sync/job_types.py index 069eaa6591..7a868ef265 100644 --- a/backend/src/baserow/contrib/database/data_sync/job_types.py +++ b/backend/src/baserow/contrib/database/data_sync/job_types.py @@ -1,4 +1,11 @@ +from collections import defaultdict +from datetime import timedelta + +from django.conf import settings +from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError +from django.db.models import Q +from django.utils import timezone from loguru import logger from rest_framework import serializers @@ -19,6 +26,8 @@ from baserow.contrib.database.db.atomic import ( read_repeatable_read_single_table_transaction, ) from baserow.contrib.database.table.handler import TableHandler +from baserow.contrib.database.table.models import Table +from baserow.contrib.database.table.signals import table_updated from baserow.core.action.registries import action_type_registry from baserow.core.db import transaction_atomic from baserow.core.exceptions import UserNotInWorkspace @@ -29,10 +38,17 @@ from baserow.core.jobs.registries import JobType from .actions import SyncDataSyncTableActionType from .handler import DataSyncHandler -from .models import SyncDataSyncTableJob -from .operations import SyncTableOperationType +from .models import ( + DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + DataSync, + SyncDataSyncTableJob, +) +from .operations import ListDataSyncJobsOperationType, SyncTableOperationType from .registries import data_sync_type_registry +MAX_FOREIGN_DATA_SYNCS_TO_SCOPE = 50 + def validation_error_to_human_readable_string(e): return "\n".join(e.messages) @@ -59,29 +75,143 @@ class SyncDataSyncTableJobType(JobType): help_text="The ID of data sync to sync.", ), } - serializer_field_names = ["data_sync"] + serializer_field_names = ["data_sync", "triggered_by", "user_name"] serializer_field_overrides = { "data_sync": DataSyncSerializer(read_only=True), + "triggered_by": serializers.CharField( + read_only=True, + help_text="Whether this sync run was started manually or periodically.", + ), + "user_name": serializers.CharField( + source="user.first_name", + read_only=True, + help_text="The name of the user that started this sync run.", + ), } + def get_filters_serializer(self): + from baserow.contrib.database.api.data_sync.serializers import ( + SyncDataSyncTableJobFiltersSerializer, + ) + + return SyncDataSyncTableJobFiltersSerializer + + def enhance_queryset(self, queryset: JobQuerySet) -> JobQuerySet: + return queryset.select_related("user", "data_sync__table").prefetch_related( + "data_sync__synced_properties" + ) + + def scope_queryset_to_user( + self, user: AbstractUser, queryset: JobQuerySet + ) -> JobQuerySet: + """ + On top of their own jobs, users can see the sync runs started by other + users (including periodic ones) for every data sync they have the + ``ListDataSyncJobsOperationType`` permission on. Falls back to + owner-only scoping when the queryset spans too many data syncs, so an + unfiltered listing can't trigger unbounded permission checks. + """ + + foreign_data_syncs = list( + DataSync.objects.filter( + id__in=queryset.exclude(user=user) + .exclude(data_sync_id=None) + .values("data_sync_id") + ).select_related("table__database__workspace")[ + : MAX_FOREIGN_DATA_SYNCS_TO_SCOPE + 1 + ] + ) + if len(foreign_data_syncs) > MAX_FOREIGN_DATA_SYNCS_TO_SCOPE: + return queryset.filter(user=user) + + data_syncs_by_workspace = defaultdict(list) + for data_sync in foreign_data_syncs: + data_syncs_by_workspace[data_sync.table.database.workspace].append( + data_sync + ) + + allowed_data_sync_ids = [] + for workspace, data_syncs in data_syncs_by_workspace.items(): + allowed_table_ids = set( + CoreHandler() + .filter_queryset( + user, + ListDataSyncJobsOperationType.type, + Table.objects.filter( + id__in=[data_sync.table_id for data_sync in data_syncs] + ), + workspace=workspace, + ) + .values_list("id", flat=True) + ) + allowed_data_sync_ids += [ + data_sync.id + for data_sync in data_syncs + if data_sync.table_id in allowed_table_ids + ] + + return queryset.filter(Q(user=user) | Q(data_sync_id__in=allowed_data_sync_ids)) + + def _get_running_jobs(self, job: SyncDataSyncTableJob) -> JobQuerySet: + # Server-driven periodic runs must not consume the user's manual cap. + return ( + super() + ._get_running_jobs(job) + .exclude(triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC) + ) + def _can_schedule_or_raise( self, running_jobs: JobQuerySet, new_job: SyncDataSyncTableJob ) -> None: """ - Limits concurrent data syncs to ``max_count`` per user overall, and at - most one running job per individual data sync. + Limits concurrent manual data syncs to ``max_count`` per user overall, + and at most one pending or running job per individual data sync, no + matter who or what triggered it. Periodic runs are exempt from the + per-user cap because their schedule is server-driven. Jobs that haven't + been updated within the soft time limit are considered stale leftovers + of crashed workers and don't block new syncs. :raises MaxJobCountExceeded: If a conflicting job is already running. """ - super()._can_schedule_or_raise(running_jobs, new_job) + if new_job.triggered_by != DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC: + super()._can_schedule_or_raise(running_jobs, new_job) if new_job.data_sync_id is not None: - for running_job in running_jobs: - if running_job.data_sync_id == new_job.data_sync_id: - raise MaxJobCountExceeded( - f"A {self.type} job is already running for this data sync." - ) + stale_cutoff = timezone.now() - timedelta( + seconds=settings.BASEROW_JOB_SOFT_TIME_LIMIT + ) + already_running = ( + SyncDataSyncTableJob.objects.filter( + data_sync_id=new_job.data_sync_id, + updated_on__gte=stale_cutoff, + ) + .is_pending_or_running() + .exists() + ) + if already_running: + raise MaxJobCountExceeded( + f"A {self.type} job is already running for this data sync." + ) + + def on_error(self, job: SyncDataSyncTableJob, error: Exception) -> None: + """ + Persists the sync error on the data sync and notifies clients. This must + happen here because the failed sync's transaction, including the + ``last_error`` write done inside it, has been rolled back. + """ + + if not isinstance(error, SyncError) or not job.data_sync: + return + + data_sync = job.data_sync + data_sync.last_error = str(error) + data_sync.save(update_fields=("last_error",)) + + if not data_sync.table.trashed: + table_updated.send( + self, table=data_sync.table, user=job.user, force_table_refresh=False + ) def on_cancelled(self, job: SyncDataSyncTableJob) -> None: # Delete table if this is the initial sync job (last_sync is None), to avoid @@ -112,7 +242,13 @@ class SyncDataSyncTableJobType(JobType): workspace=data_sync.table.database.workspace, context=data_sync.table, ) - return {"data_sync": data_sync} + return { + "data_sync": data_sync, + # Not in the request serializer, so API users can't set it. + "triggered_by": values.get( + "triggered_by", DATA_SYNC_JOB_TRIGGERED_BY_MANUAL + ), + } def run(self, job, progress): # Don't do anything if the data sync and/or table has been deleted because then diff --git a/backend/src/baserow/contrib/database/data_sync/models.py b/backend/src/baserow/contrib/database/data_sync/models.py index fd42f0c775..e57f81d713 100644 --- a/backend/src/baserow/contrib/database/data_sync/models.py +++ b/backend/src/baserow/contrib/database/data_sync/models.py @@ -102,6 +102,10 @@ class DataSyncSyncedProperty(models.Model): ) +DATA_SYNC_JOB_TRIGGERED_BY_MANUAL = "manual" +DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC = "periodic" + + class SyncDataSyncTableJob(Job): data_sync = models.ForeignKey( DataSync, @@ -110,6 +114,17 @@ class SyncDataSyncTableJob(Job): on_delete=models.SET_NULL, help_text="The data sync of which the table must be synced.", ) + triggered_by = models.CharField( + max_length=10, + choices=( + (DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, DATA_SYNC_JOB_TRIGGERED_BY_MANUAL), + (DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC), + ), + default=DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + db_default=DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + help_text="Whether this sync run was started manually by a user or by the " + "periodic schedule.", + ) class ICalCalendarDataSync(DataSync): diff --git a/backend/src/baserow/contrib/database/data_sync/operations.py b/backend/src/baserow/contrib/database/data_sync/operations.py index 0bb6f40f36..87b61d36a5 100644 --- a/backend/src/baserow/contrib/database/data_sync/operations.py +++ b/backend/src/baserow/contrib/database/data_sync/operations.py @@ -5,6 +5,10 @@ class SyncTableOperationType(DatabaseTableOperationType): type = "database.data_sync.sync_table" +class ListDataSyncJobsOperationType(DatabaseTableOperationType): + type = "database.data_sync.list_jobs" + + class ListPropertiesOperationType(DatabaseTableOperationType): type = "database.data_sync.list_properties" diff --git a/backend/src/baserow/contrib/database/migrations/0213_syncdatasynctablejob_triggered_by.py b/backend/src/baserow/contrib/database/migrations/0213_syncdatasynctablejob_triggered_by.py new file mode 100644 index 0000000000..ab33071467 --- /dev/null +++ b/backend/src/baserow/contrib/database/migrations/0213_syncdatasynctablejob_triggered_by.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.15 on 2026-07-10 11:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('database', '0212_data_sync_delete_unmatched_rows'), + ] + + operations = [ + migrations.AddField( + model_name='syncdatasynctablejob', + name='triggered_by', + field=models.CharField(choices=[('manual', 'manual'), ('periodic', 'periodic')], db_default='manual', default='manual', help_text='Whether this sync run was started manually by a user or by the periodic schedule.', max_length=10), + ), + ] diff --git a/backend/src/baserow/core/jobs/handler.py b/backend/src/baserow/core/jobs/handler.py index 97eaa47535..96090d7c5c 100644 --- a/backend/src/baserow/core/jobs/handler.py +++ b/backend/src/baserow/core/jobs/handler.py @@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional, Type from django.conf import settings from django.contrib.auth.models import AbstractUser +from django.contrib.contenttypes.models import ContentType from django.db import transaction from django.db.models import Q, QuerySet @@ -125,7 +126,7 @@ class JobHandler: :param base_model: An optional Job model. :param type_filters: Optional type-specific filters (e.g., field_id for GenerateAIValuesJob). - :return: A QuerySet with the filtered jobs for the user. + :return: A QuerySet with the filtered jobs visible to the user. """ if base_model is None: @@ -140,7 +141,7 @@ class JobHandler: states_q |= Q(state=state) return states_q - queryset = base_model.objects.filter(user=user).order_by("-id") + queryset = base_model.objects.all().order_by("-id") if filter_states: queryset = queryset.filter(get_job_states_filter(filter_states)) @@ -151,8 +152,63 @@ class JobHandler: if type_filters: queryset = queryset.filter(**type_filters) + queryset = cls._scope_queryset_to_user(user, queryset, base_model, filter_ids) + return queryset.select_related("content_type") + @classmethod + def _scope_queryset_to_user( + cls, + user: AbstractUser, + queryset: QuerySet, + base_model: Type[AnyJob], + filter_ids: Optional[List[int]], + ) -> QuerySet: + """ + Delegates the user-visibility scoping of a jobs listing queryset to the + job types. When a specific job model is requested its job type scopes + the whole queryset. On the generic model, jobs of other users are only + considered when explicitly requested by id, and each foreign job type + decides whether the user may see them. + + :param user: The user requesting the jobs listing. + :param queryset: The already filtered queryset of jobs. + :param base_model: The job model the queryset is based on. + :param filter_ids: The specific job ids requested, if any. + :return: The queryset restricted to what the user may see. + """ + + if base_model is not Job: + job_type = job_type_registry.get_by_model(base_model) + return job_type.scope_queryset_to_user(user, queryset) + + if not filter_ids: + return queryset.filter(user=user) + + visible_q = Q(user=user) + foreign_content_type_ids = list( + Job.objects.filter(id__in=filter_ids) + .exclude(user=user) + .values_list("content_type_id", flat=True) + .distinct() + ) + content_types_by_id = ContentType.objects.in_bulk(foreign_content_type_ids) + for content_type_id in foreign_content_type_ids: + content_type = content_types_by_id.get(content_type_id) + model_class = content_type.model_class() if content_type else None + if model_class is None: + continue + try: + job_type = job_type_registry.get_by_model(model_class) + except job_type_registry.does_not_exist_exception_class: + continue + scoped = job_type.scope_queryset_to_user( + user, job_type.model_class.objects.filter(id__in=filter_ids) + ) + visible_q |= Q(id__in=scoped.values("id")) + + return queryset.filter(visible_q) + @classmethod def get_pending_or_running_jobs( cls, diff --git a/backend/src/baserow/core/jobs/registries.py b/backend/src/baserow/core/jobs/registries.py index b3aa696033..6f350a2d37 100644 --- a/backend/src/baserow/core/jobs/registries.py +++ b/backend/src/baserow/core/jobs/registries.py @@ -100,6 +100,33 @@ class JobType( "the same time." ) + def scope_queryset_to_user( + self, user: AbstractUser, queryset: JobQuerySet + ) -> JobQuerySet: + """ + Restricts a jobs listing queryset to the jobs that ``user`` may see. By + default jobs are only visible to the user that created them. A job type + can widen this, after an explicit object-level permission check, to also + expose jobs created by other users (e.g. runs of a shared resource). + + :param user: The user requesting the jobs listing. + :param queryset: The already filtered queryset of jobs of this type. + :return: The queryset restricted to what the user may see. + """ + + return queryset.filter(user=user) + + def enhance_queryset(self, queryset: JobQuerySet) -> JobQuerySet: + """ + Adds the relations needed to serialize this job type efficiently. The jobs + listing calls this hook on each concrete job queryset before serialization. + + :param queryset: A queryset for this job type's concrete model. + :return: The queryset with any required relations selected or prefetched. + """ + + return queryset + def transaction_atomic_context(self, job: Job): """ This method gives the possibility to change the transaction context per request. diff --git a/backend/src/baserow/core/jobs/tasks.py b/backend/src/baserow/core/jobs/tasks.py index 4757f10dea..4066ab6652 100644 --- a/backend/src/baserow/core/jobs/tasks.py +++ b/backend/src/baserow/core/jobs/tasks.py @@ -2,6 +2,8 @@ from datetime import timedelta from django.conf import settings +from loguru import logger + from baserow.config.celery import app from baserow.core.jobs.exceptions import JobCancelled from baserow.core.jobs.registries import job_type_registry @@ -74,6 +76,13 @@ def run_async_job(self, job_id: int): job.set_state_failed(str(e), error) job.save() + try: + job_type.on_error(job, e) + except Exception: + logger.exception( + f"The on_error hook of the {job_type.type} job {job.id} failed." + ) + if should_raise: raise finally: diff --git a/backend/tests/baserow/api/jobs/test_jobs_views.py b/backend/tests/baserow/api/jobs/test_jobs_views.py index 3bbdcedc96..238ccec687 100644 --- a/backend/tests/baserow/api/jobs/test_jobs_views.py +++ b/backend/tests/baserow/api/jobs/test_jobs_views.py @@ -157,7 +157,7 @@ def test_list_jobs(data_fixture, api_client): } assert response.status_code == HTTP_200_OK - assert response.json() == {"jobs": [job_2_json, job_1_json]} + assert response.json() == {"jobs": [job_2_json, job_1_json], "count": 2} valid_job_states = ",".join(["pending", "finished"]) response = api_client.get( @@ -166,7 +166,7 @@ def test_list_jobs(data_fixture, api_client): ) assert response.status_code == HTTP_200_OK - assert response.json() == {"jobs": [job_1_json]} + assert response.json() == {"jobs": [job_1_json], "count": 1} response = api_client.get( f"{url}?states=!finished", @@ -174,7 +174,7 @@ def test_list_jobs(data_fixture, api_client): ) assert response.status_code == HTTP_200_OK - assert response.json() == {"jobs": [job_2_json, job_1_json]} + assert response.json() == {"jobs": [job_2_json, job_1_json], "count": 2} response = api_client.get( f"{url}?states=importing", @@ -203,7 +203,8 @@ def test_list_jobs(data_fixture, api_client): ) assert response.status_code == HTTP_200_OK - assert response.json() == {"jobs": [job_2_json]} + # No count on the job_ids polling path to keep it cheap. + assert response.json() == {"jobs": [job_2_json], "count": None} response = api_client.get( f"{url}?job_ids=invalid_job_id", diff --git a/backend/tests/baserow/contrib/database/api/data_sync/test_data_sync_job_listing.py b/backend/tests/baserow/contrib/database/api/data_sync/test_data_sync_job_listing.py new file mode 100644 index 0000000000..0b7d8212b4 --- /dev/null +++ b/backend/tests/baserow/contrib/database/api/data_sync/test_data_sync_job_listing.py @@ -0,0 +1,191 @@ +from django.contrib.contenttypes.models import ContentType +from django.db import connection +from django.shortcuts import reverse +from django.test.utils import CaptureQueriesContext, override_settings + +import pytest +from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST + +from baserow.contrib.database.data_sync.models import ( + DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + SyncDataSyncTableJob, +) +from baserow.core.jobs.constants import JOB_FINISHED + + +def create_data_sync_with_two_members(data_fixture): + owner, token = data_fixture.create_user_and_token(first_name="Owner") + workspace = data_fixture.create_workspace(user=owner) + member = data_fixture.create_user(workspace=workspace, first_name="Member") + database = data_fixture.create_database_application(workspace=workspace) + table = data_fixture.create_database_table(database=database) + data_sync = data_fixture.create_ical_data_sync( + table=table, ical_url="https://baserow.io/ical.ics" + ) + return owner, token, member, data_sync + + +@pytest.mark.django_db +def test_list_sync_jobs_includes_other_users_runs(api_client, data_fixture): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + foreign_job = SyncDataSyncTableJob.objects.create( + user=member, + data_sync=data_sync, + state=JOB_FINISHED, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + ) + + response = api_client.get( + reverse("api:jobs:list") + f"?type=sync_data_sync_table" + f"&sync_data_sync_table_data_sync_id={data_sync.id}&limit=10", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["count"] == 1 + jobs = response.json()["jobs"] + assert [job["id"] for job in jobs] == [foreign_job.id] + assert jobs[0]["triggered_by"] == DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC + assert jobs[0]["user_name"] == "Member" + assert jobs[0]["state"] == JOB_FINISHED + + +@pytest.mark.django_db +def test_list_sync_jobs_hidden_without_workspace_access(api_client, data_fixture): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync, state=JOB_FINISHED + ) + outsider, outsider_token = data_fixture.create_user_and_token() + + response = api_client.get( + reverse("api:jobs:list") + f"?type=sync_data_sync_table" + f"&sync_data_sync_table_data_sync_id={data_sync.id}", + HTTP_AUTHORIZATION=f"JWT {outsider_token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["jobs"] == [] + + +@pytest.mark.django_db +def test_polling_by_job_ids_only_widens_for_opted_in_job_types( + api_client, data_fixture +): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + foreign_sync_job = SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync + ) + foreign_other_job = data_fixture.create_fake_job(user=member) + + response = api_client.get( + reverse("api:jobs:list") + + f"?job_ids={foreign_sync_job.id},{foreign_other_job.id}", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert [job["id"] for job in response.json()["jobs"]] == [foreign_sync_job.id] + + +@pytest.mark.django_db +def test_starting_sync_conflicts_with_another_users_running_job( + api_client, data_fixture +): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + SyncDataSyncTableJob.objects.create(user=member, data_sync=data_sync) + + response = api_client.post( + reverse( + "api:database:data_sync:sync_table", + kwargs={"data_sync_id": data_sync.id}, + ), + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_MAX_JOB_COUNT_EXCEEDED" + + +@pytest.mark.django_db +def test_list_sync_jobs_paginates_with_count(api_client, data_fixture): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + jobs = [ + SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync, state=JOB_FINISHED + ) + for _ in range(3) + ] + + response = api_client.get( + reverse("api:jobs:list") + f"?type=sync_data_sync_table" + f"&sync_data_sync_table_data_sync_id={data_sync.id}&limit=2&offset=2", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["count"] == 3 + assert [job["id"] for job in response.json()["jobs"]] == [jobs[0].id] + + +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_list_sync_jobs_query_count_does_not_scale_with_results( + api_client, data_fixture +): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + url = ( + reverse("api:jobs:list") + f"?type=sync_data_sync_table" + f"&sync_data_sync_table_data_sync_id={data_sync.id}&limit=10" + ) + + SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync, state=JOB_FINISHED + ) + ContentType.objects.clear_cache() + with CaptureQueriesContext(connection) as queries_for_one: + response = api_client.get(url, HTTP_AUTHORIZATION=f"JWT {token}") + assert response.status_code == HTTP_200_OK + + for _ in range(9): + SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync, state=JOB_FINISHED + ) + ContentType.objects.clear_cache() + with CaptureQueriesContext(connection) as queries_for_ten: + response = api_client.get(url, HTTP_AUTHORIZATION=f"JWT {token}") + assert response.status_code == HTTP_200_OK + assert len(response.json()["jobs"]) == 10 + + assert len(queries_for_ten) <= len(queries_for_one) + + +@pytest.mark.django_db +def test_polling_foreign_job_types_batches_content_type_lookup( + api_client, data_fixture +): + owner, token, member, data_sync = create_data_sync_with_two_members(data_fixture) + foreign_sync_job = SyncDataSyncTableJob.objects.create( + user=member, data_sync=data_sync + ) + foreign_other_job = data_fixture.create_fake_job(user=member) + ContentType.objects.clear_cache() + + with CaptureQueriesContext(connection) as queries: + response = api_client.get( + reverse("api:jobs:list") + + f"?job_ids={foreign_sync_job.id},{foreign_other_job.id}", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + batched_content_type_fetches = [ + query + for query in queries + if 'FROM "django_content_type"' in query["sql"] + and '"django_content_type"."id" IN (' in query["sql"] + ] + # User scoping resolves every requested foreign job type with one IN query. Other + # single-ID content-type reads can still be made while serializing concrete jobs. + assert len(batched_content_type_fetches) == 1 diff --git a/backend/tests/baserow/contrib/database/data_sync/test_data_sync_job_type.py b/backend/tests/baserow/contrib/database/data_sync/test_data_sync_job_type.py new file mode 100644 index 0000000000..5a10696252 --- /dev/null +++ b/backend/tests/baserow/contrib/database/data_sync/test_data_sync_job_type.py @@ -0,0 +1,151 @@ +from datetime import timedelta + +from django.utils import timezone + +import pytest +import responses + +from baserow.contrib.database.data_sync.models import ( + DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + SyncDataSyncTableJob, +) +from baserow.contrib.database.table.signals import table_updated +from baserow.core.jobs.constants import JOB_FAILED +from baserow.core.jobs.exceptions import MaxJobCountExceeded +from baserow.core.jobs.handler import JobHandler +from baserow.core.jobs.registries import job_type_registry + + +@pytest.mark.django_db(transaction=True) +@responses.activate +def test_failed_sync_persists_last_error_and_broadcasts_table_updated(data_fixture): + responses.add( + responses.GET, + "https://baserow.io/ical.ics", + status=404, + body="", + ) + + user = data_fixture.create_user() + data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + + updated_table_ids = [] + + def receiver(sender, table, **kwargs): + updated_table_ids.append(table.id) + + table_updated.connect(receiver) + try: + job = JobHandler().create_and_start_job( + user, "sync_data_sync_table", sync=True, data_sync_id=data_sync.id + ) + finally: + table_updated.disconnect(receiver) + + job.refresh_from_db() + assert job.state == JOB_FAILED + assert job.triggered_by == DATA_SYNC_JOB_TRIGGERED_BY_MANUAL + + # The sync transaction rolled back, but on_error must persist the error. + data_sync.refresh_from_db() + assert ( + data_sync.last_error + == "The request to the URL didn't respond with an OK response code." + ) + assert data_sync.table_id in updated_table_ids + + +@pytest.mark.django_db +def test_cannot_start_sync_when_another_users_sync_is_running(data_fixture): + user_1 = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user_1) + user_2 = data_fixture.create_user(workspace=workspace) + database = data_fixture.create_database_application(workspace=workspace) + table = data_fixture.create_database_table(database=database) + data_sync = data_fixture.create_ical_data_sync( + table=table, ical_url="https://baserow.io/ical.ics" + ) + + SyncDataSyncTableJob.objects.create(user=user_2, data_sync=data_sync) + + with pytest.raises(MaxJobCountExceeded): + JobHandler().create_and_start_job( + user_1, "sync_data_sync_table", data_sync_id=data_sync.id + ) + + +@pytest.mark.django_db +def test_periodic_runs_bypass_the_per_user_max_count(data_fixture): + user = data_fixture.create_user() + job_type = job_type_registry.get("sync_data_sync_table") + + for _ in range(job_type.max_count): + data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + SyncDataSyncTableJob.objects.create(user=user, data_sync=data_sync) + + new_data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + + manual_job = SyncDataSyncTableJob( + user=user, + data_sync=new_data_sync, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + ) + with pytest.raises(MaxJobCountExceeded): + job_type.can_schedule_or_raise(manual_job) + + periodic_job = SyncDataSyncTableJob( + user=user, + data_sync=new_data_sync, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + ) + job_type.can_schedule_or_raise(periodic_job) + + +@pytest.mark.django_db +def test_stale_job_rows_do_not_block_new_syncs(data_fixture, settings): + user = data_fixture.create_user() + data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + stale_job = SyncDataSyncTableJob.objects.create(user=user, data_sync=data_sync) + SyncDataSyncTableJob.objects.filter(id=stale_job.id).update( + updated_on=timezone.now() + - timedelta(seconds=settings.BASEROW_JOB_SOFT_TIME_LIMIT + 1) + ) + + job_type = job_type_registry.get("sync_data_sync_table") + job_type.can_schedule_or_raise(SyncDataSyncTableJob(user=user, data_sync=data_sync)) + + +@pytest.mark.django_db +def test_periodic_runs_do_not_consume_the_users_manual_cap(data_fixture): + user = data_fixture.create_user() + job_type = job_type_registry.get("sync_data_sync_table") + + for _ in range(job_type.max_count): + data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + SyncDataSyncTableJob.objects.create( + user=user, + data_sync=data_sync, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + ) + + new_data_sync = data_fixture.create_ical_data_sync( + user=user, ical_url="https://baserow.io/ical.ics" + ) + job_type.can_schedule_or_raise( + SyncDataSyncTableJob( + user=user, + data_sync=new_data_sync, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_MANUAL, + ) + ) diff --git a/backend/tests/baserow/core/jobs/test_job_tasks.py b/backend/tests/baserow/core/jobs/test_job_tasks.py index 1816c6c07a..5af7f4357d 100644 --- a/backend/tests/baserow/core/jobs/test_job_tasks.py +++ b/backend/tests/baserow/core/jobs/test_job_tasks.py @@ -15,6 +15,7 @@ from baserow.core.jobs.constants import ( JOB_PENDING, JOB_STARTED, ) +from baserow.core.jobs.handler import JobHandler from baserow.core.jobs.models import Job from baserow.core.jobs.registries import JobType from baserow.core.jobs.tasks import clean_up_jobs, run_async_job @@ -172,6 +173,107 @@ def test_run_task_with_exception_mapping(mock_get_by_model, data_fixture): assert job.human_readable_error == "Error message" +@pytest.mark.django_db(transaction=True) +@patch("baserow.core.jobs.registries.JobTypeRegistry.get_by_model") +def test_run_task_calls_on_error_for_mapped_exception(mock_get_by_model, data_fixture): + job_type = TmpCustomJobType() + exception = ConnectionError("connection error") + job_type.run = Mock(side_effect=exception) + job_type.on_error = Mock() + mock_get_by_model.return_value = job_type + + job = data_fixture.create_fake_job() + + run_async_job(job.id) + + job_type.on_error.assert_called_once() + called_job, called_error = job_type.on_error.call_args.args + assert called_job.id == job.id + assert called_error is exception + + job.refresh_from_db() + assert job.state == JOB_FAILED + + +@pytest.mark.django_db(transaction=True) +@patch("baserow.core.jobs.registries.JobTypeRegistry.get_by_model") +def test_run_task_calls_on_error_for_unmapped_exception( + mock_get_by_model, data_fixture +): + job_type = TmpCustomJobType() + exception = Exception("test-1") + job_type.run = Mock(side_effect=exception) + job_type.on_error = Mock() + mock_get_by_model.return_value = job_type + + job = data_fixture.create_fake_job() + + with pytest.raises(Exception): + run_async_job(job.id) + + job_type.on_error.assert_called_once() + + +@pytest.mark.django_db(transaction=True) +@patch("baserow.core.jobs.registries.JobTypeRegistry.get_by_model") +def test_run_task_does_not_call_on_error_on_success_or_cancellation( + mock_get_by_model, data_fixture +): + job_type = TmpCustomJobType() + job_type.run = Mock() + job_type.on_error = Mock() + mock_get_by_model.return_value = job_type + + job = data_fixture.create_fake_job() + run_async_job(job.id) + job_type.on_error.assert_not_called() + + cancelled_job = data_fixture.create_fake_job() + JobHandler.cancel_job(cancelled_job) + run_async_job(cancelled_job.id) + job_type.on_error.assert_not_called() + + +@pytest.mark.django_db(transaction=True) +@patch("baserow.core.jobs.registries.JobTypeRegistry.get_by_model") +def test_on_error_runs_after_failed_state_is_saved(mock_get_by_model, data_fixture): + job_type = TmpCustomJobType() + job_type.run = Mock(side_effect=ConnectionError("connection error")) + + def on_error(failed_job, error): + Job.objects.filter(id=failed_job.id).update( + human_readable_error="from-on-error" + ) + + job_type.on_error = Mock(side_effect=on_error) + mock_get_by_model.return_value = job_type + + job = data_fixture.create_fake_job() + + run_async_job(job.id) + + # A hook running before the failure save would be overwritten by it. + job.refresh_from_db() + assert job.human_readable_error == "from-on-error" + + +@pytest.mark.django_db(transaction=True) +@patch("baserow.core.jobs.registries.JobTypeRegistry.get_by_model") +def test_on_error_exception_does_not_mask_job_failure(mock_get_by_model, data_fixture): + job_type = TmpCustomJobType() + job_type.run = Mock(side_effect=ConnectionError("connection error")) + job_type.on_error = Mock(side_effect=RuntimeError("hook broke")) + mock_get_by_model.return_value = job_type + + job = data_fixture.create_fake_job() + + run_async_job(job.id) + + job.refresh_from_db() + assert job.state == JOB_FAILED + assert job.human_readable_error == "Error message" + + @pytest.mark.django_db @patch("baserow.core.storage.get_default_storage") def test_cleanup_file_import_job(storage_mock, data_fixture, settings): diff --git a/backend/tests/baserow/core/jobs/test_jobs_handler.py b/backend/tests/baserow/core/jobs/test_jobs_handler.py index 14102cb697..99f187ae7e 100644 --- a/backend/tests/baserow/core/jobs/test_jobs_handler.py +++ b/backend/tests/baserow/core/jobs/test_jobs_handler.py @@ -396,3 +396,20 @@ def test_job_cancel_cancelled(data_fixture, test_thread, mutable_job_type_regist out = JobHandler.cancel_job(job) # won't cancel already cancelled assert out is None + + +@pytest.mark.django_db +def test_get_jobs_for_user_remains_scoped_to_owner(data_fixture): + user_1 = data_fixture.create_user() + user_2 = data_fixture.create_user() + job_1 = data_fixture.create_fake_job(user=user_1) + job_2 = data_fixture.create_fake_job(user=user_2) + + jobs = JobHandler.get_jobs_for_user(user_1, filter_states=None, filter_ids=None) + assert [job.id for job in jobs] == [job_1.id] + + # Requesting another user's job by id must not expose it (owner-only default). + jobs = JobHandler.get_jobs_for_user( + user_1, filter_states=None, filter_ids=[job_1.id, job_2.id] + ) + assert [job.id for job in jobs] == [job_1.id] diff --git a/changelog/entries/unreleased/feature/5722_shows_the_sync_history_of_synced_tables_including_runs_start.json b/changelog/entries/unreleased/feature/5722_shows_the_sync_history_of_synced_tables_including_runs_start.json new file mode 100644 index 0000000000..9fd155d08f --- /dev/null +++ b/changelog/entries/unreleased/feature/5722_shows_the_sync_history_of_synced_tables_including_runs_start.json @@ -0,0 +1,9 @@ +{ + "type": "feature", + "message": "Shows the sync history of synced tables, including runs started by the periodic schedule", + "issue_origin": "github", + "issue_number": 5722, + "domain": "database", + "bullet_points": [], + "created_at": "2026-07-10" +} diff --git a/docs/patterns/jobs.md b/docs/patterns/jobs.md index 4eeeba3d57..87fc6ab433 100644 --- a/docs/patterns/jobs.md +++ b/docs/patterns/jobs.md @@ -255,10 +255,25 @@ implemented. However, a subclass can also: * Hook into a job creation by preprocessing values provided by a user/postprocessing a created job. * Hook into a job deletion process. -* Provide a job error handler. +* Provide a job error handler (`JobType.on_error`). It's called after a failed job's + transaction has been rolled back and its failed state has been saved, so database + changes made in the hook are kept. Use it to persist error details on related models + (e.g. `SyncDataSyncTableJobType` stores `data_sync.last_error` there). * Provide custom job serializer fields or a custom serializer for a job model. * Pap exceptions to specific HTTP response codes. * Have [a model class](#job-sub-models). +* Declare listing filters (`JobType.get_filters_serializer`) so `GET /api/jobs/` can + filter jobs of that type by a related object, e.g. + `?type=sync_data_sync_table&sync_data_sync_table_data_sync_id=1&limit=10`. +* Widen listing visibility (`JobType.scope_queryset_to_user`). By default users only + see their own jobs. A job type can override this queryset scoping, after an explicit + object-level permission check, to expose runs started by other users (including + server-triggered ones). This applies both to type-filtered listings and to polling + by `job_ids`. +* Add the relations required by its response serializer with + `JobType.enhance_queryset`. The jobs listing invokes this hook on each concrete job + queryset, avoiding per-job relation queries without coupling the generic endpoint to + fields owned by a particular job type. `JobType` subclasses are registered and managed with a job type registry, so it should be easy to add new job types without modifying existing code. Each job type should have @@ -424,4 +439,3 @@ The component should use the `ProgressBar` subcomponent to display the progress: The buttons for the job creation/cancellation are up to the component. Their state can utilize properties above to control visibility. - diff --git a/enterprise/backend/src/baserow_enterprise/data_sync/handler.py b/enterprise/backend/src/baserow_enterprise/data_sync/handler.py index b3b23a7e1a..6ef721deda 100644 --- a/enterprise/backend/src/baserow_enterprise/data_sync/handler.py +++ b/enterprise/backend/src/baserow_enterprise/data_sync/handler.py @@ -2,20 +2,24 @@ from datetime import datetime, time from django.conf import settings from django.contrib.auth.models import AbstractUser -from django.core.cache import cache from django.db import transaction from django.db.models import Q from django.utils import timezone from loguru import logger -from baserow.contrib.database.data_sync.exceptions import ( - SyncDataSyncTableAlreadyRunning, +from baserow.contrib.database.api.data_sync.errors import ( + ERROR_SYNC_DATA_SYNC_ALREADY_RUNNING, +) +from baserow.contrib.database.data_sync.job_types import SyncDataSyncTableJobType +from baserow.contrib.database.data_sync.models import ( + DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + DataSync, ) -from baserow.contrib.database.data_sync.handler import DataSyncHandler -from baserow.contrib.database.data_sync.models import DataSync from baserow.contrib.database.data_sync.operations import SyncTableOperationType from baserow.core.handler import CoreHandler +from baserow.core.jobs.exceptions import MaxJobCountExceeded +from baserow.core.jobs.handler import JobHandler from baserow_enterprise.data_sync.models import ( DATA_SYNC_INTERVAL_DAILY, DATA_SYNC_INTERVAL_HOURLY, @@ -129,13 +133,7 @@ class EnterpriseDataSyncHandler: # locked, then we can skip the sync for now because the data sync is already # being updated. It doesn't matter if we skip it because it will then be # picked up the next time this method is called. - .select_for_update( - of=( - "self", - "data_sync", - ), - skip_locked=True, - ) + .select_for_update(of=("self", "data_sync"), skip_locked=True) ) updated_periodic_data_sync = [] @@ -146,30 +144,14 @@ class EnterpriseDataSyncHandler: DATA_SYNC, periodic_data_sync.data_sync.table.database.workspace ) if workspace_has_feature: - lock_key = DataSyncHandler().get_table_sync_lock_key( - periodic_data_sync.data_sync_id - ) - sync_is_running = cache.get(lock_key) is not None - periodic_data_sync.last_periodic_sync = now updated_periodic_data_sync.append(periodic_data_sync) - # If the sync is already running because the lock exists, - # then nothing sohuld happen because the sync has already happened - # within the correct periodic timeframe. We do want to update the - # `last_periodic_sync`, so that it doesn't try again on the next run. - if sync_is_running: - logger.info( - f"Skipping periodic data sync of data sync " - f"{periodic_data_sync.data_sync_id} because the sync already " - f"running." - ) - else: - transaction.on_commit( - lambda pds=periodic_data_sync: sync_periodic_data_sync.delay( - pds.id - ) + transaction.on_commit( + lambda pds_id=periodic_data_sync.id: sync_periodic_data_sync.delay( + pds_id ) + ) else: periodic_data_sync.interval = DATA_SYNC_INTERVAL_MANUAL periodic_data_sync.automatically_deactivated = True @@ -201,8 +183,10 @@ class EnterpriseDataSyncHandler: @classmethod def sync_periodic_data_sync(cls, periodic_data_sync_id): """ - Syncs the data sync of a periodic data sync. This is typically executed by the - async task `sync_periodic_data_sync`. + Syncs the data sync of a periodic data sync by running a + `sync_data_sync_table` job on behalf of the authorized user, so that the + run is recorded in the sync job history. This is typically executed by + the async task `sync_periodic_data_sync`. :param periodic_data_sync_id: The ID of the periodic data sync object that must be synced. Note that this not equal to the data sync ID. @@ -211,11 +195,9 @@ class EnterpriseDataSyncHandler: """ try: - periodic_data_sync = ( - PeriodicDataSyncInterval.objects.select_related("data_sync") - .select_for_update(of=("self",)) - .get(id=periodic_data_sync_id, automatically_deactivated=False) - ) + periodic_data_sync = PeriodicDataSyncInterval.objects.select_related( + "data_sync" + ).get(id=periodic_data_sync_id, automatically_deactivated=False) except PeriodicDataSyncInterval.DoesNotExist: logger.info( f"Skipping periodic data sync {periodic_data_sync_id} because it " @@ -223,46 +205,65 @@ class EnterpriseDataSyncHandler: ) return False + authorized_user = periodic_data_sync.authorized_user + data_sync_id = periodic_data_sync.data_sync_id + + # The job runs outside a transaction: its context sets the isolation level. try: - data_sync = DataSyncHandler().sync_data_sync_table( - periodic_data_sync.authorized_user, - periodic_data_sync.data_sync.specific, + job = JobHandler().create_and_start_job( + authorized_user, + SyncDataSyncTableJobType.type, + sync=True, + data_sync_id=data_sync_id, + triggered_by=DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, ) - except SyncDataSyncTableAlreadyRunning: - # If the sync has started in the meantime, then we don't want to do - # anything because the sync already ran. + except MaxJobCountExceeded: + # A pending/running sync job means it already ran within this timeframe. logger.info( - f"Skipping periodic data sync of data sync " - f"{periodic_data_sync.data_sync_id} because the sync is running." + f"Skipping periodic data sync of data sync {data_sync_id} because " + f"a sync job is already running." ) return False + except Exception: + # Job creation errors and unexpected run errors both count as failed runs. + logger.exception( + f"The periodic data sync of data sync {data_sync_id} failed." + ) + run_failed = True + else: + # A lost race with a concurrent manual sync is not a real failure. + run_failed = ( + job.failed + and job.human_readable_error != ERROR_SYNC_DATA_SYNC_ALREADY_RUNNING[2] + ) - if data_sync.last_error: - # If the data sync has an error, then something went wrong during execution, - # and we need to increase the consecutive count so that when the max errors - # is reached, we can deactivate it. This to protect the system from - # periodically syncing a data sync that doesn't work anyway. - periodic_data_sync.consecutive_failed_count += 1 - if ( - periodic_data_sync.consecutive_failed_count - >= settings.BASEROW_ENTERPRISE_MAX_PERIODIC_DATA_SYNC_CONSECUTIVE_ERRORS - ): - periodic_data_sync.automatically_deactivated = True - periodic_data_sync.deactivation_reason = DEACTIVATION_REASON_FAILURE + with transaction.atomic(): + try: + periodic_data_sync = PeriodicDataSyncInterval.objects.select_for_update( + of=("self",) + ).get(id=periodic_data_sync_id) + except PeriodicDataSyncInterval.DoesNotExist: + return True - # Send a notification to the authorized user that the periodic data - # sync was deactivated. - transaction.on_commit( - lambda: PeriodicDataSyncDeactivatedNotificationType.notify_authorized_user( - periodic_data_sync + if run_failed: + # Deactivate after too many consecutive failures to protect the system. + periodic_data_sync.consecutive_failed_count += 1 + if ( + periodic_data_sync.consecutive_failed_count + >= settings.BASEROW_ENTERPRISE_MAX_PERIODIC_DATA_SYNC_CONSECUTIVE_ERRORS + ): + periodic_data_sync.automatically_deactivated = True + periodic_data_sync.deactivation_reason = DEACTIVATION_REASON_FAILURE + transaction.on_commit( + lambda: PeriodicDataSyncDeactivatedNotificationType.notify_authorized_user( + periodic_data_sync + ) ) - ) - periodic_data_sync.save() - elif periodic_data_sync.consecutive_failed_count > 0: - # Once it runs successfully, the consecutive count can be reset because we - # now know it actually works, and it doesn't have to be deactivated anymore. - periodic_data_sync.consecutive_failed_count = 0 - periodic_data_sync.save() + periodic_data_sync.save() + elif periodic_data_sync.consecutive_failed_count > 0: + # A successful run proves it works again, so the count can reset. + periodic_data_sync.consecutive_failed_count = 0 + periodic_data_sync.save() return True diff --git a/enterprise/backend/src/baserow_enterprise/data_sync/tasks.py b/enterprise/backend/src/baserow_enterprise/data_sync/tasks.py index b07da9c183..5df0dbe469 100644 --- a/enterprise/backend/src/baserow_enterprise/data_sync/tasks.py +++ b/enterprise/backend/src/baserow_enterprise/data_sync/tasks.py @@ -3,10 +3,23 @@ from datetime import timedelta from django.conf import settings from django.db import transaction +from celery_singleton import Singleton + from baserow.config.celery import app +PERIODIC_DATA_SYNC_DISPATCH_TIME_LIMIT = 60 * 5 -@app.task(bind=True, queue="export") + +@app.task( + base=Singleton, + bind=True, + queue="export", + raise_on_duplicate=False, + soft_time_limit=PERIODIC_DATA_SYNC_DISPATCH_TIME_LIMIT, + time_limit=PERIODIC_DATA_SYNC_DISPATCH_TIME_LIMIT, + # Must match time_limit, or a hard-killed worker's lock blocks dispatches. + lock_expiry=PERIODIC_DATA_SYNC_DISPATCH_TIME_LIMIT, +) def call_periodic_data_sync_syncs_that_are_due(self): from baserow_enterprise.data_sync.handler import EnterpriseDataSyncHandler @@ -27,5 +40,5 @@ def setup_periodic_enterprise_data_sync_tasks(sender, **kwargs): def sync_periodic_data_sync(self, periodic_data_sync_id): from baserow_enterprise.data_sync.handler import EnterpriseDataSyncHandler - with transaction.atomic(): - EnterpriseDataSyncHandler().sync_periodic_data_sync(periodic_data_sync_id) + # No transaction wrapper: the sync job's isolation level needs a fresh one. + EnterpriseDataSyncHandler().sync_periodic_data_sync(periodic_data_sync_id) diff --git a/enterprise/backend/src/baserow_enterprise/role/default_roles.py b/enterprise/backend/src/baserow_enterprise/role/default_roles.py index 136d5b22fa..5a8882e046 100755 --- a/enterprise/backend/src/baserow_enterprise/role/default_roles.py +++ b/enterprise/backend/src/baserow_enterprise/role/default_roles.py @@ -95,6 +95,7 @@ from baserow.contrib.database.airtable.operations import ( ) from baserow.contrib.database.data_sync.operations import ( GetIncludingPublicValuesOperationType, + ListDataSyncJobsOperationType, ListPropertiesOperationType, SyncTableOperationType, ) @@ -568,6 +569,7 @@ default_roles[BUILDER_ROLE_UID].extend( UpdateBuilderWorkflowActionOperationType, OrderBuilderWorkflowActionOperationType, SyncTableOperationType, + ListDataSyncJobsOperationType, ListPropertiesOperationType, GetIncludingPublicValuesOperationType, CreateWidgetOperationType, diff --git a/enterprise/backend/tests/baserow_enterprise_tests/data_sync/test_enterprise_data_sync_handler.py b/enterprise/backend/tests/baserow_enterprise_tests/data_sync/test_enterprise_data_sync_handler.py index 38c18ba241..d75b3a19d9 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/data_sync/test_enterprise_data_sync_handler.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/data_sync/test_enterprise_data_sync_handler.py @@ -2,7 +2,6 @@ from datetime import datetime, time, timezone from unittest.mock import patch from django.conf import settings -from django.core.cache import cache from django.db import transaction from django.test.utils import override_settings from django.utils import timezone as django_timezone @@ -12,9 +11,14 @@ import responses from freezegun.api import freeze_time from baserow.contrib.database.data_sync.handler import DataSyncHandler -from baserow.contrib.database.data_sync.models import DataSync +from baserow.contrib.database.data_sync.models import ( + DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC, + DataSync, + SyncDataSyncTableJob, +) from baserow.core.db import specific_iterator from baserow.core.exceptions import UserNotInWorkspace +from baserow.core.jobs.constants import JOB_FAILED, JOB_FINISHED from baserow.core.notifications.models import Notification from baserow_enterprise.data_sync.handler import EnterpriseDataSyncHandler from baserow_enterprise.data_sync.models import ( @@ -527,34 +531,39 @@ def test_skip_locked_data_syncs(enterprise_data_fixture, synced_roles): @pytest.mark.data_sync @override_settings(DEBUG=True) @patch("baserow_enterprise.data_sync.handler.sync_periodic_data_sync") -def test_skip_syncing_data_syncs( +def test_call_periodic_data_sync_enqueues_each_due_sync( mock_sync_periodic_data_sync, enterprise_data_fixture, synced_roles ): enterprise_data_fixture.enable_enterprise() user = enterprise_data_fixture.create_user() - not_yet_executed_1 = EnterpriseDataSyncHandler.update_periodic_data_sync_interval( + due_1 = EnterpriseDataSyncHandler.update_periodic_data_sync_interval( + user=user, + data_sync=enterprise_data_fixture.create_ical_data_sync(user=user), + interval="DAILY", + when=time(hour=12, minute=10, second=1, microsecond=1), + ) + due_2 = EnterpriseDataSyncHandler.update_periodic_data_sync_interval( user=user, data_sync=enterprise_data_fixture.create_ical_data_sync(user=user), interval="DAILY", when=time(hour=12, minute=10, second=1, microsecond=1), ) - lock_key = DataSyncHandler().get_table_sync_lock_key( - not_yet_executed_1.data_sync_id - ) - cache.add(lock_key, "locked", timeout=2) - with freeze_time("2024-10-10T12:15:00.00Z"): with transaction.atomic(): EnterpriseDataSyncHandler.call_periodic_data_sync_syncs_that_are_due() - not_yet_executed_1.refresh_from_db() - # Should be updated if the data sync is already running. - assert not_yet_executed_1.last_periodic_sync is not None + due_1.refresh_from_db() + due_2.refresh_from_db() + assert due_1.last_periodic_sync is not None + assert due_2.last_periodic_sync is not None - # Should not be called if the data sync is already running. - mock_sync_periodic_data_sync.delay.assert_not_called() + # Every due sync must be enqueued with its own id, not the last iterated one. + called_ids = { + call.args[0] for call in mock_sync_periodic_data_sync.delay.call_args_list + } + assert called_ids == {due_1.id, due_2.id} @pytest.mark.django_db @@ -596,26 +605,27 @@ def test_sync_periodic_data_sync_already_syncing(enterprise_data_fixture): when=time(hour=12, minute=10, second=1, microsecond=1), ) - lock_key = DataSyncHandler().get_table_sync_lock_key( - periodic_data_sync.data_sync_id + SyncDataSyncTableJob.objects.create( + user=user, data_sync=periodic_data_sync.data_sync ) - cache.add(lock_key, "locked", timeout=2) assert ( EnterpriseDataSyncHandler.sync_periodic_data_sync(periodic_data_sync.id) is False ) + periodic_data_sync.refresh_from_db() + assert periodic_data_sync.consecutive_failed_count == 0 periodic_data_sync.data_sync.refresh_from_db() assert periodic_data_sync.data_sync.last_sync is None -@pytest.mark.django_db +@pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @override_settings(DEBUG=True) @responses.activate def test_sync_periodic_data_sync_consecutive_failed_count_increases( - enterprise_data_fixture, + enterprise_data_fixture, synced_roles ): responses.add( responses.GET, @@ -642,14 +652,14 @@ def test_sync_periodic_data_sync_consecutive_failed_count_increases( assert periodic_data_sync.consecutive_failed_count == 1 -@pytest.mark.django_db +@pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @override_settings( DEBUG=True, BASEROW_ENTERPRISE_MAX_PERIODIC_DATA_SYNC_CONSECUTIVE_ERRORS=2 ) @responses.activate def test_sync_periodic_data_sync_consecutive_failed_count_reset( - enterprise_data_fixture, + enterprise_data_fixture, synced_roles ): responses.add( responses.GET, @@ -682,11 +692,13 @@ END:VCALENDAR""", assert periodic_data_sync.consecutive_failed_count == 0 -@pytest.mark.django_db +@pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @override_settings(DEBUG=True) @responses.activate -def test_sync_periodic_data_sync_deactivated_max_failure(enterprise_data_fixture): +def test_sync_periodic_data_sync_deactivated_max_failure( + enterprise_data_fixture, synced_roles +): responses.add( responses.GET, "https://baserow.io/ical.ics", @@ -742,8 +754,7 @@ def test_sync_periodic_data_sync_deactivated_max_failure_notification_send( periodic_data_sync.consecutive_failed_count = 3 periodic_data_sync.save() - with transaction.atomic(): - EnterpriseDataSyncHandler.sync_periodic_data_sync(periodic_data_sync.id) + EnterpriseDataSyncHandler.sync_periodic_data_sync(periodic_data_sync.id) all_notifications = list(Notification.objects.all()) assert len(all_notifications) == 1 @@ -765,10 +776,12 @@ def test_sync_periodic_data_sync_deactivated_max_failure_notification_send( } -@pytest.mark.django_db +@pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @override_settings(DEBUG=True) -def test_sync_periodic_data_sync_authorized_user_is_none(enterprise_data_fixture): +def test_sync_periodic_data_sync_authorized_user_is_none( + enterprise_data_fixture, synced_roles +): enterprise_data_fixture.enable_enterprise() user = enterprise_data_fixture.create_user() @@ -778,7 +791,7 @@ def test_sync_periodic_data_sync_authorized_user_is_none(enterprise_data_fixture interval="DAILY", when=time(hour=12, minute=10, second=1, microsecond=1), ) - periodic_data_sync.authorized_user is None + periodic_data_sync.authorized_user = None periodic_data_sync.save() assert ( @@ -789,11 +802,11 @@ def test_sync_periodic_data_sync_authorized_user_is_none(enterprise_data_fixture assert periodic_data_sync.consecutive_failed_count == 1 -@pytest.mark.django_db +@pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @override_settings(DEBUG=True) @responses.activate -def test_sync_periodic_data_sync(enterprise_data_fixture): +def test_sync_periodic_data_sync(enterprise_data_fixture, synced_roles): responses.add( responses.GET, "https://baserow.io/ical.ics", @@ -823,6 +836,12 @@ END:VCALENDAR""", assert periodic_data_sync.data_sync.last_sync is not None assert periodic_data_sync.data_sync.last_error is None + job = SyncDataSyncTableJob.objects.get() + assert job.user_id == user.id + assert job.data_sync_id == periodic_data_sync.data_sync_id + assert job.triggered_by == DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC + assert job.state == JOB_FINISHED + @pytest.mark.django_db(transaction=True) @pytest.mark.data_sync @@ -1104,3 +1123,35 @@ def test_create_and_set_two_way_data_sync_table( assert fields[0].read_only is True assert fields[1].primary is False assert fields[1].read_only is False + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.data_sync +@override_settings(DEBUG=True) +@patch( + "baserow.contrib.database.data_sync.handler.DataSyncHandler.sync_data_sync_table", + side_effect=RuntimeError("unexpected"), +) +def test_sync_periodic_data_sync_unexpected_error_counts_as_failed_run( + mock_sync_data_sync_table, enterprise_data_fixture, synced_roles +): + enterprise_data_fixture.enable_enterprise() + user = enterprise_data_fixture.create_user() + + periodic_data_sync = EnterpriseDataSyncHandler.update_periodic_data_sync_interval( + user=user, + data_sync=enterprise_data_fixture.create_ical_data_sync(user=user), + interval="DAILY", + when=time(hour=12, minute=10, second=1, microsecond=1), + ) + + assert ( + EnterpriseDataSyncHandler.sync_periodic_data_sync(periodic_data_sync.id) is True + ) + + periodic_data_sync.refresh_from_db() + assert periodic_data_sync.consecutive_failed_count == 1 + + job = SyncDataSyncTableJob.objects.get() + assert job.state == JOB_FAILED + assert job.triggered_by == DATA_SYNC_JOB_TRIGGERED_BY_PERIODIC diff --git a/web-frontend/modules/core/assets/scss/components/all.scss b/web-frontend/modules/core/assets/scss/components/all.scss index d0165816df..cb13f79228 100644 --- a/web-frontend/modules/core/assets/scss/components/all.scss +++ b/web-frontend/modules/core/assets/scss/components/all.scss @@ -197,6 +197,7 @@ @import 'dashboard/all'; @import 'export_workspace'; @import 'import_workspace'; +@import 'data_sync_runs'; @import 'admin_dashboard'; @import 'user_admin'; @import 'group_admin'; diff --git a/web-frontend/modules/core/assets/scss/components/data_sync_runs.scss b/web-frontend/modules/core/assets/scss/components/data_sync_runs.scss new file mode 100644 index 0000000000..652c7e29dd --- /dev/null +++ b/web-frontend/modules/core/assets/scss/components/data_sync_runs.scss @@ -0,0 +1,98 @@ +.data-sync-runs { + border: 1px solid $palette-neutral-200; + overflow: hidden; + + @include rounded($rounded-md); +} + +.data-sync-runs__item { + padding: 12px 16px; + + &:not(:last-child) { + border-bottom: 1px solid $palette-neutral-200; + } +} + +.data-sync-runs__head { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + color: inherit; + + &:hover { + color: inherit; + text-decoration: none; + } + + &--expandable { + width: 100%; + padding: 0; + border: 0; + background: none; + font: inherit; + text-align: left; + cursor: pointer; + } +} + +.data-sync-runs__info { + @extend %ellipsis; + + flex: 1 1 auto; + min-width: 0; + color: $palette-neutral-700; + font-size: 12px; +} + +.data-sync-runs__duration { + flex: 0 0 auto; + color: $palette-neutral-700; + font-size: 12px; +} + +.data-sync-runs__toggle-icon { + flex: 0 0 auto; + color: $palette-neutral-700; + font-size: 14px; + + .data-sync-runs__item--open & { + color: $palette-neutral-1200; + } +} + +.data-sync-runs__error { + margin-top: 10px; + padding: 10px; + max-height: 120px; + overflow: auto; + background-color: $palette-neutral-100; + color: $palette-red-800; + font-family: monospace; + font-size: 12px; + line-height: 18px; + white-space: pre-wrap; + overflow-wrap: anywhere; + + @include rounded($rounded-md); +} + +.data-sync-runs__paginator { + margin-top: 10px; +} + +.data-sync-runs__empty { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 24px 16px; + border: 1px dashed $palette-neutral-200; + color: $palette-neutral-700; + + @include rounded($rounded-md); +} + +.data-sync-runs__empty-icon { + font-size: 16px; +} diff --git a/web-frontend/modules/core/mixins/job.js b/web-frontend/modules/core/mixins/job.js index 64c7ff4cda..44ca3befc9 100644 --- a/web-frontend/modules/core/mixins/job.js +++ b/web-frontend/modules/core/mixins/job.js @@ -127,7 +127,7 @@ export default { this.$t('unknown error'), }) } - if (this.onJobCancelFailed === 'function') { + if (typeof this.onJobCancelFailed === 'function') { this.onJobCancelFailed() } } diff --git a/web-frontend/modules/core/store/job.js b/web-frontend/modules/core/store/job.js index 3c710c56c2..23d5286cd8 100644 --- a/web-frontend/modules/core/store/job.js +++ b/web-frontend/modules/core/store/job.js @@ -1,7 +1,7 @@ import JobService from '@baserow/modules/core/services/job' import _ from 'lodash' -const FINISHED_STATES = ['finished', 'failed', 'cancelled'] +export const FINISHED_STATES = ['finished', 'failed', 'cancelled'] const STARTING_TIMEOUT_MS = 200 const MAX_POLLING_ATTEMPTS = 100 diff --git a/web-frontend/modules/database/components/dataSync/ConfigureDataSyncHistory.vue b/web-frontend/modules/database/components/dataSync/ConfigureDataSyncHistory.vue new file mode 100644 index 0000000000..63fc6fc200 --- /dev/null +++ b/web-frontend/modules/database/components/dataSync/ConfigureDataSyncHistory.vue @@ -0,0 +1,26 @@ + + + diff --git a/web-frontend/modules/database/components/dataSync/DataSyncRunHead.vue b/web-frontend/modules/database/components/dataSync/DataSyncRunHead.vue new file mode 100644 index 0000000000..ac465634e7 --- /dev/null +++ b/web-frontend/modules/database/components/dataSync/DataSyncRunHead.vue @@ -0,0 +1,36 @@ + + + diff --git a/web-frontend/modules/database/components/dataSync/DataSyncRunsList.vue b/web-frontend/modules/database/components/dataSync/DataSyncRunsList.vue new file mode 100644 index 0000000000..5faec3e8fb --- /dev/null +++ b/web-frontend/modules/database/components/dataSync/DataSyncRunsList.vue @@ -0,0 +1,242 @@ + + + diff --git a/web-frontend/modules/database/components/dataSync/SyncTableModal.vue b/web-frontend/modules/database/components/dataSync/SyncTableModal.vue index 6b6209a063..ba13b525e1 100644 --- a/web-frontend/modules/database/components/dataSync/SyncTableModal.vue +++ b/web-frontend/modules/database/components/dataSync/SyncTableModal.vue @@ -1,7 +1,7 @@ @@ -43,9 +50,11 @@