The platform for continuously improving AI agents.
"""Versioned sync-config creation for connectors."""
from __future__ import annotations
from typing import Any
from django.db import transaction
from django.utils import timezone
from overbae.services.connectors.sync import restart_connector_import
_UNSET = object()
def save_sync_config(
credential,
*,
source_project_id: str = "",
target_project=None,
lookback_days: Any = _UNSET,
backfill_from: Any = _UNSET,
backfill_to: Any = _UNSET,
) -> Any:
"""Create the next config version and restart the import for it. A save that changes
nothing returns the config in force, and the import carries on."""
from overbae.models import ConnectorSyncConfig
prev = credential.active_config()
values = {
"source_project_id": source_project_id or (prev.source_project_id if prev else ""),
"target_project": target_project or (prev.target_project if prev else None),
"lookback_days": lookback_days
if lookback_days is not _UNSET
else (prev.lookback_days if prev else None),
"backfill_from": prev.backfill_from
if backfill_from is _UNSET and prev
else (None if backfill_from is _UNSET else backfill_from),
"backfill_to": prev.backfill_to
if backfill_to is _UNSET and prev
else (None if backfill_to is _UNSET else backfill_to),
}
if prev is not None and all(getattr(prev, field) == value for field, value in values.items()):
return prev
# The new version and the restart land together: a version whose import never
# restarted would be skipped by every later retry.
with transaction.atomic():
config = ConnectorSyncConfig.objects.create(
credential=credential,
version=(prev.version + 1) if prev else 1,
effective_from=timezone.now(),
**values,
)
if prev is not None:
# Each save compares with the version it replaced, so concurrent saves still see
# a source change.
restart_connector_import(
credential, source_changed=config.source_project_id != prev.source_project_id
)
if prev is None and credential.auto_sync_enabled:
# First config + auto-sync: kick a normal backfill.
from overbae.tasks.connector_sync import sync_connector_chunk
type(credential).objects.filter(pk=credential.pk).update(next_poll_at=None)
sync_connector_chunk.apply_async(args=[str(credential.id)])
return config