feat: data sync run history - record every sync as a job and show it to users (#5706)

* fix: call JobType.on_error hook again when a job fails

The call was accidentally dropped in e0a07588a, leaving the documented
post-transaction error hook dead. Job types rely on it to persist error
details that would otherwise be lost to the rolled-back job transaction.

* feat: record data sync runs as jobs and show the sync history

Periodic data syncs now run through the job system on behalf of the
authorized user, so every sync run (manual or periodic) is recorded as a
SyncDataSyncTableJob with a triggered_by discriminator. A new JobType
scoping hook lets the generic jobs listing expose runs started by other
users after a ListDataSyncJobsOperationType permission check, on both the
type-filter and job_ids polling paths. The frontend shows a paginated run
history (state, trigger, user, time, duration, error) in the data sync
configuration modal and below the manual sync modal, live-updating
through the existing job store poller.

* fix: address feedback
This commit is contained in:
Davide Silvestri authored and GitHub committed 2026-07-22 13:35:50 +02:00
1 parent 342a00e380
commit 3486ba237a
38 files changed
+1783 -140

No files matched your search

+28 -1
View File
@@ -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)(),
+21 -10
View File
@@ -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"],
@@ -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.",
)
@@ -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())
@@ -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
@@ -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):
@@ -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"
@@ -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),
),
]
+58 -2
View File
@@ -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,
@@ -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.
+9
View File
@@ -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:
@@ -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",
@@ -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
@@ -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,
)
)
@@ -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):
@@ -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]
@@ -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"
}
+16 -2
View File
@@ -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.
@@ -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
@@ -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)
@@ -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,
@@ -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
@@ -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';
@@ -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;
}
+1 -1
View File
@@ -127,7 +127,7 @@ export default {
this.$t('unknown error'),
})
}
if (this.onJobCancelFailed === 'function') {
if (typeof this.onJobCancelFailed === 'function') {
this.onJobCancelFailed()
}
}
+1 -1
View File
@@ -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
@@ -0,0 +1,26 @@
<template>
<div>
<h2 class="box__title">{{ $t('dataSyncRuns.title') }}</h2>
<p class="margin-bottom-2">{{ $t('dataSyncRuns.description') }}</p>
<DataSyncRunsList :data-sync-id="table.data_sync.id" />
</div>
</template>
<script>
import DataSyncRunsList from '@baserow/modules/database/components/dataSync/DataSyncRunsList'
export default {
name: 'ConfigureDataSyncHistory',
components: { DataSyncRunsList },
props: {
database: {
type: Object,
required: true,
},
table: {
type: Object,
required: true,
},
},
}
</script>
@@ -0,0 +1,36 @@
<template>
<button
v-if="expandable"
type="button"
class="data-sync-runs__head data-sync-runs__head--expandable"
:aria-expanded="expanded"
:aria-controls="controls"
@click="$emit('toggle')"
>
<slot></slot>
</button>
<div v-else class="data-sync-runs__head">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'DataSyncRunHead',
props: {
expandable: {
type: Boolean,
required: true,
},
expanded: {
type: Boolean,
required: true,
},
controls: {
type: String,
required: true,
},
},
emits: ['toggle'],
}
</script>
@@ -0,0 +1,242 @@
<template>
<div>
<div v-if="loading" class="loading margin-top-2"></div>
<template v-else>
<Error :error="error"></Error>
<template v-if="loaded">
<p v-if="rows.length === 0" class="data-sync-runs__empty">
<i class="iconoir-data-transfer-down data-sync-runs__empty-icon"></i>
{{ $t('dataSyncRuns.noRuns') }}
</p>
<div v-else class="data-sync-runs">
<div
v-for="row in rows"
:key="row.id"
class="data-sync-runs__item"
:class="{ 'data-sync-runs__item--open': isExpanded(row.id) }"
>
<DataSyncRunHead
:expandable="Boolean(row.human_readable_error)"
:expanded="isExpanded(row.id)"
:controls="`data-sync-run-error-${row.id}`"
@toggle="toggleExpanded(row.id)"
>
<Badge :color="stateColor(row.state)" rounded>{{
stateLabel(row.state)
}}</Badge>
<Badge
:color="row.triggered_by === 'periodic' ? 'cyan' : 'neutral'"
rounded
>{{
row.triggered_by === 'periodic'
? $t('dataSyncRuns.triggerPeriodic')
: $t('dataSyncRuns.triggerManual')
}}</Badge
>
<span class="data-sync-runs__info">
{{ timestamp(row) }}
<template v-if="row.user_name">
{{ $t('dataSyncRuns.byUser', { name: row.user_name }) }}
</template>
</span>
<span class="data-sync-runs__duration">
<template v-if="isEnded(row)">{{
$t('dataSyncRuns.duration', { seconds: duration(row) })
}}</template>
<template v-else>{{ row.progress_percentage }}%</template>
</span>
<i
v-if="row.human_readable_error"
class="data-sync-runs__toggle-icon"
:class="
isExpanded(row.id)
? 'iconoir-nav-arrow-up'
: 'iconoir-nav-arrow-down'
"
></i>
</DataSyncRunHead>
<div
v-if="isExpanded(row.id)"
:id="`data-sync-run-error-${row.id}`"
class="data-sync-runs__error"
>
{{ row.human_readable_error }}
</div>
</div>
</div>
<Paginator
v-if="totalPages > 1"
class="data-sync-runs__paginator"
:total-pages="totalPages"
:page="page"
@change-page="changePage"
></Paginator>
</template>
</template>
</div>
</template>
<script>
import Paginator from '@baserow/modules/core/components/Paginator'
import error from '@baserow/modules/core/mixins/error'
import { FINISHED_STATES } from '@baserow/modules/core/store/job'
import DataSyncService from '@baserow/modules/database/services/dataSync'
import DataSyncRunHead from '@baserow/modules/database/components/dataSync/DataSyncRunHead'
import moment from '@baserow/modules/core/moment'
export default {
name: 'DataSyncRunsList',
components: { DataSyncRunHead, Paginator },
mixins: [error],
props: {
dataSyncId: {
type: Number,
required: true,
},
limit: {
type: Number,
required: false,
default: 10,
},
},
emits: ['running-job'],
data() {
return {
loading: false,
loaded: false,
jobs: [],
count: 0,
page: 1,
expandedJobIds: [],
}
},
computed: {
storeJobs() {
return this.$store.getters['job/getAll']
},
totalPages() {
return Math.max(1, Math.ceil(this.count / this.limit))
},
rows() {
// Store copies win (live via poller); page 1 also shows store-only new runs.
const rowsById = new Map()
if (this.page === 1) {
for (const job of this.storeJobs) {
if (
job.type === 'sync_data_sync_table' &&
job.data_sync?.id === this.dataSyncId
) {
rowsById.set(job.id, job)
}
}
}
for (const job of this.jobs) {
if (!rowsById.has(job.id)) {
rowsById.set(
job.id,
this.storeJobs.find((item) => item.id === job.id) || job
)
}
}
return [...rowsById.values()].sort((a, b) => b.id - a.id)
},
unfinishedTrackedJobCount() {
return this.storeJobs.filter(
(item) =>
!FINISHED_STATES.includes(item.state) &&
this.rows.some((row) => row.id === item.id)
).length
},
},
watch: {
unfinishedTrackedJobCount(newCount, oldCount) {
// Page 1 only: elsewhere a drop can be pagination swapping rows out.
if (newCount < oldCount && this.page === 1) {
this.reload()
}
},
},
mounted() {
this.reload()
},
methods: {
async reload(page = this.page) {
if (!this.loaded) {
this.loading = true
}
try {
const { data } = await DataSyncService(this.$client).fetchSyncJobs(
this.dataSyncId,
{ limit: this.limit, offset: (page - 1) * this.limit }
)
this.hideError()
this.page = page
this.jobs = data.jobs
this.count = data.count ?? data.jobs.length
const unfinished = data.jobs.filter(
(job) => !FINISHED_STATES.includes(job.state)
)
await Promise.all(
unfinished.map((job) => this.$store.dispatch('job/create', job))
)
if (unfinished.length > 0) {
this.$emit('running-job', unfinished[0])
}
this.loaded = true
} catch (error) {
this.handleError(error)
} finally {
this.loading = false
}
},
changePage(page) {
if (page >= 1 && page <= this.totalPages && page !== this.page) {
this.reload(page)
}
},
isEnded(job) {
return FINISHED_STATES.includes(job.state)
},
isExpanded(jobId) {
return this.expandedJobIds.includes(jobId)
},
stateColor(state) {
const colors = {
finished: 'green',
failed: 'red',
cancelled: 'yellow',
}
return colors[state] || 'cyan'
},
stateLabel(state) {
const translations = {
pending: this.$t('job.statePending'),
started: this.$t('job.stateStarted'),
failed: this.$t('job.stateFailed'),
finished: this.$t('job.stateFinished'),
cancelled: this.$t('job.stateCanceled'),
}
return translations[state] || this.$t('job.stateStarted')
},
timestamp(job) {
return moment.utc(job.created_on).local().format('YYYY-MM-DD HH:mm:ss')
},
duration(job) {
return Math.max(
0,
Math.round(
(moment.utc(job.updated_on) - moment.utc(job.created_on)) / 1000
)
)
},
toggleExpanded(jobId) {
const index = this.expandedJobIds.indexOf(jobId)
if (index > -1) {
this.expandedJobIds.splice(index, 1)
} else {
this.expandedJobIds.push(jobId)
}
},
},
}
</script>
@@ -1,7 +1,7 @@
<template>
<Modal
ref="modal"
:can-close="!syncLoading && !jobIsRunning"
:can-close="!syncLoading && (!jobIsRunning || attachedToExistingRun)"
@hidden="hidden"
>
<template #content>
@@ -27,7 +27,7 @@
size="large"
:disabled="syncLoading || jobIsRunning"
:loading="syncLoading || jobIsRunning"
@click="syncTable(table)"
@click="startSync()"
>
{{ $t('syncTableModal.sync') }}
</Button>
@@ -36,6 +36,13 @@
}}</Button>
</div>
</div>
<div v-if="table.data_sync" class="margin-top-3">
<h3>{{ $t('dataSyncRuns.previousRuns') }}</h3>
<DataSyncRunsList
:data-sync-id="table.data_sync.id"
@running-job="attachToRunningJob"
/>
</div>
</template>
</Modal>
</template>
@@ -43,9 +50,11 @@
<script>
import modal from '@baserow/modules/core/mixins/modal'
import dataSync from '@baserow/modules/database/mixins/dataSync'
import DataSyncRunsList from '@baserow/modules/database/components/dataSync/DataSyncRunsList'
export default {
name: 'SyncTableModal',
components: { DataSyncRunsList },
mixins: [modal, dataSync],
props: {
table: {
@@ -53,12 +62,29 @@ export default {
required: true,
},
},
data() {
return {
attachedToExistingRun: false,
}
},
methods: {
show() {
this.job = null
this.attachedToExistingRun = false
this.hideError()
modal.methods.show.bind(this)()
},
startSync() {
this.attachedToExistingRun = false
return this.syncTable(this.table)
},
// Show an in-flight run's progress instead of failing with "already running".
async attachToRunningJob(job) {
if (!this.jobIsRunning) {
this.attachedToExistingRun = true
await this.createAndMonitorJob(job)
}
},
hidden() {},
},
}
@@ -1,6 +1,7 @@
import { Registerable } from '@baserow/modules/core/registry'
import ConfigureDataSyncVisibleFields from '@baserow/modules/database/components/dataSync/ConfigureDataSyncVisibleFields'
import ConfigureDataSyncSettings from '@baserow/modules/database/components/dataSync/ConfigureDataSyncSettings'
import ConfigureDataSyncHistory from '@baserow/modules/database/components/dataSync/ConfigureDataSyncHistory'
export class ConfigureDataSyncType extends Registerable {
get name() {
@@ -57,3 +58,21 @@ export class SettingsConfigureDataSyncType extends ConfigureDataSyncType {
return ConfigureDataSyncSettings
}
}
export class SyncHistoryConfigureDataSyncType extends ConfigureDataSyncType {
static getType() {
return 'sync-history'
}
get name() {
return this.app.$i18n.t('configureDataSyncModal.syncHistory')
}
get iconClass() {
return 'iconoir-clock'
}
get component() {
return ConfigureDataSyncHistory
}
}
+12 -1
View File
@@ -1157,7 +1157,18 @@
"configureDataSyncModal": {
"title": "Data sync",
"syncedFields": "Synced fields",
"syncSettings": "Sync settings"
"syncSettings": "Sync settings",
"syncHistory": "Sync history"
},
"dataSyncRuns": {
"title": "Sync history",
"description": "The most recent sync runs of this table, no matter who or what started them.",
"previousRuns": "Previous runs",
"noRuns": "This table hasn't been synced yet.",
"triggerManual": "Manual",
"triggerPeriodic": "Periodic",
"byUser": "by {name}",
"duration": "{seconds}s"
},
"configureDataSyncVisibleFields": {
"title": "Change synced fields",
+5
View File
@@ -358,6 +358,7 @@ import {
import {
SyncedFieldsConfigureDataSyncType,
SettingsConfigureDataSyncType,
SyncHistoryConfigureDataSyncType,
} from '@baserow/modules/database/configureDataSyncTypes'
import { DatabaseGuidedTourType } from '@baserow/modules/database/guidedTourTypes'
import {
@@ -1067,6 +1068,10 @@ export default defineNuxtPlugin({
'configureDataSync',
new SettingsConfigureDataSyncType(context)
)
$registry.register(
'configureDataSync',
new SyncHistoryConfigureDataSyncType(context)
)
$registry.register('guidedTour', new DatabaseGuidedTourType(context))
@@ -12,6 +12,18 @@ export default (client) => {
syncTable(dataSyncId) {
return client.post(`/database/data-sync/${dataSyncId}/sync/async/`)
},
fetchSyncJobs(dataSyncId, { limit = 10, offset = 0, states = null } = {}) {
const params = {
type: 'sync_data_sync_table',
sync_data_sync_table_data_sync_id: dataSyncId,
limit,
offset,
}
if (states) {
params.states = states.join(',')
}
return client.get(`/jobs/`, { params })
},
fetchProperties(values) {
return client.post(`/database/data-sync/properties/`, values)
},
@@ -0,0 +1,43 @@
import { vi } from 'vitest'
import { TestApp } from '@baserow/test/helpers/testApp'
import jobMixin from '@baserow/modules/core/mixins/job'
describe('job mixin', () => {
let testApp = null
beforeEach(() => {
testApp = new TestApp()
})
afterEach(() => {
testApp.afterEach()
})
test('onJobCancelFailed is called when the cancellation request fails', async () => {
testApp.dontFailOnErrorResponses()
const onJobCancelFailed = vi.fn()
const showError = vi.fn()
const TestComponent = {
template: '<div></div>',
mixins: [jobMixin],
methods: { onJobCancelFailed, showError },
}
const wrapper = await testApp.mount(TestComponent, {})
wrapper.vm.job = await testApp.store.dispatch('job/create', {
id: 1,
type: 'export_applications',
state: 'started',
progress_percentage: 10,
})
testApp.mockServer.mock
.onPost('/jobs/1/cancel/')
.reply(400, { error: 'ERROR_SOMETHING', detail: '' })
await wrapper.vm.cancelJob()
expect(showError).toHaveBeenCalled()
expect(onJobCancelFailed).toHaveBeenCalled()
})
})
@@ -0,0 +1,180 @@
import { flushPromises } from '@vue/test-utils'
import { TestApp } from '@baserow/test/helpers/testApp'
import ConfigureDataSyncHistory from '@baserow/modules/database/components/dataSync/ConfigureDataSyncHistory'
import { createSyncJob } from '@baserow/test/unit/database/components/dataSync/helpers'
describe('ConfigureDataSyncHistory', () => {
let testApp = null
let mockServer = null
beforeEach(() => {
testApp = new TestApp()
mockServer = testApp.mockServer
})
afterEach(() => {
testApp.afterEach()
})
const database = { id: 10, workspace: { id: 1 } }
const table = { id: 20, name: 'Synced', data_sync: { id: 42 } }
test('renders running, failed and finished runs', async () => {
mockServer.fakeJobs({
jobs: [
createSyncJob({ id: 3, state: 'started', progress_percentage: 40 }),
createSyncJob({
id: 2,
state: 'failed',
triggered_by: 'periodic',
user_name: 'Periodic user',
human_readable_error: 'The sync failed badly.',
}),
createSyncJob({ id: 1, state: 'finished' }),
],
})
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
const items = wrapper.findAll('.data-sync-runs__item')
expect(items).toHaveLength(3)
expect(items.at(0).html()).toContain('job.stateStarted')
expect(items.at(0).find('.progress-bar').exists()).toBe(false)
expect(items.at(0).find('.data-sync-runs__duration').text()).toBe('40%')
expect(items.at(1).html()).toContain('job.stateFailed')
expect(items.at(1).html()).toContain('dataSyncRuns.triggerPeriodic')
expect(items.at(1).html()).toContain('dataSyncRuns.byUser')
// Error details are exposed through an accessible disclosure button.
const errorToggle = items.at(1).find('.data-sync-runs__head')
expect(errorToggle.element.tagName).toBe('BUTTON')
expect(errorToggle.attributes('type')).toBe('button')
expect(errorToggle.attributes('aria-expanded')).toBe('false')
expect(items.at(1).find('.data-sync-runs__error').exists()).toBe(false)
await errorToggle.trigger('click')
expect(errorToggle.attributes('aria-expanded')).toBe('true')
expect(items.at(1).find('.data-sync-runs__error').text()).toBe(
'The sync failed badly.'
)
expect(items.at(2).html()).toContain('job.stateFinished')
expect(items.at(2).html()).toContain('dataSyncRuns.triggerManual')
expect(items.at(2).find('.data-sync-runs__head').element.tagName).toBe(
'DIV'
)
})
test('seeds unfinished jobs into the job store', async () => {
mockServer.fakeJobs({
jobs: [
createSyncJob({ id: 1, state: 'started', progress_percentage: 40 }),
createSyncJob({ id: 3, state: 'finished' }),
],
})
await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
const storeJobIds = testApp.store.getters['job/getAll'].map((job) => job.id)
expect(storeJobIds).toContain(1)
expect(storeJobIds).not.toContain(3)
})
test('shows the empty state when there are no runs', async () => {
mockServer.fakeJobs({ jobs: [] })
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
expect(wrapper.html()).toContain('dataSyncRuns.noRuns')
})
test('paginates when there are more runs than the page size', async () => {
mockServer.fakeJobs({
jobs: Array.from({ length: 10 }, (_, index) =>
createSyncJob({ id: 100 - index, state: 'finished' })
),
count: 25,
})
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
expect(wrapper.findAll('.data-sync-runs__item')).toHaveLength(10)
expect(wrapper.find('.paginator').exists()).toBe(true)
})
test('hides the paginator when everything fits one page', async () => {
mockServer.fakeJobs({
jobs: [createSyncJob({ id: 1, state: 'finished' })],
count: 1,
})
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
expect(wrapper.find('.paginator').exists()).toBe(false)
})
test('shows an error when the runs cannot be loaded', async () => {
testApp.dontFailOnErrorResponses()
mockServer.mock
.onGet('jobs/')
.reply(400, { error: 'ERROR_SOMETHING', detail: '' })
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
expect(wrapper.find('.alert').exists()).toBe(true)
expect(wrapper.find('.data-sync-runs').exists()).toBe(false)
})
test('hides a stale loading error after a successful retry', async () => {
testApp.dontFailOnErrorResponses()
const firstPage = Array.from({ length: 10 }, (_, index) =>
createSyncJob({ id: 100 - index, state: 'finished' })
)
mockServer.mock.onGet('jobs/').replyOnce(200, {
jobs: firstPage,
count: 20,
})
mockServer.mock
.onGet('jobs/')
.replyOnce(400, { error: 'ERROR_SOMETHING', detail: '' })
mockServer.mock.onGet('jobs/').replyOnce(200, {
jobs: [createSyncJob({ id: 1, state: 'finished' })],
count: 20,
})
const wrapper = await testApp.mount(ConfigureDataSyncHistory, {
propsData: { database, table },
})
await flushPromises()
const nextPageButton = () => wrapper.findAll('.paginator__button').at(1)
await nextPageButton().trigger('click')
await flushPromises()
expect(wrapper.find('.alert').exists()).toBe(true)
await nextPageButton().trigger('click')
await flushPromises()
expect(wrapper.find('.alert').exists()).toBe(false)
expect(wrapper.findAll('.data-sync-runs__item')).toHaveLength(1)
})
})
@@ -0,0 +1,13 @@
export function createSyncJob(values) {
return {
type: 'sync_data_sync_table',
progress_percentage: 100,
human_readable_error: '',
created_on: '2026-07-10T10:00:00Z',
updated_on: '2026-07-10T10:00:30Z',
triggered_by: 'manual',
user_name: 'John',
data_sync: { id: 42 },
...values,
}
}
@@ -0,0 +1,62 @@
import { flushPromises } from '@vue/test-utils'
import { TestApp } from '@baserow/test/helpers/testApp'
import SyncTableModal from '@baserow/modules/database/components/dataSync/SyncTableModal'
import { createSyncJob } from '@baserow/test/unit/database/components/dataSync/helpers'
describe('SyncTableModal', () => {
let testApp = null
let mockServer = null
beforeEach(() => {
testApp = new TestApp()
mockServer = testApp.mockServer
})
afterEach(() => {
testApp.afterEach()
})
const table = { id: 20, name: 'Synced', data_sync: { id: 42 } }
test('shows previous runs and attaches to an in-flight one', async () => {
mockServer.fakeJobs({
jobs: [
createSyncJob({
id: 7,
state: 'started',
progress_percentage: 60,
triggered_by: 'periodic',
user_name: 'Periodic user',
}),
createSyncJob({ id: 6, state: 'finished' }),
],
})
const wrapper = await testApp.mount(SyncTableModal, {
propsData: { table },
})
await wrapper.vm.show()
await flushPromises()
expect(wrapper.html()).toContain('dataSyncRuns.previousRuns')
expect(wrapper.findAll('.data-sync-runs__item')).toHaveLength(2)
expect(wrapper.find('button[disabled]').exists()).toBe(true)
expect(testApp.store.getters['job/get'](7)).toBeTruthy()
})
test('stays idle when no sync run is in flight', async () => {
mockServer.fakeJobs({
jobs: [createSyncJob({ id: 6, state: 'finished' })],
})
const wrapper = await testApp.mount(SyncTableModal, {
propsData: { table },
})
await wrapper.vm.show()
await flushPromises()
expect(wrapper.findAll('.data-sync-runs__item')).toHaveLength(1)
expect(wrapper.find('button[disabled]').exists()).toBe(false)
})
})