Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
89f175c
feat(integrations): add model to track integration health status
afsuyadi Jul 4, 2026
3bdf907
feat(integrations): add services to provide method for third-party wr…
afsuyadi Jul 5, 2026
46dde6d
feat(integrations): add unit test for record_integration_health
afsuyadi Jul 6, 2026
6d6f0ce
feat(integrations): add method to retrieve latest integration health
afsuyadi Jul 6, 2026
433b73c
feat(integrations): add latest_health_field to base environment integ…
afsuyadi Jul 6, 2026
8aed422
feat(integrations): add latest_health field for meta class
afsuyadi Jul 6, 2026
f3233c3
feat(integrations): add unit test for integration common services and…
afsuyadi Jul 6, 2026
1f58eb4
feat(integrations): add types for ActiveIntegration interface
afsuyadi Jul 6, 2026
8033b4d
feat(integrations): add indicator for integration health status
afsuyadi Jul 6, 2026
a36895a
feat(integrations): add record_integration_health method for HTTP-bas…
afsuyadi Jul 6, 2026
b4cb0ae
feat(integrations): add unit tests for wrappers
afsuyadi Jul 7, 2026
fce7899
feat(integrations): add payload field to accomodate new serializer fo…
afsuyadi Jul 7, 2026
f90e7f7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
22d5bbb
fix(integrations): fix component by lint
afsuyadi Jul 8, 2026
590d7e4
fix(serializer): add type notation
afsuyadi Jul 9, 2026
2a372ac
fix(serializer): parameterize return type and use .pk instead of .id
afsuyadi Jul 9, 2026
dbf3a1e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
a3082a5
fix(integrations-newrelic): normalize base_url
afsuyadi Jul 9, 2026
581b8de
fix(integrations-newrelic): use try and except
afsuyadi Jul 9, 2026
a99eee6
fix(integrations): use try and except to prevent crash
afsuyadi Jul 9, 2026
6c3c86a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
99ff48e
fix(integrations-amplitude): add timeout for requests.post()
afsuyadi Jul 9, 2026
dff9cb2
fix(integrations-amlitude): use try and except
afsuyadi Jul 9, 2026
afc6a27
fix(integrations-datadog): use try and except
afsuyadi Jul 9, 2026
ab65d07
fix(integrations-dynatrace): use try and except
afsuyadi Jul 9, 2026
24e5f7c
fix(integrations-grafana): use try and except
afsuyadi Jul 9, 2026
a02158f
fix(integrations-heap): use try and except
afsuyadi Jul 9, 2026
a92e0b4
fix(integrations-mixpanel): use try and except
afsuyadi Jul 9, 2026
3de347f
fix(integrations-newrelic): use try and except
afsuyadi Jul 9, 2026
7967069
fix(integrations-webhook): use try and except
afsuyadi Jul 9, 2026
5920997
feat(docs): add guide on how to cleanup integration health record
afsuyadi Jul 9, 2026
94a845c
feat(integrations): add scheduled action to cleanup health records th…
afsuyadi Jul 9, 2026
3ca740e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
81dd7bb
feat(integrations): add Meta class for IntegrationHealthRecord class
afsuyadi Jul 9, 2026
0a0a4cf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
cb547ed
feat(integrations): add migration for health record indexing
afsuyadi Jul 9, 2026
30b2a54
fix(integrations-dynatrace): normalize base_url
afsuyadi Jul 9, 2026
4e6318d
fix(integrations-dynatrace): add timeout for requests.post()
afsuyadi Jul 9, 2026
a798310
fix(integrations-heap): add timeout for requests.post()
afsuyadi Jul 9, 2026
5bfd90d
fix(tests): add content_type when searching for health records
afsuyadi Jul 9, 2026
dba07f4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
dbbbe9a
fix(tests): add coverage for non-2xx status code
afsuyadi Jul 9, 2026
b640ed0
fix(tests): add None type for function
afsuyadi Jul 9, 2026
b00b090
fix(tests): assert result is not None
afsuyadi Jul 9, 2026
75696aa
fix(tests): add testing for anti-pattern
afsuyadi Jul 9, 2026
d76ce48
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 9, 2026
7ea716f
fix(integrations): fix import path
afsuyadi Jul 9, 2026
65152bb
fix(integrations): extract ternary expressions into a variable
afsuyadi Jul 9, 2026
8ae9c2b
fix(integrations): guard base_url when it's None
afsuyadi Jul 9, 2026
69a7b1b
fix(integrations): run lint
afsuyadi Jul 9, 2026
c6d4a6d
fix(integrations): address typing errors in unit tests from CI
afsuyadi Jul 16, 2026
c6cb750
fix(integrations): address typing errors in serializers tests from CI
afsuyadi Jul 16, 2026
cada674
fix(integrations): add guard if base_url is null
afsuyadi Jul 16, 2026
3b2a49e
fix(integrations): add type annotations
afsuyadi Jul 16, 2026
dd9a4f5
fix(integrations): add missing type annotations
afsuyadi Jul 16, 2026
125ab22
fix(tests): fix runtime bug
afsuyadi Jul 16, 2026
42fb57f
docs(event-catalogue): update changes based on CI
afsuyadi Jul 16, 2026
0311e07
fix(integrations): remove ternary expression on component
afsuyadi Jul 16, 2026
e585a76
fix(integrations): add separator for expected url
afsuyadi Jul 16, 2026
f36fea5
fix(tests): add separator for expected url and match assertions
afsuyadi Jul 16, 2026
7b1733d
fix(integrations): add savepoint
afsuyadi Jul 16, 2026
2f587fe
fix(tests): add unit test for cleanup health records function
afsuyadi Jul 16, 2026
2475be5
fix(tests): add exception-path tests to address codecov's review
afsuyadi Jul 16, 2026
d463141
chore: trigger CI re-run
afsuyadi Jul 16, 2026
daa92f6
fix(integrations): establish 3-colour dot for health tracking status …
afsuyadi Jul 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/app/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@
"integrations.gitlab",
"integrations.grafana",
"integrations.vcs",
"integrations.common",
# Rate limiting admin endpoints
"axes",
"telemetry",
Expand Down
28 changes: 5 additions & 23 deletions api/audit/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,7 @@ def send_audit_log_event_to_datadog(sender, instance, **kwargs): # type: ignore
if not data_dog_config:
return

