Metadata-Version: 2.5
Name: dq-export-connector
Version: 0.1.0.dev27
Summary: Worker logic for the Export Connector DCR.
Author: Decentriq
Requires-Python: >=3.12
Requires-Dist: pydantic<3,>=2.14
Provides-Extra: bucket
Requires-Dist: obstore<0.12,>=0.11.1; extra == 'bucket'
Provides-Extra: snap
Requires-Dist: requests<3,>=2.32; extra == 'snap'
Description-Content-Type: text/markdown

# dq-export-connector

Worker logic for the **Export Connector DCR**: one package for every
Connector Kind, each in its own sub-package with an extra of the same name for
its dependencies.

- The **bucket** kind uploads each Input's dataset to S3, Azure Blob or GCS
  through [`obstore`](https://developmentseed.org/obstore/).
- The **snap** kind fills one Snap Segment per Input with hashed identifiers,
  through Snap's Marketing API.

ddc pins this package by hash in a fully locked `requirements.txt` and runs
`dq_export_connector.runner.main` in the task's Python environment. It is
published to PyPI, since the compiled graph installs it from there.

- `dq_export_connector.runner`: the entry point. Reads `/input/config.json`,
  `/input/credentials.json` and any platform secret under
  `/input/platform_secrets/`, sets up logging, and dispatches on the Connector
  Kind and the action, then writes what the action reports: a connection
  test's result into `/output`, and an export's receipt and either action's
  warnings and error under `/internal`, as the task's Task Report, Application
  Warnings and Application Error. A run with an error fails.
- `dq_export_connector.errors`: the error and warning codes the worker
  reports, and `ExportConnectorError`, which stops a run with an error code.
  Codes are named for the situation, not the kind, so any kind can report them.
- `dq_export_connector.outcome`: collects a run's error, warnings and receipt
  while it runs, and cuts each message to 1,000 characters, and a provider's
  own error to 4,000, once redacted.
- `dq_export_connector.redact`: keeps every value from the sealed half, and
  URL query strings, out of log lines and result messages. For the ad
  platforms it also masks tokens, `key=secret` pairs, JWTs and SHA-256 hex.
- `dq_export_connector.datasets`: how an Input's dataset maps to files (a
  stored ZIP, or one raw file).
- `dq_export_connector.bucket`: the bucket kind (`ValidateConnection` and
  `Export`).
- `dq_export_connector.audience`: what the ad-platform kinds share: HTTPS to an
  allowlist with retries by idempotency class, OAuth, identifier
  normalisation, and the per-Input sync flow.
- `dq_export_connector.snap`: the snap kind.
- `dq_export_connector.models`: the types the worker reads and writes, those
  of every Connector Kind directly in it and a kind's own in its submodule,
  such as `models.bucket`. They are pydantic models generated in
  `dq_export_connector._models` from ddc's JSON schemas, so the config the
  worker reads and the receipt, messages and validation result it writes match
  ddc's Rust types. Regenerate them with `scripts/codegen-models.sh` after the
  types change and `decentriq_dcr_compiler` has been rebuilt; a test fails
  while they are stale.

```sh
uv run pytest            # unit tests, against obstore's in-memory store and a fake Snap API
uv run pytest -m live    # against real buckets and Snap, credentials from the environment
uv run mypy dq_export_connector tests scripts
```

## Snap

A Snap connector's config names the ad account and, per Input, a Segment, the
identifier type its lines hold and a Merge Mode. ddc validates it. The
credentials are the refresh token of the Snap user who consented; Decentriq's
Snap app is the `export_connector_snap_app` platform secret
(`{"clientId", "clientSecret"}`).

A run looks each Segment up by name in the ad account and creates it when
there is none, marked `Managed by Decentriq`. It writes into a same-named
Segment whoever made it, with a `SEGMENT_NOT_MANAGED` warning when Decentriq
didn't. ADD adds the Input's values; REPLACE empties the Segment first, so it
is briefly empty. A run stops at the first Input that fails. When the failure
came after the Segment changed, the error says so; a rerun is safe in both
modes. Don't run one connector twice at the same time.

