: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement dynamics365 source (#73763)
Tom Owers52b7b864ec12
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9634b2f2e1c1..00b468932587 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -230,6 +230,7 @@ the row lists both.| dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ || dub | HTTP | requests + `rest_source.RESTClient` | ✅ |+| dynamics365 | HTTP | requests + `rest_source.RESTClient` | ✅ || dynamodb | HTTP | requests | ✅ || dynatrace | HTTP | requests | ✅ || e2b | HTTP | requests | ✅ |@@ -951,7 +952,6 @@ doesn't conflict with concurrent PRs.- dubsado- ducklake- dwolla-- dynamics365- dynamics_365_business_central- e2b- easybilldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/canonical_descriptions.pynew file mode 100644index 000000000000..be00c801e4c7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/canonical_descriptions.py@@ -0,0 +1,368 @@+"""Curated table/column descriptions from the Dataverse table reference on Microsoft Learn.++Dataverse returns lookup columns as `_<name>_value`, so that's how they're keyed here. Every+standard table shares the ownership and audit columns in `_SYSTEM_COLUMNS`.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.settings import DYNAMICS365_ENDPOINTS++_SYSTEM_COLUMNS: dict[str, str] = {+ "createdon": "Date and time the record was created.",+ "modifiedon": "Date and time the record was last modified.",+ "_createdby_value": "User who created the record.",+ "_modifiedby_value": "User who last modified the record.",+ "_ownerid_value": "User or team that owns the record.",+ "_owningbusinessunit_value": "Business unit that owns the record.",+ "_owninguser_value": "User that owns the record, when ownership isn't held by a team.",+ "_owningteam_value": "Team that owns the record, when ownership isn't held by a user.",+ "statecode": "State of the record, for example active or inactive.",+ "statuscode": "Reason for the record's current state.",+ "versionnumber": "Row version, incremented on every change.",+ "importsequencenumber": "Sequence number of the data import that created the record.",+ "overriddencreatedon": "Original creation date and time of a record brought in by a data import.",+ "_transactioncurrencyid_value": "Currency the record's monetary amounts are stored in.",+ "exchangerate": "Exchange rate between the record's currency and the base currency.",+}++_COLUMNS: dict[str, dict[str, str]] = {+ "Accounts": {+ "accountid": "Unique identifier of the account.",+ "name": "Company or business name.",+ "accountnumber": "Account number, usually from an external accounting system.",+ "accountcategorycode": "Category of the account, for example preferred customer or standard.",+ "customertypecode": "Relationship type, for example customer, competitor, or vendor.",+ "industrycode": "Industry the account operates in.",+ "ownershipcode": "Ownership structure, for example public or private.",+ "emailaddress1": "Primary email address of the account.",+ "telephone1": "Main phone number of the account.",+ "websiteurl": "Website of the account.",+ "revenue": "Annual revenue of the account.",+ "numberofemployees": "Number of employees at the account.",+ "description": "Additional information about the account.",+ "_primarycontactid_value": "Primary contact for the account.",+ "_parentaccountid_value": "Parent account in the account hierarchy.",+ "address1_city": "City of the primary address.",+ "address1_stateorprovince": "State or province of the primary address.",+ "address1_postalcode": "ZIP or postal code of the primary address.",+ "address1_country": "Country or region of the primary address.",+ },+ "Contacts": {+ "contactid": "Unique identifier of the contact.",+ "fullname": "Full name of the contact.",+ "firstname": "First name of the contact.",+ "lastname": "Last name of the contact.",+ "jobtitle": "Job title of the contact.",+ "emailaddress1": "Primary email address of the contact.",+ "telephone1": "Business phone number of the contact.",+ "mobilephone": "Mobile phone number of the contact.",+ "_parentcustomerid_value": "Account or contact the contact belongs to.",+ "birthdate": "Birthday of the contact.",+ "gendercode": "Gender of the contact.",+ "donotemail": "Whether the contact has opted out of email.",+ "donotbulkemail": "Whether the contact has opted out of bulk email.",+ "donotphone": "Whether the contact has opted out of phone calls.",+ "preferredcontactmethodcode": "How the contact prefers to be contacted.",+ "description": "Additional information about the contact.",+ "address1_city": "City of the primary address.",+ "address1_country": "Country or region of the primary address.",+ },+ "Leads": {+ "leadid": "Unique identifier of the lead.",+ "subject": "Short description of the lead.",+ "fullname": "Full name of the lead's primary contact.",+ "firstname": "First name of the lead's primary contact.",+ "lastname": "Last name of the lead's primary contact.",+ "companyname": "Company the lead belongs to.",+ "jobtitle": "Job title of the lead's primary contact.",+ "emailaddress1": "Primary email address of the lead.",+ "telephone1": "Phone number of the lead.",+ "leadsourcecode": "How the lead was generated, for example web or trade show.",+ "leadqualitycode": "Rating of the lead, for example hot, warm, or cold.",+ "estimatedvalue": "Estimated revenue the lead could generate.",+ "estimatedclosedate": "Date the lead is expected to close.",+ "budgetamount": "Budget the lead has available.",+ "_campaignid_value": "Campaign the lead responded to.",+ "_qualifyingopportunityid_value": "Opportunity created when the lead was qualified.",+ "_parentaccountid_value": "Account the lead was converted into or belongs to.",+ "_parentcontactid_value": "Contact the lead was converted into or belongs to.",+ "description": "Additional information about the lead.",+ },+ "Opportunities": {+ "opportunityid": "Unique identifier of the opportunity.",+ "name": "Short description of the opportunity.",+ "_customerid_value": "Account or contact the opportunity is for.",+ "_parentaccountid_value": "Account the opportunity is associated with.",+ "_parentcontactid_value": "Contact the opportunity is associated with.",+ "estimatedvalue": "Estimated revenue of the opportunity.",+ "estimatedclosedate": "Date the opportunity is expected to close.",+ "actualvalue": "Revenue realised when the opportunity closed.",+ "actualclosedate": "Date the opportunity was won or lost.",+ "closeprobability": "Probability, as a percentage, that the opportunity will close.",+ "salesstagecode": "Stage of the sales process the opportunity is in.",+ "stepname": "Current step within the sales stage.",+ "budgetamount": "Budget the customer has available.",+ "_campaignid_value": "Campaign the opportunity came from.",+ "description": "Additional information about the opportunity.",+ },+ "Cases": {+ "incidentid": "Unique identifier of the case.",+ "ticketnumber": "Human-readable case number.",+ "title": "Subject of the case.",+ "description": "Details of the customer's issue.",+ "_customerid_value": "Account or contact the case was raised for.",+ "_primarycontactid_value": "Contact handling the case on the customer's side.",+ "casetypecode": "Type of case, for example question, problem, or request.",+ "caseorigincode": "Channel the case arrived through, for example phone, email, or web.",+ "prioritycode": "Priority of the case.",+ "severitycode": "Severity of the case.",+ "resolveby": "Date and time the case must be resolved by.",+ "followupby": "Date and time a follow-up with the customer is due.",+ "_parentcaseid_value": "Parent case, when this case is a child of another.",+ "_productid_value": "Product the case relates to.",+ "_subjectid_value": "Subject the case is filed under.",+ "_entitlementid_value": "Entitlement applied to the case.",+ },+ "Campaigns": {+ "campaignid": "Unique identifier of the campaign.",+ "name": "Name of the campaign.",+ "codename": "Code identifying the campaign.",+ "description": "Additional information about the campaign.",+ "typecode": "Type of campaign, for example advertisement or event.",+ "objective": "Goal of the campaign.",+ "proposedstart": "Planned start date of the campaign.",+ "proposedend": "Planned end date of the campaign.",+ "actualstart": "Date the campaign actually started.",+ "actualend": "Date the campaign actually ended.",+ "budgetedcost": "Budgeted cost of the campaign.",+ "totalactualcost": "Total cost incurred by the campaign.",+ "expectedresponse": "Expected response rate, as a percentage.",+ "expectedrevenue": "Revenue the campaign is expected to generate.",+ "promotioncodename": "Promotional code offered by the campaign.",+ },+ "Quotes": {+ "quoteid": "Unique identifier of the quote.",+ "quotenumber": "Human-readable quote number.",+ "name": "Name of the quote.",+ "revisionnumber": "Revision of the quote.",+ "_customerid_value": "Account or contact the quote is for.",+ "_opportunityid_value": "Opportunity the quote belongs to.",+ "_pricelevelid_value": "Price list applied to the quote.",+ "totalamount": "Total of the quote, after discounts, freight, and tax.",+ "totallineitemamount": "Sum of the quote's line item amounts.",+ "discountamount": "Discount applied to the quote.",+ "freightamount": "Shipping cost on the quote.",+ "totaltax": "Tax on the quote.",+ "effectivefrom": "Date the quote's pricing becomes effective.",+ "effectiveto": "Date the quote's pricing stops being effective.",+ "expireson": "Date the quote expires.",+ },+ "Orders": {+ "salesorderid": "Unique identifier of the order.",+ "ordernumber": "Human-readable order number.",+ "name": "Name of the order.",+ "_customerid_value": "Account or contact the order is for.",+ "_opportunityid_value": "Opportunity the order came from.",+ "_quoteid_value": "Quote the order was created from.",+ "_pricelevelid_value": "Price list applied to the order.",+ "totalamount": "Total of the order, after discounts, freight, and tax.",+ "totallineitemamount": "Sum of the order's line item amounts.",+ "discountamount": "Discount applied to the order.",+ "freightamount": "Shipping cost on the order.",+ "totaltax": "Tax on the order.",+ "requestdeliveryby": "Date the customer wants the order delivered by.",+ "datefulfilled": "Date the order was fulfilled.",+ },+ "Invoices": {+ "invoiceid": "Unique identifier of the invoice.",+ "invoicenumber": "Human-readable invoice number.",+ "name": "Name of the invoice.",+ "_customerid_value": "Account or contact the invoice is for.",+ "_salesorderid_value": "Order the invoice was created from.",+ "_opportunityid_value": "Opportunity the invoice relates to.",+ "_pricelevelid_value": "Price list applied to the invoice.",+ "totalamount": "Total of the invoice, after discounts, freight, and tax.",+ "totallineitemamount": "Sum of the invoice's line item amounts.",+ "discountamount": "Discount applied to the invoice.",+ "freightamount": "Shipping cost on the invoice.",+ "totaltax": "Tax on the invoice.",+ "duedate": "Date payment is due.",+ "datedelivered": "Date the invoiced items were delivered.",+ },+ "Products": {+ "productid": "Unique identifier of the product.",+ "name": "Name of the product.",+ "productnumber": "Part or product number.",+ "description": "Additional information about the product.",+ "producttypecode": "Type of product, for example sales inventory or services.",+ "productstructure": "Whether the product is a standalone product, a family, or a bundle.",+ "price": "List price of the product.",+ "standardcost": "Standard cost of the product.",+ "currentcost": "Current cost of the product.",+ "quantityonhand": "Quantity currently in stock.",+ "validfromdate": "Date the product becomes available.",+ "validtodate": "Date the product stops being available.",+ "isstockitem": "Whether the product is stocked as inventory.",+ "_parentproductid_value": "Product family or bundle the product belongs to.",+ "_defaultuomid_value": "Default unit the product is sold in.",+ },+ "Activities": {+ "activityid": "Unique identifier of the activity.",+ "activitytypecode": "Type of activity, for example email, phone call, task, or appointment.",+ "subject": "Subject of the activity.",+ "description": "Details of the activity.",+ "_regardingobjectid_value": "Record the activity relates to, for example an account or case.",+ "scheduledstart": "Date and time the activity is scheduled to start.",+ "scheduledend": "Date and time the activity is scheduled to end.",+ "actualstart": "Date and time the activity actually started.",+ "actualend": "Date and time the activity actually ended.",+ "scheduleddurationminutes": "Scheduled duration of the activity, in minutes.",+ "actualdurationminutes": "Actual duration of the activity, in minutes.",+ "prioritycode": "Priority of the activity.",+ "instancetypecode": "Whether the activity is a single instance, a series, or an occurrence.",+ "isbilled": "Whether the activity was billed as part of a contract.",+ "isregularactivity": "Whether this is a regular activity rather than a service appointment.",+ },+ "Tasks": {+ "activityid": "Unique identifier of the task.",+ "subject": "Subject of the task.",+ "description": "Details of the task.",+ "_regardingobjectid_value": "Record the task relates to.",+ "scheduledstart": "Date and time the task is scheduled to start.",+ "scheduledend": "Due date and time of the task.",+ "actualdurationminutes": "Time spent on the task, in minutes.",+ "percentcomplete": "How complete the task is, as a percentage.",+ "prioritycode": "Priority of the task.",+ },+ "PhoneCalls": {+ "activityid": "Unique identifier of the phone call.",+ "subject": "Subject of the phone call.",+ "description": "Notes taken during the phone call.",+ "phonenumber": "Number that was called.",+ "directioncode": "Whether the call was outgoing or incoming.",+ "_regardingobjectid_value": "Record the phone call relates to.",+ "actualstart": "Date and time the call started.",+ "actualend": "Date and time the call ended.",+ "actualdurationminutes": "Duration of the call, in minutes.",+ "prioritycode": "Priority of the phone call.",+ },+ "Emails": {+ "activityid": "Unique identifier of the email.",+ "subject": "Subject line of the email.",+ "description": "Body of the email.",+ "sender": "Email address the message was sent from.",+ "torecipients": "Email addresses the message was sent to.",+ "directioncode": "Whether the email was outgoing or incoming.",+ "messageid": "Message id assigned by the email provider.",+ "senton": "Date and time the email was sent.",+ "_regardingobjectid_value": "Record the email relates to.",+ "deliveryreceiptrequested": "Whether a delivery receipt was requested.",+ "prioritycode": "Priority of the email.",+ },+ "Appointments": {+ "activityid": "Unique identifier of the appointment.",+ "subject": "Subject of the appointment.",+ "description": "Details of the appointment.",+ "location": "Where the appointment takes place.",+ "scheduledstart": "Date and time the appointment starts.",+ "scheduledend": "Date and time the appointment ends.",+ "scheduleddurationminutes": "Duration of the appointment, in minutes.",+ "isalldayevent": "Whether the appointment lasts all day.",+ "_regardingobjectid_value": "Record the appointment relates to.",+ "prioritycode": "Priority of the appointment.",+ },+ "Notes": {+ "annotationid": "Unique identifier of the note.",+ "subject": "Title of the note.",+ "notetext": "Body text of the note.",+ "filename": "Name of the file attached to the note.",+ "filesize": "Size of the attached file, in bytes.",+ "mimetype": "MIME type of the attached file.",+ "isdocument": "Whether the note has a file attached.",+ "_objectid_value": "Record the note is attached to.",+ "objecttypecode": "Type of record the note is attached to.",+ },+ "Competitors": {+ "competitorid": "Unique identifier of the competitor.",+ "name": "Name of the competitor.",+ "description": "Additional information about the competitor.",+ "websiteurl": "Website of the competitor.",+ "tickersymbol": "Stock exchange ticker symbol of the competitor.",+ "reportedrevenue": "Revenue the competitor reports.",+ "strengths": "Strengths of the competitor.",+ "weaknesses": "Weaknesses of the competitor.",+ "opportunities": "Opportunities available to the competitor.",+ "threats": "Threats facing the competitor.",+ "keyproduct": "Competitor's primary product.",+ "address1_city": "City of the competitor's primary address.",+ "address1_country": "Country or region of the competitor's primary address.",+ },+ "Users": {+ "systemuserid": "Unique identifier of the user.",+ "fullname": "Full name of the user.",+ "firstname": "First name of the user.",+ "lastname": "Last name of the user.",+ "domainname": "Sign-in name of the user.",+ "internalemailaddress": "Primary email address of the user.",+ "title": "Job title of the user.",+ "isdisabled": "Whether the user's account is disabled.",+ "_businessunitid_value": "Business unit the user belongs to.",+ "_parentsystemuserid_value": "Manager of the user.",+ "_territoryid_value": "Sales territory the user belongs to.",+ "applicationid": "Entra ID application id, set for application (service) users.",+ },+ "Teams": {+ "teamid": "Unique identifier of the team.",+ "name": "Name of the team.",+ "description": "Additional information about the team.",+ "teamtype": "Type of team, for example owner, access, or Microsoft Entra ID group.",+ "_businessunitid_value": "Business unit the team belongs to.",+ "_administratorid_value": "User who administers the team.",+ "isdefault": "Whether this is the default team of its business unit.",+ "emailaddress": "Email address of the team.",+ },+ "BusinessUnits": {+ "businessunitid": "Unique identifier of the business unit.",+ "name": "Name of the business unit.",+ "divisionname": "Division the business unit belongs to.",+ "_parentbusinessunitid_value": "Parent business unit in the hierarchy.",+ "isdisabled": "Whether the business unit is disabled.",+ "emailaddress": "Email address of the business unit.",+ "websiteurl": "Website of the business unit.",+ "costcenter": "Cost center the business unit reports against.",+ },+}++_DESCRIPTIONS: dict[str, str] = {+ "Accounts": "Businesses your organization has a relationship with — customers, prospects, partners, competitors, and vendors.",+ "Contacts": "People your organization has a relationship with, usually linked to an account.",+ "Leads": "Potential customers who haven't yet been qualified into an account, contact, or opportunity.",+ "Opportunities": "Potential revenue-generating deals with a customer, tracked through the sales process.",+ "Cases": "Customer service requests, questions, and problems (the `incident` table).",+ "Campaigns": "Marketing programs run to promote a product or service, with their planned and actual costs.",+ "Quotes": "Formal offers of products or services at proposed prices, issued to a customer.",+ "Orders": "Confirmed customer orders for products or services (the `salesorder` table).",+ "Invoices": "Bills issued to customers for ordered products or services.",+ "Products": "Items and services your organization sells, including product families and bundles.",+ "Activities": "Every activity in the system through its shared base table (`activitypointer`) — emails, phone calls, tasks, appointments, and more.",+ "Tasks": "Work items assigned to a user, with a due date and completion state.",+ "PhoneCalls": "Logged inbound and outbound phone calls, with duration and outcome.",+ "Emails": "Emails tracked in Dynamics 365, including sender, recipients, and body.",+ "Appointments": "Scheduled meetings and commitments, with attendees and location.",+ "Notes": "Notes and attachments linked to other records (the `annotation` table). File contents are not synced.",+ "Competitors": "Competing organizations, with the products and SWOT analysis recorded against them.",+ "Users": "Users of the Dynamics 365 environment, including application (service) users.",+ "Teams": "Groups of users that can own records and share access.",+ "BusinessUnits": "Organizational units that scope record ownership and security.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ name: {+ "description": _DESCRIPTIONS[name],+ "docs_url": config.docs_url,+ "columns": {**_COLUMNS[name], **_SYSTEM_COLUMNS},+ }+ for name, config in DYNAMICS365_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/dynamics365.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/dynamics365.pynew file mode 100644index 000000000000..49307bd14691--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/dynamics365.py@@ -0,0 +1,291 @@+import re+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlparse++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponsePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.settings import (+ DYNAMICS365_ENDPOINTS,+ DYNAMICS365_LOGIN_HOST,+ DYNAMICS365_PAGE_SIZE,+ DYNAMICS365_REQUEST_TIMEOUT,+ Dynamics365EndpointConfig,+)++# The environment URL is customer-supplied and is where the minted access token is sent, so it is+# pinned to the hosts Microsoft actually serves Dataverse on: `{org}[.api].crm{n}.<suffix>`, where+# crm{n} is the region (crm = North America, crm4 = EMEA, crm11 = UK, ...) and the suffix covers+# commercial, China (21Vianet), and US government clouds. Anything else — including an internal+# host or an attacker's server — is refused before a token is minted.+_ORGANIZATION_HOST_RE = re.compile(+ r"^[a-z0-9][a-z0-9-]{0,62}(\.api)?\.crm[0-9]{0,2}\.(dynamics\.com|dynamics\.cn|microsoftdynamics\.us|appsplatform\.us)$"+)+# Entra tenant ids are GUIDs or verified domain names; both are interpolated into the token URL+# path, so anything that could escape that path segment is refused.+_TENANT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")+# A watermark that reaches `$filter` as a string must look like a timestamp — the value is+# interpolated into an OData expression, so an arbitrary string can't be passed through.+_TIMESTAMP_RE = re.compile(r"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$")++INVALID_ORGANIZATION_URL_ERROR = "Enter your Dynamics 365 environment URL, for example https://contoso.crm.dynamics.com"+INVALID_TENANT_ID_ERROR = "Enter the directory (tenant) ID of your Microsoft Entra ID tenant"+INVALID_WATERMARK_ERROR = "The stored incremental value is not a timestamp Dynamics 365 can filter on"+++class Dynamics365ConfigurationError(Exception):+ """A customer-supplied value can't be used to build a Dataverse request."""++[email protected](frozen=True)+class Dynamics365ResumeConfig:+ # Opaque `@odata.nextLink` of the next unfetched page (it embeds Dataverse's $skiptoken, which+ # must never be constructed by hand).+ next_url: Optional[str] = None+++def normalize_organization_url(raw: str) -> str:+ """Validate the environment URL and reduce it to `https://<host>`.++ Rebuilding from the parsed hostname alone drops any port, userinfo, path, or query the user+ pasted, so the base URL can't be pointed at a non-Dataverse target.+ """+ value = (raw or "").strip().rstrip("/")+ if not value:+ raise Dynamics365ConfigurationError(INVALID_ORGANIZATION_URL_ERROR)+ if "://" not in value:+ value = f"https://{value}"+ parsed = urlparse(value)+ host = (parsed.hostname or "").lower()+ if parsed.scheme != "https" or not _ORGANIZATION_HOST_RE.match(host):+ raise Dynamics365ConfigurationError(INVALID_ORGANIZATION_URL_ERROR)+ return f"https://{host}"+++def token_url(tenant_id: str) -> str:+ value = (tenant_id or "").strip()+ if not _TENANT_ID_RE.match(value):+ raise Dynamics365ConfigurationError(INVALID_TENANT_ID_ERROR)+ return f"https://{DYNAMICS365_LOGIN_HOST}/{value}/oauth2/v2.0/token"+++def base_url(organization_url: str, api_version: str) -> str:+ return f"{organization_url}/api/data/{api_version}"+++def make_auth(tenant_id: str, client_id: str, client_secret: str, organization_url: str) -> OAuth2Auth:+ """Build the client-credentials auth for a Dataverse application user.++ The app registration's secret is exchanged for an access token scoped to the environment+ itself (`https://{org}.crm.dynamics.com/.default`); the framework caches it for the run and+ re-mints on expiry.+ """+ return OAuth2Auth(+ token_url=token_url(tenant_id),+ client_id=client_id,+ client_secret=client_secret,+ grant_type="client_credentials",+ scopes=f"{organization_url}/.default",+ )+++def request_headers() -> dict[str, str]:+ return {+ "Accept": "application/json",+ "OData-MaxVersion": "4.0",+ "OData-Version": "4.0",+ # Without this Dataverse pages at 5,000 rows anyway, but declaring it keeps the page size+ # stable if the server default ever changes.+ "Prefer": f"odata.maxpagesize={DYNAMICS365_PAGE_SIZE}",+ }+++def format_odata_datetime(value: Any) -> str:+ if isinstance(value, datetime):+ moment = value if value.tzinfo else value.replace(tzinfo=UTC)+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ text = str(value).strip()+ if not _TIMESTAMP_RE.match(text):+ raise Dynamics365ConfigurationError(INVALID_WATERMARK_ERROR)+ return text.replace(" ", "T")+++def resolve_incremental_field(config: Dynamics365EndpointConfig, requested: Optional[str]) -> str:+ """Honour the cursor the user picked in the schema settings, ignoring anything unadvertised.++ The name is interpolated into `$filter` and `$orderby`, so only the advertised columns are+ accepted — an unexpected value falls back to the endpoint default rather than reaching OData.+ """+ advertised = {incremental["field"] for incremental in config.incremental_fields}+ if requested in advertised:+ return str(requested)+ return config.default_incremental_field+++def build_query_params(+ config: Dynamics365EndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ incremental_field: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.select:+ params["$select"] = ",".join(config.select)+ if not should_use_incremental_field:+ return params++ cursor = resolve_incremental_field(config, incremental_field)+ # Dataverse's default order is undocumented, so the cursor column is ordered explicitly to make+ # the ascending `sort_mode` the pipeline checkpoints against true.+ params["$orderby"] = f"{cursor} asc"+ if db_incremental_field_last_value is not None:+ params["$filter"] = f"{cursor} gt {format_odata_datetime(db_incremental_field_last_value)}"+ return params+++def strip_odata_annotations(row: dict[str, Any]) -> dict[str, Any]:+ """Drop the OData control annotations Dataverse mixes into every record.++ Each row carries `@odata.etag` (and, when requested, formatted-value annotations); those aren't+ table columns and an `@` in a column name is hostile to everything downstream.+ """+ return {key: value for key, value in row.items() if "@" not in key}+++def _client_config(auth: OAuth2Auth, organization_url: str, api_version: str) -> ClientConfig:+ return {+ "base_url": base_url(organization_url, api_version),+ "headers": request_headers(),+ "auth": auth,+ # `@odata.nextLink` is an absolute URL carrying an opaque $skiptoken plus the original+ # query, so the filter and ordering persist across pages.+ "paginator": JSONResponsePaginator(next_url_path="'@odata.nextLink'"),+ # Pin every request — including next links — to the validated environment host, and refuse+ # redirects, so a spoofed link can't carry the access token off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": DYNAMICS365_REQUEST_TIMEOUT,+ }+++def dynamics365_source(+ organization_url: str,+ tenant_id: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[Dynamics365ResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = DYNAMICS365_ENDPOINTS[endpoint]+ organization = normalize_organization_url(organization_url)+ auth = make_auth(tenant_id, client_id, client_secret, organization)++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_url is not None:+ initial_paginator_state = {"next_url": resume.next_url}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # The hook fires after a page has been yielded, so a crash re-yields the last batch (the+ # merge dedupes on the GUID primary key) instead of skipping it.+ if state is not None and state.get("next_url") is not None:+ resumable_source_manager.save_state(Dynamics365ResumeConfig(next_url=str(state["next_url"])))++ endpoint_config: Endpoint = {+ "path": f"/{config.entity_set}",+ "params": build_query_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ ),+ "data_selector": "value",+ # An OData collection response always carries `value`. Failing loud beats silently syncing+ # zero rows if a request ever comes back shaped like something else.+ "data_selector_required": True,+ }+ rest_config: RESTAPIConfig = {+ "client": _client_config(auth, organization, api_version),+ "resources": [+ {+ "name": endpoint,+ "endpoint": endpoint_config,+ "data_map": strip_odata_annotations,+ }+ ],+ }+ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(config.primary_keys),+ # Incremental runs order by the cursor column explicitly; full refreshes are unordered but+ # commit no watermark.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],+ )+++def probe_credentials(+ organization_url: str,+ tenant_id: str,+ client_id: str,+ client_secret: str,+ api_version: str,+ endpoint: Optional[str] = None,+ *,+ ok_statuses: tuple[int, ...] = (200,),+) -> tuple[bool, int | None]:+ """Mint a token and read one row from a table, reporting `(is_valid, status_code)`.++ Raises `Dynamics365ConfigurationError` when the environment URL or tenant id can't be used at+ all — the caller turns that into a field-level message instead of a failed probe.+ """+ organization = normalize_organization_url(organization_url)+ # An unknown (or absent) schema name falls back to accounts, the table every environment has.+ config = DYNAMICS365_ENDPOINTS.get(endpoint or "", DYNAMICS365_ENDPOINTS["Accounts"])+ auth = make_auth(tenant_id, client_id, client_secret, organization)+ url = f"{base_url(organization, api_version)}/{config.entity_set}?$top=1&$select={config.primary_keys[0]}"+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(client_secret,)),+ url,+ headers=request_headers(),+ auth=auth,+ ok_statuses=ok_statuses,+ # The environment host is pinned by normalize_organization_url; refuse a redirect rather+ # than replay the token somewhere else.+ allow_redirects=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/settings.pynew file mode 100644index 000000000000..c575a8272701--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/settings.py@@ -0,0 +1,121 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Dataverse Web API version pinned in the request path (`/api/data/v9.2/`). Microsoft keeps older+# minor versions addressable, so this is a real version choice rather than a cosmetic `/v1/`.+DYNAMICS365_API_VERSION = "v9.2"++# Entra ID (Azure AD) v2 token endpoint. The tenant id is interpolated into the path.+DYNAMICS365_LOGIN_HOST = "login.microsoftonline.com"++# Largest page size Dataverse honours for `Prefer: odata.maxpagesize`.+DYNAMICS365_PAGE_SIZE = 5000++# (connect, read) seconds. Read is generous because a 5,000-row page of a wide table is slow to+# build server side. Dataverse's service protection limits come back as a 429 with Retry-After,+# which the tracked transport already honours, so there's no client-side throttle to configure.+DYNAMICS365_REQUEST_TIMEOUT = (10.0, 300.0)+++def _tracking_fields() -> list[IncrementalField]:+ """Incremental cursor options shared by every standard Dataverse table.++ `modifiedon` and `createdon` exist on all of them and both are server-side `$filter`-able, so+ both are advertised; `modifiedon` is the default because it also catches updates.+ """+ return [incremental_field("modifiedon"), incremental_field("createdon")]+++@dataclass(frozen=True)+class Dynamics365EndpointConfig:+ name: str+ # OData entity set name (the plural logical name Dataverse exposes at /api/data/<version>/).+ entity_set: str+ # Dataverse primary keys are a single GUID column named `<logical name>id`, unique table-wide.+ primary_keys: list[str]+ # Table reference page on Microsoft Learn, surfaced to the semantic-enrichment LLM.+ docs_url: str+ incremental_fields: list[IncrementalField] = field(default_factory=_tracking_fields)+ default_incremental_field: str = "modifiedon"+ # Stable creation timestamp — never `modifiedon`, which would rewrite partitions every sync.+ partition_key: str = "createdon"+ # Explicit `$select` column list. Left empty Dataverse returns every populated column, which is+ # what we want almost everywhere; it's set only for tables holding file payloads, so the sync+ # never downloads attachment bytes. Lookup columns are named without the `_..._value` wrapper+ # Dataverse uses in the response.+ select: tuple[str, ...] = ()+++def _endpoint(+ name: str,+ entity_set: str,+ primary_key: str,+ docs_entity: str,+ select: tuple[str, ...] = (),+) -> Dynamics365EndpointConfig:+ return Dynamics365EndpointConfig(+ name=name,+ entity_set=entity_set,+ primary_keys=[primary_key],+ docs_url=f"https://learn.microsoft.com/en-us/dynamics365/developer/reference/entities/{docs_entity}",+ select=select,+ )+++# `annotation` stores each attachment's bytes in `documentbody`, so this table is the one place we+# name the columns we want — pulling file payloads into the warehouse would be neither useful nor+# affordable.+_ANNOTATION_COLUMNS = (+ "annotationid",+ "subject",+ "notetext",+ "filename",+ "filesize",+ "mimetype",+ "isdocument",+ "objectid",+ "objecttypecode",+ "ownerid",+ "createdby",+ "modifiedby",+ "createdon",+ "modifiedon",+)+++# The standard Customer Engagement tables (Sales, Customer Service, Marketing). Custom and+# unlisted tables would need discovery through the EntityDefinitions metadata API, which this+# catalog deliberately doesn't do — it keeps schema listing credential-free.+DYNAMICS365_ENDPOINTS: dict[str, Dynamics365EndpointConfig] = {+ config.name: config+ for config in (+ _endpoint("Accounts", "accounts", "accountid", "account"),+ _endpoint("Contacts", "contacts", "contactid", "contact"),+ _endpoint("Leads", "leads", "leadid", "lead"),+ _endpoint("Opportunities", "opportunities", "opportunityid", "opportunity"),+ _endpoint("Cases", "incidents", "incidentid", "incident"),+ _endpoint("Campaigns", "campaigns", "campaignid", "campaign"),+ _endpoint("Quotes", "quotes", "quoteid", "quote"),+ _endpoint("Orders", "salesorders", "salesorderid", "salesorder"),+ _endpoint("Invoices", "invoices", "invoiceid", "invoice"),+ _endpoint("Products", "products", "productid", "product"),+ _endpoint("Activities", "activitypointers", "activityid", "activitypointer"),+ _endpoint("Tasks", "tasks", "activityid", "task"),+ _endpoint("PhoneCalls", "phonecalls", "activityid", "phonecall"),+ _endpoint("Emails", "emails", "activityid", "email"),+ _endpoint("Appointments", "appointments", "activityid", "appointment"),+ _endpoint("Notes", "annotations", "annotationid", "annotation", select=_ANNOTATION_COLUMNS),+ _endpoint("Competitors", "competitors", "competitorid", "competitor"),+ _endpoint("Users", "systemusers", "systemuserid", "systemuser"),+ _endpoint("Teams", "teams", "teamid", "team"),+ _endpoint("BusinessUnits", "businessunits", "businessunitid", "businessunit"),+ )+}++ENDPOINTS = tuple(DYNAMICS365_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DYNAMICS365_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/source.pyindex ec939ab97492..b1a796358e2b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/source.py@@ -1,33 +1,207 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+)+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.dynamics365.dynamics365 import (+ INVALID_ORGANIZATION_URL_ERROR,+ INVALID_TENANT_ID_ERROR,+ INVALID_WATERMARK_ERROR,+ Dynamics365ConfigurationError,+ Dynamics365ResumeConfig,+ dynamics365_source,+ probe_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.settings import (+ DYNAMICS365_API_VERSION,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamics365 import (Dynamics365SourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+CREDENTIALS_REJECTED_ERROR = "Dynamics 365 rejected these credentials. Check the directory (tenant) ID, application (client) ID, and client secret, and that the secret hasn't expired."+PERMISSION_ERROR = "Dynamics 365 accepted the credentials but denied access to the data. Check that the app registration has an application user in the environment with a security role that can read this table."+TABLE_MISSING_ERROR = "This table doesn't exist in your Dynamics 365 environment. It belongs to an app (Sales, Customer Service, Marketing) that isn't installed there."+UNREACHABLE_ERROR = "Couldn't reach your Dynamics 365 environment. Check the environment URL and try again."+@SourceRegistry.register-class Dynamics365Source(SimpleSource[Dynamics365SourceConfig]):+class Dynamics365Source(ResumableSource[Dynamics365SourceConfig, Dynamics365ResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = (DYNAMICS365_API_VERSION,)+ default_version = DYNAMICS365_API_VERSION+ api_docs_url = "https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DYNAMICS365+ @property+ def connection_host_fields(self) -> list[str]:+ # The client secret is posted to a token endpoint derived from `tenant_id`, and the minted+ # token is sent to `organization_url` — retargeting either must re-require the secret.+ return ["organization_url", "tenant_id"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ OAUTH2_PERMANENT_ERROR_MARKER: CREDENTIALS_REJECTED_ERROR,+ "401 Client Error: Unauthorized for url": CREDENTIALS_REJECTED_ERROR,+ "403 Client Error: Forbidden for url": PERMISSION_ERROR,+ "404 Client Error: Not Found for url": TABLE_MISSING_ERROR,+ INVALID_ORGANIZATION_URL_ERROR: None,+ INVALID_TENANT_ID_ERROR: None,+ INVALID_WATERMARK_ERROR: None,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: Dynamics365SourceConfig,+ 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 validate_credentials(+ self,+ config: Dynamics365SourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ is_valid, status = probe_credentials(+ config.organization_url,+ config.tenant_id,+ config.client_id,+ config.client_secret,+ self.resolve_api_version(api_version),+ schema_name,+ # A 403 at source-create means the token minted but the application user can't read+ # accounts — the credentials are genuine, so let setup continue. The per-schema+ # check (schema_name set) still fails on 403 so the user sees which table needs a+ # grant before syncing it.+ ok_statuses=(200,) if schema_name else (200, 403),+ )+ except Dynamics365ConfigurationError as error:+ return False, str(error)++ if is_valid:+ return True, None+ if status == 401:+ return False, CREDENTIALS_REJECTED_ERROR+ if status == 403:+ return False, PERMISSION_ERROR+ if status == 404:+ return False, TABLE_MISSING_ERROR+ return False, UNREACHABLE_ERROR++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[Dynamics365ResumeConfig]:+ return ResumableSourceManager[Dynamics365ResumeConfig](inputs, Dynamics365ResumeConfig)++ def source_for_pipeline(+ self,+ config: Dynamics365SourceConfig,+ resumable_source_manager: ResumableSourceManager[Dynamics365ResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return dynamics365_source(+ organization_url=config.organization_url,+ tenant_id=config.tenant_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DYNAMICS365,category=DataWarehouseSourceCategory.CRM,- keywords=["microsoft dynamics", "dynamics"],+ keywords=["microsoft dynamics", "dynamics", "dataverse"],label="Microsoft Dynamics 365",+ caption="""Sync your Dynamics 365 (Dataverse) customer data — accounts, contacts, leads, opportunities, cases and activities — into the PostHog Data warehouse.++To connect, register an app in **Microsoft Entra ID** and add a client secret. Then add that app as an **application user** in your Dynamics 365 environment (Power Platform admin center > Environments > Settings > Users + permissions > Application users) and give it a security role that can read the tables you want to sync. The environment URL is the one you use to open the app, for example `https://contoso.crm.dynamics.com`.""",iconPath="/static/services/dynamics365.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/dynamics365",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="organization_url",+ label="Environment URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://contoso.crm.dynamics.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="tenant_id",+ label="Directory (tenant) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="72f988bf-86f1-41af-91ab-2d7cd011db47",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Application (client) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00001111-aaaa-2222-bbbb-3333cccc4444",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365.pynew file mode 100644index 000000000000..b7f6390b70b1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365.py@@ -0,0 +1,510 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.dynamics365 import (+ INVALID_ORGANIZATION_URL_ERROR,+ Dynamics365ConfigurationError,+ Dynamics365ResumeConfig,+ build_query_params,+ dynamics365_source,+ format_odata_datetime,+ normalize_organization_url,+ probe_credentials,+ resolve_incremental_field,+ strip_odata_annotations,+ token_url,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.settings import (+ DYNAMICS365_ENDPOINTS,+ ENDPOINTS,+)++CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+AUTH_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth.make_tracked_session"+)+PROBE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.dynamics365.make_tracked_session"+)++ORGANIZATION_URL = "https://contoso.crm.dynamics.com"+TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47"+API_VERSION = "v9.2"+DATA_URL = f"{ORGANIZATION_URL}/api/data/{API_VERSION}"+++def _response(payload: dict[str, Any], status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = json.dumps(payload).encode()+ response.url = f"{DATA_URL}/accounts"+ return response+++def _page(rows: list[dict[str, Any]], next_link: str | None = None) -> dict[str, Any]:+ body: dict[str, Any] = {"value": rows}+ if next_link:+ body["@odata.nextLink"] = next_link+ return body+++def _token_response(expires_in: int = 3599) -> mock.MagicMock:+ # OAuth2Auth reads the token exchange body via response.raw.read (stream=True).+ response = mock.MagicMock()+ response.status_code = 200+ response.raw.read.return_value = json.dumps(+ {"access_token": "tok-1", "expires_in": expires_in, "token_type": "Bearer"}+ ).encode()+ return response+++def _make_manager(resume_state: Dynamics365ResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock RESTClient session, snapshotting each request as it is prepared.++ ``request.params`` is one dict mutated across pages, so it has to be copied at prepare time. A+ real ``requests.Session`` does the preparing, so the OAuth2 token mint and Bearer header are+ genuinely applied.+ """+ session.headers = {}+ real_session = requests.Session()+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> requests.PreparedRequest:+ prepared = real_session.prepare_request(request)+ snapshots.append({"params": dict(request.params or {}), "url": prepared.url, "headers": dict(prepared.headers)})+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]+++def _source(+ endpoint: str,+ manager: mock.MagicMock,+ *,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+ organization_url: str = ORGANIZATION_URL,+) -> SourceResponse:+ return dynamics365_source(+ organization_url=organization_url,+ tenant_id=TENANT_ID,+ client_id="cid",+ client_secret="sec",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ api_version=API_VERSION,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ )+++class TestNormalizeOrganizationUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("https://contoso.crm.dynamics.com", "https://contoso.crm.dynamics.com"),+ ("https://contoso.crm.dynamics.com/", "https://contoso.crm.dynamics.com"),+ ("contoso.crm.dynamics.com", "https://contoso.crm.dynamics.com"),+ (" https://Contoso.CRM4.dynamics.com ", "https://contoso.crm4.dynamics.com"),+ ("https://contoso.crm11.dynamics.com", "https://contoso.crm11.dynamics.com"),+ ("https://contoso.api.crm.dynamics.com", "https://contoso.api.crm.dynamics.com"),+ ("https://contoso.crm.dynamics.cn", "https://contoso.crm.dynamics.cn"),+ ("https://contoso.crm.microsoftdynamics.us", "https://contoso.crm.microsoftdynamics.us"),+ # A pasted deep link keeps only the origin, and a stray port is dropped — Dataverse is+ # only ever served over 443.+ ("https://contoso.crm.dynamics.com/main.aspx?pagetype=entitylist", "https://contoso.crm.dynamics.com"),+ ("https://contoso.crm.dynamics.com:8080", "https://contoso.crm.dynamics.com"),+ ],+ )+ def test_accepts_and_normalizes_dataverse_hosts(self, raw: str, expected: str) -> None:+ assert normalize_organization_url(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ "",+ " ",+ "http://contoso.crm.dynamics.com", # plaintext+ "https://contoso.crm.dynamics.com.evil.test",+ "https://evil.test",+ "https://localhost",+ "https://169.254.169.254",+ "https://contoso.dynamics.com", # missing the crm{n} region label+ "https://user:[email protected]/contoso.crm.dynamics.com",+ ],+ )+ def test_rejects_anything_else(self, raw: str) -> None:+ with pytest.raises(Dynamics365ConfigurationError) as error:+ normalize_organization_url(raw)+ assert str(error.value) == INVALID_ORGANIZATION_URL_ERROR+++class TestTokenUrl:+ @pytest.mark.parametrize("tenant", [TENANT_ID, "contoso.onmicrosoft.com", "common"])+ def test_builds_entra_token_url(self, tenant: str) -> None:+ assert token_url(tenant) == f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"++ @pytest.mark.parametrize("tenant", ["", " ", "../../evil", "tenant/oauth2", "tenant?x=1", "tenant#frag"])+ def test_rejects_values_that_could_escape_the_path(self, tenant: str) -> None:+ with pytest.raises(Dynamics365ConfigurationError):+ token_url(tenant)+++class TestFormatOdataDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ("2024-01-02 03:04:05+00:00", "2024-01-02T03:04:05+00:00"),+ ("2024-01-02", "2024-01-02"),+ ],+ )+ def test_formats_odata_literals(self, value: Any, expected: str) -> None:+ assert format_odata_datetime(value) == expected++ @pytest.mark.parametrize("value", ["2024-01-02T03:04:05Z or 1 eq 1", "yesterday", "", "null"])+ def test_rejects_values_that_are_not_timestamps(self, value: str) -> None:+ with pytest.raises(Dynamics365ConfigurationError):+ format_odata_datetime(value)+++class TestQueryParams:+ @pytest.mark.parametrize("requested, expected", [("modifiedon", "modifiedon"), ("createdon", "createdon")])+ def test_honours_the_users_cursor(self, requested: str, expected: str) -> None:+ assert resolve_incremental_field(DYNAMICS365_ENDPOINTS["Accounts"], requested) == expected++ @pytest.mark.parametrize("requested", [None, "", "name desc,modifiedon", "unknowncolumn"])+ def test_falls_back_to_the_default_cursor(self, requested: str | None) -> None:+ assert resolve_incremental_field(DYNAMICS365_ENDPOINTS["Accounts"], requested) == "modifiedon"++ def test_full_refresh_sends_no_filter_or_order(self) -> None:+ assert build_query_params(DYNAMICS365_ENDPOINTS["Accounts"], False, None, None) == {}++ def test_incremental_without_watermark_only_orders(self) -> None:+ params = build_query_params(DYNAMICS365_ENDPOINTS["Accounts"], True, None, "modifiedon")+ assert params == {"$orderby": "modifiedon asc"}++ def test_incremental_filters_and_orders_on_the_chosen_cursor(self) -> None:+ params = build_query_params(+ DYNAMICS365_ENDPOINTS["Opportunities"], True, datetime(2024, 3, 4, 5, 6, 7, tzinfo=UTC), "createdon"+ )+ assert params == {"$orderby": "createdon asc", "$filter": "createdon gt 2024-03-04T05:06:07Z"}++ def test_notes_selects_columns_without_the_attachment_body(self) -> None:+ params = build_query_params(DYNAMICS365_ENDPOINTS["Notes"], False, None, None)+ selected = params["$select"].split(",")+ assert "notetext" in selected+ assert "documentbody" not in selected++ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if name != "Notes"])+ def test_every_other_endpoint_returns_all_columns(self, endpoint: str) -> None:+ assert "$select" not in build_query_params(DYNAMICS365_ENDPOINTS[endpoint], False, None, None)+++class TestStripOdataAnnotations:+ def test_drops_annotations_and_keeps_lookup_columns(self) -> None:+ row = {+ "@odata.etag": 'W/"1234"',+ "accountid": "a-1",+ "[email protected]": "Active",+ "statecode": 0,+ "_primarycontactid_value": "c-1",+ }+ assert strip_odata_annotations(row) == {+ "accountid": "a-1",+ "statecode": 0,+ "_primarycontactid_value": "c-1",+ }+++class TestDynamics365Source:+ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_next_link_until_absent(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ next_link = f"{DATA_URL}/accounts?$skiptoken=page2"+ snapshots = _wire(+ session,+ [+ _response(_page([{"accountid": "a-1", "@odata.etag": 'W/"1"'}], next_link=next_link)),+ _response(_page([{"accountid": "a-2"}])),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("Accounts", manager))++ assert [row["accountid"] for row in rows] == ["a-1", "a-2"]+ # The etag annotation never reaches the warehouse.+ assert all("@odata.etag" not in row for row in rows)+ assert snapshots[0]["url"] == f"{DATA_URL}/accounts"+ assert snapshots[1]["url"] == next_link+ # State is saved only while a next link remains, after the page has been yielded.+ assert [call.args[0].next_url for call in manager.save_state.call_args_list] == [next_link]++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_the_saved_next_link(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ saved = f"{DATA_URL}/contacts?$skiptoken=page9"+ snapshots = _wire(session, [_response(_page([{"contactid": "c-9"}]))])++ rows = _rows(_source("Contacts", _make_manager(Dynamics365ResumeConfig(next_url=saved))))++ assert snapshots[0]["url"] == saved+ assert [row["contactid"] for row in rows] == ["c-9"]++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_page_stops_without_saving(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ _wire(session, [_response(_page([]))])++ manager = _make_manager()+ assert _rows(_source("Leads", manager)) == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_a_response_without_a_value_collection_fails_loud(+ self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock+ ) -> None:+ # Better to fail than to report a successful sync of zero rows.+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ _wire(session, [_response({"error": {"code": "0x0", "message": "unexpected"}})])++ with pytest.raises(ValueError, match="matched nothing in the response"):+ _rows(_source("Accounts", _make_manager()))++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_off_host_next_link_is_refused(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ # A spoofed next link must not carry the access token to another host.+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ _wire(+ session,+ [+ _response(_page([{"accountid": "a-1"}], next_link="https://evil.test/api/data/v9.2/accounts")),+ _response(_page([{"accountid": "a-2"}])),+ ],+ )++ with pytest.raises(Exception, match="allowed hosts"):+ _rows(_source("Accounts", _make_manager()))++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sends_odata_headers_and_page_size_preference(+ self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ snapshots = _wire(session, [_response(_page([]))])++ _rows(_source("Accounts", _make_manager()))++ assert snapshots[0]["headers"]["Authorization"] == "Bearer tok-1"+ # The OData negotiation headers ride the session the client builds.+ assert session.headers["OData-Version"] == "4.0"+ assert session.headers["OData-MaxVersion"] == "4.0"+ assert session.headers["Prefer"] == "odata.maxpagesize=5000"++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_mints_one_environment_scoped_token_for_the_run(+ self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ _wire(+ session,+ [+ _response(_page([{"accountid": "a-1"}], next_link=f"{DATA_URL}/accounts?$skiptoken=p2")),+ _response(_page([{"accountid": "a-2"}])),+ ],+ )++ _rows(_source("Accounts", _make_manager()))++ assert MockAuth.return_value.post.call_count == 1+ assert (+ MockAuth.return_value.post.call_args.args[0]+ == f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"+ )+ body = MockAuth.return_value.post.call_args.kwargs["data"]+ assert body["grant_type"] == "client_credentials"+ assert body["scope"] == f"{ORGANIZATION_URL}/.default"+ assert body["client_secret"] == "sec"++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_remints_token_when_it_expires_mid_run(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ # expires_in=0 is the deterministic stand-in for a sync outliving the token lifetime.+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response(expires_in=0)+ _wire(+ session,+ [+ _response(_page([{"accountid": "a-1"}], next_link=f"{DATA_URL}/accounts?$skiptoken=p2")),+ _response(_page([{"accountid": "a-2"}])),+ ],+ )++ rows = _rows(_source("Accounts", _make_manager()))++ assert [row["accountid"] for row in rows] == ["a-1", "a-2"]+ assert MockAuth.return_value.post.call_count == 2++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_run_filters_server_side(self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ snapshots = _wire(session, [_response(_page([]))])++ _rows(+ _source(+ "Cases",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),+ incremental_field="modifiedon",+ )+ )++ assert snapshots[0]["params"] == {+ "$orderby": "modifiedon asc",+ "$filter": "modifiedon gt 2024-01-02T03:04:05Z",+ }++ @mock.patch(AUTH_SESSION_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_next_link_carries_the_query_so_params_are_not_reapplied(+ self, MockSession: mock.MagicMock, MockAuth: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ MockAuth.return_value.post.return_value = _token_response()+ next_link = f"{DATA_URL}/accounts?%24filter=modifiedon+gt+2024-01-02T03%3A04%3A05Z&%24skiptoken=p2"+ snapshots = _wire(+ session,+ [_response(_page([{"accountid": "a-1"}], next_link=next_link)), _response(_page([]))],+ )++ _rows(+ _source(+ "Accounts",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ )++ assert snapshots[1]["url"] == next_link++ def test_rejects_an_environment_url_before_minting_a_token(self) -> None:+ with pytest.raises(Dynamics365ConfigurationError):+ _source("Accounts", _make_manager(), organization_url="https://evil.test")++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_source_response_shape_per_endpoint(self, endpoint: str) -> None:+ config = DYNAMICS365_ENDPOINTS[endpoint]+ response = _source(endpoint, _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ # Partitioned on the creation timestamp, which never changes for a record.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdon"]+++class TestProbeCredentials:+ @pytest.mark.parametrize(+ "status, ok_statuses, expected",+ [+ (200, (200,), True),+ (403, (200,), False),+ (403, (200, 403), True),+ (401, (200, 403), False),+ (404, (200,), False),+ (500, (200,), False),+ ],+ )+ @mock.patch(PROBE_SESSION_PATCH)+ def test_maps_probe_status(+ self, mock_session: mock.MagicMock, status: int, ok_statuses: tuple[int, ...], expected: bool+ ) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)++ is_valid, reported = probe_credentials(+ ORGANIZATION_URL, TENANT_ID, "cid", "sec", API_VERSION, ok_statuses=ok_statuses+ )++ assert is_valid is expected+ assert reported == status++ @mock.patch(PROBE_SESSION_PATCH)+ def test_reports_unreachable_environment(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert probe_credentials(ORGANIZATION_URL, TENANT_ID, "cid", "sec", API_VERSION) == (False, None)++ @pytest.mark.parametrize(+ "endpoint, expected_url",+ [+ (None, f"{DATA_URL}/accounts?$top=1&$select=accountid"),+ ("Opportunities", f"{DATA_URL}/opportunities?$top=1&$select=opportunityid"),+ # An unknown schema name falls back to the default probe rather than building a bad URL.+ ("NotATable", f"{DATA_URL}/accounts?$top=1&$select=accountid"),+ ],+ )+ @mock.patch(PROBE_SESSION_PATCH)+ def test_probes_one_row_of_the_requested_table(+ self, mock_session: mock.MagicMock, endpoint: str | None, expected_url: str+ ) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)++ probe_credentials(ORGANIZATION_URL, TENANT_ID, "cid", "sec", API_VERSION, endpoint)++ call = mock_session.return_value.get.call_args+ assert call.args[0] == expected_url+ assert call.kwargs["auth"].scopes == f"{ORGANIZATION_URL}/.default"+ assert call.kwargs["allow_redirects"] is False++ def test_raises_on_an_unusable_environment_url(self) -> None:+ with pytest.raises(Dynamics365ConfigurationError):+ probe_credentials("https://evil.test", TENANT_ID, "cid", "sec", API_VERSION)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365_source.pynew file mode 100644index 000000000000..65ed886f96b1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics365/tests/test_dynamics365_source.py@@ -0,0 +1,240 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.dynamics365 import (+ INVALID_ORGANIZATION_URL_ERROR,+ Dynamics365ResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.settings import (+ DYNAMICS365_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.source import (+ CREDENTIALS_REJECTED_ERROR,+ PERMISSION_ERROR,+ TABLE_MISSING_ERROR,+ UNREACHABLE_ERROR,+ Dynamics365Source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamics365 import (+ Dynamics365SourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++PROBE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.source.probe_credentials"+SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamics365.source.dynamics365_source"+++class TestDynamics365Source:+ def setup_method(self) -> None:+ self.source = Dynamics365Source()+ self.team_id = 123+ self.config = Dynamics365SourceConfig(+ organization_url="https://contoso.crm.dynamics.com",+ tenant_id="72f988bf-86f1-41af-91ab-2d7cd011db47",+ client_id="cid",+ client_secret="sec",+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DYNAMICS365++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Dynamics365"+ assert config.label == "Microsoft Dynamics 365"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/dynamics365.png"+ assert [field.name for field in config.fields] == [+ "organization_url",+ "tenant_id",+ "client_id",+ "client_secret",+ ]++ def test_only_the_client_secret_is_a_secret_field(self) -> None:+ fields = [field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldInputConfig)]++ secret_fields = [field for field in fields if field.secret]+ assert [field.name for field in secret_fields] == ["client_secret"]+ assert secret_fields[0].type == SourceFieldInputConfigType.PASSWORD+ assert all(field.required for field in fields)++ def test_retargeting_the_environment_or_tenant_requires_new_secrets(self) -> None:+ # Both fields decide where the client secret and the minted token are sent.+ assert self.source.connection_host_fields == ["organization_url", "tenant_id"]++ def test_api_version_is_pinned_to_the_path_the_code_calls(self) -> None:+ assert self.source.supported_versions == ("v9.2",)+ assert self.source.default_version == "v9.2"+ assert self.source.resolve_api_version(None) == "v9.2"++ @pytest.mark.parametrize(+ "observed_error",+ [+ "HTTP 401 from the OAuth2 token endpoint: invalid_client [oauth2_token_config_error]",+ "401 Client Error: Unauthorized for url: https://contoso.crm.dynamics.com/api/data/v9.2/accounts",+ "403 Client Error: Forbidden for url: https://contoso.crm.dynamics.com/api/data/v9.2/incidents",+ "404 Client Error: Not Found for url: https://contoso.crm.dynamics.com/api/data/v9.2/campaigns",+ INVALID_ORGANIZATION_URL_ERROR,+ ],+ )+ def test_permanent_failures_are_non_retryable(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://contoso.crm.dynamics.com/api/data/v9.2/accounts",+ "503 Server Error: Service Unavailable for url: https://contoso.crm.dynamics.com/api/data/v9.2/accounts",+ "HTTP 429 from the OAuth2 token endpoint",+ ],+ )+ def test_throttles_and_server_errors_stay_retryable(self, other_error: str) -> None:+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_lists_every_endpoint_as_incrementable(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ assert all(schema.supports_incremental for schema in schemas.values())+ # Dataverse exposes both tracking columns on every standard table.+ assert [field["field"] for field in schemas["Accounts"].incremental_fields] == ["modifiedon", "createdon"]+ assert schemas["Cases"].incremental_fields == INCREMENTAL_FIELDS["Cases"]++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Contacts"])+ assert [schema.name for schema in schemas] == ["Contacts"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)+ for name, entry in descriptions.items():+ columns = entry.get("columns") or {}+ # The GUID primary key and both tracking columns are always documented.+ assert DYNAMICS365_ENDPOINTS[name].primary_keys[0] in columns+ assert {"createdon", "modifiedon"} <= set(columns)++ @mock.patch(PROBE_PATCH)+ def test_validate_credentials_accepts_a_working_probe(self, mock_probe: mock.MagicMock) -> None:+ mock_probe.return_value = (True, 200)++ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_probe.call_args.args[4] == "v9.2"++ @pytest.mark.parametrize(+ "status, expected_message",+ [+ (401, CREDENTIALS_REJECTED_ERROR),+ (403, PERMISSION_ERROR),+ (404, TABLE_MISSING_ERROR),+ (500, UNREACHABLE_ERROR),+ (None, UNREACHABLE_ERROR),+ ],+ )+ @mock.patch(PROBE_PATCH)+ def test_validate_credentials_explains_the_failure(+ self, mock_probe: mock.MagicMock, status: int | None, expected_message: str+ ) -> None:+ mock_probe.return_value = (False, status)++ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert message == expected_message++ @pytest.mark.parametrize(+ "schema_name, expected_ok_statuses",+ [+ # At source-create a valid token that can't read accounts must not block setup.+ (None, (200, 403)),+ # Checking one table must surface a missing grant for that table.+ ("Cases", (200,)),+ ],+ )+ @mock.patch(PROBE_PATCH)+ def test_validate_credentials_tolerates_403_only_at_source_create(+ self, mock_probe: mock.MagicMock, schema_name: str | None, expected_ok_statuses: tuple[int, ...]+ ) -> None:+ mock_probe.return_value = (True, 200)++ self.source.validate_credentials(self.config, self.team_id, schema_name)++ assert mock_probe.call_args.kwargs["ok_statuses"] == expected_ok_statuses+ assert mock_probe.call_args.args[5] == schema_name++ def test_validate_credentials_rejects_a_non_dataverse_environment_url(self) -> None:+ config = Dynamics365SourceConfig(+ organization_url="https://evil.test",+ tenant_id="72f988bf-86f1-41af-91ab-2d7cd011db47",+ client_id="cid",+ client_secret="sec",+ )++ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert message == INVALID_ORGANIZATION_URL_ERROR++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is Dynamics365ResumeConfig++ @mock.patch(SOURCE_PATCH)+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Opportunities"+ inputs.team_id = 7+ inputs.job_id = "job-7"+ inputs.api_version = None+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ inputs.incremental_field = "createdon"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["organization_url"] == "https://contoso.crm.dynamics.com"+ assert kwargs["tenant_id"] == "72f988bf-86f1-41af-91ab-2d7cd011db47"+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["endpoint"] == "Opportunities"+ assert kwargs["api_version"] == "v9.2"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"+ assert kwargs["incremental_field"] == "createdon"++ @mock.patch(SOURCE_PATCH)+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Accounts"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch(SOURCE_PATCH)+ def test_source_for_pipeline_honours_a_pinned_api_version(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Accounts"+ inputs.api_version = "v9.1"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["api_version"] == "v9.1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365.pyindex 5abacfa57b29..c4d09c9e5b52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass Dynamics365SourceConfig(config.Config):- pass+ organization_url: str+ tenant_id: str+ client_id: str+ client_secret: str