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-12856-9f741b9c64220db31bd94c62dd0749d0b71e9358
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit 6191598c2995bf486eb7c8c725978632db288c5a
Author: Goutam Adwant <[email protected]>
AuthorDate: Fri Nov 6 02:07:15 2026 +0000

    [Docs][Zeta] Add OpenAPI contract for two REST v2 read endpoints (#12856)
    
    Signed-off-by: Goutam Adwant <[email protected]>
---
 .dlc.json                                          |   6 +
 docs/en/engines/zeta/openapi-v2.yaml               | 190 +++++++++++++++++
 docs/en/engines/zeta/rest-api-v2.md                |   2 +
 docs/zh/engines/zeta/rest-api-v2.md                |   2 +
 .../engine/server/rest/RestApiHttpBasicTest.java   | 100 +++++++++
 .../engine/server/rest/TestOpenApiV2RouteSync.java | 228 +++++++++++++++++++++
 .../rest/servlet/WorkerResourceServletTest.java    |  17 ++
 7 files changed, 545 insertions(+)

diff --git a/.dlc.json b/.dlc.json
index bb9dfad7ac..b7cb2f4d23 100644
--- a/.dlc.json
+++ b/.dlc.json
@@ -1,4 +1,10 @@
 {
+  "replacementPatterns": [
+    {
+      "pattern": "^@site/docs/",
+      "replacement": "{{BASEURL}}/docs/en/"
+    }
+  ],
   "ignorePatterns": [
     {
       "pattern": "^http://localhost";
diff --git a/docs/en/engines/zeta/openapi-v2.yaml 
b/docs/en/engines/zeta/openapi-v2.yaml
new file mode 100644
index 0000000000..687a7bf45a
--- /dev/null
+++ b/docs/en/engines/zeta/openapi-v2.yaml
@@ -0,0 +1,190 @@
+# 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.
+
+openapi: 3.1.0
+info:
+  title: SeaTunnel Zeta REST v2 (read-only subset)
+  version: 0.1.0
+  description: >-
+    This initial contract covers only GET /overview and GET /resource/workers.
+    Other REST v2 endpoints are not yet described. The YAML is maintained with
+    the Jetty servlet routes and response tests in this repository.
+servers:
+  - url: http://localhost:8080
+    description: >-
+      Example only. Set the scheme, host, port, and configured context path for
+      your running Zeta REST service before using a generated client. Use HTTPS
+      when sending Basic authentication credentials beyond localhost.
+security:
+  - basicAuth: []
+  - {}
+paths:
+  /overview:
+    get:
+      operationId: getOverview
+      summary: Get cluster overview
+      description: >-
+        Optional query keys filter the worker and slot totals by worker tags.
+        Job counts are cluster-wide. Count fields are JSON strings in this
+        servlet's current response, even though their source fields are 
numeric.
+      parameters:
+        - name: tags
+          in: query
+          required: false
+          description: >-
+            Free-form worker tag keys and string values, serialized as
+            key=value pairs such as region=west&team=data. There is no literal
+            tags query key.
+          style: form
+          explode: true
+          schema:
+            type: object
+            additionalProperties:
+              type: string
+      responses:
+        '200':
+          description: Current cluster overview.
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/Overview'
+        '401':
+          description: Basic authentication is enabled and credentials are 
missing or invalid.
+        '500':
+          description: The server could not complete the request; error bodies 
vary.
+  /resource/workers:
+    get:
+      operationId: getWorkerResources
+      summary: Get worker resource snapshot
+      description: >-
+        Returns the latest worker resource projection. During a master
+        transition, available is false and workers is empty; HTTP 200 still
+        indicates a successfully delivered snapshot.
+      responses:
+        '200':
+          description: Point-in-time worker resource snapshot.
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/WorkerResourceSnapshot'
+        '401':
+          description: Basic authentication is enabled and credentials are 
missing or invalid.
+        '500':
+          description: The server could not complete the request; error bodies 
vary.
+components:
+  securitySchemes:
+    basicAuth:
+      type: http
+      scheme: basic
+      description: Optional; configured on the Zeta Jetty service.
+  schemas:
+    Overview:
+      type: object
+      required:
+        - projectVersion
+        - gitCommitAbbrev
+        - totalSlot
+        - unassignedSlot
+        - runningJobs
+        - finishedJobs
+        - failedJobs
+        - pendingJobs
+        - cancelledJobs
+        - workers
+      properties:
+        projectVersion:
+          type: string
+        gitCommitAbbrev:
+          type: string
+        totalSlot:
+          $ref: '#/components/schemas/DecimalCountString'
+        unassignedSlot:
+          $ref: '#/components/schemas/DecimalCountString'
+        runningJobs:
+          $ref: '#/components/schemas/DecimalCountString'
+        finishedJobs:
+          $ref: '#/components/schemas/DecimalCountString'
+        failedJobs:
+          $ref: '#/components/schemas/DecimalCountString'
+        pendingJobs:
+          $ref: '#/components/schemas/DecimalCountString'
+        cancelledJobs:
+          $ref: '#/components/schemas/DecimalCountString'
+        workers:
+          $ref: '#/components/schemas/DecimalCountString'
+    DecimalCountString:
+      type: string
+      pattern: '^[0-9]+$'
+      description: A non-negative count serialized as a decimal JSON string.
+    WorkerResourceSnapshot:
+      type: object
+      required: [available, collectedAt, workers]
+      properties:
+        available:
+          type: boolean
+          description: False when the resource projection could not be 
collected.
+        collectedAt:
+          type: integer
+          format: int64
+          description: Snapshot collection time in Unix epoch milliseconds.
+        workers:
+          type: array
+          items:
+            $ref: '#/components/schemas/WorkerResourceDiagnostic'
+    WorkerResourceDiagnostic:
+      type: object
+      required: [address, tags, totalSlots, freeSlots, usedSlots, dynamicSlot, 
runningJobIds]
+      properties:
+        address:
+          type: string
+        tags:
+          type: object
+          additionalProperties:
+            type: string
+        totalSlots:
+          type: integer
+          format: int32
+          description: For dynamic slots, current assigned plus unassigned 
slots.
+        freeSlots:
+          type: integer
+          format: int32
+        usedSlots:
+          type: integer
+          format: int32
+        dynamicSlot:
+          type: boolean
+        totalCpuCores:
+          type: integer
+          format: int32
+        availableCpuCores:
+          type: integer
+          format: int32
+        totalHeapMemoryBytes:
+          type: integer
+          format: int64
+        availableHeapMemoryBytes:
+          type: integer
+          format: int64
+        cpuUsage:
+          type: number
+          format: double
+        memUsage:
+          type: number
+          format: double
+        runningJobIds:
+          type: array
+          items:
+            type: integer
+            format: int64
diff --git a/docs/en/engines/zeta/rest-api-v2.md 
b/docs/en/engines/zeta/rest-api-v2.md
index 91345d1c65..e20bbaec5d 100644
--- a/docs/en/engines/zeta/rest-api-v2.md
+++ b/docs/en/engines/zeta/rest-api-v2.md
@@ -90,6 +90,8 @@ Please refer [security](security.md)
 
 ## API reference
 
+The [OpenAPI 3.1 contract for the read-only REST v2 subset](openapi-v2.yaml) 
currently covers `GET /overview` and `GET /resource/workers` only. Other 
endpoints below remain documented here but are not yet included in the 
machine-readable contract. The spec is maintained alongside the servlet route 
registrations and response tests. Configure the generated client's base URL for 
your listener, port, and optional context path. Basic authentication depends on 
your server configuration; use HT [...]
+
 ### Get Connector Option Rules
 
 <details>
diff --git a/docs/zh/engines/zeta/rest-api-v2.md 
b/docs/zh/engines/zeta/rest-api-v2.md
index 404db94d8d..32f3bcc565 100644
--- a/docs/zh/engines/zeta/rest-api-v2.md
+++ b/docs/zh/engines/zeta/rest-api-v2.md
@@ -85,6 +85,8 @@ seatunnel:
 
 ## API参考
 
+[REST v2 只读接口的 OpenAPI 3.1 规范](@site/docs/engines/zeta/openapi-v2.yaml)目前仅覆盖 
`GET /overview` 和 `GET /resource/workers`。下文的其他接口仍有文档,但尚未纳入机器可读规范。该规范与 Servlet 
路由注册及响应测试一起维护。使用生成的客户端时,请按实际地址、端口及可选的上下文路径设置基础 URL。是否使用 Basic 
认证取决于服务端配置;向非本机发送凭据时请使用 HTTPS。
+
 ### 获取 Connector 的 OptionRule
 
 <details>
diff --git 
a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiHttpBasicTest.java
 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiHttpBasicTest.java
index 8206bb14b9..1f1d2cde2e 100644
--- 
a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiHttpBasicTest.java
+++ 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiHttpBasicTest.java
@@ -17,6 +17,8 @@
 
 package org.apache.seatunnel.engine.server.rest;
 
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.seatunnel.shade.org.apache.commons.lang3.StringUtils;
 
 import org.apache.seatunnel.engine.common.config.SeaTunnelConfig;
@@ -30,6 +32,7 @@ import org.apache.seatunnel.engine.server.SeaTunnelServer;
 import org.apache.seatunnel.engine.server.SeaTunnelServerStarter;
 import org.apache.seatunnel.engine.server.TestUtils;
 
+import org.awaitility.Awaitility;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeAll;
@@ -47,15 +50,20 @@ import java.nio.charset.StandardCharsets;
 import java.util.Base64;
 import java.util.Base64.Encoder;
 import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
 import static 
org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_LOGS;
 import static 
org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_OVERVIEW;
+import static 
org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_WORKER_RESOURCES;
 
 /** Test for Rest API with Basic. */
 class RestApiHttpBasicTest extends AbstractSeaTunnelServerTest {
 
     private static final int HTTP_PORT = 18081;
+    private static final int HTTP_TIMEOUT_MILLIS = 10_000;
     private static final Long JOB_1 = System.currentTimeMillis() + 1L;
     private static final String USER = "admin";
     private static final String PASS = "admin";
@@ -63,6 +71,7 @@ class RestApiHttpBasicTest extends 
AbstractSeaTunnelServerTest {
 
     private static final String AUTHORIZATION_HEADER = "Authorization";
     private static final String BASIC_PREFIX = "Basic ";
+    private static final ObjectMapper JSON = new ObjectMapper();
 
     @Override
     @BeforeAll
@@ -124,6 +133,97 @@ class RestApiHttpBasicTest extends 
AbstractSeaTunnelServerTest {
         }
     }
 
+    @Test
+    void testDocumentedReadOnlyEndpoints() throws IOException {
+        for (String path : new String[] {REST_URL_OVERVIEW, 
REST_URL_WORKER_RESOURCES}) {
+            HttpURLConnection unauthenticated = null;
+            try {
+                unauthenticated = (HttpURLConnection) new URL(DOMAIN + 
path).openConnection();
+                unauthenticated.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
+                unauthenticated.setReadTimeout(HTTP_TIMEOUT_MILLIS);
+                Assertions.assertEquals(401, 
unauthenticated.getResponseCode(), path);
+                Assertions.assertTrue(
+                        
unauthenticated.getHeaderField("WWW-Authenticate").startsWith("Basic "),
+                        path);
+            } finally {
+                if (unauthenticated != null) {
+                    unauthenticated.disconnect();
+                }
+            }
+        }
+
+        JsonNode overview = getAuthenticatedJson(REST_URL_OVERVIEW);
+        Assertions.assertEquals(
+                Set.of(
+                        "projectVersion",
+                        "gitCommitAbbrev",
+                        "totalSlot",
+                        "unassignedSlot",
+                        "runningJobs",
+                        "finishedJobs",
+                        "failedJobs",
+                        "pendingJobs",
+                        "cancelledJobs",
+                        "workers"),
+                fields(overview));
+        overview.fields()
+                .forEachRemaining(
+                        field ->
+                                Assertions.assertTrue(
+                                        field.getValue().isTextual(), 
field.getKey()));
+
+        JsonNode filteredOverview = getAuthenticatedJson(REST_URL_OVERVIEW + 
"?region=unmatched");
+        Assertions.assertEquals("0", 
filteredOverview.path("workers").asText());
+
+        JsonNode snapshot =
+                Awaitility.await()
+                        .atMost(30, TimeUnit.SECONDS)
+                        .until(
+                                () -> 
getAuthenticatedJson(REST_URL_WORKER_RESOURCES),
+                                value ->
+                                        value.path("available").asBoolean()
+                                                && 
!value.path("workers").isEmpty());
+        Assertions.assertEquals(Set.of("available", "collectedAt", "workers"), 
fields(snapshot));
+        Assertions.assertTrue(snapshot.path("available").isBoolean());
+        Assertions.assertTrue(snapshot.path("collectedAt").isIntegralNumber());
+        Assertions.assertTrue(snapshot.path("workers").isArray());
+        Assertions.assertFalse(snapshot.path("workers").isEmpty());
+        snapshot.path("workers")
+                .forEach(
+                        worker -> {
+                            
Assertions.assertTrue(worker.path("address").isTextual());
+                            
Assertions.assertTrue(worker.path("tags").isObject());
+                            
Assertions.assertTrue(worker.path("totalSlots").isIntegralNumber());
+                            
Assertions.assertTrue(worker.path("freeSlots").isIntegralNumber());
+                            
Assertions.assertTrue(worker.path("usedSlots").isIntegralNumber());
+                            
Assertions.assertTrue(worker.path("dynamicSlot").isBoolean());
+                            
Assertions.assertTrue(worker.path("runningJobIds").isArray());
+                        });
+    }
+
+    private JsonNode getAuthenticatedJson(String path) throws IOException {
+        HttpURLConnection connection = null;
+        try {
+            connection = (HttpURLConnection) new URL(DOMAIN + 
path).openConnection();
+            connection.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
+            connection.setReadTimeout(HTTP_TIMEOUT_MILLIS);
+            setBasicAuth(connection);
+            Assertions.assertEquals(200, connection.getResponseCode(), path);
+            
Assertions.assertTrue(connection.getContentType().startsWith("application/json"),
 path);
+            return JSON.readTree(connection.getInputStream());
+        } finally {
+            if (connection != null) {
+                connection.disconnect();
+            }
+        }
+    }
+
+    private static Set<String> fields(JsonNode node) {
+        Set<String> names = new HashSet<>();
+        node.fieldNames().forEachRemaining(names::add);
+        return names;
+    }
+
     @Test
     void testLogRestApiResponseFailure() throws IOException {
         startJob();
diff --git 
a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/TestOpenApiV2RouteSync.java
 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/TestOpenApiV2RouteSync.java
new file mode 100644
index 0000000000..427918533b
--- /dev/null
+++ 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/TestOpenApiV2RouteSync.java
@@ -0,0 +1,228 @@
+/*
+ * 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.engine.server.rest;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+import 
org.apache.seatunnel.shade.com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
+
+import org.apache.seatunnel.common.utils.JsonUtils;
+import org.apache.seatunnel.engine.server.diagnostic.WorkerResourceDiagnostic;
+import org.apache.seatunnel.engine.server.diagnostic.WorkerResourceSnapshot;
+import 
org.apache.seatunnel.engine.server.resourcemanager.resource.OverviewInfo;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.gson.Gson;
+import com.hazelcast.internal.util.JsonUtil;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class TestOpenApiV2RouteSync {
+
+    private static final Path MODULE_DIR =
+            Path.of(System.getProperty("basedir", 
".")).toAbsolutePath().normalize();
+    private static final Path SOURCE =
+            
MODULE_DIR.resolve("src/main/java/org/apache/seatunnel/engine/server");
+    private static final Path SPEC =
+            
MODULE_DIR.resolve("../../docs/en/engines/zeta/openapi-v2.yaml").normalize();
+    private static final Pattern CONSTANT =
+            Pattern.compile("public static final String 
(REST_URL_[A-Z_]+)\\s*=\\s*\"([^\"]+)\"");
+    private static final Pattern REGISTRATION =
+            Pattern.compile(
+                    
"context\\.addServlet\\(\\s*(\\w+)\\s*,\\s*convertUrlToPath\\((REST_URL_[A-Z_]+)\\)\\s*\\);",
+                    Pattern.DOTALL);
+    private static final Pattern HOLDER =
+            Pattern.compile(
+                    "ServletHolder\\s+(\\w+)\\s*=\\s*new ServletHolder\\(new 
(\\w+)\\(",
+                    Pattern.DOTALL);
+    private static final Map<String, String> COVERED_ROUTES =
+            Map.of(
+                    "REST_URL_OVERVIEW", "OverviewServlet",
+                    "REST_URL_WORKER_RESOURCES", "WorkerResourceServlet");
+    private static final ObjectMapper JSON = new ObjectMapper();
+
+    @Test
+    void selectedGetRoutesStayRegisteredAndDocumented() throws IOException {
+        JsonNode spec = new YAMLMapper().readTree(SPEC.toFile());
+        assertEquals("3.1.0", spec.path("openapi").asText());
+        assertEquals(Set.of("/overview", "/resource/workers"), 
fieldNames(spec.path("paths")));
+
+        String constants = read(SOURCE.resolve("rest/RestConstant.java"));
+        String registrations = read(SOURCE.resolve("JettyService.java"));
+        Map<String, String> pathsByConstant = new HashMap<>();
+        Matcher constantMatcher = CONSTANT.matcher(constants);
+        while (constantMatcher.find()) {
+            pathsByConstant.put(constantMatcher.group(1), 
constantMatcher.group(2));
+        }
+        Map<String, String> classesByHolder = new HashMap<>();
+        Matcher holderMatcher = HOLDER.matcher(registrations);
+        while (holderMatcher.find()) {
+            classesByHolder.put(holderMatcher.group(1), 
holderMatcher.group(2));
+        }
+        Map<String, String> registeredClasses = new HashMap<>();
+        Matcher registrationMatcher = REGISTRATION.matcher(registrations);
+        while (registrationMatcher.find()) {
+            if (COVERED_ROUTES.containsKey(registrationMatcher.group(2))) {
+                registeredClasses.put(
+                        registrationMatcher.group(2),
+                        classesByHolder.get(registrationMatcher.group(1)));
+            }
+        }
+        assertEquals(
+                COVERED_ROUTES,
+                registeredClasses,
+                "JettyService route registrations changed: update 
TestOpenApiV2RouteSync patterns "
+                        + "or openapi-v2.yaml to match the current 
registrations");
+        for (Map.Entry<String, String> route : COVERED_ROUTES.entrySet()) {
+            String path = pathsByConstant.get(route.getKey());
+            JsonNode operation = spec.path("paths").path(path);
+            assertEquals(Set.of("get"), fieldNames(operation), path);
+            assertTrue(operation.path("get").path("responses").has("200"), 
path);
+            assertTrue(
+                    read(SOURCE.resolve("rest/servlet/" + route.getValue() + 
".java"))
+                            .contains("void doGet("),
+                    route.getValue() + " no longer handles GET");
+        }
+        assertEquals(
+                Set.of("basicAuth"), 
fieldNames(spec.path("components").path("securitySchemes")));
+        assertTrue(spec.path("security").toString().contains("{}"));
+    }
+
+    @Test
+    void responseSchemasMatchCurrentSerializedFields() throws IOException {
+        JsonNode spec = new YAMLMapper().readTree(SPEC.toFile());
+        JsonNode schemas = spec.path("components").path("schemas");
+        OverviewInfo overview = new OverviewInfo();
+        overview.setProjectVersion("3.0.1");
+        overview.setGitCommitAbbrev("abc123");
+        overview.setTotalSlot(2);
+        overview.setWorkers(1);
+        JsonNode overviewBody =
+                JSON.readTree(
+                        
JsonUtil.toJsonObject(JsonUtils.toMap(JsonUtils.toJsonString(overview)))
+                                .toString());
+        JsonNode overviewSchema = schemas.path("Overview");
+        assertEquals(fieldNames(overviewBody), 
fieldNames(overviewSchema.path("properties")));
+        assertEquals(fieldNames(overviewBody), 
arrayValues(overviewSchema.path("required")));
+        assertEquals("string", 
schemas.path("DecimalCountString").path("type").asText());
+        for (String field : fieldNames(overviewBody)) {
+            assertTrue(overviewBody.path(field).isTextual(), field + " must be 
a JSON string");
+            JsonNode property = overviewSchema.path("properties").path(field);
+            if (property.has("$ref")) {
+                assertEquals(
+                        "#/components/schemas/DecimalCountString", 
property.path("$ref").asText());
+            } else {
+                assertEquals("string", property.path("type").asText());
+            }
+        }
+
+        WorkerResourceDiagnostic worker = new WorkerResourceDiagnostic();
+        worker.setAddress("127.0.0.1:5801");
+        worker.setTags(Map.of("region", "west"));
+        worker.setTotalSlots(2);
+        worker.setFreeSlots(1);
+        worker.setUsedSlots(1);
+        worker.setDynamicSlot(true);
+        worker.setTotalCpuCores(4);
+        worker.setAvailableCpuCores(2);
+        worker.setTotalHeapMemoryBytes(1024L);
+        worker.setAvailableHeapMemoryBytes(512L);
+        worker.setCpuUsage(0.25);
+        worker.setMemUsage(0.5);
+        worker.setRunningJobIds(Collections.singletonList(42L));
+        JsonNode snapshotBody =
+                JSON.readTree(
+                        new Gson()
+                                .toJson(
+                                        new WorkerResourceSnapshot(
+                                                true, 1234L, 
Collections.singletonList(worker))));
+        JsonNode snapshotSchema = schemas.path("WorkerResourceSnapshot");
+        assertEquals(fieldNames(snapshotBody), 
fieldNames(snapshotSchema.path("properties")));
+        assertEquals(fieldNames(snapshotBody), 
arrayValues(snapshotSchema.path("required")));
+        for (String field : fieldNames(snapshotBody)) {
+            assertType(
+                    snapshotBody.path(field), 
snapshotSchema.path("properties").path(field), field);
+        }
+        JsonNode workerBody = snapshotBody.path("workers").get(0);
+        JsonNode workerSchema = schemas.path("WorkerResourceDiagnostic");
+        assertEquals(fieldNames(workerBody), 
fieldNames(workerSchema.path("properties")));
+        
assertTrue(fieldNames(workerBody).containsAll(arrayValues(workerSchema.path("required"))));
+        for (String field : fieldNames(workerBody)) {
+            assertType(workerBody.path(field), 
workerSchema.path("properties").path(field), field);
+        }
+        assertTrue(workerBody.path("tags").path("region").isTextual());
+        assertTrue(workerBody.path("runningJobIds").get(0).isIntegralNumber());
+    }
+
+    private static void assertType(JsonNode value, JsonNode schema, String 
field) {
+        switch (schema.path("type").asText()) {
+            case "string":
+                assertTrue(value.isTextual(), field);
+                break;
+            case "integer":
+                assertTrue(value.isIntegralNumber(), field);
+                break;
+            case "number":
+                assertTrue(value.isNumber(), field);
+                break;
+            case "boolean":
+                assertTrue(value.isBoolean(), field);
+                break;
+            case "object":
+                assertTrue(value.isObject(), field);
+                break;
+            case "array":
+                assertTrue(value.isArray(), field);
+                break;
+            default:
+                throw new AssertionError("Unexpected schema type for " + 
field);
+        }
+    }
+
+    private static Set<String> fieldNames(JsonNode node) {
+        Set<String> names = new HashSet<>();
+        Iterator<String> fields = node.fieldNames();
+        fields.forEachRemaining(names::add);
+        return names;
+    }
+
+    private static Set<String> arrayValues(JsonNode node) {
+        Set<String> values = new HashSet<>();
+        node.forEach(value -> values.add(value.asText()));
+        return values;
+    }
+
+    private static String read(Path path) throws IOException {
+        return Files.readString(path, StandardCharsets.UTF_8);
+    }
+}
diff --git 
a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/WorkerResourceServletTest.java
 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/WorkerResourceServletTest.java
index 2952ede99d..65c5b8811b 100644
--- 
a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/WorkerResourceServletTest.java
+++ 
b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/WorkerResourceServletTest.java
@@ -56,4 +56,21 @@ class WorkerResourceServletTest {
         verify(response).setCharacterEncoding("UTF-8");
         verify(response).setContentType("application/json; charset=UTF-8");
     }
+
+    @Test
+    void shouldWriteUnavailableSnapshotAsSuccessfulJsonResponse() throws 
Exception {
+        WorkerResourceService service = mock(WorkerResourceService.class);
+        when(service.getWorkerResources())
+                .thenReturn(new WorkerResourceSnapshot(false, 5678L, 
Collections.emptyList()));
+        HttpServletResponse response = mock(HttpServletResponse.class);
+        StringWriter output = new StringWriter();
+        when(response.getWriter()).thenReturn(new PrintWriter(output));
+
+        new WorkerResourceServlet(mock(NodeEngineImpl.class), service)
+                .doGet(mock(HttpServletRequest.class), response);
+
+        assertEquals(
+                "{\"available\":false,\"collectedAt\":5678,\"workers\":[]}", 
output.toString());
+        verify(response).setContentType("application/json; charset=UTF-8");
+    }
 }

Reply via email to