Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement instagram source (#73782)

Tom Owers42b7e2bad59b
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 7620085ab95b..cc23d7ab73c4 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -73,6 +73,7 @@ export interface integrationsLogicValues {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -154,6 +155,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -266,6 +268,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -318,6 +321,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -387,6 +391,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -443,6 +448,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -492,6 +498,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -552,6 +559,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -597,6 +605,7 @@ export interface integrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -661,6 +670,7 @@ export interface integrationsLogicMeta {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index 50f62c986ef2..48f948f99a8e 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -20,6 +20,7 @@ import IconGoogleSheets from 'public/services/google-sheets.svg'
import IconGoogleAnalytics from 'public/services/google_analytics.png'
import IconGoogleCalendar from 'public/services/google_calendar.png'
import IconHubspot from 'public/services/hubspot.png'
+import IconInstagram from 'public/services/instagram.png'
import IconIntercom from 'public/services/intercom.png'
import IconJira from 'public/services/jira.svg'
import IconLinear from 'public/services/linear.png'
@@ -61,6 +62,7 @@ export const ICONS: Record<IntegrationKind, any> = {
github: IconGitHub,
gitlab: IconGitLab,
'meta-ads': IconMetaAds,
+ instagram: IconInstagram,
twilio: IconTwilio,
clickup: IconClickUp,
'reddit-ads': IconReddit,
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a6ad197cd70f..69c9fd7849a1 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28471,6 +28471,7 @@
"github",
"gitlab",
"meta-ads",
+ "instagram",
"clickup",
"reddit-ads",
"databricks",
diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
index 18cd2969522a..5f87a978bd65 100644
--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
@@ -36,6 +36,7 @@ export interface organizationIntegrationsLogicValues {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -106,6 +107,7 @@ export interface organizationIntegrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -158,6 +160,7 @@ export interface organizationIntegrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -211,6 +214,7 @@ export interface organizationIntegrationsLogicMeta {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index 12fd14cff84c..2067b447ae91 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -142,6 +142,7 @@ export interface personalIntegrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -194,6 +195,7 @@ export interface personalIntegrationsLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 40b0b9560b28..751173337d0f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5472,6 +5472,7 @@ export const INTEGRATION_KINDS = [
'github',
'gitlab',
'meta-ads',
+ 'instagram',
'clickup',
'reddit-ads',
'databricks',
diff --git a/posthog/migrations/1297_add_instagram_integration_kind.py b/posthog/migrations/1297_add_instagram_integration_kind.py
new file mode 100644
index 000000000000..7b6abb677440
--- /dev/null
+++ b/posthog/migrations/1297_add_instagram_integration_kind.py
@@ -0,0 +1,67 @@
+# Generated by Django 5.2.14 on 2026-08-05 12:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1296_backfill_cimd_verification_token_url"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="integration",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("anthropic", "Anthropic"),
+ ("apns", "Apple Push"),
+ ("aws-redshift", "Aws Redshift"),
+ ("aws-s3", "Aws S3"),
+ ("azure-blob", "Azure Blob"),
+ ("bing-ads", "Bing Ads"),
+ ("clickup", "Clickup"),
+ ("customerio-app", "Customerio App"),
+ ("customerio-track", "Customerio Track"),
+ ("customerio-webhook", "Customerio Webhook"),
+ ("databricks", "Databricks"),
+ ("email", "Email"),
+ ("firebase", "Firebase"),
+ ("github", "Github"),
+ ("gitlab", "Gitlab"),
+ ("google-ads", "Google Ads"),
+ ("google-analytics", "Google Analytics"),
+ ("google-calendar", "Google Calendar"),
+ ("google-cloud-service-account", "Google Cloud Service Account"),
+ ("google-cloud-storage", "Google Cloud Storage"),
+ ("google-pubsub", "Google Pubsub"),
+ ("google-search-console", "Google Search Console"),
+ ("google-sheets", "Google Sheets"),
+ ("hubspot", "Hubspot"),
+ ("instagram", "Instagram"),
+ ("intercom", "Intercom"),
+ ("jira", "Jira"),
+ ("linear", "Linear"),
+ ("linkedin-ads", "Linkedin Ads"),
+ ("meta-ads", "Meta Ads"),
+ ("pardot", "Pardot"),
+ ("pinterest-ads", "Pinterest Ads"),
+ ("postgresql", "Postgresql"),
+ ("posthog", "Posthog"),
+ ("reddit-ads", "Reddit Ads"),
+ ("resend", "Resend"),
+ ("s3-compatible", "S3 Compatible"),
+ ("salesforce", "Salesforce"),
+ ("slack", "Slack"),
+ ("slack-posthog-code", "Slack Posthog Code"),
+ ("snapchat", "Snapchat"),
+ ("snowflake", "Snowflake"),
+ ("stripe", "Stripe"),
+ ("tiktok-ads", "Tiktok Ads"),
+ ("twilio", "Twilio"),
+ ("vercel", "Vercel"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 6b2a402fe98a..6a06ee7a3e31 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1296_backfill_cimd_verification_token_url
+1297_add_instagram_integration_kind
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 69916a7cc196..a15a28862362 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -503,6 +503,17 @@ def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn
ERROR_TOKEN_REFRESH_FAILED = "TOKEN_REFRESH_FAILED"
+# Graph API version the Instagram OAuth dialog, token exchange and refresh are pinned to. Kept in
+# step with the warehouse Instagram source's `default_version`, which calls the same Graph version.
+INSTAGRAM_GRAPH_API_VERSION = "v23.0"
+
+# Instagram API with Facebook Login: the professional account is reached through the Facebook Page
+# it is linked to, so the grant needs the page permissions as well as the Instagram ones.
+# https://developers.facebook.com/docs/instagram-platform/instagram-api-with-facebook-login
+INSTAGRAM_OAUTH_SCOPE = (
+ "instagram_basic instagram_manage_insights instagram_manage_comments pages_show_list pages_read_engagement"
+)
+
class IntegrationQuerySet(models.QuerySet["Integration"]):
def for_github_installation_id(self, installation_id: str | int) -> Self:
@@ -562,6 +573,7 @@ class Integration(models.Model):
GOOGLE_SEARCH_CONSOLE = "google-search-console"
GOOGLE_SHEETS = "google-sheets"
HUBSPOT = "hubspot"
+ INSTAGRAM = "instagram"
INTERCOM = "intercom"
JIRA = "jira"
LINEAR = "linear"
@@ -840,6 +852,7 @@ class OauthIntegration:
"tiktok-ads",
"bing-ads",
"meta-ads",
+ "instagram",
"intercom",
"linear",
"clickup",
@@ -1168,6 +1181,24 @@ class OauthIntegration:
id_path="id",
name_path="name",
)
+ elif kind == "instagram":
+ if not settings.INSTAGRAM_APP_CLIENT_ID or not settings.INSTAGRAM_APP_CLIENT_SECRET:
+ raise NotImplementedError("Instagram app not configured")
+
+ # Same Facebook Login endpoints as Meta Ads, and the credentials may even be the same
+ # Meta app, but the two grants request different scopes so they stay separate kinds.
+ # The token response carries no account identifier, so id/name come from `/me`.
+ return OauthConfig(
+ authorize_url=f"https://www.facebook.com/{INSTAGRAM_GRAPH_API_VERSION}/dialog/oauth",
+ token_url=f"https://graph.facebook.com/{INSTAGRAM_GRAPH_API_VERSION}/oauth/access_token",
+ token_info_url=f"https://graph.facebook.com/{INSTAGRAM_GRAPH_API_VERSION}/me",
+ token_info_config_fields=["id", "name"],
+ client_id=settings.INSTAGRAM_APP_CLIENT_ID,
+ client_secret=settings.INSTAGRAM_APP_CLIENT_SECRET,
+ scope=INSTAGRAM_OAUTH_SCOPE,
+ id_path="id",
+ name_path="name",
+ )
elif kind == "reddit-ads":
if not settings.REDDIT_ADS_CLIENT_ID or not settings.REDDIT_ADS_CLIENT_SECRET:
raise NotImplementedError("Reddit Ads app not configured")
@@ -3983,13 +4014,21 @@ class GitLabIntegration:
return {"issue_id": issue["iid"]}
-class MetaAdsIntegration:
+class MetaGraphIntegration:
+ """Token handling shared by the Meta Graph OAuth kinds (Meta Ads, Instagram).
+
+ Meta issues no refresh token: a long-lived user access token is swapped for a fresh one
+ through the `fb_exchange_token` grant, which is why these kinds sit outside the generic
+ `OauthIntegration` refresh sweep and refresh on use instead.
+ """
+
integration: Integration
+ kind: str = ""
api_version: str = "v25.0"
def __init__(self, integration: Integration) -> None:
- if integration.kind != "meta-ads":
- raise Exception("MetaAdsIntegration init called with Integration with wrong 'kind'")
+ if integration.kind != self.kind:
+ raise Exception(f"{type(self).__name__} init called with Integration with wrong 'kind'")
self.integration = integration
def refresh_access_token(self):
@@ -4041,6 +4080,15 @@ class MetaAdsIntegration:
self.integration.save()
+class MetaAdsIntegration(MetaGraphIntegration):
+ kind = "meta-ads"
+
+
+class InstagramIntegration(MetaGraphIntegration):
+ kind = "instagram"
+ api_version = INSTAGRAM_GRAPH_API_VERSION
+
+
class TwilioIntegration:
integration: Integration
twilio_provider: TwilioProvider
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index e98ab81c65e9..73410cd1a228 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -48,6 +48,7 @@ from posthog.models.integration import (
GoogleAdsIntegration,
GoogleCloudIntegration,
GoogleCloudServiceAccountIntegration,
+ InstagramIntegration,
Integration,
JiraIntegration,
LinearIntegration,
@@ -4632,3 +4633,62 @@ class TestPardotIntegrationModel(BaseTest):
assert integration.integration_id == "https://acme.my.salesforce.com"
assert integration.config["expires_in"] == 3600
+
+
+@override_settings(INSTAGRAM_APP_CLIENT_ID="instagram-client-id", INSTAGRAM_APP_CLIENT_SECRET="instagram-client-secret")
+class TestInstagramIntegrationModel(BaseTest):
+ def test_oauth_config(self):
+ config = OauthIntegration.oauth_config_for_kind("instagram")
+
+ assert config.authorize_url == "https://www.facebook.com/v23.0/dialog/oauth"
+ assert config.token_url == "https://graph.facebook.com/v23.0/oauth/access_token"
+ assert config.token_info_url == "https://graph.facebook.com/v23.0/me"
+ assert config.client_id == "instagram-client-id"
+ assert config.client_secret == "instagram-client-secret"
+ assert config.id_path == "id"
+ assert config.name_path == "name"
+ # Instagram is reached through the Facebook page it is linked to, so the page scopes
+ # are as load-bearing as the Instagram ones.
+ assert set(config.scope.split(" ")) == {
+ "instagram_basic",
+ "instagram_manage_insights",
+ "instagram_manage_comments",
+ "pages_show_list",
+ "pages_read_engagement",
+ }
+
+ @override_settings(INSTAGRAM_APP_CLIENT_ID="", INSTAGRAM_APP_CLIENT_SECRET="")
+ def test_oauth_config_unconfigured_raises(self):
+ with pytest.raises(NotImplementedError, match="Instagram app not configured"):
+ OauthIntegration.oauth_config_for_kind("instagram")
+
+ def test_the_instagram_grant_is_separate_from_the_meta_ads_one(self):
+ # Both ride the same Meta app, but an ads grant carries none of the Instagram scopes,
+ # so pointing the Instagram source at a meta-ads integration must not be possible.
+ integration = Integration.objects.create(team=self.team, kind="meta-ads", integration_id="1")
+
+ with pytest.raises(Exception, match="wrong 'kind'"):
+ InstagramIntegration(integration)
+
+ @patch("posthog.models.integration.requests.post")
+ def test_refresh_exchanges_the_long_lived_token_rather_than_a_refresh_token(self, mock_post):
+ # Meta issues no refresh token: the current access token is swapped for a fresh one.
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="instagram",
+ integration_id="fb-user-1",
+ config={"expires_in": 100, "refreshed_at": int(time.time()) - 90},
+ sensitive_config={"access_token": "old-token"},
+ )
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {"access_token": "new-token", "expires_in": 5184000}
+
+ InstagramIntegration(integration).refresh_access_token()
+
+ sent = mock_post.call_args.kwargs["data"]
+ assert sent["grant_type"] == "fb_exchange_token"
+ assert sent["fb_exchange_token"] == "old-token"
+ assert sent["client_id"] == "instagram-client-id"
+ integration.refresh_from_db()
+ assert integration.sensitive_config["access_token"] == "new-token"
+ assert integration.errors == ""
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index b69ad8b37446..b342e6436250 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2874,6 +2874,7 @@ class IntegrationKind(StrEnum):
GITHUB = "github"
GITLAB = "gitlab"
META_ADS = "meta-ads"
+ INSTAGRAM = "instagram"
CLICKUP = "clickup"
REDDIT_ADS = "reddit-ads"
DATABRICKS = "databricks"
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 73a05cf3d467..5693c77cb5fb 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -72,6 +72,11 @@ STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS = get_list(get_from_env("STAMPHOG_SANDBOX_
META_ADS_APP_CLIENT_ID = get_from_env("META_ADS_APP_CLIENT_ID", "")
META_ADS_APP_CLIENT_SECRET = get_from_env("META_ADS_APP_CLIENT_SECRET", "")
+# Instagram professional accounts authorize through Facebook Login, so these may point at the
+# same Meta app as META_ADS_APP_* — the two grants differ only in the scopes they request.
+INSTAGRAM_APP_CLIENT_ID = get_from_env("INSTAGRAM_APP_CLIENT_ID", "")
+INSTAGRAM_APP_CLIENT_SECRET = get_from_env("INSTAGRAM_APP_CLIENT_SECRET", "")
+
BING_ADS_CLIENT_ID = get_from_env("BING_ADS_CLIENT_ID", "")
BING_ADS_CLIENT_SECRET = get_from_env("BING_ADS_CLIENT_SECRET", "")
BING_ADS_CLIENT_ID_FALLBACK = get_from_env("BING_ADS_CLIENT_ID_FALLBACK", "")
diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.py
index fbcc6062d551..dfa892fa0b1a 100644
--- a/posthog/tasks/integrations.py
+++ b/posthog/tasks/integrations.py
@@ -23,9 +23,11 @@ def refresh_integrations() -> int:
# refreshes are minted on demand under a Postgres row lock by the sync path
# (resolve_resend_oauth_token). This unlocked periodic sweep would race that path and
# double-spend the rotating token, so it must not refresh Resend.
+ # The Meta kinds are excluded because their grants carry no refresh token: a long-lived token is
+ # re-exchanged on use by `MetaGraphIntegration.refresh_access_token` rather than by this sweep.
oauth_integrations = defer_repository_cache_fields(
Integration.objects.filter(kind__in=OauthIntegration.supported_kinds)
- .exclude(kind__in=["meta-ads", "resend"])
+ .exclude(kind__in=["meta-ads", "instagram", "resend"])
.all()
)
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.ts
index 5d9bd0d8fcdc..20fbaaa10a52 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts
@@ -98,6 +98,7 @@ export interface alertNotificationLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -150,6 +151,7 @@ export interface alertNotificationLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 802b4b8ca1cd..bc5cf15379ee 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -4667,6 +4667,7 @@ export const IntegrationKindApi = {
Github: 'github',
Gitlab: 'gitlab',
MetaAds: 'meta-ads',
+ Instagram: 'instagram',
Clickup: 'clickup',
RedditAds: 'reddit-ads',
Databricks: 'databricks',
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index 1861118bb417..7d28aeb90794 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -175,6 +175,7 @@ export interface RoleLookupResponseApi {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -224,6 +225,7 @@ export const IntegrationKindEnumApi = {
GoogleSearchConsole: 'google-search-console',
GoogleSheets: 'google-sheets',
Hubspot: 'hubspot',
+ Instagram: 'instagram',
Intercom: 'intercom',
Jira: 'jira',
Linear: 'linear',
@@ -491,6 +493,7 @@ export interface IntegrationAccessRequestApi {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -652,6 +655,7 @@ export type IntegrationsListParams = {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -712,6 +716,7 @@ export const IntegrationsListKind = {
GoogleSearchConsole: 'google-search-console',
GoogleSheets: 'google-sheets',
Hubspot: 'hubspot',
+ Instagram: 'instagram',
Intercom: 'intercom',
Jira: 'jira',
Linear: 'linear',
diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.ts
index 4423d92915fe..7cb41e6a8ba2 100644
--- a/products/integrations/frontend/generated/api.zod.ts
+++ b/products/integrations/frontend/generated/api.zod.ts
@@ -86,6 +86,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -109,7 +110,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -143,6 +144,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -167,7 +169,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -201,6 +203,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -224,7 +227,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -265,6 +268,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -288,7 +292,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -376,6 +380,7 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -399,10 +404,10 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
)
.describe(
- "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel"
+ "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel"
),
reason: zod
.string()
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
index 6cc52c4cf88a..f4e6cf7f3402 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
@@ -93,6 +93,7 @@ export interface logsAlertNotificationLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -145,6 +146,7 @@ export interface logsAlertNotificationLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 9249c66edea0..6b837165e84e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -136,6 +136,7 @@ export interface taskTrackerSceneLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -188,6 +189,7 @@ export interface taskTrackerSceneLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index b6fbe27ad4e8..951c45a0523e 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3997,6 +3997,7 @@ export const IntegrationKindApi = {
Github: 'github',
Gitlab: 'gitlab',
MetaAds: 'meta-ads',
+ Instagram: 'instagram',
Clickup: 'clickup',
RedditAds: 'reddit-ads',
Databricks: 'databricks',
diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
index 300eda18b3c9..47cfd435e26a 100644
--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
@@ -82,6 +82,7 @@ export interface visualReviewSettingsSceneLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
@@ -134,6 +135,7 @@ export interface visualReviewSettingsSceneLogicActions {
| 'google-search-console'
| 'google-sheets'
| 'hubspot'
+ | 'instagram'
| 'intercom'
| 'jira'
| 'linear'
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 5e0b78a407c8..eac6b4180417 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -339,6 +339,7 @@ the row lists both.
| inflowinventory | HTTP | requests | ✅ |
| inngest | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
+| instagram | HTTP | requests | ✅ |
| instana | HTTP | requests | ✅ |
| instantly | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| instatus | HTTP | requests | ✅ |
@@ -1072,7 +1073,6 @@ doesn't conflict with concurrent PRs.
- influxdb_cloud
- infor_nexus
- insightful
-- instagram
- interzoid
- inth
- iyzico
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instagram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instagram.py
index 91ad9b89dd37..df552ddc7b27 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instagram.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instagram.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class InstagramSourceConfig(config.Config):
- pass
+ instagram_account_id: str
+ instagram_integration_id: int = config.value(converter=config.str_to_int)
+ start_date: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/canonical_descriptions.py
new file mode 100644
index 000000000000..85b738500b51
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/canonical_descriptions.py
@@ -0,0 +1,100 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_USER_DOCS = "https://developers.facebook.com/docs/instagram-platform/instagram-graph-api/reference/ig-user/"
+_MEDIA_DOCS = "https://developers.facebook.com/docs/instagram-platform/reference/instagram-media/"
+_COMMENT_DOCS = "https://developers.facebook.com/docs/instagram-platform/reference/instagram-comment/"
+_INSIGHTS_DOCS = "https://developers.facebook.com/docs/instagram-platform/insights/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "account": {
+ "description": "The connected Instagram professional account, refreshed on every sync.",
+ "docs_url": _USER_DOCS,
+ "columns": {
+ "id": "App-scoped Instagram user ID.",
+ "username": "The account's Instagram profile username.",
+ "name": "The account's Instagram profile name.",
+ "biography": "Profile bio text.",
+ "website": "The website URL shown on the profile.",
+ "profile_picture_url": "URL of the account's profile picture.",
+ "followers_count": "Total number of Instagram users following the account.",
+ "follows_count": "Total number of Instagram accounts this account follows.",
+ "media_count": "Total number of published media on the account.",
+ },
+ },
+ "media": {
+ "description": "Posts, reels and carousels published by the account, newest first. Limited to the 10,000 most recently created media.",
+ "docs_url": _MEDIA_DOCS,
+ "columns": {
+ "id": "Media identifier.",
+ "caption": "The media's caption text. Excludes @ symbols unless the requester is an admin of the tagged account.",
+ "media_type": "Media type: CAROUSEL_ALBUM, IMAGE or VIDEO.",
+ "media_product_type": "Surface the media appears on: AD, FEED, STORY or REELS.",
+ "media_url": "URL of the media content. Omitted for media flagged for copyright.",
+ "permalink": "Permanent URL to the media.",
+ "thumbnail_url": "Thumbnail URL. Video content only.",
+ "timestamp": "ISO 8601 creation timestamp in UTC.",
+ "username": "Username of the account that created the media.",
+ "shortcode": "The media's shortcode.",
+ "like_count": "Number of likes. Omitted if the owner has hidden like counts.",
+ "comments_count": "Number of comments on the media.",
+ "is_comment_enabled": "Whether comments are enabled on the media.",
+ },
+ },
+ "stories": {
+ "description": "Stories published by the account in the last 24 hours. Instagram deletes stories after 24 hours, so history only accumulates from syncs that ran while a story was live.",
+ "docs_url": _MEDIA_DOCS,
+ "columns": {
+ "id": "Story media identifier.",
+ "caption": "The story's caption text.",
+ "media_type": "Media type: IMAGE or VIDEO.",
+ "media_product_type": "Always STORY for this table.",
+ "media_url": "URL of the story content.",
+ "permalink": "Permanent URL to the story.",
+ "thumbnail_url": "Thumbnail URL. Video stories only.",
+ "timestamp": "ISO 8601 creation timestamp in UTC.",
+ "username": "Username of the account that published the story.",
+ },
+ },
+ "media_comments": {
+ "description": "Comments on the account's media, one row per comment. Keyed by media and comment, because the table aggregates comments across every post.",
+ "docs_url": _COMMENT_DOCS,
+ "columns": {
+ "id": "Comment identifier.",
+ "media_id": "Identifier of the media the comment was left on.",
+ "text": "The comment's text.",
+ "timestamp": "ISO 8601 timestamp of when the comment was posted, in UTC.",
+ "username": "Username of the account that left the comment.",
+ "like_count": "Number of likes on the comment.",
+ "hidden": "Whether the comment is hidden on the media.",
+ },
+ },
+ "media_insights": {
+ "description": "Lifetime performance metrics per post, in long format: one row per media and metric. Available metrics vary by media type, and Meta retires metrics between Graph API versions.",
+ "docs_url": _INSIGHTS_DOCS,
+ "columns": {
+ "media_id": "Identifier of the media the metric belongs to.",
+ "media_timestamp": "ISO 8601 creation timestamp of the media, in UTC.",
+ "media_product_type": "Surface the media appears on: AD, FEED, STORY or REELS.",
+ "metric": "Metric name, for example reach, likes, saved, shares, total_interactions or views.",
+ "period": "Aggregation period Meta reported the metric over. Media metrics are lifetime totals.",
+ "title": "Meta's human-readable title for the metric.",
+ "description": "Meta's human-readable description of the metric.",
+ "value": "The metric's value.",
+ },
+ },
+ "account_insights": {
+ "description": "Daily account-level metrics, in long format: one row per metric and day. Meta only serves insights in windows of at most 30 days and retains roughly two years of history.",
+ "docs_url": _INSIGHTS_DOCS,
+ "columns": {
+ "instagram_account_id": "Instagram account the metric belongs to.",
+ "metric": "Metric name, for example reach or views.",
+ "period": "Aggregation period. Always day for this table.",
+ "date": "ISO 8601 end time of the day the metric covers, in UTC.",
+ "value": "The metric's value for that day.",
+ "title": "Meta's human-readable title for the metric.",
+ "description": "Meta's human-readable description of the metric.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/instagram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/instagram.py
new file mode 100644
index 000000000000..3b7b5821613b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/instagram.py
@@ -0,0 +1,757 @@
+import re
+import dataclasses
+from collections.abc import Iterator, Sequence
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.settings import (
+ ACCOUNT_INSIGHT_METRICS,
+ ACCOUNT_INSIGHTS_WINDOW_DAYS,
+ DEFAULT_INSIGHTS_LOOKBACK_DAYS,
+ DEFAULT_MEDIA_INSIGHT_METRICS,
+ GRAPH_API_HOST,
+ INSTAGRAM_ENDPOINTS,
+ MAX_INSIGHTS_LOOKBACK_DAYS,
+ MEDIA_INSIGHT_METRICS,
+ MEDIA_PARENT_FIELDS,
+ PAGE_FIELDS,
+ PAGE_SIZE,
+ InstagramEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+# Instagram account node IDs are plain integers. Anything else spliced into the Graph path
+# risks retargeting the request at a different object or injecting path/query segments.
+_NUMERIC_ACCOUNT_ID = re.compile(r"^[0-9]+$")
+
+# The media edge tops out at 10K posts; at PAGE_SIZE per page that is 100 pages. The cap
+# is a runaway guard for a paginator that never signals the end, not a real limit.
+MAX_PAGES_PER_STREAM = 500
+# Comment threads are unbounded, so each parent post gets its own page budget.
+MAX_PAGES_PER_PARENT = 50
+# Ceiling on the Graph calls a single sync may issue, drawn down by every request the run
+# makes. The two page caps above each bound one loop in isolation, which bounds nothing on
+# the fan-out endpoints because they multiply: a parent listing of N posts each paging its
+# own child edge is N * MAX_PAGES_PER_PARENT requests. This budget is what actually bounds
+# a sync's share of the account's Meta rate limit and of the worker's time. It sits well
+# above what a full sync of the documented 10K-post media edge needs, so it only bites on a
+# runaway fan-out; whatever it cuts short is picked up by the next sync.
+MAX_REQUESTS_PER_SYNC = 25_000
+
+# Substrings the source's `get_non_retryable_errors` matches on. Meta reports an expired
+# token as an HTTP 400 with `error.code` 190 as often as it does a 401, so the source
+# can't key its permanent failures off the status line alone.
+AUTH_ERROR_PREFIX = "Instagram API authentication failed"
+PERMISSION_ERROR_PREFIX = "Instagram API permission denied"
+
+# https://developers.facebook.com/docs/graph-api/guides/error-handling
+META_AUTH_ERROR_CODES = frozenset({102, 190, 458, 459, 460, 463, 464, 467})
+META_THROTTLE_ERROR_CODES = frozenset({4, 17, 32, 613})
+META_TRANSIENT_ERROR_CODES = frozenset({1, 2})
+META_PERMISSION_ERROR_CODE = 10
+
+
+class InstagramAPIError(Exception):
+ pass
+
+
+class InstagramRetryableError(InstagramAPIError):
+ pass
+
+
+class InstagramAuthError(InstagramAPIError):
+ pass
+
+
+class InstagramPermissionError(InstagramAPIError):
+ pass
+
+
+class InstagramBadRequestError(InstagramAPIError):
+ pass
+
+
+class InstagramRequestBudgetError(InstagramAPIError):
+ pass
+
+
+class InstagramResumeConfig:
+ # Fully-built next request URL. Every stream — plain edges, the parent listing of a
+ # fan-out, and the per-metric insight windows — checkpoints as a URL, so one field
+ # covers all of them.
+ next_url: str
+
+
+def _is_permission_code(code: Any) -> bool:
+ if not isinstance(code, int):
+ return False
+ return code == META_PERMISSION_ERROR_CODE or 200 <= code < 300
+
+
+def _normalize_timestamp(value: Any) -> Any:
+ """Rewrite Meta's `2024-03-01T18:10:00+0000` into ISO 8601 with an offset colon.
+
+ These columns are the incremental cursors and partition keys, and the compact-offset
+ form is not what downstream Arrow/Delta type inference recognises as a timestamp.
+ """
+ if not isinstance(value, str) or not value:
+ return value
+ for fmt in ("%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z"):
+ try:
+ return datetime.strptime(value, fmt).astimezone(UTC).isoformat()
+ except ValueError:
+ continue
+ return value
+
+
+def _normalize_row(row: dict[str, Any], timestamp_fields: Sequence[str]) -> dict[str, Any]:
+ normalized = dict(row)
+ for name in timestamp_fields:
+ if name in normalized:
+ normalized[name] = _normalize_timestamp(normalized[name])
+ return normalized
+
+
+def _to_unix_seconds(value: Any) -> Optional[int]:
+ """Coerce an incremental watermark or a user-supplied start date to Unix seconds."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return None
+ parsed = _normalize_timestamp(text)
+ try:
+ return int(datetime.fromisoformat(parsed).timestamp())
+ except ValueError:
+ pass
+ try:
+ return int(datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=UTC).timestamp())
+ except ValueError:
+ return None
+ return None
+
+
+def _with_query_param(url: str, name: str, value: str) -> str:
+ parts = urlparse(url)
+ params = [(key, item) for key, item in parse_qsl(parts.query, keep_blank_values=True) if key != name]
+ params.append((name, value))
+ return urlunparse(parts._replace(query=urlencode(params)))
+
+
+class InstagramClient:
+ """Thin Graph API client.
+
+ Hand-rolled rather than declarative because a single Instagram sync has to walk insight
+ windows and demote a metric Meta has retired, neither of which the shared `rest_source`
+ endpoint config can express.
+ """
+
+ def __init__(
+ self,
+ access_token: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+ max_requests: Optional[int] = None,
+ ) -> None:
+ self._base_url = f"{GRAPH_API_HOST}/{api_version}"
+ self._access_token = access_token
+ self._logger = logger
+ # One client is built per stream, so its counter is the whole sync's request budget.
+ self._max_requests = MAX_REQUESTS_PER_SYNC if max_requests is None else max_requests
+ self._requests_made = 0
+ self._budget_exhausted_logged = False
+ # The transport's status retries are disabled so they don't compound with the
+ # tenacity loop below, which also has to catch Meta's throttling error codes
+ # (delivered as HTTP 400 bodies, invisible to a status-code retry).
+ self._session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ retry=Retry(total=0),
+ redact_values=(access_token,),
+ # Graph API responses carry user-authored content — bios, captions, comments,
+ # usernames — that the name-based scrubbers can't recognise, so keep these
+ # bodies out of the shared HTTP sample bucket while still metering the calls.
+ capture=False,
+ )
+
+ def build_url(self, path: str, params: Optional[dict[str, str]] = None) -> str:
+ query = urlencode(dict(params or {}))
+ url = f"{self._base_url}/{path.strip('/')}"
+ return f"{url}?{query}" if query else url
+
+ @property
+ def requests_made(self) -> int:
+ return self._requests_made
+
+ def has_request_budget(self) -> bool:
+ """Whether this sync may still spend Graph calls.
+
+ Every loop that can fan out asks before issuing a request and stops cleanly when the
+ answer is no, leaving the last checkpoint pointing at the page it was draining.
+ """
+ if self._requests_made < self._max_requests:
+ return True
+
+ if not self._budget_exhausted_logged:
+ self._budget_exhausted_logged = True
+ self._logger.warning(
+ f"Instagram: this sync has spent its budget of {self._max_requests} Graph API requests, "
+ "stopping early. The rows it did not reach are picked up by the next sync."
+ )
+ return False
+
+ @retry(
+ retry=retry_if_exception_type((InstagramRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=120),
+ reraise=True,
+ )
+ def get(self, url: str) -> dict[str, Any]:
+ if self._requests_made >= self._max_requests:
+ # Backstop only: every loop that can fan out checks `has_request_budget` and
+ # stops cleanly before it gets here, so reaching this is a caller bug and the
+ # sync should fail loudly rather than keep drawing on the account's quota.
+ raise InstagramRequestBudgetError(f"Instagram API request budget of {self._max_requests} requests spent")
+ # Counted per attempt, retries included: a retry costs the account's quota too.
+ self._requests_made += 1
+
+ response = self._session.get(
+ url,
+ headers={"Authorization": f"Bearer {self._access_token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ self._raise_for_error(response)
+ body = response.json()
+ return body if isinstance(body, dict) else {"data": body}
+
+ def _raise_for_error(self, response: requests.Response) -> None:
+ if response.ok:
+ return
+
+ error: dict[str, Any] = {}
+ try:
+ payload = response.json()
+ if isinstance(payload, dict):
+ error = payload.get("error") or {}
+ except ValueError:
+ error = {}
+
+ code = error.get("code")
+ message = error.get("message") or response.text[:500]
+ detail = f"status={response.status_code}, code={code}, message={message}"
+
+ if (
+ response.status_code == 429
+ or response.status_code >= 500
+ or code in META_THROTTLE_ERROR_CODES
+ or code in META_TRANSIENT_ERROR_CODES
+ ):
+ raise InstagramRetryableError(f"Instagram API error (retryable): {detail}")
+
+ if response.status_code == 401 or code in META_AUTH_ERROR_CODES:
+ raise InstagramAuthError(f"{AUTH_ERROR_PREFIX}: {detail}")
+
+ if response.status_code == 403 or _is_permission_code(code):
+ raise InstagramPermissionError(f"{PERMISSION_ERROR_PREFIX}: {detail}")
+
+ self._logger.error(f"Instagram API error: {detail}")
+ raise InstagramBadRequestError(f"Instagram API error: {detail}")
+
+
+def _iter_pages(
+ client: InstagramClient,
+ url: str,
+ max_pages: int,
+) -> Iterator[tuple[list[dict[str, Any]], Optional[str]]]:
+ """Yield `(rows, next_url)` per page of a cursor-paginated edge.
+
+ Meta hands back both a ready-made `paging.next` and the raw `after` cursor. We rebuild
+ the URL from the cursor instead of following `paging.next`, so the resume checkpoint is
+ a URL we constructed and Meta can't echo the access token into our saved state.
+ """
+ pages = 0
+ current: Optional[str] = url
+ while current is not None and pages < max_pages and client.has_request_budget():
+ body = client.get(current)
+ rows = body.get("data")
+ rows = rows if isinstance(rows, list) else []
+ paging = body.get("paging") or {}
+ after = (paging.get("cursors") or {}).get("after")
+ next_url = _with_query_param(current, "after", str(after)) if paging.get("next") and after else None
+
+ yield rows, next_url
+
+ current = next_url
+ pages += 1
+
+
+def _account_path(instagram_account_id: str, edge: str = "") -> str:
+ # A Facebook Login token is scoped to a person, so `me` would resolve to the Facebook
+ # user rather than the Instagram account. Every request names the account node.
+ node = instagram_account_id.strip()
+ return f"{node}/{edge}" if edge else node
+
+
+def _insight_points(entry: dict[str, Any]) -> list[dict[str, Any]]:
+ """Flatten one insight entry into `(value, end_time)` points.
+
+ Meta returns `time_series` for `metric_type=time_series`, `values` for the legacy
+ shape, and a bare `total_value` for lifetime metrics.
+ """
+ for key in ("time_series", "values"):
+ points = entry.get(key)
+ if isinstance(points, list) and points:
+ return [point for point in points if isinstance(point, dict)]
+
+ total_value = entry.get("total_value")
+ if isinstance(total_value, dict) and "value" in total_value:
+ return [{"value": total_value["value"], "end_time": None}]
+
+ return []
+
+
+def _media_rows(
+ client: InstagramClient,
+ instagram_account_id: str,
+ config: InstagramEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ logger: FilteringBoundLogger,
+ since: Optional[int],
+) -> Iterator[list[dict[str, Any]]]:
+ """Page a plain edge hung off the account node (media, stories)."""
+ params: dict[str, str] = {"fields": config.fields, "limit": str(PAGE_SIZE)}
+ if config.supports_time_window and since is not None:
+ params["since"] = str(since)
+
+ url = _resume_url(resumable_source_manager, logger, config.name) or client.build_url(
+ _account_path(instagram_account_id, config.edge), params
+ )
+
+ for rows, next_url in _iter_pages(client, url, MAX_PAGES_PER_STREAM):
+ if rows:
+ yield [_normalize_row(row, config.timestamp_fields) for row in rows]
+ # Checkpoint after the yield: a crash then re-yields the last page instead of
+ # skipping it, and the merge dedupes on the primary key.
+ if next_url is not None:
+ resumable_source_manager.save_state(InstagramResumeConfig(next_url=next_url))
+
+
+def _account_row(
+ client: InstagramClient,
+ instagram_account_id: str,
+ config: InstagramEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ body = client.get(client.build_url(_account_path(instagram_account_id), {"fields": config.fields}))
+ if body.get("id"):
+ yield [_normalize_row(body, config.timestamp_fields)]
+
+
+def _fanout_rows(
+ client: InstagramClient,
+ instagram_account_id: str,
+ config: InstagramEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the media edge, then query one child edge per post.
+
+ The checkpoint is the parent page, saved once its children are drained, so a resume
+ replays at most one page of posts.
+ """
+ parent_params: dict[str, str] = {"fields": MEDIA_PARENT_FIELDS, "limit": str(PAGE_SIZE)}
+ url = _resume_url(resumable_source_manager, logger, config.name) or client.build_url(
+ _account_path(instagram_account_id, config.edge), parent_params
+ )
+
+ for media_page, next_url in _iter_pages(client, url, MAX_PAGES_PER_STREAM):
+ for media in media_page:
+ media_id = media.get("id")
+ if not media_id:
+ continue
+
+ if not client.has_request_budget():
+ # Return without checkpointing: the saved state still points at the page
+ # being drained, so a resumed attempt replays it instead of skipping the
+ # posts whose children were never fetched.
+ return
+
+ if config.child_edge == "insights":
+ rows = _media_insight_rows(client, media, logger)
+ else:
+ rows = _media_comment_rows(client, media, config, logger)
+
+ if rows:
+ yield rows
+
+ if next_url is not None:
+ resumable_source_manager.save_state(InstagramResumeConfig(next_url=next_url))
+
+
+def _media_comment_rows(
+ client: InstagramClient,
+ media: dict[str, Any],
+ config: InstagramEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ media_id = str(media["id"])
+ url = client.build_url(f"{media_id}/comments", {"fields": config.fields, "limit": str(PAGE_SIZE)})
+
+ rows: list[dict[str, Any]] = []
+ try:
+ for page, _ in _iter_pages(client, url, MAX_PAGES_PER_PARENT):
+ rows.extend(_normalize_row({**comment, "media_id": media_id}, config.timestamp_fields) for comment in page)
+ except InstagramBadRequestError as error:
+ # Comments are disabled or the post was deleted mid-sync. Neither is fixable by
+ # retrying and neither should sink the whole table.
+ logger.warning(f"Instagram: skipping comments for media {media_id}: {error}")
+ return []
+
+ return rows
+
+
+def _media_insight_rows(
+ client: InstagramClient,
+ media: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ media_id = str(media["id"])
+ product_type = str(media.get("media_product_type") or "")
+ metrics = MEDIA_INSIGHT_METRICS.get(product_type, DEFAULT_MEDIA_INSIGHT_METRICS)
+ media_timestamp = _normalize_timestamp(media.get("timestamp"))
+
+ url = client.build_url(f"{media_id}/insights", {"metric": ",".join(metrics)})
+ try:
+ body = client.get(url)
+ except InstagramBadRequestError as error:
+ # Meta retires metrics per Graph version and rejects the whole request when one
+ # of them doesn't apply to this post. Skip the post rather than the table.
+ logger.warning(f"Instagram: skipping insights for media {media_id}: {error}")
+ return []
+
+ entries = body.get("data")
+ entries = entries if isinstance(entries, list) else []
+
+ rows: list[dict[str, Any]] = []
+ for entry in entries:
+ points = _insight_points(entry)
+ if not points:
+ continue
+ rows.append(
+ {
+ "media_id": media_id,
+ "media_timestamp": media_timestamp,
+ "media_product_type": product_type or None,
+ "metric": entry.get("name"),
+ "period": entry.get("period"),
+ "title": entry.get("title"),
+ "description": entry.get("description"),
+ # Media insights are lifetime totals, so there is exactly one point.
+ "value": points[0].get("value"),
+ }
+ )
+
+ return rows
+
+
+def _insight_windows(since: int, until: int, window_days: int = ACCOUNT_INSIGHTS_WINDOW_DAYS) -> list[tuple[int, int]]:
+ """Split a range into windows Meta will accept (it rejects spans over 30 days)."""
+ if until <= since:
+ return []
+
+ step = window_days * 24 * 60 * 60
+ windows: list[tuple[int, int]] = []
+ start = since
+ while start < until:
+ end = min(start + step, until)
+ windows.append((start, end))
+ start = end
+ return windows
+
+
+def _account_insight_plan(
+ client: InstagramClient,
+ instagram_account_id: str,
+ since: int,
+ until: int,
+) -> list[list[tuple[str, str]]]:
+ """Build the request plan as one `(metric, url)` group per time window.
+
+ Window-major, not metric-major: every metric for a window is fetched together so the
+ rows for that window can be emitted in date order. Walking metric by metric instead
+ would rewind the stream to the start of the range on each new metric, which breaks
+ the ascending watermark the pipeline checkpoints after every batch.
+ """
+ path = _account_path(instagram_account_id, "insights")
+ plan: list[list[tuple[str, str]]] = []
+ for window_since, window_until in _insight_windows(since, until):
+ plan.append(
+ [
+ (
+ metric,
+ client.build_url(
+ path,
+ {
+ "metric": metric,
+ "period": "day",
+ "metric_type": "time_series",
+ "since": str(window_since),
+ "until": str(window_until),
+ },
+ ),
+ )
+ for metric in ACCOUNT_INSIGHT_METRICS
+ ]
+ )
+ return plan
+
+
+def _account_insight_rows(
+ client: InstagramClient,
+ instagram_account_id: str,
+ config: InstagramEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ logger: FilteringBoundLogger,
+ since: Optional[int],
+) -> Iterator[list[dict[str, Any]]]:
+ now = datetime.now(UTC)
+ until = int(now.timestamp())
+ # Clamp the (user-controlled) start date to Meta's retention horizon: a date like
+ # `0001-01-01` would otherwise fan out into tens of thousands of empty 30-day windows.
+ earliest = int((now - timedelta(days=MAX_INSIGHTS_LOOKBACK_DAYS)).timestamp())
+ start = (
+ max(since, earliest)
+ if since is not None
+ else int((now - timedelta(days=DEFAULT_INSIGHTS_LOOKBACK_DAYS)).timestamp())
+ )
+
+ plan = _account_insight_plan(client, instagram_account_id, start, until)
+
+ resume_url = _resume_url(resumable_source_manager, logger, config.name)
+ if resume_url is not None:
+ # A window is identified by the URL of its first metric.
+ heads = [window[0][1] for window in plan]
+ if resume_url in heads:
+ plan = plan[heads.index(resume_url) :]
+ else:
+ logger.warning("Instagram: saved account_insights checkpoint is outside this run's window, restarting")
+
+ for index, window in enumerate(plan):
+ if not client.has_request_budget():
+ # The checkpoint saved by the previous window already points here, so a resumed
+ # attempt carries on from this window rather than replaying the whole range.
+ return
+
+ rows: list[dict[str, Any]] = []
+ for metric, url in window:
+ try:
+ body = client.get(url)
+ except (InstagramBadRequestError, InstagramPermissionError) as error:
+ # `impressions` was retired in v22.0 and Meta rejects the whole request
+ # for a metric the account can't serve. Drop the metric, keep the window.
+ logger.warning(f"Instagram: skipping account insight metric '{metric}': {error}")
+ continue
+
+ entries = body.get("data")
+ entries = entries if isinstance(entries, list) else []
+
+ for entry in entries:
+ for point in _insight_points(entry):
+ end_time = point.get("end_time")
+ if end_time is None:
+ continue
+ rows.append(
+ {
+ "instagram_account_id": instagram_account_id,
+ "metric": entry.get("name") or metric,
+ "period": entry.get("period"),
+ "date": _normalize_timestamp(end_time),
+ "value": point.get("value"),
+ "title": entry.get("title"),
+ "description": entry.get("description"),
+ }
+ )
+
+ if rows:
+ # Sorted so the batch is genuinely ascending by date, which is what
+ # `sort_mode="asc"` promises the pipeline.
+ rows.sort(key=lambda row: (str(row["date"]), str(row["metric"])))
+ yield rows
+
+ next_index = index + 1
+ if next_index < len(plan):
+ resumable_source_manager.save_state(InstagramResumeConfig(next_url=plan[next_index][0][1]))
+
+
+def _resume_url(
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ logger: FilteringBoundLogger,
+ endpoint: str,
+) -> Optional[str]:
+ if not resumable_source_manager.can_resume():
+ return None
+
+ state = resumable_source_manager.load_state()
+ if state is None or not state.next_url:
+ return None
+
+ logger.debug(f"Instagram: resuming {endpoint} from saved checkpoint")
+ return state.next_url
+
+
+def list_professional_accounts(
+ access_token: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ """Every Instagram professional account reachable through the connected Facebook user's pages.
+
+ A page with no linked professional account is skipped rather than offered as a choice that
+ can never sync.
+ """
+ client = InstagramClient(access_token=access_token, api_version=api_version, logger=logger)
+ url = client.build_url("me/accounts", {"fields": PAGE_FIELDS, "limit": str(PAGE_SIZE)})
+
+ accounts: list[dict[str, Any]] = []
+ for pages, _ in _iter_pages(client, url, MAX_PAGES_PER_STREAM):
+ for page in pages:
+ linked = page.get("instagram_business_account")
+ if not isinstance(linked, dict) or not linked.get("id"):
+ continue
+ accounts.append(
+ {
+ "id": str(linked["id"]),
+ "username": linked.get("username"),
+ "name": linked.get("name"),
+ "page_name": page.get("name"),
+ }
+ )
+
+ return accounts
+
+
+def validate_credentials(
+ access_token: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+ instagram_account_id: Optional[str] = None,
+) -> tuple[bool, Optional[str]]:
+ """Probe the account node to confirm the token can read the chosen Instagram account."""
+ account_id = (instagram_account_id or "").strip()
+ if not account_id:
+ return False, "Choose the Instagram account you want to sync."
+ # The account ID is spliced straight into the Graph API path, so anything but the plain
+ # numeric node ID could select a different object or inject extra path/query segments.
+ if not _NUMERIC_ACCOUNT_ID.match(account_id):
+ return False, "That is not a valid Instagram account. Pick the account again from the list."
+
+ client = InstagramClient(access_token=access_token, api_version=api_version, logger=logger)
+
+ try:
+ body = client.get(client.build_url(_account_path(account_id), {"fields": "id,username"}))
+ except InstagramAuthError:
+ return False, "The Instagram connection has expired. Reconnect your Instagram account and try again."
+ except InstagramPermissionError:
+ return False, (
+ "The Instagram connection is missing permissions this source needs. Reconnect it and grant "
+ "access to your page, Instagram insights and comments."
+ )
+ except Exception:
+ return False, "Could not reach the Instagram API with this connection."
+
+ if not body.get("id"):
+ return False, "That account is not an Instagram professional account. Pick a different account."
+
+ return True, None
+
+
+def get_rows(
+ access_token: str,
+ api_version: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ instagram_account_id: str,
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INSTAGRAM_ENDPOINTS[endpoint]
+ client = InstagramClient(access_token=access_token, api_version=api_version, logger=logger)
+
+ since: Optional[int] = None
+ if config.supports_time_window:
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ since = _to_unix_seconds(db_incremental_field_last_value)
+ if since is None:
+ since = _to_unix_seconds(start_date)
+
+ if endpoint == "account":
+ yield from _account_row(client, instagram_account_id, config)
+ elif endpoint == "account_insights":
+ yield from _account_insight_rows(
+ client=client,
+ instagram_account_id=instagram_account_id,
+ config=config,
+ resumable_source_manager=resumable_source_manager,
+ logger=logger,
+ since=since,
+ )
+ elif config.child_edge is not None:
+ yield from _fanout_rows(client, instagram_account_id, config, resumable_source_manager, logger)
+ else:
+ yield from _media_rows(client, instagram_account_id, config, resumable_source_manager, logger, since)
+
+
+def instagram_source(
+ access_token: str,
+ api_version: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ instagram_account_id: str,
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ config = INSTAGRAM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ api_version=api_version,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ instagram_account_id=instagram_account_id,
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/settings.py
new file mode 100644
index 000000000000..9bdad01acf74
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/settings.py
@@ -0,0 +1,167 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField
+
+# PostHog's Meta app authorizes through Facebook Login, so the Instagram Platform surface is
+# reached on graph.facebook.com. (graph.instagram.com serves the same edges, but only for
+# tokens minted by Instagram Login.)
+GRAPH_API_HOST = "https://graph.facebook.com"
+
+# Node/edge field selections. Meta returns nothing but `id` unless `fields` is passed,
+# so every request names its columns explicitly.
+ACCOUNT_FIELDS = "id,username,name,biography,website,profile_picture_url,followers_count,follows_count,media_count"
+MEDIA_FIELDS = (
+ "id,caption,media_type,media_product_type,media_url,permalink,thumbnail_url,"
+ "timestamp,username,shortcode,like_count,comments_count,is_comment_enabled"
+)
+STORY_FIELDS = "id,caption,media_type,media_product_type,media_url,permalink,thumbnail_url,timestamp,username"
+COMMENT_FIELDS = "id,text,timestamp,username,like_count,hidden"
+# Parent listing for the fan-out endpoints — only what the child rows need to be keyed
+# and partitioned, so the fan-out doesn't pay for the full media projection.
+MEDIA_PARENT_FIELDS = "id,timestamp,media_product_type"
+# Page listing used by the account picker. A professional Instagram account is only
+# reachable through the Facebook Page it is linked to, so the picker walks the pages.
+PAGE_FIELDS = "name,instagram_business_account{id,username,name}"
+
+# Rows per page. Meta caps the media edge at 100 and silently clamps anything larger.
+PAGE_SIZE = 100
+
+# Account insights are a daily time series; Meta rejects a since/until span wider than
+# 30 days, so a backfill walks the range in windows.
+ACCOUNT_INSIGHTS_WINDOW_DAYS = 30
+# How far back account insights start when the user gives no start date. Meta only
+# retains ~2 years of insights, but a fresh connection defaulting to two years of
+# 30-day windows is a lot of calls for data most people don't want.
+DEFAULT_INSIGHTS_LOOKBACK_DAYS = 90
+# Hard floor on how far back a user-supplied start date can push the account-insights
+# backfill. Meta only retains ~2 years of insights anyway, so a start date older than
+# this returns nothing but would still fan out into thousands of empty 30-day windows.
+MAX_INSIGHTS_LOOKBACK_DAYS = 365 * 2
+
+# Account-level metrics pulled as a daily time series. Meta churns this list per Graph
+# version (`impressions` was retired in v22.0 in favour of `views`), so each metric is
+# requested on its own and an unsupported one is skipped rather than failing the sync.
+ACCOUNT_INSIGHT_METRICS: tuple[str, ...] = ("reach", "views")
+
+# Per-media metrics, keyed by `media_product_type`. Stories expose a different set from
+# feed posts and reels.
+DEFAULT_MEDIA_INSIGHT_METRICS: tuple[str, ...] = (
+ "reach",
+ "likes",
+ "comments",
+ "saved",
+ "shares",
+ "total_interactions",
+ "views",
+)
+MEDIA_INSIGHT_METRICS: dict[str, tuple[str, ...]] = {
+ "FEED": DEFAULT_MEDIA_INSIGHT_METRICS,
+ "REELS": DEFAULT_MEDIA_INSIGHT_METRICS,
+ "AD": DEFAULT_MEDIA_INSIGHT_METRICS,
+ "STORY": ("reach", "replies", "views"),
+}
+
+
+@dataclass
+class InstagramEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField]
+ # Graph edge hung off the Instagram user node. "" means the node itself.
+ edge: str = ""
+ # `fields` query-string value for the request this endpoint issues.
+ fields: str = ""
+ # Edge queried once per media node. Set only for fan-out endpoints, which page the
+ # media edge as their parent listing.
+ child_edge: Optional[str] = None
+ # Stable creation timestamp used for partitioning. Never an updated-at column.
+ partition_key: Optional[str] = None
+ sort_mode: SortMode = "desc"
+ # True only where the Graph edge genuinely honours `since`/`until`. Everything else
+ # is a full refresh — a client-side filter would still walk every page.
+ supports_time_window: bool = False
+ # Columns carrying Meta's `+0000` offset, normalized to ISO 8601 on the way out.
+ timestamp_fields: tuple[str, ...] = field(default_factory=tuple)
+
+
+INSTAGRAM_ENDPOINTS: dict[str, InstagramEndpointConfig] = {
+ # The professional account itself — one row, refreshed each sync.
+ "account": InstagramEndpointConfig(
+ name="account",
+ edge="",
+ fields=ACCOUNT_FIELDS,
+ primary_keys=["id"],
+ incremental_fields=[],
+ sort_mode="asc",
+ ),
+ # The media edge honours since/until (Unix seconds) against the post's creation
+ # time and returns newest-first, so it is the one genuinely incremental collection.
+ "media": InstagramEndpointConfig(
+ name="media",
+ edge="media",
+ fields=MEDIA_FIELDS,
+ primary_keys=["id"],
+ incremental_fields=[incremental_field("timestamp")],
+ partition_key="timestamp",
+ sort_mode="desc",
+ supports_time_window=True,
+ timestamp_fields=("timestamp",),
+ ),
+ # Stories only exist for 24 hours, so there is nothing to sync incrementally.
+ "stories": InstagramEndpointConfig(
+ name="stories",
+ edge="stories",
+ fields=STORY_FIELDS,
+ primary_keys=["id"],
+ incremental_fields=[],
+ partition_key="timestamp",
+ sort_mode="desc",
+ timestamp_fields=("timestamp",),
+ ),
+ # Comments have no server-side time filter, so the fan-out is a full refresh. The
+ # media id is part of the key: the table aggregates comments from every post.
+ "media_comments": InstagramEndpointConfig(
+ name="media_comments",
+ edge="media",
+ child_edge="comments",
+ fields=COMMENT_FIELDS,
+ primary_keys=["media_id", "id"],
+ incremental_fields=[],
+ partition_key="timestamp",
+ sort_mode="desc",
+ timestamp_fields=("timestamp",),
+ ),
+ # One row per (media, metric) in long format — Meta varies the available metrics by
+ # media type, so a wide table would be mostly nulls and would break on every
+ # Graph version that retires a metric.
+ "media_insights": InstagramEndpointConfig(
+ name="media_insights",
+ edge="media",
+ child_edge="insights",
+ primary_keys=["media_id", "metric"],
+ incremental_fields=[],
+ partition_key="media_timestamp",
+ sort_mode="desc",
+ timestamp_fields=("media_timestamp",),
+ ),
+ # Daily account metrics, also long format, walked in 30-day windows.
+ "account_insights": InstagramEndpointConfig(
+ name="account_insights",
+ edge="insights",
+ primary_keys=["instagram_account_id", "metric", "date"],
+ incremental_fields=[incremental_field("date")],
+ partition_key="date",
+ sort_mode="asc",
+ supports_time_window=True,
+ timestamp_fields=("date",),
+ ),
+}
+
+ENDPOINTS = tuple(INSTAGRAM_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in INSTAGRAM_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/source.py
index 32b479158cbe..054efeac63cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/source.py
@@ -1,21 +1,69 @@
-from typing import cast
+from typing import Optional, cast
+
+import structlog
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldOauthAccountSelectConfig,
+ SourceFieldOauthConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, INSTAGRAM_OAUTH_SCOPE, InstagramIntegration
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.instagram import (
InstagramSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.instagram import (
+ AUTH_ERROR_PREFIX,
+ PERMISSION_ERROR_PREFIX,
+ InstagramAPIError,
+ InstagramAuthError,
+ InstagramPermissionError,
+ InstagramResumeConfig,
+ instagram_source,
+ list_professional_accounts,
+ validate_credentials as validate_instagram_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+logger = structlog.get_logger(__name__)
+
@SourceRegistry.register
-class InstagramSource(SimpleSource[InstagramSourceConfig]):
+class InstagramSource(ResumableSource[InstagramSourceConfig, InstagramResumeConfig], OAuthMixin):
+ api_docs_url = "https://developers.facebook.com/docs/instagram-platform"
+ # Meta pins the Graph API by URL path segment and keeps each version alive for
+ # roughly two years, so the pin is a real choice rather than a constant.
+ supported_versions = ("v22.0", "v23.0")
+ default_version = "v23.0"
+
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INSTAGRAM
@@ -26,7 +74,175 @@ class InstagramSource(SimpleSource[InstagramSourceConfig]):
name=SchemaExternalDataSourceType.INSTAGRAM,
category=DataWarehouseSourceCategory.COMMUNICATION,
label="Instagram",
+ caption="""Pull posts, stories, comments and insights from an Instagram professional (Business or Creator) account into the PostHog Data warehouse.
+
+Connect your Instagram account, then pick the professional account you want to sync. The account has to be linked to a Facebook page, and you'll be asked to grant access to that page along with Instagram insights and comments.""",
iconPath="/static/services/instagram.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/instagram",
+ keywords=["ig", "meta", "social"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ featureFlag="dwh-instagram",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldOauthConfig(
+ name="instagram_integration_id",
+ label="Instagram account",
+ required=True,
+ kind="instagram",
+ requiredScopes=INSTAGRAM_OAUTH_SCOPE,
+ ),
+ SourceFieldOauthAccountSelectConfig(
+ name="instagram_account_id",
+ label="Instagram professional account",
+ integrationField="instagram_integration_id",
+ integrationKind="instagram",
+ required=True,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ AUTH_ERROR_PREFIX: (
+ "The Instagram connection has expired. Reconnect your Instagram account to keep syncing."
+ ),
+ PERMISSION_ERROR_PREFIX: (
+ "The Instagram connection is missing permissions this sync needs. Reconnect it and grant "
+ "access to your page, Instagram insights and comments."
+ ),
+ "Failed to refresh the Instagram connection": (
+ "The Instagram connection could not be refreshed. Reconnect your Instagram account."
+ ),
+ # The source still points at an `instagram_integration_id` whose Integration row is gone
+ # (deleted or de-authorized), which `get_oauth_integration` reports as a ValueError.
+ # Retrying can't bring the row back; only reconnecting can.
+ "Integration not found": (
+ "The Instagram connection for this source no longer exists. Reconnect your Instagram account."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: InstagramSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def _access_token(self, integration_id: int, team_id: int) -> str:
+ """An access token Meta will still accept.
+
+ Meta issues no refresh token, so a long-lived token is swapped for a fresh one on use.
+ `refresh_access_token` is a no-op while the current token has more than 7 days left.
+ """
+ integration = self.get_oauth_integration(integration_id, team_id)
+ InstagramIntegration(integration).refresh_access_token()
+
+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED or not integration.access_token:
+ raise ValueError("Failed to refresh the Instagram connection")
+
+ return integration.access_token
+
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # A Facebook user's pages are few, so `search` is ignored here and the endpoint filters the list.
+ try:
+ access_token = self._access_token(integration_id, team_id)
+ except ValueError as e:
+ raise IntegrationAccountListingError(
+ "The linked Instagram connection could not be used. Please reconnect your Instagram account."
+ ) from e
+
+ try:
+ accounts = list_professional_accounts(
+ access_token=access_token,
+ api_version=self.default_version,
+ logger=logger,
+ )
+ except (InstagramAuthError, InstagramPermissionError) as e:
+ raise IntegrationAccountListingError(
+ "Instagram rejected this connection. Reconnect your Instagram account and grant access to "
+ "the page your professional account is linked to."
+ ) from e
+ except InstagramAPIError as e:
+ # Throttling or a Graph API blip. Neither is a bug, so surface it as something the user
+ # can retry rather than a 500 that pages us.
+ raise IntegrationAccountListingError(
+ "Instagram is having trouble responding right now. Please try again in a few minutes."
+ ) from e
+
+ return [
+ IntegrationAccount(
+ value=account["id"],
+ display_name=account.get("username") or account.get("name") or "Instagram account",
+ secondary_text=account.get("page_name"),
+ )
+ for account in accounts
+ ]
+
+ def validate_credentials(
+ self,
+ config: InstagramSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ try:
+ access_token = self._access_token(config.instagram_integration_id, team_id)
+ except ValueError:
+ return False, "Connect an Instagram account before syncing."
+
+ return validate_instagram_credentials(
+ access_token=access_token,
+ api_version=self.resolve_api_version(api_version),
+ logger=logger,
+ instagram_account_id=config.instagram_account_id,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InstagramResumeConfig]:
+ # Each endpoint checkpoints a URL built for its own edge, so a retry that lands on
+ # a different table must not pick up the previous table's cursor.
+ return ResumableSourceManager[InstagramResumeConfig](
+ inputs, InstagramResumeConfig, namespace=inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: InstagramSourceConfig,
+ resumable_source_manager: ResumableSourceManager[InstagramResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return instagram_source(
+ access_token=self._access_token(config.instagram_integration_id, inputs.team_id),
+ api_version=self.resolve_api_version(inputs.api_version),
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ instagram_account_id=config.instagram_account_id,
+ start_date=config.start_date,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram.py
new file mode 100644
index 000000000000..2d7a2458ee25
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram.py
@@ -0,0 +1,892 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.instagram import (
+ AUTH_ERROR_PREFIX,
+ MAX_REQUESTS_PER_SYNC,
+ MAX_RETRY_ATTEMPTS,
+ PERMISSION_ERROR_PREFIX,
+ InstagramAuthError,
+ InstagramBadRequestError,
+ InstagramClient,
+ InstagramPermissionError,
+ InstagramRequestBudgetError,
+ InstagramResumeConfig,
+ InstagramRetryableError,
+ _account_insight_plan,
+ _insight_points,
+ _insight_windows,
+ _normalize_timestamp,
+ _to_unix_seconds,
+ _with_query_param,
+ get_rows,
+ instagram_source,
+ list_professional_accounts,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.settings import (
+ ACCOUNT_INSIGHT_METRICS,
+ ACCOUNT_INSIGHTS_WINDOW_DAYS,
+ INSTAGRAM_ENDPOINTS,
+ MAX_INSIGHTS_LOOKBACK_DAYS,
+ MEDIA_INSIGHT_METRICS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.instagram.instagram"
+LOGGER = structlog.get_logger("instagram-tests")
+ACCOUNT_ID = "17841400000000000"
+
+
+class FakeResponse:
+ def __init__(self, status_code: int = 200, payload: Any = None, text: str = "", repeat: bool = False) -> None:
+ self.status_code = status_code
+ self._payload = payload
+ self.text = text or ("" if payload is None else str(payload))
+ # Retryable responses are served on every matching request, so a test can watch
+ # the retry loop exhaust itself instead of falling through to the next queued one.
+ self.repeat = repeat
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> Any:
+ if self._payload is None:
+ raise ValueError("no json body")
+ return self._payload
+
+
+class FakeSession:
+ """Stands in for the tracked session, matching queued responses by URL substring."""
+
+ def __init__(self, responses: Optional[list[tuple[str, FakeResponse]]] = None) -> None:
+ self.responses: list[tuple[str, FakeResponse]] = list(responses or [])
+ self.requested_urls: list[str] = []
+ self.headers: dict[str, str] = {}
+ self.default_response = FakeResponse(200, {"data": []})
+
+ def get(self, url: str, headers: Optional[dict[str, str]] = None, timeout: Optional[int] = None) -> FakeResponse:
+ self.requested_urls.append(url)
+ for index, (fragment, response) in enumerate(self.responses):
+ if fragment in url:
+ if not response.repeat:
+ self.responses.pop(index)
+ return response
+ return self.default_response
+
+ def params(self, index: int) -> dict[str, list[str]]:
+ return parse_qs(urlparse(self.requested_urls[index]).query)
+
+
+class FakeResumableSourceManager(ResumableSourceManager[InstagramResumeConfig]):
+ """Resume manager backed by memory instead of Redis."""
+
+ def __init__(self, state: Optional[InstagramResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[InstagramResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[InstagramResumeConfig]:
+ return self.state
+
+ def save_state(self, data: InstagramResumeConfig) -> None:
+ self.saved.append(data)
+ self.state = data
+
+ def clear_state(self) -> None:
+ self.state = None
+
+
+def _page(rows: Iterable[dict[str, Any]], after: Optional[str] = None) -> dict[str, Any]:
+ body: dict[str, Any] = {"data": list(rows)}
+ if after is not None:
+ body["paging"] = {"cursors": {"after": after}, "next": "https://graph.facebook.com/next"}
+ return body
+
+
+def _collect(
+ endpoint: str,
+ session: FakeSession,
+ manager: Optional[FakeResumableSourceManager] = None,
+ **kwargs: Any,
+) -> list[dict[str, Any]]:
+ resume_manager = manager or FakeResumableSourceManager()
+ kwargs.setdefault("instagram_account_id", ACCOUNT_ID)
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ access_token="tok",
+ api_version="v23.0",
+ endpoint=endpoint,
+ logger=LOGGER,
+ resumable_source_manager=resume_manager,
+ **kwargs,
+ )
+ )
+ return [row for batch in batches for row in batch]
+
+
+class TestInstagramTransport:
+ def test_every_request_is_addressed_to_the_chosen_account_node(self) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=FakeSession()):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+
+ # A Facebook Login token is scoped to a person, so `me` would resolve to the Facebook
+ # user rather than the Instagram account.
+ assert client.build_url(f"{ACCOUNT_ID}/media").startswith(
+ f"https://graph.facebook.com/v23.0/{ACCOUNT_ID}/media"
+ )
+
+ def test_the_access_token_never_rides_in_the_query_string(self) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(200, {"id": ACCOUNT_ID}))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+ client.get(client.build_url(ACCOUNT_ID))
+
+ assert "tok" not in session.requested_urls[0]
+
+ def test_graph_responses_are_kept_out_of_the_http_sample_bucket(self) -> None:
+ # Graph API bodies carry user-authored content (bios, captions, comments) the
+ # generic scrubbers can't redact, so the session must opt out of sample capture.
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=FakeSession()) as factory:
+ InstagramClient("tok", "v23.0", LOGGER)
+
+ assert factory.call_args.kwargs["capture"] is False
+
+ @pytest.mark.parametrize(
+ "url,expected",
+ [
+ ("https://x/me/media?limit=100", ["CUR"]),
+ ("https://x/me/media?limit=100&after=OLD", ["CUR"]),
+ ],
+ )
+ def test_with_query_param_replaces_rather_than_appends(self, url: str, expected: list[str]) -> None:
+ updated = _with_query_param(url, "after", "CUR")
+ assert parse_qs(urlparse(updated).query)["after"] == expected
+ assert parse_qs(urlparse(updated).query)["limit"] == ["100"]
+
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ ("2024-03-01T18:10:00+0000", "2024-03-01T18:10:00+00:00"),
+ ("2024-03-01T18:10:00.500+0000", "2024-03-01T18:10:00.500000+00:00"),
+ ("2024-03-01T18:10:00+00:00", "2024-03-01T18:10:00+00:00"),
+ ("not-a-timestamp", "not-a-timestamp"),
+ ("", ""),
+ (None, None),
+ (17, 17),
+ ],
+ )
+ def test_normalize_timestamp(self, value: Any, expected: Any) -> None:
+ assert _normalize_timestamp(value) == expected
+
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (None, None),
+ ("", None),
+ ("2024-01-01", 1704067200),
+ ("2024-01-01T00:00:00+0000", 1704067200),
+ (datetime(2024, 1, 1, tzinfo=UTC), 1704067200),
+ (datetime(2024, 1, 1), 1704067200),
+ (1704067200, 1704067200),
+ ("nonsense", None),
+ ],
+ )
+ def test_to_unix_seconds(self, value: Any, expected: Optional[int]) -> None:
+ assert _to_unix_seconds(value) == expected
+
+ @pytest.mark.parametrize(
+ "since,until,expected",
+ [
+ (0, 0, []),
+ (100, 50, []),
+ (0, 10 * 86400, [(0, 864000)]),
+ (0, 45 * 86400, [(0, 30 * 86400), (30 * 86400, 45 * 86400)]),
+ ],
+ )
+ def test_insight_windows_never_exceed_meta_s_30_day_limit(
+ self, since: int, until: int, expected: list[tuple[int, int]]
+ ) -> None:
+ windows = _insight_windows(since, until)
+ assert windows == expected
+ assert all(end - start <= 30 * 86400 for start, end in windows)
+
+ @pytest.mark.parametrize(
+ "entry,expected",
+ [
+ ({"time_series": [{"value": 1, "end_time": "t"}]}, [{"value": 1, "end_time": "t"}]),
+ ({"values": [{"value": 2, "end_time": "t"}]}, [{"value": 2, "end_time": "t"}]),
+ ({"total_value": {"value": 3}}, [{"value": 3, "end_time": None}]),
+ ({"values": []}, []),
+ ({}, []),
+ ],
+ )
+ def test_insight_points_handles_every_shape_meta_returns(
+ self, entry: dict[str, Any], expected: list[dict[str, Any]]
+ ) -> None:
+ assert _insight_points(entry) == expected
+
+ @pytest.mark.parametrize(
+ "status_code,payload,expected",
+ [
+ (400, {"error": {"code": 190, "message": "expired"}}, InstagramAuthError),
+ (401, {"error": {"code": 0, "message": "bad token"}}, InstagramAuthError),
+ (400, {"error": {"code": 10, "message": "no permission"}}, InstagramPermissionError),
+ (400, {"error": {"code": 200, "message": "missing scope"}}, InstagramPermissionError),
+ (403, {"error": {"code": 0, "message": "forbidden"}}, InstagramPermissionError),
+ (400, {"error": {"code": 100, "message": "bad metric"}}, InstagramBadRequestError),
+ (404, None, InstagramBadRequestError),
+ ],
+ )
+ def test_permanent_errors_are_classified_from_status_and_meta_error_code(
+ self, status_code: int, payload: Any, expected: type[Exception]
+ ) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(status_code, payload, text="body"))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+
+ with pytest.raises(expected):
+ client.get(client.build_url(ACCOUNT_ID))
+
+ # A permanent failure must not be retried — Meta's throttle budget is per app.
+ assert len(session.requested_urls) == 1
+
+ @pytest.mark.parametrize(
+ "status_code,payload",
+ [
+ (429, {"error": {"code": 4, "message": "throttled"}}),
+ # Meta reports most of its throttling as an HTTP 400 body, which a
+ # status-code retry layer would never notice.
+ (400, {"error": {"code": 4, "message": "app limit"}}),
+ (400, {"error": {"code": 32, "message": "page limit"}}),
+ (400, {"error": {"code": 2, "message": "transient"}}),
+ (503, {"error": {"code": 1, "message": "unknown"}}),
+ ],
+ )
+ def test_throttling_and_transient_errors_are_retried_then_surfaced(self, status_code: int, payload: Any) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(status_code, payload, repeat=True))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+
+ with pytest.raises(InstagramRetryableError):
+ client.get(client.build_url(ACCOUNT_ID))
+
+ assert len(session.requested_urls) == MAX_RETRY_ATTEMPTS
+
+ @pytest.mark.parametrize(
+ "status_code,code,prefix",
+ [
+ (400, 190, AUTH_ERROR_PREFIX),
+ (400, 10, PERMISSION_ERROR_PREFIX),
+ ],
+ )
+ def test_permanent_failures_carry_the_prefix_the_source_matches_on(
+ self, status_code: int, code: int, prefix: str
+ ) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(status_code, {"error": {"code": code, "message": "nope"}}))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+
+ with pytest.raises(Exception) as error:
+ client.get(client.build_url(ACCOUNT_ID))
+
+ assert prefix in str(error.value)
+
+ def test_a_throttled_request_is_retried_and_then_succeeds(self) -> None:
+ session = FakeSession(
+ [
+ (ACCOUNT_ID, FakeResponse(429, {"error": {"code": 4, "message": "throttled"}})),
+ (ACCOUNT_ID, FakeResponse(200, {"id": "1"})),
+ ]
+ )
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+ assert client.get(client.build_url(ACCOUNT_ID)) == {"id": "1"}
+
+ assert len(session.requested_urls) == 2
+
+
+class TestInstagramEdges:
+ def test_media_pages_until_meta_stops_returning_a_cursor(self) -> None:
+ session = FakeSession(
+ [
+ (
+ f"{ACCOUNT_ID}/media",
+ FakeResponse(200, _page([{"id": "1", "timestamp": "2024-03-01T18:10:00+0000"}], "CUR")),
+ ),
+ ("after=CUR", FakeResponse(200, _page([{"id": "2", "timestamp": "2024-02-01T00:00:00+0000"}]))),
+ ]
+ )
+ manager = FakeResumableSourceManager()
+
+ rows = _collect("media", session, manager)
+
+ assert [row["id"] for row in rows] == ["1", "2"]
+ # Meta's `+0000` offset is rewritten so the cursor/partition column parses.
+ assert rows[0]["timestamp"] == "2024-03-01T18:10:00+00:00"
+ assert len(session.requested_urls) == 2
+
+ def test_media_stops_when_the_cursor_is_missing_even_though_next_is_present(self) -> None:
+ session = FakeSession(
+ [(f"{ACCOUNT_ID}/media", FakeResponse(200, {"data": [{"id": "1"}], "paging": {"next": "https://x/next"}}))]
+ )
+
+ rows = _collect("media", session)
+
+ assert [row["id"] for row in rows] == ["1"]
+ assert len(session.requested_urls) == 1
+
+ def test_incremental_media_sync_asks_meta_for_the_window_after_the_watermark(self) -> None:
+ session = FakeSession()
+
+ _collect(
+ "media",
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00+0000",
+ )
+
+ assert session.params(0)["since"] == ["1704067200"]
+
+ def test_a_full_refresh_media_sync_sends_no_time_window(self) -> None:
+ session = FakeSession()
+
+ _collect("media", session, should_use_incremental_field=False, db_incremental_field_last_value="2024-01-01")
+
+ assert "since" not in session.params(0)
+
+ def test_start_date_bounds_the_first_media_sync(self) -> None:
+ session = FakeSession()
+
+ _collect("media", session, start_date="2024-01-01")
+
+ assert session.params(0)["since"] == ["1704067200"]
+
+ def test_the_next_page_is_checkpointed_only_after_its_rows_are_yielded(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "1"}], "CUR"))),
+ ("after=CUR", FakeResponse(200, _page([{"id": "2"}]))),
+ ]
+ )
+ manager = FakeResumableSourceManager()
+
+ _collect("media", session, manager)
+
+ assert len(manager.saved) == 1
+ assert "after=CUR" in manager.saved[0].next_url
+
+ def test_a_saved_checkpoint_restarts_mid_stream_instead_of_from_page_one(self) -> None:
+ session = FakeSession([("after=CUR", FakeResponse(200, _page([{"id": "2"}])))])
+ manager = FakeResumableSourceManager(
+ InstagramResumeConfig(next_url="https://graph.facebook.com/v23.0/me/media?limit=100&after=CUR")
+ )
+
+ rows = _collect("media", session, manager)
+
+ assert [row["id"] for row in rows] == ["2"]
+ assert session.requested_urls == ["https://graph.facebook.com/v23.0/me/media?limit=100&after=CUR"]
+
+ def test_the_account_endpoint_yields_the_chosen_account_node(self) -> None:
+ session = FakeSession([(f"{ACCOUNT_ID}?", FakeResponse(200, {"id": ACCOUNT_ID, "username": "posthog"}))])
+
+ rows = _collect("account", session)
+
+ assert rows == [{"id": ACCOUNT_ID, "username": "posthog"}]
+ assert f"/v23.0/{ACCOUNT_ID}?" in session.requested_urls[0]
+
+
+class TestInstagramFanOut:
+ def test_comments_carry_the_parent_media_id(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}, {"id": "m2"}]))),
+ ("m1/comments", FakeResponse(200, _page([{"id": "c1", "timestamp": "2024-03-01T18:10:00+0000"}]))),
+ ("m2/comments", FakeResponse(200, _page([{"id": "c2"}]))),
+ ]
+ )
+
+ rows = _collect("media_comments", session)
+
+ assert [(row["media_id"], row["id"]) for row in rows] == [("m1", "c1"), ("m2", "c2")]
+ assert rows[0]["timestamp"] == "2024-03-01T18:10:00+00:00"
+
+ def test_a_post_with_comments_disabled_is_skipped_rather_than_failing_the_table(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}, {"id": "m2"}]))),
+ ("m1/comments", FakeResponse(400, {"error": {"code": 100, "message": "comments disabled"}})),
+ ("m2/comments", FakeResponse(200, _page([{"id": "c2"}]))),
+ ]
+ )
+
+ rows = _collect("media_comments", session)
+
+ assert [row["id"] for row in rows] == ["c2"]
+
+ @pytest.mark.parametrize("product_type", ["FEED", "REELS", "STORY"])
+ def test_media_insights_request_the_metric_set_for_the_media_type(self, product_type: str) -> None:
+ session = FakeSession(
+ [(f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1", "media_product_type": product_type}])))]
+ )
+
+ _collect("media_insights", session)
+
+ requested = session.params(1)["metric"][0].split(",")
+ assert requested == list(MEDIA_INSIGHT_METRICS[product_type])
+
+ def test_media_insights_are_emitted_one_row_per_metric(self) -> None:
+ session = FakeSession(
+ [
+ (
+ f"{ACCOUNT_ID}/media",
+ FakeResponse(
+ 200,
+ _page([{"id": "m1", "media_product_type": "FEED", "timestamp": "2024-03-01T18:10:00+0000"}]),
+ ),
+ ),
+ (
+ "m1/insights",
+ FakeResponse(
+ 200,
+ {
+ "data": [
+ {"name": "reach", "period": "lifetime", "values": [{"value": 10}]},
+ {"name": "likes", "period": "lifetime", "total_value": {"value": 4}},
+ {"name": "shares", "period": "lifetime"},
+ ]
+ },
+ ),
+ ),
+ ]
+ )
+
+ rows = _collect("media_insights", session)
+
+ assert [(row["metric"], row["value"]) for row in rows] == [("reach", 10), ("likes", 4)]
+ assert {row["media_id"] for row in rows} == {"m1"}
+ assert rows[0]["media_timestamp"] == "2024-03-01T18:10:00+00:00"
+
+ def test_a_post_meta_refuses_to_report_on_is_skipped(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1", "media_product_type": "FEED"}]))),
+ ("m1/insights", FakeResponse(400, {"error": {"code": 100, "message": "unsupported metric"}})),
+ ]
+ )
+
+ assert _collect("media_insights", session) == []
+
+ def test_the_parent_page_is_checkpointed_once_its_children_are_drained(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}], "CUR"))),
+ ("m1/comments", FakeResponse(200, _page([{"id": "c1"}]))),
+ ("after=CUR", FakeResponse(200, _page([{"id": "m2"}]))),
+ ("m2/comments", FakeResponse(200, _page([{"id": "c2"}]))),
+ ]
+ )
+ manager = FakeResumableSourceManager()
+
+ rows = _collect("media_comments", session, manager)
+
+ assert [row["id"] for row in rows] == ["c1", "c2"]
+ assert len(manager.saved) == 1
+ assert "after=CUR" in manager.saved[0].next_url
+
+
+class TestInstagramRequestBudget:
+ """The per-stream and per-parent page caps bound one loop each; the fan-out multiplies
+ them, so a sync-wide budget is the only thing that bounds the requests a sync issues."""
+
+ def test_the_default_budget_covers_a_full_sync_of_the_biggest_documented_account(self) -> None:
+ # Meta caps the media edge at 10K posts, one insights request each.
+ assert MAX_REQUESTS_PER_SYNC > 10_000
+
+ def test_the_fan_out_stops_once_the_sync_has_spent_its_request_budget(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}, {"id": "m2"}, {"id": "m3"}]))),
+ ("m1/comments", FakeResponse(200, _page([{"id": "c1"}]))),
+ ("m2/comments", FakeResponse(200, _page([{"id": "c2"}]))),
+ ("m3/comments", FakeResponse(200, _page([{"id": "c3"}]))),
+ ]
+ )
+
+ # One parent listing plus two children is the whole budget, so the third post is
+ # never reached and the sync stops instead of fanning out further.
+ with mock.patch(f"{MODULE}.MAX_REQUESTS_PER_SYNC", 3):
+ rows = _collect("media_comments", session)
+
+ assert [row["id"] for row in rows] == ["c1", "c2"]
+ assert len(session.requested_urls) == 3
+
+ def test_a_stopped_fan_out_leaves_the_checkpoint_on_the_page_it_was_draining(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}, {"id": "m2"}], "CUR"))),
+ ("m1/comments", FakeResponse(200, _page([{"id": "c1"}]))),
+ ("m2/comments", FakeResponse(200, _page([{"id": "c2"}]))),
+ ]
+ )
+ manager = FakeResumableSourceManager()
+
+ with mock.patch(f"{MODULE}.MAX_REQUESTS_PER_SYNC", 2):
+ rows = _collect("media_comments", session, manager)
+
+ # The page is only checkpointed once every post on it has been drained, so a resumed
+ # attempt replays this page rather than skipping the post it never reached.
+ assert [row["id"] for row in rows] == ["c1"]
+ assert manager.saved == []
+
+ def test_pagination_stops_when_the_budget_runs_out_mid_stream(self) -> None:
+ session = FakeSession(
+ [
+ (f"{ACCOUNT_ID}/media", FakeResponse(200, _page([{"id": "m1"}], "CUR"))),
+ ("after=CUR", FakeResponse(200, _page([{"id": "m2"}], "CUR2"))),
+ ]
+ )
+
+ with mock.patch(f"{MODULE}.MAX_REQUESTS_PER_SYNC", 1):
+ rows = _collect("media", session)
+
+ assert [row["id"] for row in rows] == ["m1"]
+ assert len(session.requested_urls) == 1
+
+ def test_account_insight_windows_stop_when_the_budget_runs_out(self) -> None:
+ session = FakeSession([(f"{ACCOUNT_ID}/insights", FakeResponse(200, {"data": []}, repeat=True))])
+
+ with mock.patch(f"{MODULE}.MAX_REQUESTS_PER_SYNC", 2):
+ _collect("account_insights", session)
+
+ assert len(session.requested_urls) == 2
+
+ def test_the_client_refuses_a_request_once_the_budget_is_spent(self) -> None:
+ session = FakeSession()
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = InstagramClient("tok", "v23.0", LOGGER, max_requests=1)
+
+ client.get(client.build_url("me"))
+
+ assert client.requests_made == 1
+ assert client.has_request_budget() is False
+ # A caller that never checks the budget is stopped by the client itself rather than
+ # being allowed to keep drawing on the account's Meta quota.
+ with pytest.raises(InstagramRequestBudgetError):
+ client.get(client.build_url("me"))
+ assert len(session.requested_urls) == 1
+
+
+class TestInstagramAccountInsights:
+ def test_the_request_plan_groups_every_metric_under_its_window(self) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=FakeSession()):
+ client = InstagramClient("tok", "v23.0", LOGGER)
+
+ plan = _account_insight_plan(client, ACCOUNT_ID, 0, 45 * 86400)
+
+ # 45 days is two windows; each carries the full metric set so the window's rows
+ # can be emitted in date order.
+ assert [[metric for metric, _ in window] for window in plan] == [
+ list(ACCOUNT_INSIGHT_METRICS),
+ list(ACCOUNT_INSIGHT_METRICS),
+ ]
+ urls = [url for window in plan for _, url in window]
+ assert all("metric_type=time_series" in url and "period=day" in url for url in urls)
+ assert [parse_qs(urlparse(url).query)["since"][0] for url in urls[:2]] == ["0", "0"]
+ assert parse_qs(urlparse(urls[-1]).query)["since"][0] == str(30 * 86400)
+
+ def test_a_window_is_emitted_as_one_batch_in_date_order(self) -> None:
+ def _series(name: str, values: list[tuple[int, str]]) -> dict[str, Any]:
+ return {
+ "data": [
+ {
+ "name": name,
+ "period": "day",
+ "time_series": [{"value": value, "end_time": end_time} for value, end_time in values],
+ }
+ ]
+ }
+
+ session = FakeSession(
+ [
+ ("metric=reach", FakeResponse(200, _series("reach", [(5, "2024-03-02T07:00:00+0000")]))),
+ ("metric=views", FakeResponse(200, _series("views", [(9, "2024-03-01T07:00:00+0000")]))),
+ ]
+ )
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ access_token="tok",
+ api_version="v23.0",
+ endpoint="account_insights",
+ logger=LOGGER,
+ resumable_source_manager=FakeResumableSourceManager(),
+ instagram_account_id=ACCOUNT_ID,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-01",
+ )
+ )
+
+ assert len(batches) == 1
+ assert [row["date"] for row in batches[0]] == [
+ "2024-03-01T07:00:00+00:00",
+ "2024-03-02T07:00:00+00:00",
+ ]
+
+ def test_daily_points_become_one_row_per_metric_and_day(self) -> None:
+ session = FakeSession(
+ [
+ (
+ "metric=reach",
+ FakeResponse(
+ 200,
+ {
+ "data": [
+ {
+ "name": "reach",
+ "period": "day",
+ "time_series": [
+ {"value": 5, "end_time": "2024-03-01T07:00:00+0000"},
+ {"value": 7, "end_time": "2024-03-02T07:00:00+0000"},
+ ],
+ }
+ ]
+ },
+ ),
+ )
+ ]
+ )
+
+ rows = _collect(
+ "account_insights",
+ session,
+ instagram_account_id=ACCOUNT_ID,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-01",
+ )
+
+ reach_rows = [row for row in rows if row["metric"] == "reach"]
+ assert [(row["date"], row["value"]) for row in reach_rows] == [
+ ("2024-03-01T07:00:00+00:00", 5),
+ ("2024-03-02T07:00:00+00:00", 7),
+ ]
+ assert {row["instagram_account_id"] for row in reach_rows} == {ACCOUNT_ID}
+
+ def test_a_metric_meta_has_retired_is_dropped_without_failing_the_table(self) -> None:
+ session = FakeSession(
+ [
+ ("metric=reach", FakeResponse(400, {"error": {"code": 100, "message": "metric deprecated"}})),
+ (
+ "metric=views",
+ FakeResponse(
+ 200,
+ {
+ "data": [
+ {
+ "name": "views",
+ "period": "day",
+ "time_series": [{"value": 9, "end_time": "2024-03-01T07:00:00+0000"}],
+ }
+ ]
+ },
+ ),
+ ),
+ ]
+ )
+
+ rows = _collect(
+ "account_insights",
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-01",
+ )
+
+ assert [row["metric"] for row in rows] == ["views"]
+
+ def test_each_finished_window_checkpoints_the_start_of_the_next(self) -> None:
+ session = FakeSession()
+ manager = FakeResumableSourceManager()
+
+ _collect("account_insights", session, manager, start_date="2024-01-01")
+
+ assert manager.saved
+ # A checkpoint always names the first metric of the next window, and windows
+ # advance forward in time.
+ assert all("metric=reach" in state.next_url for state in manager.saved)
+ checkpoints = [int(parse_qs(urlparse(state.next_url).query)["since"][0]) for state in manager.saved]
+ assert checkpoints == sorted(checkpoints)
+
+ def test_a_checkpoint_from_an_older_window_restarts_the_plan(self) -> None:
+ session = FakeSession()
+ manager = FakeResumableSourceManager(InstagramResumeConfig(next_url="https://graph.facebook.com/stale"))
+
+ _collect(
+ "account_insights",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-01",
+ )
+
+ assert session.requested_urls
+ assert "metric=reach" in session.requested_urls[0]
+
+ def test_an_ancient_start_date_is_clamped_to_the_retention_horizon(self) -> None:
+ # Without the clamp a start date like this fans out into tens of thousands of
+ # empty 30-day windows; Meta only retains ~2 years anyway.
+ session = FakeSession()
+
+ _collect("account_insights", session, start_date="0001-01-01")
+
+ windows = [url for url in session.requested_urls if "metric=reach" in url]
+ max_windows = MAX_INSIGHTS_LOOKBACK_DAYS // ACCOUNT_INSIGHTS_WINDOW_DAYS + 1
+ assert 0 < len(windows) <= max_windows
+
+
+class TestProfessionalAccountListing:
+ def test_only_pages_with_a_linked_professional_account_are_offered(self) -> None:
+ session = FakeSession(
+ [
+ (
+ "me/accounts",
+ FakeResponse(
+ 200,
+ _page(
+ [
+ {
+ "id": "page-1",
+ "name": "PostHog",
+ "instagram_business_account": {"id": ACCOUNT_ID, "username": "posthog"},
+ },
+ {"id": "page-2", "name": "A page with no Instagram account"},
+ ]
+ ),
+ ),
+ )
+ ]
+ )
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ accounts = list_professional_accounts("tok", "v23.0", LOGGER)
+
+ assert accounts == [{"id": ACCOUNT_ID, "username": "posthog", "name": None, "page_name": "PostHog"}]
+
+ def test_every_page_of_the_listing_is_walked(self) -> None:
+ def _page_row(page_id: str, account_id: str) -> dict[str, Any]:
+ return {"id": page_id, "name": page_id, "instagram_business_account": {"id": account_id}}
+
+ session = FakeSession(
+ [
+ ("me/accounts", FakeResponse(200, _page([_page_row("page-1", "1")], "CUR"))),
+ ("after=CUR", FakeResponse(200, _page([_page_row("page-2", "2")]))),
+ ]
+ )
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ accounts = list_professional_accounts("tok", "v23.0", LOGGER)
+
+ assert [account["id"] for account in accounts] == ["1", "2"]
+
+
+class TestValidateCredentials:
+ def test_a_working_connection_validates(self) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(200, {"id": ACCOUNT_ID, "username": "posthog"}))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("tok", "v23.0", LOGGER, instagram_account_id=ACCOUNT_ID) == (True, None)
+
+ def test_no_chosen_account_is_rejected_before_any_request(self) -> None:
+ session = FakeSession()
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("tok", "v23.0", LOGGER)
+
+ assert is_valid is False
+ assert message is not None and "Choose the Instagram account" in message
+ assert session.requested_urls == []
+
+ @pytest.mark.parametrize(
+ "status_code,code,expected_fragment",
+ [
+ (400, 190, "has expired"),
+ (401, 0, "has expired"),
+ (403, 0, "missing permissions"),
+ (400, 10, "missing permissions"),
+ ],
+ )
+ def test_auth_and_scope_failures_get_actionable_messages(
+ self, status_code: int, code: int, expected_fragment: str
+ ) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(status_code, {"error": {"code": code, "message": "nope"}}))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("tok", "v23.0", LOGGER, instagram_account_id=ACCOUNT_ID)
+
+ assert is_valid is False
+ assert message is not None and expected_fragment in message
+
+ def test_a_node_without_an_id_is_not_a_professional_account(self) -> None:
+ session = FakeSession([(ACCOUNT_ID, FakeResponse(200, {}))])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("tok", "v23.0", LOGGER, instagram_account_id=ACCOUNT_ID)
+
+ assert is_valid is False
+ assert message is not None and "professional account" in message
+
+ @pytest.mark.parametrize("account_id", ["17841/../me", "me?fields=id", "17841 or 1", "abc"])
+ def test_a_non_numeric_account_id_is_rejected_before_any_request(self, account_id: str) -> None:
+ # The account ID is spliced into the Graph path, so a non-numeric value could
+ # retarget the request or inject path/query segments.
+ session = FakeSession()
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("tok", "v23.0", LOGGER, instagram_account_id=account_id)
+
+ assert is_valid is False
+ assert message is not None and "not a valid Instagram account" in message
+ assert session.requested_urls == []
+
+
+class TestInstagramSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(INSTAGRAM_ENDPOINTS))
+ def test_every_endpoint_declares_the_keys_and_partitioning_from_its_settings(self, endpoint: str) -> None:
+ config = INSTAGRAM_ENDPOINTS[endpoint]
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=FakeSession()):
+ response = instagram_source(
+ access_token="tok",
+ api_version="v23.0",
+ endpoint=endpoint,
+ logger=LOGGER,
+ resumable_source_manager=FakeResumableSourceManager(),
+ instagram_account_id=ACCOUNT_ID,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == config.sort_mode
+ assert response.partition_keys == ([config.partition_key] if config.partition_key else None)
+
+ def test_items_are_only_fetched_once_the_pipeline_iterates(self) -> None:
+ session = FakeSession()
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ response = instagram_source(
+ access_token="tok",
+ api_version="v23.0",
+ endpoint="media",
+ logger=LOGGER,
+ resumable_source_manager=FakeResumableSourceManager(),
+ instagram_account_id=ACCOUNT_ID,
+ )
+ assert session.requested_urls == []
+ list(cast("Iterable[Any]", response.items()))
+
+ assert len(session.requested_urls) == 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram_source.py
new file mode 100644
index 000000000000..633d75f8d4c8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instagram/tests/test_instagram_source.py
@@ -0,0 +1,290 @@
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldOauthAccountSelectConfig,
+ SourceFieldOauthConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.instagram import (
+ InstagramSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.instagram import (
+ AUTH_ERROR_PREFIX,
+ PERMISSION_ERROR_PREFIX,
+ InstagramAuthError,
+ InstagramResumeConfig,
+ InstagramRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.settings import (
+ ENDPOINTS,
+ INSTAGRAM_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instagram.source import InstagramSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.instagram.source"
+ACCOUNT_ID = "17841400000000000"
+
+
+def _inputs(schema_name: str = "media", **overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-id",
+ "logger": structlog.get_logger("instagram-tests"),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestInstagramSource:
+ def setup_method(self) -> None:
+ self.source = InstagramSource()
+ self.team_id = 1
+ self.config = InstagramSourceConfig(instagram_integration_id=7, instagram_account_id=ACCOUNT_ID)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.INSTAGRAM
+
+ def test_the_source_ships_visible_and_documented(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Instagram"
+ assert config.label == "Instagram"
+ assert config.category == DataWarehouseSourceCategory.COMMUNICATION
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.featureFlag == "dwh-instagram"
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/instagram.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/instagram"
+
+ def test_source_fields(self) -> None:
+ config = self.source.get_source_config
+
+ assert [field.name for field in config.fields] == [
+ "instagram_integration_id",
+ "instagram_account_id",
+ "start_date",
+ ]
+
+ def test_the_connection_is_a_posthog_owned_oauth_app(self) -> None:
+ integration = next(f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldOauthConfig))
+
+ assert integration.kind == "instagram"
+ assert integration.required is True
+ # The insights and comments tables are unreadable without these, so the frontend has to
+ # be able to tell the user which grant is missing.
+ assert integration.requiredScopes is not None
+ assert set(integration.requiredScopes.split(" ")) == {
+ "instagram_basic",
+ "instagram_manage_insights",
+ "instagram_manage_comments",
+ "pages_show_list",
+ "pages_read_engagement",
+ }
+
+ def test_the_account_is_picked_from_the_connection_rather_than_typed_in(self) -> None:
+ account = next(
+ f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldOauthAccountSelectConfig)
+ )
+
+ assert account.name == "instagram_account_id"
+ assert account.integrationField == "instagram_integration_id"
+ assert account.integrationKind == "instagram"
+ assert account.required is True
+
+ def test_the_graph_api_version_is_pinned_to_something_the_code_calls(self) -> None:
+ assert self.source.default_version in self.source.supported_versions
+ assert self.source.resolve_api_version(None) == "v23.0"
+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+
+ def test_get_schemas_honors_the_picker_filter(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["media", "account"])
+
+ assert {schema.name for schema in schemas} == {"media", "account"}
+
+ @pytest.mark.parametrize(
+ "endpoint,incremental,field_name",
+ [
+ ("media", True, "timestamp"),
+ ("account_insights", True, "date"),
+ ("account", False, None),
+ ("stories", False, None),
+ ("media_comments", False, None),
+ ("media_insights", False, None),
+ ],
+ )
+ def test_only_endpoints_with_a_server_side_time_filter_sync_incrementally(
+ self, endpoint: str, incremental: bool, field_name: Optional[str]
+ ) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ assert schema.supports_incremental is incremental
+ assert [f["field"] for f in schema.incremental_fields] == ([field_name] if field_name else [])
+
+ def test_fan_out_tables_key_on_the_parent_so_rows_stay_unique_table_wide(self) -> None:
+ assert INSTAGRAM_ENDPOINTS["media_comments"].primary_keys == ["media_id", "id"]
+ assert INSTAGRAM_ENDPOINTS["media_insights"].primary_keys == ["media_id", "metric"]
+
+ def test_the_table_catalog_is_published_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ documented = {table["name"] for table in self.source.get_documented_tables()}
+ assert documented == set(ENDPOINTS)
+
+ def test_every_endpoint_is_described_from_the_meta_docs(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions) == set(ENDPOINTS)
+ assert all(descriptions[name].get("columns") for name in ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ f"{AUTH_ERROR_PREFIX}: status=400, code=190, message=Session has expired",
+ f"{PERMISSION_ERROR_PREFIX}: status=400, code=10, message=Application does not have permission",
+ "Failed to refresh the Instagram connection",
+ "Integration not found: 7",
+ ],
+ )
+ def test_auth_and_scope_failures_stop_the_source_instead_of_retrying(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_a_throttling_error_is_left_retryable(self) -> None:
+ observed_error = "Instagram API error (retryable): status=429, code=4, message=rate limited"
+
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_validate_credentials_uses_the_connection_token_and_the_chosen_account(self) -> None:
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="refreshed-token"),
+ mock.patch(f"{SOURCE_MODULE}.validate_instagram_credentials", return_value=(True, None)) as validate,
+ ):
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+
+ assert validate.call_args.kwargs["access_token"] == "refreshed-token"
+ assert validate.call_args.kwargs["instagram_account_id"] == ACCOUNT_ID
+ assert validate.call_args.kwargs["api_version"] == "v23.0"
+
+ def test_validate_credentials_fails_cleanly_when_the_connection_is_gone(self) -> None:
+ with (
+ mock.patch.object(InstagramSource, "_access_token", side_effect=ValueError("Integration not found: 7")),
+ mock.patch(f"{SOURCE_MODULE}.validate_instagram_credentials") as validate,
+ ):
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert message is not None and "Connect an Instagram account" in message
+ validate.assert_not_called()
+
+ def test_validate_credentials_surfaces_the_failure_message(self) -> None:
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="tok"),
+ mock.patch(f"{SOURCE_MODULE}.validate_instagram_credentials", return_value=(False, "bad token")),
+ ):
+ assert self.source.validate_credentials(self.config, self.team_id) == (False, "bad token")
+
+ def test_the_account_picker_lists_the_professional_accounts_the_connection_can_reach(self) -> None:
+ listed = [
+ {"id": ACCOUNT_ID, "username": "posthog", "name": "PostHog", "page_name": "PostHog page"},
+ {"id": "17841999", "username": None, "name": None, "page_name": "Unnamed page"},
+ ]
+
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="tok"),
+ mock.patch(f"{SOURCE_MODULE}.list_professional_accounts", return_value=listed),
+ ):
+ accounts = self.source.get_oauth_accounts(7, self.team_id)
+
+ assert [(account.value, account.display_name, account.secondary_text) for account in accounts] == [
+ (ACCOUNT_ID, "posthog", "PostHog page"),
+ ("17841999", "Instagram account", "Unnamed page"),
+ ]
+
+ @pytest.mark.parametrize(
+ "raised,expected_fragment",
+ [
+ (InstagramAuthError("nope"), "Reconnect your Instagram account"),
+ (InstagramRetryableError("throttled"), "try again in a few minutes"),
+ ],
+ )
+ def test_a_failing_account_listing_is_reported_as_something_the_user_can_act_on(
+ self, raised: Exception, expected_fragment: str
+ ) -> None:
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="tok"),
+ mock.patch(f"{SOURCE_MODULE}.list_professional_accounts", side_effect=raised),
+ ):
+ with pytest.raises(IntegrationAccountListingError, match=expected_fragment):
+ self.source.get_oauth_accounts(7, self.team_id)
+
+ def test_the_resume_manager_is_isolated_per_table(self) -> None:
+ media = self.source.get_resumable_source_manager(_inputs("media"))
+ comments = self.source.get_resumable_source_manager(_inputs("media_comments"))
+
+ assert isinstance(media, ResumableSourceManager)
+ assert media._data_class is InstagramResumeConfig
+ # Each table checkpoints a URL built for its own edge, so the Redis slots differ.
+ assert media._key != comments._key
+
+ def test_source_for_pipeline_syncs_with_the_connection_token(self) -> None:
+ config = InstagramSourceConfig(
+ instagram_integration_id=7, instagram_account_id=ACCOUNT_ID, start_date="2024-01-01"
+ )
+ inputs = _inputs(
+ "media",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-06-01T00:00:00+0000",
+ api_version="v22.0",
+ )
+
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="refreshed-token"),
+ mock.patch(f"{SOURCE_MODULE}.instagram_source") as build_source,
+ ):
+ self.source.source_for_pipeline(config, self.source.get_resumable_source_manager(inputs), inputs)
+
+ kwargs = build_source.call_args.kwargs
+ assert kwargs["access_token"] == "refreshed-token"
+ assert kwargs["endpoint"] == "media"
+ assert kwargs["api_version"] == "v22.0"
+ assert kwargs["instagram_account_id"] == ACCOUNT_ID
+ assert kwargs["start_date"] == "2024-01-01"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01T00:00:00+0000"
+
+ def test_a_full_refresh_run_never_forwards_a_watermark(self) -> None:
+ inputs = _inputs("media", should_use_incremental_field=False, db_incremental_field_last_value="2024-06-01")
+
+ with (
+ mock.patch.object(InstagramSource, "_access_token", return_value="tok"),
+ mock.patch(f"{SOURCE_MODULE}.instagram_source") as build_source,
+ ):
+ self.source.source_for_pipeline(self.config, self.source.get_resumable_source_manager(inputs), inputs)
+
+ assert build_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 496afd3c835f..e5237e9baa84 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5791,6 +5791,7 @@ export namespace Schemas {
Github: 'github',
Gitlab: 'gitlab',
MetaAds: 'meta-ads',
+ Instagram: 'instagram',
Clickup: 'clickup',
RedditAds: 'reddit-ads',
Databricks: 'databricks',
@@ -40029,6 +40030,7 @@ export namespace Schemas {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -40079,6 +40081,7 @@ export namespace Schemas {
GoogleSearchConsole: 'google-search-console',
GoogleSheets: 'google-sheets',
Hubspot: 'hubspot',
+ Instagram: 'instagram',
Intercom: 'intercom',
Jira: 'jira',
Linear: 'linear',
@@ -40129,6 +40132,7 @@ export namespace Schemas {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -84877,6 +84881,7 @@ export namespace Schemas {
* * `google-search-console` - Google Search Console
* * `google-sheets` - Google Sheets
* * `hubspot` - Hubspot
+ * * `instagram` - Instagram
* * `intercom` - Intercom
* * `jira` - Jira
* * `linear` - Linear
@@ -84938,6 +84943,7 @@ export namespace Schemas {
GoogleSearchConsole: 'google-search-console',
GoogleSheets: 'google-sheets',
Hubspot: 'hubspot',
+ Instagram: 'instagram',
Intercom: 'intercom',
Jira: 'jira',
Linear: 'linear',
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index bb07eead7a87..342bb30f206b 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -43,6 +43,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({
'google-search-console',
'google-sheets',
'hubspot',
+ 'instagram',
'intercom',
'jira',
'linear',
@@ -67,7 +68,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
index cff7b622288f..21c6dad5f3b5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"kind": {
- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",
+ "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",
"enum": [
"anthropic",
"apns",
@@ -28,6 +28,7 @@
"google-search-console",
"google-sheets",
"hubspot",
+ "instagram",
"intercom",
"jira",
"linear",