You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/15 06:01:24 UTC
(seatunnel) branch dev updated: [Feature][Connector-V2] Add Google Analytics 4 report source (#12280)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new f4a9665e84 [Feature][Connector-V2] Add Google Analytics 4 report source (#12280)
f4a9665e84 is described below
commit f4a9665e8457239dd30c04a8738b506fa3fce180
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Tue Sep 15 05:50:43 2026 +0000
[Feature][Connector-V2] Add Google Analytics 4 report source (#12280)
Signed-off-by: Goutam Adwant <wo...@gmail.com>
---
.github/workflows/labeler/label-scope-conf.yml | 7 +
config/plugin_config | 1 +
.../changelog/connector-google-analytics4.md | 24 +
docs/en/connectors/source/GoogleAnalytics4.md | 191 ++++++++
.../changelog/connector-google-analytics4.md | 24 +
docs/zh/connectors/source/GoogleAnalytics4.md | 179 ++++++++
plugin-mapping.properties | 1 +
.../connector-google-analytics4/pom.xml | 105 +++++
.../google/analytics4/GoogleAnalytics4Config.java | 201 +++++++++
.../analytics4/GoogleAnalytics4HttpTransport.java | 278 ++++++++++++
.../google/analytics4/GoogleAnalytics4Report.java | 319 ++++++++++++++
.../google/analytics4/GoogleAnalytics4Source.java | 67 +++
.../analytics4/GoogleAnalytics4SourceFactory.java | 76 ++++
.../analytics4/GoogleAnalytics4SourceOptions.java | 114 +++++
.../analytics4/GoogleAnalytics4SourceReader.java | 260 +++++++++++
.../analytics4/GoogleAnalytics4ReportTest.java | 336 ++++++++++++++
.../GoogleAnalytics4SourceReaderTest.java | 490 +++++++++++++++++++++
.../TestGoogleAnalytics4PackagingIT.java | 208 +++++++++
seatunnel-connectors-v2/pom.xml | 1 +
seatunnel-dist/pom.xml | 6 +
seatunnel-dist/release-docs/LICENSE | 28 ++
.../licenses/LICENSE-google-api-common.txt | 26 ++
.../release-docs/licenses/LICENSE-google-auth.txt | 28 ++
.../connector-google-analytics4-e2e/pom.xml | 48 ++
.../google/analytics4/GoogleAnalytics4IT.java | 135 ++++++
.../resources/google_analytics4_to_assert.conf | 55 +++
seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml | 1 +
.../examples/google_analytics4_to_console.conf | 43 ++
28 files changed, 3252 insertions(+)
diff --git a/.github/workflows/labeler/label-scope-conf.yml b/.github/workflows/labeler/label-scope-conf.yml
index 5e46ce070f..f4fe6c9946 100644
--- a/.github/workflows/labeler/label-scope-conf.yml
+++ b/.github/workflows/labeler/label-scope-conf.yml
@@ -187,6 +187,13 @@ google-ads:
- changed-files:
- any-glob-to-any-file: seatunnel-connectors-v2/connector-google-ads/**
- all-globs-to-all-files: '!seatunnel-connectors-v2/connector-!(google-ads)/**'
+google-analytics4:
+ - all:
+ - changed-files:
+ - any-glob-to-any-file:
+ - seatunnel-connectors-v2/connector-google-analytics4/**
+ - seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/**
+ - all-globs-to-all-files: '!seatunnel-connectors-v2/connector-!(google-analytics4)/**'
google-firestore:
- all:
- changed-files:
diff --git a/config/plugin_config b/config/plugin_config
index 0a912b6d30..d4efe4cdee 100644
--- a/config/plugin_config
+++ b/config/plugin_config
@@ -61,6 +61,7 @@ connector-google-pubsub
connector-azure-queue-storage
connector-google-bigtable
connector-google-ads
+connector-google-analytics4
connector-facebook-ads
connector-tiktok-ads
connector-graphql
diff --git a/docs/en/connectors/changelog/connector-google-analytics4.md b/docs/en/connectors/changelog/connector-google-analytics4.md
new file mode 100644
index 0000000000..623c91b637
--- /dev/null
+++ b/docs/en/connectors/changelog/connector-google-analytics4.md
@@ -0,0 +1,24 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<details><summary> Change Log </summary>
+
+| Change | Commit | Version |
+| --- | --- | --- |
+|[Feature][Connector-V2] Add bounded Google Analytics 4 source|-|Next|
+
+</details>
diff --git a/docs/en/connectors/source/GoogleAnalytics4.md b/docs/en/connectors/source/GoogleAnalytics4.md
new file mode 100644
index 0000000000..a5ae60dda7
--- /dev/null
+++ b/docs/en/connectors/source/GoogleAnalytics4.md
@@ -0,0 +1,191 @@
+import ChangeLog from '../changelog/connector-google-analytics4.md';
+
+# GoogleAnalytics4
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+## Description
+
+Read one Google Analytics 4 property report through the Data API v1beta `runReport` REST method.
+This source reads aggregated reporting rows, **not raw events, CDC, or an immutable snapshot**.
+
+## Supported Connector Version
+
+Google Analytics 4, Data API v1beta. Universal Analytics is not supported.
+The connector artifact bundles its Google authentication and HTTP dependencies; no separate driver installation is required.
+
+## Supported Engines
+
+SeaTunnel Zeta, Flink and Spark.
+
+## Key Features
+
+- Batch only, source parallelism must be 1.
+- One property and one inclusive absolute date range in the property's time zone.
+- Explicit dimensions, metrics, Google metric types and matching SeaTunnel schema.
+- Bounded page requests, response sizes, deadlines and transient-error retries.
+- Service-account OAuth refresh; no credentials are needed for the isolated HTTP test fixture.
+
+## Consistency and Recovery
+
+All dimensions are ordered ascending using Google's `ALPHANUMERIC` ordering, in configured order.
+The next offset advances by the number of rows actually returned, including short nonempty pages.
+The source rejects changing `rowCount`, duplicate/out-of-order dimension tuples, empty pages before
+the reported end, and mismatched headers, types or row widths. It never truncates at `max_report_rows`.
+
+These checks **do not prove completeness or snapshot consistency**. GA4 can update historical reports
+between requests without changing their count or ordering. Rows can still move across offsets, and
+metric values can change. Absolute dates freeze the request, not the service's data. Prefer a settled
+historical range and reconcile results with the property when consistency matters.
+
+A single report is read while the common single-split reader holds the checkpoint lock. There are no
+page checkpoints or resumable offsets. Recovery replays the whole report from offset zero with the
+same absolute dates. The connector does not restart internally on a changing report. Engine/job
+restart limits remain the operator's responsibility. Previously emitted rows can be replayed, and a
+late page failure can leave partial output in a nontransactional sink. Use a staging/replacement
+workflow or a sink suited to your recovery requirements; do not treat failed-job output as complete.
+
+The source rejects reports whose metadata indicates sampling (`samplingMetadatas`), thresholding
+(`subjectToThresholding`), other-row data loss (`dataLossFromOtherRow`), active metric restrictions,
+or a nonempty `emptyReason`. Thresholding is rejected even when it may not have removed any rows.
+There is no option to silently accept these limitations. Missing optional metadata is accepted, and
+absence of a warning is not a complete-data guarantee. A literal dimension value `(other)` alone is
+not interpreted as the metadata signal.
+
+## Authentication
+
+Enable the Google Analytics Data API in the service-account project and grant the service-account
+email read access (for example, Viewer) to the GA4 property. Supply a trusted service-account JSON
+file on every worker at the configured path. Only service-account key files are supported in V1:
+there is no Application Default Credentials, raw token, user refresh-token or workload federation mode.
+
+The connector uses Google Auth Library with the `analytics.readonly` scope. It refreshes before
+expiry and once on HTTP 401 per page. Token exchange uses the fixed
+`https://oauth2.googleapis.com/token` endpoint and is bounded by the HTTP/report deadline.
+Malformed keys, nonstandard token URIs and refresh failures fail without including keys, tokens,
+HTTP bodies or underlying authentication exceptions in connector diagnostics. Keep key files
+restricted to the worker account. Do not put key contents in the job configuration.
+
+`emulator_url` is an explicit **unauthenticated test-fixture origin**, not an official GA4 emulator.
+It is mutually exclusive with the key file and supports only a non-Google HTTP origin, without
+userinfo, query, fragment or path. Never use this mode for production GA4 access. Production requests
+use the fixed HTTPS Google endpoint. Redirects, cookies and implicit HTTP retries are disabled.
+
+## Source Options
+
+| Name | Type | Required | Default | Description |
+| :--- | :--- | :--- | :--- | :--- |
+| property_id | string | yes | - | One numeric GA4 property ID, not a measurement ID. |
+| start_date | string | yes | - | Inclusive absolute calendar date, `yyyy-MM-dd`. Relative dates are rejected. |
+| end_date | string | yes | - | Inclusive absolute date, not before start_date. |
+| dimensions | array | no | [] | Ordered unique dimension API names, at most 9. |
+| metrics | array | yes | - | Ordered unique metric API names, 1 to 10; must not overlap dimensions. |
+| metric_types | array | yes | - | Exact Google MetricType enum per metric, in the same order. |
+| schema | config | yes | - | Exactly all dimensions followed by all metrics, with names, order and types matching. |
+| service_account_key_file | string | conditional | - | Trusted service-account file on workers; at most 1 MiB. Exactly one authentication option is required. |
+| emulator_url | string | conditional | - | Unauthenticated local/isolated HTTP fixture origin, mutually exclusive with key file. |
+| page_size | int | no | 1000 | Requested rows per page, 1 to 10000. This connector intentionally uses a smaller bound than Google's API maximum. |
+| max_report_rows | int | no | 1000000 | Fail if reported row count exceeds this bound; range 1 to 10000000. |
+| max_response_bytes | int | no | 4194304 | Fail on a larger page response; range 1024 to 16777216. Oversize responses are not retried. |
+| request_timeout_ms | int | no | 30000 | HTTP request deadline, including body transfer; 100 to 120000 ms. Synchronous JVM/platform DNS resolution is not guaranteed to be interruptible. |
+| report_timeout_ms | int | no | 600000 | Whole report deadline; 100 to 3600000 ms. Applies to HTTP, auth and retry waits; checked between collected rows. It cannot interrupt synchronous DNS resolution or a downstream sink's blocking collect call. |
+| max_retries | int | no | 3 | Additional attempts per page for transient transport errors or HTTP 429/500/502/503/504; 0 to 5. |
+| max_retry_wait_ms | int | no | 30000 | Upper bound on a retry wait; 1000 to 120000 ms. |
+
+Retries use bounded exponential backoff with jitter and honor `Retry-After` seconds or HTTP dates.
+If the server requests a longer wait than configured, the job fails instead of retrying early.
+Invalid requests, forbidden access, schema errors, oversized responses and auth refresh errors are
+not retried. Exhausted token/server-error quota reported on an unfinished page fails the job before
+another request. No background polling waits for a daily/hourly quota reset.
+
+Memory is bounded per page, not for the whole report. JSON parsing and typed rows require more memory
+than the byte limit itself. Tune both page size and byte limit for the worker heap. Close/cancellation
+aborts active HTTP requests and wakes retry waits. HTTP connection and body deadlines also bound stalled
+responses. Report timeout does not control engine restarts or downstream backpressure.
+Apache HttpClient resolves hostnames synchronously before socket connection. JVM/platform DNS lookup
+can block outside connect/socket timeouts, and aborting a request does not guarantee interruption of
+that lookup. Request/report deadlines and cancellation are therefore not hard wall-clock bounds while
+DNS resolution is blocked; this also applies to OAuth token requests.
+
+## Data Types
+
+Dimension values use STRING, including empty strings and date-like dimension values; the source does
+not reinterpret them as dates. `TYPE_INTEGER` metrics require BIGINT and are checked for 64-bit overflow.
+`TYPE_FLOAT`, `TYPE_SECONDS`, `TYPE_MILLISECONDS`, `TYPE_MINUTES`, `TYPE_HOURS`, `TYPE_STANDARD`,
+`TYPE_CURRENCY`, `TYPE_FEET`, `TYPE_MILES`, `TYPE_METERS` and `TYPE_KILOMETERS` require DOUBLE.
+Nonfinite/invalid values fail. DOUBLE has floating-point precision, including currency metrics;
+this is not an exact-decimal money representation. Exact Google enum types are checked on every page
+so changes in metric units do not pass as compatible DOUBLE values.
+
+Check the property's supported dimensions/metrics and their compatibility before configuring a report.
+API incompatibility errors fail with the HTTP status and redacted response details. V1 does not support
+filters, expressions, cohorts, comparisons, multiple date ranges, realtime reports or metric aggregations.
+No network call is made to discover or mutate the schema during factory construction.
+
+## Example
+
+```hocon
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+source {
+ GoogleAnalytics4 {
+ property_id = "123456789"
+ service_account_key_file = "/run/secrets/ga4-service-account.json"
+ start_date = "2024-01-01"
+ end_date = "2024-01-31"
+ dimensions = ["country"]
+ metrics = ["activeUsers", "purchaseRevenue"]
+ metric_types = ["TYPE_INTEGER", "TYPE_CURRENCY"]
+ schema {
+ fields {
+ country = string
+ activeUsers = bigint
+ purchaseRevenue = double
+ }
+ }
+ }
+}
+sink {
+ Console {}
+}
+```
+
+For an isolated mock test, replace `service_account_key_file` with `emulator_url = "http://fixture:1080"`.
+Never configure both.
+
+## Verification
+
+The connector includes deterministic HTTP fixture tests and a mock-server engine E2E test.
+Authentication tests use generated RSA credentials and a mock OAuth token exchange. These tests do not
+verify a live GA4 property. Before a production handoff, verify property access, metric compatibility,
+pagination, quota behavior and reporting limitations using authorized real-property credentials.
+No such credentials are bundled with the connector.
+
+## References
+
+- [runReport REST API](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport)
+- [Response metadata](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/ResponseMetaData)
+- [Metric types](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/MetricType)
+- [Quotas](https://developers.google.com/analytics/devguides/reporting/data/v1/quotas)
+- [API quickstart and property access](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries)
+
+## Changelog
+
+<ChangeLog />
diff --git a/docs/zh/connectors/changelog/connector-google-analytics4.md b/docs/zh/connectors/changelog/connector-google-analytics4.md
new file mode 100644
index 0000000000..623c91b637
--- /dev/null
+++ b/docs/zh/connectors/changelog/connector-google-analytics4.md
@@ -0,0 +1,24 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<details><summary> Change Log </summary>
+
+| Change | Commit | Version |
+| --- | --- | --- |
+|[Feature][Connector-V2] Add bounded Google Analytics 4 source|-|Next|
+
+</details>
diff --git a/docs/zh/connectors/source/GoogleAnalytics4.md b/docs/zh/connectors/source/GoogleAnalytics4.md
new file mode 100644
index 0000000000..d6bdd964e5
--- /dev/null
+++ b/docs/zh/connectors/source/GoogleAnalytics4.md
@@ -0,0 +1,179 @@
+import ChangeLog from '../changelog/connector-google-analytics4.md';
+
+# GoogleAnalytics4
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+## 描述
+
+通过 Google Analytics Data API v1beta 的 `runReport` REST 方法读取一个 GA4 属性的聚合报告。
+本连接器不是原始事件导出、CDC 或不可变快照。
+
+## 支持的连接器版本
+
+Google Analytics 4,Data API v1beta;不支持 Universal Analytics。
+连接器 JAR 已包含 Google 认证和 HTTP 依赖,无需单独安装驱动。
+
+## 支持的引擎
+
+SeaTunnel Zeta、Flink、Spark。
+
+## 主要功能
+
+- 仅支持批处理,source 并行度必须为 1。
+- 一个属性、一个明确的绝对日期区间(首尾日期均包含,按属性时区解释)。
+- 明确的维度、指标、Google 指标类型和匹配的 SeaTunnel schema。
+- 有界分页、响应大小、请求时限及瞬时错误重试。
+- 使用服务账号文件进行 OAuth 令牌刷新;隔离的 HTTP 测试服务不需要凭据。
+
+## 一致性与恢复
+
+按配置顺序对全部维度使用 Google 的 `ALPHANUMERIC` 升序排序。
+下一页 offset 按实际返回行数推进,允许非空短页;不会跳过空页或静默截断。
+返回总行数变化、重复或乱序维度组合、到达报告末尾前的空页,以及响应列名、类型、行宽不匹配均导致失败。
+
+这些检查不能证明数据完整或具有快照一致性。GA4 可能在分页请求之间更新历史报告,
+即使总行数和排序未变化,也可能有行跨越 offset 或指标值变化。
+绝对日期只固定请求参数,不冻结服务端数据。重要场景应使用已稳定的历史区间并进行结果核对。
+
+一次报告读取期间,共用的 single-split reader 持有 checkpoint 锁;没有页级 checkpoint 或可恢复 offset。
+任务恢复会使用相同日期从 offset 0 重读整个报告。报告变化时连接器不会自行重新开始报告。
+引擎或作业的重启次数限制由运维配置。已输出的行可能重放,后续页面失败也可能在非事务 sink 中留下部分数据。
+应使用暂存/替换流程或符合恢复要求的 sink,不能把失败作业的输出当作完整报告。
+
+检测到以下元数据时,连接器明确失败:`samplingMetadatas` 采样、`subjectToThresholding` 阈值处理、
+`dataLossFromOtherRow` 聚合数据丢失、活动指标访问限制,以及非空 `emptyReason`。
+即使阈值处理可能未实际删除任何行,也会拒绝该报告;V1 不提供静默接受这些限制的选项。
+允许缺少可选元数据,但没有警告不代表完整性保证。
+单独出现字面维度值 `(other)` 不作为聚合丢失的判断依据。
+
+## 认证
+
+在服务账号所属项目启用 Google Analytics Data API,并授予服务账号邮箱对 GA4 属性的只读权限
+(例如 Viewer)。在每个 worker 的配置路径提供可信的服务账号 JSON 文件,限制文件读取权限。
+V1 仅支持服务账号密钥文件,不支持 ADC、直接 access token、用户 refresh token 或工作负载身份联合。
+不要把密钥内容放在作业配置中。
+
+通过 Google Auth Library 使用 `analytics.readonly` scope,在令牌即将过期时刷新,
+每页收到 HTTP 401 后最多强制刷新一次。
+令牌端点固定为 `https://oauth2.googleapis.com/token`,请求及报告时限同样适用于令牌交换。
+无效文件、非标准 token_uri 或刷新错误均失败,连接器错误信息不包含密钥、令牌、HTTP 正文或底层认证异常。
+
+`emulator_url` 是显式启用的未认证 HTTP 测试服务地址,不是 Google 官方 GA4 模拟器。
+它与密钥文件互斥,仅接受非 Google 的 HTTP origin,不允许用户信息、路径、query 或 fragment。
+不要用于生产 GA4 访问。生产请求固定使用 Google HTTPS 端点,禁用重定向、cookie 和隐式 HTTP 重试。
+
+## Source 选项
+
+| 名称 | 类型 | 必填 | 默认值 | 说明 |
+| :--- | :--- | :--- | :--- | :--- |
+| property_id | string | 是 | - | 一个数字 GA4 属性 ID,不是 measurement ID。 |
+| start_date | string | 是 | - | 包含的开始日期,绝对有效日历日期 yyyy-MM-dd,不支持相对日期。 |
+| end_date | string | 是 | - | 包含的结束日期,不早于 start_date。 |
+| dimensions | array | 否 | [] | 按顺序指定不重复的维度 API 名称,最多 9 个。 |
+| metrics | array | 是 | - | 按顺序指定不重复的指标 API 名称,1 至 10 个,不能与维度重名。 |
+| metric_types | array | 是 | - | 与指标顺序一致的精确 Google MetricType 枚举值。 |
+| schema | config | 是 | - | 字段必须严格按维度、指标顺序排列,名称和类型必须匹配。 |
+| service_account_key_file | string | 条件必填 | - | worker 上的可信服务账号 JSON 文件,最大 1 MiB;两个认证选项必须且只能选一个。 |
+| emulator_url | string | 条件必填 | - | 未认证的隔离 HTTP 测试服务 origin,与密钥文件互斥。 |
+| page_size | int | 否 | 1000 | 每页请求行数,1 至 10000;有意小于 Google API 最大值。 |
+| max_report_rows | int | 否 | 1000000 | 报告总行数超过此值则失败,不截断;1 至 10000000。 |
+| max_response_bytes | int | 否 | 4194304 | 每页最大响应字节数,1024 至 16777216;超过时失败且不重试。 |
+| request_timeout_ms | int | 否 | 30000 | 包括响应正文传输的 HTTP 请求时限,100 至 120000 毫秒;不保证能中断 JVM/平台的同步 DNS 解析。 |
+| report_timeout_ms | int | 否 | 600000 | 报告整体时限,100 至 3600000 毫秒;适用于 HTTP、认证和重试等待,在行输出之间检查,不能中断同步 DNS 解析或下游阻塞的 collect 调用。 |
+| max_retries | int | 否 | 3 | 每页瞬时传输错误或 HTTP 429/500/502/503/504 的额外尝试次数,0 至 5。 |
+| max_retry_wait_ms | int | 否 | 30000 | 每次重试等待上限,1000 至 120000 毫秒。 |
+
+重试采用有界指数退避和抖动,并遵守 `Retry-After` 秒数或 HTTP 日期。
+服务端要求的等待超过配置上限时,作业失败而不是提前重试。
+无效请求、权限错误、schema 错误、过大响应和认证刷新错误不重试。
+未完成报告的页面返回 token 或 server-error 配额耗尽时,在下一次请求之前失败;
+不会在后台持续等待每日或每小时配额重置。
+
+内存按页限制,不缓存整个报告。JSON 解析和类型化行的内存使用量会超过响应字节大小本身。
+应根据 worker 堆内存同时调整 page_size 和 max_response_bytes。
+关闭/取消会终止活动 HTTP 请求并唤醒重试等待。请求时限也约束停滞的响应。
+报告时限不控制引擎重启,也不能消除下游背压。
+Apache HttpClient 在建立 socket 连接之前同步解析主机名。JVM/平台的 DNS 查询可能在连接和
+socket 超时之外阻塞,终止请求也不保证中断该查询。因此,DNS 解析阻塞期间,请求/报告时限
+和取消不是严格的墙钟时间上限;OAuth token 请求也有相同限制。
+
+## 数据类型
+
+维度使用 STRING,包括空字符串和日期形式的维度值,不自动解析日期。
+`TYPE_INTEGER` 指标要求 BIGINT,并检查 64 位溢出。
+`TYPE_FLOAT`、`TYPE_SECONDS`、`TYPE_MILLISECONDS`、`TYPE_MINUTES`、`TYPE_HOURS`、
+`TYPE_STANDARD`、`TYPE_CURRENCY`、`TYPE_FEET`、`TYPE_MILES`、`TYPE_METERS` 和
+`TYPE_KILOMETERS` 要求 DOUBLE。无效或非有限数值导致失败。
+DOUBLE 使用浮点精度,货币指标也不是精确十进制金额。
+每页检查精确 Google 类型枚举,因此不会把单位变化误认为兼容的 DOUBLE 类型。
+
+请先核对属性可用的维度、指标及兼容性。API 拒绝不兼容请求时,连接器返回 HTTP 状态并隐藏响应正文。
+V1 不支持过滤器、表达式、cohort、comparison、多个日期区间、实时报告或额外指标聚合。
+构造 factory/schema 时不执行网络请求。
+
+## 示例
+
+```hocon
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+source {
+ GoogleAnalytics4 {
+ property_id = "123456789"
+ service_account_key_file = "/run/secrets/ga4-service-account.json"
+ start_date = "2024-01-01"
+ end_date = "2024-01-31"
+ dimensions = ["country"]
+ metrics = ["activeUsers", "purchaseRevenue"]
+ metric_types = ["TYPE_INTEGER", "TYPE_CURRENCY"]
+ schema {
+ fields {
+ country = string
+ activeUsers = bigint
+ purchaseRevenue = double
+ }
+ }
+ }
+}
+sink {
+ Console {}
+}
+```
+
+仅在隔离测试中,将 service_account_key_file 替换为 `emulator_url = "http://fixture:1080"`,不要同时配置两者。
+
+## 验证
+
+提供确定性的 HTTP 测试以及模拟服务器的引擎 E2E 测试。
+认证测试使用临时生成的 RSA 密钥和模拟 OAuth 交换,不验证真实 GA4 属性。
+生产使用前仍需用经过授权的真实属性凭据验证访问权限、指标兼容性、分页、配额和报告限制。
+连接器不包含真实凭据。
+
+## 参考
+
+- [runReport REST API](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport)
+- [响应元数据](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/ResponseMetaData)
+- [指标类型](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/MetricType)
+- [配额](https://developers.google.com/analytics/devguides/reporting/data/v1/quotas)
+- [快速开始与属性访问](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries)
+
+## 更新日志
+
+<ChangeLog />
diff --git a/plugin-mapping.properties b/plugin-mapping.properties
index 79313b987a..f3bf789fbe 100644
--- a/plugin-mapping.properties
+++ b/plugin-mapping.properties
@@ -107,6 +107,7 @@ seatunnel.sink.AzureQueueStorage = connector-azure-queue-storage
seatunnel.source.GoogleBigtable = connector-google-bigtable
seatunnel.sink.GoogleBigtable = connector-google-bigtable
seatunnel.source.GoogleAds = connector-google-ads
+seatunnel.source.GoogleAnalytics4 = connector-google-analytics4
seatunnel.source.FacebookAds = connector-facebook-ads
seatunnel.source.TikTokAds = connector-tiktok-ads
seatunnel.sink.Tablestore = connector-tablestore
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/pom.xml b/seatunnel-connectors-v2/connector-google-analytics4/pom.xml
new file mode 100644
index 0000000000..0fd0216866
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/pom.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>seatunnel-connectors-v2</artifactId>
+ <version>${revision}</version>
+ </parent>
+ <artifactId>connector-google-analytics4</artifactId>
+ <name>SeaTunnel : Connectors V2 : Google Analytics 4</name>
+ <dependencies>
+ <dependency>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-common</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.auth</groupId>
+ <artifactId>google-auth-library-oauth2-http</artifactId>
+ <version>1.40.0</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>33.5.0-android</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>4.5.13</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <resources>
+ <resource>
+ <targetPath>META-INF/licenses</targetPath>
+ <directory>${project.basedir}/../../seatunnel-dist/release-docs/licenses</directory>
+ <includes>
+ <include>LICENSE-google-auth.txt</include>
+ <include>LICENSE-google-api-common.txt</include>
+ </includes>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <ga4.jar>${project.build.directory}/${project.build.finalName}.jar</ga4.jar>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <configuration>
+ <transformers>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer" />
+ </transformers>
+ <relocations>
+ <relocation>
+ <pattern>com.google</pattern>
+ <shadedPattern>${seatunnel.shade.package}.google.analytics4.com.google</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>org.apache.http</pattern>
+ <shadedPattern>${seatunnel.shade.package}.google.analytics4.org.apache.http</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>io.grpc</pattern>
+ <shadedPattern>${seatunnel.shade.package}.google.analytics4.io.grpc</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>io.opencensus</pattern>
+ <shadedPattern>${seatunnel.shade.package}.google.analytics4.io.opencensus</shadedPattern>
+ </relocation>
+ </relocations>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Config.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Config.java
new file mode 100644
index 0000000000..78391d317d
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Config.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.CatalogTableUtil;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+
+import lombok.Getter;
+
+import java.io.Serializable;
+import java.net.URI;
+import java.time.LocalDate;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.BACKOFF;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.DIMENSIONS;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.EMULATOR_URL;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.END_DATE;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.KEY_FILE;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.MAX_BYTES;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.MAX_ROWS;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.METRICS;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.METRIC_TYPES;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.PAGE_SIZE;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.PROPERTY_ID;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.REPORT_TIMEOUT;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.RETRIES;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.START_DATE;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4SourceOptions.TIMEOUT;
+
+@Getter
+final class GoogleAnalytics4Config implements Serializable {
+ private static final long serialVersionUID = 1L;
+ static final Set<String> FLOAT_TYPES =
+ Collections.unmodifiableSet(
+ new HashSet<>(
+ Arrays.asList(
+ "TYPE_FLOAT",
+ "TYPE_SECONDS",
+ "TYPE_MILLISECONDS",
+ "TYPE_MINUTES",
+ "TYPE_HOURS",
+ "TYPE_STANDARD",
+ "TYPE_CURRENCY",
+ "TYPE_FEET",
+ "TYPE_MILES",
+ "TYPE_METERS",
+ "TYPE_KILOMETERS")));
+
+ private final String propertyId;
+ private final String startDate;
+ private final String endDate;
+ private final List<String> dimensions;
+ private final List<String> metrics;
+ private final List<String> metricTypes;
+ private final String keyFile;
+ private final String endpoint;
+ private final int pageSize;
+ private final int maxRows;
+ private final int maxBytes;
+ private final int timeout;
+ private final int reportTimeout;
+ private final int retries;
+ private final int backoff;
+ private final CatalogTable table;
+
+ GoogleAnalytics4Config(ReadonlyConfig config) {
+ propertyId = config.get(PROPERTY_ID);
+ require(
+ propertyId != null && propertyId.matches("[1-9][0-9]{0,19}"),
+ "property_id must be numeric");
+ startDate = config.get(START_DATE);
+ endDate = config.get(END_DATE);
+ require(!date(startDate).isAfter(date(endDate)), "start_date must not follow end_date");
+ dimensions = names(config.get(DIMENSIONS), 0, 9, "dimensions");
+ metrics = names(config.get(METRICS), 1, 10, "metrics");
+ Set<String> all = new HashSet<>(dimensions);
+ require(metrics.stream().allMatch(all::add), "dimensions and metrics must not overlap");
+ metricTypes = Collections.unmodifiableList(new ArrayList<>(config.get(METRIC_TYPES)));
+ require(metricTypes.size() == metrics.size(), "metric_types must match metrics length");
+ for (String type : metricTypes) {
+ require(
+ "TYPE_INTEGER".equals(type) || FLOAT_TYPES.contains(type),
+ "unsupported metric_types entry");
+ }
+ keyFile = config.getOptional(KEY_FILE).orElse(null);
+ String emulator = config.getOptional(EMULATOR_URL).orElse(null);
+ require(
+ (keyFile == null) != (emulator == null),
+ "exactly one of service_account_key_file and emulator_url is required");
+ if (keyFile != null) {
+ require(!keyFile.trim().isEmpty(), "service_account_key_file must not be blank");
+ }
+ endpoint = emulator == null ? "https://analyticsdata.googleapis.com" : emulator(emulator);
+ pageSize = range(config.get(PAGE_SIZE), 1, 10000, "page_size");
+ maxRows = range(config.get(MAX_ROWS), 1, 10000000, "max_report_rows");
+ maxBytes = range(config.get(MAX_BYTES), 1024, 16777216, "max_response_bytes");
+ timeout = range(config.get(TIMEOUT), 100, 120000, "request_timeout_ms");
+ reportTimeout = range(config.get(REPORT_TIMEOUT), 100, 3600000, "report_timeout_ms");
+ retries = range(config.get(RETRIES), 0, 5, "max_retries");
+ backoff = range(config.get(BACKOFF), 1000, 120000, "max_retry_wait_ms");
+ table = CatalogTableUtil.buildWithConfig(config);
+ SeaTunnelRowType schema = table.getSeaTunnelRowType();
+ List<String> names = new ArrayList<>(dimensions);
+ names.addAll(metrics);
+ require(
+ Arrays.equals(schema.getFieldNames(), names.toArray(new String[0])),
+ "schema fields must exactly match dimensions followed by metrics, in order");
+ for (int i = 0; i < names.size(); i++) {
+ Object expected =
+ i < dimensions.size()
+ ? BasicType.STRING_TYPE
+ : ("TYPE_INTEGER".equals(metricTypes.get(i - dimensions.size()))
+ ? BasicType.LONG_TYPE
+ : BasicType.DOUBLE_TYPE);
+ require(
+ expected.equals(schema.getFieldType(i)),
+ "schema types must be STRING dimensions, BIGINT integer metrics and DOUBLE other metrics");
+ }
+ }
+
+ private static List<String> names(List<String> values, int min, int max, String option) {
+ require(
+ values != null && values.size() >= min && values.size() <= max,
+ option + " has invalid length");
+ Set<String> unique = new HashSet<>();
+ for (String name : values) {
+ require(
+ name != null
+ && name.length() <= 256
+ && name.matches("[a-zA-Z][a-zA-Z0-9_:]*")
+ && unique.add(name),
+ option + " must contain unique API names");
+ }
+ return Collections.unmodifiableList(new ArrayList<>(values));
+ }
+
+ private static LocalDate date(String value) {
+ require(
+ value != null && value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}"),
+ "dates must be absolute yyyy-MM-dd");
+ try {
+ return LocalDate.parse(value);
+ } catch (DateTimeParseException e) {
+ throw new IllegalArgumentException("GA4 dates must be valid calendar dates");
+ }
+ }
+
+ private static String emulator(String value) {
+ try {
+ URI uri = URI.create(value);
+ require(
+ "http".equals(uri.getScheme())
+ && uri.getHost() != null
+ && !uri.getHost().endsWith("googleapis.com")
+ && uri.getUserInfo() == null
+ && uri.getQuery() == null
+ && uri.getFragment() == null
+ && (uri.getPath().isEmpty() || "/".equals(uri.getPath())),
+ "emulator_url must be a non-Google HTTP origin without credentials, path, query or fragment");
+ return value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("GA4 emulator_url must be a non-Google HTTP origin");
+ }
+ }
+
+ private static int range(int value, int min, int max, String option) {
+ require(value >= min && value <= max, option + " is outside its supported bounds");
+ return value;
+ }
+
+ private static void require(boolean condition, String message) {
+ if (!condition) {
+ throw new IllegalArgumentException("GA4 " + message);
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4HttpTransport.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4HttpTransport.java
new file mode 100644
index 0000000000..daea3c95e5
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4HttpTransport.java
@@ -0,0 +1,278 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ByteArrayEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+
+import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.LowLevelHttpRequest;
+import com.google.api.client.http.LowLevelHttpResponse;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4Report.failure;
+
+/** One bounded HTTP path for report requests and the Google library's token exchange. */
+class GoogleAnalytics4HttpTransport extends HttpTransport implements Closeable {
+ private final CloseableHttpClient client =
+ HttpClients.custom()
+ .disableAutomaticRetries()
+ .disableRedirectHandling()
+ .disableCookieManagement()
+ .disableContentCompression()
+ .build();
+ private final ScheduledThreadPoolExecutor deadlines =
+ new ScheduledThreadPoolExecutor(
+ 1,
+ task -> {
+ Thread thread = new Thread(task, "google-analytics4-request-deadline");
+ thread.setDaemon(true);
+ return thread;
+ });
+ private final int timeout;
+ private final int maxBytes;
+ private volatile boolean closed;
+ private volatile HttpPost active;
+ private volatile long reportDeadline = Long.MAX_VALUE;
+
+ GoogleAnalytics4HttpTransport(GoogleAnalytics4Config config) {
+ timeout = config.getTimeout();
+ maxBytes = config.getMaxBytes();
+ deadlines.setRemoveOnCancelPolicy(true);
+ }
+
+ void setReportDeadline(long deadline) {
+ reportDeadline = deadline;
+ }
+
+ void checkActive() throws IOException {
+ if (closed || Thread.currentThread().isInterrupted()) {
+ throw failure("request cancelled");
+ }
+ if (System.nanoTime() >= reportDeadline) {
+ throw failure("report_timeout_ms exceeded");
+ }
+ }
+
+ Response post(String url, byte[] body, String token, int limit) throws IOException {
+ checkActive();
+ HttpPost request = new HttpPost(url);
+ active = request;
+ ScheduledFuture<?> abort = null;
+ try {
+ checkActive();
+ long remaining =
+ reportDeadline == Long.MAX_VALUE
+ ? timeout
+ : TimeUnit.NANOSECONDS.toMillis(reportDeadline - System.nanoTime());
+ int requestTimeout = (int) Math.max(1, Math.min(timeout, remaining));
+ request.setConfig(
+ RequestConfig.custom()
+ .setConnectTimeout(requestTimeout)
+ .setConnectionRequestTimeout(requestTimeout)
+ .setSocketTimeout(requestTimeout)
+ .setRedirectsEnabled(false)
+ .build());
+ request.setHeader(
+ "Content-Type",
+ token == null && url.endsWith("/token")
+ ? "application/x-www-form-urlencoded"
+ : "application/json");
+ if (token != null) {
+ request.setHeader("Authorization", "Bearer " + token);
+ }
+ request.setEntity(new ByteArrayEntity(body));
+ abort = deadlines.schedule(request::abort, requestTimeout, TimeUnit.MILLISECONDS);
+ try (CloseableHttpResponse response = client.execute(request)) {
+ HttpEntity entity = response.getEntity();
+ byte[] bytes = new byte[0];
+ if (entity != null) {
+ try {
+ if (entity.getContentLength() > limit) {
+ throw new ResponseLimitException();
+ }
+ bytes = readBounded(entity.getContent(), limit);
+ } catch (ResponseLimitException e) {
+ request.abort();
+ throw e;
+ }
+ }
+ checkActive();
+ if (request.isAborted()) {
+ throw failure("request_timeout_ms exceeded");
+ }
+ return new Response(
+ response.getStatusLine().getStatusCode(),
+ bytes,
+ response.getFirstHeader("Retry-After") == null
+ ? null
+ : response.getFirstHeader("Retry-After").getValue());
+ }
+ } catch (ResponseLimitException e) {
+ throw e;
+ } catch (IOException | RuntimeException e) {
+ checkActive();
+ throw failure(
+ request.isAborted()
+ ? "request_timeout_ms exceeded"
+ : "HTTP transport request failed");
+ } finally {
+ if (abort != null) {
+ abort.cancel(false);
+ }
+ request.abort();
+ active = null;
+ }
+ }
+
+ Response report(String url, byte[] body, String token) throws IOException {
+ return post(url, body, token, maxBytes);
+ }
+
+ static byte[] readBounded(InputStream input, int limit) throws IOException {
+ ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(8192, limit));
+ byte[] buffer = new byte[8192];
+ int count;
+ while ((count = input.read(buffer, 0, Math.min(buffer.length, limit - output.size() + 1)))
+ != -1) {
+ if (count > limit - output.size()) {
+ throw new ResponseLimitException();
+ }
+ output.write(buffer, 0, count);
+ }
+ return output.toByteArray();
+ }
+
+ @Override
+ public boolean supportsMethod(String method) {
+ return "POST".equals(method);
+ }
+
+ @Override
+ protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
+ if (!"POST".equals(method) || !"https://oauth2.googleapis.com/token".equals(url)) {
+ throw failure("unsupported token endpoint or method");
+ }
+ return new LowLevelHttpRequest() {
+ @Override
+ public void addHeader(String name, String value) {
+ // Google auth headers are not needed for this fixed OAuth endpoint.
+ }
+
+ @Override
+ public LowLevelHttpResponse execute() throws IOException {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ getStreamingContent().writeTo(body);
+ Response response = post(url, body.toByteArray(), null, 65536);
+ return new LowLevelHttpResponse() {
+ @Override
+ public InputStream getContent() {
+ return new ByteArrayInputStream(response.body);
+ }
+
+ @Override
+ public String getContentEncoding() {
+ return null;
+ }
+
+ @Override
+ public long getContentLength() {
+ return response.body.length;
+ }
+
+ @Override
+ public String getContentType() {
+ return "application/json";
+ }
+
+ @Override
+ public String getStatusLine() {
+ return "HTTP/1.1 " + response.status;
+ }
+
+ @Override
+ public int getStatusCode() {
+ return response.status;
+ }
+
+ @Override
+ public String getReasonPhrase() {
+ return "";
+ }
+
+ @Override
+ public int getHeaderCount() {
+ return 0;
+ }
+
+ @Override
+ public String getHeaderName(int index) {
+ return null;
+ }
+
+ @Override
+ public String getHeaderValue(int index) {
+ return null;
+ }
+ };
+ }
+ };
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed = true;
+ HttpPost request = active;
+ if (request != null) {
+ request.abort();
+ }
+ deadlines.shutdownNow();
+ client.close();
+ }
+
+ static final class Response {
+ final int status;
+ final byte[] body;
+ final String retryAfter;
+
+ Response(int status, byte[] body, String retryAfter) {
+ this.status = status;
+ this.body = body;
+ this.retryAfter = retryAfter;
+ }
+ }
+
+ static final class ResponseLimitException extends IOException {
+ ResponseLimitException() {
+ super("GoogleAnalytics4: response size limit exceeded");
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Report.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Report.java
new file mode 100644
index 0000000000..72af23f01c
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Report.java
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.JsonParser;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.DeserializationFeature;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+final class GoogleAnalytics4Report {
+ private static final ObjectMapper MAPPER =
+ new ObjectMapper()
+ .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+ private final GoogleAnalytics4Config config;
+ private long expectedCount = -1;
+ private List<String> previousKey;
+ private String currency;
+ private String timeZone;
+
+ GoogleAnalytics4Report(GoogleAnalytics4Config config) {
+ this.config = config;
+ }
+
+ byte[] request(long offset) throws IOException {
+ ObjectNode request = MAPPER.createObjectNode();
+ ArrayNode dimensions = request.putArray("dimensions");
+ ArrayNode order = request.putArray("orderBys");
+ for (String name : config.getDimensions()) {
+ dimensions.addObject().put("name", name);
+ order.addObject()
+ .putObject("dimension")
+ .put("dimensionName", name)
+ .put("orderType", "ALPHANUMERIC");
+ }
+ ArrayNode metrics = request.putArray("metrics");
+ config.getMetrics().forEach(name -> metrics.addObject().put("name", name));
+ request.putArray("dateRanges")
+ .addObject()
+ .put("startDate", config.getStartDate())
+ .put("endDate", config.getEndDate());
+ request.put("offset", Long.toString(offset));
+ request.put("limit", Integer.toString(config.getPageSize()));
+ request.put("keepEmptyRows", true);
+ request.put("returnPropertyQuota", true);
+ return MAPPER.writeValueAsBytes(request);
+ }
+
+ Page parse(byte[] bytes, long offset) throws IOException {
+ JsonNode response;
+ try {
+ response = MAPPER.readTree(bytes);
+ } catch (IOException | RuntimeException e) {
+ throw failure("invalid JSON response");
+ }
+ if (response == null || !response.isObject() || response.has("error")) {
+ throw failure("invalid report response");
+ }
+ validateMetadata(response.path("metadata"));
+ headers(response.path("dimensionHeaders"), config.getDimensions(), false);
+ headers(response.path("metricHeaders"), config.getMetrics(), true);
+ // Protobuf JSON omits zero-valued scalar fields and empty repeated fields.
+ long count = response.has("rowCount") ? count(response.get("rowCount"), "rowCount") : 0;
+ if (count > config.getMaxRows() || (expectedCount >= 0 && expectedCount != count)) {
+ throw failure("rowCount changed or exceeds max_report_rows; restart the entire report");
+ }
+ if (config.getDimensions().isEmpty() && count > 1) {
+ throw failure("a report without dimensions must contain at most one row");
+ }
+ JsonNode rows = response.path("rows");
+ if (!rows.isMissingNode() && !rows.isArray()) {
+ throw failure("rows must be an array");
+ }
+ if (offset > count
+ || rows.size() > config.getPageSize()
+ || offset + rows.size() > count
+ || (offset < count && rows.size() == 0)) {
+ throw failure("inconsistent page length or rowCount; no page was skipped");
+ }
+ List<SeaTunnelRow> result = new ArrayList<>(rows.size());
+ for (JsonNode row : rows) {
+ JsonNode dims = row.path("dimensionValues");
+ JsonNode metrics = row.path("metricValues");
+ values(dims, config.getDimensions().size());
+ values(metrics, config.getMetrics().size());
+ Object[] fields =
+ new Object[config.getDimensions().size() + config.getMetrics().size()];
+ List<String> key = new ArrayList<>();
+ int field = 0;
+ for (JsonNode dim : dims) {
+ String value = text(dim.path("value"), "dimension value");
+ key.add(value);
+ fields[field++] = value;
+ }
+ if (previousKey != null && compare(previousKey, key) >= 0) {
+ throw failure("duplicate or out-of-order dimension tuple; report may have changed");
+ }
+ for (int i = 0; i < config.getMetrics().size(); i++) {
+ String value = text(metrics.get(i).path("value"), "metric value");
+ try {
+ if ("TYPE_INTEGER".equals(config.getMetricTypes().get(i))) {
+ if (!value.matches("-?[0-9]+")) {
+ throw new NumberFormatException();
+ }
+ fields[field++] = Long.parseLong(value);
+ } else {
+ if (!value.matches(
+ "-?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?")) {
+ throw new NumberFormatException();
+ }
+ double number = Double.parseDouble(value);
+ if (!Double.isFinite(number)) {
+ throw new NumberFormatException();
+ }
+ fields[field++] = number;
+ }
+ } catch (NumberFormatException e) {
+ throw failure("metric value is invalid or outside the configured numeric type");
+ }
+ }
+ SeaTunnelRow output = new SeaTunnelRow(fields);
+ output.setTableId(config.getTable().getTableId().toTablePath().toString());
+ result.add(output);
+ previousKey = key;
+ }
+ expectedCount = count;
+ boolean finished = offset + result.size() == count;
+ if (!finished) {
+ checkQuota(response.path("propertyQuota"));
+ }
+ return new Page(result, finished);
+ }
+
+ private void headers(JsonNode headers, List<String> names, boolean metric) throws IOException {
+ if ((names.isEmpty() && headers.isMissingNode())) {
+ return;
+ }
+ if (!headers.isArray() || headers.size() != names.size()) {
+ throw failure("response headers do not match configured schema");
+ }
+ for (int i = 0; i < names.size(); i++) {
+ if (!names.get(i).equals(text(headers.get(i).path("name"), "header name"))
+ || (metric
+ && !config.getMetricTypes()
+ .get(i)
+ .equals(text(headers.get(i).path("type"), "metric type")))) {
+ throw failure(
+ "response header name or metric type does not match configured schema");
+ }
+ }
+ }
+
+ private void validateMetadata(JsonNode metadata) throws IOException {
+ if (metadata.isMissingNode()) {
+ return;
+ }
+ if (!metadata.isObject()) {
+ throw failure("invalid metadata");
+ }
+ for (String flag : new String[] {"dataLossFromOtherRow", "subjectToThresholding"}) {
+ if (metadata.has(flag)
+ && (!metadata.get(flag).isBoolean() || metadata.get(flag).booleanValue())) {
+ throw failure("report metadata indicates " + flag + "; report rejected");
+ }
+ }
+ if (metadata.has("samplingMetadatas")
+ && (!metadata.get("samplingMetadatas").isArray()
+ || metadata.get("samplingMetadatas").size() != 0)) {
+ throw failure("sampled report is not supported");
+ }
+ JsonNode restrictions = metadata.path("schemaRestrictionResponse");
+ if (!restrictions.isMissingNode()) {
+ if (!restrictions.isObject()) {
+ throw failure("invalid schemaRestrictionResponse");
+ }
+ JsonNode active = restrictions.path("activeMetricRestrictions");
+ if (!active.isMissingNode() && (!active.isArray() || active.size() != 0)) {
+ throw failure("report contains restricted metrics");
+ }
+ }
+ if (metadata.has("emptyReason")
+ && !text(metadata.get("emptyReason"), "emptyReason").isEmpty()) {
+ throw failure(
+ "report metadata contains an emptyReason; check property access and reporting availability");
+ }
+ if (metadata.has("currencyCode")) {
+ String current = text(metadata.get("currencyCode"), "currencyCode");
+ if (currency != null && !currency.equals(current)) {
+ throw failure("report currency changed");
+ }
+ currency = current;
+ }
+ if (metadata.has("timeZone")) {
+ String current = text(metadata.get("timeZone"), "timeZone");
+ if (timeZone != null && !timeZone.equals(current)) {
+ throw failure("report timeZone changed");
+ }
+ timeZone = current;
+ }
+ }
+
+ private static void checkQuota(JsonNode quota) throws IOException {
+ if (quota.isMissingNode()) {
+ return;
+ }
+ if (!quota.isObject()) {
+ throw failure("invalid propertyQuota");
+ }
+ for (String bucket :
+ new String[] {
+ "tokensPerDay",
+ "tokensPerHour",
+ "tokensPerProjectPerHour",
+ "serverErrorsPerProjectPerHour"
+ }) {
+ JsonNode status = quota.path(bucket);
+ if (!status.isMissingNode()) {
+ if (!status.isObject()) {
+ throw failure("invalid propertyQuota status");
+ }
+ // A present status with omitted remaining means protobuf's default zero.
+ long remaining =
+ status.has("remaining")
+ ? count(status.get("remaining"), "quota remaining")
+ : 0;
+ if (remaining == 0) {
+ throw failure(
+ "property quota exhausted before report completion; retry the job after quota reset");
+ }
+ }
+ }
+ }
+
+ private static void values(JsonNode values, int width) throws IOException {
+ if (width == 0 && values.isMissingNode()) {
+ return;
+ }
+ if (!values.isArray() || values.size() != width) {
+ throw failure("row width does not match configured schema");
+ }
+ }
+
+ private static String text(JsonNode value, String field) throws IOException {
+ if (!value.isTextual()) {
+ throw failure("missing or invalid " + field);
+ }
+ return value.textValue();
+ }
+
+ private static long count(JsonNode value, String field) throws IOException {
+ if (!value.isIntegralNumber() || !value.canConvertToLong() || value.longValue() < 0) {
+ throw failure("invalid " + field);
+ }
+ return value.longValue();
+ }
+
+ // Google ALPHANUMERIC compares Unicode code points, not UTF-16 code units.
+ static int compare(List<String> left, List<String> right) {
+ for (int i = 0; i < left.size(); i++) {
+ String a = left.get(i);
+ String b = right.get(i);
+ int x = 0;
+ int y = 0;
+ while (x < a.length() && y < b.length()) {
+ int aPoint = a.codePointAt(x);
+ int bPoint = b.codePointAt(y);
+ int cmp = Integer.compare(aPoint, bPoint);
+ if (cmp != 0) {
+ return cmp;
+ }
+ x += Character.charCount(aPoint);
+ y += Character.charCount(bPoint);
+ }
+ int cmp = Integer.compare(a.length() - x, b.length() - y);
+ if (cmp != 0) {
+ return cmp;
+ }
+ }
+ return 0;
+ }
+
+ static IOException failure(String message) {
+ // Never attach an HTTP/JSON/auth exception: it may contain credentials or report data.
+ return new IOException("GoogleAnalytics4: " + message);
+ }
+
+ static final class Page {
+ final List<SeaTunnelRow> rows;
+ final boolean finished;
+
+ Page(List<SeaTunnelRow> rows, boolean finished) {
+ this.rows = rows;
+ this.finished = finished;
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Source.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Source.java
new file mode 100644
index 0000000000..7710d47fc2
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4Source.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.api.common.JobContext;
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.source.Boundedness;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.common.constants.JobMode;
+import org.apache.seatunnel.connectors.seatunnel.common.source.AbstractSingleSplitReader;
+import org.apache.seatunnel.connectors.seatunnel.common.source.AbstractSingleSplitSource;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+
+import java.util.Collections;
+import java.util.List;
+
+public class GoogleAnalytics4Source extends AbstractSingleSplitSource<SeaTunnelRow> {
+ public static final String PLUGIN_NAME = "GoogleAnalytics4";
+ private final GoogleAnalytics4Config config;
+
+ public GoogleAnalytics4Source(ReadonlyConfig options) {
+ config = new GoogleAnalytics4Config(options);
+ }
+
+ @Override
+ public void setJobContext(JobContext context) {
+ if (context.getJobMode() != JobMode.BATCH) {
+ throw new IllegalArgumentException("GoogleAnalytics4 supports batch jobs only");
+ }
+ }
+
+ @Override
+ public String getPluginName() {
+ return PLUGIN_NAME;
+ }
+
+ @Override
+ public Boundedness getBoundedness() {
+ return Boundedness.BOUNDED;
+ }
+
+ @Override
+ public List<CatalogTable> getProducedCatalogTables() {
+ return Collections.singletonList(config.getTable());
+ }
+
+ @Override
+ public AbstractSingleSplitReader<SeaTunnelRow> createReader(SingleSplitReaderContext context) {
+ return new GoogleAnalytics4SourceReader(config, context);
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceFactory.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceFactory.java
new file mode 100644
index 0000000000..bca4655528
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceFactory.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.api.configuration.util.OptionRule;
+import org.apache.seatunnel.api.options.ConnectorCommonOptions;
+import org.apache.seatunnel.api.source.SeaTunnelSource;
+import org.apache.seatunnel.api.source.SourceSplit;
+import org.apache.seatunnel.api.table.connector.TableSource;
+import org.apache.seatunnel.api.table.factory.Factory;
+import org.apache.seatunnel.api.table.factory.TableSourceFactory;
+import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
+
+import com.google.auto.service.AutoService;
+
+import java.io.Serializable;
+
+@AutoService(Factory.class)
+public class GoogleAnalytics4SourceFactory implements TableSourceFactory {
+ @Override
+ public String factoryIdentifier() {
+ return GoogleAnalytics4Source.PLUGIN_NAME;
+ }
+
+ @Override
+ public OptionRule optionRule() {
+ return OptionRule.builder()
+ .required(
+ GoogleAnalytics4SourceOptions.PROPERTY_ID,
+ GoogleAnalytics4SourceOptions.START_DATE,
+ GoogleAnalytics4SourceOptions.END_DATE,
+ GoogleAnalytics4SourceOptions.METRICS,
+ GoogleAnalytics4SourceOptions.METRIC_TYPES,
+ ConnectorCommonOptions.SCHEMA)
+ .exclusive(
+ GoogleAnalytics4SourceOptions.KEY_FILE,
+ GoogleAnalytics4SourceOptions.EMULATOR_URL)
+ .optional(
+ GoogleAnalytics4SourceOptions.DIMENSIONS,
+ GoogleAnalytics4SourceOptions.PAGE_SIZE,
+ GoogleAnalytics4SourceOptions.MAX_ROWS,
+ GoogleAnalytics4SourceOptions.MAX_BYTES,
+ GoogleAnalytics4SourceOptions.TIMEOUT,
+ GoogleAnalytics4SourceOptions.REPORT_TIMEOUT,
+ GoogleAnalytics4SourceOptions.RETRIES,
+ GoogleAnalytics4SourceOptions.BACKOFF)
+ .build();
+ }
+
+ @Override
+ public <T, SplitT extends SourceSplit, StateT extends Serializable>
+ TableSource<T, SplitT, StateT> createSource(TableSourceFactoryContext context) {
+ GoogleAnalytics4Source source = new GoogleAnalytics4Source(context.getOptions());
+ return () -> (SeaTunnelSource<T, SplitT, StateT>) source;
+ }
+
+ @Override
+ public Class<? extends SeaTunnelSource> getSourceClass() {
+ return GoogleAnalytics4Source.class;
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceOptions.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceOptions.java
new file mode 100644
index 0000000000..caae19d972
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceOptions.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.api.configuration.Option;
+import org.apache.seatunnel.api.configuration.Options;
+
+import java.util.Collections;
+import java.util.List;
+
+public final class GoogleAnalytics4SourceOptions {
+ private GoogleAnalytics4SourceOptions() {}
+
+ public static final Option<String> PROPERTY_ID =
+ Options.key("property_id")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("One numeric GA4 property ID.");
+ public static final Option<String> START_DATE =
+ Options.key("start_date")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "Inclusive absolute start date, yyyy-MM-dd in the property time zone.");
+ public static final Option<String> END_DATE =
+ Options.key("end_date")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "Inclusive absolute end date, yyyy-MM-dd in the property time zone.");
+ public static final Option<List<String>> DIMENSIONS =
+ Options.key("dimensions")
+ .listType()
+ .defaultValue(Collections.emptyList())
+ .withDescription("Ordered dimension API names, at most 9.");
+ public static final Option<List<String>> METRICS =
+ Options.key("metrics")
+ .listType()
+ .noDefaultValue()
+ .withDescription("Ordered metric API names, 1 to 10.");
+ public static final Option<List<String>> METRIC_TYPES =
+ Options.key("metric_types")
+ .listType()
+ .noDefaultValue()
+ .withDescription(
+ "Exact Google MetricType enum for each metric; checked on every response.");
+ public static final Option<String> KEY_FILE =
+ Options.key("service_account_key_file")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "Trusted service account JSON file available on the worker; mutually exclusive with emulator_url.");
+ public static final Option<String> EMULATOR_URL =
+ Options.key("emulator_url")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "Explicit HTTP mock server origin. Disables authentication; never use for Google Analytics.");
+ public static final Option<Integer> PAGE_SIZE =
+ Options.key("page_size")
+ .intType()
+ .defaultValue(1000)
+ .withDescription("Rows requested per page, 1 to 10000.");
+ public static final Option<Integer> MAX_ROWS =
+ Options.key("max_report_rows")
+ .intType()
+ .defaultValue(1000000)
+ .withDescription(
+ "Fail, never truncate, if rowCount exceeds this bound (1 to 10000000).");
+ public static final Option<Integer> MAX_BYTES =
+ Options.key("max_response_bytes")
+ .intType()
+ .defaultValue(4194304)
+ .withDescription("Maximum response bytes per page, 1024 to 16777216.");
+ public static final Option<Integer> TIMEOUT =
+ Options.key("request_timeout_ms")
+ .intType()
+ .defaultValue(30000)
+ .withDescription(
+ "Total HTTP request deadline including response body, 100 to 120000 ms.");
+ public static final Option<Integer> REPORT_TIMEOUT =
+ Options.key("report_timeout_ms")
+ .intType()
+ .defaultValue(600000)
+ .withDescription(
+ "Whole report deadline checked between rows/requests, 100 to 3600000 ms.");
+ public static final Option<Integer> RETRIES =
+ Options.key("max_retries")
+ .intType()
+ .defaultValue(3)
+ .withDescription(
+ "Additional attempts per report page for 429, 500, 502, 503, 504 or transport failure, 0 to 5.");
+ public static final Option<Integer> BACKOFF =
+ Options.key("max_retry_wait_ms")
+ .intType()
+ .defaultValue(30000)
+ .withDescription(
+ "Maximum retry wait, 1000 to 120000 ms. Longer Retry-After fails the job instead of retrying early.");
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReader.java b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReader.java
new file mode 100644
index 0000000000..35fd3c7733
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/main/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReader.java
@@ -0,0 +1,260 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.connectors.seatunnel.common.source.AbstractSingleSplitReader;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+
+import com.google.auth.oauth2.AccessToken;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.auth.oauth2.ServiceAccountCredentials;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.Collections;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4Report.failure;
+
+final class GoogleAnalytics4SourceReader extends AbstractSingleSplitReader<SeaTunnelRow> {
+ private final GoogleAnalytics4Config config;
+ private final SingleSplitReaderContext context;
+ private final Object cancellation = new Object();
+ private volatile boolean closed;
+ private volatile GoogleAnalytics4HttpTransport transport;
+ private GoogleCredentials credentials;
+
+ GoogleAnalytics4SourceReader(GoogleAnalytics4Config config, SingleSplitReaderContext context) {
+ this(config, context, null);
+ }
+
+ GoogleAnalytics4SourceReader(
+ GoogleAnalytics4Config config,
+ SingleSplitReaderContext context,
+ GoogleAnalytics4HttpTransport transport) {
+ this.config = config;
+ this.context = context;
+ this.transport = transport;
+ }
+
+ @Override
+ public void open() throws IOException {
+ synchronized (cancellation) {
+ if (closed) {
+ throw failure("reader is closed");
+ }
+ if (transport == null) {
+ transport = new GoogleAnalytics4HttpTransport(config);
+ }
+ }
+ try {
+ if (config.getKeyFile() != null) {
+ try (InputStream file = Files.newInputStream(Paths.get(config.getKeyFile()))) {
+ byte[] key = GoogleAnalytics4HttpTransport.readBounded(file, 1048576);
+ ServiceAccountCredentials account =
+ ServiceAccountCredentials.fromStream(
+ new ByteArrayInputStream(key), () -> transport);
+ if (!"https://oauth2.googleapis.com/token"
+ .equals(account.getTokenServerUri().toString())) {
+ throw failure("service account token_uri must use Google's OAuth endpoint");
+ }
+ credentials =
+ account.createWithCustomRetryStrategy(false)
+ .createScoped(
+ Collections.singleton(
+ "https://www.googleapis.com/auth/analytics.readonly"));
+ }
+ }
+ } catch (IOException | RuntimeException e) {
+ close();
+ throw failure(
+ "cannot load service_account_key_file; use a trusted service account JSON file with the standard token_uri");
+ }
+ }
+
+ @Override
+ public void internalPollNext(Collector<SeaTunnelRow> output) throws Exception {
+ long deadline =
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(config.getReportTimeout());
+ transport.setReportDeadline(deadline);
+ GoogleAnalytics4Report report = new GoogleAnalytics4Report(config);
+ long offset = 0;
+ while (!closed) {
+ transport.checkActive();
+ byte[] response = fetch(report.request(offset), deadline);
+ GoogleAnalytics4Report.Page page = report.parse(response, offset);
+ for (SeaTunnelRow row : page.rows) {
+ transport.checkActive();
+ output.collect(row);
+ }
+ offset += page.rows.size();
+ if (page.finished) {
+ transport.checkActive();
+ context.signalNoMoreElement();
+ return;
+ }
+ }
+ throw failure("reader cancelled");
+ }
+
+ private byte[] fetch(byte[] request, long deadline) throws IOException {
+ boolean refreshed = false;
+ int retry = 0;
+ while (true) {
+ transport.checkActive();
+ String token = token(false);
+ GoogleAnalytics4HttpTransport.Response response;
+ try {
+ response =
+ transport.report(
+ config.getEndpoint()
+ + "/v1beta/properties/"
+ + config.getPropertyId()
+ + ":runReport",
+ request,
+ token);
+ } catch (GoogleAnalytics4HttpTransport.ResponseLimitException e) {
+ throw e;
+ } catch (IOException e) {
+ transport.checkActive();
+ if (retry >= config.getRetries()) {
+ throw e;
+ }
+ awaitRetry(retry++, null, deadline);
+ continue;
+ }
+ if (response.status == 200) {
+ return response.body;
+ }
+ if (response.status == 401 && credentials != null && !refreshed) {
+ token(true);
+ refreshed = true;
+ continue;
+ }
+ boolean transientStatus =
+ response.status == 429
+ || response.status == 500
+ || response.status == 502
+ || response.status == 503
+ || response.status == 504;
+ if (!transientStatus || retry >= config.getRetries()) {
+ throw failure(
+ "runReport failed with HTTP "
+ + response.status
+ + "; check request compatibility, property access or quota (response body redacted)");
+ }
+ awaitRetry(retry++, response.retryAfter, deadline);
+ }
+ }
+
+ private String token(boolean force) throws IOException {
+ if (credentials == null) {
+ return null;
+ }
+ try {
+ AccessToken token = credentials.getAccessToken();
+ if (force
+ || token == null
+ || token.getExpirationTime() == null
+ || token.getExpirationTime().getTime() <= System.currentTimeMillis() + 60000) {
+ // Synchronous refresh; no background refresh executor or hidden page retry.
+ credentials.refresh();
+ token = credentials.getAccessToken();
+ }
+ transport.checkActive();
+ if (token == null
+ || token.getTokenValue() == null
+ || token.getTokenValue().isEmpty()
+ || !token.getTokenValue().matches("[A-Za-z0-9._~+/=-]+")) {
+ throw failure("invalid access token");
+ }
+ return token.getTokenValue();
+ } catch (IOException | RuntimeException e) {
+ throw failure("authentication refresh failed (details redacted)");
+ }
+ }
+
+ private void awaitRetry(int attempt, String retryAfter, long deadline) throws IOException {
+ long base = Math.min(config.getBackoff(), 1000L << attempt);
+ long jittered = ThreadLocalRandom.current().nextLong(Math.max(1, base / 2), base + 1);
+ long wait =
+ retryDelay(retryAfter, jittered, config.getBackoff(), System.currentTimeMillis());
+ if (TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()) <= wait) {
+ throw failure("retry would exceed report_timeout_ms");
+ }
+ long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(wait);
+ synchronized (cancellation) {
+ while (!closed && System.nanoTime() < until) {
+ try {
+ TimeUnit.NANOSECONDS.timedWait(cancellation, until - System.nanoTime());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw failure("retry interrupted");
+ }
+ }
+ }
+ transport.checkActive();
+ }
+
+ static long retryDelay(String header, long fallback, long maximum, long now)
+ throws IOException {
+ long wait = fallback;
+ if (header != null) {
+ try {
+ String value = header.trim();
+ if (value.matches("[0-9]+")) {
+ wait = Math.max(wait, Math.multiplyExact(Long.parseLong(value), 1000L));
+ } else {
+ wait =
+ Math.max(
+ wait,
+ ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)
+ .toInstant()
+ .toEpochMilli()
+ - now);
+ }
+ } catch (NumberFormatException | ArithmeticException | DateTimeParseException e) {
+ throw failure("invalid Retry-After header");
+ }
+ }
+ if (wait > maximum) {
+ throw failure("Retry-After exceeds max_retry_wait_ms; retry the job later");
+ }
+ return wait;
+ }
+
+ @Override
+ public void close() throws IOException {
+ synchronized (cancellation) {
+ closed = true;
+ cancellation.notifyAll();
+ if (transport != null) {
+ transport.close();
+ }
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4ReportTest.java b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4ReportTest.java
new file mode 100644
index 0000000000..2b14f0502d
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4ReportTest.java
@@ -0,0 +1,336 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.configuration.util.ConfigValidator;
+import org.apache.seatunnel.api.table.factory.Factory;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+class GoogleAnalytics4ReportTest {
+ static final ObjectMapper JSON = new ObjectMapper();
+
+ static Map<String, Object> options() {
+ Map<String, Object> options = new LinkedHashMap<>();
+ options.put("property_id", "123");
+ options.put("start_date", "2024-01-01");
+ options.put("end_date", "2024-01-31");
+ options.put("dimensions", Collections.singletonList("country"));
+ options.put("metrics", Arrays.asList("activeUsers", "purchaseRevenue"));
+ options.put("metric_types", Arrays.asList("TYPE_INTEGER", "TYPE_CURRENCY"));
+ options.put("emulator_url", "http://localhost:12345");
+ options.put("page_size", 2);
+ options.put("max_retries", 0);
+ Map<String, Object> fields = new LinkedHashMap<>();
+ fields.put("country", "string");
+ fields.put("activeUsers", "bigint");
+ fields.put("purchaseRevenue", "double");
+ options.put("schema", Collections.singletonMap("fields", fields));
+ return options;
+ }
+
+ static GoogleAnalytics4Config config() {
+ return new GoogleAnalytics4Config(ReadonlyConfig.fromMap(options()));
+ }
+
+ static ObjectNode page(int count, String... countries) {
+ ObjectNode page = JSON.createObjectNode();
+ page.putArray("dimensionHeaders").addObject().put("name", "country");
+ page.putArray("metricHeaders")
+ .addObject()
+ .put("name", "activeUsers")
+ .put("type", "TYPE_INTEGER");
+ page.withArray("metricHeaders")
+ .addObject()
+ .put("name", "purchaseRevenue")
+ .put("type", "TYPE_CURRENCY");
+ page.put("rowCount", count);
+ for (String country : countries) {
+ ObjectNode row = page.withArray("rows").addObject();
+ row.putArray("dimensionValues").addObject().put("value", country);
+ row.putArray("metricValues").addObject().put("value", "9223372036854775807");
+ row.withArray("metricValues").addObject().put("value", "1.25");
+ }
+ return page;
+ }
+
+ static byte[] bytes(ObjectNode node) {
+ return node.toString().getBytes(StandardCharsets.UTF_8);
+ }
+
+ @Test
+ void typedPagesAndDeterministicRequest() throws Exception {
+ GoogleAnalytics4Report report = new GoogleAnalytics4Report(config());
+ ObjectNode request = (ObjectNode) JSON.readTree(report.request(2));
+ Assertions.assertEquals("2", request.path("offset").asText());
+ Assertions.assertEquals(
+ "ALPHANUMERIC",
+ request.path("orderBys").get(0).path("dimension").path("orderType").asText());
+ Assertions.assertEquals(
+ "2024-01-01", request.path("dateRanges").get(0).path("startDate").asText());
+ Assertions.assertTrue(request.path("returnPropertyQuota").asBoolean());
+ GoogleAnalytics4Report.Page first = report.parse(bytes(page(3, "CA", "DE")), 0);
+ Assertions.assertFalse(first.finished);
+ Assertions.assertEquals(Long.MAX_VALUE, first.rows.get(0).getField(1));
+ Assertions.assertEquals(1.25, first.rows.get(0).getField(2));
+ GoogleAnalytics4Report.Page last = report.parse(bytes(page(3, "US")), 2);
+ Assertions.assertTrue(last.finished);
+ Assertions.assertEquals("US", last.rows.get(0).getField(0));
+ }
+
+ @Test
+ void shortPageAdvancesByActualRows() throws Exception {
+ GoogleAnalytics4Report report = new GoogleAnalytics4Report(config());
+ Assertions.assertFalse(report.parse(bytes(page(2, "CA")), 0).finished);
+ Assertions.assertTrue(report.parse(bytes(page(2, "US")), 1).finished);
+ }
+
+ @Test
+ void acceptsEmptyReportAndOptionalMetadataOmission() throws Exception {
+ ObjectNode response = page(0);
+ response.remove("rowCount");
+ Assertions.assertTrue(
+ new GoogleAnalytics4Report(config()).parse(bytes(response), 0).finished);
+ }
+
+ @Test
+ void acceptsExplicitEmptyAndLiteralOtherDimension() throws Exception {
+ List<SeaTunnelRow> rows =
+ new GoogleAnalytics4Report(config()).parse(bytes(page(2, "", "(other)")), 0).rows;
+ Assertions.assertEquals("", rows.get(0).getField(0));
+ Assertions.assertEquals("(other)", rows.get(1).getField(0));
+ }
+
+ @Test
+ void rejectsChangedCountsRepeatedAndOutOfOrderPages() throws Exception {
+ GoogleAnalytics4Report report = new GoogleAnalytics4Report(config());
+ report.parse(bytes(page(3, "CA", "DE")), 0);
+ Assertions.assertTrue(
+ Assertions.assertThrows(
+ IOException.class, () -> report.parse(bytes(page(4, "US")), 2))
+ .getMessage()
+ .contains("rowCount"));
+ Assertions.assertTrue(
+ Assertions.assertThrows(
+ IOException.class, () -> report.parse(bytes(page(3, "DE")), 2))
+ .getMessage()
+ .contains("duplicate"));
+ assertBad(page(2, "US", "CA"), "out-of-order");
+ }
+
+ @Test
+ void rejectsCountsWidthsHeadersMissingValuesAndMalformedNumbers() {
+ assertBad(page(3), "page length");
+ assertBad(page(1, "CA", "US"), "page length");
+ assertBad(page(3, "CA", "DE", "US"), "page length");
+ ObjectNode p = page(1, "CA");
+ p.put("rowCount", -1);
+ assertBad(p, "rowCount");
+ p = page(1, "CA");
+ p.put("rowCount", "1");
+ assertBad(p, "rowCount");
+ p = page(1, "CA");
+ ((ObjectNode) p.path("metricHeaders").get(0)).put("name", "unexpected");
+ assertBad(p, "header");
+ p = page(1, "CA");
+ ((ObjectNode) p.path("metricHeaders").get(1)).put("type", "TYPE_FLOAT");
+ assertBad(p, "metric type");
+ p = page(1, "CA");
+ ((ObjectNode) p.path("rows").get(0)).remove("metricValues");
+ assertBad(p, "width");
+ p = page(1, "CA");
+ ((ObjectNode) p.path("rows").get(0).path("dimensionValues").get(0)).remove("value");
+ assertBad(p, "dimension value");
+ for (String value : Arrays.asList("1.2", "9223372036854775808", "secret-number")) {
+ p = page(1, "CA");
+ ((ObjectNode) p.path("rows").get(0).path("metricValues").get(0)).put("value", value);
+ assertBad(p, "metric value");
+ }
+ for (String value : Arrays.asList("NaN", "Infinity", "1e309", "0x1.0p0")) {
+ p = page(1, "CA");
+ ((ObjectNode) p.path("rows").get(0).path("metricValues").get(1)).put("value", value);
+ assertBad(p, "metric value");
+ }
+ }
+
+ @Test
+ void failsClosedForDetectedLimitationsNotAbsentMetadata() throws Exception {
+ for (String flag : Arrays.asList("subjectToThresholding", "dataLossFromOtherRow")) {
+ ObjectNode p = page(1, "CA");
+ p.putObject("metadata").put(flag, true);
+ assertBad(p, flag);
+ p.with("metadata").put(flag, false);
+ Assertions.assertTrue(new GoogleAnalytics4Report(config()).parse(bytes(p), 0).finished);
+ }
+ ObjectNode p = page(1, "CA");
+ p.putObject("metadata")
+ .putArray("samplingMetadatas")
+ .addObject()
+ .put("samplesReadCount", "1")
+ .put("samplingSpaceSize", "2");
+ assertBad(p, "sampled");
+ p = page(1, "CA");
+ p.putObject("metadata")
+ .putObject("schemaRestrictionResponse")
+ .putArray("activeMetricRestrictions")
+ .addObject()
+ .put("metricName", "purchaseRevenue");
+ assertBad(p, "restricted");
+ p = page(0);
+ p.putObject("metadata").put("emptyReason", "private-report-detail");
+ assertBad(p, "emptyReason");
+ }
+
+ @Test
+ void rejectsExhaustedQuotaBeforeAnotherPageButAllowsCompletedReport() throws Exception {
+ ObjectNode p = page(2, "CA");
+ p.putObject("propertyQuota").putObject("tokensPerHour").put("remaining", 0);
+ assertBad(p, "quota exhausted");
+ p.put("rowCount", 1);
+ Assertions.assertTrue(new GoogleAnalytics4Report(config()).parse(bytes(p), 0).finished);
+ }
+
+ @Test
+ void rejectsInvalidJsonWithoutPayloadAndDuplicateFields() {
+ for (String json :
+ Arrays.asList("private-secret", "{\"rowCount\":1,\"rowCount\":2}", "{} {}")) {
+ IOException error =
+ Assertions.assertThrows(
+ IOException.class,
+ () ->
+ new GoogleAnalytics4Report(config())
+ .parse(json.getBytes(StandardCharsets.UTF_8), 0));
+ Assertions.assertNull(error.getCause());
+ Assertions.assertFalse(error.getMessage().contains("private-secret"));
+ }
+ }
+
+ @Test
+ void comparesUnicodeCodePoints() {
+ Assertions.assertTrue(
+ GoogleAnalytics4Report.compare(
+ Collections.singletonList("a"), Collections.singletonList("ab"))
+ < 0);
+ Assertions.assertTrue(
+ GoogleAnalytics4Report.compare(
+ Collections.singletonList("ab"), Collections.singletonList("a"))
+ > 0);
+ Assertions.assertEquals(
+ 0,
+ GoogleAnalytics4Report.compare(
+ Collections.singletonList(""), Collections.singletonList("")));
+ Assertions.assertTrue(
+ GoogleAnalytics4Report.compare(
+ Collections.singletonList("\uE000"),
+ Collections.singletonList("\uD800\uDC00"))
+ < 0);
+ }
+
+ @Test
+ void validatesOptionsBeforeIo() {
+ invalid("property_id", "../123", "property_id");
+ invalid("start_date", "today", "dates");
+ invalid("start_date", "2024-02-30", "calendar");
+ invalid("end_date", "2023-01-01", "start_date");
+ invalid("dimensions", Arrays.asList("country", "country"), "unique");
+ invalid("metrics", Collections.singletonList("country"), "overlap");
+ invalid("metric_types", Arrays.asList("TYPE_INTEGER", "UNKNOWN"), "metric_types");
+ invalid("page_size", 0, "page_size");
+ invalid("max_report_rows", 0, "max_report_rows");
+ invalid("max_response_bytes", 16777217, "max_response_bytes");
+ invalid("max_retries", 6, "max_retries");
+ invalid("request_timeout_ms", 0, "request_timeout_ms");
+ invalid("emulator_url", "http://user:secret@localhost", "emulator_url");
+ invalid("emulator_url", "http://analyticsdata.googleapis.com", "emulator_url");
+ invalid("service_account_key_file", "/not/read", "exactly one");
+ invalid(
+ "schema",
+ Collections.singletonMap("fields", Collections.singletonMap("country", "string")),
+ "schema");
+ }
+
+ @Test
+ void factorySpiOptionRuleAndSourceSerialization() throws Exception {
+ GoogleAnalytics4SourceFactory factory = new GoogleAnalytics4SourceFactory();
+ ConfigValidator.of(ReadonlyConfig.fromMap(options())).validate(factory.optionRule());
+ Map<String, Object> missingAuth = options();
+ missingAuth.remove("emulator_url");
+ Assertions.assertThrows(
+ Exception.class,
+ () ->
+ ConfigValidator.of(ReadonlyConfig.fromMap(missingAuth))
+ .validate(factory.optionRule()));
+ boolean found = false;
+ for (Factory candidate : ServiceLoader.load(Factory.class)) {
+ found |= candidate instanceof GoogleAnalytics4SourceFactory;
+ }
+ Assertions.assertTrue(found);
+ GoogleAnalytics4Source source =
+ new GoogleAnalytics4Source(ReadonlyConfig.fromMap(options()));
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
+ out.writeObject(source);
+ }
+ try (ObjectInputStream in =
+ new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
+ GoogleAnalytics4Source restored = (GoogleAnalytics4Source) in.readObject();
+ Assertions.assertEquals(
+ source.getProducedCatalogTables().get(0).getSeaTunnelRowType(),
+ restored.getProducedCatalogTables().get(0).getSeaTunnelRowType());
+ }
+ }
+
+ private void invalid(String key, Object value, String message) {
+ Map<String, Object> options = options();
+ options.put(key, value);
+ IllegalArgumentException failure =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new GoogleAnalytics4Config(ReadonlyConfig.fromMap(options)));
+ Assertions.assertTrue(failure.getMessage().contains(message), failure.getMessage());
+ }
+
+ private void assertBad(ObjectNode response, String message) {
+ IOException error =
+ Assertions.assertThrows(
+ IOException.class,
+ () -> new GoogleAnalytics4Report(config()).parse(bytes(response), 0));
+ Assertions.assertTrue(error.getMessage().contains(message), error.getMessage());
+ Assertions.assertNull(error.getCause());
+ Assertions.assertFalse(error.getMessage().contains("private-report-detail"));
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReaderTest.java b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReaderTest.java
new file mode 100644
index 0000000000..f5d5d5717a
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/GoogleAnalytics4SourceReaderTest.java
@@ -0,0 +1,490 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.source.SourceReader;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.JSON;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.bytes;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.options;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.page;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class GoogleAnalytics4SourceReaderTest {
+ private HttpServer server;
+ private GoogleAnalytics4SourceReader reader;
+ private final SourceReader.Context context = mock(SourceReader.Context.class);
+ private final List<SeaTunnelRow> rows = new ArrayList<>();
+ private final AtomicReference<Throwable> serverFailure = new AtomicReference<>();
+ private ExecutorService executor;
+ private String origin;
+ @TempDir Path temp;
+
+ @AfterEach
+ void close() throws Exception {
+ if (reader != null) {
+ reader.close();
+ }
+ if (server != null) {
+ server.stop(0);
+ }
+ if (executor != null) {
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ if (serverFailure.get() != null) {
+ throw new AssertionError("Mock HTTP contract failed", serverFailure.get());
+ }
+ }
+
+ private void start(Handler handler) throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ try {
+ handler.handle(exchange);
+ } catch (Throwable e) {
+ serverFailure.set(e);
+ } finally {
+ exchange.close();
+ }
+ });
+ server.start();
+ origin = "http://127.0.0.1:" + server.getAddress().getPort();
+ }
+
+ private interface Handler {
+ void handle(HttpExchange exchange) throws Exception;
+ }
+
+ private GoogleAnalytics4Config configure(Map<String, Object> values) throws IOException {
+ values.put("emulator_url", origin);
+ GoogleAnalytics4Config config = new GoogleAnalytics4Config(ReadonlyConfig.fromMap(values));
+ reader = new GoogleAnalytics4SourceReader(config, new SingleSplitReaderContext(context));
+ reader.open();
+ return config;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Collector<SeaTunnelRow> collector() {
+ Collector<SeaTunnelRow> collector = mock(Collector.class);
+ when(collector.getCheckpointLock()).thenReturn(new Object());
+ doAnswer(
+ invocation -> {
+ rows.add(invocation.getArgument(0));
+ return null;
+ })
+ .when(collector)
+ .collect(any(SeaTunnelRow.class));
+ return collector;
+ }
+
+ private void reply(HttpExchange exchange, int status, byte[] body) throws IOException {
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, body.length);
+ exchange.getResponseBody().write(body);
+ }
+
+ @Test
+ void followsActualOffsetsAndSignalsCompletionOnlyOnce() throws Exception {
+ List<Integer> offsets = new ArrayList<>();
+ start(
+ exchange -> {
+ Assertions.assertEquals(
+ "/v1beta/properties/123:runReport", exchange.getRequestURI().getPath());
+ Assertions.assertEquals("POST", exchange.getRequestMethod());
+ Assertions.assertNull(exchange.getRequestHeaders().getFirst("Authorization"));
+ JsonNode request = JSON.readTree(exchange.getRequestBody());
+ int offset = request.path("offset").asInt();
+ offsets.add(offset);
+ reply(exchange, 200, bytes(offset == 0 ? page(3, "CA") : page(3, "DE", "US")));
+ });
+ configure(options());
+ Collector<SeaTunnelRow> collector = collector();
+ reader.pollNext(collector);
+ reader.pollNext(collector);
+ Assertions.assertEquals(java.util.Arrays.asList(0, 1), offsets);
+ Assertions.assertEquals(3, rows.size());
+ verify(context, times(1)).signalNoMoreElement();
+ // The common single-split snapshot has no page offset. A new reader replays.
+ Assertions.assertNull(reader.snapshotState(1).get(0).getState());
+ reader.close();
+ configure(options());
+ reader.pollNext(collector());
+ Assertions.assertEquals(java.util.Arrays.asList(0, 1, 0, 1), offsets);
+ }
+
+ @Test
+ void retriesTransientStatusAtSameOffset() throws Exception {
+ AtomicInteger requests = new AtomicInteger();
+ start(
+ exchange -> {
+ JsonNode request = JSON.readTree(exchange.getRequestBody());
+ Assertions.assertEquals("0", request.path("offset").asText());
+ int call = requests.incrementAndGet();
+ reply(
+ exchange,
+ call == 1 ? 503 : 200,
+ call == 1
+ ? "{}".getBytes(StandardCharsets.UTF_8)
+ : bytes(page(1, "CA")));
+ });
+ Map<String, Object> options = options();
+ options.put("max_retries", 1);
+ configure(options);
+ reader.pollNext(collector());
+ Assertions.assertEquals(2, requests.get());
+ Assertions.assertEquals(1, rows.size());
+ }
+
+ @Test
+ void oversizedBodyIsNotRetriedAndDoesNotComplete() throws Exception {
+ AtomicInteger calls = new AtomicInteger();
+ start(
+ exchange -> {
+ calls.incrementAndGet();
+ reply(exchange, 200, new byte[2048]);
+ });
+ Map<String, Object> options = options();
+ options.put("max_response_bytes", 1024);
+ options.put("max_retries", 5);
+ configure(options);
+ IOException error =
+ Assertions.assertThrows(IOException.class, () -> reader.pollNext(collector()));
+ Assertions.assertTrue(error.getMessage().contains("size limit"));
+ Assertions.assertEquals(1, calls.get());
+ verify(context, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void permissionFailureDoesNotRetryOrLeakErrorBody() throws Exception {
+ AtomicInteger calls = new AtomicInteger();
+ start(
+ exchange -> {
+ calls.incrementAndGet();
+ reply(
+ exchange,
+ 403,
+ "{\"error\":\"private-token\"}".getBytes(StandardCharsets.UTF_8));
+ });
+ Map<String, Object> options = options();
+ options.put("max_retries", 5);
+ configure(options);
+ IOException error =
+ Assertions.assertThrows(IOException.class, () -> reader.pollNext(collector()));
+ Assertions.assertTrue(error.getMessage().contains("403"));
+ Assertions.assertFalse(error.getMessage().contains("private-token"));
+ Assertions.assertNull(error.getCause());
+ Assertions.assertEquals(1, calls.get());
+ verify(context, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void laterPageFailureDoesNotSignalSuccessfulPartialReport() throws Exception {
+ start(
+ exchange -> {
+ int offset = JSON.readTree(exchange.getRequestBody()).path("offset").asInt();
+ reply(exchange, 200, bytes(offset == 0 ? page(2, "CA") : page(3, "US")));
+ });
+ configure(options());
+ Assertions.assertThrows(IOException.class, () -> reader.pollNext(collector()));
+ Assertions.assertEquals(1, rows.size());
+ verify(context, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void cancellationWakesRetryWait() throws Exception {
+ CountDownLatch arrived = new CountDownLatch(1);
+ start(
+ exchange -> {
+ exchange.getResponseHeaders().set("Retry-After", "30");
+ reply(exchange, 429, "{}".getBytes(StandardCharsets.UTF_8));
+ arrived.countDown();
+ });
+ Map<String, Object> options = options();
+ options.put("max_retries", 3);
+ configure(options);
+ executor = Executors.newSingleThreadExecutor();
+ AtomicReference<Thread> pollingThread = new AtomicReference<>();
+ Future<?> poll =
+ executor.submit(
+ () -> {
+ pollingThread.set(Thread.currentThread());
+ return Assertions.assertThrows(
+ IOException.class, () -> reader.pollNext(collector()));
+ });
+ Assertions.assertTrue(arrived.await(5, TimeUnit.SECONDS));
+ org.awaitility.Awaitility.await()
+ .atMost(5, TimeUnit.SECONDS)
+ .until(
+ () ->
+ pollingThread.get() != null
+ && pollingThread.get().getState()
+ == Thread.State.TIMED_WAITING
+ && java.util.Arrays.stream(
+ pollingThread.get().getStackTrace())
+ .anyMatch(
+ frame ->
+ frame.getMethodName()
+ .equals("awaitRetry")));
+ reader.close();
+ poll.get(5, TimeUnit.SECONDS);
+ verify(context, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void cancellationAbortsActiveResponse() throws Exception {
+ CountDownLatch arrived = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ start(
+ exchange -> {
+ exchange.sendResponseHeaders(200, 0);
+ exchange.getResponseBody().write('{');
+ exchange.getResponseBody().flush();
+ arrived.countDown();
+ try {
+ release.await(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ configure(options());
+ executor = Executors.newSingleThreadExecutor();
+ Future<?> poll =
+ executor.submit(
+ () ->
+ Assertions.assertThrows(
+ IOException.class, () -> reader.pollNext(collector())));
+ try {
+ Assertions.assertTrue(arrived.await(5, TimeUnit.SECONDS));
+ reader.close();
+ poll.get(5, TimeUnit.SECONDS);
+ } finally {
+ release.countDown();
+ }
+ verify(context, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void retryAfterIsBoundedAndHttpDateIsHonored() throws Exception {
+ Assertions.assertEquals(3000, GoogleAnalytics4SourceReader.retryDelay("3", 1000, 5000, 0));
+ Assertions.assertEquals(
+ 3000,
+ GoogleAnalytics4SourceReader.retryDelay(
+ "Thu, 01 Jan 1970 00:00:03 GMT", 1000, 5000, 0));
+ for (String value :
+ java.util.Arrays.asList("3600", "999999999999999999999", "private-invalid")) {
+ IOException error =
+ Assertions.assertThrows(
+ IOException.class,
+ () -> GoogleAnalytics4SourceReader.retryDelay(value, 1000, 30000, 0));
+ Assertions.assertFalse(error.getMessage().contains(value));
+ }
+ }
+
+ @Test
+ void invalidCredentialFileFailsLocallyAndRedacts() throws Exception {
+ Path file = temp.resolve("key.json");
+ Files.write(file, "{\"private_key\":\"secret-key\"}".getBytes(StandardCharsets.UTF_8));
+ Map<String, Object> options = options();
+ options.remove("emulator_url");
+ options.put("service_account_key_file", file.toString());
+ reader =
+ new GoogleAnalytics4SourceReader(
+ new GoogleAnalytics4Config(ReadonlyConfig.fromMap(options)),
+ new SingleSplitReaderContext(context));
+ IOException error = Assertions.assertThrows(IOException.class, reader::open);
+ Assertions.assertNull(error.getCause());
+ Assertions.assertFalse(error.getMessage().contains(file.toString()));
+ Assertions.assertFalse(error.getMessage().contains("secret-key"));
+ Assertions.assertThrows(IOException.class, reader::open);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void realServiceAccountRefreshesAfter401OrExpiryAndRedactsOAuthFailure(boolean unauthorized)
+ throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ KeyPair key = generator.generateKeyPair();
+ AtomicInteger tokens = new AtomicInteger();
+ AtomicInteger reports = new AtomicInteger();
+ start(
+ exchange -> {
+ if ("/token".equals(exchange.getRequestURI().getPath())) {
+ String form =
+ new String(
+ GoogleAnalytics4HttpTransport.readBounded(
+ exchange.getRequestBody(), 65536),
+ StandardCharsets.UTF_8);
+ String assertion = null;
+ for (String pair : form.split("&")) {
+ if (pair.startsWith("assertion=")) {
+ assertion =
+ URLDecoder.decode(
+ pair.substring("assertion=".length()), "UTF-8");
+ }
+ }
+ Assertions.assertNotNull(assertion);
+ String[] parts = assertion.split("\\.");
+ Signature verifier = Signature.getInstance("SHA256withRSA");
+ verifier.initVerify(key.getPublic());
+ verifier.update(
+ (parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII));
+ Assertions.assertTrue(
+ verifier.verify(Base64.getUrlDecoder().decode(parts[2])));
+ JsonNode claims = JSON.readTree(Base64.getUrlDecoder().decode(parts[1]));
+ Assertions.assertEquals(
+ "https://www.googleapis.com/auth/analytics.readonly",
+ claims.path("scope").asText());
+ Assertions.assertEquals(
+ "https://oauth2.googleapis.com/token", claims.path("aud").asText());
+ int count = tokens.incrementAndGet();
+ reply(
+ exchange,
+ count < 3 ? 200 : 400,
+ (count < 3
+ ? "{\"access_token\":\"token-"
+ + count
+ + "\",\"expires_in\":"
+ + (unauthorized ? 3600 : 1)
+ + ",\"token_type\":\"Bearer\"}"
+ : "{\"error\":\"invalid_grant\",\"error_description\":\"private-secret\"}")
+ .getBytes(StandardCharsets.UTF_8));
+ } else {
+ int call = reports.incrementAndGet();
+ Assertions.assertEquals(
+ "Bearer token-" + (call == 1 ? 1 : 2),
+ exchange.getRequestHeaders().getFirst("Authorization"));
+ reply(
+ exchange,
+ call == 1 && unauthorized ? 401 : 200,
+ call == 1 && unauthorized
+ ? "{}".getBytes(StandardCharsets.UTF_8)
+ : bytes(
+ unauthorized
+ ? page(1, "CA")
+ : page(2, call == 1 ? "CA" : "US")));
+ }
+ });
+ Path file = temp.resolve("service-account.json");
+ org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode json =
+ JSON.createObjectNode()
+ .put("type", "service_account")
+ .put("project_id", "fixture")
+ .put("client_id", "123")
+ .put("client_email", "fixture@example.iam.gserviceaccount.com")
+ .put("private_key_id", "fixture-key")
+ .put(
+ "private_key",
+ "-----BEGIN PRIVATE KEY-----\n"
+ + Base64.getEncoder()
+ .encodeToString(key.getPrivate().getEncoded())
+ + "\n-----END PRIVATE KEY-----\n")
+ .put("token_uri", "https://oauth2.googleapis.com/token");
+ Files.write(file, bytes(json));
+ Map<String, Object> values = options();
+ values.remove("emulator_url");
+ values.put("service_account_key_file", file.toString());
+ GoogleAnalytics4Config config = new GoogleAnalytics4Config(ReadonlyConfig.fromMap(values));
+ // Only reroute the HTTP destination. Production key parsing, endpoint validation,
+ // JWT signing, LowLevelHttpRequest/Response adapter and token refresh all execute.
+ reader =
+ new GoogleAnalytics4SourceReader(
+ config, new SingleSplitReaderContext(context), fixtureTransport(config));
+ reader.open();
+ reader.pollNext(collector());
+ Assertions.assertEquals(2, tokens.get());
+ Assertions.assertEquals(2, reports.get());
+ Assertions.assertEquals(unauthorized ? 1 : 2, rows.size());
+ reader.close();
+ reader =
+ new GoogleAnalytics4SourceReader(
+ config, new SingleSplitReaderContext(context), fixtureTransport(config));
+ reader.open();
+ IOException redacted =
+ Assertions.assertThrows(IOException.class, () -> reader.pollNext(collector()));
+ Assertions.assertFalse(redacted.getMessage().contains("private-secret"));
+ Assertions.assertNull(redacted.getCause());
+ Assertions.assertEquals(3, tokens.get());
+ reader.close();
+ json.put("token_uri", "http://private-secret.invalid/token");
+ Files.write(file, bytes(json));
+ reader = new GoogleAnalytics4SourceReader(config, new SingleSplitReaderContext(context));
+ IOException invalidUri = Assertions.assertThrows(IOException.class, reader::open);
+ Assertions.assertFalse(invalidUri.getMessage().contains("private-secret"));
+ Assertions.assertNull(invalidUri.getCause());
+ }
+
+ private GoogleAnalytics4HttpTransport fixtureTransport(GoogleAnalytics4Config config) {
+ return new GoogleAnalytics4HttpTransport(config) {
+ @Override
+ Response post(String url, byte[] body, String token, int limit) throws IOException {
+ Assertions.assertTrue(
+ url.equals("https://oauth2.googleapis.com/token")
+ || url.equals(
+ "https://analyticsdata.googleapis.com/v1beta/properties/123:runReport"));
+ return super.post(origin + java.net.URI.create(url).getPath(), body, token, limit);
+ }
+ };
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/TestGoogleAnalytics4PackagingIT.java b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/TestGoogleAnalytics4PackagingIT.java
new file mode 100644
index 0000000000..ddd9415a8d
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-google-analytics4/src/test/java/org/apache/seatunnel/connectors/seatunnel/google/analytics4/TestGoogleAnalytics4PackagingIT.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.google.analytics4;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.factory.TableSourceFactory;
+import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import com.sun.net.httpserver.HttpServer;
+
+import java.io.ByteArrayInputStream;
+import java.io.Closeable;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.net.InetSocketAddress;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.JSON;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.bytes;
+import static org.apache.seatunnel.connectors.seatunnel.google.analytics4.GoogleAnalytics4ReportTest.options;
+
+/**
+ * Runs after shade, without permitting parent-classloader fallback for connector/private classes.
+ */
+class TestGoogleAnalytics4PackagingIT {
+ @Test
+ void shadedArtifactLoadsFactoryOAuthAndBoundedHttp() throws Exception {
+ Path artifact = Paths.get(System.getProperty("ga4.jar"));
+ String own = "org.apache.seatunnel.connectors.seatunnel.google.analytics4.";
+ String shaded = "org.apache.seatunnel.shade.google.analytics4.";
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/token",
+ exchange -> {
+ try {
+ String request =
+ new String(
+ GoogleAnalytics4HttpTransport.readBounded(
+ exchange.getRequestBody(), 65536),
+ StandardCharsets.UTF_8);
+ Assertions.assertTrue(request.contains("assertion="));
+ byte[] body =
+ "{\"access_token\":\"packaged-token\",\"token_type\":\"Bearer\",\"expires_in\":3600}"
+ .getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(200, body.length);
+ exchange.getResponseBody().write(body);
+ } catch (Throwable e) {
+ failure.set(e);
+ } finally {
+ exchange.close();
+ }
+ });
+ server.createContext(
+ "/report",
+ exchange -> {
+ try {
+ Assertions.assertEquals(
+ "Bearer packaged-token",
+ exchange.getRequestHeaders().getFirst("Authorization"));
+ byte[] body = "{}".getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(200, body.length);
+ exchange.getResponseBody().write(body);
+ } catch (Throwable e) {
+ failure.set(e);
+ } finally {
+ exchange.close();
+ }
+ });
+ server.start();
+ String origin = "http://127.0.0.1:" + server.getAddress().getPort();
+ try (URLClassLoader loader =
+ new URLClassLoader(
+ new URL[] {artifact.toUri().toURL()}, getClass().getClassLoader()) {
+ @Override
+ protected Class<?> loadClass(String name, boolean resolve)
+ throws ClassNotFoundException {
+ if (!name.startsWith(own) && !name.startsWith(shaded)) {
+ return super.loadClass(name, resolve);
+ }
+ synchronized (getClassLoadingLock(name)) {
+ Class<?> type = findLoadedClass(name);
+ if (type == null) {
+ type = findClass(name);
+ }
+ if (resolve) {
+ resolveClass(type);
+ }
+ return type;
+ }
+ }
+ }) {
+ Class<?> credentialType =
+ loader.loadClass(shaded + "com.google.auth.oauth2.ServiceAccountCredentials");
+ Assertions.assertEquals(
+ artifact.toUri().toURL(),
+ credentialType.getProtectionDomain().getCodeSource().getLocation());
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ KeyPair key = generator.generateKeyPair();
+ ObjectNode json =
+ JSON.createObjectNode()
+ .put("type", "service_account")
+ .put("client_id", "123")
+ .put("client_email", "fixture@example.iam.gserviceaccount.com")
+ .put("private_key_id", "fixture-key")
+ .put("project_id", "fixture")
+ .put(
+ "private_key",
+ "-----BEGIN PRIVATE KEY-----\n"
+ + Base64.getEncoder()
+ .encodeToString(key.getPrivate().getEncoded())
+ + "\n-----END PRIVATE KEY-----\n")
+ .put("token_uri", origin + "/token");
+ Object credential =
+ credentialType
+ .getMethod("fromStream", java.io.InputStream.class)
+ .invoke(null, new ByteArrayInputStream(bytes(json)));
+ credential =
+ credentialType
+ .getMethod("createScoped", java.util.Collection.class)
+ .invoke(
+ credential,
+ Collections.singleton(
+ "https://www.googleapis.com/auth/analytics.readonly"));
+ credentialType.getMethod("refresh").invoke(credential);
+ Object token = credentialType.getMethod("getAccessToken").invoke(credential);
+ Assertions.assertEquals(
+ "packaged-token", token.getClass().getMethod("getTokenValue").invoke(token));
+
+ Map<String, Object> options = options();
+ options.put("emulator_url", origin);
+ TableSourceFactory factory =
+ (TableSourceFactory)
+ loader.loadClass(own + "GoogleAnalytics4SourceFactory")
+ .getConstructor()
+ .newInstance();
+ Assertions.assertEquals("GoogleAnalytics4", factory.factoryIdentifier());
+ Assertions.assertEquals(
+ "GoogleAnalytics4",
+ factory.createSource(
+ new TableSourceFactoryContext(
+ ReadonlyConfig.fromMap(options), loader))
+ .createSource()
+ .getPluginName());
+
+ Class<?> configType = loader.loadClass(own + "GoogleAnalytics4Config");
+ Constructor<?> configConstructor =
+ configType.getDeclaredConstructor(ReadonlyConfig.class);
+ configConstructor.setAccessible(true);
+ Object config = configConstructor.newInstance(ReadonlyConfig.fromMap(options));
+ Class<?> transportType = loader.loadClass(own + "GoogleAnalytics4HttpTransport");
+ Constructor<?> transportConstructor = transportType.getDeclaredConstructor(configType);
+ transportConstructor.setAccessible(true);
+ try (Closeable transport = (Closeable) transportConstructor.newInstance(config)) {
+ Method report =
+ transportType.getDeclaredMethod(
+ "report", String.class, byte[].class, String.class);
+ report.setAccessible(true);
+ Object response =
+ report.invoke(
+ transport,
+ origin + "/report",
+ "{}".getBytes(StandardCharsets.UTF_8),
+ "packaged-token");
+ java.lang.reflect.Field status = response.getClass().getDeclaredField("status");
+ status.setAccessible(true);
+ Assertions.assertEquals(200, status.getInt(response));
+ }
+ } finally {
+ server.stop(0);
+ }
+ if (failure.get() != null) {
+ throw new AssertionError("Packaged fixture failed", failure.get());
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/pom.xml b/seatunnel-connectors-v2/pom.xml
index eb3a305e12..18640cb0b7 100644
--- a/seatunnel-connectors-v2/pom.xml
+++ b/seatunnel-connectors-v2/pom.xml
@@ -75,6 +75,7 @@
<module>connector-google-firestore</module>
<module>connector-google-pubsub</module>
<module>connector-google-ads</module>
+ <module>connector-google-analytics4</module>
<module>connector-facebook-ads</module>
<module>connector-tiktok-ads</module>
<module>connector-azure-queue-storage</module>
diff --git a/seatunnel-dist/pom.xml b/seatunnel-dist/pom.xml
index 38a5d8a29a..13787f09cc 100644
--- a/seatunnel-dist/pom.xml
+++ b/seatunnel-dist/pom.xml
@@ -566,6 +566,12 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-google-analytics4</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.seatunnel</groupId>
<artifactId>connector-facebook-ads</artifactId>
diff --git a/seatunnel-dist/release-docs/LICENSE b/seatunnel-dist/release-docs/LICENSE
index 822d334be8..343be5ef4e 100644
--- a/seatunnel-dist/release-docs/LICENSE
+++ b/seatunnel-dist/release-docs/LICENSE
@@ -452,3 +452,31 @@ The following components are provided under the Public Domain License. See proje
The text of each license is also included at licenses/LICENSE-[project].txt.
(Public Domain) XZ for Java (org.tukaani:xz:1.5 - http://tukaani.org/xz/java.html)
+
+========================================================================
+Google Analytics 4 connector dependencies
+========================================================================
+
+The Google Analytics 4 connector also bundles these components:
+
+ (BSD-3-Clause) Google Auth Library (com.google.auth:google-auth-library-oauth2-http:1.40.0 and com.google.auth:google-auth-library-credentials:1.40.0 - https://github.com/googleapis/google-auth-library-java)
+ See licenses/LICENSE-google-auth.txt.
+ (BSD-3-Clause) Google API Common (com.google.api:api-common:2.53.0 - https://github.com/googleapis/api-common-java)
+ See licenses/LICENSE-google-api-common.txt.
+ (Apache-2.0) auto-value-annotations (com.google.auto.value:auto-value-annotations:1.11.0 - https://github.com/google/auto)
+ (Apache-2.0) google-http-client (com.google.http-client:google-http-client:2.0.2 - https://github.com/googleapis/google-http-java-client)
+ (Apache-2.0) grpc-context (io.grpc:grpc-context:1.70.0 - https://github.com/grpc/grpc-java)
+ (Apache-2.0) grpc-api (io.grpc:grpc-api:1.70.0 - https://github.com/grpc/grpc-java)
+ (Apache-2.0) opencensus-api (io.opencensus:opencensus-api:0.31.1 - https://github.com/census-instrumentation/opencensus-java)
+ (Apache-2.0) opencensus-contrib-http-util (io.opencensus:opencensus-contrib-http-util:0.31.1 - https://github.com/census-instrumentation/opencensus-java)
+ (Apache-2.0) google-http-client-gson (com.google.http-client:google-http-client-gson:2.0.2 - https://github.com/googleapis/google-http-java-client)
+ (Apache-2.0) error_prone_annotations (com.google.errorprone:error_prone_annotations:2.38.0 - https://github.com/google/error-prone)
+ (Apache-2.0) gson (com.google.code.gson:gson:2.12.1 - https://github.com/google/gson)
+ (Apache-2.0) guava (com.google.guava:guava:33.5.0-android - https://github.com/google/guava)
+ (Apache-2.0) failureaccess (com.google.guava:failureaccess:1.0.3 - https://github.com/google/guava)
+ (Apache-2.0) jspecify (org.jspecify:jspecify:1.0.0 - https://github.com/jspecify/jspecify)
+ (Apache-2.0) j2objc-annotations (com.google.j2objc:j2objc-annotations:3.1 - https://github.com/google/j2objc)
+ (Apache-2.0) httpcore (org.apache.httpcomponents:httpcore:4.4.13 - https://hc.apache.org/)
+
+The existing CDDL entry for javax.annotation:javax.annotation-api:1.3.2 applies
+to this connector as well. Its license is retained in the connector JAR.
diff --git a/seatunnel-dist/release-docs/licenses/LICENSE-google-api-common.txt b/seatunnel-dist/release-docs/licenses/LICENSE-google-api-common.txt
new file mode 100644
index 0000000000..7fea74e476
--- /dev/null
+++ b/seatunnel-dist/release-docs/licenses/LICENSE-google-api-common.txt
@@ -0,0 +1,26 @@
+Copyright 2016, Google Inc.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/seatunnel-dist/release-docs/licenses/LICENSE-google-auth.txt b/seatunnel-dist/release-docs/licenses/LICENSE-google-auth.txt
new file mode 100644
index 0000000000..12edf23c67
--- /dev/null
+++ b/seatunnel-dist/release-docs/licenses/LICENSE-google-auth.txt
@@ -0,0 +1,28 @@
+Copyright 2014, Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/pom.xml b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/pom.xml
new file mode 100644
index 0000000000..48d4ae5a66
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/pom.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>seatunnel-connector-v2-e2e</artifactId>
+ <version>${revision}</version>
+ </parent>
+ <artifactId>connector-google-analytics4-e2e</artifactId>
+ <name>SeaTunnel : E2E : Connector V2 : Google Analytics 4</name>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-google-analytics4</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-assert</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mock-server</groupId>
+ <artifactId>mockserver-netty-no-dependencies</artifactId>
+ <version>5.14.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/java/org/apache/seatunnel/e2e/connector/google/analytics4/GoogleAnalytics4IT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/java/org/apache/seatunnel/e2e/connector/google/analytics4/GoogleAnalytics4IT.java
new file mode 100644
index 0000000000..c100d1c658
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/java/org/apache/seatunnel/e2e/connector/google/analytics4/GoogleAnalytics4IT.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.e2e.connector.google.analytics4;
+
+import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.TestSuiteBase;
+import org.apache.seatunnel.e2e.common.container.TestContainer;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.TestTemplate;
+import org.mockserver.client.MockServerClient;
+import org.mockserver.model.HttpRequest;
+import org.mockserver.model.HttpResponse;
+import org.mockserver.model.JsonBody;
+import org.mockserver.verify.VerificationTimes;
+import org.testcontainers.containers.Container;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.wait.strategy.Wait;
+import org.testcontainers.utility.DockerImageName;
+
+public class GoogleAnalytics4IT extends TestSuiteBase implements TestResource {
+ private GenericContainer<?> fixture;
+ private MockServerClient client;
+
+ @BeforeAll
+ @Override
+ public void startUp() {
+ fixture =
+ new GenericContainer<>(DockerImageName.parse("mockserver/mockserver:5.14.0"))
+ .withNetwork(NETWORK)
+ .withNetworkAliases("ga4-fixture")
+ .withExposedPorts(1080)
+ .withEnv("MOCKSERVER_LOG_LEVEL", "WARN")
+ .waitingFor(Wait.forHttp("/").forStatusCode(404));
+ fixture.start();
+ client = new MockServerClient(fixture.getHost(), fixture.getMappedPort(1080));
+ }
+
+ @AfterAll
+ @Override
+ public void tearDown() {
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } finally {
+ try {
+ if (fixture != null) {
+ fixture.stop();
+ }
+ } finally {
+ // Engine callbacks finish before this single-class module's fixture teardown.
+ NETWORK.close();
+ }
+ }
+ }
+
+ @TestTemplate
+ void readsTypedPaginatedReport(TestContainer container) throws Exception {
+ client.reset();
+ HttpRequest first = request("0");
+ HttpRequest last = request("2");
+ client.when(first)
+ .respond(
+ HttpResponse.response()
+ .withHeader("Content-Type", "application/json")
+ .withBody(
+ report(
+ row("CA", "10", "1.25")
+ + ","
+ + row("DE", "20", "2.50"))));
+ client.when(last)
+ .respond(
+ HttpResponse.response()
+ .withHeader("Content-Type", "application/json")
+ .withBody(report(row("US", "30", "3.75"))));
+ Container.ExecResult result = container.executeJob("/google_analytics4_to_assert.conf");
+ Assertions.assertEquals(0, result.getExitCode(), result.getStderr());
+ client.verify(first, VerificationTimes.exactly(1));
+ client.verify(last, VerificationTimes.exactly(1));
+ }
+
+ private HttpRequest request(String offset) {
+ return HttpRequest.request()
+ .withMethod("POST")
+ .withPath("/v1beta/properties/123:runReport")
+ .withBody(
+ JsonBody.json(
+ "{\"dimensions\":[{\"name\":\"country\"}],"
+ + "\"metrics\":[{\"name\":\"activeUsers\"},{\"name\":\"purchaseRevenue\"}],"
+ + "\"dateRanges\":[{\"startDate\":\"2024-01-01\",\"endDate\":\"2024-01-31\"}],"
+ + "\"orderBys\":[{\"dimension\":{\"dimensionName\":\"country\",\"orderType\":\"ALPHANUMERIC\"}}],"
+ + "\"offset\":\""
+ + offset
+ + "\",\"limit\":\"2\",\"returnPropertyQuota\":true,\"keepEmptyRows\":true}"));
+ }
+
+ private String report(String rows) {
+ return "{\"dimensionHeaders\":[{\"name\":\"country\"}],"
+ + "\"metricHeaders\":[{\"name\":\"activeUsers\",\"type\":\"TYPE_INTEGER\"},"
+ + "{\"name\":\"purchaseRevenue\",\"type\":\"TYPE_CURRENCY\"}],"
+ + "\"rowCount\":3,\"rows\":["
+ + rows
+ + "],"
+ + "\"metadata\":{\"currencyCode\":\"USD\",\"timeZone\":\"UTC\"}}";
+ }
+
+ private String row(String country, String users, String revenue) {
+ return "{\"dimensionValues\":[{\"value\":\""
+ + country
+ + "\"}],"
+ + "\"metricValues\":[{\"value\":\""
+ + users
+ + "\"},{\"value\":\""
+ + revenue
+ + "\"}]}";
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/resources/google_analytics4_to_assert.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/resources/google_analytics4_to_assert.conf
new file mode 100644
index 0000000000..7d32f9da86
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-google-analytics4-e2e/src/test/resources/google_analytics4_to_assert.conf
@@ -0,0 +1,55 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+source {
+ GoogleAnalytics4 {
+ property_id = "123"
+ emulator_url = "http://ga4-fixture:1080"
+ start_date = "2024-01-01"
+ end_date = "2024-01-31"
+ dimensions = ["country"]
+ metrics = ["activeUsers", "purchaseRevenue"]
+ metric_types = ["TYPE_INTEGER", "TYPE_CURRENCY"]
+ page_size = 2
+ schema {
+ fields {
+ country = string
+ activeUsers = bigint
+ purchaseRevenue = double
+ }
+ }
+ }
+}
+sink {
+ Assert {
+ rules {
+ row_rules = [
+ { rule_type = MIN_ROW, rule_value = 3 },
+ { rule_type = MAX_ROW, rule_value = 3 }
+ ]
+ field_rules = [
+ { field_name = country, field_type = string, field_value = [{ rule_type = NOT_NULL }] },
+ { field_name = activeUsers, field_type = bigint, field_value = [{ rule_type = NOT_NULL }] },
+ { field_name = purchaseRevenue, field_type = double, field_value = [{ rule_type = NOT_NULL }] }
+ ]
+ }
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml b/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
index 84b7f3fba7..2341cbe852 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
@@ -74,6 +74,7 @@
<module>connector-druid-e2e</module>
<module>connector-google-firestore-e2e</module>
<module>connector-google-pubsub-e2e</module>
+ <module>connector-google-analytics4-e2e</module>
<module>connector-snmp-e2e</module>
<module>connector-azure-queue-storage-e2e</module>
<module>connector-rocketmq-e2e</module>
diff --git a/seatunnel-examples/seatunnel-engine-examples/src/main/resources/examples/google_analytics4_to_console.conf b/seatunnel-examples/seatunnel-engine-examples/src/main/resources/examples/google_analytics4_to_console.conf
new file mode 100644
index 0000000000..3ed6c8410b
--- /dev/null
+++ b/seatunnel-examples/seatunnel-engine-examples/src/main/resources/examples/google_analytics4_to_console.conf
@@ -0,0 +1,43 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+source {
+ GoogleAnalytics4 {
+ property_id = "123456789"
+ service_account_key_file = "/run/secrets/ga4-service-account.json"
+ start_date = "2024-01-01"
+ end_date = "2024-01-31"
+ dimensions = ["country"]
+ metrics = ["activeUsers", "purchaseRevenue"]
+ metric_types = ["TYPE_INTEGER", "TYPE_CURRENCY"]
+ page_size = 2
+ schema {
+ fields {
+ country = string
+ activeUsers = bigint
+ purchaseRevenue = double
+ }
+ }
+ }
+}
+sink {
+ Console {}
+}