编写CDC 、api采集
这个提交包含在:
+52
@@ -0,0 +1,52 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/dataops/v1/api-ingestions")
|
||||
public class ApiPollController {
|
||||
private final ApiPollService service;
|
||||
private final ApiPollProfileService profiles;
|
||||
|
||||
public record EnabledCommand(boolean enabled) { }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId) { return R.ok(profiles.view(intakeId)); }
|
||||
|
||||
@Log(title="API采集请求配置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId,
|
||||
@RequestBody ApiPollProfileService.Command command) {
|
||||
return R.ok(profiles.save(intakeId, command));
|
||||
}
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> state(@PathVariable long intakeId) { return R.ok(service.state(intakeId)); }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll/runs")
|
||||
public R<List<ApiPollService.PollRun>> runs(@PathVariable long intakeId) { return R.ok(service.runs(intakeId)); }
|
||||
|
||||
@Log(title="API采集轮询设置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> enabled(@PathVariable long intakeId, @RequestBody EnabledCommand command) {
|
||||
return R.ok(service.setEnabled(intakeId, command.enabled()));
|
||||
}
|
||||
|
||||
@Log(title="API采集立即运行", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:submit")
|
||||
@PostMapping("/{intakeId}/poll/run")
|
||||
public R<ApiPollService.PollRun> run(@PathVariable long intakeId) { return R.ok(service.runNow(intakeId)); }
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollProfileService {
|
||||
private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}");
|
||||
private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}");
|
||||
private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}");
|
||||
private static final Set<String> AUTH = Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY");
|
||||
private static final Set<String> SIGN = Set.of("NONE", "HMAC_SHA256", "RSA_SHA256");
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final FileManagedCredentialGateway credentials;
|
||||
|
||||
public record Command(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
char[] signingKey) {
|
||||
@Override public String toString() { return "ApiPollProfileCommand[signingKey=REDACTED]"; }
|
||||
}
|
||||
|
||||
public record View(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
boolean signingKeyConfigured) { }
|
||||
|
||||
public View view(long intakeId) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
return view(profile(actor, intakeId));
|
||||
}
|
||||
|
||||
ApiPollProfile profile(FileIngestionActor actor, long intakeId) {
|
||||
requireApi(actor, intakeId);
|
||||
var rows = jdbc.query("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=? AND org_scope_id=?",
|
||||
(rs, index) -> rs.getString(1), intakeId, actor.orgScopeId());
|
||||
if (rows.isEmpty()) return null;
|
||||
try { return json.readValue(rows.getFirst(), ApiPollProfile.class); }
|
||||
catch (Exception failure) { throw FileIngestionException.validation("API高级配置无效"); }
|
||||
}
|
||||
|
||||
public View save(long intakeId, Command command) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
if (command == null) throw FileIngestionException.validation("API高级配置不能为空");
|
||||
ApiPollProfile current = profile(actor, intakeId);
|
||||
String newRef = null;
|
||||
char[] supplied = command.signingKey();
|
||||
try {
|
||||
validate(command);
|
||||
String kind = command.signatureKind() == null ? "NONE" : command.signatureKind();
|
||||
String signingRef = "NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind())
|
||||
? null : current == null ? null : current.signingSecretRef();
|
||||
if (supplied != null && supplied.length > 0) {
|
||||
if ("NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("此认证方式无需单独提供签名密钥");
|
||||
newRef = credentials.provision(supplied);
|
||||
signingRef = newRef;
|
||||
}
|
||||
if (!"NONE".equals(kind) && signingRef == null && !"SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("请输入签名密钥");
|
||||
var profile = new ApiPollProfile(command.authKind(), command.tokenEndpoint(), command.tokenFormat(),
|
||||
command.clientId(), command.tokenClientField(), command.tokenSecretField(),
|
||||
command.tokenCredentialStyle(), command.tokenPath(), command.expiresPath(), command.requestMethod(),
|
||||
command.headers() == null ? Map.of() : Map.copyOf(command.headers()),
|
||||
command.queryParameters() == null ? Map.of() : Map.copyOf(command.queryParameters()),
|
||||
command.requestBody(), command.pageSize(), command.lookbackSeconds(), command.successPath(),
|
||||
command.successValue(), kind, command.signatureTemplate(), command.signaturePlacement(), command.signatureHeader(),
|
||||
command.signatureEncoding(), signingRef);
|
||||
String encoded = json.writeValueAsString(profile);
|
||||
int updated = jdbc.update("UPDATE ing_api_poll_profile SET profile_json=?,updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?",
|
||||
encoded, intakeId, actor.orgScopeId());
|
||||
if (updated == 0) jdbc.update("INSERT INTO ing_api_poll_profile(intake_id,org_scope_id,profile_json) VALUES (?,?,?)",
|
||||
intakeId, actor.orgScopeId(), encoded);
|
||||
newRef = null;
|
||||
if (current != null && current.signingSecretRef() != null &&
|
||||
!current.signingSecretRef().equals(signingRef)) safeRevoke(current.signingSecretRef());
|
||||
return view(profile);
|
||||
} catch (RuntimeException failure) {
|
||||
if (newRef != null) safeRevoke(newRef);
|
||||
throw failure;
|
||||
} finally {
|
||||
if (supplied != null) Arrays.fill(supplied, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private void requireApi(FileIngestionActor actor, long intakeId) {
|
||||
if (repository.config(actor, intakeId).sourceType() != FileSourceType.API_SAAS)
|
||||
throw FileIngestionException.validation("仅API采集可配置请求协议");
|
||||
}
|
||||
|
||||
private static View view(ApiPollProfile value) {
|
||||
if (value == null) return new View("STATIC_BEARER", null, "FORM", null,
|
||||
"client_id", "client_secret", "BODY", "$.access_token",
|
||||
"$.expires_in", "GET", Map.of(), Map.of(), null, 100, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", false);
|
||||
return new View(value.authKind(), value.tokenEndpoint(), value.tokenFormat(), value.clientId(),
|
||||
value.tokenClientField(), value.tokenSecretField(), value.tokenCredentialStyle(),
|
||||
value.tokenPath(), value.expiresPath(), value.requestMethod(), value.headers(),
|
||||
value.queryParameters(), value.requestBody(), value.pageSize(), value.lookbackSeconds(),
|
||||
value.successPath(), value.successValue(), value.signatureKind(), value.signatureTemplate(),
|
||||
value.signaturePlacement(), value.signatureHeader(), value.signatureEncoding(),
|
||||
value.signingSecretRef() != null || "SIGN_ONLY".equals(value.authKind()));
|
||||
}
|
||||
|
||||
private static void validate(Command c) {
|
||||
if (!AUTH.contains(c.authKind()) || !Set.of("GET", "POST").contains(c.requestMethod()) ||
|
||||
c.pageSize() == null || c.pageSize() < 1 || c.pageSize() > 1000 ||
|
||||
c.lookbackSeconds() == null || c.lookbackSeconds() < 0 || c.lookbackSeconds() > 86400 ||
|
||||
!SIGN.contains(c.signatureKind() == null ? "NONE" : c.signatureKind()))
|
||||
throw FileIngestionException.validation("API请求配置无效");
|
||||
if ("SIGN_ONLY".equals(c.authKind()) && (c.signatureKind() == null || "NONE".equals(c.signatureKind())))
|
||||
throw FileIngestionException.validation("仅签名认证必须开启请求签名");
|
||||
if (!"STATIC_BEARER".equals(c.authKind()) && !"API_KEY_HEADER".equals(c.authKind()) &&
|
||||
!"SIGN_ONLY".equals(c.authKind())) {
|
||||
try {
|
||||
URI uri = URI.create(c.tokenEndpoint());
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null ||
|
||||
uri.getRawQuery() != null || uri.getFragment() != null) throw new IllegalArgumentException();
|
||||
} catch (RuntimeException failure) { throw FileIngestionException.validation("认证接口必须是无密钥参数的HTTPS地址"); }
|
||||
if (!Set.of("FORM", "JSON").contains(c.tokenFormat()) ||
|
||||
c.clientId() == null || c.clientId().isBlank() || c.clientId().length() > 256 ||
|
||||
!FIELD.matcher(c.tokenClientField() == null ? "" : c.tokenClientField()).matches() ||
|
||||
!FIELD.matcher(c.tokenSecretField() == null ? "" : c.tokenSecretField()).matches() ||
|
||||
!Set.of("BODY", "BASIC").contains(c.tokenCredentialStyle()) ||
|
||||
("PASSWORD_TOKEN".equals(c.authKind()) && "BASIC".equals(c.tokenCredentialStyle())) ||
|
||||
!path(c.tokenPath()) || (c.expiresPath() != null && !path(c.expiresPath())))
|
||||
throw FileIngestionException.validation("动态Token配置无效");
|
||||
}
|
||||
checkMap(c.headers(), true);
|
||||
checkMap(c.queryParameters(), false);
|
||||
if (c.requestBody() != null && (c.requestBody().length() > 8192 ||
|
||||
(!"POST".equals(c.requestMethod()) && !c.requestBody().isBlank())))
|
||||
throw FileIngestionException.validation("请求体配置无效");
|
||||
if (c.successPath() != null && (!path(c.successPath()) || c.successValue() == null ||
|
||||
c.successValue().length() > 128)) throw FileIngestionException.validation("业务状态路径无效");
|
||||
if (!"NONE".equals(c.signatureKind())) {
|
||||
if (c.signatureTemplate() == null || c.signatureTemplate().isBlank() ||
|
||||
c.signatureTemplate().length() > 2048 || !c.signatureTemplate().matches("(?s)[A-Za-z0-9_{}$./?&=+%\\n\\r :|-]*") ||
|
||||
!Set.of("HEADER", "QUERY").contains(c.signaturePlacement()) ||
|
||||
!("HEADER".equals(c.signaturePlacement()) ? HEADER : FIELD)
|
||||
.matcher(c.signatureHeader() == null ? "" : c.signatureHeader()).matches() ||
|
||||
Set.of("authorization", "cookie", "host").contains(c.signatureHeader().toLowerCase()) ||
|
||||
!Set.of("BASE64", "HEX").contains(c.signatureEncoding()))
|
||||
throw FileIngestionException.validation("签名配置无效");
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkMap(Map<String, String> values, boolean headers) {
|
||||
if (values == null) return;
|
||||
if (values.size() > 20) throw FileIngestionException.validation("请求参数过多");
|
||||
for (var item : values.entrySet()) {
|
||||
String name = item.getKey(), value = item.getValue();
|
||||
if (name == null || value == null || value.length() > 1024 || value.contains("\r") || value.contains("\n") ||
|
||||
!(headers ? HEADER : FIELD).matcher(name).matches() ||
|
||||
(headers && Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key")
|
||||
.contains(name.toLowerCase())) ||
|
||||
(!headers && Set.of("token", "access_token", "secret", "password", "api_key").contains(name.toLowerCase())))
|
||||
throw FileIngestionException.validation("请求参数包含不允许的字段");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); }
|
||||
private void safeRevoke(String ref) { try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* retained safely */ } }
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** API-only polling ownership, leases and committed watermarks. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final IntegrationFileIngestionGateway integration;
|
||||
@Autowired(required = false)
|
||||
private ApiPollProfileService profiles;
|
||||
|
||||
public record PollState(long intakeId, boolean enabled, String watermark, LocalDateTime nextDueAt,
|
||||
String lastStatus, String lastErrorCode, int lastWrittenRows,
|
||||
LocalDateTime lastRunAt) { }
|
||||
public record PollRun(long runId, String triggerType, String status, int writtenRows,
|
||||
String errorCode, String watermarkBefore, String watermarkAfter,
|
||||
LocalDateTime startedAt, LocalDateTime completedAt) { }
|
||||
|
||||
public PollState state(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
List<PollState> rows = jdbc.query("""
|
||||
SELECT intake_id,enabled,watermark,next_due_at,last_status,last_error_code,
|
||||
last_written_rows,last_run_at FROM ing_api_poll_state
|
||||
WHERE intake_id=? AND org_scope_id=?
|
||||
""", (rs, index) -> new PollState(rs.getLong(1), rs.getInt(2) == 1, rs.getString(3),
|
||||
time(rs.getTimestamp(4)), rs.getString(5), rs.getString(6), rs.getInt(7),
|
||||
time(rs.getTimestamp(8))), intakeId, actor.orgScopeId());
|
||||
return rows.isEmpty() ? new PollState(intakeId, false, null, null, "NEVER", null, 0, null) : rows.getFirst();
|
||||
}
|
||||
|
||||
public List<PollRun> runs(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
return jdbc.query("""
|
||||
SELECT run_id,trigger_type,run_status,written_rows,error_code,watermark_before,
|
||||
watermark_after,started_at,completed_at FROM ing_api_poll_run
|
||||
WHERE intake_id=? AND org_scope_id=? ORDER BY started_at DESC FETCH FIRST 50 ROWS ONLY
|
||||
""", (rs, index) -> new PollRun(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getInt(4),
|
||||
rs.getString(5), rs.getString(6), rs.getString(7), time(rs.getTimestamp(8)),
|
||||
time(rs.getTimestamp(9))), intakeId, actor.orgScopeId());
|
||||
}
|
||||
|
||||
public PollState setEnabled(long intakeId, boolean enabled) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (enabled && !supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled,next_due_at)
|
||||
SELECT ?,?,?,?,CURRENT_TIMESTAMP FROM DUAL WHERE NOT EXISTS
|
||||
(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), enabled ? 1 : 0, intakeId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET enabled=?, actor_id=?,
|
||||
next_due_at=CASE WHEN ?=1 THEN CURRENT_TIMESTAMP ELSE next_due_at END,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
""", enabled ? 1 : 0, actor.actorId(), enabled ? 1 : 0, intakeId, actor.orgScopeId());
|
||||
return state(intakeId);
|
||||
}
|
||||
|
||||
public PollRun runNow(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (!supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
ensureState(actor, intakeId);
|
||||
return execute(actor, intakeId, "MANUAL", config);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${datagov.api-poll.scan-delay-ms:15000}")
|
||||
public void scan() {
|
||||
List<long[]> due;
|
||||
try {
|
||||
due = jdbc.query("""
|
||||
SELECT intake_id,org_scope_id,actor_id FROM ing_api_poll_state
|
||||
WHERE enabled=1 AND next_due_at<=CURRENT_TIMESTAMP
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
ORDER BY next_due_at FETCH FIRST 10 ROWS ONLY
|
||||
""", (rs, index) -> new long[]{rs.getLong(1), rs.getLong(2), rs.getLong(3)});
|
||||
} catch (RuntimeException unavailable) { return; }
|
||||
for (long[] item : due) {
|
||||
try {
|
||||
FileIngestionActor actor = new FileIngestionActor(item[2], item[1]);
|
||||
FileIngestionPolicy.Config config = requireApi(actor, item[0]);
|
||||
if (supported(config)) execute(actor, item[0], "SCHEDULED", config);
|
||||
else disableInvalid(item[0], item[1]);
|
||||
} catch (RuntimeException failure) {
|
||||
try { disableInvalid(item[0], item[1]); } catch (RuntimeException unavailable) { /* retry on next scan */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PollRun execute(FileIngestionActor actor, long intakeId, String trigger,
|
||||
FileIngestionPolicy.Config config) {
|
||||
String lease = UUID.randomUUID().toString();
|
||||
int claimed = jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET lease_id=?, lease_until=DATEADD(HOUR, 2, CURRENT_TIMESTAMP),
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
""" + ("SCHEDULED".equals(trigger) ? " AND enabled=1" : ""), lease, intakeId, actor.orgScopeId());
|
||||
if (claimed != 1) throw FileIngestionException.conflict("该API采集任务正在运行");
|
||||
long runId = IdGeneratorUtil.nextLongId();
|
||||
String before = jdbc.queryForObject("SELECT watermark FROM ing_api_poll_state WHERE intake_id=?",
|
||||
String.class, intakeId);
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_run(run_id,intake_id,org_scope_id,actor_id,trigger_type,
|
||||
started_at,run_status,watermark_before)
|
||||
VALUES(?,?,?,?,?,CURRENT_TIMESTAMP,'RUNNING',?)
|
||||
""", runId, intakeId, actor.orgScopeId(), actor.actorId(), trigger, before);
|
||||
DataCollectionIntegrationService.ApiPollResult result;
|
||||
try {
|
||||
result = integration.pollApi(actor, intakeId, config, before,
|
||||
profiles == null ? null : profiles.profile(actor, intakeId));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
result = new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_GATEWAY_UNKNOWN");
|
||||
}
|
||||
boolean success = result != null && "SUCCEEDED".equals(result.status());
|
||||
String error = success ? null : result == null ? "API_POLL_RESPONSE_MISSING" :
|
||||
FileIngestionPolicy.safeErrorCode(result.errorCode(), "API_POLL_UNKNOWN");
|
||||
String after = success ? result.watermark() : before;
|
||||
int count = success ? Math.max(0, result.writtenRows()) : 0;
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_run SET completed_at=CURRENT_TIMESTAMP,run_status=?,written_rows=?,
|
||||
error_code=?,watermark_after=? WHERE run_id=?
|
||||
""", success ? "SUCCEEDED" : "UNKNOWN", count, error, after, runId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET watermark=?,last_status=?,last_error_code=?,
|
||||
last_written_rows=?,last_run_at=CURRENT_TIMESTAMP,
|
||||
next_due_at=DATEADD(SECOND, ?, CURRENT_TIMESTAMP),lease_id=NULL,lease_until=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? AND lease_id=?
|
||||
""", after, success ? "SUCCEEDED" : "UNKNOWN", error, count,
|
||||
config.periodSeconds(), intakeId, actor.orgScopeId(), lease);
|
||||
return new PollRun(runId, trigger, success ? "SUCCEEDED" : "UNKNOWN", count, error,
|
||||
before, after, null, null);
|
||||
}
|
||||
|
||||
private void ensureState(FileIngestionActor actor, long intakeId) {
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled)
|
||||
SELECT ?,?,?,0 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), intakeId);
|
||||
}
|
||||
|
||||
private FileIngestionPolicy.Config requireApi(FileIngestionActor actor, long intakeId) {
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅API来源可执行轮询");
|
||||
return config;
|
||||
}
|
||||
|
||||
private static boolean supported(FileIngestionPolicy.Config config) {
|
||||
return config.apiConnector() != null && "GENERIC_HTTPS_JSON".equals(config.apiConnector().name()) &&
|
||||
config.authMode() != null && "BEARER".equals(config.authMode().name()) &&
|
||||
config.paginationMode() != null &&
|
||||
config.maxPages() != null && config.maxPages() >= 1 && config.maxPages() <= 100 &&
|
||||
config.periodSeconds() != null && config.periodSeconds() >= 60 &&
|
||||
config.secretRef() != null;
|
||||
}
|
||||
|
||||
private void disableInvalid(long intakeId, long orgId) {
|
||||
jdbc.update("UPDATE ing_api_poll_state SET enabled=0,last_status='UNKNOWN',last_error_code='API_POLL_CONFIG_INVALID',updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?", intakeId, orgId);
|
||||
}
|
||||
|
||||
private static LocalDateTime time(Timestamp value) { return value == null ? null : value.toLocalDateTime(); }
|
||||
}
|
||||
+6
@@ -259,6 +259,9 @@ public class FileIngestionService {
|
||||
throw FileIngestionException.conflict("仅草稿或就绪配置可执行能力校验");
|
||||
}
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
String code = FileIngestionPolicy.deferredAdapterCode(config);
|
||||
String summary = FileIngestionPolicy.deferredAdapterSummary(config);
|
||||
@@ -309,6 +312,9 @@ public class FileIngestionService {
|
||||
FileIngestionActor actor = actorProvider.current();
|
||||
String key = FileIngestionPolicy.requireIdempotencyKey(idempotencyKey);
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
repository.markCapability(actor, intakeId, AggregateCapabilityStatus.UNSUPPORTED);
|
||||
throw FileIngestionException.external(FileIngestionPolicy.deferredAdapterSummary(config));
|
||||
|
||||
+15
-2
@@ -35,6 +35,19 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
public IntegrationFileIngestionGateway() {
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark) {
|
||||
return pollApi(actor, intakeId, config, watermark, null);
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark,
|
||||
DataCollectionIntegrationService.ApiPollProfile profile) {
|
||||
return integration.pollApi(new DataCollectionIntegrationService.ApiPollRequest(actor.actorId(),
|
||||
actor.orgScopeId(), intakeId, watermark, snapshot(config),
|
||||
targetProfile(actor.actorId(), actor.orgScopeId(), config), profile));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CapabilityResult checkCapability(CapabilityRequest request) {
|
||||
try {
|
||||
@@ -166,7 +179,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
"文件动作证据暂不可用");
|
||||
}
|
||||
|
||||
private DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
long actorId, long orgScopeId, FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (storageReferences == null || config == null || config.targetStorageResourceId() == null ||
|
||||
@@ -180,7 +193,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
resolved.serviceAccount(), resolved.secretRef(), resolved.tlsEnabled());
|
||||
}
|
||||
|
||||
private static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (config == null) return null;
|
||||
|
||||
+2
@@ -18,6 +18,8 @@ public class RealtimeController {
|
||||
public R<cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.SourcePage> sources(@RequestParam(required=false) String keyword){return R.ok(directory.realtimeSources(keyword));}
|
||||
@GetMapping("/relay-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<java.util.List<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.RelayOption>> relays(@RequestParam long sourceId){return R.ok(service.relays(sourceId));}
|
||||
@GetMapping("/source-defaults") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.SourceDefaults> sourceDefaults(@RequestParam long sourceId){return R.ok(service.sourceDefaults(sourceId));}
|
||||
@GetMapping @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.Page> list(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.list(pageNum,pageSize));}
|
||||
@GetMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
|
||||
+15
-9
@@ -46,6 +46,7 @@ public class RealtimeService {
|
||||
}
|
||||
public View get(long id) {return view(require(id,false),true);}
|
||||
public List<RelayOption> relays(long sourceId){return integration.relays(actor(),org(),sourceId);}
|
||||
public SourceDefaults sourceDefaults(long sourceId){return integration.sourceDefaults(actor(),org(),sourceId);}
|
||||
private Row require(long id,boolean lock) {
|
||||
var rows=db.query("SELECT * FROM ing_realtime_task WHERE id=? AND org_id=? AND owner_id=?"+(lock?" FOR UPDATE":""),
|
||||
(rs,n)->map(rs),id,org(),actor());
|
||||
@@ -95,7 +96,7 @@ public class RealtimeService {
|
||||
}
|
||||
public View action(long id,String action,Action request) {
|
||||
if(request==null)throw new ServiceException("请求不能为空");key(request.key());
|
||||
if(!Set.of("CHECK","START","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效");
|
||||
if(!Set.of("CHECK","START","RETRY","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效");
|
||||
Row prior=require(id,false);
|
||||
Row reserved=tx.execute(status->{
|
||||
Row r=require(id,true);
|
||||
@@ -108,9 +109,9 @@ public class RealtimeService {
|
||||
if(r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))throw new ServiceException("操作仍在处理中,请稍后刷新");
|
||||
allowed(r,action);
|
||||
// SeaTunnel 2.3.13 restores the same job ID; a new ID would start a new snapshot.
|
||||
long nextAttempt=r.attempt()+(action.equals("START")?1:0);
|
||||
long nextAttempt=r.attempt()+(Set.of("START","RETRY").contains(action)?1:0);
|
||||
String external=nextAttempt>0?RealtimeCollectionService.jobId(r.org(),r.id(),nextAttempt):null;
|
||||
String state=action.equals("START")||action.equals("RESUME")?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status();
|
||||
String state=Set.of("START","RETRY","RESUME").contains(action)?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status();
|
||||
db.update("UPDATE ing_realtime_task SET status=?,version=version+1,attempt=?,external_id=?,busy_until=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",state,nextAttempt,external,LocalDateTime.now().plusMinutes(3),id);
|
||||
db.update("INSERT INTO ing_realtime_event(id,task_id,request_key,action,status,created_at) VALUES(?,?,?,?, 'PENDING',CURRENT_TIMESTAMP)",IdGeneratorUtil.nextId(),id,request.key(),action);
|
||||
return require(id,false);
|
||||
@@ -133,10 +134,10 @@ public class RealtimeService {
|
||||
}
|
||||
else {
|
||||
var command=new Command(r.owner(),r.org(),r.id(),r.attempt(),r.spec(),
|
||||
Set.of("CHECK","START","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(),
|
||||
action.equals("RESUME")?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null);
|
||||
Set.of("CHECK","START","RETRY","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(),
|
||||
Set.of("RESUME","RETRY").contains(action)?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null);
|
||||
if(action.equals("CHECK")) {
|
||||
var c=integration.check(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint();
|
||||
var c=integration.prepare(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint();
|
||||
} else {
|
||||
invoked=true;
|
||||
var result=integration.execute(command,action.equals("DELETE")?"REFRESH":action,r.external(),action.equals("RESUME")?
|
||||
@@ -144,6 +145,10 @@ public class RealtimeService {
|
||||
if(result==null || !Objects.equals(r.external(),result.externalId()))throw new IllegalStateException("CDC_RESULT_IDENTITY_MISMATCH");
|
||||
result=retainConfirmedTerminal(action,prior,result);
|
||||
state=result.status();summary=result.summary();checkpoint=result.checkpointId();read=result.readRows();written=result.writeRows();
|
||||
if("UNKNOWN".equals(state) && checkpoint==null && prior.checkpoint()!=null) {
|
||||
checkpoint=prior.checkpoint();read=prior.readRows();written=prior.writeRows();
|
||||
summary=(summary==null?"外部结果待确认":summary)+";保留上次已确认检查点,恢复时仍须验证原作业已结束和检查点有效";
|
||||
}
|
||||
if(action.equals("DELETE")) {
|
||||
if(terminal(state)) {state="ARCHIVED";summary="任务已删除,历史操作记录保留";}
|
||||
else summary="未删除:外部作业尚未确认结束,请同步状态后重试";
|
||||
@@ -154,8 +159,8 @@ public class RealtimeService {
|
||||
}
|
||||
}
|
||||
} catch(RuntimeException ex) {
|
||||
if(action.equals("CHECK")) {state="DRAFT";summary="校验未完成,请检查来源、目标授权和集成服务";}
|
||||
else if(!invoked && Set.of("START","RESUME").contains(action)) {
|
||||
if(action.equals("CHECK")) {state="DRAFT";fingerprint=null;summary="检查并准备未完成,请检查来源、目标授权和集成服务;如已建表会保留,请重新检查确认";}
|
||||
else if(!invoked && Set.of("START","RETRY","RESUME").contains(action)) {
|
||||
state=prior.status();attempt=prior.attempt();external=prior.external();checkpoint=prior.checkpoint();
|
||||
summary="来源或目标授权检查未通过,未提交外部作业";
|
||||
}
|
||||
@@ -188,7 +193,8 @@ public class RealtimeService {
|
||||
case "CHECK","ARCHIVE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status());
|
||||
case "DELETE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status()) || terminal(r.status());
|
||||
case "START" -> r.attempt()==0 && "READY".equals(r.status()) && r.fingerprint()!=null;
|
||||
case "RESUME" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null;
|
||||
case "RETRY" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()==null && r.fingerprint()!=null;
|
||||
case "RESUME" -> r.attempt()>0 && (Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null || "UNKNOWN".equals(r.status()));
|
||||
case "STOP","REFRESH" -> r.attempt()>0;
|
||||
case "RECREATE" -> r.attempt()>0 && "UNKNOWN".equals(r.status()) && r.checkpoint()==null;
|
||||
default -> false;
|
||||
|
||||
+32
-9
@@ -30,7 +30,9 @@ import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Repository
|
||||
@@ -460,7 +462,17 @@ public class StorageResourceRepository {
|
||||
"SELECT " + CAPACITY_COLUMNS + " FROM store_capacity_snapshot " +
|
||||
"WHERE resource_id=? AND del_flag='0' ORDER BY snapshot_id DESC LIMIT ?",
|
||||
(resultSet, rowNumber) -> mapCapacity(resultSet), resourceId, limit);
|
||||
return snapshots.stream().map(this::withDimensions).toList();
|
||||
if (snapshots.isEmpty()) return snapshots;
|
||||
String placeholders = String.join(",", java.util.Collections.nCopies(snapshots.size(), "?"));
|
||||
Map<Long, List<StorageCapacityDimensionView>> dimensions = new HashMap<>();
|
||||
jdbcTemplate.query("SELECT snapshot_id, " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id IN (" + placeholders +
|
||||
") AND del_flag='0' ORDER BY snapshot_id, dimension_name", rs -> {
|
||||
dimensions.computeIfAbsent(rs.getLong("snapshot_id"), ignored -> new ArrayList<>())
|
||||
.add(mapDimension(rs));
|
||||
}, snapshots.stream().map(StorageCapacitySnapshotView::snapshotId).toArray());
|
||||
return snapshots.stream().map(snapshot -> attachDimensions(snapshot,
|
||||
dimensions.getOrDefault(snapshot.snapshotId(), List.of()))).toList();
|
||||
}
|
||||
|
||||
void lockCapacityWindow(long resourceId) {
|
||||
@@ -863,14 +875,21 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "previous_snapshot_id"), resultSet.getString("contract_version"), List.of());
|
||||
}
|
||||
|
||||
private static final String DIMENSION_COLUMNS = """
|
||||
dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
""";
|
||||
|
||||
private StorageCapacitySnapshotView withDimensions(StorageCapacitySnapshotView snapshot) {
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("""
|
||||
SELECT dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
FROM store_capacity_dimension
|
||||
WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name
|
||||
""", (resultSet, rowNumber) -> new StorageCapacityDimensionView(
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("SELECT " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name",
|
||||
(resultSet, rowNumber) -> mapDimension(resultSet), snapshot.snapshotId());
|
||||
return attachDimensions(snapshot, dimensions);
|
||||
}
|
||||
|
||||
private static StorageCapacityDimensionView mapDimension(ResultSet resultSet) throws SQLException {
|
||||
return new StorageCapacityDimensionView(
|
||||
StorageTelemetryDimensionType.valueOf(resultSet.getString("dimension_name")),
|
||||
StorageTelemetryMetricState.valueOf(resultSet.getString("metric_status")),
|
||||
resultSet.getString("source_type"), resultSet.getString("source_identity"),
|
||||
@@ -881,7 +900,11 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "total_bytes"), nullableLong(resultSet, "used_bytes"),
|
||||
nullableLong(resultSet, "available_bytes"), nullableLong(resultSet, "value_bytes"),
|
||||
resultSet.getBigDecimal("value_percent"), resultSet.getString("comparison_fingerprint"),
|
||||
resultSet.getString("algorithm_version")), snapshot.snapshotId());
|
||||
resultSet.getString("algorithm_version"));
|
||||
}
|
||||
|
||||
private static StorageCapacitySnapshotView attachDimensions(StorageCapacitySnapshotView snapshot,
|
||||
List<StorageCapacityDimensionView> dimensions) {
|
||||
if (dimensions.isEmpty()) {
|
||||
dimensions = legacyDimensions(snapshot);
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises profile persistence and secret-reference handling against the dedicated DM test schema. */
|
||||
@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST")
|
||||
class ApiPollProfileJdbcTest {
|
||||
@Test void savesRedactedProfileAndRevokesReplacedSigningKey() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
ds.setDriverClassName("dm.jdbc.driver.DmDriver");
|
||||
ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"));
|
||||
ds.setUsername(System.getenv("DATAGOV_DM_USERNAME"));
|
||||
ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA"));
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var credentials = mock(FileManagedCredentialGateway.class);
|
||||
var actor = new FileIngestionActor(900009L, 900009L);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, -900009L)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(credentials.provision(any(char[].class))).thenReturn("file:///managed/api-sign?version=v1");
|
||||
char[] signingKey = "test-signing-material".toCharArray();
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollProfileService(jdbc, JsonMapper.builder().findAndAddModules().build(),
|
||||
actors, repository, credentials);
|
||||
var first = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of("X-Tenant", "example"), Map.of("status", "paid"), "{\"page\":${page}}",
|
||||
50, 60, "$.success", "true", "HMAC_SHA256", "${method}\n${pathQuery}\n${timestamp}\n${nonce}",
|
||||
"HEADER", "X-Sign", "BASE64", signingKey);
|
||||
assertThat(service.save(-900009L, first).signingKeyConfigured()).isTrue();
|
||||
assertThat(signingKey).containsOnly('\0');
|
||||
String stored = jdbc.queryForObject("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=?",
|
||||
String.class, -900009L);
|
||||
assertThat(stored).contains("file:///managed/api-sign?version=v1").doesNotContain("test-signing-material");
|
||||
assertThat(service.view(-900009L).requestMethod()).isEqualTo("POST");
|
||||
var second = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of(), Map.of(), null, 50, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", null);
|
||||
assertThat(service.save(-900009L, second).signingKeyConfigured()).isFalse();
|
||||
verify(credentials).revoke("file:///managed/api-sign?version=v1");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.*;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises the production polling SQL against disposable rows in the dedicated DM test schema. */
|
||||
@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST")
|
||||
class ApiPollServiceJdbcTest {
|
||||
@BeforeAll static void identifiers() {
|
||||
var beans = new DefaultListableBeanFactory();
|
||||
beans.registerSingleton("identifierGenerator", com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance());
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(beans);
|
||||
}
|
||||
|
||||
@Test void successfulRunCommitsWatermarkAndUnknownKeepsIt() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
ds.setDriverClassName("dm.jdbc.driver.DmDriver");
|
||||
ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"));
|
||||
ds.setUsername(System.getenv("DATAGOV_DM_USERNAME"));
|
||||
ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA"));
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var integration = mock(IntegrationFileIngestionGateway.class);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
var actor = new FileIngestionActor(900008L, 900008L);
|
||||
long intakeId = -900008L;
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, intakeId)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(config.apiConnector()).thenReturn(FileApiConnector.GENERIC_HTTPS_JSON);
|
||||
when(config.authMode()).thenReturn(FileAuthMode.BEARER);
|
||||
when(config.paginationMode()).thenReturn(FilePaginationMode.PAGE_SIZE);
|
||||
when(config.maxPages()).thenReturn(2);
|
||||
when(config.periodSeconds()).thenReturn(60);
|
||||
when(config.secretRef()).thenReturn("file:///managed/data-source/test?version=v1");
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), isNull(), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", 2, "2026-11-26T00:00:00Z", null));
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), eq("2026-11-26T00:00:00Z"), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_HTTP_503"));
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollService(jdbc, actors, repository, integration);
|
||||
assertThat(service.state(intakeId).lastStatus()).isEqualTo("NEVER");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("SUCCEEDED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("UNKNOWN");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.runs(intakeId)).hasSize(2);
|
||||
assertThat(service.setEnabled(intakeId, true).enabled()).isTrue();
|
||||
service.scan();
|
||||
assertThat(service.runs(intakeId)).hasSize(3);
|
||||
assertThat(service.runs(intakeId).getFirst().triggerType()).isEqualTo("SCHEDULED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.setEnabled(intakeId, false).enabled()).isFalse();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -44,7 +44,7 @@ class RealtimeJdbcTest {
|
||||
String createKey=UUID.randomUUID().toString();var created=service.create(spec,createKey);
|
||||
assertThat(service.create(spec,createKey).id()).isEqualTo(created.id());
|
||||
long id=Long.parseLong(created.id());
|
||||
when(provider.check(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id")));
|
||||
when(provider.prepare(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id")));
|
||||
var ready=service.action(id,"CHECK",action(created));assertThat(ready.status()).isEqualTo("READY");
|
||||
var startKey=UUID.randomUUID().toString();
|
||||
when(provider.execute(any(),eq("START"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"unknown",null,null,null));
|
||||
|
||||
+11
-2
@@ -3,6 +3,14 @@ import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
class RealtimePolicyTest {
|
||||
@Test void retryRequiresConfirmedTerminalWithoutCheckpoint(){
|
||||
for(String state:java.util.List.of("FAILED","CANCELED"))
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,1,null),"RETRY")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("UNKNOWN","RUNNING","SUBMITTING","STOPPING","READY","SUCCEEDED","ARCHIVED"))
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",1,"1041"),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",0,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void recreateOnlyUnknownWithoutCheckpoint() {
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RECREATE")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("RUNNING","SUBMITTING","STOPPING","DRAFT","ARCHIVED"))
|
||||
@@ -34,9 +42,10 @@ class RealtimePolicyTest {
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("ARCHIVED",1,null),"REFRESH")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
static RealtimeService.Row row(String status,long attempt,String checkpoint){return new RealtimeService.Row(1,2,3,null,status,0,attempt,null,"a".repeat(64),checkpoint,null,null,null,null,null);}
|
||||
@Test void cannotStartAgainOrResumeUnknownJob(){
|
||||
@Test void unknownJobCanOnlyBeRecoveredThroughGuardedSavepointPath(){
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"START")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("RUNNING",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void resumeRequiresTerminalAndCheckpoint(){
|
||||
|
||||
在新工单中引用
屏蔽一个用户