data_dog = DataDogWrapper(
base_url=data_dog_config.base_url, # type: ignore[arg-type]
api_key=data_dog_config.api_key,
use_custom_source=data_dog_config.use_custom_source,
)
data_dog = DataDogWrapper(data_dog_config)
_track_event_async(instance, data_dog) # type: ignore[no-untyped-call]


Expand All @@ -156,11 +152,7 @@ def send_audit_log_event_to_new_relic(sender, instance, **kwargs): # type: igno
if not new_relic_config:
return

new_relic = NewRelicWrapper(
base_url=new_relic_config.base_url, # type: ignore[arg-type]
api_key=new_relic_config.api_key,
app_id=new_relic_config.app_id,
)
new_relic = NewRelicWrapper(new_relic_config)
_track_event_async(instance, new_relic) # type: ignore[no-untyped-call]


Expand All @@ -171,11 +163,7 @@ def send_audit_log_event_to_dynatrace(sender, instance, **kwargs): # type: igno
if not dynatrace_config:
return

dynatrace = DynatraceWrapper(
base_url=dynatrace_config.base_url, # type: ignore[arg-type]
api_key=dynatrace_config.api_key,
entity_selector=dynatrace_config.entity_selector,
)
dynatrace = DynatraceWrapper(dynatrace_config)
_track_event_async(instance, dynatrace) # type: ignore[no-untyped-call]


Expand All @@ -186,10 +174,7 @@ def send_audit_log_event_to_grafana(sender, instance, **kwargs): # type: ignore
if not grafana_config:
return

grafana = GrafanaWrapper(
base_url=grafana_config.base_url, # type: ignore[arg-type]
api_key=grafana_config.api_key,
)
grafana = GrafanaWrapper(grafana_config)
_track_event_async(instance, grafana) # type: ignore[no-untyped-call]


