编写CDC 、api采集
这个提交包含在:
+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());
|
||||
}
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户