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/01 08:34:33 UTC
(seatunnel) 01/01: [Feature][Connector-V2] Add Firebase Realtime Database source connector (#11637)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-11637-0e1d7f09c5e51fc4909281cfaa081cf71b970715
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit f20479bb37b8472d6bc0b03f42a77b8c0d9465f2
Author: Kareemingit <ka...@gmail.com>
AuthorDate: Tue Sep 1 08:34:09 2026 +0000
[Feature][Connector-V2] Add Firebase Realtime Database source connector (#11637)
---
.github/workflows/labeler/label-scope-conf.yml | 5 +
config/plugin_config | 1 +
docs/en/connectors/changelog/connector-firebase.md | 7 +
docs/en/connectors/source/Firebase.md | 101 +++++
docs/zh/connectors/changelog/connector-firebase.md | 7 +
docs/zh/connectors/source/Firebase.md | 101 +++++
plugin-mapping.properties | 1 +
seatunnel-connectors-v2/connector-firebase/pom.xml | 77 ++++
.../firebase/client/FirebaseHttpClient.java | 303 +++++++++++++++
.../firebase/config/FirebaseSourceOptions.java | 66 ++++
.../seatunnel/firebase/source/FirebaseSource.java | 86 +++++
.../firebase/source/FirebaseSourceFactory.java | 71 ++++
.../firebase/source/FirebaseSourceReader.java | 273 +++++++++++++
.../firebase/source/FirebaseSourceSplit.java | 55 +++
.../source/FirebaseSourceSplitEnumerator.java | 234 ++++++++++++
.../source/FirebaseSourceSplitSerializer.java | 62 +++
.../firebase/source/FirebaseSourceState.java | 37 ++
.../source/FirebaseSourceStateSerializer.java | 83 ++++
.../firebase/client/FirebaseHttpClientTest.java | 161 ++++++++
.../source/FirebaseDataDeserializerTest.java | 85 +++++
.../firebase/source/FirebaseSourceReaderTest.java | 425 +++++++++++++++++++++
.../source/FirebaseSourceSplitEnumeratorTest.java | 309 +++++++++++++++
seatunnel-connectors-v2/pom.xml | 1 +
seatunnel-dist/pom.xml | 6 +
.../connector-firebase-e2e/pom.xml | 67 ++++
.../e2e/connector/firebase/FirebaseSourceIT.java | 178 +++++++++
.../test/resources/firebase_source_to_assert.conf | 103 +++++
seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml | 1 +
28 files changed, 2906 insertions(+)
diff --git a/.github/workflows/labeler/label-scope-conf.yml b/.github/workflows/labeler/label-scope-conf.yml
index e4cbc53bd3..9fec74b421 100644
--- a/.github/workflows/labeler/label-scope-conf.yml
+++ b/.github/workflows/labeler/label-scope-conf.yml
@@ -402,3 +402,8 @@ nats-jetstream:
- all-globs-to-all-files:
- '!seatunnel-connectors-v2/connector-!(nats-jetstream)/**'
- '!seatunnel-e2e/seatunnel-connector-v2-e2e/connector-!(nats-jetstream)-e2e/**'
+firebase:
+ - all:
+ - changed-files:
+ - any-glob-to-any-file: seatunnel-connectors-v2/connector-firebase/**
+ - all-globs-to-all-files: '!seatunnel-connectors-v2/connector-!(firebase)/**'
diff --git a/config/plugin_config b/config/plugin_config
index 2e85547eda..cec3f3ceff 100644
--- a/config/plugin_config
+++ b/config/plugin_config
@@ -50,6 +50,7 @@ connector-file-sftp
connector-file-obs
connector-file-bos
connector-fluss
+connector-firebase
connector-google-sheets
connector-google-firestore
connector-google-pubsub
diff --git a/docs/en/connectors/changelog/connector-firebase.md b/docs/en/connectors/changelog/connector-firebase.md
new file mode 100644
index 0000000000..f0a1fcbe84
--- /dev/null
+++ b/docs/en/connectors/changelog/connector-firebase.md
@@ -0,0 +1,7 @@
+<details><summary> Change Log </summary>
+
+| Change | Commit | Version |
+| --- | --- | --- |
+|[Feature][Connector-V2] Add Firebase Source Connector| | Unreleased |
+
+</details>
\ No newline at end of file
diff --git a/docs/en/connectors/source/Firebase.md b/docs/en/connectors/source/Firebase.md
new file mode 100644
index 0000000000..8500427fd3
--- /dev/null
+++ b/docs/en/connectors/source/Firebase.md
@@ -0,0 +1,101 @@
+import ChangeLog from '../changelog/connector-firebase.md';
+
+# Firebase
+
+> Firebase Source Connector
+
+## Description
+
+The Firebase Source Connector allows reading data from Google Firebase Realtime Database via its REST API. It supports extracting node structures into SeaTunnel internal rows using defined schema fields.
+
+## Key Features
+
+- [x] Batch
+- [ ] Stream
+- [ ] Exactly-Once
+- [x] Column Projection
+
+---
+
+## Options
+
+| Name | Type | Required | Default | Description |
+| :--- | :--- | :--- | :--- | :--- |
+| `url` | String | Yes | - | The base URL of your Firebase Realtime Database (e.g., `https://<DATABASE_NAME>.firebaseio.com`). |
+| `path` | String | Yes | - | The JSON node path to read from (e.g., `users` or `logs/2026`). |
+| `service_account_path` | String | No | - | Absolute path to the Google Service Account JSON key file for OAuth2 service authentication. |
+| `credentials` | String | No | - | Base64-encoded Service Account JSON credentials content. |
+| `database_secret` | String | No | - | Legacy Firebase database secret key or Web API token. |
+| `timeout_ms` | Integer | No | `10000` | HTTP request timeout in milliseconds. |
+| `query_params` | Map | No | - | Additional REST API query parameters to pass with requests. |
+| `schema` | Config | Yes | - | The target table schema definition mapping JSON keys to SeaTunnel data types. |
+| `common-options` | Config | No | - | Source common options. Refer to [Source Common Options](../common-options/source-common-options.md) for details. |
+
+---
+
+## Data Type Mapping
+
+The Firebase connector converts incoming JSON node structures into SeaTunnel internal data types:
+
+| Firebase / JSON Type | SeaTunnel Data Type |
+| :--- | :--- |
+| `String` | `STRING` |
+| `Number` (Integer) | `INT` / `BIGINT` |
+| `Number` (Floating point) | `FLOAT` / `DOUBLE` |
+| `Boolean` | `BOOLEAN` |
+| `Object` (Nested node) | `ROW` / `MAP` |
+| `Array` | `ARRAY` |
+
+---
+
+## How to Set Up
+
+### 1. Authentication Options
+The connector supports three authentication methods:
+- **`service_account_path`**: Point to a local service account JSON key file downloaded from **Firebase Console > Project Settings > Service accounts**.
+- **`credentials`**: Provide the Base64-encoded content of a service account JSON file (useful for CI/CD or cloud secret injection).
+- **`database_secret`**: Pass a legacy database secret key or Web API token.
+
+### 2. Path & Record Structuring
+- **Collection Path (`path = "users"`):** The connector fetches child node objects (e.g., `user_101`, `user_102`) and emits each child object as an individual row.
+- **Single Record Path (`path = "users/user_101"`):** The connector automatically aggregates child primitive fields (e.g., `name`, `role`) into a single output row matching the schema.
+
+---
+
+## Example
+
+### Reading a Collection Path
+
+```hocon
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ Firebase {
+ url = "https://my-app-default-rtdb.firebaseio.com"
+ path = "users"
+ service_account_path = "/etc/seatunnel/firebase-credentials.json"
+ timeout_ms = 5000
+
+ schema {
+ fields {
+ name = "string"
+ role = "string"
+ }
+ }
+ plugin_output = "firebase_users"
+ }
+}
+
+sink {
+ Console {
+ plugin_input = "firebase_users"
+ }
+}
+```
+
+## Changelog
+
+<ChangeLog />
diff --git a/docs/zh/connectors/changelog/connector-firebase.md b/docs/zh/connectors/changelog/connector-firebase.md
new file mode 100644
index 0000000000..f0a1fcbe84
--- /dev/null
+++ b/docs/zh/connectors/changelog/connector-firebase.md
@@ -0,0 +1,7 @@
+<details><summary> Change Log </summary>
+
+| Change | Commit | Version |
+| --- | --- | --- |
+|[Feature][Connector-V2] Add Firebase Source Connector| | Unreleased |
+
+</details>
\ No newline at end of file
diff --git a/docs/zh/connectors/source/Firebase.md b/docs/zh/connectors/source/Firebase.md
new file mode 100644
index 0000000000..851cd3d92f
--- /dev/null
+++ b/docs/zh/connectors/source/Firebase.md
@@ -0,0 +1,101 @@
+import ChangeLog from '../changelog/connector-firebase.md';
+
+# Firebase
+
+> Firebase Source Connector
+
+## 描述
+
+Firebase Source Connector 支持通过 REST API 从 Google Firebase Realtime Database 读取数据。它支持根据定义的 Schema 字段,将 JSON 节点结构提取并转换为 SeaTunnel 内部数据行。
+
+## 关键特性
+
+- [x] 批处理 (Batch)
+- [ ] 流处理 (Stream)
+- [ ] 精确一次 (Exactly-Once)
+- [x] 列裁剪 (Column Projection)
+
+---
+
+## 参数项
+
+| 参数名称 | 类型 | 是否必填 | 默认值 | 描述 |
+| :--- | :--- | :--- | :--- | :--- |
+| `url` | String | 是 | - | Firebase Realtime Database 的基础 URL(例如:`https://<DATABASE_NAME>.firebaseio.com`)。 |
+| `path` | String | 是 | - | 要读取的 JSON 节点路径(例如:`users` 或 `logs/2026`)。 |
+| `service_account_path` | String | 否 | - | 用于 OAuth2 服务认证的 Google 服务账号 JSON 密钥文件的绝对路径。 |
+| `credentials` | String | 否 | - | Base64 编码后的服务账号 JSON 密钥文件内容。 |
+| `database_secret` | String | 否 | - | 遗留的 Firebase 数据库密钥(Database Secret)或 Web API Token。 |
+| `timeout_ms` | Integer | 否 | `10000` | HTTP 请求超时时间(毫秒)。 |
+| `query_params` | Map | 否 | - | 随请求传递的附加 REST API 查询参数。 |
+| `schema` | Config | 是 | - | 目标表 Schema 定义,将 JSON 键映射为 SeaTunnel 数据类型。 |
+| `common-options` | Config | 否 | - | Source 端通用参数,详情请参考 [Source 通用参数](../common-options/source-common-options.md)。 |
+
+---
+
+## 数据类型映射
+
+Firebase 连接器将传入的 JSON 节点结构转换为 SeaTunnel 内部数据类型:
+
+| Firebase / JSON 类型 | SeaTunnel 数据类型 |
+| :--- | :--- |
+| `String` | `STRING` |
+| `Number` (整数) | `INT` / `BIGINT` |
+| `Number` (浮点数) | `FLOAT` / `DOUBLE` |
+| `Boolean` | `BOOLEAN` |
+| `Object` (嵌套节点) | `ROW` / `MAP` |
+| `Array` | `ARRAY` |
+
+---
+
+## 如何配置
+
+### 1. 认证方式
+连接器支持三种认证方式:
+- **`service_account_path`**:指向从 **Firebase 控制台 > 项目设置 > 服务账号** 下载的本地服务账号 JSON 密钥文件。
+- **`credentials`**:提供 Base64 编码后的服务账号 JSON 文件内容(适用于 CI/CD 或云端 Secret 注入)。
+- **`database_secret`**:传递遗留的数据库密钥(Database Secret)或 Web API Token。
+
+### 2. 路径与记录结构化
+- **集合路径 (`path = "users"`)**:连接器拉取子节点对象(例如 `user_101`、`user_102`),并将每个子节点对象作为单独的一行(Row)输出。
+- **单条记录路径 (`path = "users/user_101"`)**:连接器会自动将子标量字段(例如 `name`、`role`)聚合为与 Schema 匹配的单行数据输出。
+
+---
+
+## 示例
+
+### 读取集合路径
+
+```hocon
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ Firebase {
+ url = "https://my-app-default-rtdb.firebaseio.com"
+ path = "users"
+ service_account_path = "/etc/seatunnel/firebase-credentials.json"
+ timeout_ms = 5000
+
+ schema {
+ fields {
+ name = "string"
+ role = "string"
+ }
+ }
+ plugin_output = "firebase_users"
+ }
+}
+
+sink {
+ Console {
+ plugin_input = "firebase_users"
+ }
+}
+```
+
+## 变更日志
+
+<ChangeLog />
diff --git a/plugin-mapping.properties b/plugin-mapping.properties
index eb8305a6ea..53ded4c36b 100644
--- a/plugin-mapping.properties
+++ b/plugin-mapping.properties
@@ -52,6 +52,7 @@ seatunnel.source.OssJindoFile = connector-file-jindo-oss
seatunnel.sink.OssJindoFile = connector-file-jindo-oss
seatunnel.source.CosFile = connector-file-cos
seatunnel.sink.CosFile = connector-file-cos
+seatunnel.source.Firebase = connector-firebase
seatunnel.source.Pulsar = connector-pulsar
seatunnel.sink.DingTalk = connector-dingtalk
seatunnel.source.Elasticsearch = connector-elasticsearch
diff --git a/seatunnel-connectors-v2/connector-firebase/pom.xml b/seatunnel-connectors-v2/connector-firebase/pom.xml
new file mode 100644
index 0000000000..523c4d1b5d
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/pom.xml
@@ -0,0 +1,77 @@
+<?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 http://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-firebase</artifactId>
+ <name>SeaTunnel : Connectors V2 : Firebase</name>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>seatunnel-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.auto.service</groupId>
+ <artifactId>auto-service</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>seatunnel-format-json</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.auth</groupId>
+ <artifactId>google-auth-library-oauth2-http</artifactId>
+ <version>1.3.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>31.1-android</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClient.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClient.java
new file mode 100644
index 0000000000..2c55c97120
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClient.java
@@ -0,0 +1,303 @@
+/*
+ * 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.firebase.client;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.seatunnel.shade.org.apache.commons.lang3.StringUtils;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.common.utils.SeaTunnelException;
+import org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import com.google.auth.oauth2.AccessToken;
+import com.google.auth.oauth2.GoogleCredentials;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.locks.ReentrantLock;
+
+@Slf4j
+public class FirebaseHttpClient {
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ private static final int MAX_ERROR_BODY_BYTES = 4096;
+ private final String baseUrl;
+ private final String path;
+ private final int timeoutMs;
+ private final Map<String, String> extraQueryParams;
+ private static final List<String> FIREBASE_SCOPES =
+ Arrays.asList(
+ "https://www.googleapis.com/auth/firebase.database",
+ "https://www.googleapis.com/auth/userinfo.email");
+ private final GoogleCredentials credentials;
+ private final String databaseSecret;
+ private final ReentrantLock tokenLock = new ReentrantLock();
+
+ public FirebaseHttpClient(ReadonlyConfig config) {
+ this.baseUrl = config.get(FirebaseSourceOptions.URL).replaceAll("/+$", "");
+ this.path = config.get(FirebaseSourceOptions.PATH).replaceAll("^/+|/+$", "");
+ int toms = config.get(FirebaseSourceOptions.TIMEOUT_MS);
+ if (toms <= 0) {
+ throw new SeaTunnelException("timeout_ms must be greater than 0");
+ }
+ this.timeoutMs = toms;
+ this.extraQueryParams =
+ config.getOptional(FirebaseSourceOptions.QUERY_PARAMS)
+ .orElse(Collections.emptyMap());
+
+ this.credentials = initGoogleCredentials(config);
+ this.databaseSecret =
+ config.getOptional(FirebaseSourceOptions.DATABASE_SECRET).orElse(null);
+ if (this.credentials != null) {
+ log.info("Initialized FirebaseHttpClient with Google OAuth2 Service Account.");
+ } else if (StringUtils.isNotEmpty(this.databaseSecret)) {
+ log.info("Initialized FirebaseHttpClient with Legacy Database Secret.");
+ } else {
+ log.info("Initialized FirebaseHttpClient without authentication (Public Read).");
+ }
+ }
+
+ /**
+ * Executes a shallow scan on the configured node path to retrieve top-level keys. Endpoint: GET
+ * /<path>.json?shallow=true
+ */
+ public List<String> fetchShallowKeys() {
+ String endpointUrl = buildUrl(this.path, "shallow=true", false);
+ String jsonResponse = executeGet(endpointUrl);
+ return parseShallowKeys(jsonResponse);
+ }
+
+ /** Parses the JSON payload returned by a shallow scan query. */
+ List<String> parseShallowKeys(String jsonResponse) {
+ if (jsonResponse == null || jsonResponse.trim().equals("null")) {
+ return Collections.emptyList();
+ }
+ String trimmed = jsonResponse.trim();
+ if (!trimmed.startsWith("{")) {
+ return Collections.emptyList();
+ }
+
+ try {
+ Map<String, Boolean> keysMap =
+ OBJECT_MAPPER.readValue(trimmed, new TypeReference<Map<String, Boolean>>() {});
+ return new ArrayList<>(keysMap.keySet());
+ } catch (Exception e) {
+ throw new SeaTunnelException("Failed to parse shallow keys from Firebase response", e);
+ }
+ }
+
+ /**
+ * Fetches the raw JSON payload for a given sub-path or individual node key. Endpoint: GET
+ * /<path>/<nodeKey>.json
+ */
+ public String fetchNodeData(String nodeKey) {
+ String targetPath =
+ nodeKey == null || nodeKey.isEmpty() ? this.path : this.path + "/" + nodeKey;
+
+ String endpointUrl = buildUrl(targetPath, null, true);
+ return executeGet(endpointUrl);
+ }
+
+ /** Constructs a full REST URL with .json extension and query string parameters. */
+ String buildUrl(String subPath, String extraQueryParam, boolean includeExtraParams) {
+ StringBuilder urlBuilder = new StringBuilder(baseUrl);
+ String cleanSubPath = subPath == null ? "" : subPath.replaceAll("^/+|/+$", "");
+ urlBuilder.append("/").append(cleanSubPath);
+
+ urlBuilder.append(".json");
+
+ List<String> queryParts = new ArrayList<>();
+ if (extraQueryParam != null && !extraQueryParam.isEmpty()) {
+ queryParts.add(extraQueryParam);
+ }
+
+ if (databaseSecret != null && !databaseSecret.isEmpty()) {
+ queryParts.add("auth=" + encodeUriComponent(databaseSecret));
+ }
+
+ if (includeExtraParams) {
+ for (Map.Entry<String, String> entry : extraQueryParams.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+
+ if ("orderBy".equals(key)
+ || "equalTo".equals(key)
+ || "startAt".equals(key)
+ || "endAt".equals(key)) {
+ if (!value.startsWith("\"")) {
+ value = "\"" + value + "\"";
+ }
+ }
+
+ queryParts.add(encodeUriComponent(key) + "=" + encodeUriComponent(value));
+ }
+ }
+
+ if (!queryParts.isEmpty()) {
+ urlBuilder.append("?").append(String.join("&", queryParts));
+ }
+ return urlBuilder.toString();
+ }
+
+ /** Sends an HTTP GET request and handles status code verification. */
+ private String executeGet(String urlStr) {
+ HttpURLConnection connection = null;
+ try {
+ URL url;
+ try {
+ url = URI.create(urlStr).toURL();
+ } catch (IllegalArgumentException e) {
+ throw new SeaTunnelException(
+ "Invalid Firebase REST URI constructed. Check parameter formatting.");
+ }
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("GET");
+ connection.setConnectTimeout(timeoutMs);
+ connection.setReadTimeout(timeoutMs);
+ connection.setRequestProperty("Accept", "application/json");
+ connection.setInstanceFollowRedirects(true);
+
+ if (credentials != null) {
+ String token = getAccessToken();
+ connection.setRequestProperty("Authorization", "Bearer " + token);
+ }
+
+ int responseCode = connection.getResponseCode();
+ if (responseCode >= 200 && responseCode < 300) {
+ try (InputStream inputStream = connection.getInputStream();
+ BufferedReader reader =
+ new BufferedReader(
+ new InputStreamReader(
+ inputStream, StandardCharsets.UTF_8))) {
+ StringBuilder responseBuilder = new StringBuilder();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ responseBuilder.append(line);
+ }
+ return responseBuilder.toString();
+ }
+ } else {
+ String rawErrorBody = readErrorStream(connection);
+ throw new SeaTunnelException(
+ String.format(
+ "Firebase HTTP request failed with status code %d. Response body: %s",
+ responseCode, rawErrorBody.isEmpty() ? "N/A" : rawErrorBody));
+ }
+ } catch (IOException e) {
+ throw new SeaTunnelException("Failed to execute HTTP request to Firebase endpoint", e);
+ } finally {
+ if (connection != null) {
+ connection.disconnect();
+ }
+ }
+ }
+
+ private String encodeUriComponent(String value) {
+ try {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8.name())
+ .replaceAll("\\+", "%20"); // Handle space encoding for URIs
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String readErrorStream(HttpURLConnection connection) {
+ InputStream errorStream = connection.getErrorStream();
+ if (errorStream == null) {
+ return "";
+ }
+ try (BufferedReader reader =
+ new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) {
+ StringBuilder builder = new StringBuilder();
+ char[] buffer = new char[1024];
+ int bytesRead;
+ int totalRead = 0;
+ while ((bytesRead =
+ reader.read(
+ buffer,
+ 0,
+ Math.min(buffer.length, MAX_ERROR_BODY_BYTES - totalRead)))
+ != -1) {
+ builder.append(buffer, 0, bytesRead);
+ totalRead += bytesRead;
+ if (totalRead >= MAX_ERROR_BODY_BYTES) {
+ break;
+ }
+ }
+ return builder.toString().trim();
+ } catch (IOException e) {
+ log.warn("Failed to read error stream from Firebase HTTP connection", e);
+ return "";
+ }
+ }
+
+ /** Retrieves or refreshes OAuth 2.0 access token safely. */
+ private synchronized String getAccessToken() throws IOException {
+ tokenLock.lock();
+ try {
+ AccessToken token = credentials.getAccessToken();
+ if (token == null
+ || token.getExpirationTime() == null
+ || token.getExpirationTime().getTime() <= System.currentTimeMillis() + 60000) {
+ credentials.refresh();
+ token = credentials.getAccessToken();
+ }
+ return token.getTokenValue();
+ } finally {
+ tokenLock.unlock();
+ }
+ }
+
+ private GoogleCredentials initGoogleCredentials(ReadonlyConfig config) {
+ try {
+ if (config.getOptional(FirebaseSourceOptions.CREDENTIALS).isPresent()) {
+ String base64Credentials = config.get(FirebaseSourceOptions.CREDENTIALS);
+ byte[] decodedBytes = Base64.getDecoder().decode(base64Credentials);
+ try (InputStream inputStream = new ByteArrayInputStream(decodedBytes)) {
+ return GoogleCredentials.fromStream(inputStream).createScoped(FIREBASE_SCOPES);
+ }
+ } else if (config.getOptional(FirebaseSourceOptions.SERVICE_ACCOUNT_PATH).isPresent()) {
+ String path = config.get(FirebaseSourceOptions.SERVICE_ACCOUNT_PATH);
+ try (InputStream inputStream = new FileInputStream(path)) {
+ return GoogleCredentials.fromStream(inputStream).createScoped(FIREBASE_SCOPES);
+ }
+ }
+ } catch (IOException e) {
+ throw new SeaTunnelException(
+ "Failed to initialize Google Service Account credentials", e);
+ }
+ return null;
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/config/FirebaseSourceOptions.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/config/FirebaseSourceOptions.java
new file mode 100644
index 0000000000..7da9643fdb
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/config/FirebaseSourceOptions.java
@@ -0,0 +1,66 @@
+/*
+ * 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.firebase.config;
+
+import org.apache.seatunnel.api.configuration.Option;
+import org.apache.seatunnel.api.configuration.Options;
+import org.apache.seatunnel.api.options.ConnectorCommonOptions;
+
+import java.util.Map;
+
+public class FirebaseSourceOptions {
+ public static final Option<String> URL =
+ Options.key("url")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("The base URL of the Firebase Realtime Database.");
+ public static final Option<String> PATH =
+ Options.key("path")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("The JSON node path to read from.");
+ public static final Option<Map<String, Object>> SCHEMA = ConnectorCommonOptions.SCHEMA;
+ public static final Option<String> SERVICE_ACCOUNT_PATH =
+ Options.key("service_account_path")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("Path to the Google Service Account JSON key file.");
+ public static final Option<String> CREDENTIALS =
+ Options.key("credentials")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("Base64-encoded Service Account JSON credentials.");
+ public static final Option<String> DATABASE_SECRET =
+ Options.key("database_secret")
+ .stringType()
+ .noDefaultValue()
+ .withDescription("Legacy Firebase database secret key or Web API token.");
+
+ public static final Option<Integer> TIMEOUT_MS =
+ Options.key("timeout_ms")
+ .intType()
+ .defaultValue(10000)
+ .withDescription(
+ "HTTP connection and read timeout in milliseconds (must be > 0).");
+
+ public static final Option<Map<String, String>> QUERY_PARAMS =
+ Options.key("query_params")
+ .mapType()
+ .noDefaultValue()
+ .withDescription("Additional REST API query parameters.");
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSource.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSource.java
new file mode 100644
index 0000000000..3e82862546
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSource.java
@@ -0,0 +1,86 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.serialization.Serializer;
+import org.apache.seatunnel.api.source.Boundedness;
+import org.apache.seatunnel.api.source.SeaTunnelSource;
+import org.apache.seatunnel.api.source.SourceReader;
+import org.apache.seatunnel.api.source.SourceSplitEnumerator;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+
+import java.util.Collections;
+import java.util.List;
+
+public class FirebaseSource
+ implements SeaTunnelSource<SeaTunnelRow, FirebaseSourceSplit, FirebaseSourceState> {
+ private final ReadonlyConfig config;
+ private final CatalogTable catalogTable;
+
+ public FirebaseSource(ReadonlyConfig config, CatalogTable catalogTable) {
+ this.config = config;
+ this.catalogTable = catalogTable;
+ }
+
+ @Override
+ public String getPluginName() {
+ return "Firebase";
+ }
+
+ @Override
+ public Boundedness getBoundedness() {
+ return Boundedness.BOUNDED;
+ }
+
+ @Override
+ public SourceReader<SeaTunnelRow, FirebaseSourceSplit> createReader(
+ SourceReader.Context readerContext) throws Exception {
+ return new FirebaseSourceReader(readerContext, config, catalogTable);
+ }
+
+ @Override
+ public SourceSplitEnumerator<FirebaseSourceSplit, FirebaseSourceState> createEnumerator(
+ SourceSplitEnumerator.Context<FirebaseSourceSplit> enumeratorContext) throws Exception {
+ return new FirebaseSourceSplitEnumerator(enumeratorContext, config);
+ }
+
+ @Override
+ public SourceSplitEnumerator<FirebaseSourceSplit, FirebaseSourceState> restoreEnumerator(
+ SourceSplitEnumerator.Context<FirebaseSourceSplit> enumeratorContext,
+ FirebaseSourceState checkpointState)
+ throws Exception {
+ return new FirebaseSourceSplitEnumerator(enumeratorContext, config, checkpointState);
+ }
+
+ @Override
+ public Serializer<FirebaseSourceSplit> getSplitSerializer() {
+ return new FirebaseSourceSplitSerializer();
+ }
+
+ @Override
+ public Serializer<FirebaseSourceState> getEnumeratorStateSerializer() {
+ return new FirebaseSourceStateSerializer();
+ }
+
+ @Override
+ public List<CatalogTable> getProducedCatalogTables() {
+ return Collections.singletonList(catalogTable);
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceFactory.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceFactory.java
new file mode 100644
index 0000000000..1e317c3a31
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceFactory.java
@@ -0,0 +1,71 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.configuration.util.OptionRule;
+import org.apache.seatunnel.api.source.SeaTunnelSource;
+import org.apache.seatunnel.api.source.SourceSplit;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.CatalogTableUtil;
+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 org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import com.google.auto.service.AutoService;
+
+import java.io.Serializable;
+
+@AutoService(Factory.class)
+public class FirebaseSourceFactory implements TableSourceFactory {
+ @Override
+ public String factoryIdentifier() {
+ return "Firebase";
+ }
+
+ @Override
+ public OptionRule optionRule() {
+ return OptionRule.builder()
+ .required(
+ FirebaseSourceOptions.URL,
+ FirebaseSourceOptions.PATH,
+ FirebaseSourceOptions.SCHEMA)
+ .optional(
+ FirebaseSourceOptions.SERVICE_ACCOUNT_PATH,
+ FirebaseSourceOptions.CREDENTIALS,
+ FirebaseSourceOptions.DATABASE_SECRET,
+ FirebaseSourceOptions.TIMEOUT_MS,
+ FirebaseSourceOptions.QUERY_PARAMS)
+ .build();
+ }
+
+ @Override
+ public <T, SplitT extends SourceSplit, StateT extends Serializable>
+ TableSource<T, SplitT, StateT> createSource(TableSourceFactoryContext context) {
+ CatalogTable catalogTable = CatalogTableUtil.buildWithConfig(context.getOptions());
+ return () ->
+ (SeaTunnelSource<T, SplitT, StateT>)
+ new FirebaseSource(context.getOptions(), catalogTable);
+ }
+
+ @Override
+ public Class<? extends SeaTunnelSource> getSourceClass() {
+ return FirebaseSource.class;
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReader.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReader.java
new file mode 100644
index 0000000000..985dd8c976
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReader.java
@@ -0,0 +1,273 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+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.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.common.utils.SeaTunnelException;
+import org.apache.seatunnel.connectors.seatunnel.firebase.client.FirebaseHttpClient;
+import org.apache.seatunnel.format.json.JsonDeserializationSchema;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+@Slf4j
+public class FirebaseSourceReader implements SourceReader<SeaTunnelRow, FirebaseSourceSplit> {
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private final SourceReader.Context context;
+ private final ReadonlyConfig config;
+ private final CatalogTable catalogTable;
+ private final FirebaseHttpClient httpClient;
+ private final JsonDeserializationSchema deserializationSchema;
+ private final Set<String> declaredFields;
+ private final Queue<FirebaseSourceSplit> splits = new ConcurrentLinkedQueue<>();
+ private volatile boolean noMoreSplits = false;
+
+ public FirebaseSourceReader(
+ SourceReader.Context context, ReadonlyConfig config, CatalogTable catalogTable) {
+ this.context = context;
+ this.config = config;
+ this.catalogTable = catalogTable;
+ this.httpClient = new FirebaseHttpClient(config);
+
+ SeaTunnelRowType rowType = catalogTable.getTableSchema().toPhysicalRowDataType();
+ this.declaredFields = extractDeclaredFields(catalogTable);
+ this.deserializationSchema = new JsonDeserializationSchema(false, false, rowType);
+ }
+
+ FirebaseSourceReader(
+ SourceReader.Context context,
+ ReadonlyConfig config,
+ CatalogTable catalogTable,
+ FirebaseHttpClient httpClient) {
+ this.context = context;
+ this.config = config;
+ this.catalogTable = catalogTable;
+ this.httpClient = httpClient;
+
+ SeaTunnelRowType rowType = catalogTable.getTableSchema().toPhysicalRowDataType();
+ this.declaredFields = extractDeclaredFields(catalogTable);
+ this.deserializationSchema = new JsonDeserializationSchema(false, false, rowType);
+ }
+
+ @Override
+ public void open() throws Exception {
+ // No persistent connection setup required for REST client
+ }
+
+ @Override
+ public void pollNext(Collector<SeaTunnelRow> output) throws Exception {
+ FirebaseSourceSplit split = splits.poll();
+ if (split != null) {
+ readSplit(split, output);
+ return;
+ }
+
+ if (noMoreSplits) {
+ log.info("notify engine , no more splits");
+ context.signalNoMoreElement();
+ } else {
+ Thread.sleep(100);
+ }
+ }
+
+ private void readSplit(FirebaseSourceSplit split, Collector<SeaTunnelRow> output)
+ throws Exception {
+ log.info(
+ "Reading split [{}] with path [{}] and keys count [{}]",
+ split.splitId(),
+ split.getPath(),
+ split.getKeys().size());
+ List<String> keys = split.getKeys();
+
+ if (keys != null && !keys.isEmpty()) {
+ Map<String, Object> reconstructedMap = new LinkedHashMap<>();
+
+ for (String key : keys) {
+ String jsonPayload = httpClient.fetchNodeData(key);
+ if (jsonPayload != null && !jsonPayload.trim().equals("null")) {
+
+ String trimmedPayload = jsonPayload.trim();
+
+ if (declaredFields.contains(key)) {
+ try {
+ Object parsedVal =
+ OBJECT_MAPPER.readValue(trimmedPayload, Object.class);
+ reconstructedMap.put(key, parsedVal);
+ } catch (Exception e) {
+ reconstructedMap.put(key, trimmedPayload);
+ }
+ } else if (trimmedPayload.startsWith("{") || trimmedPayload.startsWith("[")) {
+ processJsonPayload(trimmedPayload, output);
+ } else {
+ reconstructedMap.put(key, trimmedPayload);
+ }
+ }
+ }
+
+ if (!reconstructedMap.isEmpty()) {
+ String singleRowJson = OBJECT_MAPPER.writeValueAsString(reconstructedMap);
+ emitJsonRecord(singleRowJson, output);
+ }
+ } else {
+ String jsonPayload = httpClient.fetchNodeData(null);
+ processJsonPayload(jsonPayload, output);
+ }
+ }
+
+ /** Extracts top-level schema field names into an unmodifiable Set once during construction. */
+ private static Set<String> extractDeclaredFields(CatalogTable catalogTable) {
+ if (catalogTable != null && catalogTable.getTableSchema() != null) {
+ SeaTunnelRowType rowType = catalogTable.getTableSchema().toPhysicalRowDataType();
+ if (rowType != null && rowType.getFieldNames() != null) {
+ return Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList(rowType.getFieldNames())));
+ }
+ }
+ return Collections.emptySet();
+ }
+
+ /** Helper method that consistently handles single records, record maps, and JSON arrays. */
+ private void processJsonPayload(String jsonPayload, Collector<SeaTunnelRow> output)
+ throws Exception {
+ if (jsonPayload == null || jsonPayload.trim().equalsIgnoreCase("null")) {
+ return;
+ }
+ String trimmed = jsonPayload.trim();
+
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
+ throw new SeaTunnelException("Unexpected JSON payload format from Firebase");
+ }
+
+ // Work queue to store objects (Maps, Lists) pending evaluation
+ Queue<Object> workQueue = new ArrayDeque<>();
+
+ // Parse initial payload once into Java Map/List
+ Object initialParsed = OBJECT_MAPPER.readValue(trimmed, Object.class);
+ workQueue.add(initialParsed);
+
+ while (!workQueue.isEmpty()) {
+ Object current = workQueue.poll();
+ if (current == null) {
+ continue;
+ }
+
+ if (current instanceof Map) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> recordMap = (Map<String, Object>) current;
+
+ if (isSingleRecordObject(recordMap)) {
+ // Base Case: It's a single database row -> emit it
+ String recordJson = OBJECT_MAPPER.writeValueAsString(recordMap);
+ emitJsonRecord(recordJson, output);
+ } else {
+ // Recursive Case 1: Un-nest child values into queue
+ for (Object childValue : recordMap.values()) {
+ if (childValue != null) {
+ workQueue.add(childValue);
+ }
+ }
+ }
+ } else if (current instanceof List) {
+ // Recursive Case 2: Un-nest array elements into queue
+ @SuppressWarnings("unchecked")
+ List<Object> recordList = (List<Object>) current;
+
+ for (Object item : recordList) {
+ if (item != null) {
+ workQueue.add(item);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks if a JSON map represents a single row record matching the catalog schema rather than a
+ * dictionary of child records.
+ */
+ private boolean isSingleRecordObject(Map<String, Object> map) {
+ if (map == null || map.isEmpty() || declaredFields.isEmpty()) {
+ return false;
+ }
+
+ for (String fieldName : declaredFields) {
+ if (map.containsKey(fieldName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void emitJsonRecord(String jsonRecord, Collector<SeaTunnelRow> output)
+ throws IOException {
+ if (jsonRecord != null && !jsonRecord.trim().equals("null")) {
+ SeaTunnelRow row =
+ deserializationSchema.deserialize(jsonRecord.getBytes(StandardCharsets.UTF_8));
+ if (row != null) {
+ output.collect(row);
+ }
+ }
+ }
+
+ @Override
+ public List<FirebaseSourceSplit> snapshotState(long checkpointId) {
+ return new ArrayList<>(splits);
+ }
+
+ @Override
+ public void addSplits(List<FirebaseSourceSplit> newSplits) {
+ splits.addAll(newSplits);
+ }
+
+ @Override
+ public void handleNoMoreSplits() {
+ log.info(
+ "Reader subtask [{}] received handleNoMoreSplits signal.",
+ context.getIndexOfSubtask());
+ this.noMoreSplits = true;
+ }
+
+ @Override
+ public void close() throws IOException {
+ // Cleanup resources if necessary
+ }
+
+ @Override
+ public void notifyCheckpointComplete(long checkpointId) throws Exception {}
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplit.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplit.java
new file mode 100644
index 0000000000..419b6ada1e
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplit.java
@@ -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.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.firebase.source;
+
+import org.apache.seatunnel.api.source.SourceSplit;
+
+import lombok.Getter;
+
+import java.util.Collections;
+import java.util.List;
+
+public class FirebaseSourceSplit implements SourceSplit {
+ private static final long serialVersionUID = 1L;
+
+ private final String splitId;
+ @Getter private final String path;
+ @Getter private final List<String> keys; // Sub-keys to fetch if using key-based splitting
+
+ public FirebaseSourceSplit(String splitId, String path) {
+ this.splitId = splitId;
+ this.path = path;
+ this.keys = Collections.emptyList();
+ }
+
+ public FirebaseSourceSplit(String splitId, String path, List<String> keys) {
+ this.splitId = splitId;
+ this.path = path;
+ this.keys = keys;
+ }
+
+ @Override
+ public String splitId() {
+ return splitId;
+ }
+
+ @Override
+ public String toString() {
+ return splitId + " " + path + " keys : " + keys.toString();
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumerator.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumerator.java
new file mode 100644
index 0000000000..d5220a5389
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumerator.java
@@ -0,0 +1,234 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.source.SourceSplitEnumerator;
+import org.apache.seatunnel.connectors.seatunnel.firebase.client.FirebaseHttpClient;
+import org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+@Slf4j
+public class FirebaseSourceSplitEnumerator
+ implements SourceSplitEnumerator<FirebaseSourceSplit, FirebaseSourceState> {
+ private final Context<FirebaseSourceSplit> context;
+ private final ReadonlyConfig config;
+ private final FirebaseHttpClient httpClient;
+
+ private final Set<FirebaseSourceSplit> pendingSplits = new HashSet<>();
+ private final Set<String> assignedSplitIds = new HashSet<>();
+
+ private final Set<Integer> signalledReaders = new HashSet<>();
+ private volatile boolean discoveryDone = false;
+
+ public FirebaseSourceSplitEnumerator(
+ Context<FirebaseSourceSplit> context, ReadonlyConfig config) {
+ this.context = context;
+ this.config = config;
+ this.httpClient = new FirebaseHttpClient(config);
+ }
+
+ public FirebaseSourceSplitEnumerator(
+ Context<FirebaseSourceSplit> context,
+ ReadonlyConfig config,
+ FirebaseSourceState state) {
+ this(context, config);
+ if (state != null) {
+ synchronized (this) {
+ this.pendingSplits.addAll(state.getPendingSplits());
+ this.assignedSplitIds.addAll(state.getAssignedSplitIds());
+ this.discoveryDone = true;
+ }
+ }
+ }
+
+ FirebaseSourceSplitEnumerator(
+ Context<FirebaseSourceSplit> context,
+ ReadonlyConfig config,
+ FirebaseHttpClient httpClient) {
+ this.context = context;
+ this.config = config;
+ this.httpClient = httpClient;
+ }
+
+ @Override
+ public void open() {
+ // No explicit persistent connections needed for REST client
+ }
+
+ @Override
+ public void run() throws Exception {
+ log.info("FirebaseSourceSplitEnumerator run()");
+ synchronized (this) {
+ if (!pendingSplits.isEmpty() || !assignedSplitIds.isEmpty()) {
+ this.discoveryDone = true;
+ assignSplits();
+ return;
+ }
+ }
+ String basePath = config.get(FirebaseSourceOptions.PATH);
+ List<FirebaseSourceSplit> generatedSplits = new ArrayList<>();
+
+ try {
+ log.info("Attempting automatic key discovery (shallow scan) on path [{}]", basePath);
+ List<String> keys = httpClient.fetchShallowKeys();
+ if (!keys.isEmpty()) {
+ generatedSplits = partitionKeysIntoSplits(basePath, keys);
+ log.info(
+ "Key discovery succeeded. Partitioned path into {} splits.",
+ generatedSplits.size());
+ } else {
+ log.info("Shallow scan returned no child keys. Falling back to Single Path Split.");
+ generatedSplits.add(createSinglePathSplit(basePath));
+ }
+ } catch (Exception e) {
+ log.warn(
+ "Shallow key discovery failed on path [{}]. "
+ + "Falling back to Single Path Split. Reason: {}",
+ basePath,
+ e.getMessage());
+ generatedSplits.add(createSinglePathSplit(basePath));
+ }
+ synchronized (this) {
+ pendingSplits.addAll(generatedSplits);
+ log.info("pending Splits : {}", pendingSplits);
+ this.discoveryDone = true;
+ assignSplits();
+ }
+ }
+
+ @Override
+ public synchronized void registerReader(int subtaskId) {
+ log.info("Reader subtask [{}] registered.", subtaskId);
+ assignSplits();
+ }
+
+ @Override
+ public synchronized FirebaseSourceState snapshotState(long checkpointId) throws Exception {
+ return new FirebaseSourceState(
+ new HashSet<>(pendingSplits), new HashSet<>(assignedSplitIds));
+ }
+
+ @Override
+ public void close() throws IOException {
+ // Cleanup resources if needed
+ }
+
+ @Override
+ public synchronized void addSplitsBack(List<FirebaseSourceSplit> splits, int subtaskId) {
+ if (splits == null || splits.isEmpty()) {
+ return;
+ }
+ log.info(
+ "Adding {} splits back from failed/restarted subtask [{}]",
+ splits.size(),
+ subtaskId);
+ for (FirebaseSourceSplit split : splits) {
+ pendingSplits.add(split);
+ assignedSplitIds.remove(split.splitId());
+ }
+ assignSplits();
+ }
+
+ @Override
+ public synchronized int currentUnassignedSplitSize() {
+ return pendingSplits.size();
+ }
+
+ @Override
+ public synchronized void handleSplitRequest(int subtaskId) {
+ assignSplits();
+ }
+
+ @Override
+ public void notifyCheckpointComplete(long checkpointId) throws Exception {}
+
+ /** Splits top-level keys among available worker threads according to current parallelism. */
+ private List<FirebaseSourceSplit> partitionKeysIntoSplits(String basePath, List<String> keys) {
+ int currentParallelism = Math.max(1, context.currentParallelism());
+ List<FirebaseSourceSplit> splits = new ArrayList<>();
+
+ int totalKeys = keys.size();
+ int chunkSize = (int) Math.ceil((double) totalKeys / currentParallelism);
+ for (int i = 0; i < totalKeys; i += chunkSize) {
+ int end = Math.min(i + chunkSize, totalKeys);
+ List<String> keySubList = new ArrayList<>(keys.subList(i, end));
+ String splitId = "split_key_range_" + i + "_" + (end - 1);
+ splits.add(new FirebaseSourceSplit(splitId, basePath, keySubList));
+ }
+ return splits;
+ }
+
+ private FirebaseSourceSplit createSinglePathSplit(String basePath) {
+ return new FirebaseSourceSplit("split_single_path_" + basePath.hashCode(), basePath);
+ }
+
+ /** Assigns pending splits to available reader subtasks idempotently. */
+ private void assignSplits() {
+ Set<Integer> registeredReaders = context.registeredReaders();
+ if (registeredReaders.isEmpty()) {
+ return;
+ }
+
+ // 1. Assign any remaining pending splits
+ if (!pendingSplits.isEmpty()) {
+ List<Integer> readersList = new ArrayList<>(registeredReaders);
+ Map<Integer, List<FirebaseSourceSplit>> assignmentMap = new HashMap<>();
+ int readerIndex = 0;
+ Set<FirebaseSourceSplit> assignedInThisBatch = new HashSet<>();
+
+ for (FirebaseSourceSplit split : pendingSplits) {
+ int targetReader = readersList.get(readerIndex % readersList.size());
+ assignmentMap.computeIfAbsent(targetReader, k -> new ArrayList<>()).add(split);
+ assignedSplitIds.add(split.splitId());
+ assignedInThisBatch.add(split);
+ readerIndex++;
+ }
+
+ for (Map.Entry<Integer, List<FirebaseSourceSplit>> entry : assignmentMap.entrySet()) {
+ int readerId = entry.getKey();
+ List<FirebaseSourceSplit> splitsForReader = entry.getValue();
+ context.assignSplit(readerId, splitsForReader);
+ log.info(
+ "Assigned {} splits to reader subtask [{}]",
+ splitsForReader.size(),
+ readerId);
+ }
+
+ pendingSplits.removeAll(assignedInThisBatch);
+ }
+
+ if (discoveryDone && pendingSplits.isEmpty()) {
+ for (Integer readerId : registeredReaders) {
+ if (signalledReaders.add(readerId)) {
+ context.signalNoMoreSplits(readerId);
+ log.info("Signaled NO_MORE_SPLITS to reader subtask [{}]", readerId);
+ }
+ }
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitSerializer.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitSerializer.java
new file mode 100644
index 0000000000..fd28ca8c72
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitSerializer.java
@@ -0,0 +1,62 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.serialization.Serializer;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class FirebaseSourceSplitSerializer implements Serializer<FirebaseSourceSplit> {
+ @Override
+ public byte[] serialize(FirebaseSourceSplit split) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (DataOutputStream out = new DataOutputStream(baos)) {
+ out.writeUTF(split.splitId());
+ out.writeUTF(split.getPath());
+
+ List<String> keys = split.getKeys();
+ out.writeInt(keys.size());
+ for (String key : keys) {
+ out.writeUTF(key);
+ }
+ out.flush();
+ }
+ return baos.toByteArray();
+ }
+
+ @Override
+ public FirebaseSourceSplit deserialize(byte[] serialized) throws IOException {
+ try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(serialized))) {
+ String splitId = in.readUTF();
+ String path = in.readUTF();
+
+ int size = in.readInt();
+ List<String> keys = new ArrayList<>(size);
+ for (int i = 0; i < size; i++) {
+ keys.add(in.readUTF());
+ }
+ return new FirebaseSourceSplit(splitId, path, keys);
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceState.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceState.java
new file mode 100644
index 0000000000..ac8852d844
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceState.java
@@ -0,0 +1,37 @@
+/*
+ * 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.firebase.source;
+
+import lombok.Getter;
+
+import java.io.Serializable;
+import java.util.Set;
+
+@Getter
+public class FirebaseSourceState implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private final Set<FirebaseSourceSplit> pendingSplits;
+ private final Set<String> assignedSplitIds;
+
+ public FirebaseSourceState(
+ Set<FirebaseSourceSplit> pendingSplits, Set<String> assignedSplitIds) {
+ this.pendingSplits = pendingSplits;
+ this.assignedSplitIds = assignedSplitIds;
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceStateSerializer.java b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceStateSerializer.java
new file mode 100644
index 0000000000..8822b9b9c6
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/main/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceStateSerializer.java
@@ -0,0 +1,83 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.serialization.Serializer;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+public class FirebaseSourceStateSerializer implements Serializer<FirebaseSourceState> {
+
+ private final FirebaseSourceSplitSerializer splitSerializer =
+ new FirebaseSourceSplitSerializer();
+
+ @Override
+ public byte[] serialize(FirebaseSourceState state) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (DataOutputStream out = new DataOutputStream(baos)) {
+ // 1. Serialize Pending Splits
+ Set<FirebaseSourceSplit> pendingSplits = state.getPendingSplits();
+ out.writeInt(pendingSplits.size());
+ for (FirebaseSourceSplit split : pendingSplits) {
+ byte[] splitBytes = splitSerializer.serialize(split);
+ out.writeInt(splitBytes.length);
+ out.write(splitBytes);
+ }
+
+ // 2. Serialize Assigned Split IDs
+ Set<String> assignedSplitIds = state.getAssignedSplitIds();
+ out.writeInt(assignedSplitIds.size());
+ for (String splitId : assignedSplitIds) {
+ out.writeUTF(splitId);
+ }
+
+ out.flush();
+ }
+ return baos.toByteArray();
+ }
+
+ @Override
+ public FirebaseSourceState deserialize(byte[] serialized) throws IOException {
+ try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(serialized))) {
+ // 1. Deserialize Pending Splits
+ int pendingSize = in.readInt();
+ Set<FirebaseSourceSplit> pendingSplits = new HashSet<>(pendingSize);
+ for (int i = 0; i < pendingSize; i++) {
+ int splitBytesLen = in.readInt();
+ byte[] splitBytes = new byte[splitBytesLen];
+ in.readFully(splitBytes);
+ pendingSplits.add(splitSerializer.deserialize(splitBytes));
+ }
+
+ // 2. Deserialize Assigned Split IDs
+ int assignedSize = in.readInt();
+ Set<String> assignedSplitIds = new HashSet<>(assignedSize);
+ for (int i = 0; i < assignedSize; i++) {
+ assignedSplitIds.add(in.readUTF());
+ }
+
+ return new FirebaseSourceState(pendingSplits, assignedSplitIds);
+ }
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClientTest.java b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClientTest.java
new file mode 100644
index 0000000000..352d01de4b
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/client/FirebaseHttpClientTest.java
@@ -0,0 +1,161 @@
+/*
+ * 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.firebase.client;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.common.utils.SeaTunnelException;
+import org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class FirebaseHttpClientTest {
+ @Test
+ void testConfigUrlAndPathNormalization() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com///");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "///users/nodes///");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ String constructedUrl = client.buildUrl("users/nodes", null, false);
+ assertEquals("https://test-db.firebaseio.com/users/nodes.json", constructedUrl);
+ }
+
+ @Test
+ void testBuildUrlPercentEncodesDatabaseSecretWithSpecialCharacters() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+ configMap.put(FirebaseSourceOptions.DATABASE_SECRET.key(), "sec ret+123&key=\"val\"");
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ String url = client.buildUrl("users", null, false);
+
+ // Asserts spaces (+ -> %20), quotes (%22), and special characters are percent-encoded
+ assertTrue(url.contains("auth=sec%20ret%2B123%26key%3D%22val%22"));
+ assertFalse(url.contains("sec ret"));
+ assertFalse(url.contains("auth=sec+ret"));
+ }
+
+ @Test
+ void testBuildUrlQuotesAndEncodesFilterParameters() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ Map<String, String> queryParams = new HashMap<>();
+ queryParams.put("orderBy", "name");
+ queryParams.put("equalTo", "John Doe");
+ configMap.put(FirebaseSourceOptions.QUERY_PARAMS.key(), queryParams);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ String url = client.buildUrl("users", null, true);
+
+ // Asserts values are quote-wrapped ("name", "John Doe") and percent-encoded (%22)
+ assertTrue(url.contains("orderBy=%22name%22"));
+ assertTrue(url.contains("equalTo=%22John%20Doe%22"));
+ }
+
+ @Test
+ void testBuildUrlShallowScanExcludesQueryParams() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ Map<String, String> queryParams = new HashMap<>();
+ queryParams.put("limitToFirst", "10");
+ configMap.put(FirebaseSourceOptions.QUERY_PARAMS.key(), queryParams);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ // Shallow scan call: includeExtraParams = false
+ String shallowUrl = client.buildUrl("users", "shallow=true", false);
+ assertEquals("https://test-db.firebaseio.com/users.json?shallow=true", shallowUrl);
+ assertFalse(shallowUrl.contains("limitToFirst"));
+
+ // Regular node fetch call: includeExtraParams = true
+ String nodeUrl = client.buildUrl("users", null, true);
+ assertEquals("https://test-db.firebaseio.com/users.json?limitToFirst=10", nodeUrl);
+ }
+
+ @Test
+ void testParseShallowKeysWithValidJson() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ String jsonResponse = "{\"user_101\": true, \"user_102\": true}";
+ List<String> keys = client.parseShallowKeys(jsonResponse);
+
+ assertEquals(2, keys.size());
+ assertTrue(keys.contains("user_101"));
+ assertTrue(keys.contains("user_102"));
+ }
+
+ @Test
+ void testParseShallowKeysReturnsEmptyListOnNullOrNonObjectResponse() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ assertTrue(client.parseShallowKeys("null").isEmpty());
+ assertTrue(client.parseShallowKeys(null).isEmpty());
+ assertTrue(client.parseShallowKeys(" ").isEmpty());
+ assertTrue(client.parseShallowKeys("[\"user_101\"]").isEmpty());
+ }
+
+ @Test
+ void testParseShallowKeysThrowsSeaTunnelExceptionOnMalformedJson() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.TIMEOUT_MS.key(), 5000);
+
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+ FirebaseHttpClient client = new FirebaseHttpClient(config);
+
+ assertThrows(SeaTunnelException.class, () -> client.parseShallowKeys("{invalid_json_body"));
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseDataDeserializerTest.java b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseDataDeserializerTest.java
new file mode 100644
index 0000000000..e0bc4fbc57
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseDataDeserializerTest.java
@@ -0,0 +1,85 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.serialization.DeserializationSchema;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.format.json.JsonDeserializationSchema;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+public class FirebaseDataDeserializerTest {
+ private DeserializationSchema<SeaTunnelRow> deserializer;
+
+ @BeforeEach
+ void setUp() {
+ // Build schema matching {"name": String, "age": Int, "active": Boolean}
+ String[] fieldNames = new String[] {"name", "age", "active"};
+ SeaTunnelDataType<?>[] fieldTypes =
+ new SeaTunnelDataType<?>[] {
+ BasicType.STRING_TYPE, BasicType.INT_TYPE, BasicType.BOOLEAN_TYPE
+ };
+ SeaTunnelRowType rowType = new SeaTunnelRowType(fieldNames, fieldTypes);
+
+ // Standard SeaTunnel JSON Deserializer setup used inside FirebaseSourceReader
+ this.deserializer = new JsonDeserializationSchema(false, false, rowType);
+ }
+
+ @Test
+ void testDeserializeSingleRecordJson() throws Exception {
+ String jsonPayload = "{\"name\": \"john doe\", \"age\": 22, \"active\": true}";
+
+ SeaTunnelRow row = deserializer.deserialize(jsonPayload.getBytes(StandardCharsets.UTF_8));
+
+ assertNotNull(row);
+ assertEquals("john doe", row.getField(0));
+ assertEquals(22, row.getField(1));
+ assertEquals(true, row.getField(2));
+ }
+
+ @Test
+ void testDeserializeJsonWithMissingFields() throws Exception {
+ // Sparse JSON record (active missing)
+ String jsonPayload = "{\"name\": \"my name\", \"age\": 30}";
+
+ SeaTunnelRow row = deserializer.deserialize(jsonPayload.getBytes(StandardCharsets.UTF_8));
+
+ assertNotNull(row);
+ assertEquals("my name", row.getField(0));
+ assertEquals(30, row.getField(1));
+ assertEquals(null, row.getField(2)); // Missing fields map gracefully to null
+ }
+
+ @Test
+ void testDeserializeNonAsciiJsonRow() throws Exception {
+ String jsonPayload = "{\"name\":\"اسم عربي\" , \"age\": 44,\"active\":true}";
+ SeaTunnelRow row = deserializer.deserialize(jsonPayload.getBytes(StandardCharsets.UTF_8));
+
+ assertNotNull(row);
+ assertEquals("اسم عربي", row.getField(0));
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReaderTest.java b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReaderTest.java
new file mode 100644
index 0000000000..26379d7a00
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceReaderTest.java
@@ -0,0 +1,425 @@
+/*
+ * 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.firebase.source;
+
+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.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.common.utils.SeaTunnelException;
+import org.apache.seatunnel.connectors.seatunnel.firebase.client.FirebaseHttpClient;
+import org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+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 FirebaseSourceReaderTest {
+ private SourceReader.Context mockContext;
+ private Collector<SeaTunnelRow> mockCollector;
+ private FirebaseHttpClient mockHttpClient;
+ private CatalogTable catalogTable;
+ private ReadonlyConfig config;
+
+ @BeforeEach
+ void setUp() {
+ mockContext = mock(SourceReader.Context.class);
+ mockCollector = mock(Collector.class);
+ mockHttpClient = mock(FirebaseHttpClient.class);
+
+ // Build ReadonlyConfig
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ config = ReadonlyConfig.fromMap(configMap);
+
+ // Build CatalogTable with schema matching {"name": String, "title": String}
+ TableSchema tableSchema =
+ TableSchema.builder()
+ .column(
+ PhysicalColumn.of(
+ "name",
+ BasicType.STRING_TYPE,
+ (Long) null,
+ true,
+ null,
+ null))
+ .column(
+ PhysicalColumn.of(
+ "title",
+ BasicType.STRING_TYPE,
+ (Long) null,
+ true,
+ null,
+ null))
+ .build();
+
+ catalogTable =
+ CatalogTable.of(
+ TableIdentifier.of("default", "default", "users"),
+ tableSchema,
+ Collections.emptyMap(),
+ Collections.emptyList(),
+ "Firebase Users Table");
+ }
+
+ @Test
+ void testPollNextReadsKeysAndEmitsRows() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("split_0", "users", Collections.singletonList("user_101"));
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData("user_101"))
+ .thenReturn("{\"name\": \"john doe\", \"title\": \"Backend Engineer\"}");
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(captor.capture());
+
+ SeaTunnelRow row = captor.getValue();
+ assertNotNull(row);
+ assertEquals("john doe", row.getField(0));
+ assertEquals("Backend Engineer", row.getField(1));
+
+ verify(mockContext, never()).signalNoMoreElement();
+ }
+
+ @Test
+ void testPollNextSinglePathUnnestsRecordMap() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split = new FirebaseSourceSplit("split_single", "users");
+ reader.addSplits(Collections.singletonList(split));
+
+ String mapJson =
+ "{"
+ + "\"user_101\": {\"name\": \"any name 1\", \"title\": \"Backend Engineer\"},"
+ + "\"user_102\": {\"name\": \"any name 2\", \"title\": \"manager\"}"
+ + "}";
+ when(mockHttpClient.fetchNodeData(null)).thenReturn(mapJson);
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(2)).collect(captor.capture());
+
+ List<SeaTunnelRow> rows = captor.getAllValues();
+ assertEquals("any name 1", rows.get(0).getField(0));
+ assertEquals("Backend Engineer", rows.get(0).getField(1));
+ assertEquals("any name 2", rows.get(1).getField(0));
+ assertEquals("manager", rows.get(1).getField(1));
+ }
+
+ @Test
+ void testSignalNoMoreElementWhenSplitsEmptyAndNoMoreSplitsSet() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ // 1. Signal no more splits from enumerator
+ reader.handleNoMoreSplits();
+
+ // 2. Poll next on empty queue
+ reader.pollNext(mockCollector);
+
+ // 3. Verify signalNoMoreElement was delivered to Zeta engine
+ verify(mockContext, times(1)).signalNoMoreElement();
+ }
+
+ @Test
+ void testPollNextWithUndeclaredObjectKeyDoesNotDiscardRow() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ // Split containing declared schema fields ("name", "title") and an undeclared object key
+ // ("audit")
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit(
+ "split_0", "users", Arrays.asList("name", "title", "audit"));
+ reader.addSplits(Collections.singletonList(split));
+
+ // Mock HTTP responses for each key in the split
+ when(mockHttpClient.fetchNodeData("name")).thenReturn("\"john doe\"");
+ when(mockHttpClient.fetchNodeData("title")).thenReturn("\"Backend Engineer\"");
+ // "audit" is NOT in catalogTable schema and returns a nested JSON object payload
+ when(mockHttpClient.fetchNodeData("audit"))
+ .thenReturn("{\"created_at\": 1700000000, \"updated_by\": \"system\"}");
+
+ // Act
+ reader.pollNext(mockCollector);
+
+ // Assert: Verify that the row for declared fields was captured and emitted,
+ // and was NOT silently discarded due to the presence of the "audit" JSON object key.
+ ArgumentCaptor<SeaTunnelRow> rowCaptor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(rowCaptor.capture());
+
+ SeaTunnelRow emittedRow = rowCaptor.getValue();
+ assertNotNull(emittedRow);
+ assertEquals("john doe", emittedRow.getField(0));
+ assertEquals("Backend Engineer", emittedRow.getField(1));
+ }
+
+ @Test
+ void testPollNextWithNullAndLiteralNullPayloads() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("split_nulls", "users", Arrays.asList("key1", "key2"));
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData("key1")).thenReturn(null);
+ when(mockHttpClient.fetchNodeData("key2")).thenReturn(" null ");
+
+ reader.pollNext(mockCollector);
+
+ verify(mockCollector, never()).collect(any(SeaTunnelRow.class));
+ }
+
+ @Test
+ void testPollNextSinglePathNullResponse() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split = new FirebaseSourceSplit("split_single_null", "users");
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData(null)).thenReturn("null");
+
+ reader.pollNext(mockCollector);
+
+ verify(mockCollector, never()).collect(any(SeaTunnelRow.class));
+ }
+
+ @Test
+ void testPollNextSinglePathReturnsJsonArrayOfRecords() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split = new FirebaseSourceSplit("split_array", "users");
+ reader.addSplits(Collections.singletonList(split));
+
+ String arrayJson =
+ "["
+ + "{\"name\": \"Alice\", \"title\": \"Lead\"},"
+ + "{\"name\": \"Bob\", \"title\": \"Dev\"}"
+ + "]";
+ when(mockHttpClient.fetchNodeData(null)).thenReturn(arrayJson);
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(2)).collect(captor.capture());
+
+ List<SeaTunnelRow> rows = captor.getAllValues();
+ assertEquals("Alice", rows.get(0).getField(0));
+ assertEquals("Bob", rows.get(1).getField(0));
+ }
+
+ @Test
+ void testPollNextWithUndeclaredArrayKey() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit(
+ "split_arr_key", "users", Arrays.asList("name", "team_members"));
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData("name")).thenReturn("\"Project X\"");
+ when(mockHttpClient.fetchNodeData("team_members"))
+ .thenReturn("[{\"name\": \"Member 1\", \"title\": \"QA\"}]");
+
+ reader.pollNext(mockCollector);
+
+ // Expect 1 row from reconstructedMap + 1 row un-nested from the array = 2 rows
+ verify(mockCollector, times(2)).collect(any(SeaTunnelRow.class));
+ }
+
+ @Test
+ void testProcessJsonPayloadWithPrimitiveThrowsException() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split = new FirebaseSourceSplit("split_prim", "users");
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData(null)).thenReturn("\"just a string payload\"");
+
+ assertThrows(SeaTunnelException.class, () -> reader.pollNext(mockCollector));
+ }
+
+ @Test
+ void testPollNextFallbackToRawStringOnParseError() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("split_raw", "users", Collections.singletonList("name"));
+ reader.addSplits(Collections.singletonList(split));
+
+ // Malformed JSON value for name field
+ when(mockHttpClient.fetchNodeData("name")).thenReturn("unquoted_raw_string");
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(captor.capture());
+ assertEquals("unquoted_raw_string", captor.getValue().getField(0));
+ }
+
+ @Test
+ void testPollNextDeeplyNestedContainerUnnesting() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split = new FirebaseSourceSplit("split_deep", "users");
+ reader.addSplits(Collections.singletonList(split));
+
+ // Deeply nested structure: root -> department -> team -> user record
+ String deepJson =
+ "{"
+ + "\"engineering\": {"
+ + " \"backend\": {"
+ + " \"user_999\": {\"name\": \"Charlie\", \"title\": \"Architect\"}"
+ + " }"
+ + "}"
+ + "}";
+ when(mockHttpClient.fetchNodeData(null)).thenReturn(deepJson);
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(captor.capture());
+ assertEquals("Charlie", captor.getValue().getField(0));
+ assertEquals("Architect", captor.getValue().getField(1));
+ }
+
+ @Test
+ void testPollNextProcessesMultipleSplitsSequentially() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split1 =
+ new FirebaseSourceSplit("s1", "users", Collections.singletonList("user_1"));
+ FirebaseSourceSplit split2 =
+ new FirebaseSourceSplit("s2", "users", Collections.singletonList("user_2"));
+
+ reader.addSplits(Arrays.asList(split1, split2));
+
+ when(mockHttpClient.fetchNodeData("user_1"))
+ .thenReturn("{\"name\": \"User 1\", \"title\": \"Dev\"}");
+ when(mockHttpClient.fetchNodeData("user_2"))
+ .thenReturn("{\"name\": \"User 2\", \"title\": \"QA\"}");
+
+ // First poll processes split1
+ reader.pollNext(mockCollector);
+ verify(mockCollector, times(1)).collect(any(SeaTunnelRow.class));
+
+ // Second poll processes split2
+ reader.pollNext(mockCollector);
+ verify(mockCollector, times(2)).collect(any(SeaTunnelRow.class));
+ }
+
+ @Test
+ void testSnapshotStateAndAddSplits() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("s1", "users", Collections.singletonList("k1"));
+
+ reader.addSplits(Collections.singletonList(split));
+ List<FirebaseSourceSplit> state = reader.snapshotState(1L);
+
+ assertNotNull(state);
+ assertEquals(1, state.size());
+ assertEquals("s1", state.get(0).splitId());
+ }
+
+ @Test
+ void testPollNextMergesScalarKeysIntoSingleRow() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("split_scalars", "users", Arrays.asList("name", "title"));
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData("name")).thenReturn("\"Jane Doe\"");
+ when(mockHttpClient.fetchNodeData("title")).thenReturn("\"Data Engineer\"");
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(captor.capture());
+
+ SeaTunnelRow row = captor.getValue();
+ assertEquals("Jane Doe", row.getField(0));
+ assertEquals("Data Engineer", row.getField(1));
+ }
+
+ @Test
+ void testPollNextPreservesNonAsciiCharacters() throws Exception {
+ FirebaseSourceReader reader =
+ new FirebaseSourceReader(mockContext, config, catalogTable, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit(
+ "split_utf8", "users", Collections.singletonList("user_unicode"));
+ reader.addSplits(Collections.singletonList(split));
+
+ when(mockHttpClient.fetchNodeData("user_unicode"))
+ .thenReturn(
+ "{\"name\": \"عربي / 王伟 / René\", \"title\": \"Software Engineer 🚀\"}");
+
+ reader.pollNext(mockCollector);
+
+ ArgumentCaptor<SeaTunnelRow> captor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+ verify(mockCollector, times(1)).collect(captor.capture());
+
+ SeaTunnelRow row = captor.getValue();
+ assertEquals("عربي / 王伟 / René", row.getField(0));
+ assertEquals("Software Engineer 🚀", row.getField(1));
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumeratorTest.java b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumeratorTest.java
new file mode 100644
index 0000000000..d0b11fd562
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-firebase/src/test/java/org/apache/seatunnel/connectors/seatunnel/firebase/source/FirebaseSourceSplitEnumeratorTest.java
@@ -0,0 +1,309 @@
+/*
+ * 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.firebase.source;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.source.SourceSplitEnumerator;
+import org.apache.seatunnel.connectors.seatunnel.firebase.client.FirebaseHttpClient;
+import org.apache.seatunnel.connectors.seatunnel.firebase.config.FirebaseSourceOptions;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+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 static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class FirebaseSourceSplitEnumeratorTest {
+ private SourceSplitEnumerator.Context<FirebaseSourceSplit> mockContext;
+ private FirebaseHttpClient mockHttpClient;
+ private ReadonlyConfig config;
+
+ @BeforeEach
+ void setUp() {
+ mockContext = mock(SourceSplitEnumerator.Context.class);
+ mockHttpClient = mock(FirebaseHttpClient.class);
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ config = ReadonlyConfig.fromMap(configMap);
+
+ when(mockContext.currentParallelism()).thenReturn(2);
+ }
+
+ @Test
+ void testAssignSplitsFromRestoredState() throws Exception {
+ // 1. Mock registered reader subtask [0]
+ Set<Integer> readers = new HashSet<>();
+ readers.add(0);
+ when(mockContext.registeredReaders()).thenReturn(readers);
+ when(mockContext.currentParallelism()).thenReturn(1);
+
+ // 2. Build ReadonlyConfig
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(
+ FirebaseSourceOptions.URL.key(), "https://test-50a28-default-rtdb.firebaseio.com");
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+
+ // 3. Build state with pre-created split
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit(
+ "split_key_range_0_0", "users", Collections.singletonList("user_101"));
+ FirebaseSourceState state =
+ new FirebaseSourceState(Collections.singleton(split), new HashSet<>());
+
+ // 4. Instantiate enumerator with restored state
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, state);
+
+ // 5. Execute run() and registerReader()
+ enumerator.run();
+ enumerator.registerReader(0);
+
+ // 6. Assert interactions on mockContext (using batch assignSplits)
+ verify(mockContext, atLeastOnce()).assignSplit(eq(0), Collections.singletonList(any()));
+ verify(mockContext, atLeastOnce()).signalNoMoreSplits(0);
+ assertEquals(0, enumerator.currentUnassignedSplitSize());
+ }
+
+ @Test
+ void testRunKeyDiscoveryAndAssignSplits() throws Exception {
+ // 1. Mock registered reader subtask [0]
+ Set<Integer> readers = new HashSet<>();
+ readers.add(0);
+ when(mockContext.registeredReaders()).thenReturn(readers);
+ when(mockContext.currentParallelism()).thenReturn(2);
+
+ // 2. Mock HTTP client key response
+ when(mockHttpClient.fetchShallowKeys()).thenReturn(Arrays.asList("user_101", "user_102"));
+
+ // 3. Build ReadonlyConfig
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ configMap.put(FirebaseSourceOptions.URL.key(), "https://test-db.firebaseio.com");
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+
+ // 4. Instantiate enumerator with mocked HTTP client
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, mockHttpClient);
+
+ // 5. Register reader subtask 0
+ enumerator.registerReader(0);
+
+ // 6. Execute run() — triggers shallow scan + partitioning + assignSplits()
+ enumerator.run();
+
+ // 7. Verify splits were assigned to reader 0 and NO_MORE_SPLITS was signaled
+ verify(mockContext, atLeastOnce()).assignSplit(eq(0), Collections.singletonList(any()));
+ verify(mockContext, atLeastOnce()).signalNoMoreSplits(0);
+ assertEquals(0, enumerator.currentUnassignedSplitSize());
+ }
+
+ @Test
+ void testFallbackToSinglePathSplitWhenKeysEmpty() throws Exception {
+ Set<Integer> readers = new HashSet<>();
+ readers.add(0);
+ when(mockContext.registeredReaders()).thenReturn(readers);
+ when(mockContext.currentParallelism()).thenReturn(1);
+
+ // Simulate empty keys or exception fallback
+ when(mockHttpClient.fetchShallowKeys()).thenReturn(Collections.emptyList());
+
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, mockHttpClient);
+
+ enumerator.registerReader(0);
+ enumerator.run();
+
+ // Verify single path fallback split assignment
+ verify(mockContext, atLeastOnce()).assignSplit(eq(0), Collections.singletonList(any()));
+ verify(mockContext, atLeastOnce()).signalNoMoreSplits(0);
+ assertEquals(0, enumerator.currentUnassignedSplitSize());
+ }
+
+ @Test
+ void testAddSplitsBackReQueuesAndReAssigns() throws Exception {
+ Set<Integer> readers = new HashSet<>();
+ readers.add(0);
+ when(mockContext.registeredReaders()).thenReturn(readers);
+
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put(FirebaseSourceOptions.PATH.key(), "users");
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, mockHttpClient);
+
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit(
+ "split_failed_1", "users", Collections.singletonList("user_101"));
+
+ // Simulate subtask failover returning split back
+ enumerator.addSplitsBack(Collections.singletonList(split), 0);
+
+ // Verify returned split gets re-assigned immediately to available reader subtask 0
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<FirebaseSourceSplit>> captor = ArgumentCaptor.forClass(List.class);
+ verify(mockContext, atLeastOnce()).assignSplit(eq(0), captor.capture());
+
+ List<FirebaseSourceSplit> assignedSplits = captor.getValue();
+ assertEquals(1, assignedSplits.size());
+ assertEquals("split_failed_1", assignedSplits.get(0).splitId());
+ assertEquals(0, enumerator.currentUnassignedSplitSize());
+ }
+
+ @Test
+ public void testRestorePathSignalsNoMoreSplitsToLateRegisteringReaders() throws Exception {
+ // 1. Mock Context
+ @SuppressWarnings("unchecked")
+ SourceSplitEnumerator.Context<FirebaseSourceSplit> mockContext =
+ mock(SourceSplitEnumerator.Context.class);
+
+ // 2. Prepare restored state with 1 pending split
+ FirebaseSourceSplit restoredSplit = new FirebaseSourceSplit("split_restored_1", "users");
+ Set<FirebaseSourceSplit> pendingSplits =
+ new HashSet<>(Collections.singletonList(restoredSplit));
+ Set<String> assignedSplitIds = new HashSet<>();
+ FirebaseSourceState restoredState =
+ new FirebaseSourceState(pendingSplits, assignedSplitIds);
+
+ // 3. Construct ReadonlyConfig with both "url" and "path"
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put("url", "https://test-db.firebaseio.com");
+ configMap.put("path", "users");
+ ReadonlyConfig config = ReadonlyConfig.fromMap(configMap);
+
+ // 4. Construct enumerator from state
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, restoredState);
+
+ // 5. Step 1: Reader 0 registers first
+ Set<Integer> registeredReaders = new HashSet<>(Collections.singletonList(0));
+ when(mockContext.registeredReaders()).thenReturn(registeredReaders);
+
+ enumerator.registerReader(0);
+
+ // Verify Reader 0 received the split and NO_MORE_SPLITS signal
+ ArgumentCaptor<List<FirebaseSourceSplit>> splitCaptor = ArgumentCaptor.forClass(List.class);
+ verify(mockContext).assignSplit(eq(0), splitCaptor.capture());
+ assertEquals(1, splitCaptor.getValue().size());
+ assertEquals("split_restored_1", splitCaptor.getValue().get(0).splitId());
+ verify(mockContext).signalNoMoreSplits(eq(0));
+
+ // 6. Step 2: Reader 1 registers later (pendingSplits is now empty)
+ registeredReaders.add(1); // registeredReaders is now {0, 1}
+ when(mockContext.registeredReaders()).thenReturn(registeredReaders);
+
+ enumerator.registerReader(1);
+
+ // 7. Assertion: Reader 1 MUST receive NO_MORE_SPLITS signal despite pendingSplits being
+ // empty
+ verify(mockContext).signalNoMoreSplits(eq(1));
+ }
+
+ @Test
+ void testConcurrentStateAccessDoesNotThrowException() throws Exception {
+ FirebaseSourceSplitEnumerator enumerator =
+ new FirebaseSourceSplitEnumerator(mockContext, config, mockHttpClient);
+
+ int iterations = 1000;
+ int numThreads = 3;
+ ExecutorService executor = Executors.newFixedThreadPool(numThreads);
+ CountDownLatch startLatch = new CountDownLatch(1);
+
+ List<Future<?>> futures = new ArrayList<>();
+
+ // Thread 1: Simulates checkpointing thread calling snapshotState()
+ futures.add(
+ executor.submit(
+ () -> {
+ startLatch.await();
+ for (int i = 0; i < iterations; i++) {
+ FirebaseSourceState state = enumerator.snapshotState(i);
+ assertNotNull(state);
+ }
+ return null;
+ }));
+
+ // Thread 2: Simulates failover/retry thread calling addSplitsBack()
+ futures.add(
+ executor.submit(
+ () -> {
+ startLatch.await();
+ for (int i = 0; i < iterations; i++) {
+ FirebaseSourceSplit split =
+ new FirebaseSourceSplit("split_concurrent_" + i, "users");
+ enumerator.addSplitsBack(Collections.singletonList(split), 0);
+ }
+ return null;
+ }));
+
+ // Thread 3: Simulates Hazelcast operation thread registering readers & requesting splits
+ futures.add(
+ executor.submit(
+ () -> {
+ startLatch.await();
+ for (int i = 0; i < iterations; i++) {
+ int subtaskId = i % 2;
+ enumerator.registerReader(subtaskId);
+ enumerator.handleSplitRequest(subtaskId);
+ }
+ return null;
+ }));
+
+ // Release all threads simultaneously to create maximum contention
+ startLatch.countDown();
+
+ // Verify that none of the threads threw a ConcurrentModificationException
+ for (Future<?> future : futures) {
+ assertDoesNotThrow(
+ () -> future.get(10, TimeUnit.SECONDS),
+ "Thread execution threw an exception due to a race condition or lock missing");
+ }
+
+ executor.shutdown();
+ assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ }
+}
diff --git a/seatunnel-connectors-v2/pom.xml b/seatunnel-connectors-v2/pom.xml
index c764541bb1..208749b90c 100644
--- a/seatunnel-connectors-v2/pom.xml
+++ b/seatunnel-connectors-v2/pom.xml
@@ -104,6 +104,7 @@
<module>connector-edge-socket</module>
<module>connector-azurecosmosdb</module>
<module>connector-nats-jetstream</module>
+ <module>connector-firebase</module>
</modules>
<dependencyManagement>
diff --git a/seatunnel-dist/pom.xml b/seatunnel-dist/pom.xml
index 2f126d25bf..627da6aec9 100644
--- a/seatunnel-dist/pom.xml
+++ b/seatunnel-dist/pom.xml
@@ -434,6 +434,12 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-firebase</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.seatunnel</groupId>
<artifactId>connector-hudi</artifactId>
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/pom.xml b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/pom.xml
new file mode 100644
index 0000000000..76b3bb95d1
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/pom.xml
@@ -0,0 +1,67 @@
+<?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 http://maven.apache.org/maven-v4_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-firebase-e2e</artifactId>
+ <name>SeaTunnel : E2E : Connector V2 : Firebase</name>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.13.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-firebase</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.testcontainers</groupId>
+ <artifactId>testcontainers</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+
+ <url>http://maven.apache.org</url>
+</project>
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/java/org/apache/seatunnel/e2e/connector/firebase/FirebaseSourceIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/java/org/apache/seatunnel/e2e/connector/firebase/FirebaseSourceIT.java
new file mode 100644
index 0000000000..4659bf2534
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/java/org/apache/seatunnel/e2e/connector/firebase/FirebaseSourceIT.java
@@ -0,0 +1,178 @@
+/*
+ * 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.firebase;
+
+import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.TestSuiteBase;
+import org.apache.seatunnel.e2e.common.container.TestContainer;
+
+import org.awaitility.Awaitility;
+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.testcontainers.Testcontainers;
+import org.testcontainers.containers.Container;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.containers.wait.strategy.Wait;
+import org.testcontainers.utility.DockerImageName;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Slf4j
+public class FirebaseSourceIT extends TestSuiteBase implements TestResource {
+ private static final String FIREBASE_EMULATOR_IMAGE = "andreysenov/firebase-tools:latest";
+ private static final int REALTIME_DATABASE_EMULATOR_PORT = 9000;
+
+ private GenericContainer<?> firebaseEmulator;
+ private String emulatorHostUrl;
+ private int mappedPort;
+
+ @BeforeAll
+ @Override
+ public void startUp() throws Exception {
+ log.info("Starting Firebase Realtime Database Emulator container...");
+
+ // Define inline firebase.json configuration to bind database emulator to 0.0.0.0
+ String firebaseJson =
+ "{"
+ + " \"emulators\": {"
+ + " \"database\": {"
+ + " \"host\": \"0.0.0.0\","
+ + " \"port\": 9000"
+ + " }"
+ + " }"
+ + "}";
+
+ // Rule 1: Dynamic Port Assignment via Testcontainers
+ firebaseEmulator =
+ new GenericContainer<>(DockerImageName.parse(FIREBASE_EMULATOR_IMAGE))
+ .withExposedPorts(REALTIME_DATABASE_EMULATOR_PORT)
+ // Write firebase.json on startup and run the emulator
+ .withCommand(
+ "sh",
+ "-c",
+ "echo '"
+ + firebaseJson
+ + "' > firebase.json && firebase emulators:start --only database --project test-project")
+ .waitingFor(
+ Wait.forHttp("/.json")
+ .forStatusCode(200)
+ .withStartupTimeout(Duration.ofSeconds(60)))
+ .withLogConsumer(new Slf4jLogConsumer(log));
+
+ firebaseEmulator.start();
+
+ String host = firebaseEmulator.getHost();
+ this.mappedPort = firebaseEmulator.getMappedPort(REALTIME_DATABASE_EMULATOR_PORT);
+
+ Testcontainers.exposeHostPorts(mappedPort);
+ emulatorHostUrl = String.format("http://%s:%d", host, mappedPort);
+
+ log.info(
+ "Firebase Emulator initialized successfully at dynamic endpoint: {}",
+ emulatorHostUrl);
+
+ seedTestData();
+ }
+
+ private void seedTestData() throws Exception {
+ log.info("Seeding structured test dataset to Firebase Emulator REST API...");
+
+ String jsonPayload =
+ "{"
+ + " \"user_1\": {\"id\": 101, \"name\": \"Any Name\", \"score\": 98.5, \"is_active\": true, \"timestamp\": 1700000000000},"
+ + " \"user_2\": {\"id\": 102, \"name\": \"Apache SeaTunnel\", \"score\": 100.0, \"is_active\": false, \"timestamp\": 1700000005000}"
+ + "}";
+
+ String putEndpointUrl = emulatorHostUrl + "/users.json?ns=test-project";
+
+ // Wait until PUT returns 200 OK
+ Awaitility.await()
+ .atMost(30, TimeUnit.SECONDS)
+ .pollInterval(1, TimeUnit.SECONDS)
+ .until(() -> executePut(putEndpointUrl, jsonPayload) == 200);
+
+ log.info("Successfully seeded test records into /users.json?ns=test-project");
+ }
+
+ private int executePut(String urlStr, String jsonBody) {
+ HttpURLConnection connection = null;
+ try {
+ URL url = URI.create(urlStr).toURL();
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("PUT");
+ connection.setDoOutput(true);
+ connection.setRequestProperty("Content-Type", "application/json");
+ connection.setConnectTimeout(5000);
+ connection.setReadTimeout(5000);
+
+ try (OutputStream os = connection.getOutputStream()) {
+ byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
+ os.write(input, 0, input.length);
+ }
+ return connection.getResponseCode();
+ } catch (Exception e) {
+ log.warn("Failed to seed data via PUT request to {}: {}", urlStr, e.getMessage());
+ return -1;
+ } finally {
+ if (connection != null) {
+ connection.disconnect();
+ }
+ }
+ }
+
+ @TestTemplate
+ public void testFirebaseSourceToAssertSink(TestContainer container) throws Exception {
+ log.info("Executing Firebase Source E2E Job execution on container engine...");
+ String targetUrl = String.format("http://host.testcontainers.internal:%d", mappedPort);
+
+ List<String> variables = Collections.singletonList("URL=" + targetUrl);
+
+ Container.ExecResult execResult =
+ container.executeJob("/firebase_source_to_assert.conf", variables);
+
+ Assertions.assertEquals(
+ 0,
+ execResult.getExitCode(),
+ "SeaTunnel job failed to execute. Error output: " + execResult.getStderr());
+
+ log.info("Firebase Source E2E integration test executed successfully.");
+ }
+
+ @AfterAll
+ @Override
+ public void tearDown() throws Exception {
+ if (firebaseEmulator != null) {
+ log.info("Stopping Firebase Emulator container and freeing bound host ports...");
+ firebaseEmulator.stop();
+ firebaseEmulator = null;
+ }
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/resources/firebase_source_to_assert.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/resources/firebase_source_to_assert.conf
new file mode 100644
index 0000000000..452e5f7c05
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-firebase-e2e/src/test/resources/firebase_source_to_assert.conf
@@ -0,0 +1,103 @@
+#
+# 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 {
+ Firebase {
+ url = ${URL}
+ path = "users"
+ timeout_ms = 10000
+
+ query_params = {
+ ns = "test-project"
+ }
+
+ schema = {
+ fields {
+ id = "INT"
+ name = "STRING"
+ score = "DOUBLE"
+ is_active = "BOOLEAN"
+ timestamp = "BIGINT"
+ }
+ }
+ }
+}
+
+sink {
+ Assert {
+ rules {
+ row_rules = [
+ {
+ rule_type = MAX_ROW
+ rule_value = 2
+ },
+ {
+ rule_type = MIN_ROW
+ rule_value = 2
+ }
+ ]
+
+ field_rules = [
+ {
+ field_name = "id"
+ field_type = "INT"
+ field_value = [
+ { rule_type = NOT_NULL },
+ { rule_type = MIN, rule_value = 101 },
+ { rule_type = MAX, rule_value = 102 }
+ ]
+ },
+ {
+ field_name = "name"
+ field_type = "STRING"
+ field_value = [
+ { rule_type = NOT_NULL }
+ ]
+ },
+ {
+ field_name = "score"
+ field_type = "DOUBLE"
+ field_value = [
+ { rule_type = NOT_NULL },
+ { rule_type = MIN, rule_value = 98.0 },
+ { rule_type = MAX, rule_value = 100.0 }
+ ]
+ },
+ {
+ field_name = "is_active"
+ field_type = "BOOLEAN"
+ field_value = [
+ { rule_type = NOT_NULL }
+ ]
+ },
+ {
+ field_name = "timestamp"
+ field_type = "BIGINT"
+ field_value = [
+ { rule_type = NOT_NULL },
+ { rule_type = MIN, rule_value = 1700000000000 }
+ ]
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml b/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
index 61324e27d3..8b09ffffed 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/pom.xml
@@ -105,6 +105,7 @@
<module>connector-bigquery-e2e</module>
<module>connector-nats-jetstream-e2e</module>
<module>connector-couchbase-e2e</module>
+ <module>connector-firebase-e2e</module>
</modules>
<properties>