Expand Down Expand Up @@ -238,10 +223,7 @@ def send_audit_log_event_to_sentry(sender: FeatureState, **kwargs: Any) -> None:
).first()
if not config:
return
sentry = SentryChangeTracking(
webhook_url=config.webhook_url,
secret=config.secret,
)
sentry = SentryChangeTracking(config)
if event_data := sentry.generate_event_data(sender):
sentry.track_event_async(event=event_data)

Expand Down
29 changes: 29 additions & 0 deletions api/integrations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Integrations

## Integration Health Records Cleanup

Integration health records are stored to track the status of external integration calls. These records can grow over time. A management command is provided to clean up old records.

### Running the cleanup command

To delete integration health records older than 30 days (default):

```bash
python manage.py cleanup_integration_health_records
```

To specify a custom retention period:

```bash
python manage.py cleanup_integration_health_records --days=60
```

### Scheduling automatic cleanup

To prevent the `IntegrationHealthRecord` table from growing unbounded, schedule the cleanup command to run periodically using cron or your preferred task scheduler.

Example cron entry (runs daily at 3 AM):

```cron
0 3 * * * cd /path/to/flagsmith && python manage.py cleanup_integration_health_records
```
8 changes: 7 additions & 1 deletion api/integrations/amplitude/amplitude.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from environments.identities.models import Identity
from environments.identities.traits.models import Trait
from features.models import FeatureState
from integrations.common.services import record_integration_health
from integrations.common.wrapper import AbstractBaseIdentityIntegrationWrapper

from .models import AmplitudeConfiguration
Expand All @@ -18,13 +19,18 @@

class AmplitudeWrapper(AbstractBaseIdentityIntegrationWrapper[AmplitudeUserData]):
def __init__(self, config: AmplitudeConfiguration):
self.config = config
self.api_key = config.api_key
self.url = f"{config.base_url}/identify"

def _identify_user(self, user_data: AmplitudeUserData) -> None:
payload = {"api_key": self.api_key, "identification": json.dumps([user_data])}

response = requests.post(self.url, data=payload)
response = requests.post(self.url, data=payload, timeout=10)
try:
record_integration_health(self.config, response.status_code)
except Exception:
logger.warning("Failed to record Amplitude integration health")
logger.debug(
"Sent event to Amplitude. Response code was: %s" % response.status_code
)
Expand Down
2 changes: 1 addition & 1 deletion api/integrations/amplitude/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
class AmplitudeConfigurationSerializer(BaseEnvironmentIntegrationModelSerializer):
class Meta:
model = AmplitudeConfiguration
fields = ("id", "api_key", "base_url")
fields = ("id", "api_key", "base_url", "latest_health")
6 changes: 6 additions & 0 deletions api/integrations/common/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from django.apps import AppConfig


class IntegrationCommonConfig(AppConfig):
name = "integrations.common"
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from datetime import timedelta

from django.core.management import BaseCommand, CommandParser
from django.utils import timezone

from integrations.common.models import IntegrationHealthRecord


class Command(BaseCommand):
help = "Delete integration health records older than the specified number of days."

def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
"--days",
type=int,
default=30,
help="Delete records older than this many days (default: 30).",
)

def handle(self, *args, **options): # type: ignore[no-untyped-def]
days = options["days"]
cutoff = timezone.now() - timedelta(days=days)
deleted, _ = IntegrationHealthRecord.objects.filter(
created_at__lt=cutoff
).delete()
self.stdout.write(
f"Deleted {deleted} integration health record(s) older than {days} days."
)
43 changes: 43 additions & 0 deletions api/integrations/common/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Generated by Django 5.2.15 on 2026-07-04 10:38

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
("contenttypes", "0002_remove_content_type_name"),
]

operations = [
migrations.CreateModel(
name="IntegrationHealthRecord",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"created_at",
models.DateTimeField(auto_now_add=True, verbose_name="Created At"),
),
("object_id", models.PositiveIntegerField()),
("status_code", models.PositiveIntegerField()),
(
"content_type",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="contenttypes.contenttype",
),
),
],
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 5.2.15 on 2026-07-09 01:26

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("common", "0001_initial"),
("contenttypes", "0002_remove_content_type_name"),
]

