编写CDC 、api采集
这个提交包含在:
@@ -10,6 +10,9 @@ docs
|
||||
outputs
|
||||
tmp
|
||||
.cache
|
||||
/runtime/dev-private
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/node_modules
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
+27
@@ -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<String, String> headers, Map<String, String> 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);
|
||||
|
||||
+4
@@ -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<RelayOption> 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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
+5
@@ -57,6 +57,11 @@ public class GatewayHttpClientProperties {
|
||||
*/
|
||||
private Duration unifiedIngestionSubmitResponseTimeout = Duration.ofSeconds(180);
|
||||
|
||||
/**
|
||||
* 实时采集操作包含源端校验与外部作业提交,须长于 DataOps 的 120 秒 Dubbo 调用时限。
|
||||
*/
|
||||
private Duration realtimeIngestionActionResponseTimeout = Duration.ofSeconds(135);
|
||||
|
||||
/**
|
||||
* 数据画像创建及数字ID重试等待Governance同步执行完成的超时时间
|
||||
*/
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
+52
@@ -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<ApiPollProfileService.View> 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<ApiPollProfileService.View> 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<ApiPollService.PollState> state(@PathVariable long intakeId) { return R.ok(service.state(intakeId)); }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll/runs")
|
||||
public R<List<ApiPollService.PollRun>> 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<ApiPollService.PollState> 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<ApiPollService.PollRun> run(@PathVariable long intakeId) { return R.ok(service.runNow(intakeId)); }
|
||||
}
|
||||
+188
@@ -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<String> AUTH = Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY");
|
||||
private static final Set<String> 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<String, String> headers, Map<String, String> 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<String, String> headers, Map<String, String> 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<String, String> 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 */ } }
|
||||
}
|
||||
+179
@@ -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<PollState> 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<PollRun> 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<long[]> 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<CURRENT_TIMESTAMP)
|
||||
ORDER BY next_due_at FETCH FIRST 10 ROWS ONLY
|
||||
""", (rs, index) -> 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<CURRENT_TIMESTAMP)
|
||||
""" + ("SCHEDULED".equals(trigger) ? " AND enabled=1" : ""), lease, intakeId, actor.orgScopeId());
|
||||
if (claimed != 1) throw FileIngestionException.conflict("该API采集任务正在运行");
|
||||
long runId = IdGeneratorUtil.nextLongId();
|
||||
String before = jdbc.queryForObject("SELECT watermark FROM ing_api_poll_state WHERE intake_id=?",
|
||||
String.class, intakeId);
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_run(run_id,intake_id,org_scope_id,actor_id,trigger_type,
|
||||
started_at,run_status,watermark_before)
|
||||
VALUES(?,?,?,?,?,CURRENT_TIMESTAMP,'RUNNING',?)
|
||||
""", runId, intakeId, actor.orgScopeId(), actor.actorId(), trigger, before);
|
||||
DataCollectionIntegrationService.ApiPollResult result;
|
||||
try {
|
||||
result = integration.pollApi(actor, intakeId, config, before,
|
||||
profiles == null ? null : profiles.profile(actor, intakeId));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
result = new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_GATEWAY_UNKNOWN");
|
||||
}
|
||||
boolean success = result != null && "SUCCEEDED".equals(result.status());
|
||||
String error = success ? null : result == null ? "API_POLL_RESPONSE_MISSING" :
|
||||
FileIngestionPolicy.safeErrorCode(result.errorCode(), "API_POLL_UNKNOWN");
|
||||
String after = success ? result.watermark() : before;
|
||||
int count = success ? Math.max(0, result.writtenRows()) : 0;
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_run SET completed_at=CURRENT_TIMESTAMP,run_status=?,written_rows=?,
|
||||
error_code=?,watermark_after=? WHERE run_id=?
|
||||
""", success ? "SUCCEEDED" : "UNKNOWN", count, error, after, runId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET watermark=?,last_status=?,last_error_code=?,
|
||||
last_written_rows=?,last_run_at=CURRENT_TIMESTAMP,
|
||||
next_due_at=DATEADD(SECOND, ?, CURRENT_TIMESTAMP),lease_id=NULL,lease_until=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? AND lease_id=?
|
||||
""", after, success ? "SUCCEEDED" : "UNKNOWN", error, count,
|
||||
config.periodSeconds(), intakeId, actor.orgScopeId(), lease);
|
||||
return new PollRun(runId, trigger, success ? "SUCCEEDED" : "UNKNOWN", count, error,
|
||||
before, after, null, null);
|
||||
}
|
||||
|
||||
private void ensureState(FileIngestionActor actor, long intakeId) {
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled)
|
||||
SELECT ?,?,?,0 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), intakeId);
|
||||
}
|
||||
|
||||
private FileIngestionPolicy.Config requireApi(FileIngestionActor actor, long intakeId) {
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅API来源可执行轮询");
|
||||
return config;
|
||||
}
|
||||
|
||||
private static boolean supported(FileIngestionPolicy.Config config) {
|
||||
return config.apiConnector() != null && "GENERIC_HTTPS_JSON".equals(config.apiConnector().name()) &&
|
||||
config.authMode() != null && "BEARER".equals(config.authMode().name()) &&
|
||||
config.paginationMode() != null &&
|
||||
config.maxPages() != null && config.maxPages() >= 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(); }
|
||||
}
|
||||
+6
@@ -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));
|
||||
|
||||
+15
-2
@@ -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;
|
||||
|
||||
+2
@@ -18,6 +18,8 @@ public class RealtimeController {
|
||||
public R<cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.SourcePage> sources(@RequestParam(required=false) String keyword){return R.ok(directory.realtimeSources(keyword));}
|
||||
@GetMapping("/relay-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<java.util.List<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.RelayOption>> relays(@RequestParam long sourceId){return R.ok(service.relays(sourceId));}
|
||||
@GetMapping("/source-defaults") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.SourceDefaults> sourceDefaults(@RequestParam long sourceId){return R.ok(service.sourceDefaults(sourceId));}
|
||||
@GetMapping @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.Page> 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")
|
||||
|
||||
+15
-9
@@ -46,6 +46,7 @@ public class RealtimeService {
|
||||
}
|
||||
public View get(long id) {return view(require(id,false),true);}
|
||||
public List<RelayOption> 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;
|
||||
|
||||
+32
-9
@@ -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<Long, List<StorageCapacityDimensionView>> 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<StorageCapacityDimensionView> 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<StorageCapacityDimensionView> 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<StorageCapacityDimensionView> dimensions) {
|
||||
if (dimensions.isEmpty()) {
|
||||
dimensions = legacyDimensions(snapshot);
|
||||
}
|
||||
|
||||
+65
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
+75
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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));
|
||||
|
||||
+11
-2
@@ -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(){
|
||||
|
||||
+20
-4
@@ -153,8 +153,8 @@ final class NativeLogReader implements SourceReader<SeaTunnelRow,NativeLogSource
|
||||
if(positionOnly)return Collections.emptyList();
|
||||
long cutoff=Long.parseLong(next.cursor),end=selected.get(selected.size()-1).last;
|
||||
try{
|
||||
for(int i=0;i<files.size();i++)try(CallableStatement ps=db.prepareCall("CALL DBMS_LOGMNR.ADD_LOGFILE(?, ?)")){
|
||||
ps.setQueryTimeout(30);ps.setString(1,files.get(i));ps.setInt(2,i==0?1:2);ps.execute();
|
||||
for(int i=0;i<files.size();i++)try(CallableStatement ps=db.prepareCall(damengAddLogSql(i==0))){
|
||||
ps.setQueryTimeout(30);ps.setString(1,files.get(i));ps.execute();
|
||||
}
|
||||
// Include unfinished transactions; COMMITTED_DATA_ONLY would hide the very prefix we must pin.
|
||||
try(CallableStatement ps=db.prepareCall("CALL DBMS_LOGMNR.START_LOGMNR(OPTIONS=>2128, ENDSCN=>?)")){ps.setQueryTimeout(60);ps.setLong(1,end);ps.execute();}
|
||||
@@ -205,9 +205,25 @@ final class NativeLogReader implements SourceReader<SeaTunnelRow,NativeLogSource
|
||||
next.cursor=Long.toString(Math.max(cutoff,end));
|
||||
next.archiveSequence=selected.get(selected.size()-1).sequence;
|
||||
next.archives=DamengArchiveWindow.names(retained);next.anchor=next.archives.get(0);
|
||||
endDamengSession(db);
|
||||
return rows;
|
||||
}finally{
|
||||
try(CallableStatement ps=db.prepareCall("CALL DBMS_LOGMNR.END_LOGMNR()")){ps.setQueryTimeout(30);ps.execute();}
|
||||
}catch(SQLException|RuntimeException failure){
|
||||
// Cleanup must never hide the first failure (DM -2846 means no active session).
|
||||
try{endDamengSession(db);}catch(SQLException cleanup){failure.addSuppressed(cleanup);}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
static String damengAddLogSql(boolean first){
|
||||
return "CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR."+(first?"\"NEW\"":"ADDFILE")+")";
|
||||
}
|
||||
|
||||
static void endDamengSession(Connection connection)throws SQLException{
|
||||
try(CallableStatement ps=connection.prepareCall("CALL DBMS_LOGMNR.END_LOGMNR()")){
|
||||
ps.setQueryTimeout(30);ps.execute();
|
||||
}catch(SQLException error){
|
||||
// Already absent is an idempotent cleanup outcome; all other errors remain failures.
|
||||
if(error.getErrorCode()!=-2846)throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+15
@@ -12,6 +12,21 @@ import com.kingbase8.replication.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class NativeLogContractTest {
|
||||
@Test void damengFilesUseNamedAddOptionsRatherThanRemoveOption(){
|
||||
assertEquals("CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR.\"NEW\")",NativeLogReader.damengAddLogSql(true));
|
||||
assertEquals("CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR.ADDFILE)",NativeLogReader.damengAddLogSql(false));
|
||||
}
|
||||
@Test void damengCleanupIsIdempotentButDoesNotSwallowOtherErrors()throws Exception {
|
||||
int[] code={-2846};
|
||||
CallableStatement statement=(CallableStatement)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{CallableStatement.class},(proxy,m,args)->{
|
||||
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;
|
||||
|
||||
+491
@@ -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<String, Token> 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<InputStream> 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<InputStream> 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<InputStream> 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<InputStream> 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);
|
||||
}
|
||||
}
|
||||
+10
@@ -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) {
|
||||
|
||||
+72
-17
@@ -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<String>();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<String> fields=new ArrayList<>(), keys=new ArrayList<>(), signatures=new ArrayList<>();
|
||||
List<RealtimeTargetTable.Field> 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<String>();
|
||||
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); }
|
||||
|
||||
+122
@@ -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<Field> fields(ResultSetMetaData md,String vendor) throws SQLException {
|
||||
var fields=new ArrayList<Field>();
|
||||
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<Field> fields,List<String> 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<Field>();
|
||||
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<Field> fields,List<String> 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<Field> expected,ResultSetMetaData actual) throws SQLException {
|
||||
if(actual.getColumnCount()!=expected.size())throw new IllegalArgumentException("目标表字段数量不一致:源表 "+expected.size()+",目标表 "+actual.getColumnCount()+";未修改已有表");
|
||||
Map<String,Integer> 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+"`";}
|
||||
}
|
||||
+17
-8
@@ -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","原作业检查点缺失、损坏或早于已确认进度;已拒绝恢复,不会重新全量采集");
|
||||
|
||||
+2
@@ -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;
|
||||
}
|
||||
|
||||
+11
-1
@@ -29,9 +29,13 @@ public final class ManagedFileSecretProvisioner implements SecretProvisioner {
|
||||
private static final Set<PosixFilePermission> 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);
|
||||
|
||||
+64
@@ -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;
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -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) {
|
||||
|
||||
+213
@@ -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<String>();
|
||||
var query = new AtomicReference<String>();
|
||||
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<String>();
|
||||
var observedBody = new AtomicReference<String>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+27
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -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);
|
||||
}
|
||||
}
|
||||
+73
@@ -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<RealtimeTargetTable.Field> 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");
|
||||
}
|
||||
}
|
||||
+17
-8
@@ -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<String> 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))",
|
||||
|
||||
+7
-2
@@ -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) {
|
||||
|
||||
+35
-7
@@ -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;
|
||||
|
||||
+51
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
queryParameters: Record<string, string>;
|
||||
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<ApiPollState> => request({ url: `${base}/${id}/poll`, method: 'get' });
|
||||
export const setApiPolling = (id: FileId, enabled: boolean): AxiosPromise<ApiPollState> =>
|
||||
request({ url: `${base}/${id}/poll`, method: 'put', data: { enabled } });
|
||||
export const runApiPoll = (id: FileId): AxiosPromise<ApiPollRun> =>
|
||||
request({ url: `${base}/${id}/poll/run`, method: 'post', headers: { repeatSubmit: false } });
|
||||
export const listApiPollRuns = (id: FileId): AxiosPromise<ApiPollRun[]> =>
|
||||
request({ url: `${base}/${id}/poll/runs`, method: 'get' });
|
||||
export const getApiProfile = (id: FileId): AxiosPromise<ApiPollProfile> =>
|
||||
request({ url: `${base}/${id}/profile`, method: 'get' });
|
||||
export const saveApiProfile = (id: FileId, profile: ApiPollProfile): AxiosPromise<ApiPollProfile> =>
|
||||
request({ url: `${base}/${id}/profile`, method: 'put', data: profile });
|
||||
@@ -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<string, unknown>[];
|
||||
}
|
||||
const base = '/api/dataops/v1/realtime-ingestions';
|
||||
export const getSourceDefaults = (sourceId: string | number): AxiosPromise<SourceDefaults> => request({url:`${base}/source-defaults`,params:{sourceId},timeout:45000,suppressErrorToast:true});
|
||||
export const listCdcRelays = (sourceId: string | number): AxiosPromise<CdcRelayOption[]> => 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 } });
|
||||
|
||||
@@ -7,7 +7,7 @@ const primaryIcons: Record<string, string> = {
|
||||
|
||||
const routeIcons: Record<string, string> = {
|
||||
'/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',
|
||||
|
||||
@@ -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<InstanceType<typeof EngineeringEvidence>>(); 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<string[]>([]); const chosen = ref<string[]>([]); const changes = ref<ContentChange[]>([]); 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(); } });
|
||||
</script>
|
||||
<style scoped>.engineering-assist{margin:8px 0}.answer{white-space:pre-wrap;line-height:1.7}.hint{color:var(--el-text-color-secondary);font-size:13px;line-height:1.7}.candidate-canvas{height:470px;margin:12px 0}pre{max-height:250px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font-family:inherit}</style>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<FileIngestion kind="api" />
|
||||
</template>
|
||||
|
||||
<script setup name="ApiIngestion" lang="ts">
|
||||
import FileIngestion from '../file-ingestion/index.vue';
|
||||
</script>
|
||||
@@ -6,9 +6,9 @@
|
||||
<el-form-item label="关键词">
|
||||
<el-input v-model="query.keyword" clearable maxlength="128" placeholder="请输入配置名称" @keyup.enter="search" />
|
||||
</el-form-item>
|
||||
<el-form-item label="来源类型">
|
||||
<el-select v-model="query.sourceType" clearable placeholder="全部">
|
||||
<el-option v-for="item in sourceTypeOptions" :key="item" :label="sourceTypeLabel(item)" :value="item" />
|
||||
<el-form-item v-if="activeKind === 'file'" label="来源类型">
|
||||
<el-select v-model="query.sourceType" placeholder="请选择来源类型" @change="search">
|
||||
<el-option v-for="item in fileSourceTypes" :key="item" :label="sourceTypeLabel(item)" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
@@ -28,7 +28,7 @@
|
||||
<template #header>
|
||||
<div class="toolbar-shell">
|
||||
<div class="table-heading">
|
||||
<h3>文件接入</h3>
|
||||
<h3>{{ activeKind === 'api' ? 'API 采集' : '文件采集' }}</h3>
|
||||
<p>共 {{ total }} 条记录</p>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
@@ -48,15 +48,16 @@
|
||||
<template #default><el-button link type="primary" @click="loadIntakes">重新加载</el-button></template>
|
||||
</el-alert>
|
||||
|
||||
<el-table v-loading="loading" :data="intakes" row-key="intakeId" border class="data-table" empty-text="暂无文件接入配置">
|
||||
<el-table v-loading="loading" :data="intakes" row-key="intakeId" border class="data-table" empty-text="暂无采集配置">
|
||||
<el-table-column prop="name" label="配置名称" min-width="170" fixed="left" />
|
||||
<el-table-column label="来源类型" width="130">
|
||||
<el-table-column v-if="activeKind === 'file'" label="来源类型" width="130">
|
||||
<template #default="{ row }">{{ sourceTypeLabel(row.sourceType) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="来源" min-width="170" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ sourceSummary(row as FileIntakeVO) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="fileNamePattern" label="文件规则" min-width="150" show-overflow-tooltip />
|
||||
<el-table-column v-if="activeKind === 'file'" prop="fileNamePattern" label="文件规则" min-width="150" show-overflow-tooltip />
|
||||
<el-table-column v-else label="轮询状态" min-width="150"><template #default="{ row }">{{ pollStates[String(row.intakeId)]?.enabled ? '已开启' : '未开启' }} · {{ pollStates[String(row.intakeId)]?.lastStatus || '未运行' }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="105">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="statusType(row.status)" effect="plain">{{ statusLabel(row.status) }}</el-tag>
|
||||
@@ -70,7 +71,7 @@
|
||||
v-hasPermi="['aixun:dataops:file-ingestion:update']"
|
||||
link type="primary" icon="Edit" @click="openEdit(row as FileIntakeVO)">编辑</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="能力校验" placement="top">
|
||||
<el-tooltip v-if="activeKind === 'file'" content="能力校验" placement="top">
|
||||
<el-button
|
||||
v-if="row.status === 'DRAFT' || row.status === 'READY'"
|
||||
v-hasPermi="['aixun:dataops:file-ingestion:update']"
|
||||
@@ -81,13 +82,16 @@
|
||||
v-hasPermi="['aixun:dataops:file-ingestion:delete']"
|
||||
link type="danger" icon="Delete" @click="deleteDraft(row as FileIntakeVO)">删除草稿</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="提交" placement="top">
|
||||
<el-tooltip v-if="activeKind === 'file'" content="提交" placement="top">
|
||||
<el-button
|
||||
v-if="row.status === 'READY'"
|
||||
v-hasPermi="['aixun:dataops:file-ingestion:submit']"
|
||||
link type="primary" icon="Promotion" @click="submitIntake(row as FileIntakeVO)">提交</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="运行与批次" placement="top">
|
||||
<el-button v-if="activeKind === 'api'" v-hasPermi="['aixun:dataops:file-ingestion:submit']" link type="primary" @click="runApi(row as FileIntakeVO)">立即采集</el-button>
|
||||
<el-button v-if="activeKind === 'api' && (pollStates[String(row.intakeId)]?.enabled || row.status === 'DRAFT' || row.status === 'READY')" v-hasPermi="['aixun:dataops:file-ingestion:update']" link type="primary" @click="toggleApi(row as FileIntakeVO)">{{ pollStates[String(row.intakeId)]?.enabled ? '停止轮询' : '配置并开启轮询' }}</el-button>
|
||||
<el-button v-if="activeKind === 'api'" link type="primary" @click="showApiRuns(row as FileIntakeVO)">轮询记录</el-button>
|
||||
<el-tooltip v-if="activeKind === 'file'" content="运行与批次" placement="top">
|
||||
<el-button link type="primary" icon="View" @click="openRuns(row as FileIntakeVO)">运行与批次</el-button>
|
||||
</el-tooltip>
|
||||
<WorkbenchOrigin type="FILE_INGESTION" :object-id="row.intakeId" /></RowActions></template>
|
||||
@@ -105,13 +109,13 @@
|
||||
|
||||
<el-dialog
|
||||
v-model="configDialogVisible"
|
||||
:title="editingIntakeId ? '编辑文件接入' : '新增文件接入'"
|
||||
:title="`${editingIntakeId ? '编辑' : '新增'}${activeKind === 'api' ? 'API 采集' : '文件采集'}`"
|
||||
width="900px"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
@closed="clearCredential"
|
||||
>
|
||||
<EngineeringAssist type="FILE_INGESTION" :configuration="configForm" :disabled="saving" :editable-keys="['name', 'relativePath', 'fileNamePattern', 'allowedFormats', 'maxFileSizeBytes', 'minRecordCount', 'maxRecordCount', 'schema']" @adopt="Object.assign(configForm, $event)" />
|
||||
<EngineeringAssist type="FILE_INGESTION" :configuration="configForm" :disabled="saving" :editable-keys="activeKind === 'api' ? ['name', 'schema'] : ['name', 'relativePath', 'fileNamePattern', 'allowedFormats', 'maxFileSizeBytes', 'minRecordCount', 'maxRecordCount', 'schema']" @adopt="Object.assign(configForm, $event)" />
|
||||
<div v-if="editingIntakeId && configForm.sourceType === 'SHARED_DIRECTORY'" class="mb-3">
|
||||
<FilePreview :selection="previewSelection" :disabled="saving || previewBaseline !== JSON.stringify(configForm)" :fingerprint="JSON.stringify(configForm)" @adopt="configForm.schema = mergePreviewMappings(configForm.schema, $event)" />
|
||||
<el-text v-if="previewBaseline !== JSON.stringify(configForm)" type="info" class="ml-2">表单已修改,保存后可读取对应文件</el-text>
|
||||
@@ -121,15 +125,15 @@
|
||||
<el-col :span="12">
|
||||
<el-form-item label="配置名称" prop="name"><el-input v-model="configForm.name" maxlength="128" /></el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-col v-if="activeKind === 'file'" :span="12">
|
||||
<el-form-item label="来源类型" prop="sourceType">
|
||||
<el-select v-model="configForm.sourceType" class="w-full" @change="onSourceTypeChanged">
|
||||
<el-option v-for="item in sourceTypeOptions" :key="item" :label="sourceTypeLabel(item)" :value="item" />
|
||||
<el-option v-for="item in fileSourceTypes" :key="item" :label="sourceTypeLabel(item)" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col v-if="configForm.sourceType !== 'SHARED_DIRECTORY'" :span="12">
|
||||
<el-form-item label="访问凭据" prop="password">
|
||||
<el-form-item :label="activeKind === 'api' && profileForm.authKind === 'SIGN_ONLY' ? '签名密钥' : '访问凭据'" prop="password">
|
||||
<el-input
|
||||
v-model="configForm.password"
|
||||
type="password"
|
||||
@@ -149,13 +153,7 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-form-item label="认证方式" prop="authMode">
|
||||
<el-select v-model="configForm.authMode" class="w-full">
|
||||
<el-option v-for="item in authModeOptions" :key="item" :label="authModeLabel(item)" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12"><el-form-item label="认证方式"><el-text>{{ apiAuthLabel(profileForm.authKind) }}</el-text></el-form-item></el-col>
|
||||
<el-col :span="24">
|
||||
<el-form-item label="HTTPS 地址" prop="endpoint">
|
||||
<el-input
|
||||
@@ -165,21 +163,6 @@
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
<el-collapse v-model="advancedSections">
|
||||
<el-collapse-item title="高级拉取设置" name="api">
|
||||
<el-row :gutter="16">
|
||||
<el-col :span="12"><el-form-item label="分页方式" prop="paginationMode"><el-select v-model="configForm.paginationMode" class="w-full"><el-option v-for="item in paginationOptions" :key="item" :label="paginationLabel(item)" :value="item" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="每分钟限流" prop="rateLimitPerMinute"><el-input-number v-model="configForm.rateLimitPerMinute" :min="1" :max="10000" controls-position="right" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="增量字段" prop="incrementalMarker"><el-input v-model="configForm.incrementalMarker" maxlength="128" placeholder="可选" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="执行周期" prop="periodSeconds"><el-input-number v-model="configForm.periodSeconds" :min="60" :max="2592000" controls-position="right" /><el-text type="info" size="small">单位:秒</el-text></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="分页参数" prop="paginationField"><el-input v-model="configForm.paginationField" maxlength="128" placeholder="例如 page" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="最多页数" prop="maxPages"><el-input-number v-model="configForm.maxPages" :min="1" :max="10000" controls-position="right" /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="数据所在路径" prop="responseContentField"><el-input v-model="configForm.responseContentField" maxlength="255" placeholder="可选,例如 $.data[*]" /></el-form-item></el-col>
|
||||
</el-row>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-col>
|
||||
</template>
|
||||
|
||||
<el-col v-else :span="24">
|
||||
@@ -226,17 +209,65 @@
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="12">
|
||||
<el-col v-if="activeKind === 'file'" :span="12">
|
||||
<el-form-item label="文件名规则" prop="fileNamePattern">
|
||||
<el-input v-model="configForm.fileNamePattern" maxlength="128" placeholder="例如 orders-*.csv" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24"><el-collapse v-model="advancedSections"><el-collapse-item title="高级文件校验" name="file"><el-row :gutter="16">
|
||||
<el-col v-if="activeKind === 'file'" :span="24" class="config-advanced-section"><el-collapse v-model="advancedSections"><el-collapse-item title="高级文件校验" name="file"><el-row :gutter="16">
|
||||
<el-col :span="12"><el-form-item label="允许格式" prop="allowedFormats"><el-select v-model="configForm.allowedFormats" class="w-full" multiple collapse-tags><el-option v-for="item in formatOptions" :key="item" :label="item" :value="item" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="大小上限" prop="maxFileSizeBytes"><el-input-number v-model="configForm.maxFileSizeBytes" :min="1" :max="1099511627776" controls-position="right" /><el-text type="info"> 字节</el-text></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="最少记录" prop="minRecordCount"><el-input-number v-model="configForm.minRecordCount" :min="0" controls-position="right" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="最多记录" prop="maxRecordCount"><el-input-number v-model="configForm.maxRecordCount" :min="0" controls-position="right" /></el-form-item></el-col>
|
||||
</el-row></el-collapse-item></el-collapse></el-col>
|
||||
<el-col v-if="configForm.sourceType === 'API_SAAS'" :span="24" class="config-advanced-section">
|
||||
<el-collapse v-model="advancedSections">
|
||||
<el-collapse-item title="高级拉取设置" name="api">
|
||||
<el-row :gutter="16">
|
||||
<el-col :span="24"><el-form-item label="开启轮询"><el-switch v-model="pollingEnabled" /><el-text type="info" size="small" class="ml-3">{{ pollingEnabled ? '保存后自动按间隔采集' : '关闭时仅可手动采集' }}</el-text></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="分页方式" prop="paginationMode"><el-select v-model="configForm.paginationMode" class="w-full"><el-option v-for="item in paginationOptions" :key="item" :label="paginationLabel(item)" :value="item" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="每分钟限流" prop="rateLimitPerMinute"><el-input-number v-model="configForm.rateLimitPerMinute" :min="1" :max="10000" controls-position="right" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="增量字段" prop="incrementalMarker"><el-input v-model="configForm.incrementalMarker" maxlength="128" placeholder="可选" /></el-form-item></el-col>
|
||||
<el-col v-if="pollingEnabled" :span="12"><el-form-item label="轮询间隔" prop="periodSeconds"><el-input-number v-model="configForm.periodSeconds" :min="60" :max="2592000" controls-position="right" /><el-text type="info" size="small" class="ml-2">秒</el-text></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="分页参数" prop="paginationField"><el-input v-model="configForm.paginationField" maxlength="128" placeholder="例如 page" /></el-form-item></el-col>
|
||||
<el-col v-if="configForm.paginationMode === 'CURSOR'" :span="12"><el-form-item label="下页游标路径"><el-input v-model="configForm.cursorResponseField" placeholder="例如 $.next_cursor" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="最多页数" prop="maxPages"><el-input-number v-model="configForm.maxPages" :min="1" :max="100" controls-position="right" /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="数据所在路径" prop="responseContentField"><el-input v-model="configForm.responseContentField" maxlength="255" placeholder="可选,例如 $.data[*]" /></el-form-item></el-col>
|
||||
</el-row>
|
||||
</el-collapse-item>
|
||||
<el-collapse-item title="高级请求与认证" name="request">
|
||||
<el-row :gutter="16">
|
||||
<el-col :span="12"><el-form-item label="认证方式"><el-select v-model="profileForm.authKind" class="w-full" @change="onApiAuthKindChanged"><el-option label="固定 Bearer" value="STATIC_BEARER" /><el-option label="动态 Token(客户端凭据)" value="CLIENT_CREDENTIALS" /><el-option label="动态 Token(账号密码)" value="PASSWORD_TOKEN" /><el-option label="API Key 请求头" value="API_KEY_HEADER" /><el-option label="仅请求签名" value="SIGN_ONLY" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="数据请求方法"><el-select v-model="profileForm.requestMethod" class="w-full"><el-option label="GET" value="GET" /><el-option label="POST" value="POST" /></el-select></el-form-item></el-col>
|
||||
<template v-if="profileForm.authKind === 'CLIENT_CREDENTIALS' || profileForm.authKind === 'PASSWORD_TOKEN'">
|
||||
<el-col :span="24"><el-form-item label="获取 Token 地址"><el-input v-model="profileForm.tokenEndpoint" placeholder="https://api.example.com/token" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item :label="profileForm.authKind === 'CLIENT_CREDENTIALS' ? 'Client ID' : '账号'"><el-input v-model="profileForm.clientId" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="认证请求格式"><el-select v-model="profileForm.tokenFormat" class="w-full"><el-option label="Form" value="FORM" /><el-option label="JSON" value="JSON" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="身份参数名"><el-input v-model="profileForm.tokenClientField" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="密钥参数名"><el-input v-model="profileForm.tokenSecretField" /></el-form-item></el-col>
|
||||
<el-col v-if="profileForm.authKind === 'CLIENT_CREDENTIALS'" :span="12"><el-form-item label="凭据传递方式"><el-select v-model="profileForm.tokenCredentialStyle" class="w-full"><el-option label="请求体" value="BODY" /><el-option label="Basic 请求头" value="BASIC" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="Token 响应路径"><el-input v-model="profileForm.tokenPath" placeholder="$.access_token" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="有效期响应路径"><el-input v-model="profileForm.expiresPath" placeholder="$.expires_in" /></el-form-item></el-col>
|
||||
</template>
|
||||
<el-col :span="12"><el-form-item label="每页数量"><el-input-number v-model="profileForm.pageSize" :min="1" :max="1000" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="增量回看秒数"><el-input-number v-model="profileForm.lookbackSeconds" :min="0" :max="86400" /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="固定请求头 JSON"><el-input v-model="requestHeadersText" type="textarea" :rows="2" placeholder='例如 {"X-Tenant":"example"};不要填写密钥' /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="固定查询参数 JSON"><el-input v-model="requestQueryText" type="textarea" :rows="2" placeholder='例如 {"status":"paid"}' /></el-form-item></el-col>
|
||||
<el-col v-if="profileForm.requestMethod === 'POST'" :span="24"><el-form-item label="请求体模板"><el-input v-model="profileForm.requestBody" type="textarea" :rows="3" placeholder='例如 {"page":${page},"size":${size},"updatedAfter":"${watermark}"}' /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="成功状态路径"><el-input v-model="profileForm.successPath" placeholder="可选,例如 $.success" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="成功状态值"><el-input v-model="profileForm.successValue" placeholder="可选,例如 true" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="请求签名"><el-select v-model="profileForm.signatureKind" class="w-full"><el-option label="关闭" value="NONE" /><el-option label="HMAC-SHA256" value="HMAC_SHA256" /><el-option label="RSA-SHA256" value="RSA_SHA256" /></el-select></el-form-item></el-col>
|
||||
<template v-if="profileForm.signatureKind !== 'NONE'">
|
||||
<el-col :span="12"><el-form-item label="签名位置"><el-select v-model="profileForm.signaturePlacement" class="w-full"><el-option label="请求头" value="HEADER" /><el-option label="查询参数" value="QUERY" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="签名字段名"><el-input v-model="profileForm.signatureHeader" placeholder="X-Sign 或 sign" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="签名编码"><el-select v-model="profileForm.signatureEncoding" class="w-full"><el-option label="Base64" value="BASE64" /><el-option label="Hex" value="HEX" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="签名原文模板"><el-input v-model="profileForm.signatureTemplate" type="textarea" :rows="3" placeholder="${method}\n${pathQuery}\n${bodySha256}\n${timestamp}\n${nonce}" /></el-form-item></el-col>
|
||||
<el-col v-if="profileForm.authKind !== 'SIGN_ONLY'" :span="24"><el-form-item label="签名密钥"><el-input v-model="profileForm.signingKey" type="password" show-password autocomplete="new-password" :placeholder="profileForm.signingKeyConfigured ? '留空保持原密钥' : 'HMAC 密钥或 PKCS8 PEM 私钥'" /></el-form-item></el-col>
|
||||
</template>
|
||||
</el-row>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
@@ -247,6 +278,16 @@
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-drawer v-model="apiRunDrawerVisible" title="API 采集运行记录" size="75%" append-to-body destroy-on-close>
|
||||
<el-table :data="apiRuns" row-key="runId" border empty-text="暂无运行记录">
|
||||
<el-table-column prop="triggerType" label="触发方式" width="120" />
|
||||
<el-table-column prop="status" label="状态" width="120" />
|
||||
<el-table-column prop="writtenRows" label="写入行数" width="120" />
|
||||
<el-table-column prop="errorCode" label="错误代码" min-width="170" />
|
||||
<el-table-column prop="watermarkAfter" label="提交位点" min-width="200" />
|
||||
<el-table-column prop="startedAt" label="开始时间" min-width="170" />
|
||||
</el-table>
|
||||
</el-drawer>
|
||||
<el-drawer v-model="runDrawerVisible" title="运行与文件批次" size="80%" append-to-body destroy-on-close>
|
||||
<el-alert v-if="runError" type="error" :title="runError" :closable="false" show-icon />
|
||||
<el-table v-loading="runsLoading" :data="runs" row-key="runId" border class="data-table" empty-text="暂无运行记录">
|
||||
@@ -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<FileIntakeQuery>({ pageNum: 1, pageSize: 20 });
|
||||
const query = reactive<FileIntakeQuery>({ pageNum: 1, pageSize: 20, sourceType: props.kind === 'api' ? 'API_SAAS' : 'SHARED_DIRECTORY' });
|
||||
const intakes = ref<FileIntakeVO[]>([]);
|
||||
const pollStates = ref<Record<string, ApiPollState>>({});
|
||||
const apiRuns = ref<ApiPollRun[]>([]);
|
||||
const apiRunDrawerVisible = ref(false);
|
||||
const targetTables = ref<TableFileVO[]>([]);
|
||||
const targetTablesLoading = ref(false);
|
||||
const targetTablesError = ref('');
|
||||
@@ -434,9 +480,14 @@ const currentSecretConfigured = ref(false);
|
||||
const currentAction = ref<FileActionType>('VALIDATE');
|
||||
const currentActionTarget = ref<FileId>();
|
||||
const advancedSections = ref<string[]>([]);
|
||||
const pollingEnabled = ref(false);
|
||||
const originalPollingEnabled = ref(false);
|
||||
const configFormRef = ref<FormInstance>();
|
||||
const actionFormRef = ref<FormInstance>();
|
||||
const configForm = reactive<FileIntakeForm & { version?: number; targetTableFileId: string }>(emptyConfig());
|
||||
const profileForm = reactive<ApiPollProfile>(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<string, string> {
|
||||
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<string, string>;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.config-advanced-section { margin-top: 12px; }
|
||||
.config-advanced-section :deep(.el-collapse-item__content) { padding: 12px 4px 4px; }
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="p-2 app-container">
|
||||
<el-card shadow="hover" class="table-panel">
|
||||
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>实时采集</h3><p>将数据库的新增、更新和删除持续同步到 Doris,支持原生 CDC 与日志通道接入。</p></div>
|
||||
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>实时采集</h3></div>
|
||||
<div class="toolbar-actions"><el-button icon="Refresh" :disabled="busy" @click="load">刷新列表</el-button>
|
||||
<el-button v-hasPermi="['aixun:dataops:realtime:manage']" type="primary" icon="Plus" :disabled="busy" @click="openCreate">新增实时采集</el-button></div></div></template>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon class="mb-3" />
|
||||
@@ -10,17 +10,18 @@
|
||||
<el-table-column label="来源表" min-width="200"><template #default="{row}">{{ sourceName(row.spec) }}</template></el-table-column>
|
||||
<el-table-column label="目标表" min-width="150"><template #default="{row}">{{ row.spec.targetTable }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="110"><template #default="{row}"><el-tag :type="tone(row.status)">{{ label(row.status) }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="最近观测" min-width="170"><template #default="{row}">{{ row.observedAt || '--' }}</template></el-table-column>
|
||||
<el-table-column label="状态更新时间" min-width="170"><template #default="{row}">{{ row.observedAt || '--' }}</template></el-table-column>
|
||||
<el-table-column label="说明" min-width="220" show-overflow-tooltip><template #default="{row}">{{ row.summary || '--' }}</template></el-table-column>
|
||||
<el-table-column label="操作" width="400" fixed="right" align="center" class-name="dg-row-actions"><template #default="{row}"><RowActions :max-primary="3">
|
||||
<el-button link type="primary" icon="View" :disabled="busy" @click="details(row)">详情</el-button>
|
||||
<template v-if="checkPermi(['aixun:dataops:realtime:manage'])">
|
||||
<el-button v-if="row.attempt === 0" link type="primary" icon="Edit" :disabled="busy" @click="edit(row)">编辑</el-button>
|
||||
<el-button v-if="row.status === 'READY'" link type="primary" icon="VideoPlay" :disabled="busy" @click="act(row,'START')">启动</el-button>
|
||||
<el-button v-if="row.attempt === 0" link type="primary" icon="CircleCheck" :disabled="busy" @click="act(row,'CHECK')">校验</el-button>
|
||||
<el-button v-if="row.attempt > 0" link type="primary" icon="Refresh" :disabled="busy" @click="act(row,'REFRESH')">同步状态</el-button>
|
||||
<el-button v-if="row.attempt === 0" link type="primary" icon="CircleCheck" :disabled="busy" @click="act(row,'CHECK')">检查并准备</el-button>
|
||||
<el-button v-if="row.attempt > 0 && ['FAILED','CANCELED'].includes(row.status) && !row.checkpointId" link type="primary" icon="RefreshRight" :disabled="busy" @click="act(row,'RETRY')">重试启动</el-button>
|
||||
<el-button v-if="row.attempt > 0" link type="primary" icon="Refresh" title="仅查询任务运行结果,不会重试或重新启动" :disabled="busy" @click="act(row,'REFRESH')">刷新状态</el-button>
|
||||
<el-button v-if="row.attempt > 0 && !['FAILED','CANCELED','SUCCEEDED'].includes(row.status)" link type="warning" icon="VideoPause" :disabled="busy" @click="act(row,'STOP')">停止</el-button>
|
||||
<el-button v-if="['FAILED','CANCELED'].includes(row.status) && row.checkpointId" link type="primary" icon="RefreshRight" :disabled="busy" @click="act(row,'RESUME')">恢复</el-button>
|
||||
<el-button v-if="(['FAILED','CANCELED'].includes(row.status) && row.checkpointId) || row.status === 'UNKNOWN'" link type="primary" icon="RefreshRight" :disabled="busy" @click="act(row,'RESUME')">检查并恢复</el-button>
|
||||
<el-button v-if="row.status === 'UNKNOWN' && row.attempt > 0 && !row.checkpointId" link type="warning" icon="RefreshRight" :disabled="busy" @click="act(row,'RECREATE')">清理并重建</el-button>
|
||||
<el-button v-if="['DRAFT','READY','FAILED','CANCELED','SUCCEEDED'].includes(row.status)" link type="danger" icon="Delete" :disabled="busy" @click="act(row,'DELETE')">删除</el-button>
|
||||
</template>
|
||||
@@ -28,56 +29,42 @@
|
||||
</el-table>
|
||||
<pagination v-if="total > 0" v-model:page="pageNum" v-model:limit="pageSize" :total="total" @pagination="load" />
|
||||
</el-card>
|
||||
<el-dialog v-model="dialog" :title="editing ? '编辑实时采集' : '新增实时采集'" width="780px" append-to-body :close-on-click-modal="false" :before-close="closeCreate">
|
||||
<el-alert title="首期同步全部字段,字段名称与顺序须与目标表一致;目标表须已建成 Unique Key 模型,且主键与源表一致。" type="info" :closable="false" class="mb-4" />
|
||||
<el-form label-width="130px" class="dialog-grid-form" :disabled="busy">
|
||||
<el-form-item label="任务名称" required><el-input v-model="form.name" maxlength="100" /></el-form-item>
|
||||
<el-row :gutter="20"><el-col :span="12"><el-form-item label="来源数据源" required><el-select v-model="form.sourceId" filterable class="w-full" @change="sourceChanged">
|
||||
<el-option v-for="s in sources" :key="String(s.id)" :value="s.id" :label="`${s.name}(${typeNames[s.type] || s.type})`" :disabled="!s.available" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="来源数据库"><el-input v-model="form.sourceDatabase" disabled /></el-form-item></el-col></el-row>
|
||||
<el-alert v-if="source" :title="sourceHelp" :type="nativeVendor ? 'warning' : 'info'" :closable="false" show-icon class="mb-3" />
|
||||
<el-form-item v-if="['DAMENG','KINGBASE','ORACLE'].includes(source?.type || '')" label="日志通道(可选)">
|
||||
<el-select v-model="form.cdcChannel" clearable class="w-full" :loading="relaysLoading" placeholder="留空使用原生 CDC;也可选择已登记通道" @change="relayChanged">
|
||||
<el-option v-for="channel in relayOptions" :key="channel.id" :value="channel.id" :label="`${channel.name}(${channel.schema}.${channel.table})`" />
|
||||
</el-select>
|
||||
<el-text v-if="!relaysLoading && !relayOptions.length" type="info">未登记外部日志通道,使用数据库原生日志。</el-text>
|
||||
</el-form-item>
|
||||
<el-alert v-if="form.cdcChannel" title="日志通道只消费上游消息,不自动扫描源表。完整历史数据需由上游先输出全量快照,再连续输出增删改;每个主题仅包含当前表,更新前后值须完整,且同一主键消息保持顺序。" type="warning" :closable="false" class="mb-3" />
|
||||
<el-form-item v-if="source && source.type !== 'MYSQL'" label="源架构(Schema)" required><el-input v-model="form.sourceSchema" :disabled="!!form.cdcChannel" maxlength="128" placeholder="填写表所属架构,注意大小写" /></el-form-item>
|
||||
<el-dialog v-model="dialog" :title="editing ? '编辑实时采集' : '新增实时采集'" width="min(900px, calc(100vw - 32px))" append-to-body :close-on-click-modal="false" :before-close="closeCreate">
|
||||
<el-form label-width="140px" class="dialog-grid-form realtime-form" :disabled="busy || defaultsLoading" v-loading="defaultsLoading">
|
||||
<el-form-item label="任务名称" required class="realtime-wide"><el-input v-model="form.name" maxlength="100" /></el-form-item>
|
||||
<el-form-item label="来源数据源" required><el-select v-model="form.sourceId" filterable class="w-full" @change="sourceChanged">
|
||||
<el-option v-for="s in sources" :key="String(s.id)" :value="s.id" :label="`${s.name}(${typeNames[s.type] || s.type})`" :disabled="!s.available" /></el-select></el-form-item>
|
||||
<el-form-item v-if="source?.type !== 'ORACLE'" label="来源数据库"><el-input v-model="form.sourceDatabase" disabled /></el-form-item>
|
||||
<el-form-item v-if="source && source.type !== 'MYSQL'" label="源模式" required><el-input v-model="form.sourceSchema" :disabled="!!form.cdcChannel" maxlength="128" placeholder="表所属模式,注意大小写" /></el-form-item>
|
||||
<template v-if="source?.type === 'ORACLE' && !form.cdcChannel">
|
||||
<el-form-item label="Oracle 数据库名" required><el-input v-model="form.oracleDatabase" maxlength="128" placeholder="填写 V$DATABASE.NAME,不是连接服务名" /></el-form-item>
|
||||
<el-form-item label="目标 PDB"><el-input v-model="form.oraclePdb" maxlength="128" placeholder="多租户填写实际 PDB 名;非 CDB 留空" /></el-form-item>
|
||||
<el-form-item v-if="form.oraclePdb" label="CDB 根服务名" required><el-input v-model="form.oracleCdbService" maxlength="128" placeholder="同一主机和端口上连接 CDB$ROOT 的服务名" /></el-form-item>
|
||||
<el-text v-if="form.oraclePdb" type="info">数据源须连接目标 PDB,并使用同时具备根容器日志采集及 PDB 读表权限的公共用户。数据库名填写 CDB 的 V$DATABASE.NAME。</el-text>
|
||||
<el-form-item label="Oracle数据库名" required><el-input v-model="form.oracleDatabase" :disabled="oracleDatabaseLocked" maxlength="128" placeholder="数据库实际名称,例如 FREE" /></el-form-item>
|
||||
<el-form-item label="业务库(PDB)"><el-input v-model="form.oraclePdb" :disabled="oraclePdbLocked" maxlength="128" placeholder="例如 FREEPDB1,非多租户留空" /></el-form-item>
|
||||
<el-form-item v-if="form.oraclePdb" label="日志连接服务名" required><el-input v-model="form.oracleCdbService" maxlength="128" placeholder="根容器服务名,如 free" /></el-form-item>
|
||||
</template>
|
||||
<el-form-item label="源表" required><el-input v-model="form.sourceTable" :disabled="!!form.cdcChannel" placeholder="填写数据源中的表名,不含数据库前缀" maxlength="64" /></el-form-item>
|
||||
<el-row :gutter="20"><el-col :span="12"><el-form-item label="Doris 存储" required><el-select v-model="form.targetResourceId" filterable class="w-full" @change="form.targetSpaceId = ''">
|
||||
<el-option v-for="t in targets" :key="String(t.resourceId)" :value="t.resourceId" :label="t.name" :disabled="t.accessVersion == null" /></el-select></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="目标数据库" required><el-select v-model="form.targetSpaceId" class="w-full"><el-option v-for="s in target?.databases || []" :key="String(s.spaceId)" :value="s.spaceId" :label="s.databaseName" /></el-select></el-form-item></el-col></el-row>
|
||||
<el-row :gutter="20"><el-col :span="12"><el-form-item label="目标表" required><el-input v-model="form.targetTable" maxlength="64" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="FE HTTP 端口" required><el-input-number v-model="form.httpPort" :min="1" :max="65535" /></el-form-item></el-col></el-row>
|
||||
<el-form-item label="首次启动方式"><el-radio-group v-model="form.startupMode"><el-radio value="initial">{{ form.cdcChannel ? '从主题最早保留消息开始' : '先同步历史,再持续同步' }}</el-radio><el-radio value="latest">{{ nativeVendor && source?.type === 'KINGBASE' ? '从复制槽已确认位置继续' : '仅同步启动后的变更' }}</el-radio></el-radio-group></el-form-item>
|
||||
<el-alert v-if="nativeVendor && form.startupMode === 'initial'" title="先按主键分页读取历史数据,再重放扫描期间的日志;追平前可能短暂看到旧值,完成快照和增量追平后再核对一致性。首次全量要求目标表为空。" type="info" :closable="false" class="mb-3" />
|
||||
<el-alert v-if="form.startupMode === 'latest'" title="仅增量模式不会补齐启动前的数据,请确认目标基线已准备好。" type="warning" :closable="false" class="mb-3" />
|
||||
<el-row :gutter="20"><el-col v-if="source?.type === 'MYSQL'" :span="12"><el-form-item label="Binlog server-id" required><el-input-number v-model="form.serverId" :min="1" :max="4294967295" :precision="0" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="检查点间隔(秒)"><el-input-number v-model="form.checkpointSeconds" :min="10" :max="3600" /></el-form-item></el-col></el-row>
|
||||
<el-text type="info">来源账号沿用数据源管理中的托管凭据;FE HTTP 地址沿用所选存储主机。检查通过后仍需核验新增、更新、删除及断点恢复。</el-text>
|
||||
<el-form-item label="源表" required :class="{ 'realtime-wide': !source || source.type === 'MYSQL' || (source.type === 'ORACLE' && !form.oraclePdb) }"><el-input v-model="form.sourceTable" :disabled="!!form.cdcChannel" placeholder="表名,不含数据库或模式前缀" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="Doris 存储" required><el-select v-model="form.targetResourceId" filterable class="w-full" @change="form.targetSpaceId = ''">
|
||||
<el-option v-for="t in targets" :key="String(t.resourceId)" :value="t.resourceId" :label="t.name" :disabled="t.accessVersion == null" /></el-select></el-form-item>
|
||||
<el-form-item label="目标数据库" required><el-select v-model="form.targetSpaceId" class="w-full"><el-option v-for="s in target?.databases || []" :key="String(s.spaceId)" :value="s.spaceId" :label="s.databaseName" /></el-select></el-form-item>
|
||||
<el-form-item label="目标表" required><el-input v-model="form.targetTable" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="Doris接口端口" required><el-input-number v-model="form.httpPort" :min="1" :max="65535" /></el-form-item>
|
||||
<el-form-item label="首次同步方式" class="realtime-wide"><el-radio-group v-model="form.startupMode"><el-radio value="initial">{{ form.cdcChannel ? '从最早保留的消息开始' : '先同步历史,再持续同步' }}</el-radio><el-radio value="latest">{{ nativeVendor && source?.type === 'KINGBASE' ? '从已确认的日志位置继续' : '仅同步启动后的变更' }}</el-radio></el-radio-group></el-form-item>
|
||||
<el-form-item label="进度保存间隔"><el-input-number v-model="form.checkpointSeconds" :min="10" :max="3600" /><span class="ml-2">秒</span></el-form-item>
|
||||
</el-form>
|
||||
<template #footer><div class="dialog-footer"><el-button :disabled="busy" @click="dialog=false">取消</el-button><el-button type="primary" :loading="busy" @click="save">保存配置</el-button></div></template>
|
||||
<template #footer><div class="dialog-footer"><el-button :disabled="busy" @click="dialog=false">取消</el-button><el-button type="primary" :loading="busy" :disabled="defaultsLoading" @click="save">保存配置</el-button></div></template>
|
||||
</el-dialog>
|
||||
<el-drawer v-model="drawer" title="实时采集详情" size="680px" append-to-body>
|
||||
<template v-if="selected"><el-descriptions :column="1" border>
|
||||
<el-descriptions-item label="任务">{{ selected.spec.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="状态">{{ label(selected.status) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="外部作业">{{ selected.externalId || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="采集引擎任务编号">{{ selected.externalId || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="来源">{{ sourceName(selected.spec) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="目标表">{{ selected.spec.targetTable }}</el-descriptions-item>
|
||||
<el-descriptions-item label="已完成 checkpoint">{{ selected.checkpointId || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="恢复点编号">{{ selected.checkpointId || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="读取 / 写入条数">{{ selected.readRows ?? '--' }} / {{ selected.writeRows ?? '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="最近观测">{{ selected.observedAt || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="状态更新时间">{{ displayTime(selected.observedAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="说明">{{ selected.summary || '--' }}</el-descriptions-item>
|
||||
</el-descriptions><el-alert title="持续运行不代表数据已经一致。停止后先同步状态;确认终止且存在已完成 checkpoint 时可恢复。" type="info" :closable="false" class="my-4" />
|
||||
<el-table :data="selected.history" border empty-text="暂无操作记录"><el-table-column label="操作"><template #default="{row}">{{ actionLabels[String(row.ACTION ?? row.action)] || row.ACTION || row.action }}</template></el-table-column><el-table-column label="状态"><template #default="{row}">{{ label(String(row.STATUS ?? row.status)) }}</template></el-table-column><el-table-column label="时间" min-width="180"><template #default="{row}">{{ row.CREATED_AT || row.created_at || '--' }}</template></el-table-column></el-table>
|
||||
</el-descriptions>
|
||||
<el-table :data="selected.history" border empty-text="暂无操作记录"><el-table-column label="操作"><template #default="{row}">{{ actionLabels[String(row.ACTION ?? row.action)] || row.ACTION || row.action }}</template></el-table-column><el-table-column label="状态"><template #default="{row}">{{ label(String(row.STATUS ?? row.status)) }}</template></el-table-column><el-table-column label="时间" min-width="180"><template #default="{row}">{{ displayTime(row.CREATED_AT ?? row.created_at) }}</template></el-table-column></el-table>
|
||||
</template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
@@ -90,42 +77,66 @@ import { checkPermi } from '@/utils/permission';
|
||||
import { extractErrorMessage } from '@/utils/request';
|
||||
import { listIngestionTargets } from '@/api/datagov/unified-ingestion';
|
||||
import type { SourceVO, TargetVO } from '@/api/datagov/unified-ingestion/types';
|
||||
import { actRealtime, createRealtime, getRealtime, listRealtime, updateRealtime, listCdcRelays, listRealtimeSources } from '@/api/datagov/realtime-ingestion';
|
||||
import type { RealtimeSpec, RealtimeTask, CdcRelayOption } from '@/api/datagov/realtime-ingestion';
|
||||
import { actRealtime, createRealtime, getRealtime, listRealtime, updateRealtime, listRealtimeSources, getSourceDefaults } from '@/api/datagov/realtime-ingestion';
|
||||
import type { RealtimeSpec, RealtimeTask } from '@/api/datagov/realtime-ingestion';
|
||||
const rows=ref<RealtimeTask[]>([]), sources=ref<SourceVO[]>([]), targets=ref<TargetVO[]>([]);
|
||||
const loading=ref(false), busy=ref(false), dialog=ref(false), drawer=ref(false), error=ref('');
|
||||
const pageNum=ref(1), pageSize=ref(20), total=ref(0), selected=ref<RealtimeTask>();
|
||||
const fresh=(): RealtimeSpec => ({name:'',sourceId:'',sourceVersion:0,sourceDatabase:'',sourceTable:'',targetResourceId:'',targetSpaceId:'',targetTable:'',httpPort:8030,startupMode:'initial',checkpointSeconds:30,serverId:crypto.getRandomValues(new Uint32Array(1))[0] || 1});
|
||||
const form=ref<RealtimeSpec>(fresh()); let createKey=crypto.randomUUID();
|
||||
const editing=ref<RealtimeTask>();
|
||||
const relayOptions=ref<CdcRelayOption[]>([]), relaysLoading=ref(false);
|
||||
const defaultsLoading=ref(false);
|
||||
const oracleDatabaseLocked=ref(false), oraclePdbLocked=ref(false);
|
||||
const target=computed(()=>targets.value.find(t=>String(t.resourceId)===String(form.value.targetResourceId)));
|
||||
const source=computed(()=>sources.value.find(s=>String(s.id)===String(form.value.sourceId)));
|
||||
const typeNames: Record<string,string>={MYSQL:'MySQL',ORACLE:'Oracle',SQLSERVER:'SQL Server',DAMENG:'达梦',KINGBASE:'人大金仓'};
|
||||
const nativeVendor=computed(()=>['DAMENG','KINGBASE'].includes(source.value?.type || '') && !form.value.cdcChannel);
|
||||
const sourceHelp=computed(()=>({
|
||||
MYSQL:'需启用 Binlog(ROW / FULL),账号具备读取和复制权限;server-id 必须与其他复制客户端不同。',
|
||||
ORACLE:'使用 SeaTunnel Oracle-CDC 直接读取日志。非 CDB 填写数据库名;CDB/PDB 还需填写目标 PDB 和根容器服务名。需开启归档、补充日志并授予采集权限,无需另建外部日志通道。',
|
||||
SQLSERVER:'数据库和源表均需开启 CDC,捕获作业持续运行,账号具备源表与 CDC 读取权限。采集节点需安装 SQL Server CDC 插件。',
|
||||
DAMENG:'原生 CDC 读取达梦归档日志,无需 DMHS。需启用本地归档及完整行镜像,归档生成速度决定同步延迟。按已保存进度连续读取,未结束事务所需旧日志会继续保留;请勿清理任务仍需使用的归档,缺失日志时将停止并提示。',
|
||||
KINGBASE:'原生 CDC 读取金仓逻辑复制,无需 FlySync。需 logical WAL、专用 test_decoding 复制槽和 REPLICA IDENTITY FULL。校验会提示需要的复制槽名称;不要让其他任务使用同一复制槽。'
|
||||
}[source.value?.type || ''] || ''));
|
||||
const sourceName=(s:RealtimeSpec)=>[s.sourceDatabase,s.sourceSchema,s.sourceTable].filter(Boolean).join('.');
|
||||
const labels: Record<string,string>={DRAFT:'草稿',READY:'就绪',SUBMITTING:'提交中',SUBMITTED:'已受理',PENDING:'处理中',RUNNING:'持续运行',STOPPING:'停止中',CANCELED:'已停止',FAILED:'失败',UNKNOWN:'待确认',SUCCEEDED:'已结束'};
|
||||
const actionLabels: Record<string,string>={CHECK:'校验',START:'启动',REFRESH:'同步状态',STOP:'停止',RESUME:'恢复',ARCHIVE:'归档',DELETE:'删除',RECREATE:'清理并重建'};
|
||||
const labels: Record<string,string>={DRAFT:'草稿',READY:'待启动',SUBMITTING:'提交中',SUBMITTED:'已受理',PENDING:'处理中',RUNNING:'运行中',STOPPING:'停止中',CANCELED:'已停止',FAILED:'失败',UNKNOWN:'状态待确认',SUCCEEDED:'已结束'};
|
||||
const actionLabels: Record<string,string>={CHECK:'检查并准备',START:'启动',RETRY:'重试启动',REFRESH:'刷新状态',STOP:'停止',RESUME:'恢复',ARCHIVE:'归档',DELETE:'删除',RECREATE:'清理并重建'};
|
||||
const label=(v:string)=>labels[v] || v;
|
||||
function displayTime(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value) return '--';
|
||||
const date = new Date(value.includes('T') ? value : value.replace(' ', 'T'));
|
||||
if (Number.isNaN(date.getTime())) return '--';
|
||||
const pad = (part: number) => String(part).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
const tone=(v:string): 'success'|'danger'|'warning'|'info' => v==='RUNNING'?'success':v==='FAILED'?'danger':['UNKNOWN','STOPPING'].includes(v)?'warning':'info';
|
||||
async function load(){loading.value=true;try{const {data}=await listRealtime(pageNum.value,pageSize.value);rows.value=data.rows;total.value=data.total;}catch(e){error.value=await extractErrorMessage(e)||'任务加载失败';}finally{loading.value=false;}}
|
||||
async function openCreate(){error.value='';editing.value=undefined;try{const [s,t]=await Promise.all([listRealtimeSources(),listIngestionTargets('DORIS')]);sources.value=s.data.rows.filter(x=>Object.hasOwn(typeNames,x.type));targets.value=t.data.rows;form.value=fresh();createKey=crypto.randomUUID();dialog.value=true;}catch(e){error.value=await extractErrorMessage(e)||'来源或目标加载失败';}}
|
||||
async function edit(row:RealtimeTask){await openCreate();if(dialog.value){editing.value=row;form.value={...row.spec};await loadRelays();}}
|
||||
async function loadRelays(){relayOptions.value=[];const id=form.value.sourceId;if(!id)return;relaysLoading.value=true;try{const result=await listCdcRelays(id);if(String(form.value.sourceId)===String(id))relayOptions.value=result.data;}catch(e){ElMessage.error(await extractErrorMessage(e)||'日志通道加载失败');}finally{relaysLoading.value=false;}}
|
||||
async function sourceChanged(){const s=source.value;form.value.sourceVersion=s?.version || 0;form.value.sourceDatabase=s?.databaseName || '';form.value.sourceTable='';form.value.sourceSchema=s?.type==='SQLSERVER'?'dbo':s?.type==='DAMENG'?s.databaseName:s?.type==='KINGBASE'?'public':undefined;form.value.oracleDatabase=undefined;form.value.oraclePdb=undefined;form.value.oracleCdbService=undefined;form.value.cdcChannel=undefined;await loadRelays();}
|
||||
function relayChanged(){const c=relayOptions.value.find(x=>x.id===form.value.cdcChannel);if(c){form.value.sourceSchema=c.schema;form.value.sourceTable=c.table;form.value.oracleDatabase=undefined;form.value.oraclePdb=undefined;form.value.oracleCdbService=undefined;}else form.value.cdcChannel=undefined;}
|
||||
async function openCreate(){error.value='';editing.value=undefined;oracleDatabaseLocked.value=false;oraclePdbLocked.value=false;try{const [s,t]=await Promise.all([listRealtimeSources(),listIngestionTargets('DORIS')]);sources.value=s.data.rows.filter(x=>Object.hasOwn(typeNames,x.type));targets.value=t.data.rows;form.value=fresh();createKey=crypto.randomUUID();dialog.value=true;}catch(e){error.value=await extractErrorMessage(e)||'来源或目标加载失败';}}
|
||||
async function edit(row:RealtimeTask){await openCreate();if(dialog.value){editing.value=row;form.value={...row.spec};if(source.value?.type==='ORACLE' && !form.value.cdcChannel)await loadDefaults(true);}}
|
||||
async function sourceChanged(){const s=source.value;oracleDatabaseLocked.value=false;oraclePdbLocked.value=false;form.value.sourceVersion=s?.version || 0;form.value.sourceDatabase=s?.databaseName || '';form.value.sourceTable='';form.value.sourceSchema=s?.type==='SQLSERVER'?'dbo':s?.type==='DAMENG'?s.databaseName:s?.type==='KINGBASE'?'public':undefined;form.value.oracleDatabase=undefined;form.value.oraclePdb=undefined;form.value.oracleCdbService=undefined;form.value.cdcChannel=undefined;
|
||||
await loadDefaults();}
|
||||
async function loadDefaults(preserveSelection=false){const s=source.value;if(!s || s.type==='MYSQL')return;const current=form.value;defaultsLoading.value=true;try{const {data}=await getSourceDefaults(s.id);if(form.value!==current || String(form.value.sourceId)!==String(s.id))return;if(data.sourceVersion!==s.version){ElMessage.warning('数据源已修改,请重新打开弹窗');return;}if(!preserveSelection && data.sourceSchema)form.value.sourceSchema=data.sourceSchema;
|
||||
if(data.oracleDatabase){form.value.oracleDatabase=data.oracleDatabase;oracleDatabaseLocked.value=true;}
|
||||
if(data.oraclePdb || (data.oracleDatabase && !data.warning)){form.value.oraclePdb=data.oraclePdb || undefined;oraclePdbLocked.value=true;}
|
||||
if(data.oracleCdbService && !preserveSelection)form.value.oracleCdbService=data.oracleCdbService;
|
||||
}catch{/* Optional discovery keeps unavailable fields editable without interrupting the form. */}finally{defaultsLoading.value=false;}}
|
||||
function closeCreate(done:()=>void){if(!busy.value)done();}
|
||||
async function save(){if(busy.value)return;busy.value=true;try{const pdb=form.value.oraclePdb?.trim() || undefined;const spec={...form.value,sourceSchema:form.value.sourceSchema?.trim() || undefined,oracleDatabase:form.value.oracleDatabase?.trim() || undefined,oraclePdb:pdb,oracleCdbService:pdb?(form.value.oracleCdbService?.trim() || undefined):undefined};if(editing.value)await updateRealtime(editing.value.id,spec,editing.value.version);else await createRealtime(spec,createKey);dialog.value=false;ElMessage.success('已保存,请校验后启动');await load();}catch(e){ElMessage.error(await extractErrorMessage(e)||'保存失败');}finally{busy.value=false;}}
|
||||
async function save(){if(busy.value)return;busy.value=true;try{const pdb=form.value.oraclePdb?.trim() || undefined;const spec={...form.value,sourceSchema:form.value.sourceSchema?.trim() || undefined,oracleDatabase:form.value.oracleDatabase?.trim() || undefined,oraclePdb:pdb,oracleCdbService:pdb?(form.value.oracleCdbService?.trim() || undefined):undefined};if(editing.value)await updateRealtime(editing.value.id,spec,editing.value.version);else await createRealtime(spec,createKey);dialog.value=false;ElMessage.success('已保存,请检查并准备后启动');await load();}catch(e){ElMessage.error(await extractErrorMessage(e)||'保存失败');}finally{busy.value=false;}}
|
||||
async function details(row:RealtimeTask){try{selected.value=(await getRealtime(row.id)).data;drawer.value=true;}catch(e){error.value=await extractErrorMessage(e)||'详情加载失败';}}
|
||||
async function act(row:RealtimeTask, action:string){if(busy.value)return;
|
||||
if(['START','STOP','RESUME','ARCHIVE','DELETE','RECREATE'].includes(action)){try{await ElMessageBox.confirm(action==='RECREATE'?'仅在引擎无运行或排队作业且旧作业记录不存在时,归档旧任务并按相同参数创建新草稿。保留历史记录,不删除源表和目标表数据,不自动启动。确认清理并重建?':action==='DELETE'?'确认删除此采集任务?删除后从列表移除并释放目标表占用,保留历史操作记录,不删除源表及已采集的数据。':action==='ARCHIVE'?'归档此草稿并释放目标表占用;历史操作记录保留。':action==='STOP'?'停止将请求保存点。请在操作后同步状态确认已停止。':action==='RESUME'?'从原作业最近已完成checkpoint恢复,配置和表结构须保持一致。':'启动后将持续写入目标表,包含更新与删除。',actionLabels[action],{type:'warning'});}catch{return;}}
|
||||
if(action==='CHECK'){try{await ElMessageBox.confirm(`将检查来源表及采集条件,并准备目标表“${row.spec.targetTable}”。目标表不存在时自动创建;已存在时只检查字段类型和主键,不修改表结构或数据。`, '检查并准备', {type:'warning'});}catch{return;}}
|
||||
if(action==='RETRY'){try{await ElMessageBox.confirm(`将重新校验来源和目标,并在确认原任务已结束且没有有效恢复点后重新提交。${row.spec.startupMode==='initial'?'会重新同步历史数据,再持续采集。':'将仅采集重新启动后的变更,停止期间的数据可能不被补采。'}此操作不会清空目标表。`, '重试启动', {type:'warning'});}catch{return;}}
|
||||
if(['START','STOP','RESUME','ARCHIVE','DELETE','RECREATE'].includes(action)){try{await ElMessageBox.confirm(action==='RECREATE'?'仅在旧任务记录不存在且未在运行或排队时,归档旧任务并按相同参数创建新草稿。保留历史记录,不删除源表和目标表数据,不自动启动。确认清理并重建?':action==='DELETE'?'确认删除此采集任务?删除后从列表移除并释放目标表占用,保留历史操作记录,不删除源表及已采集的数据。':action==='ARCHIVE'?'归档此草稿并释放目标表占用;历史操作记录保留。':action==='STOP'?'将请求保存采集进度并停止任务。请在操作后点击“刷新状态”确认已停止。':action==='RESUME'?'先确认原任务已结束,再检查已保存的恢复点并从该位置继续采集。缺少有效恢复点时无法恢复,不会重新同步全部历史数据。':'启动后将持续写入目标表,包含更新与删除。',actionLabels[action],{type:'warning'});}catch{return;}}
|
||||
busy.value=true;error.value='';try{const result=(await actRealtime(row.id,action,row.version,crypto.randomUUID())).data;selected.value=result;if(action==='DELETE' && result.status==='ARCHIVED'){drawer.value=false;ElMessage.success('任务已删除');if(rows.value.length===1 && pageNum.value>1)pageNum.value--;}else{drawer.value=true;}await load();}catch(e){error.value=await extractErrorMessage(e)||'操作未确认,请刷新任务后核对';await load();}finally{busy.value=false;}}
|
||||
onMounted(load);
|
||||
</script>
|
||||
<style scoped>
|
||||
.realtime-form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
column-gap: 24px;
|
||||
}
|
||||
.realtime-wide { grid-column: 1 / -1; }
|
||||
.realtime-form :deep(.el-form-item) { min-width: 0; }
|
||||
.realtime-form :deep(.el-form-item__content) { min-width: 0; }
|
||||
.realtime-form :deep(.el-form-item__label) { white-space: nowrap; }
|
||||
@media (max-width: 680px) {
|
||||
.realtime-form { grid-template-columns: minmax(0, 1fr); }
|
||||
.realtime-form :deep(.el-form-item) { display: block; }
|
||||
.realtime-form :deep(.el-form-item__label) { width: auto !important; display: block; text-align: left; }
|
||||
.realtime-form :deep(.el-radio-group) { display: flex; flex-direction: column; align-items: flex-start; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<template #header>
|
||||
<div class="toolbar-shell">
|
||||
<div class="table-heading">
|
||||
<h3>数据采集</h3>
|
||||
<h3>离线采集</h3>
|
||||
<p>{{ activeView === 'originals' ? '采集保存 PDF、Word 和图片原文件,查看保存结果并下载。' : activeView === 'create' ? '选择数据库源表,按需选择字段并采集到 Hive 或 Doris。' : activeView === 'mapping' ? '查看已有采集任务的来源、目标和字段映射。' : '查询每次采集任务、运行状态和执行详情。' }}</p>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
|
||||
@@ -237,6 +237,9 @@
|
||||
<el-switch v-model="form.useSsl" active-text="启用" inactive-text="关闭" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col v-if="form.type === 'KINGBASE' && !form.useSsl" :span="24">
|
||||
<el-text type="warning">当前连接不加密,仅供已允许非 TLS 连接的测试环境使用;正式环境请先在金仓服务端启用 TLS。</el-text>
|
||||
</el-col>
|
||||
<el-col v-if="form.type === 'SQLSERVER'" :span="24">
|
||||
<el-form-item label="信任服务器证书">
|
||||
<el-switch v-model="form.trustServerCertificate" :disabled="!form.useSsl" />
|
||||
@@ -420,7 +423,7 @@ const databaseCatalogGroups = computed<{ key: string; name: string; items: Datab
|
||||
{ key: 'oceanbase', name: 'OceanBase', icon: 'mdi:database-arrow-left-outline', logoUrl: 'https://www.oceanbase.com/favicon.ico', description: '分布式关系数据库', status: 'PLANNED' },
|
||||
{ key: 'opengauss', name: 'openGauss', icon: 'mdi:database-outline', logoUrl: 'https://opengauss.org/favicon.ico', description: '企业级开源关系数据库', status: 'PLANNED' },
|
||||
{ key: 'gaussdb', name: 'GaussDB', icon: 'mdi:database-sync-outline', logoUrl: 'https://www.huaweicloud.com/favicon.ico', description: '分布式企业数据库', status: 'PLANNED' },
|
||||
{ key: 'kingbase', type: 'KINGBASE', name: '人大金仓', icon: 'mdi:database-check-outline', logoUrl: 'https://www.kingbase.com.cn/uploadnew/image/2024/10/11/68311f83-4294-43f4-8326-34a8c9f7d876.png', description: '国产企业级关系数据库', status: 'PLANNED' },
|
||||
{ key: 'kingbase', type: 'KINGBASE', name: '人大金仓', icon: 'mdi:database-check-outline', logoUrl: 'https://www.kingbase.com.cn/uploadnew/image/2024/10/11/68311f83-4294-43f4-8326-34a8c9f7d876.png', description: '国产企业级关系数据库', status: 'SUPPORTED', registration: true },
|
||||
{ key: 'highgo', name: '瀚高数据库', icon: 'mdi:database-star-outline', logoUrl: 'https://www.highgo.com/favicon.ico', description: '国产关系数据库', status: 'PLANNED' },
|
||||
{ key: 'db2', name: 'IBM Db2', icon: 'carbon:ibm-db2', description: '企业级关系数据库', status: 'PLANNED' },
|
||||
{ key: 'sqlite', name: 'SQLite', icon: 'logos:sqlite', description: '轻量嵌入式数据库', status: 'PLANNED' }
|
||||
@@ -597,8 +600,9 @@ const defaultPortByType: Record<DataSourceType, number> = {
|
||||
const handleTypeChange = (type: DataSourceType) => {
|
||||
const previousDefaultPort = defaultPortByType[previousType.value];
|
||||
if (!form.port || form.port === previousDefaultPort) form.port = defaultPortByType[type];
|
||||
if (type === 'DAMENG' || type === 'ORACLE') form.useSsl = false;
|
||||
if (type === 'POSTGRESQL' || type === 'SQLSERVER' || type === 'KINGBASE') form.useSsl = true;
|
||||
if (type === 'DAMENG' || type === 'ORACLE' || type === 'KINGBASE' || type === 'SQLSERVER') form.useSsl = false;
|
||||
if (type === 'POSTGRESQL') form.useSsl = true;
|
||||
if (!form.useSsl) form.trustServerCertificate = false;
|
||||
if (type !== 'SQLSERVER') form.trustServerCertificate = false;
|
||||
if (!supportsServerTimezone(type)) form.serverTimezone = '';
|
||||
previousType.value = type;
|
||||
|
||||
@@ -482,6 +482,31 @@ CREATE TRIGGER dg_ut_8bb4242921eed715 BEFORE UPDATE ON dg_secret_binding FOR EAC
|
||||
IF NOT UPDATING('UPDATE_TIME') THEN :NEW.update_time := LOCALTIMESTAMP; END IF;
|
||||
END;
|
||||
/
|
||||
-- @statement ing_api_poll_state
|
||||
CREATE TABLE ing_api_poll_state (
|
||||
intake_id BIGINT PRIMARY KEY, org_scope_id BIGINT NOT NULL, actor_id BIGINT NOT NULL,
|
||||
enabled SMALLINT NOT NULL DEFAULT 0, watermark VARCHAR(64 CHAR),
|
||||
next_due_at TIMESTAMP, lease_id VARCHAR(64 CHAR), lease_until TIMESTAMP,
|
||||
last_status VARCHAR(20 CHAR) NOT NULL DEFAULT 'NEVER', last_error_code VARCHAR(80 CHAR),
|
||||
last_written_rows INT NOT NULL DEFAULT 0, last_run_at TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
-- @statement ing_api_poll_run
|
||||
CREATE TABLE ing_api_poll_run (
|
||||
run_id BIGINT PRIMARY KEY, intake_id BIGINT NOT NULL, org_scope_id BIGINT NOT NULL,
|
||||
actor_id BIGINT NOT NULL, trigger_type VARCHAR(16 CHAR) NOT NULL,
|
||||
started_at TIMESTAMP NOT NULL, completed_at TIMESTAMP,
|
||||
run_status VARCHAR(20 CHAR) NOT NULL, written_rows INT NOT NULL DEFAULT 0,
|
||||
error_code VARCHAR(80 CHAR), watermark_before VARCHAR(64 CHAR), watermark_after VARCHAR(64 CHAR)
|
||||
);
|
||||
-- @statement ing_api_poll_run
|
||||
CREATE INDEX idx_ing_api_poll_run ON ing_api_poll_run(intake_id, started_at);
|
||||
|
||||
-- @statement ing_api_poll_profile
|
||||
CREATE TABLE ing_api_poll_profile (
|
||||
intake_id BIGINT PRIMARY KEY, org_scope_id BIGINT NOT NULL,
|
||||
profile_json CLOB NOT NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- @statement dg_maintenance_lease
|
||||
CREATE TABLE dg_maintenance_lease (
|
||||
|
||||
+31
-3
@@ -5013,7 +5013,7 @@
|
||||
],
|
||||
[
|
||||
1761490000000000080,
|
||||
"数据采集",
|
||||
"离线采集",
|
||||
1761490000000002010,
|
||||
4,
|
||||
"/unified-ingestion",
|
||||
@@ -5157,9 +5157,9 @@
|
||||
],
|
||||
[
|
||||
1761490000000000090,
|
||||
"文件接入",
|
||||
"文件采集",
|
||||
1761490000000002010,
|
||||
5,
|
||||
7,
|
||||
"/file-ingestion",
|
||||
"datagov/dataops/file-ingestion/index",
|
||||
"",
|
||||
@@ -5179,6 +5179,30 @@
|
||||
null,
|
||||
"文件接入配置与批次"
|
||||
],
|
||||
[
|
||||
1761490000000002820,
|
||||
"API采集",
|
||||
1761490000000002010,
|
||||
6,
|
||||
"/api-ingestion",
|
||||
"datagov/dataops/api-ingestion/index",
|
||||
"",
|
||||
"N",
|
||||
"N",
|
||||
"C",
|
||||
"0",
|
||||
"0",
|
||||
"aixun:dataops:file-ingestion:view",
|
||||
"link",
|
||||
"",
|
||||
"",
|
||||
1761000000000000103,
|
||||
1761100000000000001,
|
||||
"2000-01-01 00:00:00",
|
||||
null,
|
||||
null,
|
||||
"API采集配置与运行"
|
||||
],
|
||||
[
|
||||
1761490000000000091,
|
||||
"新增接入",
|
||||
@@ -17827,6 +17851,10 @@
|
||||
1761300000000000001,
|
||||
1761490000000000090
|
||||
],
|
||||
[
|
||||
1761300000000000001,
|
||||
1761490000000002820
|
||||
],
|
||||
[
|
||||
1761300000000000001,
|
||||
1761490000000000091
|
||||
|
||||
@@ -1078,3 +1078,7 @@ migrations:
|
||||
ownerUnit: system
|
||||
path: db/migration/system/V20261112.276__combine_log_management_tabs.sql
|
||||
sha256: 3df45717e655d1ed2e5795630b09feb9a3c805236a329c497f9965643288a8f0
|
||||
- version: '20261126.278'
|
||||
ownerUnit: dataops
|
||||
path: db/migration/dataops/V20261126.278__create_api_poll_profile.sql
|
||||
sha256: 25118201e1d723c82410db673af46a68ecc9be53c1a61a2a1762b2110013cc72
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE ing_api_poll_profile (
|
||||
intake_id BIGINT PRIMARY KEY,
|
||||
org_scope_id BIGINT NOT NULL,
|
||||
profile_json CLOB NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 RuoYi-Cloud-Plus
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,10 @@
|
||||
AiXun-DataGov
|
||||
|
||||
This product includes software derived from RuoYi-Cloud-Plus 6.0.0:
|
||||
https://github.com/dromara/RuoYi-Cloud-Plus
|
||||
|
||||
RuoYi-Cloud-Plus is licensed under the MIT License. The unmodified upstream
|
||||
license text is preserved in the root LICENSE file.
|
||||
|
||||
Product branding and AiXun-specific modifications are maintained by AiXun.
|
||||
Nothing in this notice alters third-party license terms or attribution.
|
||||
二进制文件未显示。
二进制文件未显示。
@@ -0,0 +1,32 @@
|
||||
-- 只读检查,在目标 DataGov schema 下执行。不是应用迁移脚本。
|
||||
-- 环境必须是已有DataGov达梦实例,包含dg_dm_install_step日志表。
|
||||
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') AS current_schema FROM DUAL;
|
||||
|
||||
-- 迁移前0,迁移后4。
|
||||
SELECT COUNT(*) AS reporting_tables FROM USER_TABLES
|
||||
WHERE TABLE_NAME IN ('DG_REPORTING_CONFIG','DG_REPORTING_AUDIT','DG_REPORTING_TEMPLATE','DG_REPORTING_STANDARD');
|
||||
|
||||
-- 迁移前0,迁移后6。
|
||||
SELECT COUNT(*) AS reporting_indexes FROM USER_INDEXES
|
||||
WHERE INDEX_NAME IN ('UK_REPORTING_CODE','IDX_REPORTING_PARENT','IDX_REPORTING_ROOT','IDX_REPORTING_AUDIT','UK_REPORTING_TEMPLATE','UK_REPORTING_STANDARD');
|
||||
|
||||
-- 必须为1;已有DataGov超级管理员,不新增角色。
|
||||
SELECT COUNT(*) AS existing_superadmin FROM sys_role
|
||||
WHERE role_id=1761300000000000001 AND role_key='superadmin' AND status='0' AND del_flag='0';
|
||||
|
||||
-- 迁移前0,迁移后9;出现冲突或中间数量时停止,先核对。
|
||||
SELECT COUNT(*) AS reporting_menus FROM sys_menu
|
||||
WHERE menu_id BETWEEN 1761700000000000800 AND 1761700000000000808
|
||||
OR path='/datagov-regulatory-reporting' OR perms LIKE 'aixun:integration:regulatory-reporting:%';
|
||||
SELECT COUNT(*) AS reporting_grants FROM sys_role_menu
|
||||
WHERE menu_id BETWEEN 1761700000000000800 AND 1761700000000000808;
|
||||
SELECT COUNT(*) AS superadmin_reporting_grants FROM sys_role_menu
|
||||
WHERE role_id=1761300000000000001 AND menu_id BETWEEN 1761700000000000800 AND 1761700000000000808;
|
||||
|
||||
-- 迁移前无行,迁移后11行且全部SUCCESS:10条表/索引DDL与1条菜单事务。
|
||||
-- 如已有日志,核对状态和SHA256;不能删除日志后重跑。
|
||||
SELECT step_key,sha256,state FROM dg_dm_install_step
|
||||
WHERE step_key LIKE 'dg_reporting_config:%' OR step_key LIKE 'dg_reporting_audit:%'
|
||||
OR step_key LIKE 'dg_reporting_template:%' OR step_key LIKE 'dg_reporting_standard:%'
|
||||
OR step_key='migration:20261124.278:reporting-menu'
|
||||
ORDER BY step_key;
|
||||
@@ -0,0 +1,103 @@
|
||||
-- 达梦现有 DataGov 专属 schema 增量277;不是全量初始化脚本。
|
||||
-- 执行前先运行00_部署检查.sql,确认本次对象和日志均不存在。
|
||||
-- 客户端必须遇错停止;DDL可能自动提交,失败后核对已执行对象,不得整份重跑。
|
||||
-- 保留既有dg_dm_install_step日志契约,每条DDL后登记同一原始摘要。
|
||||
|
||||
CREATE TABLE dg_reporting_config (
|
||||
config_id VARCHAR(36 CHAR) NOT NULL,
|
||||
organization_id BIGINT NOT NULL,
|
||||
config_kind VARCHAR(16 CHAR) NOT NULL,
|
||||
config_code VARCHAR(64 CHAR) NOT NULL,
|
||||
config_name VARCHAR(160 CHAR) NOT NULL,
|
||||
parent_id VARCHAR(36 CHAR) NULL,
|
||||
root_id VARCHAR(36 CHAR) NOT NULL,
|
||||
enabled INT NOT NULL DEFAULT 0,
|
||||
state_json CLOB NOT NULL,
|
||||
credential_ref VARCHAR(512 CHAR) NULL,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
command_sha256 CHAR(64 CHAR) NOT NULL,
|
||||
create_dept BIGINT NOT NULL,
|
||||
create_by BIGINT NOT NULL,
|
||||
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
update_by BIGINT NOT NULL,
|
||||
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (organization_id,config_id),
|
||||
CONSTRAINT ck_reporting_kind CHECK (config_kind IN ('DEPARTMENT','SYSTEM','TOPIC')),
|
||||
CONSTRAINT ck_reporting_enabled CHECK (enabled IN (0,1)),
|
||||
CONSTRAINT ck_reporting_version CHECK (version>=0)
|
||||
);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_config:dg_reporting_config','1855de229464d4eac6e108244a043a7fbbe6c1b36235a961f4f50db2f8240b97','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE UNIQUE INDEX uk_reporting_code ON dg_reporting_config(organization_id,config_kind,config_code);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_config:uk_reporting_code','fe31f46ad880cdf89596d22d8ad479686adccb608a978458b3683acd72e56034','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE INDEX idx_reporting_parent ON dg_reporting_config(organization_id,parent_id,enabled);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_config:idx_reporting_parent','d06c58e3ede561cf1bce683501192c8add823d487e01e7884ebb35d8894c7398','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE INDEX idx_reporting_root ON dg_reporting_config(organization_id,root_id);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_config:idx_reporting_root','1fc53c19fbd4e91b9758917bb7b5bb99a565b97532f23c832b2f6e602aadde72','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE TABLE dg_reporting_audit (
|
||||
audit_id VARCHAR(36 CHAR) NOT NULL,
|
||||
organization_id BIGINT NOT NULL,
|
||||
object_id VARCHAR(36 CHAR) NOT NULL,
|
||||
action_name VARCHAR(40 CHAR) NOT NULL,
|
||||
actor_id BIGINT NOT NULL,
|
||||
object_version BIGINT NOT NULL,
|
||||
reason VARCHAR(1000 CHAR) NULL,
|
||||
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (audit_id)
|
||||
);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_audit:dg_reporting_audit','92c9276a8c7ac28ea1768931b482bf7f7058cab9bacb66e9644c178236b169e0','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE INDEX idx_reporting_audit ON dg_reporting_audit(organization_id,object_id,create_time);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_audit:idx_reporting_audit','da477534a59cb8ece601775efafe68140c1a43f387eb4b958a8266f971f9a99b','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE TABLE dg_reporting_template (
|
||||
template_id VARCHAR(36 CHAR) NOT NULL,
|
||||
organization_id BIGINT NOT NULL,
|
||||
file_sha256 CHAR(64 CHAR) NOT NULL,
|
||||
record_element VARCHAR(128 CHAR) NOT NULL,
|
||||
fields_json CLOB NOT NULL,
|
||||
create_by BIGINT NOT NULL,
|
||||
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (organization_id,template_id)
|
||||
);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_template:dg_reporting_template','070c2b468d18862bdaabe7c9680856cde738516aa3a19b8c5f3d28ccc2c1be0a','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE UNIQUE INDEX uk_reporting_template ON dg_reporting_template(organization_id,file_sha256,record_element);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_template:uk_reporting_template','d176087c5ea06e3661174bcb47830c681e638f014588649153f833d81875c14f','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE TABLE dg_reporting_standard (
|
||||
standard_id VARCHAR(36 CHAR) NOT NULL,
|
||||
organization_id BIGINT NOT NULL,
|
||||
standard_code VARCHAR(128 CHAR) NOT NULL,
|
||||
standard_name VARCHAR(160 CHAR) NOT NULL,
|
||||
version_label VARCHAR(64 CHAR) NOT NULL,
|
||||
standard_status VARCHAR(16 CHAR) NOT NULL,
|
||||
definition_json CLOB NOT NULL,
|
||||
difference_confirmation VARCHAR(1000 CHAR) NULL,
|
||||
command_sha256 CHAR(64 CHAR) NOT NULL,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
create_by BIGINT NOT NULL,
|
||||
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
update_by BIGINT NOT NULL,
|
||||
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (organization_id,standard_id),
|
||||
CONSTRAINT ck_reporting_standard_status CHECK (standard_status IN ('DRAFT','PUBLISHED','DISABLED')),
|
||||
CONSTRAINT ck_reporting_standard_version CHECK (version>=0)
|
||||
);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_standard:dg_reporting_standard','274ec7ebd92cbd087de71fe9d405655c6beeb214a00ad42a2dbe5c1661b986fc','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
|
||||
CREATE UNIQUE INDEX uk_reporting_standard ON dg_reporting_standard(organization_id,standard_code,version_label);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_standard:uk_reporting_standard','90251a2acd7016d0ddb7bd45d2152d555e8a241dc4ada55c13e2177a1e9c18cd','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- 达梦增量278;先完成01,确认00中菜单、关联及菜单日志为0且superadmin为1。
|
||||
-- 在数据库客户端关闭自动提交,遇错停止并ROLLBACK。
|
||||
-- 以下18条INSERT及迁移日志须在同一事务内执行,全部成功才COMMIT。
|
||||
-- 不覆盖既有菜单,不给普通角色自动授权。
|
||||
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000800,'监管数据报送',0,15,'/datagov-regulatory-reporting','','','N','N','M','0','0','','documentation','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'监管报送独立业务入口');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000801,'报送总览',1761700000000000800,1,'/regulatory-reporting-overview','datagov/regulatory-reporting/overview/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','dashboard','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'当前组织真实配置统计');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000802,'上报部门',1761700000000000800,2,'/regulatory-reporting-departments','datagov/regulatory-reporting/departments/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','tree-table','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'监管部门管理');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000803,'上报系统',1761700000000000800,3,'/regulatory-reporting-systems','datagov/regulatory-reporting/systems/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','server','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'上报系统管理');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000804,'报送主题',1761700000000000800,4,'/regulatory-reporting-topics','datagov/regulatory-reporting/topics/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','table','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'报送主题管理');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000805,'报送标准',1761700000000000800,5,'/regulatory-reporting-standards','datagov/regulatory-reporting/standards/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','documentation','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'标准版本及目标模板');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000806,'编辑报送配置',1761700000000000802,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:edit','#','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'创建修改停用部门系统主题');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000807,'绑定报送凭据',1761700000000000803,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:credential','#','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'只绑定受管引用');
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,update_by,update_time,remark) VALUES(1761700000000000808,'管理报送标准',1761700000000000805,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:standard','#','','',1761000000000000103,1761100000000000001,LOCALTIMESTAMP,NULL,NULL,'创建标准导入模板及确认发布');
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000800);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000801);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000802);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000803);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000804);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000805);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000806);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000807);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id) VALUES(1761300000000000001,1761700000000000808);
|
||||
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('migration:20261124.278:reporting-menu','ea754e7d184e2b0ebab9146a41920282dea6edfb9fe4d94ddf6b817684ac89db','SUCCESS',NULL);
|
||||
COMMIT;
|
||||
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 8.2 KiB |
@@ -0,0 +1 @@
|
||||
import"./rolldown-runtime-aKtaBQYM.js";import{D as e,E as t,On as n,St as r,_ as i,b as a,k as o,mt as s,qt as c,vn as l}from"./runtime-core.esm-bundler-r30AjZCt.js";import{t as u}from"./button-3ly4ciuM.js";import{t as d}from"./col-GVLgLuo8.js";import{t as f}from"./row-CTgz2m6E.js";import{h as p,m}from"./useApi-CROJJdhE-Tx267Zfl.js";import{t as h}from"./_plugin-vue_export-helper-BDNMzG2s.js";var g=`/assets/401-HGF6Q5qM.gif`,_={class:`errPage-container`},v={class:`list-unstyled`},y={class:`link-type`},b=[`src`],x=h(o({__name:`401`,setup(o){let h=m(),x=p(),S=l(g+`?`+ +new Date);function C(){h.query.noGoBack?x.push({path:`/`}):x.go(-1)}return(o,l)=>{let p=u,m=r(`router-link`),h=d,g=f;return s(),a(`div`,_,[e(p,{icon:`arrow-left`,class:`pan-back-btn`,onClick:C},{default:c(()=>[...l[0]||=[t(`返回`,-1)]]),_:1}),e(g,null,{default:c(()=>[e(h,{span:12},{default:c(()=>[l[2]||=i(`h1`,{class:`text-jumbo text-ginormous`},`401错误!`,-1),l[3]||=i(`h2`,null,`您没有访问权限!`,-1),l[4]||=i(`h6`,null,`对不起,您没有访问权限,请不要进行非法操作!您可以返回主页面`,-1),i(`ul`,v,[i(`li`,y,[e(m,{to:`/`},{default:c(()=>[...l[1]||=[t(`回首页`,-1)]]),_:1})])])]),_:1}),e(h,{span:12},{default:c(()=>[i(`img`,{src:n(S),width:`313`,height:`428`,alt:`Girl has dropped her ice cream.`},null,8,b)]),_:1})]),_:1})])}}}),[[`__scopeId`,`data-v-2071f375`]]);export{x as default};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.errPage-container[data-v-2071f375]{width:800px;max-width:100%;margin:100px auto}.errPage-container .pan-back-btn[data-v-2071f375]{color:#fff;background:#008489;border:none!important}.errPage-container .pan-gif[data-v-2071f375]{margin:0 auto;display:block}.errPage-container .pan-img[data-v-2071f375]{width:100%;margin:0 auto;display:block}.errPage-container .text-jumbo[data-v-2071f375]{color:#484848;font-size:60px;font-weight:700}.errPage-container .list-unstyled[data-v-2071f375]{font-size:14px}.errPage-container .list-unstyled li[data-v-2071f375]{padding-bottom:5px}.errPage-container .list-unstyled a[data-v-2071f375]{color:#008489;text-decoration:none}.errPage-container .list-unstyled a[data-v-2071f375]:hover{text-decoration:underline}
|
||||
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 160 KiB |
@@ -0,0 +1 @@
|
||||
.wscn-http404-container[data-v-5f5d8f84]{position:absolute;top:40%;left:50%;transform:translate(-50%,-50%)}.wscn-http404[data-v-5f5d8f84]{width:1200px;padding:0 50px;position:relative;overflow:hidden}.wscn-http404 .pic-404[data-v-5f5d8f84]{float:left;width:600px;position:relative;overflow:hidden}.wscn-http404 .pic-404__parent[data-v-5f5d8f84]{width:100%}.wscn-http404 .pic-404__child[data-v-5f5d8f84]{position:absolute}.wscn-http404 .pic-404__child.left[data-v-5f5d8f84]{opacity:0;width:80px;animation-name:cloudLeft-5f5d8f84;animation-duration:2s;animation-timing-function:linear;animation-delay:1s;animation-fill-mode:forwards;top:17px;left:220px}.wscn-http404 .pic-404__child.mid[data-v-5f5d8f84]{opacity:0;width:46px;animation-name:cloudMid-5f5d8f84;animation-duration:2s;animation-timing-function:linear;animation-delay:1.2s;animation-fill-mode:forwards;top:10px;left:420px}.wscn-http404 .pic-404__child.right[data-v-5f5d8f84]{opacity:0;width:62px;animation-name:cloudRight-5f5d8f84;animation-duration:2s;animation-timing-function:linear;animation-delay:1s;animation-fill-mode:forwards;top:100px;left:500px}@keyframes cloudLeft-5f5d8f84{0%{opacity:0;top:17px;left:220px}20%{opacity:1;top:33px;left:188px}80%{opacity:1;top:81px;left:92px}to{opacity:0;top:97px;left:60px}}@keyframes cloudMid-5f5d8f84{0%{opacity:0;top:10px;left:420px}20%{opacity:1;top:40px;left:360px}70%{opacity:1;top:130px;left:180px}to{opacity:0;top:160px;left:120px}}@keyframes cloudRight-5f5d8f84{0%{opacity:0;top:100px;left:500px}20%{opacity:1;top:120px;left:460px}80%{opacity:1;top:180px;left:340px}to{opacity:0;top:200px;left:300px}}.wscn-http404 .bullshit[data-v-5f5d8f84]{float:left;width:300px;padding:30px 0;position:relative;overflow:hidden}.wscn-http404 .bullshit__oops[data-v-5f5d8f84]{color:#1482f0;opacity:0;margin-bottom:20px;font-size:32px;font-weight:700;line-height:40px;animation-name:slideUp-5f5d8f84;animation-duration:.5s;animation-fill-mode:forwards}.wscn-http404 .bullshit__headline[data-v-5f5d8f84]{color:#222;opacity:0;margin-bottom:10px;font-size:20px;font-weight:700;line-height:24px;animation-name:slideUp-5f5d8f84;animation-duration:.5s;animation-delay:.1s;animation-fill-mode:forwards}.wscn-http404 .bullshit__info[data-v-5f5d8f84]{color:gray;opacity:0;margin-bottom:30px;font-size:13px;line-height:21px;animation-name:slideUp-5f5d8f84;animation-duration:.5s;animation-delay:.2s;animation-fill-mode:forwards}.wscn-http404 .bullshit__return-home[data-v-5f5d8f84]{float:left;text-align:center;color:#fff;opacity:0;cursor:pointer;background:#1482f0;border-radius:100px;width:110px;height:36px;font-size:14px;line-height:36px;animation-name:slideUp-5f5d8f84;animation-duration:.5s;animation-delay:.3s;animation-fill-mode:forwards;display:block}@keyframes slideUp-5f5d8f84{0%{opacity:0;transform:translateY(60px)}to{opacity:1;transform:translateY(0)}}
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
var e=`data:image/svg+xml,%3csvg%20width='128'%20height='128'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M121.718%2073.272v9.953c3.957-7.584%206.199-16.05%206.199-24.995C127.917%2026.079%2099.273%200%2063.958%200%2028.644%200%200%2026.079%200%2058.23c0%20.403.028.806.028%201.21l22.97-25.953h13.34l-19.76%2027.187h6.42V53.77l13.728-19.477v49.361H22.998V73.272H2.158c5.951%2020.284%2023.608%2036.208%2045.998%2041.399-1.44%203.3-5.618%2011.263-12.565%2012.674-8.607%201.764%2023.358.428%2046.163-13.178%2017.519-4.611%2031.938-15.849%2039.77-30.513h-13.506V73.272H85.02V59.464l22.998-25.977h13.008l-19.429%2027.187h6.421v-7.433l13.727-19.402v39.433h-.027zm-78.24%202.822a10.516%2010.516%200%200%201-.996-4.535V44.548c0-1.613.332-3.124.996-4.535a11.66%2011.66%200%200%201%202.713-3.68c1.134-1.032%202.49-1.864%204.04-2.468%201.55-.605%203.21-.908%204.982-.908h11.292c1.77%200%203.431.303%204.981.908%201.522.604%202.85%201.41%203.986%202.418l-12.26%2016.303v-2.898a1.96%201.96%200%200%200-.665-1.512c-.443-.403-.996-.604-1.66-.604-.665%200-1.218.201-1.661.604a1.96%201.96%200%200%200-.664%201.512v9.071L44.364%2077.606a10.556%2010.556%200%200%201-.886-1.512zm35.73-4.535c0%201.613-.332%203.124-.997%204.535a11.66%2011.66%200%200%201-2.712%203.68c-1.134%201.032-2.49%201.864-4.04%202.469-1.55.604-3.21.907-4.982.907H55.185c-1.77%200-3.431-.303-4.981-.907-1.55-.605-2.906-1.437-4.041-2.47a12.49%2012.49%200%200%201-1.384-1.512l13.727-18.217v6.375c0%20.605.222%201.109.665%201.512.442.403.996.604%201.66.604.664%200%201.218-.201%201.66-.604a1.96%201.96%200%200%200%20.665-1.512V53.87L75.97%2036.838c.913.932%201.66%201.99%202.214%203.175.664%201.41.996%202.922.996%204.535v27.011h.028z'/%3e%3c/svg%3e`;export{e as default};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
import{D as e,E as t,On as n,St as r,T as i,_ as a,b as o,g as s,k as c,mt as l,qt as u,rr as d}from"./runtime-core.esm-bundler-r30AjZCt.js";import{t as f}from"./_plugin-vue_export-helper-BDNMzG2s.js";var p={class:`wscn-http404-container`},m={class:`wscn-http404`},h={class:`bullshit`},g={class:`bullshit__headline`},_=f(c({__name:`404`,setup(c){let f=s(()=>`找不到网页!`);return(s,c)=>{let _=r(`router-link`);return l(),o(`div`,p,[a(`div`,m,[c[3]||=i(`<div class="pic-404" data-v-5f5d8f84><img class="pic-404__parent" src="/assets/404-N4aRkdWY.png" alt="404" data-v-5f5d8f84><img class="pic-404__child left" src="/assets/404_cloud-CPexjtDj.png" alt="404" data-v-5f5d8f84><img class="pic-404__child mid" src="/assets/404_cloud-CPexjtDj.png" alt="404" data-v-5f5d8f84><img class="pic-404__child right" src="/assets/404_cloud-CPexjtDj.png" alt="404" data-v-5f5d8f84></div>`,1),a(`div`,h,[c[1]||=a(`div`,{class:`bullshit__oops`},`404错误!`,-1),a(`div`,g,d(n(f)),1),c[2]||=a(`div`,{class:`bullshit__info`},` 对不起,您正在寻找的页面不存在。尝试检查URL的错误,然后按浏览器上的刷新按钮或尝试在我们的应用程序中找到其他内容。 `,-1),e(_,{to:`/index`,class:`bullshit__return-home`},{default:u(()=>[...c[0]||=[t(`返回首页`,-1)]]),_:1})])])])}}}),[[`__scopeId`,`data-v-5f5d8f84`]]);export{_ as default};
|
||||
二进制文件未显示。
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 96 KiB |
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 4.7 KiB |
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/python-C3JLglTv.js","assets/editor.api-CNxm_hDB.js","assets/preload-helper-Czpn1I53.js","assets/editor-DrYDXvPF.css"])))=>i.map(i=>d[i]);
|
||||
import{Ht as e,b as t,ct as n,it as r,k as i,mt as a,vn as o}from"./runtime-core.esm-bundler-r30AjZCt.js";import{t as s}from"./preload-helper-Czpn1I53.js";import{i as c,n as l,r as u,t as d}from"./editor.api-CNxm_hDB.js";var f={},p={},m=class e{static getOrCreate(t){return p[t]||(p[t]=new e(t)),p[t]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((e,t)=>{this._lazyLoadPromiseResolve=e,this._lazyLoadPromiseReject=t})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,f[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}};function h(e){let t=e.id;f[t]=e,c.register(e);let n=m.getOrCreate(t);c.registerTokensProviderFactory(t,{create:async()=>(await n.load()).language}),c.onLanguageEncountered(t,async()=>{let e=await n.load();c.setLanguageConfiguration(t,e.conf)})}h({id:`python`,extensions:[`.py`,`.rpy`,`.pyw`,`.cpy`,`.gyp`,`.gypi`],aliases:[`Python`,`py`],firstLine:`^#!/.*\\bpython[0-9.-]*\\b`,loader:()=>s(()=>import(`./python-C3JLglTv.js`),__vite__mapDeps([0,1,2,3]))}),h({id:`shell`,extensions:[`.sh`,`.bash`],aliases:[`Shell`,`sh`],loader:()=>s(()=>import(`./shell-CC2rA5mh.js`),[])}),h({id:`sql`,extensions:[`.sql`],aliases:[`SQL`],loader:()=>s(()=>import(`./sql-NEE52Syq.js`),[])});function g(e){return new Worker(`/assets/editor.worker-Bbk1whK-.js`,{name:e?.name})}var _=i({__name:`index`,props:{modelValue:{},language:{},readOnly:{type:Boolean,default:!1},theme:{default:`vs`}},emits:[`update:modelValue`,`ready`,`run`,`save`],setup(i,{emit:s}){self.MonacoEnvironment={getWorker:()=>new g};let c=i,f=s,p=o(),m,h,_=e=>({SQL:`sql`,SHELL:`shell`,PYTHON:`python`})[e];return n(()=>{h=u.createModel(c.modelValue,_(c.language)),m=u.create(p.value,{model:h,theme:c.theme,readOnly:c.readOnly,automaticLayout:!0,minimap:{enabled:!0},fontSize:14,lineHeight:22,renderWhitespace:`selection`,scrollBeyondLastLine:!1,wordWrap:`off`,ariaLabel:`${c.language} 代码编辑器`}),m.addCommand(l.CtrlCmd|d.Enter,()=>f(`run`)),m.addCommand(l.CtrlCmd|d.KeyS,()=>f(`save`)),m.onDidChangeModelContent(()=>f(`update:modelValue`,h.getValue())),f(`ready`,m)}),e(()=>c.readOnly,e=>m?.updateOptions({readOnly:e})),e(()=>c.theme,e=>u.setTheme(e)),e(()=>c.language,e=>{h&&u.setModelLanguage(h,_(e)),m?.updateOptions({ariaLabel:`${e} 代码编辑器`})}),e(()=>c.modelValue,e=>{h&&h.getValue()!==e&&h.setValue(e)}),r(()=>{m?.dispose(),h?.dispose()}),(e,n)=>(a(),t(`div`,{ref_key:`host`,ref:p,class:`h-[520px] w-full`,"data-testid":`aixun-code-editor`},null,512))}});export{_ as default};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.alert-stages[data-v-2d9a3688]{grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin:18px 0;display:grid}.alert-stages article[data-v-2d9a3688]{border:1px solid var(--el-border-color-lighter);border-radius:7px;padding:14px}.alert-stages .current[data-v-2d9a3688]{background:var(--el-color-primary-light-9);border-color:var(--el-color-primary)}.alert-stages strong[data-v-2d9a3688]{margin-top:10px;font-size:11px;display:block}.alert-stages small[data-v-2d9a3688],.alert-note[data-v-2d9a3688]{color:var(--el-text-color-secondary);font-size:12px;line-height:1.8}.alert-columns[data-v-2d9a3688]{grid-template-columns:1fr 1fr;gap:20px;display:grid}.alert-columns article[data-v-2d9a3688]{border:1px solid var(--el-border-color-lighter);border-radius:8px;min-width:0;padding:18px}.alert-columns h4[data-v-2d9a3688]{margin:0 0 20px}.alert-columns p[data-v-2d9a3688]{overflow-wrap:anywhere;font-size:12px;line-height:1.8}.notification[data-v-2d9a3688]{border-bottom:1px solid var(--el-border-color-lighter);padding:12px 0}.notification strong[data-v-2d9a3688]{margin-left:10px;font-size:12px}.notification small[data-v-2d9a3688]{color:var(--el-text-color-secondary);font-size:11px}@media (width<=700px){.alert-stages[data-v-2d9a3688]{grid-template-columns:repeat(3,minmax(0,1fr))}.alert-columns[data-v-2d9a3688]{grid-template-columns:1fr}}
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{$n as t,D as n,E as r,On as i,_ as a,b as o,bt as s,g as c,k as l,mt as u,o as d,qt as f,rr as p,v as m,y as h}from"./runtime-core.esm-bundler-r30AjZCt.js";import{t as g}from"./tag-C31GvCve.js";import{t as _}from"./empty-BejoSUEw.js";import{n as v,t as y}from"./timeline-cIBjqcNR.js";import{t as b}from"./_plugin-vue_export-helper-BDNMzG2s.js";import{t as x}from"./DgEvidenceMatrix-7mDF-jCx.js";function S(e){return e.mailboxState===`STORED`&&e.mailboxMessageId?{label:`已存收件箱`,tone:`success`}:e.mailboxState===`SUBMITTING`?{label:`正在存入`,tone:`warning`}:!e.mailboxState||e.mailboxState===`RECORDED`?{label:`已登记`,tone:`info`}:{label:`存储结果未知`,tone:`warning`}}var C={class:`alert-stages`},w={class:`alert-columns`},T=l({__name:`AlertObservation`,props:{detail:{}},setup(e){let l=e,b=[{key:`OPEN`,label:`待处理`},{key:`ASSIGNED`,label:`已分派`},{key:`PROCESSING`,label:`处理中`},{key:`RESOLVED`,label:`已解决`},{key:`VERIFIED`,label:`已核验`},{key:`CLOSED`,label:`已关闭`}],T=e=>b.find(t=>t.key===e)?.label||`未知`,E=c(()=>({FAILED_COUNT:`失败次数`,FAILURE_RATE_PERCENT:`失败率(%)`,BACKLOG_COUNT:`积压数量`,MAX_DURATION_MS:`最大耗时(毫秒)`})[l.detail.summary.metric]||`观测值`),D=c(()=>l.detail.occurrences.map(e=>({id:String(e.occurrenceId),label:`${e.observedFrom} → ${e.observedTo}`,cells:{value:{text:String(e.metricValue??`--`)},samples:{text:String(e.sampleCount??`--`)},evidence:{text:/^[a-f\d]{64}$/i.test(e.evidenceSha256)?`已记录摘要`:`未提供有效摘要`,tone:/^[a-f\d]{64}$/i.test(e.evidenceSha256)?`neutral`:`warning`}}})));return(c,l)=>{let O=v,k=y,A=_,j=g;return u(),o(`section`,null,[a(`div`,C,[(u(),o(d,null,s(b,n=>a(`article`,{key:n.key,class:t({current:e.detail.summary.status===n.key})},[a(`small`,null,p(n.label),1),a(`strong`,null,p(e.detail.summary.status===n.key?`当前状态`:`状态节点`),1)],2)),64))]),l[3]||=a(`p`,{class:`alert-note`},`只高亮当前状态;实际处理顺序以下方时间线为准,不按位置推断已完成。`,-1),n(x,{title:`告警发生观测`,description:`${e.detail.summary.ruleName} · ${e.detail.occurrences.length} 条已返回记录`,rows:D.value,columns:[{id:`value`,label:E.value},{id:`samples`,label:`样本数`},{id:`evidence`,label:`证据登记`}],note:`按实际发生窗口列出,不补齐缺失窗口、不生成虚假连续趋势。`},null,8,[`description`,`rows`,`columns`]),a(`div`,w,[a(`article`,null,[l[0]||=a(`h4`,null,`实际处理轨迹`,-1),e.detail.timeline.length?(u(),m(k,{key:0},{default:f(()=>[(u(!0),o(d,null,s(e.detail.timeline,e=>(u(),m(O,{key:String(e.timelineId),timestamp:e.createdAt},{default:f(()=>[a(`strong`,null,p(e.action)+` · `+p(T(e.toStatus)),1),a(`p`,null,p(e.reasonSummary||`--`),1)]),_:2},1032,[`timestamp`]))),128))]),_:1})):(u(),m(A,{key:1,description:`暂无轨迹`,"image-size":50}))]),a(`article`,null,[l[1]||=a(`h4`,null,`通知与收件箱`,-1),(u(!0),o(d,null,s(e.detail.notifications,e=>(u(),o(`div`,{key:String(e.notificationId),class:`notification`},[n(j,{type:i(S)(e).tone},{default:f(()=>[r(p(i(S)(e).label),1)]),_:2},1032,[`type`]),a(`strong`,null,p(e.recipientUserName),1),a(`p`,null,p(e.contentSummary),1),a(`small`,null,p(e.mailboxAttemptedAt||e.recordedAt),1)]))),128)),e.detail.notifications.length?h(``,!0):(u(),m(A,{key:0,description:`暂无通知记录`,"image-size":50})),l[2]||=a(`p`,{class:`alert-note`},`已登记仅表示有通知记录;已存收件箱表示站内消息已持久化,不表示实时推送送达或对方已读。`,-1)])])])}}}),E=e({default:()=>D}),D=b(T,[[`__scopeId`,`data-v-2d9a3688`]]);export{E as n,S as r,D as t};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.alert-occurrence-evidence[data-v-1e83d5bf]{display:inline-flex}
|
||||
文件差异因一行或多行过长而隐藏
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.annotation-review-assist[data-v-49c64302]{margin-bottom:12px;display:inline-flex}.source-label[data-v-49c64302]{margin:12px 0 6px;display:block}.source-text[data-v-49c64302]{box-sizing:border-box;border:1px solid var(--el-border-color);width:100%;min-height:150px;color:var(--el-text-color-primary);background:var(--el-fill-color-blank);border-radius:4px;padding:10px}.source-fragment[data-v-49c64302],.finding[data-v-49c64302]{white-space:pre-wrap;overflow-wrap:anywhere;margin-top:12px}.assist-actions[data-v-49c64302]{gap:8px;margin:16px 0;display:flex}pre[data-v-49c64302],blockquote[data-v-49c64302]{white-space:pre-wrap;overflow-wrap:anywhere}blockquote[data-v-49c64302]{border-left:3px solid var(--el-border-color);margin-left:0;padding-left:12px}
|
||||
文件差异因一行或多行过长而隐藏
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{D as t,E as n,Ht as r,_ as i,b as a,bt as o,k as s,mt as c,o as l,qt as u,rr as d,v as f,vn as p,y as m}from"./runtime-core.esm-bundler-r30AjZCt.js";import{ft as h,g}from"./user-DsL-tEKE.js";import{n as _,t as v}from"./descriptions-e2YXrSRn.js";import{n as y,t as b}from"./select-Bib_hB05.js";import{t as x}from"./alert-B7RqasP2.js";import{n as S,t as C}from"./form-BX1luqMh.js";import{t as w}from"./button-3ly4ciuM.js";import{t as T}from"./drawer-vx5Rt98l.js";var E=()=>g({url:`/api/governance/v1/anomaly-detections/assist/target-profiles`}),D=e=>g({url:`/api/governance/v1/anomaly-detections/assist/target`,method:`post`,data:{snapshotId:e}});function O(e){if(!e||typeof e.snapshotId!=`string`||!/^[1-9][0-9]{0,18}$/.test(e.snapshotId)||BigInt(e.snapshotId)>9223372036854775807n||!/^table:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e.targetLogicalId)||!/^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,511}$/.test(e.targetFqn)||!/^[0-9a-f]{64}$/.test(e.fingerprint))throw Error(`物理目标不可确认,请重新选择`);return{snapshotId:e.snapshotId,targetLogicalId:e.targetLogicalId,targetFqn:e.targetFqn,fingerprint:e.fingerprint}}function k(e){let t=O(e);return{targetLogicalId:t.targetLogicalId,targetFqn:t.targetFqn,profileTarget:{snapshotId:t.snapshotId,fingerprint:t.fingerprint}}}function A(e,t){return JSON.stringify(O(e))===JSON.stringify(O(t))}function j(e){return JSON.parse(JSON.stringify(e))}function M(e){let t=e?.response?.status??e?.status;return t===400||t===409}var N={class:`inline-flex`},P={class:`dialog-footer`},F=s({__name:`AnomalyProfileTargetPicker`,props:{disabled:{type:Boolean},formFingerprint:{}},emits:[`busy-change`,`apply`],setup(e,{emit:s}){let g=e,k=s,j=p(!1),M=p(!1),F=p(``),I=p([]),L=p(),R=p(``),z=0,B=``;r(()=>g.formFingerprint,()=>{j.value&&g.formFingerprint!==B&&(z++,L.value=void 0,R.value=`表单已变化,请关闭后重新选择`)});function V(e){M.value=e,k(`busy-change`,e)}function H(e){M.value||(z++,e())}async function U(){if(g.disabled||M.value)return;let e=++z;B=g.formFingerprint,L.value=void 0,F.value=``,I.value=[],R.value=``,j.value=!0,V(!0);try{let t=(await E()).data;e===z&&j.value&&(I.value=t||[])}finally{V(!1)}}async function W(){if(g.disabled||M.value||!F.value||!I.value.some(e=>e.snapshotId===F.value)||B!==g.formFingerprint)return;let e=++z,t=F.value;L.value=void 0,R.value=``,V(!0);try{let n=O((await D(t)).data);e===z&&j.value&&t===F.value&&B===g.formFingerprint&&(L.value=n)}finally{V(!1)}}async function G(){if(g.disabled||M.value||!L.value||B!==g.formFingerprint)return;let e=++z,t=O(L.value);V(!0);try{let n=O((await D(t.snapshotId)).data);if(e!==z||!j.value||B!==g.formFingerprint||!A(t,n)){L.value=void 0,R.value=`目标或权限已变化,请重新核对`;return}k(`apply`,n),j.value=!1,h.success(`已回填目标,请审核并保存检测`)}finally{V(!1)}}return(r,s)=>{let p=w,h=x,g=b,E=y,D=S,O=C,k=_,A=v,z=T;return c(),a(`span`,N,[t(p,{disabled:e.disabled||M.value,onClick:U},{default:u(()=>[...s[4]||=[n(`从已绑定画像选择目标`,-1)]]),_:1},8,[`disabled`]),t(z,{modelValue:j.value,"onUpdate:modelValue":s[3]||=e=>j.value=e,title:`选择当前物理目标`,size:`620px`,"append-to-body":``,"before-close":H},{footer:u(()=>[i(`div`,P,[t(p,{disabled:M.value,onClick:s[2]||=e=>j.value=!1},{default:u(()=>[...s[7]||=[n(`取消`,-1)]]),_:1},8,[`disabled`]),t(p,{type:`primary`,disabled:!L.value||e.disabled,loading:M.value,onClick:G},{default:u(()=>[...s[8]||=[n(`回填目标`,-1)]]),_:1},8,[`disabled`,`loading`])])]),default:u(()=>[t(h,{title:`选择历史画像后重新核对当前物理表、结构和读取权限,仅回填目标,不保存检测。`,type:`info`,closable:!1}),t(O,{class:`mt-4`,"label-position":`top`,disabled:M.value||e.disabled},{default:u(()=>[t(D,{label:`已绑定来源的画像`},{default:u(()=>[t(E,{modelValue:F.value,"onUpdate:modelValue":s[0]||=e=>F.value=e,filterable:``,class:`w-full`,placeholder:`请选择画像`,onChange:s[1]||=e=>L.value=void 0},{default:u(()=>[(c(!0),a(l,null,o(I.value,e=>(c(),f(g,{key:e.snapshotId,value:e.snapshotId,label:`${e.sourceLabel} · ${e.observedAt.replace(`T`,` `)}`},null,8,[`value`,`label`]))),128))]),_:1},8,[`modelValue`])]),_:1}),t(p,{loading:M.value,disabled:!F.value,onClick:W},{default:u(()=>[...s[5]||=[n(`核对当前目标`,-1)]]),_:1},8,[`loading`,`disabled`])]),_:1},8,[`disabled`]),R.value?(c(),f(h,{key:0,class:`mt-4`,title:R.value,type:`warning`,closable:!1},null,8,[`title`])):m(``,!0),L.value?(c(),f(A,{key:1,class:`mt-4`,column:1,border:``},{default:u(()=>[t(k,{label:`物理表`},{default:u(()=>[n(d(L.value.targetFqn),1)]),_:1}),t(k,{label:`来源`},{default:u(()=>[...s[6]||=[n(`历史画像已关联的当前可读对象`,-1)]]),_:1})]),_:1})):m(``,!0)]),_:1},8,[`modelValue`])])}}}),I=e({default:()=>L}),L=F;export{k as a,j as i,I as n,M as r,L as t};
|
||||
二进制
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.anomaly-series-assist[data-v-3e82d109]{display:inline-flex}.source-hint[data-v-3e82d109]{color:var(--el-text-color-secondary);font-size:12px;line-height:1.8}
|
||||
文件差异因一行或多行过长而隐藏
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{$n as t,_ as n,b as r,bt as i,g as a,k as o,mt as s,o as c,rr as l,y as u}from"./runtime-core.esm-bundler-r30AjZCt.js";import{t as d}from"./_plugin-vue_export-helper-BDNMzG2s.js";var f={class:`series-chart`,"aria-label":`真实行数观察趋势`},p={key:0,viewBox:`0 0 680 180`,role:`img`,"aria-label":`按采样时间排序的行数变化`},m=[`y1`,`y2`],h=[`points`],g=[`cx`,`cy`,`r`],_={x:`28`,y:`174`},v={x:`650`,y:`174`,"text-anchor":`end`},y=o({__name:`AnomalySeriesChart`,props:{points:{},lower:{},upper:{}},setup(e){let o=e,d=a(()=>o.points.map(e=>({...e,value:Number(e.rowCount)})).filter(e=>Number.isFinite(e.value))),y=a(()=>[{label:`下界`,raw:o.lower},{label:`上界`,raw:o.upper}].filter(e=>e.raw!=null).map(e=>({label:e.label,value:Number(e.raw)})).filter(e=>Number.isFinite(e.value))),b=a(()=>{let e=[...d.value.map(e=>e.value),...y.value.map(e=>e.value)],t=Math.min(...e,0),n=Math.max(...e,1);return{min:t,span:Math.max(n-t,1)}}),x=e=>28+622*e/Math.max(d.value.length-1,1),S=e=>150-125*(e-b.value.min)/b.value.span,C=a(()=>d.value.map((e,t)=>`${x(t)},${S(e.value)}`).join(` `));return(e,a)=>(s(),r(`figure`,f,[a[1]||=n(`figcaption`,null,[n(`strong`,null,`行数变化`),n(`span`,null,`最后一个点为本次评估,虚线为本次阈值`)],-1),d.value.length?(s(),r(`svg`,p,[a[0]||=n(`line`,{x1:`28`,y1:`150`,x2:`650`,y2:`150`,class:`axis`},null,-1),(s(!0),r(c,null,i(y.value,e=>(s(),r(`line`,{key:e.label,x1:`28`,y1:S(e.value),x2:`650`,y2:S(e.value),class:`bound`},null,8,m))),128)),n(`polyline`,{points:C.value,class:`trend`},null,8,h),(s(!0),r(c,null,i(d.value,(e,i)=>(s(),r(`circle`,{key:e.key,cx:x(i),cy:S(e.value),r:i===d.value.length-1?6:3.5,class:t([`point`,{last:i===d.value.length-1}])},[n(`title`,null,l(e.observedAt)+` · `+l(e.rowCount)+` 行`,1)],10,g))),128)),n(`text`,_,l(d.value[0]?.observedAt),1),n(`text`,v,l(d.value.at(-1)?.observedAt),1)])):u(``,!0)]))}}),b=e({default:()=>x}),x=d(y,[[`__scopeId`,`data-v-c8ba0dde`]]);export{b as n,x as t};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.series-chart[data-v-c8ba0dde]{background:var(--el-fill-color-light);border:1px solid var(--el-border-color-lighter);border-radius:8px;margin:18px 0;padding:16px}.series-chart figcaption[data-v-c8ba0dde]{color:var(--el-text-color-secondary);justify-content:space-between;gap:12px;font-size:12px;display:flex}.series-chart strong[data-v-c8ba0dde]{color:var(--el-text-color-primary);font-size:14px}svg[data-v-c8ba0dde]{width:100%;margin-top:10px;display:block}.axis[data-v-c8ba0dde]{stroke:var(--el-border-color)}.bound[data-v-c8ba0dde]{stroke:var(--el-color-warning);stroke-dasharray:6 5}.trend[data-v-c8ba0dde]{fill:none;stroke:var(--el-color-primary);stroke-width:2.5px}.point[data-v-c8ba0dde]{fill:var(--el-color-primary);stroke:var(--el-bg-color);stroke-width:2px}.last[data-v-c8ba0dde]{fill:var(--el-color-warning)}text[data-v-c8ba0dde]{fill:var(--el-text-color-secondary);font-size:10px}
|
||||
@@ -0,0 +1 @@
|
||||
.api-dependency-map[data-v-ff7932cd]{min-width:0;margin:16px 0}.snapshot-selector[data-v-ff7932cd]{width:min(520px,100%)}
|
||||
@@ -0,0 +1 @@
|
||||
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{D as t,E as n,Ht as r,b as i,bt as a,g as o,k as s,mt as c,o as l,qt as u,rr as d,v as f,vn as p,y as m}from"./runtime-core.esm-bundler-r30AjZCt.js";import{n as h,t as g}from"./descriptions-e2YXrSRn.js";import{n as _,t as v}from"./select-Bib_hB05.js";import{l as y}from"./dist-BugY7UeI.js";import{t as b}from"./_plugin-vue_export-helper-BDNMzG2s.js";import{t as x}from"./DgEvidenceFlow-CUNjVAsk.js";import{a as S,t as C}from"./projections-BZattWnH.js";var w={class:`api-dependency-map`},T=s({__name:`ApiDependencyMap`,props:{dependencies:{},managementId:{},label:{}},setup(e){let s=e,b=y({interval:1e3}),T=p(``),E=o(()=>[...s.dependencies].toSorted((e,t)=>(Date.parse(t.createTime||t.observedAt)||0)-(Date.parse(e.createTime||e.observedAt)||0)));r(()=>[s.managementId,s.dependencies],()=>{T.value=String(E.value[0]?.dependencyId??``)},{immediate:!0});let D=o(()=>E.value.find(e=>String(e.dependencyId)===T.value)),O=o(()=>!!D.value&&S(D.value,b.value.getTime())),k=o(()=>{if(D.value&&!O.value)return{graph:{nodes:[],edges:[]},error:`所选快照未知、证据不完整或已过期,请查看原记录或刷新依赖`};try{return{graph:C(D.value,s.label,Date.now()),error:``}}catch{return{graph:{nodes:[],edges:[]},error:`依赖超过显示范围或标识无效,请查看原记录`}}}),A=o(()=>Object.fromEntries(k.value.graph.nodes.map(e=>[e.id,{title:e.label,facts:{关系角色:e.kind||`--`,观测时间:D.value?.observedAt||`--`,证据摘要:D.value?.sourceSha256||`--`}}])));return(r,o)=>{let s=v,p=_,y=h,b=g;return c(),i(`section`,w,[t(p,{modelValue:T.value,"onUpdate:modelValue":o[0]||=e=>T.value=e,placeholder:`选择依赖快照`,"aria-label":`依赖快照`,class:`snapshot-selector`},{default:u(()=>[(c(!0),i(l,null,a(E.value,e=>(c(),f(s,{key:String(e.dependencyId),value:String(e.dependencyId),label:`${e.observedAt||e.createTime||`时间未知`} · ${e.status===`RELIABLE`?`记录可靠`:`记录未知`}`},null,8,[`value`,`label`]))),128))]),_:1},8,[`modelValue`]),t(x,{title:`接口消费依赖`,description:`调用方 → 当前接口 → 下游系统。`,graph:k.value.graph,error:k.value.error,"scope-key":`api:${e.managementId}:${T.value}`,details:A.value,note:`仅使用所选依赖快照;未知或过期快照不回退到早先可靠结果。不据此推算调用量、延迟或业务价值。`},null,8,[`graph`,`error`,`scope-key`,`details`]),D.value?(c(),f(b,{key:0,column:2,border:``},{default:u(()=>[t(y,{label:`来源`},{default:u(()=>[n(d(D.value.sourceType||`--`),1)]),_:1}),t(y,{label:`有效截至`},{default:u(()=>[n(d(D.value.expiresAt||`--`),1)]),_:1}),t(y,{label:`影响说明`,span:2},{default:u(()=>[n(d(O.value?D.value.impacts.join(`;`)||`--`:`当前快照不可用`),1)]),_:1})]),_:1})):m(``,!0)])}}}),E=e({default:()=>D}),D=b(T,[[`__scopeId`,`data-v-ff7932cd`]]);export{E as n,D as t};
|
||||
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.api-model-assist[data-v-03af2346]{margin-bottom:12px;display:inline-flex}.el-checkbox-group[data-v-03af2346]{margin:16px 0}
|
||||
文件差异因一行或多行过长而隐藏
二进制文件未显示。
@@ -0,0 +1 @@
|
||||
.production[data-v-be88cda8]{padding:16px 0}.production header[data-v-be88cda8]{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:16px;margin-bottom:16px;display:flex}h4[data-v-be88cda8]{margin:0;font-size:16px}header p[data-v-be88cda8],.note[data-v-be88cda8]{color:var(--el-text-color-secondary);font-size:12px;line-height:1.8}.actions[data-v-be88cda8]{align-items:center;gap:8px;display:flex}.actions .el-select[data-v-be88cda8]{width:150px}.endpoint[data-v-be88cda8]{flex-wrap:wrap;align-items:center;gap:12px;margin:16px 0;display:flex}.endpoint code[data-v-be88cda8]{overflow-wrap:anywhere}.invoke-form[data-v-be88cda8]{max-width:760px}.receipt[data-v-be88cda8]{margin:14px 0}.metrics[data-v-be88cda8]{grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:18px 0;display:grid}.metrics article[data-v-be88cda8]{border:1px solid var(--el-border-color-lighter);border-radius:8px;min-width:0;padding:14px}.metrics span[data-v-be88cda8]{color:var(--el-text-color-secondary);font-size:12px}.metrics strong[data-v-be88cda8]{font-variant-numeric:tabular-nums;margin-top:8px;font-size:23px;display:block}.chart[data-v-be88cda8]{width:100%;height:340px;margin-top:18px}.el-alert[data-v-be88cda8]{margin-bottom:12px}@media (width<=650px){.metrics[data-v-be88cda8]{grid-template-columns:repeat(2,minmax(0,1fr))}.actions[data-v-be88cda8]{width:100%}}
|
||||
二进制文件未显示。
文件差异因一行或多行过长而隐藏
二进制文件未显示。
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
在新工单中引用
屏蔽一个用户