An Input is one file of values, or a stored ZIP holding one: one value per
line, UTF-8, optional BOM, LF or CRLF, surrounding double quotes removed,
empty lines skipped, no header.

### Identifiers

| Type | Normalisation before SHA-256 | Snap schema |
|---|---|---|
| `EMAIL` | trim, lowercase; exactly one `@` with text on both sides | `EMAIL_SHA256` |
| `PHONE` | drop a `(0)` right after the country code (`+44 (0)20…`, `+44-(0)20…`), keep digits (any script's, as ASCII; drops `+`), drop a leading `00`; 8–15 digits, not starting with `0` | `PHONE_SHA256` |
| `IDFA`, `GAID` | UUID form with hyphens, lowercased | `MOBILE_AD_ID_SHA256` |
| `*_SHA256` | must be 64 hex characters; lowercased, otherwise unchanged | as above |

A pre-hashed value only matches if it was hashed from the same form: for
`PHONE_SHA256`, the digits with country code and no `+` (`41791234567`).

Up to 25% invalid rows gives an `INVALID_ROWS` warning; more fails the run
before the Segment changes. An empty Input gives an `EMPTY_DATASET` warning
and leaves its Segment as it was, in both modes.

The receipt counts invalid rows by reason (`counts.invalidReasons`, and in the
warning or error message), never with the values themselves:

| Reason | Meaning |
|---|---|
| `EMAIL_NO_AT_SIGN`, `EMAIL_MULTIPLE_AT_SIGNS` | not exactly one `@` |
| `EMAIL_EMPTY_LOCAL_PART`, `EMAIL_EMPTY_DOMAIN` | nothing before or after the `@` |
| `PHONE_NO_DIGITS` | no digits at all |
| `PHONE_NATIONAL_FORMAT` | starts with `0` after dropping `00`, i.e. no country code |
| `PHONE_TOO_SHORT`, `PHONE_TOO_LONG` | fewer than 8 or more than 15 digits |
| `NOT_A_MOBILE_AD_ID` | not a UUID with hyphens |
| `NOT_SHA256_HEX` | a `*_SHA256` value that isn't 64 hex characters |
| `NOT_UTF8` | the line isn't valid UTF-8 |
| `CONTROL_CHARACTERS` | the value holds control characters or a byte order mark, usually because the file is UTF-16 |

### Testing against Snap

The local files are gitignored in this directory:

- `platform_secrets.json`: `{"export_connector_snap_app": {"clientId": …, "clientSecret": …}}`, the dev app.
- `credentials.json`: written by the consent CLI.
- `config.json`: `{"connector": {"type": "snap", "adAccountId": …, "grantExpiresAt": null, "inputs": [{"leafId": "segA", "segmentName": …, "identifierType": "EMAIL", "mergeMode": "ADD", "retentionDays": 180}]}}`.

1. Consent, as the Snap user who has a role on the test ad account. The
   redirect URI must be an https URI registered on the app; only the URL the
   browser lands on matters.

   ```sh
   uv run python scripts/consent.py snap --platform-secrets platform_secrets.json \
     --redirect-uri "$REDIRECT_URI" --out credentials.json --config config.json
   ```
2. Run:

   ```sh
   mkdir -p local/inputs && printf 'a@example.com\nb@example.com\n' > local/inputs/segA
   uv run python scripts/run_local.py --config config.json --credentials credentials.json \
     --platform-secrets platform_secrets.json --mode validate
   uv run python scripts/run_local.py --config config.json --credentials credentials.json \
     --platform-secrets platform_secrets.json
   ```
3. Live tests, including the check that Snap doesn't rotate refresh tokens:

   ```sh
   DQ_EXPORT_LIVE_SNAP_DIR=$PWD uv run pytest -m live -s tests/test_live_snap.py
   ```

## Releasing

Bump the version with `uv version <version> --no-sync`, which also updates
`uv.lock`, commit, and push a `dq-export-connector-v<version>` tag on that
commit; the `Publish dq-export-connector to PyPI` workflow tests, builds and
uploads it. Use `.devN` versions while developing; PyPI releases can't be replaced.
ddc then pins the new version, as
[ddc's export worker README](../../dcr-compiler/ddc/src/archv2/data_room/export_connector/README.md)
describes.