operations = [
migrations.AddIndex(
model_name="integrationhealthrecord",
index=models.Index(
fields=["content_type", "object_id", "-created_at"],
name="common_inte_content_bd807d_idx",
),
),
]
Empty file.
15 changes: 15 additions & 0 deletions api/integrations/common/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_lifecycle import ( # type: ignore[import-untyped]
AFTER_SAVE,
Expand Down Expand Up @@ -40,3 +42,16 @@ def write_environment_to_dynamodb(self): # type: ignore[no-untyped-def]
@hook(AFTER_UPDATE)
def clear_environment_cache(self): # type: ignore[no-untyped-def]
self.environment.clear_environment_cache()


class IntegrationHealthRecord(models.Model):
created_at = models.DateTimeField("Created At", auto_now_add=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
status_code = models.PositiveIntegerField()
Comment thread
afsuyadi marked this conversation as resolved.

class Meta:
indexes = [
models.Index(fields=["content_type", "object_id", "-created_at"]),
]
7 changes: 7 additions & 0 deletions api/integrations/common/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import typing

from django.db.models import Model
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from .services import get_latest_integration_health


class _BaseIntegrationModelSerializer(ModelSerializer): # type: ignore[type-arg]
one_to_one_field_name = None
Expand Down Expand Up @@ -31,6 +34,10 @@ def _get_existing_integration_model_obj(

class BaseEnvironmentIntegrationModelSerializer(_BaseIntegrationModelSerializer):
one_to_one_field_name = "environment" # type: ignore[assignment]
latest_health = SerializerMethodField()

def get_latest_health(self, obj: Model) -> dict[str, typing.Any] | None:
return get_latest_integration_health(obj)


class BaseProjectIntegrationModelSerializer(_BaseIntegrationModelSerializer):
Expand Down
45 changes: 45 additions & 0 deletions api/integrations/common/services.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import logging
from typing import Any

from django.contrib.contenttypes.models import ContentType
from django.db import models, transaction

from integrations.common.models import IntegrationHealthRecord

logger = logging.getLogger(__name__)


def record_integration_health(
integration_config: models.Model,
status_code: int,
) -> None:
try:
with transaction.atomic():
IntegrationHealthRecord.objects.create(
content_object=integration_config,
status_code=status_code,
)
except Exception:
logger.exception("Failed to record integration health.")


def get_latest_integration_health(
integration_config: models.Model,
) -> dict[str, Any] | None:
latest_record = (
IntegrationHealthRecord.objects.filter(
content_type=ContentType.objects.get_for_model(integration_config),
object_id=integration_config.pk,
)
.order_by("-created_at")
.first()
)

if not latest_record:
return None

return {
"status_code": latest_record.status_code,
"is_healthy": 200 <= latest_record.status_code < 300,
"created_at": latest_record.created_at,
}
20 changes: 12 additions & 8 deletions api/integrations/datadog/datadog.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import requests

from audit.models import AuditLog
from integrations.common.services import record_integration_health
from integrations.common.wrapper import AbstractBaseEventIntegrationWrapper
from integrations.datadog.models import DataDogConfiguration

logger = logging.getLogger(__name__)

Expand All @@ -15,18 +17,15 @@
class DataDogWrapper(AbstractBaseEventIntegrationWrapper):
def __init__(
self,
base_url: str,
api_key: str,
config: DataDogConfiguration,
session: requests.Session = None, # type: ignore[assignment]
use_custom_source: bool = False,
) -> None:
self.base_url = base_url
if self.base_url[-1] != "/":
self.base_url += "/"
self.config = config
self.base_url = (config.base_url or "").rstrip("/") + "/"
self.events_url = f"{self.base_url}{EVENTS_API_URI}"
self.use_custom_source = use_custom_source
self.use_custom_source = config.use_custom_source

self.api_key = api_key
self.api_key = config.api_key
self.session = session or requests.Session()

@staticmethod
Expand All @@ -48,6 +47,11 @@ def _track_event(self, event: dict) -> None: # type: ignore[type-arg]
response = self.session.post(
f"{self.events_url}?api_key={self.api_key}", data=json.dumps(event)
)

try:
record_integration_health(self.config, response.status_code)
except Exception:
logger.warning("Failed to record DataDog integration health")
logger.debug(
"Sent event to DataDog. Response code was %s" % response.status_code
)
Loading
Loading