diff --git a/.dockerignore b/.dockerignore index 20905d2..0217fe3 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,6 +10,9 @@ docs outputs tmp .cache +/runtime/dev-private +**/.env +**/.env.* **/node_modules **/.venv **/__pycache__ diff --git a/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/DataCollectionIntegrationService.java b/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/DataCollectionIntegrationService.java index 7c1e760..ba10571 100644 --- a/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/DataCollectionIntegrationService.java +++ b/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/DataCollectionIntegrationService.java @@ -46,6 +46,33 @@ public interface DataCollectionIntegrationService { FileSubmissionResult submitFile(FileSubmissionRequest request); + /** API polling is executed inside Integration so source credentials never enter a SeaTunnel job. */ + default ApiPollResult pollApi(ApiPollRequest request) { + return new ApiPollResult("UNKNOWN", 0, null, "API_POLL_ADAPTER_UNAVAILABLE"); + } + + record ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark, + FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile, + ApiPollProfile profile) implements Serializable { + public ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark, + FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile) { + this(actorId, orgScopeId, intakeId, watermark, snapshot, targetProfile, null); + } + } + + /** Only references to managed secrets cross the service boundary. */ + record ApiPollProfile(String authKind, String tokenEndpoint, String tokenFormat, String clientId, + String tokenClientField, String tokenSecretField, String tokenCredentialStyle, + String tokenPath, String expiresPath, String requestMethod, + Map headers, Map queryParameters, + String requestBody, Integer pageSize, Integer lookbackSeconds, + String successPath, String successValue, String signatureKind, + String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding, + String signingSecretRef) implements Serializable { } + + record ApiPollResult(String status, int writtenRows, String watermark, String errorCode) + implements Serializable { } + FileBatchResult observeFileBatches(FileBatchRequest request); FileActionResult quarantineFile(FileActionRequest request); diff --git a/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/RealtimeCollectionService.java b/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/RealtimeCollectionService.java index d4e783c..f3d0821 100644 --- a/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/RealtimeCollectionService.java +++ b/aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/RealtimeCollectionService.java @@ -6,8 +6,12 @@ import java.util.List; /** Internal owner-authorized CDC execution contract; never exposed as a public request. */ public interface RealtimeCollectionService { Check check(Command command); + Check prepare(Command command); Result execute(Command command, String action, String externalId, String restoreId); List relays(long actorId,long orgId,long sourceId); + SourceDefaults sourceDefaults(long actorId,long orgId,long sourceId); + record SourceDefaults(long sourceVersion,String sourceSchema,String oracleDatabase,String oraclePdb, + String oracleCdbService,String warning) implements Serializable { } record RelayOption(String id,String name,String schema,String table,String format) implements Serializable { } record Spec(String name, long sourceId, long sourceVersion, String sourceDatabase, String sourceTable, long targetResourceId, long targetSpaceId, String targetTable, int httpPort, diff --git a/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfig.java b/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfig.java index 09648e8..2a5c114 100644 --- a/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfig.java +++ b/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfig.java @@ -31,6 +31,8 @@ public class GatewayHttpClientConfig { private static final String CONNECTION_TEST_SUFFIX = "/connection-tests"; private static final String UNIFIED_INGESTION_DRAFT_PATH = "/api/dataops/v1/unified-ingestions/draft"; private static final String UNIFIED_INGESTION_SUBMIT_PATH = "/api/dataops/v1/unified-ingestions/submit"; + private static final Pattern REALTIME_INGESTION_ACTION_PATH = Pattern.compile( + "/api/dataops/v1/realtime-ingestions/[1-9][0-9]*/(?:CHECK|START|REFRESH|STOP|RESUME|ARCHIVE|DELETE|RECREATE)"); private static final String DATA_PROFILE_CREATE_PATH = "/api/governance/v1/data-profiles"; private static final String DATA_PROFILE_RETRY_PATH_PREFIX = "/api/governance/v1/data-profiles/"; private static final Pattern NUMERIC_ID = Pattern.compile("[0-9]+"); @@ -86,8 +88,10 @@ public class GatewayHttpClientConfig { && isPositive(properties.getStandardAdoptionAiMatchResponseTimeout()); boolean runOperationAiDiagnosis = isRunOperationAiDiagnosis(method, uri) && isPositive(properties.getRunOperationAiDiagnosisResponseTimeout()); + boolean realtimeIngestionAction = isRealtimeIngestionAction(method, uri) + && isPositive(properties.getRealtimeIngestionActionResponseTimeout()); return createRequestContext(uri, properties, dataProfileExecution, metadataCatalogAiDraft, - standardAdoptionAiMatch, runOperationAiDiagnosis); + standardAdoptionAiMatch, runOperationAiDiagnosis, realtimeIngestionAction); } static HttpClientContext createRequestContext(HttpMethod method, URI uri, GatewayHttpClientProperties properties) { @@ -95,21 +99,22 @@ public class GatewayHttpClientConfig { } static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties) { - return createRequestContext(uri, properties, false, false, false, false); + return createRequestContext(uri, properties, false, false, false, false, false); } private static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties, boolean dataProfileExecution, boolean metadataCatalogAiDraft, boolean standardAdoptionAiMatch, - boolean runOperationAiDiagnosis) { + boolean runOperationAiDiagnosis, + boolean realtimeIngestionAction) { boolean m2StageCallback = isM2StageCallback(uri); boolean dataSourceConnectionTest = isDataSourceConnectionTest(uri); boolean unifiedIngestionDraft = isUnifiedIngestionDraft(uri); boolean unifiedIngestionSubmit = isUnifiedIngestionSubmit(uri); if (!dataProfileExecution && !m2StageCallback && !dataSourceConnectionTest && !unifiedIngestionDraft && !unifiedIngestionSubmit && !metadataCatalogAiDraft && !standardAdoptionAiMatch - && !runOperationAiDiagnosis) return null; + && !runOperationAiDiagnosis && !realtimeIngestionAction) return null; RequestConfig.Builder requestConfig = RequestConfig.custom(); if (properties.getConnectionRequestTimeout() != null) { @@ -139,6 +144,9 @@ public class GatewayHttpClientConfig { if (runOperationAiDiagnosis) { requestConfig.setResponseTimeout(Timeout.of(properties.getRunOperationAiDiagnosisResponseTimeout())); } + if (realtimeIngestionAction) { + requestConfig.setResponseTimeout(Timeout.of(properties.getRealtimeIngestionActionResponseTimeout())); + } HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(requestConfig.build()); @@ -175,6 +183,11 @@ public class GatewayHttpClientConfig { && RUN_OPERATION_AI_DIAGNOSIS_PATH.matcher(uri.getPath()).matches(); } + static boolean isRealtimeIngestionAction(String method, URI uri) { + return "POST".equalsIgnoreCase(method) && uri != null && uri.getPath() != null + && REALTIME_INGESTION_ACTION_PATH.matcher(uri.getPath()).matches(); + } + private static boolean isPositive(Duration value) { return value != null && !value.isZero() && !value.isNegative(); } diff --git a/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/properties/GatewayHttpClientProperties.java b/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/properties/GatewayHttpClientProperties.java index 42dcd2d..1814158 100644 --- a/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/properties/GatewayHttpClientProperties.java +++ b/aixun-gateway/src/main/java/cn/aixunkeji/gateway/config/properties/GatewayHttpClientProperties.java @@ -57,6 +57,11 @@ public class GatewayHttpClientProperties { */ private Duration unifiedIngestionSubmitResponseTimeout = Duration.ofSeconds(180); + /** + * 实时采集操作包含源端校验与外部作业提交,须长于 DataOps 的 120 秒 Dubbo 调用时限。 + */ + private Duration realtimeIngestionActionResponseTimeout = Duration.ofSeconds(135); + /** * 数据画像创建及数字ID重试等待Governance同步执行完成的超时时间 */ diff --git a/aixun-gateway/src/test/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfigTest.java b/aixun-gateway/src/test/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfigTest.java index cf3b67d..cf69ce7 100644 --- a/aixun-gateway/src/test/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfigTest.java +++ b/aixun-gateway/src/test/java/cn/aixunkeji/gateway/config/GatewayHttpClientConfigTest.java @@ -30,12 +30,31 @@ class GatewayHttpClientConfigTest { assertThat(properties.getDataSourceConnectionTestResponseTimeout()).isEqualTo(Duration.ofSeconds(75)); assertThat(properties.getUnifiedIngestionDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(120)); assertThat(properties.getUnifiedIngestionSubmitResponseTimeout()).isEqualTo(Duration.ofSeconds(180)); + assertThat(properties.getRealtimeIngestionActionResponseTimeout()).isEqualTo(Duration.ofSeconds(135)); assertThat(properties.getDataProfileExecutionResponseTimeout()).isEqualTo(Duration.ofSeconds(120)); assertThat(properties.getMetadataCatalogAiDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(75)); assertThat(properties.getStandardAdoptionAiMatchResponseTimeout()).isEqualTo(Duration.ofSeconds(75)); assertThat(properties.getRunOperationAiDiagnosisResponseTimeout()).isEqualTo(Duration.ofSeconds(75)); } + @Test + void realtimeActionsHaveBoundedLongTimeoutWithoutChangingOtherRoutes() { + for (String action : List.of("CHECK", "START", "REFRESH", "STOP", "RESUME", "ARCHIVE", "DELETE", "RECREATE")) { + URI uri = URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/" + action); + HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties); + assertThat(context.getRequestConfig().getResponseTimeout().toDuration()).isEqualTo(Duration.ofSeconds(135)); + assertThat(GatewayHttpClientConfig.createRequestContext("GET", uri, properties)).isNull(); + } + for (String path : List.of("/api/dataops/v1/realtime-ingestions/0/START", + "/api/dataops/v1/realtime-ingestions/19/START/", "/api/dataops/v1/realtime-ingestions/19/start", + "/api/dataops/v1/realtime-ingestions/19/START-extra")) { + assertThat(GatewayHttpClientConfig.createRequestContext("POST", URI.create("http://aixun-dataops" + path), properties)).isNull(); + } + properties.setRealtimeIngestionActionResponseTimeout(Duration.ZERO); + assertThat(GatewayHttpClientConfig.createRequestContext("POST", + URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/START"), properties)).isNull(); + } + @Test void createsBoundedLongTimeoutOnlyForExactRunOperationAiDiagnosisPost() { for (String source : List.of("SCHEDULING", "BATCH_INGESTION", "FILE_INGESTION", "M2_GOLDEN")) { diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollController.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollController.java new file mode 100644 index 0000000..2952493 --- /dev/null +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollController.java @@ -0,0 +1,52 @@ +package cn.aixunkeji.datagov.dataops.fileingestion; + +import cn.aixunkeji.common.core.domain.R; +import cn.aixunkeji.common.log.annotation.Log; +import cn.aixunkeji.common.log.enums.BusinessType; +import cn.dev33.satoken.annotation.SaCheckPermission; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/dataops/v1/api-ingestions") +public class ApiPollController { + private final ApiPollService service; + private final ApiPollProfileService profiles; + + public record EnabledCommand(boolean enabled) { } + + @SaCheckPermission("aixun:dataops:file-ingestion:view") + @GetMapping("/{intakeId}/profile") + public R profile(@PathVariable long intakeId) { return R.ok(profiles.view(intakeId)); } + + @Log(title="API采集请求配置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false) + @SaCheckPermission("aixun:dataops:file-ingestion:update") + @PutMapping("/{intakeId}/profile") + public R profile(@PathVariable long intakeId, + @RequestBody ApiPollProfileService.Command command) { + return R.ok(profiles.save(intakeId, command)); + } + + @SaCheckPermission("aixun:dataops:file-ingestion:view") + @GetMapping("/{intakeId}/poll") + public R state(@PathVariable long intakeId) { return R.ok(service.state(intakeId)); } + + @SaCheckPermission("aixun:dataops:file-ingestion:view") + @GetMapping("/{intakeId}/poll/runs") + public R> runs(@PathVariable long intakeId) { return R.ok(service.runs(intakeId)); } + + @Log(title="API采集轮询设置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false) + @SaCheckPermission("aixun:dataops:file-ingestion:update") + @PutMapping("/{intakeId}/poll") + public R enabled(@PathVariable long intakeId, @RequestBody EnabledCommand command) { + return R.ok(service.setEnabled(intakeId, command.enabled())); + } + + @Log(title="API采集立即运行", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false) + @SaCheckPermission("aixun:dataops:file-ingestion:submit") + @PostMapping("/{intakeId}/poll/run") + public R run(@PathVariable long intakeId) { return R.ok(service.runNow(intakeId)); } +} diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileService.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileService.java new file mode 100644 index 0000000..951fb3c --- /dev/null +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileService.java @@ -0,0 +1,188 @@ +package cn.aixunkeji.datagov.dataops.fileingestion; + +import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType; +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import tools.jackson.databind.json.JsonMapper; + +import java.net.URI; +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +@Service +@RequiredArgsConstructor +public class ApiPollProfileService { + private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}"); + private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}"); + private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}"); + private static final Set AUTH = Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY"); + private static final Set SIGN = Set.of("NONE", "HMAC_SHA256", "RSA_SHA256"); + private final JdbcTemplate jdbc; + private final JsonMapper json; + private final FileIngestionActorProvider actors; + private final FileIngestionRepository repository; + private final FileManagedCredentialGateway credentials; + + public record Command(String authKind, String tokenEndpoint, String tokenFormat, String clientId, + String tokenClientField, String tokenSecretField, String tokenCredentialStyle, + String tokenPath, String expiresPath, String requestMethod, + Map headers, Map queryParameters, + String requestBody, Integer pageSize, Integer lookbackSeconds, + String successPath, String successValue, String signatureKind, + String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding, + char[] signingKey) { + @Override public String toString() { return "ApiPollProfileCommand[signingKey=REDACTED]"; } + } + + public record View(String authKind, String tokenEndpoint, String tokenFormat, String clientId, + String tokenClientField, String tokenSecretField, String tokenCredentialStyle, + String tokenPath, String expiresPath, String requestMethod, + Map headers, Map queryParameters, + String requestBody, Integer pageSize, Integer lookbackSeconds, + String successPath, String successValue, String signatureKind, + String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding, + boolean signingKeyConfigured) { } + + public View view(long intakeId) { + var actor = actors.current(); + requireApi(actor, intakeId); + return view(profile(actor, intakeId)); + } + + ApiPollProfile profile(FileIngestionActor actor, long intakeId) { + requireApi(actor, intakeId); + var rows = jdbc.query("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=? AND org_scope_id=?", + (rs, index) -> rs.getString(1), intakeId, actor.orgScopeId()); + if (rows.isEmpty()) return null; + try { return json.readValue(rows.getFirst(), ApiPollProfile.class); } + catch (Exception failure) { throw FileIngestionException.validation("API高级配置无效"); } + } + + public View save(long intakeId, Command command) { + var actor = actors.current(); + requireApi(actor, intakeId); + if (command == null) throw FileIngestionException.validation("API高级配置不能为空"); + ApiPollProfile current = profile(actor, intakeId); + String newRef = null; + char[] supplied = command.signingKey(); + try { + validate(command); + String kind = command.signatureKind() == null ? "NONE" : command.signatureKind(); + String signingRef = "NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind()) + ? null : current == null ? null : current.signingSecretRef(); + if (supplied != null && supplied.length > 0) { + if ("NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind())) + throw FileIngestionException.validation("此认证方式无需单独提供签名密钥"); + newRef = credentials.provision(supplied); + signingRef = newRef; + } + if (!"NONE".equals(kind) && signingRef == null && !"SIGN_ONLY".equals(command.authKind())) + throw FileIngestionException.validation("请输入签名密钥"); + var profile = new ApiPollProfile(command.authKind(), command.tokenEndpoint(), command.tokenFormat(), + command.clientId(), command.tokenClientField(), command.tokenSecretField(), + command.tokenCredentialStyle(), command.tokenPath(), command.expiresPath(), command.requestMethod(), + command.headers() == null ? Map.of() : Map.copyOf(command.headers()), + command.queryParameters() == null ? Map.of() : Map.copyOf(command.queryParameters()), + command.requestBody(), command.pageSize(), command.lookbackSeconds(), command.successPath(), + command.successValue(), kind, command.signatureTemplate(), command.signaturePlacement(), command.signatureHeader(), + command.signatureEncoding(), signingRef); + String encoded = json.writeValueAsString(profile); + int updated = jdbc.update("UPDATE ing_api_poll_profile SET profile_json=?,updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?", + encoded, intakeId, actor.orgScopeId()); + if (updated == 0) jdbc.update("INSERT INTO ing_api_poll_profile(intake_id,org_scope_id,profile_json) VALUES (?,?,?)", + intakeId, actor.orgScopeId(), encoded); + newRef = null; + if (current != null && current.signingSecretRef() != null && + !current.signingSecretRef().equals(signingRef)) safeRevoke(current.signingSecretRef()); + return view(profile); + } catch (RuntimeException failure) { + if (newRef != null) safeRevoke(newRef); + throw failure; + } finally { + if (supplied != null) Arrays.fill(supplied, '\0'); + } + } + + private void requireApi(FileIngestionActor actor, long intakeId) { + if (repository.config(actor, intakeId).sourceType() != FileSourceType.API_SAAS) + throw FileIngestionException.validation("仅API采集可配置请求协议"); + } + + private static View view(ApiPollProfile value) { + if (value == null) return new View("STATIC_BEARER", null, "FORM", null, + "client_id", "client_secret", "BODY", "$.access_token", + "$.expires_in", "GET", Map.of(), Map.of(), null, 100, 0, null, null, + "NONE", null, "HEADER", "X-Sign", "BASE64", false); + return new View(value.authKind(), value.tokenEndpoint(), value.tokenFormat(), value.clientId(), + value.tokenClientField(), value.tokenSecretField(), value.tokenCredentialStyle(), + value.tokenPath(), value.expiresPath(), value.requestMethod(), value.headers(), + value.queryParameters(), value.requestBody(), value.pageSize(), value.lookbackSeconds(), + value.successPath(), value.successValue(), value.signatureKind(), value.signatureTemplate(), + value.signaturePlacement(), value.signatureHeader(), value.signatureEncoding(), + value.signingSecretRef() != null || "SIGN_ONLY".equals(value.authKind())); + } + + private static void validate(Command c) { + if (!AUTH.contains(c.authKind()) || !Set.of("GET", "POST").contains(c.requestMethod()) || + c.pageSize() == null || c.pageSize() < 1 || c.pageSize() > 1000 || + c.lookbackSeconds() == null || c.lookbackSeconds() < 0 || c.lookbackSeconds() > 86400 || + !SIGN.contains(c.signatureKind() == null ? "NONE" : c.signatureKind())) + throw FileIngestionException.validation("API请求配置无效"); + if ("SIGN_ONLY".equals(c.authKind()) && (c.signatureKind() == null || "NONE".equals(c.signatureKind()))) + throw FileIngestionException.validation("仅签名认证必须开启请求签名"); + if (!"STATIC_BEARER".equals(c.authKind()) && !"API_KEY_HEADER".equals(c.authKind()) && + !"SIGN_ONLY".equals(c.authKind())) { + try { + URI uri = URI.create(c.tokenEndpoint()); + if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null || + uri.getRawQuery() != null || uri.getFragment() != null) throw new IllegalArgumentException(); + } catch (RuntimeException failure) { throw FileIngestionException.validation("认证接口必须是无密钥参数的HTTPS地址"); } + if (!Set.of("FORM", "JSON").contains(c.tokenFormat()) || + c.clientId() == null || c.clientId().isBlank() || c.clientId().length() > 256 || + !FIELD.matcher(c.tokenClientField() == null ? "" : c.tokenClientField()).matches() || + !FIELD.matcher(c.tokenSecretField() == null ? "" : c.tokenSecretField()).matches() || + !Set.of("BODY", "BASIC").contains(c.tokenCredentialStyle()) || + ("PASSWORD_TOKEN".equals(c.authKind()) && "BASIC".equals(c.tokenCredentialStyle())) || + !path(c.tokenPath()) || (c.expiresPath() != null && !path(c.expiresPath()))) + throw FileIngestionException.validation("动态Token配置无效"); + } + checkMap(c.headers(), true); + checkMap(c.queryParameters(), false); + if (c.requestBody() != null && (c.requestBody().length() > 8192 || + (!"POST".equals(c.requestMethod()) && !c.requestBody().isBlank()))) + throw FileIngestionException.validation("请求体配置无效"); + if (c.successPath() != null && (!path(c.successPath()) || c.successValue() == null || + c.successValue().length() > 128)) throw FileIngestionException.validation("业务状态路径无效"); + if (!"NONE".equals(c.signatureKind())) { + if (c.signatureTemplate() == null || c.signatureTemplate().isBlank() || + c.signatureTemplate().length() > 2048 || !c.signatureTemplate().matches("(?s)[A-Za-z0-9_{}$./?&=+%\\n\\r :|-]*") || + !Set.of("HEADER", "QUERY").contains(c.signaturePlacement()) || + !("HEADER".equals(c.signaturePlacement()) ? HEADER : FIELD) + .matcher(c.signatureHeader() == null ? "" : c.signatureHeader()).matches() || + Set.of("authorization", "cookie", "host").contains(c.signatureHeader().toLowerCase()) || + !Set.of("BASE64", "HEX").contains(c.signatureEncoding())) + throw FileIngestionException.validation("签名配置无效"); + } + } + + private static void checkMap(Map values, boolean headers) { + if (values == null) return; + if (values.size() > 20) throw FileIngestionException.validation("请求参数过多"); + for (var item : values.entrySet()) { + String name = item.getKey(), value = item.getValue(); + if (name == null || value == null || value.length() > 1024 || value.contains("\r") || value.contains("\n") || + !(headers ? HEADER : FIELD).matcher(name).matches() || + (headers && Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key") + .contains(name.toLowerCase())) || + (!headers && Set.of("token", "access_token", "secret", "password", "api_key").contains(name.toLowerCase()))) + throw FileIngestionException.validation("请求参数包含不允许的字段"); + } + } + + private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); } + private void safeRevoke(String ref) { try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* retained safely */ } } +} diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollService.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollService.java new file mode 100644 index 0000000..d364b87 --- /dev/null +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollService.java @@ -0,0 +1,179 @@ +package cn.aixunkeji.datagov.dataops.fileingestion; + +import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil; +import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType; +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +/** API-only polling ownership, leases and committed watermarks. */ +@Service +@RequiredArgsConstructor +public class ApiPollService { + private final JdbcTemplate jdbc; + private final FileIngestionActorProvider actors; + private final FileIngestionRepository repository; + private final IntegrationFileIngestionGateway integration; + @Autowired(required = false) + private ApiPollProfileService profiles; + + public record PollState(long intakeId, boolean enabled, String watermark, LocalDateTime nextDueAt, + String lastStatus, String lastErrorCode, int lastWrittenRows, + LocalDateTime lastRunAt) { } + public record PollRun(long runId, String triggerType, String status, int writtenRows, + String errorCode, String watermarkBefore, String watermarkAfter, + LocalDateTime startedAt, LocalDateTime completedAt) { } + + public PollState state(long intakeId) { + FileIngestionActor actor = actors.current(); + requireApi(actor, intakeId); + List rows = jdbc.query(""" + SELECT intake_id,enabled,watermark,next_due_at,last_status,last_error_code, + last_written_rows,last_run_at FROM ing_api_poll_state + WHERE intake_id=? AND org_scope_id=? + """, (rs, index) -> new PollState(rs.getLong(1), rs.getInt(2) == 1, rs.getString(3), + time(rs.getTimestamp(4)), rs.getString(5), rs.getString(6), rs.getInt(7), + time(rs.getTimestamp(8))), intakeId, actor.orgScopeId()); + return rows.isEmpty() ? new PollState(intakeId, false, null, null, "NEVER", null, 0, null) : rows.getFirst(); + } + + public List runs(long intakeId) { + FileIngestionActor actor = actors.current(); + requireApi(actor, intakeId); + return jdbc.query(""" + SELECT run_id,trigger_type,run_status,written_rows,error_code,watermark_before, + watermark_after,started_at,completed_at FROM ing_api_poll_run + WHERE intake_id=? AND org_scope_id=? ORDER BY started_at DESC FETCH FIRST 50 ROWS ONLY + """, (rs, index) -> new PollRun(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getInt(4), + rs.getString(5), rs.getString(6), rs.getString(7), time(rs.getTimestamp(8)), + time(rs.getTimestamp(9))), intakeId, actor.orgScopeId()); + } + + public PollState setEnabled(long intakeId, boolean enabled) { + FileIngestionActor actor = actors.current(); + FileIngestionPolicy.Config config = requireApi(actor, intakeId); + if (enabled && !supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持"); + jdbc.update(""" + INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled,next_due_at) + SELECT ?,?,?,?,CURRENT_TIMESTAMP FROM DUAL WHERE NOT EXISTS + (SELECT 1 FROM ing_api_poll_state WHERE intake_id=?) + """, intakeId, actor.orgScopeId(), actor.actorId(), enabled ? 1 : 0, intakeId); + jdbc.update(""" + UPDATE ing_api_poll_state SET enabled=?, actor_id=?, + next_due_at=CASE WHEN ?=1 THEN CURRENT_TIMESTAMP ELSE next_due_at END, + updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? + """, enabled ? 1 : 0, actor.actorId(), enabled ? 1 : 0, intakeId, actor.orgScopeId()); + return state(intakeId); + } + + public PollRun runNow(long intakeId) { + FileIngestionActor actor = actors.current(); + FileIngestionPolicy.Config config = requireApi(actor, intakeId); + if (!supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持"); + ensureState(actor, intakeId); + return execute(actor, intakeId, "MANUAL", config); + } + + @Scheduled(fixedDelayString = "${datagov.api-poll.scan-delay-ms:15000}") + public void scan() { + List due; + try { + due = jdbc.query(""" + SELECT intake_id,org_scope_id,actor_id FROM ing_api_poll_state + WHERE enabled=1 AND next_due_at<=CURRENT_TIMESTAMP + AND (lease_until IS NULL OR lease_until new long[]{rs.getLong(1), rs.getLong(2), rs.getLong(3)}); + } catch (RuntimeException unavailable) { return; } + for (long[] item : due) { + try { + FileIngestionActor actor = new FileIngestionActor(item[2], item[1]); + FileIngestionPolicy.Config config = requireApi(actor, item[0]); + if (supported(config)) execute(actor, item[0], "SCHEDULED", config); + else disableInvalid(item[0], item[1]); + } catch (RuntimeException failure) { + try { disableInvalid(item[0], item[1]); } catch (RuntimeException unavailable) { /* retry on next scan */ } + } + } + } + + private PollRun execute(FileIngestionActor actor, long intakeId, String trigger, + FileIngestionPolicy.Config config) { + String lease = UUID.randomUUID().toString(); + int claimed = jdbc.update(""" + UPDATE ing_api_poll_state SET lease_id=?, lease_until=DATEADD(HOUR, 2, CURRENT_TIMESTAMP), + updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? + AND (lease_until IS NULL OR lease_until= 1 && config.maxPages() <= 100 && + config.periodSeconds() != null && config.periodSeconds() >= 60 && + config.secretRef() != null; + } + + private void disableInvalid(long intakeId, long orgId) { + jdbc.update("UPDATE ing_api_poll_state SET enabled=0,last_status='UNKNOWN',last_error_code='API_POLL_CONFIG_INVALID',updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?", intakeId, orgId); + } + + private static LocalDateTime time(Timestamp value) { return value == null ? null : value.toLocalDateTime(); } +} diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/FileIngestionService.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/FileIngestionService.java index 5150837..6b69fc8 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/FileIngestionService.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/FileIngestionService.java @@ -259,6 +259,9 @@ public class FileIngestionService { throw FileIngestionException.conflict("仅草稿或就绪配置可执行能力校验"); } FileIngestionPolicy.Config config = repository.config(actor, intakeId); + if (config.sourceType() == FileSourceType.API_SAAS) { + throw FileIngestionException.conflict("API采集请使用专用轮询执行入口"); + } if (FileIngestionPolicy.requiresDeferredAdapter(config)) { String code = FileIngestionPolicy.deferredAdapterCode(config); String summary = FileIngestionPolicy.deferredAdapterSummary(config); @@ -309,6 +312,9 @@ public class FileIngestionService { FileIngestionActor actor = actorProvider.current(); String key = FileIngestionPolicy.requireIdempotencyKey(idempotencyKey); FileIngestionPolicy.Config config = repository.config(actor, intakeId); + if (config.sourceType() == FileSourceType.API_SAAS) { + throw FileIngestionException.conflict("API采集请使用专用轮询执行入口"); + } if (FileIngestionPolicy.requiresDeferredAdapter(config)) { repository.markCapability(actor, intakeId, AggregateCapabilityStatus.UNSUPPORTED); throw FileIngestionException.external(FileIngestionPolicy.deferredAdapterSummary(config)); diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/IntegrationFileIngestionGateway.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/IntegrationFileIngestionGateway.java index c7c0962..a4837a8 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/IntegrationFileIngestionGateway.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/fileingestion/IntegrationFileIngestionGateway.java @@ -35,6 +35,19 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway { public IntegrationFileIngestionGateway() { } + DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId, + FileIngestionPolicy.Config config, String watermark) { + return pollApi(actor, intakeId, config, watermark, null); + } + + DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId, + FileIngestionPolicy.Config config, String watermark, + DataCollectionIntegrationService.ApiPollProfile profile) { + return integration.pollApi(new DataCollectionIntegrationService.ApiPollRequest(actor.actorId(), + actor.orgScopeId(), intakeId, watermark, snapshot(config), + targetProfile(actor.actorId(), actor.orgScopeId(), config), profile)); + } + @Override public CapabilityResult checkCapability(CapabilityRequest request) { try { @@ -166,7 +179,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway { "文件动作证据暂不可用"); } - private DataCollectionIntegrationService.StorageExecutionProfile targetProfile( + DataCollectionIntegrationService.StorageExecutionProfile targetProfile( long actorId, long orgScopeId, FileIngestionPolicy.Config config ) { if (storageReferences == null || config == null || config.targetStorageResourceId() == null || @@ -180,7 +193,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway { resolved.serviceAccount(), resolved.secretRef(), resolved.tlsEnabled()); } - private static DataCollectionIntegrationService.FileExecutionSnapshot snapshot( + static DataCollectionIntegrationService.FileExecutionSnapshot snapshot( FileIngestionPolicy.Config config ) { if (config == null) return null; diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeController.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeController.java index e27ce73..7cac0a6 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeController.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeController.java @@ -18,6 +18,8 @@ public class RealtimeController { public R sources(@RequestParam(required=false) String keyword){return R.ok(directory.realtimeSources(keyword));} @GetMapping("/relay-options") @SaCheckPermission("aixun:dataops:realtime:manage") public R> relays(@RequestParam long sourceId){return R.ok(service.relays(sourceId));} + @GetMapping("/source-defaults") @SaCheckPermission("aixun:dataops:realtime:manage") + public R sourceDefaults(@RequestParam long sourceId){return R.ok(service.sourceDefaults(sourceId));} @GetMapping @SaCheckPermission("aixun:dataops:realtime:view") public R list(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.list(pageNum,pageSize));} @GetMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:view") diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeService.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeService.java index a37e891..40867bf 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeService.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeService.java @@ -46,6 +46,7 @@ public class RealtimeService { } public View get(long id) {return view(require(id,false),true);} public List relays(long sourceId){return integration.relays(actor(),org(),sourceId);} + public SourceDefaults sourceDefaults(long sourceId){return integration.sourceDefaults(actor(),org(),sourceId);} private Row require(long id,boolean lock) { var rows=db.query("SELECT * FROM ing_realtime_task WHERE id=? AND org_id=? AND owner_id=?"+(lock?" FOR UPDATE":""), (rs,n)->map(rs),id,org(),actor()); @@ -95,7 +96,7 @@ public class RealtimeService { } public View action(long id,String action,Action request) { if(request==null)throw new ServiceException("请求不能为空");key(request.key()); - if(!Set.of("CHECK","START","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效"); + if(!Set.of("CHECK","START","RETRY","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效"); Row prior=require(id,false); Row reserved=tx.execute(status->{ Row r=require(id,true); @@ -108,9 +109,9 @@ public class RealtimeService { if(r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))throw new ServiceException("操作仍在处理中,请稍后刷新"); allowed(r,action); // SeaTunnel 2.3.13 restores the same job ID; a new ID would start a new snapshot. - long nextAttempt=r.attempt()+(action.equals("START")?1:0); + long nextAttempt=r.attempt()+(Set.of("START","RETRY").contains(action)?1:0); String external=nextAttempt>0?RealtimeCollectionService.jobId(r.org(),r.id(),nextAttempt):null; - String state=action.equals("START")||action.equals("RESUME")?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status(); + String state=Set.of("START","RETRY","RESUME").contains(action)?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status(); db.update("UPDATE ing_realtime_task SET status=?,version=version+1,attempt=?,external_id=?,busy_until=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",state,nextAttempt,external,LocalDateTime.now().plusMinutes(3),id); db.update("INSERT INTO ing_realtime_event(id,task_id,request_key,action,status,created_at) VALUES(?,?,?,?, 'PENDING',CURRENT_TIMESTAMP)",IdGeneratorUtil.nextId(),id,request.key(),action); return require(id,false); @@ -133,10 +134,10 @@ public class RealtimeService { } else { var command=new Command(r.owner(),r.org(),r.id(),r.attempt(),r.spec(), - Set.of("CHECK","START","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(), - action.equals("RESUME")?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null); + Set.of("CHECK","START","RETRY","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(), + Set.of("RESUME","RETRY").contains(action)?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null); if(action.equals("CHECK")) { - var c=integration.check(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint(); + var c=integration.prepare(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint(); } else { invoked=true; var result=integration.execute(command,action.equals("DELETE")?"REFRESH":action,r.external(),action.equals("RESUME")? @@ -144,6 +145,10 @@ public class RealtimeService { if(result==null || !Objects.equals(r.external(),result.externalId()))throw new IllegalStateException("CDC_RESULT_IDENTITY_MISMATCH"); result=retainConfirmedTerminal(action,prior,result); state=result.status();summary=result.summary();checkpoint=result.checkpointId();read=result.readRows();written=result.writeRows(); + if("UNKNOWN".equals(state) && checkpoint==null && prior.checkpoint()!=null) { + checkpoint=prior.checkpoint();read=prior.readRows();written=prior.writeRows(); + summary=(summary==null?"外部结果待确认":summary)+";保留上次已确认检查点,恢复时仍须验证原作业已结束和检查点有效"; + } if(action.equals("DELETE")) { if(terminal(state)) {state="ARCHIVED";summary="任务已删除,历史操作记录保留";} else summary="未删除:外部作业尚未确认结束,请同步状态后重试"; @@ -154,8 +159,8 @@ public class RealtimeService { } } } catch(RuntimeException ex) { - if(action.equals("CHECK")) {state="DRAFT";summary="校验未完成,请检查来源、目标授权和集成服务";} - else if(!invoked && Set.of("START","RESUME").contains(action)) { + if(action.equals("CHECK")) {state="DRAFT";fingerprint=null;summary="检查并准备未完成,请检查来源、目标授权和集成服务;如已建表会保留,请重新检查确认";} + else if(!invoked && Set.of("START","RETRY","RESUME").contains(action)) { state=prior.status();attempt=prior.attempt();external=prior.external();checkpoint=prior.checkpoint(); summary="来源或目标授权检查未通过,未提交外部作业"; } @@ -188,7 +193,8 @@ public class RealtimeService { case "CHECK","ARCHIVE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status()); case "DELETE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status()) || terminal(r.status()); case "START" -> r.attempt()==0 && "READY".equals(r.status()) && r.fingerprint()!=null; - case "RESUME" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null; + case "RETRY" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()==null && r.fingerprint()!=null; + case "RESUME" -> r.attempt()>0 && (Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null || "UNKNOWN".equals(r.status())); case "STOP","REFRESH" -> r.attempt()>0; case "RECREATE" -> r.attempt()>0 && "UNKNOWN".equals(r.status()) && r.checkpoint()==null; default -> false; diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceRepository.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceRepository.java index 9f3d89f..a424dcd 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceRepository.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceRepository.java @@ -30,7 +30,9 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.function.Function; @Repository @@ -460,7 +462,17 @@ public class StorageResourceRepository { "SELECT " + CAPACITY_COLUMNS + " FROM store_capacity_snapshot " + "WHERE resource_id=? AND del_flag='0' ORDER BY snapshot_id DESC LIMIT ?", (resultSet, rowNumber) -> mapCapacity(resultSet), resourceId, limit); - return snapshots.stream().map(this::withDimensions).toList(); + if (snapshots.isEmpty()) return snapshots; + String placeholders = String.join(",", java.util.Collections.nCopies(snapshots.size(), "?")); + Map> dimensions = new HashMap<>(); + jdbcTemplate.query("SELECT snapshot_id, " + DIMENSION_COLUMNS + + " FROM store_capacity_dimension WHERE snapshot_id IN (" + placeholders + + ") AND del_flag='0' ORDER BY snapshot_id, dimension_name", rs -> { + dimensions.computeIfAbsent(rs.getLong("snapshot_id"), ignored -> new ArrayList<>()) + .add(mapDimension(rs)); + }, snapshots.stream().map(StorageCapacitySnapshotView::snapshotId).toArray()); + return snapshots.stream().map(snapshot -> attachDimensions(snapshot, + dimensions.getOrDefault(snapshot.snapshotId(), List.of()))).toList(); } void lockCapacityWindow(long resourceId) { @@ -863,14 +875,21 @@ public class StorageResourceRepository { nullableLong(resultSet, "previous_snapshot_id"), resultSet.getString("contract_version"), List.of()); } + private static final String DIMENSION_COLUMNS = """ + dimension_name, metric_status, source_type, source_identity, observed_at, + freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes, + available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version + """; + private StorageCapacitySnapshotView withDimensions(StorageCapacitySnapshotView snapshot) { - List dimensions = jdbcTemplate.query(""" - SELECT dimension_name, metric_status, source_type, source_identity, observed_at, - freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes, - available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version - FROM store_capacity_dimension - WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name - """, (resultSet, rowNumber) -> new StorageCapacityDimensionView( + List dimensions = jdbcTemplate.query("SELECT " + DIMENSION_COLUMNS + + " FROM store_capacity_dimension WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name", + (resultSet, rowNumber) -> mapDimension(resultSet), snapshot.snapshotId()); + return attachDimensions(snapshot, dimensions); + } + + private static StorageCapacityDimensionView mapDimension(ResultSet resultSet) throws SQLException { + return new StorageCapacityDimensionView( StorageTelemetryDimensionType.valueOf(resultSet.getString("dimension_name")), StorageTelemetryMetricState.valueOf(resultSet.getString("metric_status")), resultSet.getString("source_type"), resultSet.getString("source_identity"), @@ -881,7 +900,11 @@ public class StorageResourceRepository { nullableLong(resultSet, "total_bytes"), nullableLong(resultSet, "used_bytes"), nullableLong(resultSet, "available_bytes"), nullableLong(resultSet, "value_bytes"), resultSet.getBigDecimal("value_percent"), resultSet.getString("comparison_fingerprint"), - resultSet.getString("algorithm_version")), snapshot.snapshotId()); + resultSet.getString("algorithm_version")); + } + + private static StorageCapacitySnapshotView attachDimensions(StorageCapacitySnapshotView snapshot, + List dimensions) { if (dimensions.isEmpty()) { dimensions = legacyDimensions(snapshot); } diff --git a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileJdbcTest.java b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileJdbcTest.java new file mode 100644 index 0000000..4356a97 --- /dev/null +++ b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollProfileJdbcTest.java @@ -0,0 +1,65 @@ +package cn.aixunkeji.datagov.dataops.fileingestion; + +import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +import java.util.Map; +import java.util.Properties; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** Exercises profile persistence and secret-reference handling against the dedicated DM test schema. */ +@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST") +class ApiPollProfileJdbcTest { + @Test void savesRedactedProfileAndRevokesReplacedSigningKey() { + var ds = new DriverManagerDataSource(); + ds.setDriverClassName("dm.jdbc.driver.DmDriver"); + ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT")); + ds.setUsername(System.getenv("DATAGOV_DM_USERNAME")); + ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD")); + var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA")); + ds.setConnectionProperties(properties); + var jdbc = new JdbcTemplate(ds); + var actors = mock(FileIngestionActorProvider.class); + var repository = mock(FileIngestionRepository.class); + var credentials = mock(FileManagedCredentialGateway.class); + var actor = new FileIngestionActor(900009L, 900009L); + var config = mock(FileIngestionPolicy.Config.class); + when(actors.current()).thenReturn(actor); + when(repository.config(actor, -900009L)).thenReturn(config); + when(config.sourceType()).thenReturn(FileSourceType.API_SAAS); + when(credentials.provision(any(char[].class))).thenReturn("file:///managed/api-sign?version=v1"); + char[] signingKey = "test-signing-material".toCharArray(); + new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> { + status.setRollbackOnly(); + var service = new ApiPollProfileService(jdbc, JsonMapper.builder().findAndAddModules().build(), + actors, repository, credentials); + var first = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token", + "FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in", + "POST", Map.of("X-Tenant", "example"), Map.of("status", "paid"), "{\"page\":${page}}", + 50, 60, "$.success", "true", "HMAC_SHA256", "${method}\n${pathQuery}\n${timestamp}\n${nonce}", + "HEADER", "X-Sign", "BASE64", signingKey); + assertThat(service.save(-900009L, first).signingKeyConfigured()).isTrue(); + assertThat(signingKey).containsOnly('\0'); + String stored = jdbc.queryForObject("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=?", + String.class, -900009L); + assertThat(stored).contains("file:///managed/api-sign?version=v1").doesNotContain("test-signing-material"); + assertThat(service.view(-900009L).requestMethod()).isEqualTo("POST"); + var second = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token", + "FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in", + "POST", Map.of(), Map.of(), null, 50, 0, null, null, + "NONE", null, "HEADER", "X-Sign", "BASE64", null); + assertThat(service.save(-900009L, second).signingKeyConfigured()).isFalse(); + verify(credentials).revoke("file:///managed/api-sign?version=v1"); + return null; + }); + } +} diff --git a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollServiceJdbcTest.java b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollServiceJdbcTest.java new file mode 100644 index 0000000..01dfbca --- /dev/null +++ b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/fileingestion/ApiPollServiceJdbcTest.java @@ -0,0 +1,75 @@ +package cn.aixunkeji.datagov.dataops.fileingestion; + +import cn.aixunkeji.datagov.dataops.api.fileingestion.*; +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionTemplate; + +import java.util.Properties; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** Exercises the production polling SQL against disposable rows in the dedicated DM test schema. */ +@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST") +class ApiPollServiceJdbcTest { + @BeforeAll static void identifiers() { + var beans = new DefaultListableBeanFactory(); + beans.registerSingleton("identifierGenerator", com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance()); + new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(beans); + } + + @Test void successfulRunCommitsWatermarkAndUnknownKeepsIt() { + var ds = new DriverManagerDataSource(); + ds.setDriverClassName("dm.jdbc.driver.DmDriver"); + ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT")); + ds.setUsername(System.getenv("DATAGOV_DM_USERNAME")); + ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD")); + var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA")); + ds.setConnectionProperties(properties); + var jdbc = new JdbcTemplate(ds); + var actors = mock(FileIngestionActorProvider.class); + var repository = mock(FileIngestionRepository.class); + var integration = mock(IntegrationFileIngestionGateway.class); + var config = mock(FileIngestionPolicy.Config.class); + var actor = new FileIngestionActor(900008L, 900008L); + long intakeId = -900008L; + when(actors.current()).thenReturn(actor); + when(repository.config(actor, intakeId)).thenReturn(config); + when(config.sourceType()).thenReturn(FileSourceType.API_SAAS); + when(config.apiConnector()).thenReturn(FileApiConnector.GENERIC_HTTPS_JSON); + when(config.authMode()).thenReturn(FileAuthMode.BEARER); + when(config.paginationMode()).thenReturn(FilePaginationMode.PAGE_SIZE); + when(config.maxPages()).thenReturn(2); + when(config.periodSeconds()).thenReturn(60); + when(config.secretRef()).thenReturn("file:///managed/data-source/test?version=v1"); + when(integration.pollApi(eq(actor), eq(intakeId), eq(config), isNull(), isNull())).thenReturn( + new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", 2, "2026-11-26T00:00:00Z", null)); + when(integration.pollApi(eq(actor), eq(intakeId), eq(config), eq("2026-11-26T00:00:00Z"), isNull())).thenReturn( + new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_HTTP_503")); + new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> { + status.setRollbackOnly(); + var service = new ApiPollService(jdbc, actors, repository, integration); + assertThat(service.state(intakeId).lastStatus()).isEqualTo("NEVER"); + assertThat(service.runNow(intakeId).status()).isEqualTo("SUCCEEDED"); + assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z"); + assertThat(service.runNow(intakeId).status()).isEqualTo("UNKNOWN"); + assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z"); + assertThat(service.runs(intakeId)).hasSize(2); + assertThat(service.setEnabled(intakeId, true).enabled()).isTrue(); + service.scan(); + assertThat(service.runs(intakeId)).hasSize(3); + assertThat(service.runs(intakeId).getFirst().triggerType()).isEqualTo("SCHEDULED"); + assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z"); + assertThat(service.setEnabled(intakeId, false).enabled()).isFalse(); + return null; + }); + } +} diff --git a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeJdbcTest.java b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeJdbcTest.java index c808831..d5e7837 100644 --- a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeJdbcTest.java +++ b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimeJdbcTest.java @@ -44,7 +44,7 @@ class RealtimeJdbcTest { String createKey=UUID.randomUUID().toString();var created=service.create(spec,createKey); assertThat(service.create(spec,createKey).id()).isEqualTo(created.id()); long id=Long.parseLong(created.id()); - when(provider.check(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id"))); + when(provider.prepare(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id"))); var ready=service.action(id,"CHECK",action(created));assertThat(ready.status()).isEqualTo("READY"); var startKey=UUID.randomUUID().toString(); when(provider.execute(any(),eq("START"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"unknown",null,null,null)); diff --git a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimePolicyTest.java b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimePolicyTest.java index beef46c..62d51e6 100644 --- a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimePolicyTest.java +++ b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/realtime/RealtimePolicyTest.java @@ -3,6 +3,14 @@ import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; class RealtimePolicyTest { + @Test void retryRequiresConfirmedTerminalWithoutCheckpoint(){ + for(String state:java.util.List.of("FAILED","CANCELED")) + assertThatCode(()->RealtimeService.allowed(row(state,1,null),"RETRY")).doesNotThrowAnyException(); + for(String state:java.util.List.of("UNKNOWN","RUNNING","SUBMITTING","STOPPING","READY","SUCCEEDED","ARCHIVED")) + assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RETRY")).isInstanceOf(RuntimeException.class); + assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",1,"1041"),"RETRY")).isInstanceOf(RuntimeException.class); + assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",0,null),"RETRY")).isInstanceOf(RuntimeException.class); + } @Test void recreateOnlyUnknownWithoutCheckpoint() { assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RECREATE")).doesNotThrowAnyException(); for(String state:java.util.List.of("RUNNING","SUBMITTING","STOPPING","DRAFT","ARCHIVED")) @@ -34,9 +42,10 @@ class RealtimePolicyTest { assertThatThrownBy(()->RealtimeService.allowed(row("ARCHIVED",1,null),"REFRESH")).isInstanceOf(RuntimeException.class); } static RealtimeService.Row row(String status,long attempt,String checkpoint){return new RealtimeService.Row(1,2,3,null,status,0,attempt,null,"a".repeat(64),checkpoint,null,null,null,null,null);} - @Test void cannotStartAgainOrResumeUnknownJob(){ + @Test void unknownJobCanOnlyBeRecoveredThroughGuardedSavepointPath(){ assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"START")).isInstanceOf(RuntimeException.class); - assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class); + assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).doesNotThrowAnyException(); + assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RESUME")).doesNotThrowAnyException(); assertThatThrownBy(()->RealtimeService.allowed(row("RUNNING",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class); } @Test void resumeRequiresTerminalAndCheckpoint(){ diff --git a/aixun-modules/aixun-integration/seatunnel-native-cdc/src/main/java/cn/aixunkeji/datagov/integration/cdc/NativeLogReader.java b/aixun-modules/aixun-integration/seatunnel-native-cdc/src/main/java/cn/aixunkeji/datagov/integration/cdc/NativeLogReader.java index 4077f62..cd678a7 100644 --- a/aixun-modules/aixun-integration/seatunnel-native-cdc/src/main/java/cn/aixunkeji/datagov/integration/cdc/NativeLogReader.java +++ b/aixun-modules/aixun-integration/seatunnel-native-cdc/src/main/java/cn/aixunkeji/datagov/integration/cdc/NativeLogReader.java @@ -153,8 +153,8 @@ final class NativeLogReader implements SourceReader2128, ENDSCN=>?)")){ps.setQueryTimeout(60);ps.setLong(1,end);ps.execute();} @@ -205,9 +205,25 @@ final class NativeLogReader implements SourceReader{ + if(m.getName().equals("execute"))throw new SQLException("private details","22000",code[0]); + return null; + }); + Connection connection=(Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},(proxy,m,args)->statement); + assertDoesNotThrow(()->NativeLogReader.endDamengSession(connection)); + code[0]=-2000; + assertEquals(-2000,assertThrows(SQLException.class,()->NativeLogReader.endDamengSession(connection)).getErrorCode()); + } @Test void snapshotPagesKeepLogWatermarkAndResumeCompositeKey()throws Exception { NativeLogSource source=new DamengSource();source.kind="DAMENG";source.schema="APP";source.table="T"; source.names=Arrays.asList("TENANT","ID");source.types=Arrays.asList(Types.INTEGER,Types.INTEGER);source.primaryKeys=source.names; diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutor.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutor.java new file mode 100644 index 0000000..da31c19 --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutor.java @@ -0,0 +1,491 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import cn.aixunkeji.common.json.utils.JsonUtils; +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService; +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile; +import cn.aixunkeji.datagov.integration.m2.M2SecretReader; +import tools.jackson.databind.JsonNode; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.InputStream; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** Bounded HTTPS pull and Doris write; source credentials remain inside Integration. */ +final class ApiPollExecutor { + private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]{0,127}"); + private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}"); + private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}"); + private static final int MAX_BODY = 2 * 1024 * 1024; + private static final SecureRandom RANDOM = new SecureRandom(); + private final M2SecretReader secrets; + private final HttpClient http; + private final EndpointVerifier endpointVerifier; + private final JdbcConnector jdbcConnector; + private final Map tokenCache = new ConcurrentHashMap<>(); + + interface EndpointVerifier { M3HttpEndpointPolicy.Validation validate(String endpoint); } + interface JdbcConnector { Connection open(String jdbc, String user, String password) throws SQLException; } + private record Token(String value, Instant expiresAt) { } + private record Page(int number, String cursor, URI link, String watermark, int size) { } + private static final class PollFailure extends RuntimeException { + final String code; + PollFailure(String code) { super(code); this.code = code; } + } + + ApiPollExecutor(M2SecretReader secrets) { + this(secrets, M3HttpEndpointPolicy::validate, DriverManager::getConnection, + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)) + .followRedirects(HttpClient.Redirect.NEVER).build()); + } + + ApiPollExecutor(M2SecretReader secrets, EndpointVerifier endpointVerifier, + JdbcConnector jdbcConnector, HttpClient http) { + this.secrets = secrets; + this.endpointVerifier = endpointVerifier; + this.jdbcConnector = jdbcConnector; + this.http = http; + } + + DataCollectionIntegrationService.ApiPollResult run(DataCollectionIntegrationService.ApiPollRequest request) { + try { + var source = request.snapshot(); + var target = request.targetProfile(); + ApiPollProfile profile = request.profile() == null ? defaults() : request.profile(); + if (request.actorId() <= 0 || request.orgScopeId() <= 0 || request.intakeId() <= 0 || + source == null || target == null || !"API_SAAS".equals(source.sourceType()) || + !"GENERIC_HTTPS_JSON".equals(source.apiConnector()) || !"BEARER".equals(source.authMode()) || + !Set.of("PAGE_SIZE", "OFFSET_LIMIT", "CURSOR", "LINK_HEADER").contains(source.paginationMode()) || + !"DORIS".equals(target.resourceType()) || + source.targetStorageResourceId() == null || source.targetStorageResourceId() != target.resourceId() || + source.targetStorageSpaceId() == null || target.spaceId() == null || + !source.targetStorageSpaceId().equals(target.spaceId()) || + source.maxPages() == null || source.maxPages() < 1 || source.maxPages() > 100 || + source.rateLimitPerMinute() == null || source.rateLimitPerMinute() < 1 || + source.paginationField() == null || !valid(source.paginationField()) || + source.schema() == null || source.schema().isEmpty() || source.schema().size() > 200 || + source.secretRef() == null || target.secretRef() == null) return fail("API_POLL_CONTRACT_INVALID"); + if ("CURSOR".equals(source.paginationMode()) && !path(source.cursorResponseField())) + return fail("API_POLL_CURSOR_INVALID"); + validateProfile(profile); + String[] object = source.targetObject() == null ? new String[0] : source.targetObject().split("\\."); + if (object.length != 2 || !valid(object[0]) || !valid(object[1]) || + !object[0].equals(target.externalSpaceId())) return fail("API_POLL_TARGET_INVALID"); + for (var field : source.schema()) if (field == null || !valid(field.sourceField()) || + !valid(field.targetField())) return fail("API_POLL_SCHEMA_INVALID"); + if (source.incrementalMarker() != null && !valid(source.incrementalMarker())) + return fail("API_POLL_MARKER_INVALID"); + if (profile.queryParameters().containsKey(source.paginationField()) || + profile.queryParameters().containsKey("size") || profile.queryParameters().containsKey("limit")) + return fail("API_POLL_QUERY_CONFLICT"); + if (request.watermark() != null) Instant.parse(request.watermark()); + URI endpoint = checked(source.endpoint()); + if (dynamic(profile)) checked(profile.tokenEndpoint()); + String authSecret = secrets.resolve(source.secretRef()); + String signingSecret = "NONE".equals(profile.signatureKind()) ? null : + secrets.resolve(profile.signingSecretRef() == null ? source.secretRef() : profile.signingSecretRef()); + String password = secrets.resolve(target.secretRef()); + String jdbc = "jdbc:mysql://" + target.endpointHost() + ":" + target.endpointPort() + "/" + object[0] + + "?useSSL=" + target.tlsEnabled() + "&serverTimezone=UTC"; + try (Connection connection = jdbcConnector.open(jdbc, target.serviceAccount(), password)) { + connection.setAutoCommit(false); + requireUniqueKey(connection, object); + String columns = String.join(",", source.schema().stream().map(f -> "`" + f.targetField() + "`").toList()); + String placeholders = String.join(",", source.schema().stream().map(f -> "?").toList()); + String sql = "INSERT INTO `" + object[0] + "`.`" + object[1] + "` (" + columns + ") VALUES (" + placeholders + ")"; + int written = 0; + Instant watermark = request.watermark() == null ? null : Instant.parse(request.watermark()); + String queryWatermark = watermark == null ? null : watermark.minusSeconds(profile.lookbackSeconds()).toString(); + String cursor = null; + URI link = null; + for (int page = 1; page <= source.maxPages(); page++) { + Page position = new Page(page, cursor, link, queryWatermark, profile.pageSize()); + URI uri = link != null ? checked(link.toASCIIString()) : pageUri(endpoint, source, profile, position); + checked(uri.toASCIIString()); + String body = body(profile, position); + HttpResponse response = sendData(request, profile, uri, body, + authSecret, signingSecret); + if (response.statusCode() != 200) { + response.body().close(); return fail("API_POLL_HTTP_" + response.statusCode()); + } + byte[] raw = read(response.body(), MAX_BODY); + JsonNode root = JsonUtils.getObjectMapper().readTree(new String(raw, StandardCharsets.UTF_8)); + if (profile.successPath() != null) { + JsonNode success = at(root, profile.successPath()); + if (success == null || !profile.successValue().equals(success.asText())) + return fail("API_POLL_BUSINESS_ERROR"); + } + JsonNode rows = rows(root, source.responseContentField()); + if (rows == null || !rows.isArray()) return fail("API_POLL_RESPONSE_SHAPE"); + if (!rows.isEmpty()) { + try (PreparedStatement insert = connection.prepareStatement(sql)) { + for (JsonNode row : rows) { + if (!row.isObject()) return fail("API_POLL_ROW_SHAPE"); + for (int index = 0; index < source.schema().size(); index++) { + var field = source.schema().get(index); + JsonNode value = row.get(field.sourceField()); + if ((value == null || value.isNull()) && !field.nullable()) return fail("API_POLL_REQUIRED_FIELD"); + if (value == null || value.isNull()) insert.setObject(index + 1, null); + else if (value.isObject() || value.isArray()) return fail("API_POLL_COMPLEX_FIELD"); + else insert.setString(index + 1, value.asText()); + } + if (source.incrementalMarker() != null) { + JsonNode marker = row.get(source.incrementalMarker()); + if (marker == null || !marker.isTextual()) return fail("API_POLL_MARKER_MISSING"); + Instant candidate = Instant.parse(marker.asText()); + if (watermark == null || candidate.isAfter(watermark)) watermark = candidate; + } + insert.addBatch(); + } + insert.executeBatch(); + } + connection.commit(); + written += rows.size(); + } + boolean more = switch (source.paginationMode()) { + case "CURSOR" -> { + JsonNode next = at(root, source.cursorResponseField()); + cursor = next == null || next.isNull() ? null : next.asText(); + yield cursor != null && !cursor.isBlank(); + } + case "LINK_HEADER" -> { + link = nextLink(response.headers().firstValue("Link").orElse(null), endpoint); + yield link != null; + } + default -> rows.size() >= profile.pageSize(); + }; + if (!more || rows.isEmpty()) break; + if (page == source.maxPages()) return fail("API_POLL_PAGE_LIMIT"); + Thread.sleep(Math.max(1, 60_000L / source.rateLimitPerMinute())); + } + return new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", written, + watermark == null ? request.watermark() : watermark.toString(), null); + } + } catch (PollFailure failure) { + return fail(failure.code); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); return fail("API_POLL_INTERRUPTED"); + } catch (IllegalArgumentException exception) { + return fail("API_POLL_TARGET_NOT_UNIQUE".equals(exception.getMessage()) ? + "API_POLL_TARGET_NOT_UNIQUE" : "API_POLL_CONTRACT_INVALID"); + } catch (Exception exception) { + return fail("API_POLL_EXECUTION_UNKNOWN"); + } + } + + private HttpResponse sendData(DataCollectionIntegrationService.ApiPollRequest request, + ApiPollProfile profile, URI uri, String body, + String authSecret, String signingSecret) throws Exception { + String cacheKey = request.orgScopeId() + ":" + request.intakeId() + ":" + request.snapshot().secretRef() + + ":" + profile.authKind() + ":" + profile.tokenEndpoint() + ":" + profile.clientId() + + ":" + profile.tokenFormat() + ":" + profile.tokenPath() + ":" + profile.expiresPath() + + ":" + profile.tokenClientField() + ":" + profile.tokenSecretField() + + ":" + profile.tokenCredentialStyle(); + boolean refresh = false; + for (int attempt = 0; attempt < 3; attempt++) { + boolean forceRefresh = refresh; + String token = dynamic(profile) ? token(cacheKey, profile, authSecret, forceRefresh) : authSecret; + refresh = false; + URI signedUri = uri; + String signature = null, timestamp = null, nonce = null; + if (!"NONE".equals(profile.signatureKind())) { + timestamp = Long.toString(Instant.now().getEpochSecond()); + byte[] random = new byte[16]; RANDOM.nextBytes(random); + nonce = HexFormat.of().formatHex(random); + URI unsignedUri = "QUERY".equals(profile.signaturePlacement()) + ? append(append(uri, "timestamp", timestamp), "nonce", nonce) : uri; + signature = sign(profile, signingSecret, unsignedUri, body, timestamp, nonce); + if ("QUERY".equals(profile.signaturePlacement())) + signedUri = append(unsignedUri, profile.signatureHeader(), signature); + } + HttpRequest.Builder builder = HttpRequest.newBuilder(signedUri).timeout(Duration.ofSeconds(30)) + .header("Accept", "application/json"); + if ("API_KEY_HEADER".equals(profile.authKind())) builder.header("X-API-Key", token); + else if (!"SIGN_ONLY".equals(profile.authKind())) builder.header("Authorization", "Bearer " + token); + if (signature != null) { + if ("HEADER".equals(profile.signaturePlacement())) { + builder.header("X-Timestamp", timestamp).header("X-Nonce", nonce); + builder.header(profile.signatureHeader(), signature); + } + } + boolean hasContentType = false; + for (var header : profile.headers().entrySet()) { + builder.header(header.getKey(), header.getValue()); + if ("content-type".equalsIgnoreCase(header.getKey())) hasContentType = true; + } + if ("POST".equals(profile.requestMethod())) { + if (!hasContentType) builder.header("Content-Type", "application/json"); + builder.POST(HttpRequest.BodyPublishers.ofString(body)); + } else builder.GET(); + HttpResponse response = http.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream()); + int status = response.statusCode(); + if (status == 401 && dynamic(profile) && !forceRefresh) { + response.body().close(); tokenCache.remove(cacheKey); refresh = true; continue; + } + if ((status == 429 || status >= 500 && status <= 599) && attempt < 2) { + response.body().close(); + long delay = response.headers().firstValue("Retry-After").filter(v -> v.matches("[0-9]{1,2}")) + .map(Long::parseLong).orElse(1L << attempt); + Thread.sleep(Math.min(30_000L, delay * 1000L + RANDOM.nextInt(250))); + continue; + } + return response; + } + throw new PollFailure("API_POLL_RETRY_EXHAUSTED"); + } + + private String token(String key, ApiPollProfile profile, String authSecret, boolean refresh) throws Exception { + Token cached = tokenCache.get(key); + if (!refresh && cached != null && cached.expiresAt().isAfter(Instant.now().plusSeconds(30))) return cached.value(); + URI uri = checked(profile.tokenEndpoint()); + String payload; + String contentType; + String idField = profile.tokenClientField(); + String secretField = profile.tokenSecretField(); + boolean basic = "BASIC".equals(profile.tokenCredentialStyle()); + if ("JSON".equals(profile.tokenFormat())) { + payload = (basic ? "{" : "{\"" + idField + "\":" + + JsonUtils.getObjectMapper().writeValueAsString(profile.clientId()) + ",\"" + secretField + "\":" + + JsonUtils.getObjectMapper().writeValueAsString(authSecret) + + ("CLIENT_CREDENTIALS".equals(profile.authKind()) ? "," : "")) + + ("CLIENT_CREDENTIALS".equals(profile.authKind()) ? "\"grant_type\":\"client_credentials\"" : "") + "}"; + contentType = "application/json"; + } else { + payload = (basic ? "" : encode(idField) + "=" + encode(profile.clientId()) + "&" + + encode(secretField) + "=" + encode(authSecret)) + + ("CLIENT_CREDENTIALS".equals(profile.authKind()) ? (basic ? "" : "&") + "grant_type=client_credentials" : ""); + contentType = "application/x-www-form-urlencoded"; + } + HttpRequest.Builder authBuilder = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(15)) + .header("Content-Type", contentType).header("Accept", "application/json"); + if (basic) authBuilder.header("Authorization", "Basic " + Base64.getEncoder().encodeToString( + (profile.clientId() + ":" + authSecret).getBytes(StandardCharsets.UTF_8))); + HttpRequest auth = authBuilder.POST(HttpRequest.BodyPublishers.ofString(payload)).build(); + HttpResponse response = http.send(auth, HttpResponse.BodyHandlers.ofInputStream()); + if (response.statusCode() != 200) { + response.body().close(); throw new PollFailure("API_POLL_TOKEN_HTTP_" + response.statusCode()); + } + JsonNode root = JsonUtils.getObjectMapper().readTree(new String(read(response.body(), 65536), StandardCharsets.UTF_8)); + JsonNode value = at(root, profile.tokenPath()); + if (value == null || !value.isTextual() || value.asText().isBlank() || value.asText().length() > 8192) + throw new PollFailure("API_POLL_TOKEN_RESPONSE_INVALID"); + JsonNode expiry = profile.expiresPath() == null ? null : at(root, profile.expiresPath()); + long seconds = expiry == null ? 300 : Long.parseLong(expiry.asText()); + if (seconds < 1 || seconds > 86400) throw new PollFailure("API_POLL_TOKEN_EXPIRY_INVALID"); + tokenCache.put(key, new Token(value.asText(), Instant.now().plusSeconds(seconds))); + return value.asText(); + } + + static String sign(ApiPollProfile profile, String secret, URI uri, String body, + String timestamp, String nonce) throws Exception { + String pathQuery = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()); + String input = profile.signatureTemplate().replace("${method}", profile.requestMethod()) + .replace("${path}", uri.getRawPath()).replace("${query}", uri.getRawQuery() == null ? "" : uri.getRawQuery()) + .replace("${pathQuery}", pathQuery).replace("${bodySha256}", sha256(body)) + .replace("${body}", body).replace("${timestamp}", timestamp).replace("${nonce}", nonce); + if (input.contains("${")) throw new PollFailure("API_POLL_SIGNATURE_TEMPLATE_INVALID"); + byte[] signed; + if ("HMAC_SHA256".equals(profile.signatureKind())) { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + signed = mac.doFinal(input.getBytes(StandardCharsets.UTF_8)); + } else { + String pemBegin = "-----BEGIN " + "PRIVATE KEY-----"; + String pemEnd = "-----END " + "PRIVATE KEY-----"; + String pem = secret.replace(pemBegin, "").replace(pemEnd, "").replaceAll("\\s", ""); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem)))); + signer.update(input.getBytes(StandardCharsets.UTF_8)); + signed = signer.sign(); + } + return "HEX".equals(profile.signatureEncoding()) ? HexFormat.of().formatHex(signed) : + Base64.getEncoder().encodeToString(signed); + } + + private URI pageUri(URI base, DataCollectionIntegrationService.FileExecutionSnapshot source, + ApiPollProfile profile, Page position) { + URI uri = base; + for (var item : profile.queryParameters().entrySet()) { + if (position.watermark() == null && "${watermark}".equals(item.getValue())) continue; + uri = append(uri, item.getKey(), expand(item.getValue(), position, "RAW")); + } + switch (source.paginationMode()) { + case "PAGE_SIZE" -> { uri = append(uri, source.paginationField(), Integer.toString(position.number())); + uri = append(uri, "size", Integer.toString(profile.pageSize())); } + case "OFFSET_LIMIT" -> { uri = append(uri, source.paginationField(), + Integer.toString((position.number() - 1) * profile.pageSize())); + uri = append(uri, "limit", Integer.toString(profile.pageSize())); } + case "CURSOR" -> { if (position.cursor() != null) uri = append(uri, source.paginationField(), position.cursor()); + uri = append(uri, "size", Integer.toString(profile.pageSize())); } + default -> { } + } + boolean explicitWatermark = profile.queryParameters().values().stream().anyMatch(v -> v.contains("${watermark}")) || + profile.requestBody() != null && profile.requestBody().contains("${watermark}"); + if (source.incrementalMarker() != null && position.watermark() != null && !explicitWatermark) + uri = append(uri, source.incrementalMarker(), position.watermark()); + return uri; + } + + private static String body(ApiPollProfile profile, Page page) { + if (profile.requestBody() == null) return ""; + boolean form = profile.headers().entrySet().stream().anyMatch(e -> + "content-type".equalsIgnoreCase(e.getKey()) && e.getValue().startsWith("application/x-www-form-urlencoded")); + return expand(profile.requestBody(), page, form ? "FORM" : "JSON"); + } + + private static String expand(String template, Page page, String mode) { + String watermark = page.watermark() == null ? "" : page.watermark(); + String cursor = page.cursor() == null ? "" : page.cursor(); + if ("FORM".equals(mode)) { watermark = encode(watermark); cursor = encode(cursor); } + else if ("JSON".equals(mode)) { watermark = jsonEscape(watermark); cursor = jsonEscape(cursor); } + return template.replace("${page}", Integer.toString(page.number())) + .replace("${size}", Integer.toString(page.size())) + .replace("${offset}", Integer.toString((page.number() - 1) * page.size())) + .replace("${watermark}", watermark).replace("${cursor}", cursor); + } + + private static String jsonEscape(String value) { + return value.replace("\\", "\\\\").replace("\"", "\\\"") + .replace("\n", "\\n").replace("\r", "\\r"); + } + + private static URI append(URI base, String name, String value) { + String raw = base.toASCIIString(); + String separator = base.getRawQuery() == null ? "?" : "&"; + return URI.create(raw + separator + encode(name) + "=" + encode(value)); + } + + private URI checked(String value) { + var checked = endpointVerifier.validate(value); + if (!checked.accepted() || checked.redirects() != 0 || checked.finalUri() == null || + !checked.finalUri().equals(URI.create(value))) + throw new PollFailure(checked.errorCode() == null ? "API_POLL_ENDPOINT_INVALID" : checked.errorCode()); + return checked.finalUri(); + } + + private static URI nextLink(String header, URI origin) { + if (header == null || header.length() > 2048) return null; + for (String part : header.split(",")) { + if (!part.contains("rel=\"next\"") && !part.contains("rel=next")) continue; + int start = part.indexOf('<'), end = part.indexOf('>'); + if (start < 0 || end <= start) throw new PollFailure("API_POLL_NEXT_LINK_INVALID"); + URI next = origin.resolve(part.substring(start + 1, end)); + if (!origin.getScheme().equalsIgnoreCase(next.getScheme()) || + !origin.getHost().equalsIgnoreCase(next.getHost()) || origin.getPort() != next.getPort()) + throw new PollFailure("API_POLL_NEXT_LINK_ORIGIN_CHANGED"); + return next; + } + return null; + } + + private static byte[] read(InputStream body, int maximum) throws Exception { + try (InputStream stream = body) { + byte[] bytes = stream.readNBytes(maximum + 1); + if (bytes.length > maximum) throw new PollFailure("API_POLL_RESPONSE_TOO_LARGE"); + return bytes; + } + } + + private static void requireUniqueKey(Connection connection, String[] object) throws Exception { + try (PreparedStatement statement = connection.prepareStatement("SHOW CREATE TABLE `" + object[0] + "`.`" + object[1] + "`"); + ResultSet rows = statement.executeQuery()) { + if (!rows.next() || rows.getString(2) == null || !rows.getString(2).toUpperCase().contains("UNIQUE KEY")) + throw new IllegalArgumentException("API_POLL_TARGET_NOT_UNIQUE"); + } + } + + private static JsonNode rows(JsonNode root, String path) { + return path == null || path.isBlank() || "$".equals(path) ? root : at(root, path.replace("[*]", "")); + } + + private static JsonNode at(JsonNode root, String path) { + if (!path(path)) return null; + JsonNode current = root; + if ("$".equals(path)) return current; + for (String segment : path.substring(2).split("\\.")) { + if (current == null) return null; + current = current.get(segment); + } + return current; + } + + private static void validateProfile(ApiPollProfile p) { + if (!Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY").contains(p.authKind()) || + !Set.of("GET", "POST").contains(p.requestMethod()) || p.pageSize() == null || + p.pageSize() < 1 || p.pageSize() > 1000 || p.lookbackSeconds() == null || + p.lookbackSeconds() < 0 || p.lookbackSeconds() > 86400 || + !Set.of("NONE", "HMAC_SHA256", "RSA_SHA256").contains(p.signatureKind()) || + p.headers() == null || p.queryParameters() == null || p.headers().size() > 20 || + p.queryParameters().size() > 20 || (p.requestBody() != null && p.requestBody().length() > 8192)) + throw new PollFailure("API_POLL_PROFILE_INVALID"); + if (dynamic(p) && (p.tokenEndpoint() == null || p.clientId() == null || + !Set.of("FORM", "JSON").contains(p.tokenFormat()) || !path(p.tokenPath()) || + !IDENTIFIER.matcher(p.tokenClientField() == null ? "" : p.tokenClientField()).matches() || + !IDENTIFIER.matcher(p.tokenSecretField() == null ? "" : p.tokenSecretField()).matches() || + !Set.of("BODY", "BASIC").contains(p.tokenCredentialStyle()))) + throw new PollFailure("API_POLL_TOKEN_CONFIG_INVALID"); + if ("SIGN_ONLY".equals(p.authKind()) && "NONE".equals(p.signatureKind())) + throw new PollFailure("API_POLL_SIGNATURE_CONFIG_INVALID"); + if (!"NONE".equals(p.signatureKind()) && (p.signingSecretRef() == null && !"SIGN_ONLY".equals(p.authKind()) || + p.signatureTemplate() == null || p.signatureTemplate().isBlank() || + !Set.of("HEADER", "QUERY").contains(p.signaturePlacement()) || + !("HEADER".equals(p.signaturePlacement()) ? HEADER : IDENTIFIER) + .matcher(p.signatureHeader() == null ? "" : p.signatureHeader()).matches() || + !Set.of("BASE64", "HEX").contains(p.signatureEncoding()))) + throw new PollFailure("API_POLL_SIGNATURE_CONFIG_INVALID"); + for (var item : p.headers().entrySet()) if (item.getKey() == null || item.getValue() == null || + !HEADER.matcher(item.getKey()).matches() || + Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key") + .contains(item.getKey().toLowerCase()) || item.getValue().contains("\r") || + item.getValue().contains("\n") || item.getValue().length() > 1024) + throw new PollFailure("API_POLL_HEADER_INVALID"); + for (var item : p.queryParameters().entrySet()) if (item.getKey() == null || !valid(item.getKey()) || + Set.of("token", "access_token", "secret", "password", "api_key").contains(item.getKey().toLowerCase()) || + item.getValue() == null || item.getValue().length() > 1024) + throw new PollFailure("API_POLL_QUERY_INVALID"); + } + + private static ApiPollProfile defaults() { + return new ApiPollProfile("STATIC_BEARER", null, "FORM", null, + "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in", + "GET", Map.of(), Map.of(), null, 100, 0, null, null, "NONE", null, + "HEADER", "X-Sign", "BASE64", null); + } + + private static boolean dynamic(ApiPollProfile p) { + return "CLIENT_CREDENTIALS".equals(p.authKind()) || "PASSWORD_TOKEN".equals(p.authKind()); + } + + private static String sha256(String body) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8))); + } + private static String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } + private static boolean valid(String value) { return value != null && IDENTIFIER.matcher(value).matches(); } + private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); } + private static DataCollectionIntegrationService.ApiPollResult fail(String code) { + return new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, code); + } +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/M3DataCollectionIntegrationDubboService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/M3DataCollectionIntegrationDubboService.java index 3b55f68..9f81ae1 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/M3DataCollectionIntegrationDubboService.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/M3DataCollectionIntegrationDubboService.java @@ -34,6 +34,7 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn private final DataSourceRegistry dataSourceRegistry; private final SeaTunnelAdapter seaTunnel; private final M2SecretReader secrets; + private final ApiPollExecutor apiPoll; private final M3LakehouseDirectoryVerifier lakehouse; private final M3ControlledFileStore controlledFiles; private final VisualPreviewJdbcAdapter visualPreview; @@ -81,6 +82,7 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn this.dataSourceRegistry = dataSourceRegistry; this.seaTunnel = seaTunnel; this.secrets = secrets; + this.apiPoll = secrets == null ? null : new ApiPollExecutor(secrets); this.lakehouse = new M3LakehouseDirectoryVerifier(secrets, hive); this.controlledFiles = controlledFiles; this.visualPreview = visualPreview; @@ -98,12 +100,20 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn this.dataSourceRegistry = dataSourceRegistry; this.seaTunnel = null; this.secrets = null; + this.apiPoll = null; this.lakehouse = null; this.controlledFiles = null; this.visualPreview = visualPreview; this.batchTarget = new M3BatchTargetVerifier(null); } + @Override + public ApiPollResult pollApi(ApiPollRequest request) { + return apiPoll == null || request == null + ? new ApiPollResult("UNKNOWN", 0, null, "API_POLL_ADAPTER_UNAVAILABLE") + : apiPoll.run(request); + } + @Override public LakehouseDirectoryResult validateLakehouseDirectory(LakehouseDirectoryRequest request) { if (lakehouse == null) { diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeCollectionDubboService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeCollectionDubboService.java index aa35a11..59f3707 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeCollectionDubboService.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeCollectionDubboService.java @@ -25,6 +25,43 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService if(actor<=0||org<=0||sources.find(new DataSourceAccessScope(actor,org),source)==null)return List.of(); return relays.options(org,source); } + @Override public SourceDefaults sourceDefaults(long actor,long org,long sourceId) { + if(actor<=0 || org<=0)throw new IllegalArgumentException("无权访问数据源"); + var scope=new DataSourceAccessScope(actor,org); + var s=sources.find(scope,sourceId); + if(s==null)throw new IllegalArgumentException("数据源不存在或无权访问"); + String schema=null,database=null,pdb=null,rootService=null,warning=null; + try(var db=connections.open(s,scope);var st=db.createStatement()) { + st.setQueryTimeout(10); + schema=db.getSchema(); + if("ORACLE".equals(s.type())) { + try(var rs=st.executeQuery("SELECT NAME, CDB FROM V$DATABASE")) { + if(rs.next()) { + database=rs.getString(1); + if("YES".equals(rs.getString(2))) { + try(var ps=db.createStatement()) { + ps.setQueryTimeout(10); + try(var pr=ps.executeQuery("SELECT SYS_CONTEXT('USERENV','CON_NAME') FROM DUAL")) { + if(pr.next() && !"CDB$ROOT".equals(pr.getString(1)))pdb=pr.getString(1); + } + } + } + } + } + if(pdb!=null) { + // Only advertise a service observed in the root container, never guess from the PDB name. + try(var rs=st.executeQuery("SELECT DISTINCT NETWORK_NAME FROM V$SERVICES WHERE CON_ID=1 AND NETWORK_NAME IS NOT NULL AND NAME NOT LIKE 'SYS$%'")) { + var services=new TreeSet();while(rs.next())services.add(rs.getString(1)); + if(services.size()==1)rootService=services.first(); + } catch(SQLException ignored) { /* User can supply a root service if its catalog is not visible. */ } + if(rootService==null)warning="未能唯一识别 CDB 根服务名,请由数据库管理员确认后填写。"; + } + } + } catch(SQLException | RuntimeException ex) { + warning="部分连接参数无法自动读取,请确认数据源连接及元数据读取权限,或手动填写缺失项。"; + } + return new SourceDefaults(s.version(),schema,database,pdb,rootService,warning); + } private DataSourceView source(Command c) { if(c == null || c.actorId() <= 0 || c.orgId() <= 0 || c.spec() == null || c.target() == null) throw new IllegalArgumentException("实时采集配置不完整"); @@ -48,7 +85,12 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService t.externalSpaceId(),p.targetTable(),t.serviceAccount(),secrets.resolve(t.secretRef()), "cdc_"+c.taskId()+"_"+c.attempt(),p.checkpointSeconds()); } - @Override public Check check(Command c) { + @Override public Check check(Command c) {return check(c,false);} + @Override public Check prepare(Command c) { + if(c==null || c.attempt()!=0)return rejected("仅未启动的任务可检查并准备目标表"); + return check(c,true); + } + private Check check(Command c,boolean prepare) { String stage="解析连接配置"; try { var s=source(c); var p=c.spec(); var t=c.target(); @@ -62,6 +104,7 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService } } List fields=new ArrayList<>(), keys=new ArrayList<>(), signatures=new ArrayList<>(); + List targetFields; stage="连接"+s.type()+"源库"; try(var db="MYSQL".equals(s.type()) ? connect(s.host(),s.port(),p.sourceDatabase(),s.userName(),secrets.resolve(s.secretRef())) : connections.open(s,new DataSourceAccessScope(c.actorId(),c.orgId())); @@ -80,6 +123,7 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService try(var rs=st.executeQuery("SELECT * FROM "+NativeCdcSource.table(s,p)+" WHERE 1=0")) { var md=rs.getMetaData(); if(md.getColumnCount()>200) return rejected("首期每表最多支持200个字段"); + targetFields=RealtimeTargetTable.fields(md,s.type()); for(int i=1;i<=md.getColumnCount();i++) { fields.add(md.getColumnName(i)); signatures.add(md.getColumnName(i)+":"+md.getColumnTypeName(i)+":"+md.getPrecision(i)+":"+md.getScale(i)); @@ -92,10 +136,9 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService try(var db=connect(t.endpointHost(),t.endpointPort(),t.externalSpaceId(),t.serviceAccount(),secrets.resolve(t.secretRef())); var st=db.createStatement()) { st.setQueryTimeout(15); - stage="读取Doris目标表定义"; - try(var rs=st.executeQuery("SHOW CREATE TABLE `"+t.externalSpaceId()+"`.`"+p.targetTable()+"`")) { - if(!rs.next()) return rejected("请先创建目标表"); - String ddl=rs.getString(2); + stage=prepare?"检查并准备Doris目标表":"读取Doris目标表定义"; + String ddl=RealtimeTargetTable.prepare(st,t.externalSpaceId(),p.targetTable(),targetFields,keys,prepare); + { var matcher=java.util.regex.Pattern.compile("(?is)UNIQUE\\s+KEY\\s*\\(([^)]+)\\)").matcher(ddl); if(!matcher.find()) return rejected("Doris目标表必须为Unique Key模型"); var targetKeys=Arrays.stream(matcher.group(1).replace("`", "").split(",")).map(String::trim).toList(); @@ -104,9 +147,7 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService } stage="读取Doris目标表字段"; try(var rs=st.executeQuery("SELECT * FROM `"+t.externalSpaceId()+"`.`"+p.targetTable()+"` WHERE 1=0")) { - var md=rs.getMetaData(); var targetFields=new ArrayList(); - for(int i=1;i<=md.getColumnCount();i++) targetFields.add(md.getColumnName(i)); - if(!fields.equals(targetFields)) return rejected("首期要求目标表与源表字段名称、顺序完全一致"); + RealtimeTargetTable.compatible(targetFields,rs.getMetaData()); } if("initial".equals(p.startupMode()) && c.attempt()<=1 && c.recovery()==null) { stage="检查Doris目标表是否为空"; @@ -118,7 +159,7 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService if(p.cdcChannel()!=null)signatures.add(relays.fingerprint(c)); String fingerprint=hash(p.fingerprintText()+"|"+s.version()+"|"+s.host()+"|"+s.port()+"|"+s.secretRef()+"|"+ s.userName()+"|"+t.endpointHost()+"|"+t.endpointPort()+"|"+t.serviceAccount()+"|"+t.secretRef()+"|"+t.externalSpaceId()+"|"+signatures); - return new Check(true,p.cdcChannel()==null?"源库日志、主键与目标表结构检查通过;启动后核验同步结果": + return new Check(true,p.cdcChannel()==null?(prepare?"源库与目标表准备完成;缺失目标表已创建,已有表未修改,可以启动采集":"源库日志、主键与目标表结构检查通过;启动后核验同步结果"): "日志通道绑定、源表和目标表检查通过;需确认上游已输出全量及完整变更消息,Kafka连接与真实消息在启动后验证",fingerprint,fields,keys); } catch(IllegalArgumentException e) { return rejected(e.getMessage()); } catch(Exception e) { return rejected(checkFailure(stage,e)); } @@ -132,7 +173,7 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService boolean dorisMissingTable=code==1105 && (message.contains("unknown table") || message.matches("(?s).*table[^\\n]*(does not exist|doesn't exist|not exist|not found).*")); if(code==1049 || code==4060 || code==12514 || code==1105 && message.contains("unknown database")) reason="数据库或连接服务不存在、未注册或无权访问,请核对所选数据库及服务名"; - else if(code==1146 || code==942 || code==208 || "42S02".equals(state) || dorisMissingTable) reason="表不存在或无权读取(也可能是系统视图),请核对架构、表名及大小写;Doris目标表需要预先创建"; + else if(code==1146 || code==942 || code==208 || "42S02".equals(state) || dorisMissingTable) reason="表不存在或无权读取(也可能是系统视图),请核对模式、表名及大小写;目标表缺失时请检查并准备"; else if(code==1105 && (message.contains("access denied") || message.contains("permission denied"))) reason="账号缺少此步骤需要的权限"; else if(code==1045 || code==1017 || code==18456 || state.startsWith("28")) reason="账号认证失败,请检查此端的账号和托管密码"; else if(Set.of(1044,1142,1143,1227,1031,229,297).contains(code) || "42501".equals(state)) reason="账号缺少此步骤需要的权限"; @@ -153,11 +194,23 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService return unknown(expected,"源数据源不在当前授权范围"); if(!expected.equals(externalId)) return unknown(expected,"外部作业身份不一致"); if("RECREATE".equals(action)) { - if(engine.absentFromIdleEngine(expected)) - return new Result("ABSENT",expected,"已核实引擎无运行或排队作业,旧作业记录不存在;历史执行结果不作推断",null,null,null); - return unknown(expected,"未清理:引擎仍有作业、记录仍存在或查询失败,请核实后重试"); + if(engine.absentFromEngine(expected)) + return new Result("ABSENT",expected,"已核实旧作业记录不存在,且旧作业不在运行或排队队列;历史执行结果不作推断",null,null,null); + return unknown(expected,"未清理:旧作业仍在运行或排队、记录仍存在,或引擎查询失败,请核实后重试"); } - if("START".equals(action) || "RESUME".equals(action)) { + if("START".equals(action) || "RESUME".equals(action) || "RETRY".equals(action)) { + if("RETRY".equals(action)) { + String prior=RealtimeCollectionService.jobId(c.orgId(),c.taskId(),c.attempt()-1); + var evidence=c.recovery(); + var old=engine.queryJob(prior); + var checkpoint=engine.checkpoint(prior); + if(c.attempt()<2 || evidence==null || !prior.equals(evidence.jobId()) || evidence.checkpointId()!=null || + !Set.of("FAILED","CANCELED").contains(evidence.status()) || + !prior.equals(old.jobId()) || !RealtimeCollectionService.jobName(c.taskId(),c.attempt()-1).equals(old.jobName()) || + !Set.of("FAILED","CANCELED").contains(old.status().name()) || checkpoint.completed() || + !"SEATUNNEL_CHECKPOINT_NOT_COMPLETED".equals(checkpoint.errorCode())) + return new Result("REJECTED",expected,"未重试:需确认原作业已失败或停止且没有已完成检查点;请先同步状态,有检查点请使用检查并恢复",null,null,null); + } DataSourceView s; try {s=source(c);} catch(RuntimeException ex) { return new Result("REJECTED",expected,"来源版本、目标配置或受管凭据已变化,请重新校验",null,null,null); @@ -172,7 +225,8 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService return new Result("REJECTED",expected,"恢复证据不完整、作业仍在运行或引擎不可查询;未启动新采集",null,null,null); } var job=executionJob(c,s); - if("RESUME".equals(action))job.withObject("env").put("aixun.restore.checkpoint",Long.parseLong(c.recovery().checkpointId())); + if("RESUME".equals(action))job.withObject("env").put("aixun.restore.checkpoint", + c.recovery().checkpointId()==null?0:Long.parseLong(c.recovery().checkpointId())); var result=engine.submitStreaming(RealtimeCollectionService.identity(c.orgId(),c.taskId(),c.attempt()), c.fingerprint(),name,job,restoreId); if("CDC_CHECKPOINT_UNAVAILABLE".equals(result.errorCode()))return new Result("REJECTED",expected,result.errorSummary(),null,null,null); @@ -206,8 +260,9 @@ public class RealtimeCollectionDubboService implements RealtimeCollectionService static boolean validRecovery(Command c,String restoreId) { var p=c.recovery();String id=RealtimeCollectionService.jobId(c.orgId(),c.taskId(),c.attempt()); return p!=null && id.equals(restoreId) && id.equals(p.jobId()) && - Set.of("CANCELED","FAILED").contains(p.status()) && p.checkpointId()!=null && - p.checkpointId().matches("[0-9]{1,18}") && c.fingerprint()!=null && c.fingerprint().matches("[a-f0-9]{64}"); + (Set.of("CANCELED","FAILED").contains(p.status()) && p.checkpointId()!=null || "UNKNOWN".equals(p.status())) && + (p.checkpointId()==null || p.checkpointId().matches("[0-9]{1,18}")) && + c.fingerprint()!=null && c.fingerprint().matches("[a-f0-9]{64}"); } private static Check rejected(String text) { return new Check(false,text,null,List.of(),List.of()); } private static Result unknown(String id,String text) { return new Result("UNKNOWN",id,text,null,null,null); } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTable.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTable.java new file mode 100644 index 0000000..7639629 --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTable.java @@ -0,0 +1,122 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import cn.aixunkeji.datagov.integration.api.datasource.*; +import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*; +import java.sql.*; +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** Fixed CDC Unique Key DDL only. Never alters, drops or truncates an existing table. */ +final class RealtimeTargetTable { + record Field(String name,String type,boolean nullable) { } + private static final Pattern TYPE=Pattern.compile("([A-Z0-9]+)(?:\\((\\d+)(?:,(\\d+))?\\))?"); + private RealtimeTargetTable() { } + + static List fields(ResultSetMetaData md,String vendor) throws SQLException { + var fields=new ArrayList(); + for(int i=1;i<=md.getColumnCount();i++) { + String name=md.getColumnName(i);quote(name); + if(md.isNullable(i)==ResultSetMetaData.columnNullableUnknown) + throw new IllegalArgumentException("字段“"+name+"”的可空性无法确认,不能准备目标表"); + int precision=md.getPrecision(i),scale=md.getScale(i); + String nativeType=md.getColumnTypeName(i); + String jdbc;try{jdbc=JDBCType.valueOf(md.getColumnType(i)).getName();}catch(IllegalArgumentException ex){jdbc="OTHER";} + Long bytes=Set.of(Types.CHAR,Types.VARCHAR,Types.NCHAR,Types.NVARCHAR).contains(md.getColumnType(i))?precision*4L:null; + var column=new Column(name,jdbc,i,md.isNullable(i)==ResultSetMetaData.columnNullable,false,nativeType,precision,scale,bytes); + column=switch(vendor){case "ORACLE"->OracleBatchTypes.mark(column);case "DAMENG"->DamengBatchTypes.mark(column); + case "KINGBASE"->KingbaseBatchTypes.mark(column);case "SQLSERVER"->SqlServerBatchTypes.mark(column);default->column;}; + var mapped=DataSourceObjects.mysqlTargetType(column,TargetEngine.DORIS); + if(!mapped.supported())throw new IllegalArgumentException(mapped.errorSummary()); + fields.add(new Field(name,mapped.targetType(),column.nullable())); + } + if(fields.isEmpty() || fields.stream().map(f->f.name().toLowerCase(Locale.ROOT)).distinct().count()!=fields.size()) + throw new IllegalArgumentException("源字段为空或存在重名,无法准备目标表"); + return List.copyOf(fields); + } + + static String ddl(String database,String table,List fields,List keys) { + if(keys.isEmpty() || new HashSet<>(keys).size()!=keys.size())throw new IllegalArgumentException("源表必须有明确的主键"); + var byName=fields.stream().collect(Collectors.toMap(Field::name,f->f)); + var ordered=new ArrayList(); + for(String key:keys) { + var field=byName.get(key); + if(field==null || Set.of("FLOAT","DOUBLE","STRING","BOOLEAN").contains(base(field.type()))) + throw new IllegalArgumentException("主键字段“"+key+"”无法安全用作 Doris Unique Key"); + ordered.add(field); + } + fields.stream().filter(f->!keys.contains(f.name())).forEach(ordered::add); + String columns=ordered.stream().map(f->quote(f.name())+" "+safeType(f.type())+ + (keys.contains(f.name()) || !f.nullable()?" NOT NULL":" NULL")).collect(Collectors.joining(", ")); + String keySql=keys.stream().map(RealtimeTargetTable::quote).collect(Collectors.joining(", ")); + return "CREATE TABLE "+quote(database)+"."+quote(table)+" ("+columns+") ENGINE=OLAP UNIQUE KEY ("+keySql+ + ") DISTRIBUTED BY HASH ("+quote(keys.getFirst())+") BUCKETS 10 PROPERTIES (\"replication_num\"=\"1\", \"enable_unique_key_merge_on_write\"=\"true\")"; + } + + static String definition(Statement st,String object) throws SQLException { + try(var rs=st.executeQuery("SHOW CREATE TABLE "+object)) { + if(!rs.next())throw new SQLException("Table definition unavailable","HY000"); + return rs.getString(2); + } catch(SQLException ex) {if(missing(ex))return null;throw ex;} + } + static boolean missing(SQLException ex) { + String message=Objects.toString(ex.getMessage(),"").toLowerCase(Locale.ROOT); + return ex.getErrorCode()==1146 || "42S02".equals(ex.getSQLState()) || ex.getErrorCode()==1105 && + (message.contains("unknown table") || message.matches("(?s).*table[^\\n]*(does not exist|doesn't exist|not exist|not found).*")); + } + static String prepare(Statement st,String database,String table,List fields,List keys,boolean create) throws SQLException { + String object=quote(database)+"."+quote(table),definition=definition(st,object); + if(definition!=null)return definition; + if(!create)throw new IllegalArgumentException("目标表不存在,请先点击“检查并准备”;启动和恢复不会自动建表"); + String ddl=ddl(database,table,fields,keys); + try{st.execute(ddl);}catch(SQLException ex) { + // A timeout or concurrent creator can leave the table present. Read back once; never blindly repeat DDL. + try{definition=definition(st,object);}catch(SQLException readback){throw ex;} + if(definition==null)throw ex; + return definition; + } + definition=definition(st,object); + if(definition==null)throw new IllegalArgumentException("建表结果尚未确认,请再次检查并准备;不会重复覆盖目标表"); + return definition; + } + static void compatible(List expected,ResultSetMetaData actual) throws SQLException { + if(actual.getColumnCount()!=expected.size())throw new IllegalArgumentException("目标表字段数量不一致:源表 "+expected.size()+",目标表 "+actual.getColumnCount()+";未修改已有表"); + Map indexes=new HashMap<>(); + for(int i=1;i<=actual.getColumnCount();i++)if(indexes.put(actual.getColumnName(i),i)!=null) + throw new IllegalArgumentException("目标表存在重名字段"); + for(var field:expected) { + Integer i=indexes.get(field.name()); + if(i==null)throw new IllegalArgumentException("目标表缺少字段“"+field.name()+"”;未修改已有表"); + String observed=targetType(actual,i); + if(!fits(field.type(),observed))throw new IllegalArgumentException("字段“"+field.name()+"”类型不兼容:需要 "+field.type()+",目标为 "+observed+";未修改已有表"); + if(actual.isNullable(i)==ResultSetMetaData.columnNullableUnknown || field.nullable() && actual.isNullable(i)!=ResultSetMetaData.columnNullable) + throw new IllegalArgumentException("字段“"+field.name()+"”的可空性不兼容;未修改已有表"); + } + } + static boolean fits(String expected,String actual) { + var a=TYPE.matcher(expected);var b=TYPE.matcher(actual);if(!a.matches()||!b.matches())return false; + String x=a.group(1),y=b.group(1);int p=number(a.group(2)),s=number(a.group(3)),q=number(b.group(2)),t=number(b.group(3)); + var integers=List.of("TINYINT","SMALLINT","INT","BIGINT","LARGEINT"); + if(integers.contains(x)&&integers.contains(y))return integers.indexOf(y)>=integers.indexOf(x); + if(Set.of("CHAR","VARCHAR").contains(x))return y.equals("STRING") || Set.of("CHAR","VARCHAR").contains(y)&&q>=p; + if(x.equals("FLOAT")&&y.equals("DOUBLE"))return true; + if(x.equals("DECIMAL")&&integers.contains(y))return s==0 && p<=List.of(2,4,9,18,38).get(integers.indexOf(y)); + if(!x.equals(y))return false; + if(x.equals("DECIMAL"))return t>=s && q-t>=p-s; + if(x.equals("DATETIME"))return q>=p; + return true; + } + private static String targetType(ResultSetMetaData md,int i)throws SQLException { + String raw=md.getColumnTypeName(i).toUpperCase(Locale.ROOT).replace(" ",""); + String base=raw.replaceAll("\\(.*",""); + base=switch(base){case "DECIMALV2","DECIMALV3","NUMERIC"->"DECIMAL";case "DATETIMEV2","TIMESTAMP"->"DATETIME";case "DATEV2"->"DATE";case "INTEGER"->"INT";case "BOOL","BIT"->"BOOLEAN";case "TEXT","LONGTEXT"->"STRING";default->base;}; + if(Set.of("CHAR","VARCHAR").contains(base))return base+"("+md.getPrecision(i)+")"; + if(base.equals("DECIMAL"))return base+"("+md.getPrecision(i)+","+md.getScale(i)+")"; + if(base.equals("DATETIME"))return base+"("+md.getScale(i)+")"; + return base; + } + private static int number(String value){return value==null?0:Integer.parseInt(value);} + private static String base(String value){return value.replaceAll("\\(.*","");} + private static String safeType(String value){if(!TYPE.matcher(value).matches())throw new IllegalArgumentException("不支持的目标字段类型");return value;} + static String quote(String value){if(value==null||!value.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))throw new IllegalArgumentException("库表或字段名称格式不支持");return "`"+value+"`";} +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelAdapter.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelAdapter.java index afa8249..cc2556f 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelAdapter.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelAdapter.java @@ -115,8 +115,8 @@ public class SeaTunnelAdapter { } } - /** Explicit user cleanup only. Fail closed unless the engine has no live/pending work. */ - public boolean absentFromIdleEngine(String jobId) { + /** Explicit cleanup only. Other jobs may keep running; the exact job must be absent twice. */ + public boolean absentFromEngine(String jobId) { try { var client=client(); JsonNode before=client.get().uri("/job-info/{jobId}",requireJobId(jobId)).retrieve().body(JsonNode.class); @@ -124,14 +124,18 @@ public class SeaTunnelAdapter { JsonNode pending=client.get().uri("/pending-jobs").retrieve().body(JsonNode.class); JsonNode after=client.get().uri("/job-info/{jobId}",jobId).retrieve().body(JsonNode.class); return before!=null && after!=null && documentedMissingJob(before,jobId) && documentedMissingJob(after,jobId) - && idleQueues(running,pending); + && jobAbsentFromQueues(jobId,running,pending); } catch(RuntimeException e) { return false; } } - static boolean idleQueues(JsonNode running,JsonNode pending) { - return running!=null && running.isArray() && running.isEmpty() && pending!=null - && pending.path("pendingJobs").isArray() && pending.path("pendingJobs").isEmpty() - && pending.path("queueSummary").path("size").isIntegralNumber() - && pending.path("queueSummary").path("size").asLong()==0; + static boolean jobAbsentFromQueues(String jobId, JsonNode running, JsonNode pending) { + if (running == null || !running.isArray() || pending == null || + !pending.path("pendingJobs").isArray() || + !pending.path("queueSummary").path("size").isIntegralNumber()) return false; + for (JsonNode job : running) if (jobId.equals(job.path("jobId").asText())) return false; + for (JsonNode job : pending.path("pendingJobs")) + if (jobId.equals(job.path("jobId").asText())) return false; + // A non-empty queue can contain another task. Its detailed entries must account for its size. + return pending.path("queueSummary").path("size").asLong() == pending.path("pendingJobs").size(); } private static JobInfoResult jobInfoUnavailable(String jobId, String source, String code, String summary) { return new JobInfoResult(jobId, null, source, NormalizedExternalStatus.UNKNOWN, @@ -584,6 +588,11 @@ public class SeaTunnelAdapter { normalizedBody.contains("plugin jar for pluginidentifier")) return new JobResult(requestedJobId, jobName, "PLUGIN_LOAD_REJECTED", NormalizedExternalStatus.FAILED, "SEATUNNEL_PLUGIN_LOAD_FAILED", "采集插件加载失败,任务未启动。请检查插件 JAR 与名称映射,修复采集引擎后重新创建任务"); + if ("SUBMIT".equals(phase) && normalizedBody.contains("failed to resolve oracle database version") && + normalizedBody.contains("unable to create a source for identifier 'oracle-cdc'")) + return new JobResult(requestedJobId, jobName, "ORACLE_SOURCE_REJECTED", NormalizedExternalStatus.FAILED, + "SEATUNNEL_ORACLE_VERSION_UNSUPPORTED", + "Oracle CDC 插件无法识别源库的版本名称,作业创建前已被拒绝。请更新采集插件后重新创建任务"); if("SUBMIT".equals(phase) && body.contains("AIXUN_RESTORE_CHECKPOINT_")) return new JobResult(requestedJobId,jobName,"RECOVERY_REJECTED",NormalizedExternalStatus.FAILED, "CDC_CHECKPOINT_UNAVAILABLE","原作业检查点缺失、损坏或早于已确认进度;已拒绝恢复,不会重新全量采集"); diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedCredentialProperties.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedCredentialProperties.java index 3359502..d977611 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedCredentialProperties.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedCredentialProperties.java @@ -9,6 +9,8 @@ import org.springframework.stereotype.Component; @ConfigurationProperties(prefix = "datagov.managed-credentials") public class ManagedCredentialProperties { private String root = "/var/lib/aixun-datagov/managed-secrets"; + private String keyFile = "/run/secrets/aixun-datagov/m2/api-credential-key"; + private boolean requireEncryption; private boolean allowInsecureLocalHttp; private boolean localNonProduction; } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedFileSecretProvisioner.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedFileSecretProvisioner.java index be6779f..bc9b0d8 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedFileSecretProvisioner.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedFileSecretProvisioner.java @@ -29,9 +29,13 @@ public final class ManagedFileSecretProvisioner implements SecretProvisioner { private static final Set SECRET_MODE = Set.of(PosixFilePermission.OWNER_READ); private final Path root; + private final ManagedSecretCipher cipher; + private final boolean requireEncryption; public ManagedFileSecretProvisioner(ManagedCredentialProperties properties) { this.root = initializeRoot(Path.of(properties.getRoot())); + this.cipher = new ManagedSecretCipher(Path.of(properties.getKeyFile())); + this.requireEncryption = properties.isRequireEncryption(); } @Override @@ -45,7 +49,13 @@ public final class ManagedFileSecretProvisioner implements SecretProvisioner { throw new SecretResolutionException("SECRET_PROVISION_CONFLICT", "Managed credential version already exists"); } Path temporary = null; - byte[] encoded = encode(material); + byte[] clear = encode(material); + if (requireEncryption && !cipher.available()) { + Arrays.fill(clear, (byte) 0); + throw new SecretResolutionException("SECRET_KEY_UNAVAILABLE", "Managed credential encryption key is unavailable"); + } + byte[] encoded = cipher.available() ? cipher.encrypt(clear) : clear; + if (encoded != clear) Arrays.fill(clear, (byte) 0); try { temporary = Files.createTempFile(parent, ".credential-", ".tmp"); Files.setPosixFilePermissions(temporary, TEMP_MODE); diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipher.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipher.java new file mode 100644 index 0000000..6230581 --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipher.java @@ -0,0 +1,64 @@ +package cn.aixunkeji.datagov.integration.secret; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; + +/** Versioned authenticated encryption for managed credential files. The key lives on a separate read-only mount. */ +final class ManagedSecretCipher { + private static final String PREFIX = "DG1:"; + private static final SecureRandom RANDOM = new SecureRandom(); + private final Path keyFile; + + ManagedSecretCipher(Path keyFile) { this.keyFile = keyFile; } + + boolean available() { return Files.isRegularFile(keyFile); } + + byte[] encrypt(byte[] clear) { + try { + byte[] key = key(); + byte[] nonce = new byte[12]; RANDOM.nextBytes(nonce); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce)); + byte[] sealed = cipher.doFinal(clear); + byte[] combined = new byte[nonce.length + sealed.length]; + System.arraycopy(nonce, 0, combined, 0, nonce.length); + System.arraycopy(sealed, 0, combined, nonce.length, sealed.length); + Arrays.fill(key, (byte) 0); + return (PREFIX + Base64.getEncoder().encodeToString(combined)).getBytes(StandardCharsets.US_ASCII); + } catch (Exception failure) { + throw new SecretResolutionException("SECRET_ENCRYPTION_FAILED", "Managed credential could not be encrypted"); + } + } + + char[] decrypt(String encoded) { + try { + byte[] combined = Base64.getDecoder().decode(encoded.substring(PREFIX.length())); + if (combined.length < 29) throw new IllegalArgumentException("ciphertext too short"); + byte[] key = key(); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), + new GCMParameterSpec(128, Arrays.copyOf(combined, 12))); + byte[] clear = cipher.doFinal(combined, 12, combined.length - 12); + char[] material = new String(clear, StandardCharsets.UTF_8).toCharArray(); + Arrays.fill(clear, (byte) 0); Arrays.fill(key, (byte) 0); Arrays.fill(combined, (byte) 0); + return material; + } catch (Exception failure) { + throw new SecretResolutionException("SECRET_DECRYPTION_FAILED", "Managed credential could not be decrypted"); + } + } + + static boolean encrypted(String value) { return value.startsWith(PREFIX); } + + private byte[] key() throws Exception { + byte[] key = Files.readAllBytes(keyFile); + if (key.length != 32) throw new IllegalArgumentException("invalid key length"); + return key; + } +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ReadOnlyFileSecretResolver.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ReadOnlyFileSecretResolver.java index 6d12b63..84d9776 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ReadOnlyFileSecretResolver.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/ReadOnlyFileSecretResolver.java @@ -20,8 +20,14 @@ public final class ReadOnlyFileSecretResolver implements SecretResolver { ); private final Path root; + private final ManagedSecretCipher cipher; public ReadOnlyFileSecretResolver(Path root) { + this(root, Path.of("/run/secrets/aixun-datagov/m2/api-credential-key")); + } + + ReadOnlyFileSecretResolver(Path root, Path keyFile) { + this.cipher = new ManagedSecretCipher(keyFile); try { this.root = root.toRealPath(); } catch (IOException e) { @@ -60,7 +66,7 @@ public final class ReadOnlyFileSecretResolver implements SecretResolver { if (value.isEmpty()) { throw new SecretResolutionException("SECRET_REF_MISSING", "Secret material is unavailable"); } - return new SecretMaterial(value.toCharArray()); + return new SecretMaterial(ManagedSecretCipher.encrypted(value) ? cipher.decrypt(value) : value.toCharArray()); } catch (SecretResolutionException e) { throw e; } catch (IOException | RuntimeException e) { diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutorTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutorTest.java new file mode 100644 index 0000000..e27ec2b --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/ApiPollExecutorTest.java @@ -0,0 +1,213 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService; +import cn.aixunkeji.datagov.integration.m2.M2SecretReader; +import com.sun.net.httpserver.HttpServer; +import cn.hutool.extra.spring.SpringUtil; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import tools.jackson.databind.json.JsonMapper; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** Runs the HTTP parsing and JDBC write path with a loopback transport and isolated JDBC doubles. */ +class ApiPollExecutorTest { + @BeforeAll static void initializeJsonMapper() { + var context = new AnnotationConfigApplicationContext(); + context.registerBean(JsonMapper.class, () -> JsonMapper.builder().findAndAddModules().build()); + context.refresh(); + new SpringUtil().setApplicationContext(context); + } + + @Test void pullsPageWithBearerAndCommitsMappedRowsAndWatermark() throws Exception { + var authorization = new AtomicReference(); + var query = new AtomicReference(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/orders", exchange -> { + authorization.set(exchange.getRequestHeaders().getFirst("Authorization")); + query.set(exchange.getRequestURI().getRawQuery()); + byte[] body = """ + {"data":[{"id":1,"name":"one","updated_at":"2026-11-26T00:00:00Z"}, + {"id":2,"name":"two","updated_at":"2026-11-26T01:00:00Z"}]} + """.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (var output = exchange.getResponseBody()) { output.write(body); } + }); + server.start(); + try { + var secrets = mock(M2SecretReader.class); + when(secrets.resolve("file:///managed/data-source/api?version=v1")).thenReturn("test-token"); + when(secrets.resolve("file:///managed/data-source/doris?version=v1")).thenReturn("test-password"); + Connection connection = mock(Connection.class); + PreparedStatement show = mock(PreparedStatement.class); + PreparedStatement insert = mock(PreparedStatement.class); + ResultSet ddl = mock(ResultSet.class); + when(connection.prepareStatement(startsWith("SHOW CREATE TABLE"))).thenReturn(show); + when(show.executeQuery()).thenReturn(ddl); + when(ddl.next()).thenReturn(true); + when(ddl.getString(2)).thenReturn("CREATE TABLE orders (...) UNIQUE KEY(id)"); + when(connection.prepareStatement(startsWith("INSERT INTO"))).thenReturn(insert); + var executor = new ApiPollExecutor(secrets, + endpoint -> new M3HttpEndpointPolicy.Validation(true, URI.create(endpoint), 0, null), + (jdbc, user, password) -> { + assertThat(jdbc).startsWith("jdbc:mysql://doris.test:9030/testdb"); + assertThat(user).isEqualTo("loader"); + assertThat(password).isEqualTo("test-password"); + return connection; + }, HttpClient.newHttpClient()); + String endpoint = "http://127.0.0.1:" + server.getAddress().getPort() + "/orders"; + var snapshot = new DataCollectionIntegrationService.FileExecutionSnapshot("API_SAAS", "api-test", + "GENERIC_HTTPS_JSON", endpoint, "BEARER", "file:///managed/data-source/api?version=v1", + "PAGE_SIZE", "page", null, 1, 60, "updated_at", null, null, null, + "$.data[*]", List.of(), 11L, 12L, "testdb.orders", List.of( + new DataCollectionIntegrationService.FileSchemaField(1, "id", "id", "INT", false), + new DataCollectionIntegrationService.FileSchemaField(2, "name", "name", "STRING", false), + new DataCollectionIntegrationService.FileSchemaField(3, "updated_at", "updated_at", "STRING", false))); + var target = new DataCollectionIntegrationService.StorageExecutionProfile(11L, 12L, "DORIS", + "catalog", "testdb", null, "doris.test", 9030, "loader", + "file:///managed/data-source/doris?version=v1", false); + var result = executor.run(new DataCollectionIntegrationService.ApiPollRequest(1, 1, 1, null, + snapshot, target)); + assertThat(result.status()).isEqualTo("SUCCEEDED"); + assertThat(result.writtenRows()).isEqualTo(2); + assertThat(result.watermark()).isEqualTo("2026-11-26T01:00:00Z"); + assertThat(authorization.get()).isEqualTo("Bearer test-token"); + assertThat(query.get()).contains("page=1", "size=100"); + verify(insert, times(2)).addBatch(); + verify(insert).executeBatch(); + verify(connection).commit(); + } finally { + server.stop(0); + } + } + + @Test void obtainsTokenSignsPostRetriesRateLimitAndAdvancesWatermark() throws Exception { + var tokenCalls = new AtomicInteger(); + var dataCalls = new AtomicInteger(); + var observedQuery = new AtomicReference(); + var observedBody = new AtomicReference(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/token", exchange -> { + tokenCalls.incrementAndGet(); + assertThat(exchange.getRequestMethod()).isEqualTo("POST"); + assertThat(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)) + .contains("client_id=client-test", "client_secret=auth-secret", "grant_type=client_credentials"); + byte[] value = "{\"access_token\":\"issued-token\",\"expires_in\":3600}" + .getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, value.length); + try (var out = exchange.getResponseBody()) { out.write(value); } + }); + server.createContext("/orders", exchange -> { + int call = dataCalls.incrementAndGet(); + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + observedQuery.set(exchange.getRequestURI().getRawQuery()); + observedBody.set(body); + assertThat(exchange.getRequestMethod()).isEqualTo("POST"); + assertThat(exchange.getRequestHeaders().getFirst("Authorization")).isEqualTo("Bearer issued-token"); + String canonical = "POST\n" + exchange.getRequestURI().getRawPath() + "?" + + exchange.getRequestURI().getRawQuery() + "\n" + body + "\n" + + exchange.getRequestHeaders().getFirst("X-Timestamp") + "\n" + + exchange.getRequestHeaders().getFirst("X-Nonce"); + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec("sign-secret".getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + assertThat(exchange.getRequestHeaders().getFirst("X-Sign")) + .isEqualTo(Base64.getEncoder().encodeToString(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)))); + } catch (Exception failure) { throw new RuntimeException(failure); } + if (call == 1) { + exchange.sendResponseHeaders(401, -1); + } else if (call == 2) { + exchange.getResponseHeaders().set("Retry-After", "0"); + exchange.sendResponseHeaders(429, -1); + } else { + byte[] value = (body.contains("\"page\":1") + ? "{\"success\":true,\"data\":[{\"id\":3,\"updated_at\":\"2026-11-26T01:00:00Z\"}]}" + : "{\"success\":true,\"data\":[]}").getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, value.length); + try (var out = exchange.getResponseBody()) { out.write(value); } + } + }); + server.start(); + try { + var secrets = mock(M2SecretReader.class); + when(secrets.resolve("auth-ref")).thenReturn("auth-secret"); + when(secrets.resolve("sign-ref")).thenReturn("sign-secret"); + when(secrets.resolve("doris-ref")).thenReturn("doris-secret"); + Connection connection = mock(Connection.class); + PreparedStatement show = mock(PreparedStatement.class); + PreparedStatement insert = mock(PreparedStatement.class); + ResultSet ddl = mock(ResultSet.class); + when(connection.prepareStatement(startsWith("SHOW CREATE TABLE"))).thenReturn(show); + when(show.executeQuery()).thenReturn(ddl); + when(ddl.next()).thenReturn(true); + when(ddl.getString(2)).thenReturn("CREATE TABLE orders (...) UNIQUE KEY(id)"); + when(connection.prepareStatement(startsWith("INSERT INTO"))).thenReturn(insert); + var executor = new ApiPollExecutor(secrets, + endpoint -> new M3HttpEndpointPolicy.Validation(true, URI.create(endpoint), 0, null), + (jdbc, user, password) -> connection, HttpClient.newHttpClient()); + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + var snapshot = new DataCollectionIntegrationService.FileExecutionSnapshot("API_SAAS", "orders", + "GENERIC_HTTPS_JSON", base + "/orders", "BEARER", "auth-ref", "PAGE_SIZE", "page", + null, 3, 600, "updated_at", null, null, null, "$.data[*]", List.of(), + 11L, 12L, "testdb.orders", List.of( + new DataCollectionIntegrationService.FileSchemaField(1, "id", "id", "INT", false), + new DataCollectionIntegrationService.FileSchemaField(2, "updated_at", "updated_at", "STRING", false))); + var target = new DataCollectionIntegrationService.StorageExecutionProfile(11L, 12L, "DORIS", + "catalog", "testdb", null, "doris.test", 9030, "loader", "doris-ref", false); + var profile = new DataCollectionIntegrationService.ApiPollProfile("CLIENT_CREDENTIALS", base + "/token", + "FORM", "client-test", "client_id", "client_secret", "BODY", + "$.access_token", "$.expires_in", "POST", Map.of(), + Map.of("status", "paid"), "{\"page\":${page},\"size\":${size}}", 1, 60, + "$.success", "true", "HMAC_SHA256", + "${method}\n${pathQuery}\n${body}\n${timestamp}\n${nonce}", + "HEADER", "X-Sign", "BASE64", "sign-ref"); + var result = executor.run(new DataCollectionIntegrationService.ApiPollRequest(1, 1, 1, + "2026-11-26T00:00:00Z", snapshot, target, profile)); + assertThat(result.status()).isEqualTo("SUCCEEDED"); + assertThat(result.writtenRows()).isEqualTo(1); + assertThat(result.watermark()).isEqualTo("2026-11-26T01:00:00Z"); + assertThat(tokenCalls.get()).isEqualTo(2); + assertThat(dataCalls.get()).isEqualTo(4); + assertThat(observedBody.get()).contains("\"page\":2", "\"size\":1"); + assertThat(observedQuery.get()).contains("status=paid", "page=2", "size=1", "updated_at="); + verify(connection).commit(); + } finally { server.stop(0); } + } + + @Test void rsaSignatureUsesManagedPkcs8KeyAndCanonicalTemplate() throws Exception { + var pair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + var profile = new DataCollectionIntegrationService.ApiPollProfile("SIGN_ONLY", null, "FORM", null, + "client_id", "client_secret", "BODY", null, null, "GET", Map.of(), Map.of(), null, 100, 0, null, null, + "RSA_SHA256", "${method}\n${pathQuery}\n${timestamp}\n${nonce}\n", "HEADER", "X-Sign", + "BASE64", null); + String pem = "-----BEGIN " + "PRIVATE KEY-----\n" + + Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()) + "\n-----END " + "PRIVATE KEY-----"; + String signature = ApiPollExecutor.sign(profile, pem, URI.create("https://api.example.com/orders?page=1"), + "", "123", "nonce-test"); + var verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(pair.getPublic()); + verifier.update("GET\n/orders?page=1\n123\nnonce-test\n".getBytes(StandardCharsets.UTF_8)); + assertThat(verifier.verify(Base64.getDecoder().decode(signature))).isTrue(); + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeRetryTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeRetryTest.java new file mode 100644 index 0000000..53de7d5 --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeRetryTest.java @@ -0,0 +1,27 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import cn.aixunkeji.datagov.integration.api.*; +import cn.aixunkeji.datagov.integration.m2.*; +import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; +import static org.assertj.core.api.Assertions.*; + +class RealtimeRetryTest { + @Test void retryNeverSubmitsWhenOldJobIsLiveUnknownOrHasCheckpoint(){ + for(var state:new NormalizedExternalStatus[]{NormalizedExternalStatus.RUNNING,NormalizedExternalStatus.UNKNOWN,NormalizedExternalStatus.FAILED}){ + var registry=mock(DataSourceRegistry.class); + var engine=mock(SeaTunnelAdapter.class); + when(registry.find(any(),eq(1L))).thenReturn(mock(DataSourceView.class)); + String old=RealtimeCollectionService.jobId(3,4,1), next=RealtimeCollectionService.jobId(3,4,2); + when(engine.queryJob(old)).thenReturn(new SeaTunnelAdapter.JobInfoResult(old,RealtimeCollectionService.jobName(4,1),state.name(),state,null,null,null,null,null)); + boolean completed=state==NormalizedExternalStatus.FAILED; + when(engine.checkpoint(old)).thenReturn(new SeaTunnelAdapter.CheckpointResult(old,completed,completed?"42":null,42,null,null,completed?null:"SEATUNNEL_CHECKPOINT_NOT_COMPLETED",null)); + var service=new RealtimeCollectionDubboService(registry,null,engine,null,null); + var spec=new RealtimeCollectionService.Spec("retry",1,0,"db","t",2,3,"target",8030,"initial",30,1001); + var c=new RealtimeCollectionService.Command(2,3,4,2,spec,null,"fingerprint",new RealtimeCollectionService.RecoveryEvidence(old,"FAILED",null)); + assertThat(service.execute(c,"RETRY",next,null).status()).isEqualTo("REJECTED"); + verify(engine,never()).submitStreaming(anyString(),anyString(),anyString(),any(),any()); + } + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeSourceDefaultsTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeSourceDefaultsTest.java new file mode 100644 index 0000000..66c73b7 --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeSourceDefaultsTest.java @@ -0,0 +1,46 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import cn.aixunkeji.datagov.integration.api.*; +import cn.aixunkeji.datagov.integration.m2.DataSourceRegistry; +import cn.aixunkeji.datagov.integration.datasource.DataSourceObjectConnection; +import java.sql.*; +import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; +import static org.assertj.core.api.Assertions.*; + +class RealtimeSourceDefaultsTest { + @Test void discoversPdbAndRootServiceWithoutGuessing() throws Exception { + for(int serviceCount:new int[]{0,1,2}) { + var registry=mock(DataSourceRegistry.class); + var connections=mock(DataSourceObjectConnection.class); + var source=mock(DataSourceView.class); + when(registry.find(any(),eq(7L))).thenReturn(source); + when(source.type()).thenReturn("ORACLE");when(source.version()).thenReturn(5L); + var db=mock(Connection.class);when(connections.open(eq(source),any())).thenReturn(db); + when(db.getSchema()).thenReturn("FINANCE"); + var st=mock(Statement.class);var ps=mock(Statement.class); + when(db.createStatement()).thenReturn(st,ps); + var database=mock(ResultSet.class);when(st.executeQuery("SELECT NAME, CDB FROM V$DATABASE")).thenReturn(database); + when(database.next()).thenReturn(true,false);when(database.getString(1)).thenReturn("FREE");when(database.getString(2)).thenReturn("YES"); + var pdb=mock(ResultSet.class);when(ps.executeQuery(anyString())).thenReturn(pdb); + when(pdb.next()).thenReturn(true,false);when(pdb.getString(1)).thenReturn("FREEPDB1"); + var services=mock(ResultSet.class);when(st.executeQuery(contains("V$SERVICES"))).thenReturn(services); + if(serviceCount==0)when(services.next()).thenReturn(false); + else if(serviceCount==1)when(services.next()).thenReturn(true,false); + else when(services.next()).thenReturn(true,true,false); + when(services.getString(1)).thenReturn("FREE","OTHER"); + var result=new RealtimeCollectionDubboService(registry,null,null,connections,null).sourceDefaults(1,2,7); + assertThat(result.sourceSchema()).isEqualTo("FINANCE");assertThat(result.oracleDatabase()).isEqualTo("FREE"); + assertThat(result.oraclePdb()).isEqualTo("FREEPDB1");assertThat(result.sourceVersion()).isEqualTo(5); + assertThat(result.oracleCdbService()).isEqualTo(serviceCount==1?"FREE":null); + if(serviceCount!=1)assertThat(result.warning()).isNotBlank(); + } + } + @Test void unauthorizedSourceCannotOpenConnection() { + var registry=mock(DataSourceRegistry.class);var connections=mock(DataSourceObjectConnection.class); + var service=new RealtimeCollectionDubboService(registry,null,null,connections,null); + assertThatThrownBy(()->service.sourceDefaults(1,2,7)).isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(connections); + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTableTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTableTest.java new file mode 100644 index 0000000..b9ffc4f --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/batchingestion/RealtimeTargetTableTest.java @@ -0,0 +1,73 @@ +package cn.aixunkeji.datagov.integration.batchingestion; + +import java.sql.*; +import java.util.*; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; + +class RealtimeTargetTableTest { + private final List fields=List.of(new RealtimeTargetTable.Field("name","VARCHAR(40)",true),new RealtimeTargetTable.Field("id","BIGINT",false)); + @Test void createsFixedUniqueKeyTableWithKeyColumnsFirstAndRejectsUnsafeKeys() { + String ddl=RealtimeTargetTable.ddl("db","target",fields,List.of("id")); + assertThat(ddl).startsWith("CREATE TABLE `db`.`target` (`id` BIGINT NOT NULL, `name` VARCHAR(40) NULL)") + .contains("UNIQUE KEY (`id`)","enable_unique_key_merge_on_write", "DISTRIBUTED BY HASH (`id`)").doesNotContain("DROP","ALTER","TRUNCATE"); + assertThatThrownBy(()->RealtimeTargetTable.ddl("db","t",fields,List.of())).hasMessageContaining("主键"); + assertThatThrownBy(()->RealtimeTargetTable.ddl("db;DROP","t",fields,List.of("id"))).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(()->RealtimeTargetTable.ddl("db","t",List.of(new RealtimeTargetTable.Field("id","STRING",false)),List.of("id"))).hasMessageContaining("主键"); + } + private ResultSet definition(String ddl)throws Exception {var rs=mock(ResultSet.class);when(rs.next()).thenReturn(true,false);when(rs.getString(2)).thenReturn(ddl);return rs;} + @Test void missingTableIsCreatedOnceAndReadBack()throws Exception { + var st=mock(Statement.class); + when(st.executeQuery(startsWith("SHOW CREATE TABLE"))).thenThrow(new SQLException("missing","42S02",1146)).thenReturn(definition("created")); + assertThat(RealtimeTargetTable.prepare(st,"db","t",fields,List.of("id"),true)).isEqualTo("created"); + verify(st,times(1)).execute(startsWith("CREATE TABLE")); + } + @Test void existingTableIsNeverChanged()throws Exception { + var st=mock(Statement.class);var existing=definition("existing");when(st.executeQuery(anyString())).thenReturn(existing); + assertThat(RealtimeTargetTable.prepare(st,"db","t",fields,List.of("id"),true)).isEqualTo("existing");verify(st,never()).execute(anyString()); + } + @Test void startupDoesNotRecreateMissingTableAndPermissionFailureIsNotAbsence()throws Exception { + var st=mock(Statement.class);when(st.executeQuery(anyString())).thenThrow(new SQLException("missing","42S02",1146)); + assertThatThrownBy(()->RealtimeTargetTable.prepare(st,"db","t",fields,List.of("id"),false)).hasMessageContaining("检查并准备"); + verify(st,never()).execute(anyString()); + var denied=mock(Statement.class);when(denied.executeQuery(anyString())).thenThrow(new SQLException("denied","42000",1142)); + assertThatThrownBy(()->RealtimeTargetTable.prepare(denied,"db","t",fields,List.of("id"),true)).isInstanceOf(SQLException.class); + verify(denied,never()).execute(anyString()); + } + @Test void timeoutOrConcurrentCreateIsReconciledWithoutRepeatingDdl()throws Exception { + var st=mock(Statement.class);when(st.executeQuery(anyString())).thenThrow(new SQLException("missing","42S02",1146)).thenReturn(definition("confirmed")); + when(st.execute(anyString())).thenThrow(new SQLTimeoutException()); + assertThat(RealtimeTargetTable.prepare(st,"db","t",fields,List.of("id"),true)).isEqualTo("confirmed");verify(st,times(1)).execute(anyString()); + var unknown=mock(Statement.class);when(unknown.executeQuery(anyString())).thenThrow(new SQLException("missing","42S02",1146)); + when(unknown.execute(anyString())).thenThrow(new SQLTimeoutException()); + assertThatThrownBy(()->RealtimeTargetTable.prepare(unknown,"db","t",fields,List.of("id"),true)).isInstanceOf(SQLTimeoutException.class);verify(unknown,times(1)).execute(anyString()); + } + @Test void compatibilityRejectsNarrowingAndAllowsLosslessWidening() { + assertThat(RealtimeTargetTable.fits("DECIMAL(12,2)","DECIMAL(15,3)")).isTrue(); + assertThat(RealtimeTargetTable.fits("DECIMAL(12,2)","DECIMAL(12,3)")).isFalse(); + assertThat(RealtimeTargetTable.fits("VARCHAR(40)","VARCHAR(10)")).isFalse(); + assertThat(RealtimeTargetTable.fits("VARCHAR(40)","STRING")).isTrue(); + assertThat(RealtimeTargetTable.fits("DATETIME(6)","DATETIME(0)")).isFalse(); + assertThat(RealtimeTargetTable.fits("BIGINT","INT")).isFalse(); + } + @Test void existingTableCanReorderColumnsButMustPreserveTypesAndNullability()throws Exception { + var md=mock(ResultSetMetaData.class);when(md.getColumnCount()).thenReturn(2); + when(md.getColumnName(1)).thenReturn("id");when(md.getColumnName(2)).thenReturn("name"); + when(md.getColumnTypeName(1)).thenReturn("BIGINT");when(md.getColumnTypeName(2)).thenReturn("VARCHAR"); + when(md.getPrecision(2)).thenReturn(40);when(md.isNullable(1)).thenReturn(ResultSetMetaData.columnNoNulls);when(md.isNullable(2)).thenReturn(ResultSetMetaData.columnNullable); + RealtimeTargetTable.compatible(fields,md); + when(md.getPrecision(2)).thenReturn(10); + assertThatThrownBy(()->RealtimeTargetTable.compatible(fields,md)).hasMessageContaining("name", "VARCHAR(40)", "VARCHAR(10)"); + when(md.getPrecision(2)).thenReturn(40);when(md.isNullable(2)).thenReturn(ResultSetMetaData.columnNoNulls); + assertThatThrownBy(()->RealtimeTargetTable.compatible(fields,md)).hasMessageContaining("可空性"); + } + @Test void oracleDateRetainsTimeAndUnsupportedSourceTypeNamesTheField()throws Exception { + var md=mock(ResultSetMetaData.class);when(md.getColumnCount()).thenReturn(1);when(md.getColumnName(1)).thenReturn("created_at"); + when(md.getColumnTypeName(1)).thenReturn("DATE");when(md.getColumnType(1)).thenReturn(Types.DATE);when(md.isNullable(1)).thenReturn(ResultSetMetaData.columnNullable); + assertThat(RealtimeTargetTable.fields(md,"ORACLE").getFirst().type()).isEqualTo("DATETIME(0)"); + when(md.getColumnTypeName(1)).thenReturn("BLOB");when(md.getColumnType(1)).thenReturn(Types.BLOB); + assertThatThrownBy(()->RealtimeTargetTable.fields(md,"ORACLE")).hasMessageContaining("created_at"); + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourceFormContractTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourceFormContractTest.java index ffb88ac..92a93f7 100644 --- a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourceFormContractTest.java +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourceFormContractTest.java @@ -39,9 +39,13 @@ class DataSourceFormContractTest { "MYSQL: 3306", "POSTGRESQL: 5432", "ORACLE: 1521", + "KINGBASE: 54321", "SQLSERVER: 1433", "if (!form.port || form.port === previousDefaultPort)", - "form.port = defaultPortByType[type]" + "form.port = defaultPortByType[type]", + "type === 'DAMENG' || type === 'ORACLE' || type === 'KINGBASE' || type === 'SQLSERVER') form.useSsl = false", + "if (type === 'POSTGRESQL') form.useSsl = true", + "仅供已允许非 TLS 连接的测试环境使用" ); } @@ -88,17 +92,22 @@ class DataSourceFormContractTest { @Test void deleteRegistrationUsesIndependentPermissionVersionAndRefreshesAfterSuccess() throws IOException { String page = pageSource(); + String actions = Files.readString(repositoryRoot().resolve( + "aixun-ui/src/views/datagov/integration/data-sources/rowActions.ts")); String api = Files.readString(repositoryRoot().resolve( "aixun-ui/src/api/datagov/data-sources/index.ts")); assertThat(page).contains( - "v-hasPermi=\"['aixun:integration:data-source:delete']\"", - "@click=\"removeDataSource(row)\"", + "if (action === 'delete') return removeDataSource(row)", "删除数据源登记", - "不会删除外部数据库或凭据", + "外部数据库和凭据保持不变", "deleteDataSource(row.id, row.version, idempotencyKey('delete'))", "await loadDataSources();" ); + assertThat(actions).contains( + "{ key: 'delete', label: '删除', icon: 'Delete', permission: 'delete' }", + "can(['aixun:integration:data-source:' + action.permission])" + ); assertThat(api).contains( "export function deleteDataSource(", "method: 'delete'", @@ -148,15 +157,15 @@ class DataSourceFormContractTest { .filter(line -> line.startsWith("{ key:")).toList(); assertThat(entries).hasSize(30); List registered = entries.stream().filter(line -> line.contains("registration: true")).toList(); - assertThat(registered).hasSize(7).allSatisfy(entry -> + assertThat(registered).hasSize(8).allSatisfy(entry -> assertThat(entry).contains("type:").containsAnyOf("'SUPPORTED'", "'VERIFYING'")); assertThat(registered.stream().map(entry -> { var matcher = Pattern.compile("type: '([A-Z]+)'").matcher(entry); assertThat(matcher.find()).as("registered catalog entry has a concrete type").isTrue(); return matcher.group(1); - }).toList()).containsExactlyInAnyOrder("MYSQL", "POSTGRESQL", "SQLSERVER", "ORACLE", "DAMENG", "DORIS", "HIVE"); + }).toList()).containsExactlyInAnyOrder("MYSQL", "POSTGRESQL", "SQLSERVER", "ORACLE", "DAMENG", "KINGBASE", "DORIS", "HIVE"); assertThat(entries.stream().filter(entry -> !registered.contains(entry)).toList()) - .hasSize(23).allSatisfy(entry -> { + .hasSize(22).allSatisfy(entry -> { assertThat(entry).doesNotContain("registration:", "'SUPPORTED'"); assertThat(entry).containsAnyOf("status: 'PLANNED'", "status: 'COMPATIBLE'"); }); @@ -167,7 +176,7 @@ class DataSourceFormContractTest { page.indexOf("const supportCatalogVisible")); assertThat(registration).contains("allDatabaseTypes.value.filter(", "Boolean(item.registration && item.type)"); String selectable = page.substring(page.indexOf("const selectableDatabaseTypes"), - page.indexOf("const selectedDatabaseHelp")); + page.indexOf("const healthVisible")); assertThat(selectable).contains( "registrationDatabaseTypes.value.filter(item => item.status === 'SUPPORTED' || item.status === 'VERIFYING')", "if (editingId.value && !selectable.some(item => item.type === form.type))", diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourcePolicyTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourcePolicyTest.java index 4210d8f..e6c6c40 100644 --- a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourcePolicyTest.java +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/DataSourcePolicyTest.java @@ -139,7 +139,7 @@ class DataSourcePolicyTest { assertThatThrownBy(() -> DataSourcePolicy.normalizeRegistration( registration("SQLSERVER", Map.of("serverTimezone", "UTC"), 91L), new DataSourceAccessScope(7, 91))) - .isInstanceOf(DataSourceOperationException.class).hasMessage("SQL Server连接参数不受支持"); + .isInstanceOf(DataSourceOperationException.class).hasMessage("当前数据源连接参数不受支持"); } @Test @@ -186,7 +186,7 @@ class DataSourcePolicyTest { } @Test - void postgresqlWithoutSslRequiresTheExistingExplicitLocalException() { + void postgresqlAndKingbaseWithoutSslRequireTheExistingExplicitLocalException() { ManagedCredentialProperties properties = new ManagedCredentialProperties(); DataSourceTransportPolicy policy = new DataSourceTransportPolicy(properties); @@ -196,12 +196,17 @@ class DataSourcePolicyTest { .hasMessage("PostgreSQL连接必须启用SSL"); assertThatThrownBy(() -> policy.requireApprovedDatabaseTransport("POSTGRESQL", Map.of())) .isInstanceOf(DataSourceOperationException.class); + assertThatThrownBy(() -> policy.requireApprovedDatabaseTransport( + "KINGBASE", Map.of("useSsl", "false"))) + .isInstanceOf(DataSourceOperationException.class) + .hasMessage("人大金仓连接必须启用SSL"); policy.requireApprovedDatabaseTransport("POSTGRESQL", Map.of("useSsl", "true")); policy.requireApprovedDatabaseTransport("MYSQL", Map.of("useSsl", "false")); properties.setLocalNonProduction(true); properties.setAllowInsecureLocalHttp(true); policy.requireApprovedDatabaseTransport("POSTGRESQL", Map.of("useSsl", "false")); + policy.requireApprovedDatabaseTransport("KINGBASE", Map.of("useSsl", "false")); } private static HttpServletRequest request(boolean secure, String forwardedProto) { diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelM3ContractTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelM3ContractTest.java index ae9d94b..1e3e2e0 100644 --- a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelM3ContractTest.java +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/m2/SeaTunnelM3ContractTest.java @@ -27,18 +27,46 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class SeaTunnelM3ContractTest { - @Test void cleanupRequiresExplicitEmptyQueues() { + @Test void cleanupRequiresExactJobAbsentEvenWhenAnotherJobIsRunning() { var mapper=JsonMapper.builder().build(); var running=mapper.createArrayNode(); var pending=mapper.createObjectNode(); - assertThat(SeaTunnelAdapter.idleQueues(running,pending)).isFalse(); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isFalse(); pending.putArray("pendingJobs");pending.putObject("queueSummary").put("size",0); - assertThat(SeaTunnelAdapter.idleQueues(running,pending)).isTrue(); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isTrue(); + running.addObject().put("jobId","456"); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isTrue(); running.addObject().put("jobId","123"); - assertThat(SeaTunnelAdapter.idleQueues(running,pending)).isFalse(); - assertThat(SeaTunnelAdapter.idleQueues(null,pending)).isFalse(); - running.removeAll();pending.withObject("queueSummary").put("size",1); - assertThat(SeaTunnelAdapter.idleQueues(running,pending)).isFalse(); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isFalse(); + running.removeAll(); + pending.withArray("pendingJobs").addObject().put("jobId","123"); + pending.withObject("queueSummary").put("size",1); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isFalse(); + pending.withArray("pendingJobs").removeAll(); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",running,pending)).isFalse(); + assertThat(SeaTunnelAdapter.jobAbsentFromQueues("123",null,pending)).isFalse(); + } + + @Test void oracleVersionParserFailureIsReportedAsPreSubmissionRejection() throws Exception { + var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + var posts = new AtomicInteger(); + server.createContext("/", exchange -> { + if ("POST".equals(exchange.getRequestMethod())) { + posts.incrementAndGet(); + json(exchange, 500, "Unable to create a source for identifier 'Oracle-CDC': Failed to resolve Oracle database version"); + } else { + String id = exchange.getRequestURI().getPath().substring("/job-info/".length()); + json(exchange, 200, "{\"jobId\":\"" + id + "\"}"); + } + }); + server.start(); + try { + var result = localAdapter(server).submitTracked("oracle:banner:submit", "a".repeat(64), + "oracle-banner", JsonUtils.getObjectMapper().createObjectNode()); + assertThat(result.status()).isEqualTo(NormalizedExternalStatus.FAILED); + assertThat(result.errorCode()).isEqualTo("SEATUNNEL_ORACLE_VERSION_UNSUPPORTED"); + assertThat(posts).hasValue(1); + } finally { server.stop(0); } } private static AnnotationConfigApplicationContext jsonContext; diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipherTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipherTest.java new file mode 100644 index 0000000..6a70343 --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/secret/ManagedSecretCipherTest.java @@ -0,0 +1,51 @@ +package cn.aixunkeji.datagov.integration.secret; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class ManagedSecretCipherTest { + @TempDir Path directory; + + @Test + void ciphertextDoesNotExposeTokenAndTamperingFailsClosed() throws Exception { + byte[] key = new byte[32]; new SecureRandom().nextBytes(key); + Path keyFile = directory.resolve("key"); Files.write(keyFile, key); + ManagedSecretCipher cipher = new ManagedSecretCipher(keyFile); + String token = "sensitive-test-token"; + String sealed = new String(cipher.encrypt(token.getBytes(StandardCharsets.UTF_8)), StandardCharsets.US_ASCII); + assertThat(sealed).startsWith("DG1:").doesNotContain(token); + assertThat(cipher.decrypt(sealed)).isEqualTo(token.toCharArray()); + int position = 12; + char old = sealed.charAt(position); + String changed = sealed.substring(0, position) + (old == 'A' ? 'B' : 'A') + sealed.substring(position + 1); + assertThatThrownBy(() -> cipher.decrypt(changed)).isInstanceOf(SecretResolutionException.class); + } + + @Test + void provisionedCredentialIsEncryptedAndCanBeResolved() throws Exception { + byte[] key = new byte[32]; new SecureRandom().nextBytes(key); + Path keyFile = directory.resolve("key"); Files.write(keyFile, key); + Path root = directory.resolve("secrets"); + ManagedCredentialProperties properties = new ManagedCredentialProperties(); + properties.setRoot(root.toString()); + properties.setKeyFile(keyFile.toString()); + properties.setRequireEncryption(true); + SecretRef reference = new SecretRef("file:///managed/data-source/api-test?version=v1"); + new ManagedFileSecretProvisioner(properties).provision(reference, "test-bearer-token".toCharArray()); + Path stored = root.resolve("managed/data-source/api-test"); + assertThat(Files.readString(stored)).startsWith("DG1:").doesNotContain("test-bearer-token"); + try (SecretMaterial resolved = new ReadOnlyFileSecretResolver(root, keyFile).resolve(reference, + new SecretResolveContext(0L, Set.of(reference.fingerprint())))) { + assertThat(resolved.copy()).isEqualTo("test-bearer-token".toCharArray()); + } + } +} diff --git a/aixun-ui/src/api/datagov/api-ingestion.ts b/aixun-ui/src/api/datagov/api-ingestion.ts new file mode 100644 index 0000000..2c60a6e --- /dev/null +++ b/aixun-ui/src/api/datagov/api-ingestion.ts @@ -0,0 +1,66 @@ +import request from '@/utils/request'; +import type { AxiosPromise } from '@/utils/api-types'; +import type { FileId } from './file-ingestion/types'; + +export interface ApiPollState { + intakeId: FileId; + enabled: boolean; + watermark?: string; + nextDueAt?: string; + lastStatus: string; + lastErrorCode?: string; + lastWrittenRows: number; + lastRunAt?: string; +} + +export interface ApiPollRun { + runId: FileId; + triggerType: string; + status: string; + writtenRows: number; + errorCode?: string; + watermarkBefore?: string; + watermarkAfter?: string; + startedAt?: string; + completedAt?: string; +} + +export interface ApiPollProfile { + authKind: 'STATIC_BEARER' | 'CLIENT_CREDENTIALS' | 'PASSWORD_TOKEN' | 'API_KEY_HEADER' | 'SIGN_ONLY'; + tokenEndpoint?: string; + tokenFormat?: 'FORM' | 'JSON'; + clientId?: string; + tokenClientField?: string; + tokenSecretField?: string; + tokenCredentialStyle?: 'BODY' | 'BASIC'; + tokenPath?: string; + expiresPath?: string; + requestMethod: 'GET' | 'POST'; + headers: Record; + queryParameters: Record; + requestBody?: string; + pageSize: number; + lookbackSeconds: number; + successPath?: string; + successValue?: string; + signatureKind: 'NONE' | 'HMAC_SHA256' | 'RSA_SHA256'; + signatureTemplate?: string; + signaturePlacement?: 'HEADER' | 'QUERY'; + signatureHeader?: string; + signatureEncoding?: 'BASE64' | 'HEX'; + signingKey?: string; + signingKeyConfigured?: boolean; +} + +const base = '/api/dataops/v1/api-ingestions'; +export const getApiPoll = (id: FileId): AxiosPromise => request({ url: `${base}/${id}/poll`, method: 'get' }); +export const setApiPolling = (id: FileId, enabled: boolean): AxiosPromise => + request({ url: `${base}/${id}/poll`, method: 'put', data: { enabled } }); +export const runApiPoll = (id: FileId): AxiosPromise => + request({ url: `${base}/${id}/poll/run`, method: 'post', headers: { repeatSubmit: false } }); +export const listApiPollRuns = (id: FileId): AxiosPromise => + request({ url: `${base}/${id}/poll/runs`, method: 'get' }); +export const getApiProfile = (id: FileId): AxiosPromise => + request({ url: `${base}/${id}/profile`, method: 'get' }); +export const saveApiProfile = (id: FileId, profile: ApiPollProfile): AxiosPromise => + request({ url: `${base}/${id}/profile`, method: 'put', data: profile }); diff --git a/aixun-ui/src/api/datagov/realtime-ingestion/index.ts b/aixun-ui/src/api/datagov/realtime-ingestion/index.ts index e457cc3..de9b039 100644 --- a/aixun-ui/src/api/datagov/realtime-ingestion/index.ts +++ b/aixun-ui/src/api/datagov/realtime-ingestion/index.ts @@ -9,12 +9,14 @@ export interface RealtimeSpec { sourceSchema?: string; oracleDatabase?: string; cdcChannel?: string; oraclePdb?: string; oracleCdbService?: string; } export interface CdcRelayOption { id: string; name: string; schema: string; table: string; format: string; } +export interface SourceDefaults { sourceVersion: number; sourceSchema?: string; oracleDatabase?: string; oraclePdb?: string; oracleCdbService?: string; warning?: string; } export interface RealtimeTask { id: string; spec: RealtimeSpec; status: string; version: number; attempt: number; externalId?: string; checkpointId?: string; summary?: string; readRows?: number; writeRows?: number; observedAt?: string; history: Record[]; } const base = '/api/dataops/v1/realtime-ingestions'; +export const getSourceDefaults = (sourceId: string | number): AxiosPromise => request({url:`${base}/source-defaults`,params:{sourceId},timeout:45000,suppressErrorToast:true}); export const listCdcRelays = (sourceId: string | number): AxiosPromise => request({url:`${base}/relay-options`,params:{sourceId}}); export const listRealtime = (pageNum: number, pageSize: number): AxiosPromise<{rows: RealtimeTask[]; total: number}> => request({ url: base, params: { pageNum, pageSize } }); diff --git a/aixun-ui/src/layout/components/Sidebar/menuIcons.ts b/aixun-ui/src/layout/components/Sidebar/menuIcons.ts index 941ada1..60b4a0d 100644 --- a/aixun-ui/src/layout/components/Sidebar/menuIcons.ts +++ b/aixun-ui/src/layout/components/Sidebar/menuIcons.ts @@ -7,7 +7,7 @@ const primaryIcons: Record = { const routeIcons: Record = { '/index': 'home', '/visual-workspace': 'dashboard', '/work-overview': 'chart', '/my-work': 'briefcase', - '/data-sources': 'database', '/unified-ingestion': 'download', '/realtime-ingestion': 'link', '/file-ingestion': 'upload', + '/data-sources': 'database', '/unified-ingestion': 'download', '/realtime-ingestion': 'link', '/api-ingestion': 'link', '/file-ingestion': 'upload', '/storage-resources': 'database', '/lakehouse-layers': 'layers', '/table-files': 'grid', '/enterprise-architecture': 'network', '/subject-layer': 'layers', '/model-repository': 'folder', '/model-design': 'edit', '/model-engineering': 'tools', '/architecture-governance': 'check', '/model-algorithm': 'book', diff --git a/aixun-ui/src/views/datagov/ai-workbench/EngineeringAssist.vue b/aixun-ui/src/views/datagov/ai-workbench/EngineeringAssist.vue index c4fdf26..59225f4 100644 --- a/aixun-ui/src/views/datagov/ai-workbench/EngineeringAssist.vue +++ b/aixun-ui/src/views/datagov/ai-workbench/EngineeringAssist.vue @@ -41,11 +41,13 @@ import ScheduleCanvas from '../dataops/scheduling/ScheduleCanvas.vue'; import { arrangeSchedule, definitionIssues } from '../dataops/scheduling/canvas'; import type { ScheduleDefinition } from '@/api/datagov/schedules/types'; import { adoptScheduleChanges, scheduleDraftChanges } from './scheduleDraftReview'; +import { useAiAvailability } from '@/components/PageAssist/useAiAvailability'; const props = withDefaults(defineProps<{ type: EngineeringType; configuration: object | (() => object); disabled?: boolean; editableKeys?: string[]; editingId?: string | number; editingVersion?: number; sourceTableFileId?: string }>(), { disabled: false, editableKeys: () => [] }); const edited = computed(() => props.editingId === undefined ? undefined : { id: String(props.editingId), version: props.editingVersion ?? -1 }); const evidence = ref>(); let generatedBinding: EngineeringBinding | undefined; const emit = defineEmits<{ adopt: [Content] }>(); -const allowed = computed(() => checkPermi(['aixun:ai:workbench:generate'])); +const aiFeaturesEnabled = useAiAvailability(); +const allowed = computed(() => aiFeaturesEnabled.value && checkPermi(['aixun:ai:workbench:generate'])); const visible = ref(false); const busy = ref(false); const loading = ref(false); const notice = ref(''); const answer = ref(''); const keyword = ref(''); const prompt = ref(''); const selected = ref([]); const chosen = ref([]); const changes = ref([]); const context = ref(emptyBusinessContext()); let baseline: Content = {}; let epoch = 0; let contextEpoch = 0; const field: BusinessField = { name: 'configuration', label: '工程配置', kind: 'OBJECT', required: true, options: [] }; const schedulePreview = computed(() => props.type === 'SCHEDULE' && changes.value.length ? adoptScheduleChanges(baseline, changes.value, chosen.value.length ? chosen.value : changes.value.map(change => change.key)).configuration as unknown as ScheduleDefinition : undefined); @@ -76,5 +78,6 @@ function failure(error: unknown) { return error instanceof Error ? error.message const pretty = (value: unknown) => value === undefined ? '未填写' : JSON.stringify(value, null, 2); onBeforeUnmount(stop); watch(() => [props.type, props.editingId, props.editingVersion, props.disabled, props.sourceTableFileId], () => { stop(); changes.value = []; answer.value = ''; selected.value = []; generatedBinding = undefined; }); +watch(aiFeaturesEnabled, enabled => { if (!enabled) { visible.value = false; stop(); } }); diff --git a/aixun-ui/src/views/datagov/dataops/api-ingestion/index.vue b/aixun-ui/src/views/datagov/dataops/api-ingestion/index.vue new file mode 100644 index 0000000..68814de --- /dev/null +++ b/aixun-ui/src/views/datagov/dataops/api-ingestion/index.vue @@ -0,0 +1,7 @@ + + + diff --git a/aixun-ui/src/views/datagov/dataops/file-ingestion/index.vue b/aixun-ui/src/views/datagov/dataops/file-ingestion/index.vue index 7a6905e..e143fff 100644 --- a/aixun-ui/src/views/datagov/dataops/file-ingestion/index.vue +++ b/aixun-ui/src/views/datagov/dataops/file-ingestion/index.vue @@ -6,9 +6,9 @@ - - - + + + @@ -28,7 +28,7 @@ @@ -226,17 +209,65 @@ - + - + 字节 + + + + + {{ pollingEnabled ? '保存后自动按间隔采集' : '关闭时仅可手动采集' }} + + + + 秒 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -379,7 +420,6 @@ import { import type { FileActionVO, FileApiConnector, - FileAuthMode, FileBatchVO, FileFormat, FileId, @@ -394,18 +434,24 @@ import type { } from '@/api/datagov/file-ingestion/types'; import { displayDatagovStatus } from '@/utils/datagov-display'; import { extractErrorMessage } from '@/utils/request'; +import { getApiPoll, getApiProfile, listApiPollRuns, runApiPoll, saveApiProfile, setApiPolling } from '@/api/datagov/api-ingestion'; +import type { ApiPollProfile, ApiPollRun, ApiPollState } from '@/api/datagov/api-ingestion'; type FileActionType = 'VALIDATE' | 'QUARANTINE' | 'RETRANSMIT'; -const sourceTypeOptions: FileSourceType[] = ['API_SAAS', 'FTP', 'SHARED_DIRECTORY', 'OBJECT_STORAGE']; +const fileSourceTypes: FileSourceType[] = ['SHARED_DIRECTORY', 'FTP', 'OBJECT_STORAGE']; +const props = withDefaults(defineProps<{ kind?: 'api' | 'file' }>(), { kind: 'file' }); +const activeKind = computed(() => props.kind); const statusOptions: FileIngestionStatus[] = ['DRAFT', 'READY', 'SUBMITTED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELED', 'UNKNOWN']; -const connectorOptions: FileApiConnector[] = ['GENERIC_HTTPS_JSON', 'SALESFORCE', 'SERVICENOW']; -const authModeOptions: FileAuthMode[] = ['BASIC', 'BEARER', 'API_KEY', 'OAUTH2_CLIENT_CREDENTIALS']; -const paginationOptions: FilePaginationMode[] = ['OFFSET_LIMIT', 'PAGE_SIZE', 'CURSOR', 'LINK_HEADER']; +const connectorOptions: FileApiConnector[] = ['GENERIC_HTTPS_JSON']; +const paginationOptions: FilePaginationMode[] = ['PAGE_SIZE', 'OFFSET_LIMIT', 'CURSOR', 'LINK_HEADER']; const formatOptions: FileFormat[] = ['CSV', 'JSON', 'JSONL', 'PARQUET', 'ORC', 'XLSX']; const schemaTypeOptions: FileSchemaField['fieldType'][] = ['STRING', 'BOOLEAN', 'TINYINT', 'SMALLINT', 'INT', 'BIGINT', 'FLOAT', 'DOUBLE', 'BYTES', 'DATE', 'TIMESTAMP']; -const query = reactive({ pageNum: 1, pageSize: 20 }); +const query = reactive({ pageNum: 1, pageSize: 20, sourceType: props.kind === 'api' ? 'API_SAAS' : 'SHARED_DIRECTORY' }); const intakes = ref([]); +const pollStates = ref>({}); +const apiRuns = ref([]); +const apiRunDrawerVisible = ref(false); const targetTables = ref([]); const targetTablesLoading = ref(false); const targetTablesError = ref(''); @@ -434,9 +480,14 @@ const currentSecretConfigured = ref(false); const currentAction = ref('VALIDATE'); const currentActionTarget = ref(); const advancedSections = ref([]); +const pollingEnabled = ref(false); +const originalPollingEnabled = ref(false); const configFormRef = ref(); const actionFormRef = ref(); const configForm = reactive(emptyConfig()); +const profileForm = reactive(emptyApiProfile()); +const requestHeadersText = ref('{}'); +const requestQueryText = ref('{}'); const previewBaseline = ref(''); const previewSelection = computed(() => editingIntakeId.value && configForm.version !== undefined ? ({ intakeId: editingIntakeId.value, version: configForm.version, targetTableFileId: configForm.targetTableFileId || null @@ -466,7 +517,7 @@ const configRules: FormRules = { endpoint: [conditionalRequired(() => configForm.sourceType === 'API_SAAS' && (!editingIntakeId.value || !currentEndpointConfigured.value), '请输入HTTPS地址')], paginationMode: [conditionalRequired(() => configForm.sourceType === 'API_SAAS', '请选择分页方式')], rateLimitPerMinute: [conditionalRequired(() => configForm.sourceType === 'API_SAAS', '请输入每分钟限流')], - periodSeconds: [conditionalRequired(() => configForm.sourceType === 'API_SAAS', '请输入采集周期')], + periodSeconds: [conditionalRequired(() => configForm.sourceType === 'API_SAAS' && pollingEnabled.value, '请输入轮询间隔')], paginationField: [conditionalRequired(() => configForm.sourceType === 'API_SAAS', '请输入分页字段')], maxPages: [conditionalRequired(() => configForm.sourceType === 'API_SAAS', '请输入最大分页数')], relativePath: [conditionalRequired(() => configForm.sourceType !== 'API_SAAS', '请输入相对路径')], @@ -507,10 +558,40 @@ function emptyConfig(): FileIntakeForm & { targetTableFileId: string } { }; } +function emptyApiProfile(): ApiPollProfile { + return { + authKind: 'STATIC_BEARER', tokenFormat: 'FORM', tokenPath: '$.access_token', + tokenClientField: 'client_id', tokenSecretField: 'client_secret', tokenCredentialStyle: 'BODY', + expiresPath: '$.expires_in', requestMethod: 'GET', headers: {}, queryParameters: {}, + pageSize: 100, lookbackSeconds: 0, signatureKind: 'NONE', + signatureTemplate: '${method}\n${pathQuery}\n${bodySha256}\n${timestamp}\n${nonce}\n', + signaturePlacement: 'HEADER', signatureHeader: 'X-Sign', signatureEncoding: 'BASE64' + }; +} + +const onApiAuthKindChanged = () => { + if (editingIntakeId.value) { + configForm.password = ''; + currentSecretConfigured.value = false; + } + profileForm.tokenClientField = profileForm.authKind === 'PASSWORD_TOKEN' ? 'username' : 'client_id'; + profileForm.tokenSecretField = profileForm.authKind === 'PASSWORD_TOKEN' ? 'password' : 'client_secret'; + profileForm.tokenCredentialStyle = 'BODY'; +}; + +function requestMap(value: string): Record { + const parsed: unknown = JSON.parse(value || '{}'); + if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object' || + Object.entries(parsed).some(([key, item]) => !key || typeof item !== 'string')) { + throw new Error('请求头和查询参数必须是字符串值的 JSON 对象'); + } + return parsed as Record; +} + const idempotencyKey = (action: string) => `m3:ing:file:${action}:${crypto.randomUUID().replaceAll('-', '')}`; const sourceTypeLabel = (value: FileSourceType) => ({ API_SAAS: 'API/SaaS', FTP: 'FTP', SHARED_DIRECTORY: '共享目录', OBJECT_STORAGE: '对象存储' })[value]; const connectorLabel = (value: FileApiConnector) => ({ GENERIC_HTTPS_JSON: '通用 HTTPS JSON', SALESFORCE: 'Salesforce', SERVICENOW: 'ServiceNow' })[value]; -const authModeLabel = (value: FileAuthMode) => ({ BASIC: 'Basic', BEARER: 'Bearer', API_KEY: 'API Key', OAUTH2_CLIENT_CREDENTIALS: 'OAuth2 客户端凭据' })[value]; +const apiAuthLabel = (value: ApiPollProfile['authKind']) => ({ STATIC_BEARER: '固定 Bearer', CLIENT_CREDENTIALS: '动态 Token(客户端凭据)', PASSWORD_TOKEN: '动态 Token(账号密码)', API_KEY_HEADER: 'API Key 请求头', SIGN_ONLY: '仅请求签名' })[value]; const paginationLabel = (value: FilePaginationMode) => ({ OFFSET_LIMIT: 'Offset/Limit', PAGE_SIZE: 'Page/Size', CURSOR: 'Cursor', LINK_HEADER: 'Link Header' })[value]; const statusLabel = (status: FileIngestionStatus) => displayDatagovStatus(status); const statusType = (status: FileIngestionStatus) => ({ @@ -551,6 +632,11 @@ const loadIntakes = async () => { const response = await pageFileIntakes(query); intakes.value = response.data.rows; total.value = response.data.total; + if (activeKind.value === 'api') { + const settled = await Promise.allSettled(intakes.value.map(row => getApiPoll(row.intakeId))); + pollStates.value = Object.fromEntries(settled.flatMap((item, index) => item.status === 'fulfilled' + ? [[String(intakes.value[index].intakeId), item.value.data]] : [])); + } } catch (error) { intakes.value = []; total.value = 0; @@ -560,19 +646,52 @@ const loadIntakes = async () => { } }; +const runApi = async (row: FileIntakeVO) => { + try { + const response = await runApiPoll(row.intakeId); + ElMessage[response.data.status === 'SUCCEEDED' ? 'success' : 'warning']( + response.data.status === 'SUCCEEDED' ? `采集完成,写入 ${response.data.writtenRows} 行` : `采集待核查:${response.data.errorCode || '结果未知'}`); + await loadIntakes(); + } catch (error) { ElMessage.error((await extractErrorMessage(error)) || 'API采集失败'); } +}; + +const toggleApi = async (row: FileIntakeVO) => { + if (!pollStates.value[String(row.intakeId)]?.enabled) { + await openEdit(row, true); + return; + } + try { + await setApiPolling(row.intakeId, false); + ElMessage.success('轮询已停止'); + await loadIntakes(); + } catch (error) { ElMessage.error((await extractErrorMessage(error)) || '轮询设置失败'); } +}; + +const showApiRuns = async (row: FileIntakeVO) => { + try { + apiRuns.value = (await listApiPollRuns(row.intakeId)).data; + apiRunDrawerVisible.value = true; + } catch (error) { ElMessage.error((await extractErrorMessage(error)) || '轮询记录读取失败'); } +}; + const search = () => { query.pageNum = 1; loadIntakes(); }; const resetQuery = () => { - Object.assign(query, { keyword: undefined, sourceType: undefined, status: undefined, pageNum: 1 }); + Object.assign(query, { keyword: undefined, sourceType: activeKind.value === 'api' ? 'API_SAAS' : 'SHARED_DIRECTORY', status: undefined, pageNum: 1 }); loadIntakes(); }; const resetConfig = () => { Object.assign(configForm, emptyConfig(), { version: undefined }); + Object.assign(profileForm, emptyApiProfile()); + requestHeadersText.value = '{}'; + requestQueryText.value = '{}'; advancedSections.value = []; + pollingEnabled.value = false; + originalPollingEnabled.value = false; editingIntakeId.value = undefined; previewBaseline.value = ''; originalSourceType.value = undefined; @@ -582,20 +701,34 @@ const resetConfig = () => { const openCreate = async () => { resetConfig(); + if (activeKind.value === 'file') { + configForm.sourceType = 'SHARED_DIRECTORY'; + onSourceTypeChanged(); + } configDialogVisible.value = true; await loadTargetTables(); nextTick(() => configFormRef.value?.clearValidate()); }; -const openEdit = async (row: FileIntakeVO) => { +const openEdit = async (row: FileIntakeVO, enablePolling = false) => { try { const response = await getFileIntake(row.intakeId); const detail = response.data; + const pollState = activeKind.value === 'api' ? (await getApiPoll(row.intakeId)).data : undefined; + const savedProfile = activeKind.value === 'api' ? (await getApiProfile(row.intakeId)).data : undefined; resetConfig(); + originalPollingEnabled.value = pollState?.enabled === true; + pollingEnabled.value = originalPollingEnabled.value || enablePolling; + if (enablePolling) advancedSections.value = ['api']; editingIntakeId.value = detail.intakeId; originalSourceType.value = detail.sourceType; currentEndpointConfigured.value = detail.endpointConfigured; currentSecretConfigured.value = detail.secretConfigured; + if (savedProfile) { + Object.assign(profileForm, savedProfile, { signingKey: '' }); + requestHeadersText.value = JSON.stringify(savedProfile.headers || {}, null, 2); + requestQueryText.value = JSON.stringify(savedProfile.queryParameters || {}, null, 2); + } await loadTargetTables(); const target = targetTables.value.find(item => String(item.storageResourceId) === String(detail.targetStorageResourceId) && @@ -607,7 +740,8 @@ const openEdit = async (row: FileIntakeVO) => { sourceType: detail.sourceType, apiConnector: detail.apiConnector, endpoint: '', authMode: detail.authMode, password: '', paginationMode: detail.paginationMode, rateLimitPerMinute: detail.rateLimitPerMinute, incrementalMarker: detail.incrementalMarker || '', - periodSeconds: detail.periodSeconds, relativePath: detail.relativePath, + periodSeconds: detail.sourceType === 'API_SAAS' ? detail.periodSeconds ?? 3600 : detail.periodSeconds, + relativePath: detail.relativePath, fileNamePattern: detail.fileNamePattern, allowedFormats: [...detail.allowedFormats], maxFileSizeBytes: detail.maxFileSizeBytes, minRecordCount: detail.minRecordCount, maxRecordCount: detail.maxRecordCount, paginationField: detail.paginationField || 'page', @@ -660,6 +794,7 @@ const onSourceTypeChanged = () => { const clearCredential = () => { configForm.password = ''; + profileForm.signingKey = ''; }; const closeConfigDialog = () => { @@ -692,6 +827,38 @@ const removeSchemaField = (index: number) => { const saveConfig = async () => { if (!await configFormRef.value?.validate().catch(() => false)) return; + let profilePayload: ApiPollProfile | undefined; + if (activeKind.value === 'api') { + try { + const { signingKeyConfigured, ...profileFields } = profileForm; + void signingKeyConfigured; + profilePayload = { + ...profileFields, + headers: requestMap(requestHeadersText.value), + queryParameters: requestMap(requestQueryText.value), + requestBody: profileForm.requestMethod === 'POST' ? profileForm.requestBody : undefined, + successPath: profileForm.successPath?.trim() || undefined, + successValue: profileForm.successValue?.trim() || undefined, + signingKey: profileForm.signatureKind === 'NONE' || profileForm.authKind === 'SIGN_ONLY' + ? undefined : profileForm.signingKey || undefined + }; + if ((profilePayload.authKind === 'CLIENT_CREDENTIALS' || profilePayload.authKind === 'PASSWORD_TOKEN') && + (!profilePayload.tokenEndpoint || !profilePayload.clientId || !profilePayload.tokenPath)) { + throw new Error('请填写动态 Token 地址、身份和响应路径'); + } + if (profilePayload.authKind === 'SIGN_ONLY' && profilePayload.signatureKind === 'NONE') { + throw new Error('仅签名认证必须开启请求签名'); + } + if (profilePayload.signatureKind !== 'NONE' && profilePayload.authKind !== 'SIGN_ONLY' && + !profileForm.signingKeyConfigured && !profilePayload.signingKey) { + throw new Error('请填写签名密钥'); + } + } catch (error) { + ElMessage.warning(error instanceof Error ? error.message : '高级请求配置无效'); + advancedSections.value = ['request']; + return; + } + } const target = targetTables.value.find(item => String(item.tableFileId) === configForm.targetTableFileId); if (!target || target.executionState !== 'CONFIRMED' || target.engineType !== 'DORIS' || String(target.storageResourceId) !== String(configForm.targetStorageResourceId) || @@ -701,6 +868,7 @@ const saveConfig = async () => { return; } saving.value = true; + let baseSaved = false; try { const { targetTableFileId, version, ...businessForm } = configForm; void targetTableFileId; @@ -719,19 +887,49 @@ const saveConfig = async () => { schema: configForm.schema.map(item => ({ ...item, sourceField: item.sourceField.trim(), targetField: item.targetField.trim() })), - fileNamePattern: configForm.fileNamePattern.trim() + fileNamePattern: activeKind.value === 'api' ? '*' : configForm.fileNamePattern.trim(), + allowedFormats: activeKind.value === 'api' ? ['JSON'] : [...configForm.allowedFormats], + maxFileSizeBytes: activeKind.value === 'api' ? 104857600 : configForm.maxFileSizeBytes, + minRecordCount: activeKind.value === 'api' ? 0 : configForm.minRecordCount, + maxRecordCount: activeKind.value === 'api' ? 10000000 : configForm.maxRecordCount }; + let savedId: FileId; + let savedVersion: number; if (editingIntakeId.value) { - await updateFileIntake(editingIntakeId.value, { ...data, version: configForm.version || 0 }, idempotencyKey('update')); - ElMessage.success('文件接入配置已更新'); + const response = await updateFileIntake(editingIntakeId.value, { ...data, version: configForm.version || 0 }, idempotencyKey('update')); + savedId = response.data.intakeId; + savedVersion = response.data.version; } else { - await createFileIntake(data, idempotencyKey('create')); - ElMessage.success('文件接入配置已创建'); + const response = await createFileIntake(data, idempotencyKey('create')); + savedId = response.data.intakeId; + savedVersion = response.data.version; + } + if (profilePayload) { + editingIntakeId.value = savedId; + configForm.version = savedVersion; + currentEndpointConfigured.value = true; + currentSecretConfigured.value = true; + baseSaved = true; + await saveApiProfile(savedId, profilePayload); + profileForm.signingKeyConfigured = profileForm.signatureKind !== 'NONE'; + profileForm.signingKey = ''; + } + let pollingError = ''; + if (activeKind.value === 'api' && pollingEnabled.value !== originalPollingEnabled.value) { + try { + await setApiPolling(savedId, pollingEnabled.value); + } catch (error) { + pollingError = (await extractErrorMessage(error)) || '轮询状态更新失败'; + } } configDialogVisible.value = false; await loadIntakes(); + if (pollingError) ElMessage.warning(`配置已保存,但${pollingError};请查看轮询状态`); + else ElMessage.success(`${activeKind.value === 'api' ? 'API 采集' : '文件采集'}配置已${editingIntakeId.value ? '更新' : '创建'}`); } catch (error) { - ElMessage.error((await extractErrorMessage(error)) || '文件接入配置保存失败'); + const detail = await extractErrorMessage(error); + ElMessage.error(baseSaved ? `基础配置已保存,高级配置保存失败:${detail || '请重试'}` : + detail || '采集配置保存失败'); } finally { clearCredential(); saving.value = false; @@ -871,3 +1069,8 @@ onMounted(() => { loadIntakes(); }); + + diff --git a/aixun-ui/src/views/datagov/dataops/realtime-ingestion/index.vue b/aixun-ui/src/views/datagov/dataops/realtime-ingestion/index.vue index 03a732a..3dbda40 100644 --- a/aixun-ui/src/views/datagov/dataops/realtime-ingestion/index.vue +++ b/aixun-ui/src/views/datagov/dataops/realtime-ingestion/index.vue @@ -1,7 +1,7 @@