cover_url、urdf_main_object_key、urdf_prefix只存相对路径,不包含域名+环境根目录

This commit is contained in:
lxp
2026-10-19 14:53:06 +08:00
parent 8a3ecabdc0
commit f8f2e95dbe
34 changed files with 1700 additions and 58 deletions
@@ -2,6 +2,8 @@ package com.linkerbot.community.importer;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.config.MybatisConfiguration;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.oss.OssResourcePaths;
import com.linkerbot.community.service.gitea.RestGiteaClient;
import com.linkerbot.community.service.impl.ProjectServiceImpl;
import com.linkerbot.community.service.impl.UserServiceImpl;
@@ -12,7 +14,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/** 显式加载所需组件,避免扫描在线应用的安全、AI 和 OSS 模块。 */
/** 仅加载资源路径配置,不初始化在线安全、AI 或 OSS 客户端。 */
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@MapperScan("com.linkerbot.community.service.mapper")
@@ -22,6 +24,8 @@ import org.springframework.context.annotation.Import;
RestGiteaClient.class,
ProjectServiceImpl.class,
UserServiceImpl.class,
ProjectLocks.class
ProjectLocks.class,
OssProperties.class,
OssResourcePaths.class
})
public class DatabaseConfiguration {}
@@ -8,6 +8,7 @@ import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.common.ProjectCodes;
import com.linkerbot.community.service.ProjectService;
import com.linkerbot.community.service.oss.OssResourcePaths;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.gitea.*;
import com.linkerbot.community.service.mapper.ProjectMapper;
@@ -90,6 +91,12 @@ public final class ImportApplication {
}
public static void main(String[] args) {
if (args.length > 0 && "covers".equals(args[0])) {
int status = com.linkerbot.community.importer.cover.CoverMigrationApplication.runCli(
Arrays.copyOfRange(args, 1, args.length));
if (status != 0) System.exit(status);
return;
}
if (args.length == 0 || Arrays.asList(args).contains("--help")) {
System.out.println(
"用法:--excel <文件> [--state-dir <目录>] [--dry-run | --execute (--owner-user-code"
@@ -224,6 +231,7 @@ public final class ImportApplication {
context.getBean(ProjectService.class),
context.getBean(GiteaClient.class),
context.getBean(CommunityProperties.class),
context.getBean(OssResourcePaths.class),
store,
owner,
options.migrationTimeout());
@@ -8,6 +8,7 @@ import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.service.ProjectService;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.oss.OssResourcePaths;
import com.linkerbot.community.service.gitea.*;
import com.linkerbot.community.service.gitea.GiteaClient.RemoteRepository;
import com.linkerbot.community.service.mapper.ProjectMapper;
@@ -27,6 +28,7 @@ public final class ImportCoordinator {
private final ProjectService service;
private final GiteaClient gitea;
private final CommunityProperties config;
private final OssResourcePaths resourcePaths;
private final StateStore store;
private final User owner;
private final Duration timeout;
@@ -46,6 +48,7 @@ public final class ImportCoordinator {
ProjectService service,
GiteaClient gitea,
CommunityProperties config,
OssResourcePaths resourcePaths,
StateStore store,
User owner,
Duration timeout) {
@@ -53,6 +56,7 @@ public final class ImportCoordinator {
this.service = service;
this.gitea = gitea;
this.config = config;
this.resourcePaths = resourcePaths;
this.store = store;
this.owner = owner;
this.timeout = timeout;
@@ -97,7 +101,7 @@ public final class ImportCoordinator {
project.setOwnerUserId(owner.getId());
project.setName(entry.candidate.name().trim());
project.setDescription(entry.candidate.description());
project.setCoverUrl(ProjectInputs.coverUrl(entry.candidate.coverUrl()));
project.setCoverUrl(resourcePaths.coverStorage(entry.candidate.coverUrl()));
project.setProjectType(entry.candidate.projectType());
project.setGiteaOwner(config.getGitea().getOwner());
project.setGiteaRepoName(repoName);
@@ -0,0 +1,172 @@
package com.linkerbot.community.importer.cover;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.oss.OssResourcePaths;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Instant;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.UUID;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
public final class CoverMigrationApplication {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({OssProperties.class, OssResourcePaths.class})
public static class Config {}
public record Options(boolean execute, int limit, int concurrency, int maxBytes, Path reportDirectory, Path sourceOverrides) {
public static Options parse(String[] args) {
boolean execute = false;
boolean dryRun = false;
int limit = Integer.MAX_VALUE;
int concurrency = 2;
int maxBytes = 5 * 1024 * 1024;
Path directory = Path.of("logs/cover-migration");
Path overrides = null;
List<String> seen = new ArrayList<>();
for (int index = 0; index < args.length; index++) {
String key = args[index];
if (seen.contains(key)) throw new IllegalArgumentException("参数重复");
seen.add(key);
if ("--execute".equals(key)) execute = true;
else if ("--dry-run".equals(key)) dryRun = true;
else {
if (index + 1 == args.length) throw new IllegalArgumentException("缺少参数值");
String value = args[++index];
switch (key) {
case "--limit" -> limit = Integer.parseInt(value);
case "--concurrency" -> concurrency = Integer.parseInt(value);
case "--max-bytes" -> maxBytes = Integer.parseInt(value);
case "--report-dir" -> directory = Path.of(value);
case "--source-overrides" -> overrides = Path.of(value);
default -> throw new IllegalArgumentException("不支持的参数");
}
}
}
if (execute && dryRun || limit < 1 || concurrency < 1 || concurrency > 4 || maxBytes < 1 || maxBytes > 50 * 1024 * 1024)
throw new IllegalArgumentException("参数范围不合法");
return new Options(execute, limit, concurrency, maxBytes, directory, overrides);
}
}
public static int runCli(String[] args) {
if (Arrays.asList(args).contains("--help")) {
System.out.println("用法:covers [--dry-run | --execute] [--limit N] [--concurrency 2]"
+ " [--max-bytes 5242880] [--report-dir logs/cover-migration] [--source-overrides <JSON文件>]");
return 0;
}
try {
Options options = Options.parse(args);
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE).logStartupInfo(false).run()) {
return run(options, context.getBean(JdbcTemplate.class), context.getBean(OssProperties.class),
context.getBean(OssResourcePaths.class));
}
} catch (Exception error) {
String code = error instanceof ExternalCoverDownloader.Failure failure ? failure.code() : error.getClass().getSimpleName();
System.err.println("封面迁移终止 code=" + code + ";检查本地配置和运行报告,不输出凭据或原始异常文本");
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof SQLException sql)
System.err.printf("数据库异常 sqlState=%s vendorCode=%d type=%s%n", sql.getSQLState(), sql.getErrorCode(), sql.getClass().getSimpleName());
}
return 1;
}
}
static int run(Options options, JdbcTemplate jdbc, OssProperties oss, OssResourcePaths paths) throws Exception {
CoverMigrator.Repository repository = new CoverMigrator.JdbcRepository(jdbc);
ExternalCoverDownloader downloader = new ExternalCoverDownloader(options.maxBytes());
CoverMigrator scanner = new CoverMigrator(repository, paths, downloader::download, (key, image, sha) -> {});
List<CoverMigrator.Candidate> candidates = scanner.candidates(options.limit());
long unique = candidates.stream().map(candidate -> candidate.originalUrl().trim()).distinct().count();
System.out.printf("封面迁移预览 environmentRoot=%s candidateProjects=%d uniqueUrls=%d execute=%s%n",
oss.getRootDirectory(), candidates.size(), unique, options.execute());
Path run = options.reportDirectory().resolve(Instant.now().toString().replace(':', '-') + "-" + UUID.randomUUID().toString().substring(0, 8));
Files.createDirectories(run);
restrict(run, "rwx------");
ObjectMapper json = new ObjectMapper();
Map<String, String> overrides = options.sourceOverrides() == null ? Map.of()
: json.readValue(Files.readString(options.sourceOverrides()), new TypeReference<Map<String, String>>() {});
Map<String, String> sources = downloadSources(candidates, overrides);
List<Map<String, String>> preview = candidates.stream().map(candidate -> Map.of(
"projectCode", candidate.projectCode(), "sourceHost", String.valueOf(CoverMigrator.host(candidate.originalUrl())))).toList();
writeReport(json, run.resolve("preview.json"), preview);
System.out.println("迁移报告目录=" + run.toAbsolutePath());
if (!options.execute() || candidates.isEmpty()) return 0;
if (!sources.isEmpty()) writeReport(json, run.resolve("source-overrides-backup.json"), overrides);
try (CoverOssUploader uploader = new CoverOssUploader(oss);
DurableBackup backup = new DurableBackup(run.resolve("backup.jsonl"), json)) {
CoverMigrator migrator = new CoverMigrator(repository, paths,
url -> downloader.download(sources.getOrDefault(url, url)), uploader);
List<CoverMigrator.Result> results = migrator.migrate(candidates, options.concurrency(), backup::record);
writeReport(json, run.resolve("report.json"), results);
long updated = results.stream().filter(result -> "UPDATED".equals(result.status())).count();
long failed = results.stream().filter(result -> "FAILED".equals(result.status())).count();
long changed = results.size() - updated - failed;
System.out.printf("封面迁移结束 updated=%d failed=%d changedSkipped=%d%n", updated, failed, changed);
return failed == 0 ? 0 : 2;
}
}
static Map<String, String> downloadSources(List<CoverMigrator.Candidate> candidates, Map<String, String> overrides) {
Map<String, String> sources = new LinkedHashMap<>();
for (CoverMigrator.Candidate candidate : candidates) {
String source = overrides.get(candidate.projectCode());
if (source == null) continue;
source = com.linkerbot.community.service.support.ProjectInputs.coverUrl(source);
if (source == null) throw new IllegalArgumentException("备用下载地址不能为空");
String previous = sources.putIfAbsent(candidate.originalUrl().trim(), source);
if (previous != null && !previous.equals(source))
throw new IllegalArgumentException("相同原始封面不能配置不同下载源");
}
return Map.copyOf(sources);
}
private static void writeReport(ObjectMapper json, Path path, Object value) throws Exception {
Files.write(path, json.writerWithDefaultPrettyPrinter().writeValueAsBytes(value), StandardOpenOption.CREATE_NEW);
restrict(path, "rw-------");
}
static void restrict(Path path, String mode) throws Exception {
if (Files.getFileStore(path).supportsFileAttributeView("posix"))
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode));
}
static final class DurableBackup implements AutoCloseable {
private final FileChannel channel;
private final ObjectMapper json;
DurableBackup(Path path, ObjectMapper json) throws Exception {
this.json = json;
channel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
restrict(path, "rw-------");
}
synchronized void record(CoverMigrator.Candidate candidate, String path) throws Exception {
// 原始地址仅保存于受限备份,不进入普通日志;先持久化再修改数据库。
byte[] bytes = (json.writeValueAsString(Map.of("projectCode", candidate.projectCode(),
"originalCoverUrl", candidate.originalUrl(), "newCoverPath", path)) + "\n").getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
@Override public void close() throws Exception { channel.close(); }
}
}
@@ -0,0 +1,137 @@
package com.linkerbot.community.importer.cover;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.service.oss.OssResourcePaths;
import java.net.URI;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class CoverMigrator {
public record Candidate(String projectCode, String originalUrl) {}
public record Result(String projectCode, String sourceHost, String status, String code, String coverPath) {}
public interface Repository {
List<Candidate> list();
boolean replace(Candidate candidate, String coverPath);
}
@FunctionalInterface public interface Downloader { ExternalCoverDownloader.Image download(String url) throws Exception; }
@FunctionalInterface public interface Uploader { void upload(String key, ExternalCoverDownloader.Image image, String sha256) throws Exception; }
@FunctionalInterface public interface Backup { void record(Candidate candidate, String path) throws Exception; }
public static class JdbcRepository implements Repository {
private final JdbcTemplate jdbc;
public JdbcRepository(JdbcTemplate jdbc) { this.jdbc = jdbc; }
@Override public List<Candidate> list() {
return jdbc.query("SELECT project_code, cover_url FROM project WHERE cover_url IS NOT NULL"
+ " AND cover_url <> '' ORDER BY project_code",
(row, index) -> new Candidate(row.getString("project_code"), row.getString("cover_url")));
}
@Override public boolean replace(Candidate candidate, String path) {
// HEX 比较原始 UTF-8 字节,避免默认不区分大小写的排序规则覆盖并发修改。
return jdbc.update("UPDATE project SET cover_url = ? WHERE project_code = ? AND HEX(cover_url) = HEX(?)",
path, candidate.projectCode(), candidate.originalUrl()) == 1;
}
}
private static final Logger log = LoggerFactory.getLogger(CoverMigrator.class);
private final Repository repository;
private final OssResourcePaths paths;
private final Downloader downloader;
private final Uploader uploader;
public CoverMigrator(Repository repository, OssResourcePaths paths, Downloader downloader, Uploader uploader) {
this.repository = repository;
this.paths = paths;
this.downloader = downloader;
this.uploader = uploader;
}
public List<Candidate> candidates(int limit) {
List<Candidate> candidates = new ArrayList<>();
for (Candidate candidate : repository.list()) {
String value = candidate.originalUrl();
if (value == null || value.isBlank() || value.startsWith("/")) continue;
try {
String normalized = paths.coverStorage(value);
if (normalized != null && normalized.startsWith("/project-covers/")) continue;
} catch (BusinessException | IllegalArgumentException error) {
// 非法历史外链进入失败报告,不因单条坏数据终止整个批次。
}
candidates.add(candidate);
if (candidates.size() == limit) break;
}
return List.copyOf(candidates);
}
public List<Result> migrate(List<Candidate> candidates, int concurrency, Backup backup) throws Exception {
Map<String, List<Candidate>> groups = new LinkedHashMap<>();
for (Candidate candidate : candidates)
groups.computeIfAbsent(candidate.originalUrl().trim(), ignored -> new ArrayList<>()).add(candidate);
List<Result> results = Collections.synchronizedList(new ArrayList<>());
try (ExecutorService executor = Executors.newFixedThreadPool(concurrency)) {
List<Future<?>> jobs = new ArrayList<>();
for (Map.Entry<String, List<Candidate>> group : groups.entrySet())
jobs.add(executor.submit(() -> migrateGroup(group.getKey(), group.getValue(), backup, results)));
for (Future<?> job : jobs) job.get();
}
results.sort(Comparator.comparing(Result::projectCode));
return List.copyOf(results);
}
private void migrateGroup(String url, List<Candidate> group, Backup backup, List<Result> results) {
String phase = "DOWNLOAD";
String path;
try {
ExternalCoverDownloader.Image image = downloader.download(url);
String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(image.bytes()));
path = "/project-covers/migrated/" + digest + "." + image.extension();
phase = "UPLOAD";
uploader.upload(paths.objectKey(path), image, digest);
} catch (Exception error) {
for (Candidate candidate : group) failed(candidate, phase, error, results);
return;
}
for (Candidate candidate : group) {
phase = "BACKUP";
try {
backup.record(candidate, path);
phase = "UPDATE";
boolean updated = repository.replace(candidate, path);
String status = updated ? "UPDATED" : "CHANGED";
results.add(new Result(candidate.projectCode(), host(url), status, "", path));
log.info("封面转存完成 projectCode={} status={} coverPath={}", candidate.projectCode(), status, path);
} catch (Exception error) {
failed(candidate, phase, error, results);
}
}
}
private void failed(Candidate candidate, String phase, Exception error, List<Result> results) {
String code = error instanceof ExternalCoverDownloader.Failure failure ? failure.code()
: error instanceof BusinessException business ? business.code() : error.getClass().getSimpleName();
if (error.getCause() != null) code += "/" + error.getCause().getClass().getSimpleName();
results.add(new Result(candidate.projectCode(), host(candidate.originalUrl()), "FAILED", phase + ":" + code, null));
// 异常文本可能包含带参数的原始 URL,不打印原始异常及查询参数。
log.warn("封面转存失败 projectCode={} sourceHost={} phase={} code={}",
candidate.projectCode(), host(candidate.originalUrl()), phase, code);
}
public static String host(String url) {
try {
String host = URI.create(url.trim()).getHost();
return host == null ? "invalid" : host;
}
catch (IllegalArgumentException error) { return "invalid"; }
}
}
@@ -0,0 +1,72 @@
package com.linkerbot.community.importer.cover;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.linkerbot.community.service.config.OssProperties;
import java.io.ByteArrayInputStream;
import java.util.Map;
final class CoverOssUploader implements AutoCloseable, CoverMigrator.Uploader {
private final OSS client;
private final String bucket;
CoverOssUploader(OssProperties properties) {
properties.setEnabled(true);
if (!properties.isConfigurationValid()) throw new ExternalCoverDownloader.Failure("OSS_CONFIGURATION_MISSING");
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
configuration.setConnectionTimeout(10000);
configuration.setSocketTimeout(20000);
configuration.setRequestTimeoutEnabled(true);
configuration.setRequestTimeout(30000);
configuration.setMaxErrorRetry(1);
client = OSSClientBuilder.create().endpoint(properties.resolvedEndpoint()).region(properties.getRegion())
.credentialsProvider(new DefaultCredentialProvider(properties.getAccessKeyId(), properties.getAccessKeySecret()))
.clientConfiguration(configuration).build();
bucket = properties.getBucket();
}
@Override
public void upload(String key, ExternalCoverDownloader.Image image, String sha256) {
ObjectMetadata existing = metadata(key);
if (existing != null) {
verify(existing, image, sha256);
return;
}
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(image.bytes().length);
metadata.setContentType(image.contentType());
metadata.setUserMetadata(Map.of("sha256", sha256));
metadata.setHeader("x-oss-forbid-overwrite", "true");
try {
client.putObject(new PutObjectRequest(bucket, key, new ByteArrayInputStream(image.bytes()), metadata));
} catch (OSSException error) {
if (!"FileAlreadyExists".equals(error.getErrorCode()))
throw new ExternalCoverDownloader.Failure("OSS_PUT_" + error.getErrorCode());
}
ObjectMetadata uploaded = metadata(key);
if (uploaded == null) throw new ExternalCoverDownloader.Failure("OSS_VERIFY_MISSING");
verify(uploaded, image, sha256);
}
private ObjectMetadata metadata(String key) {
try { return client.getObjectMetadata(bucket, key); }
catch (OSSException error) {
if ("NoSuchKey".equals(error.getErrorCode())) return null;
throw new ExternalCoverDownloader.Failure("OSS_HEAD_" + error.getErrorCode());
}
}
private void verify(ObjectMetadata metadata, ExternalCoverDownloader.Image image, String sha256) {
if (metadata.getContentLength() != image.bytes().length || !sha256.equals(metadata.getUserMetadata().get("sha256")))
throw new ExternalCoverDownloader.Failure("OSS_VERIFY_MISMATCH");
}
@Override public void close() { client.shutdown(); }
}
@@ -0,0 +1,132 @@
package com.linkerbot.community.importer.cover;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;
/** 仅下载公开 HTTPS 图片,不附加任何 GitHub、Gitea 或 OSS 凭据。 */
public class ExternalCoverDownloader {
public record Image(byte[] bytes, String contentType, String extension) {}
public static class Failure extends RuntimeException {
private final String code;
public Failure(String code) {
super(code);
this.code = code;
}
public String code() { return code; }
}
private final int maxBytes;
public ExternalCoverDownloader(int maxBytes) { this.maxBytes = maxBytes; }
public Image download(String url) throws Exception {
for (int attempt = 1; attempt <= 3; attempt++) {
try { return fetch(url); }
catch (IOException error) {
if (attempt == 3 || !retryable(error) || Thread.currentThread().isInterrupted()) throw error;
Thread.sleep(200L * attempt);
}
}
throw new IllegalStateException("封面下载未完成");
}
private boolean retryable(IOException error) {
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof java.security.cert.CertificateException
|| cause instanceof java.security.cert.CertPathValidatorException
|| cause instanceof java.security.cert.CertPathBuilderException) return false;
}
return true;
}
Image fetch(String url) throws Exception {
URI uri = URI.create(url.trim());
long deadline = System.nanoTime() + Duration.ofSeconds(45).toNanos();
for (int redirects = 0; redirects <= 5; redirects++) {
validate(uri);
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(15000);
connection.setRequestProperty("User-Agent", "community-cover-migration/1");
connection.setRequestProperty("Accept", "image/*");
try {
int status = connection.getResponseCode();
if (status >= 300 && status < 400) {
String location = connection.getHeaderField("Location");
if (location == null) throw new Failure("COVER_REDIRECT_INVALID");
uri = uri.resolve(location);
if (System.nanoTime() > deadline) throw new Failure("COVER_DOWNLOAD_TIMEOUT");
continue;
}
if (status != 200) throw new Failure("COVER_HTTP_" + status);
long length = connection.getContentLengthLong();
if (length > maxBytes) throw new Failure("COVER_TOO_LARGE");
byte[] bytes;
try (InputStream input = connection.getInputStream()) {
bytes = read(input, maxBytes, deadline);
}
if (length >= 0 && length != bytes.length) throw new Failure("COVER_INCOMPLETE");
return image(bytes);
} finally {
connection.disconnect();
}
}
throw new Failure("COVER_REDIRECT_LIMIT");
}
static void validate(URI uri) throws Exception {
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null
|| uri.getRawUserInfo() != null
|| (uri.getPort() != -1 && uri.getPort() != 443))
throw new Failure("COVER_URL_INVALID");
for (InetAddress address : InetAddress.getAllByName(uri.getHost())) {
byte[] bytes = address.getAddress();
boolean reservedIpv4 = bytes.length == 4 && ((bytes[0] & 255) == 0
|| (bytes[0] & 255) >= 224
|| (bytes[0] & 255) == 100 && ((bytes[1] & 255) & 192) == 64
|| (bytes[0] & 255) == 198 && ((bytes[1] & 255) == 18 || (bytes[1] & 255) == 19));
boolean privateIpv6 = bytes.length == 16 && (bytes[0] & 254) == 252;
if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress()
|| address.isSiteLocalAddress() || address.isMulticastAddress() || reservedIpv4 || privateIpv6)
throw new Failure("COVER_PRIVATE_ADDRESS");
}
}
static byte[] read(InputStream input, int maxBytes, long deadline) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int count;
while ((count = input.read(buffer)) != -1) {
if (System.nanoTime() > deadline || Thread.currentThread().isInterrupted())
throw new Failure("COVER_DOWNLOAD_TIMEOUT");
if (count > maxBytes - output.size()) throw new Failure("COVER_TOO_LARGE");
output.write(buffer, 0, count);
}
return output.toByteArray();
}
static Image image(byte[] bytes) {
if (bytes.length >= 3 && (bytes[0] & 255) == 255 && (bytes[1] & 255) == 216 && (bytes[2] & 255) == 255)
return new Image(bytes, "image/jpeg", "jpg");
if (bytes.length >= 8 && Arrays.equals(Arrays.copyOf(bytes, 8),
new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10}))
return new Image(bytes, "image/png", "png");
if (bytes.length >= 6 && bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F'
&& bytes[3] == '8' && (bytes[4] == '7' || bytes[4] == '9') && bytes[5] == 'a')
return new Image(bytes, "image/gif", "gif");
if (bytes.length >= 12 && bytes[0] == 'R' && bytes[1] == 'I' && bytes[2] == 'F' && bytes[3] == 'F'
&& bytes[8] == 'W' && bytes[9] == 'E' && bytes[10] == 'B' && bytes[11] == 'P')
return new Image(bytes, "image/webp", "webp");
throw new Failure("COVER_FORMAT_UNSUPPORTED");
}
}
@@ -17,6 +17,16 @@ mybatis-plus:
configuration:
map-underscore-to-camel-case: true
community:
oss:
# 导入只转换资源地址,永不启用 OSS SDK 或校验上传凭据。
enabled: false
region: ${OSS_REGION:cn-beijing}
bucket: ${OSS_BUCKET:linkerbot}
access-key-id: ${OSS_ACCESS_KEY_ID:}
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
public-base-url: ${OSS_PUBLIC_BASE_URL:https://linkerbot.oss-cn-beijing.aliyuncs.com}
legacy-public-base-urls: ${OSS_LEGACY_PUBLIC_BASE_URLS:}
root-directory: vibemake_dev
gitea:
base-url: ${GITEA_BASE_URL:http://localhost:3000}
owner: ${GITEA_ORGANIZATION:community}
@@ -26,3 +36,11 @@ logging:
root: WARN
com.linkerbot.community: INFO
com.linkerbot.community.service.mapper: WARN
---
spring:
config:
activate:
on-profile: prod
community:
oss:
root-directory: vibemake
@@ -11,6 +11,9 @@ import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.*;
import com.linkerbot.community.service.ProjectService;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.oss.OssResourcePaths;
import com.linkerbot.community.service.oss.OssObjectStore;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.gitea.*;
import com.linkerbot.community.service.mapper.*;
@@ -53,6 +56,9 @@ class ImportCoordinatorTest {
@Autowired ProjectService service;
@Autowired GiteaClient gitea;
@Autowired CommunityProperties config;
@Autowired OssResourcePaths resourcePaths;
@Autowired OssProperties oss;
@Autowired org.springframework.context.ApplicationContext context;
@Autowired JdbcTemplate jdbc;
@TempDir Path directory;
private StateStore store;
@@ -155,7 +161,7 @@ class ImportCoordinatorTest {
private ImportCoordinator worker(ProjectMapper mapper, ProjectService publisher) {
return new ImportCoordinator(
mapper, publisher, gitea, config, store, owner, Duration.ofMinutes(30));
mapper, publisher, gitea, config, resourcePaths, store, owner, Duration.ofMinutes(30));
}
@Test
@@ -168,6 +174,9 @@ class ImportCoordinatorTest {
assertThat(project.getPublishedCommitSha()).isEqualTo(SHA);
assertThat(project.getSourceProjectId()).isNull();
assertThat(project.getCoverUrl()).endsWith("a.gif");
assertThat(oss.isEnabled()).isFalse();
assertThat(oss.getAccessKeySecret()).isEmpty();
assertThat(context.getBeansOfType(OssObjectStore.class)).isEmpty();
assertThat(service.view(project, owner.getId()).projectCode()).isEqualTo(entry.projectCode);
verify(gitea, never()).createRepository(anyString(), anyBoolean());
verify(gitea).createBranch(remote.repository(), "main", SHA);
@@ -175,6 +184,22 @@ class ImportCoordinatorTest {
verify(gitea, times(1)).migrate(anyString(), anyString(), any(Duration.class));
}
@Test
void hostedImportCoversNormalizeWithoutOssCredentials() throws Exception {
String path = "/project-covers/111111111111/20261019/a.png";
Candidate original = entry.candidate;
entry.candidate = new Candidate(original.sheet(), original.row(), original.name(), original.repositoryUrl(),
original.description(), original.projectType(), oss.publicBaseUrl() + "/" + oss.getRootDirectory() + path);
worker(projects, service).run(entry);
assertThat(entry.phase).isEqualTo(Phase.PUBLISHED);
Project project = service.published(entry.projectCode);
assertThat(project.getCoverUrl()).isEqualTo(path);
assertThat(service.view(project, owner.getId()).coverUrl())
.isEqualTo(oss.publicBaseUrl() + "/" + oss.getRootDirectory() + path);
assertThat(oss.isEnabled()).isFalse();
assertThat(oss.getAccessKeyId()).isEmpty();
}
@Test
void normalizationErrorResumesOnlyAfterReadOnlyConfirmationOfAppliedState() throws Exception {
doThrow(new GiteaFailure(502, "GITEA_ERROR", "写入后响应失败", true))
@@ -0,0 +1,134 @@
package com.linkerbot.community.importer.cover;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.oss.OssResourcePaths;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InOrder;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class CoverMigratorTest {
@TempDir Path directory;
private final CoverMigrator.Repository repository = mock(CoverMigrator.Repository.class);
private final CoverMigrator.Downloader downloader = mock(CoverMigrator.Downloader.class);
private final CoverMigrator.Uploader uploader = mock(CoverMigrator.Uploader.class);
private final CoverMigrator.Backup backup = mock(CoverMigrator.Backup.class);
private final OssProperties oss = properties();
private final OssResourcePaths paths = new OssResourcePaths(oss);
private final ExternalCoverDownloader.Image image = new ExternalCoverDownloader.Image(new byte[] {1, 2, 3}, "image/gif", "gif");
private static final CoverMigrator.Candidate FIRST = new CoverMigrator.Candidate("1".repeat(12), "https://raw.example.com/a.gif");
private static OssProperties properties() {
OssProperties properties = new OssProperties();
properties.setRootDirectory("vibemake_dev");
properties.setPublicBaseUrl("https://cdn.example.com");
return properties;
}
@Test
void previewSkipsManagedReferencesWithoutAnyDownloadOrWrite() {
when(repository.list()).thenReturn(List.of(
new CoverMigrator.Candidate("1".repeat(12), "/project-covers/a.png"),
new CoverMigrator.Candidate("2".repeat(12), "https://cdn.example.com/vibemake_dev/project-covers/a.png"), FIRST));
CoverMigrator migrator = new CoverMigrator(repository, paths, downloader, uploader);
assertThat(migrator.candidates(10)).containsExactly(FIRST);
verify(repository, never()).replace(any(), anyString());
verifyNoInteractions(downloader, uploader);
}
@Test
void duplicatesDownloadAndUploadOnceAndBackupPrecedesConditionalUpdate() throws Exception {
CoverMigrator.Candidate second = new CoverMigrator.Candidate("2".repeat(12), FIRST.originalUrl());
when(downloader.download(FIRST.originalUrl())).thenReturn(image);
when(repository.replace(any(), anyString())).thenReturn(true);
List<CoverMigrator.Result> results = new CoverMigrator(repository, paths, downloader, uploader)
.migrate(List.of(FIRST, second), 2, backup);
assertThat(results).allSatisfy(result -> {
assertThat(result.status()).isEqualTo("UPDATED");
assertThat(result.coverPath()).matches("/project-covers/migrated/[a-f0-9]{64}[.]gif");
});
verify(downloader).download(FIRST.originalUrl());
verify(uploader).upload(startsWith("vibemake_dev/project-covers/migrated/"), same(image), anyString());
InOrder order = inOrder(backup, repository);
order.verify(backup).record(eq(FIRST), anyString());
order.verify(repository).replace(eq(FIRST), anyString());
order.verify(backup).record(eq(second), anyString());
order.verify(repository).replace(eq(second), anyString());
}
@Test
void downloadUploadAndBackupFailuresNeverReplaceDatabaseValues() throws Exception {
when(downloader.download(anyString())).thenThrow(new ExternalCoverDownloader.Failure("COVER_HTTP_404"));
CoverMigrator migrator = new CoverMigrator(repository, paths, downloader, uploader);
assertThat(migrator.migrate(List.of(FIRST), 1, backup).getFirst().code()).isEqualTo("DOWNLOAD:COVER_HTTP_404");
verifyNoInteractions(uploader, backup);
doReturn(image).when(downloader).download(anyString());
doThrow(new IllegalStateException()).when(uploader).upload(anyString(), any(), anyString());
assertThat(migrator.migrate(List.of(FIRST), 1, backup).getFirst().code()).startsWith("UPLOAD:");
verifyNoInteractions(backup);
doNothing().when(uploader).upload(anyString(), any(), anyString());
doThrow(new IllegalStateException()).when(backup).record(any(), anyString());
assertThat(migrator.migrate(List.of(FIRST), 1, backup).getFirst().code()).startsWith("BACKUP:");
verify(repository, never()).replace(any(), anyString());
}
@Test
void conditionalUpdateProtectsCaseOnlyEditsAndIsIdempotent() throws Exception {
JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:cover_migrate;MODE=MySQL;DB_CLOSE_DELAY=-1", "sa", ""));
jdbc.execute("DROP ALL OBJECTS");
jdbc.execute("CREATE ALIAS HEX FOR 'com.linkerbot.community.importer.cover.CoverMigratorTest.hex'");
jdbc.execute("CREATE TABLE project (project_code VARCHAR(32) PRIMARY KEY, cover_url VARCHAR(2048))");
jdbc.update("INSERT INTO project VALUES (?, ?)", FIRST.projectCode(), FIRST.originalUrl());
CoverMigrator.JdbcRepository database = new CoverMigrator.JdbcRepository(jdbc);
when(downloader.download(anyString())).thenReturn(image);
CoverMigrator migrator = new CoverMigrator(database, paths, downloader, uploader);
List<CoverMigrator.Candidate> candidates = migrator.candidates(10);
jdbc.update("UPDATE project SET cover_url = ?", "https://raw.example.com/A.gif");
assertThat(migrator.migrate(candidates, 1, backup).getFirst().status()).isEqualTo("CHANGED");
assertThat(jdbc.queryForObject("SELECT cover_url FROM project", String.class)).endsWith("A.gif");
assertThat(migrator.migrate(migrator.candidates(10), 1, backup).getFirst().status()).isEqualTo("UPDATED");
assertThat(migrator.candidates(10)).isEmpty();
}
@Test
void durableBackupPreservesOriginalValueBeforeWriteAndOptionsRejectConflicts() throws Exception {
Path path = directory.resolve("backup.jsonl");
try (CoverMigrationApplication.DurableBackup backupFile = new CoverMigrationApplication.DurableBackup(path, new ObjectMapper())) {
backupFile.record(FIRST, "/project-covers/migrated/a.gif");
assertThat(new ObjectMapper().readTree(Files.readString(path)).path("originalCoverUrl").asText())
.isEqualTo(FIRST.originalUrl());
}
assertThat(CoverMigrationApplication.Options.parse(new String[0]).execute()).isFalse();
assertThatThrownBy(() -> CoverMigrationApplication.Options.parse(new String[] {"--dry-run", "--execute"}))
.isInstanceOf(IllegalArgumentException.class);
}
public static String hex(String value) {
return value == null ? null : HexFormat.of().formatHex(value.getBytes(StandardCharsets.UTF_8));
}
@Test
void explicitRecoverySourcesDoNotReplaceOriginalValuesUsedForBackupAndCompare() {
String alternate = "https://raw.example.com/commit/a.gif";
assertThat(CoverMigrationApplication.downloadSources(List.of(FIRST), Map.of(FIRST.projectCode(), alternate)))
.containsEntry(FIRST.originalUrl(), alternate);
assertThat(FIRST.originalUrl()).isEqualTo("https://raw.example.com/a.gif");
assertThat(CoverMigrationApplication.downloadSources(List.of(), Map.of(FIRST.projectCode(), alternate))).isEmpty();
CoverMigrator.Candidate second = new CoverMigrator.Candidate("2".repeat(12), FIRST.originalUrl());
assertThatThrownBy(() -> CoverMigrationApplication.downloadSources(List.of(FIRST, second),
Map.of(FIRST.projectCode(), alternate, second.projectCode(), "https://raw.example.com/other.gif")))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -0,0 +1,61 @@
package com.linkerbot.community.importer.cover;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class ExternalCoverDownloaderTest {
@Test
void detectsActualImageTypesAndRejectsHtmlDisguisedAsImage() {
assertThat(ExternalCoverDownloader.image(new byte[] {(byte) 255, (byte) 216, (byte) 255}).contentType())
.isEqualTo("image/jpeg");
assertThat(ExternalCoverDownloader.image(new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10}).extension())
.isEqualTo("png");
assertThat(ExternalCoverDownloader.image("GIF89a-data".getBytes()).extension()).isEqualTo("gif");
assertThat(ExternalCoverDownloader.image("RIFF1234WEBP-data".getBytes()).extension()).isEqualTo("webp");
assertThatThrownBy(() -> ExternalCoverDownloader.image("<html>denied</html>".getBytes()))
.isInstanceOfSatisfying(ExternalCoverDownloader.Failure.class,
error -> assertThat(error.code()).isEqualTo("COVER_FORMAT_UNSUPPORTED"));
}
@Test
void boundedReadRejectsOverflowAndExpiredDownloads() throws Exception {
long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos();
assertThat(ExternalCoverDownloader.read(new ByteArrayInputStream(new byte[10]), 10, deadline)).hasSize(10);
assertThatThrownBy(() -> ExternalCoverDownloader.read(new ByteArrayInputStream(new byte[11]), 10, deadline))
.isInstanceOfSatisfying(ExternalCoverDownloader.Failure.class,
error -> assertThat(error.code()).isEqualTo("COVER_TOO_LARGE"));
assertThatThrownBy(() -> ExternalCoverDownloader.read(new ByteArrayInputStream(new byte[1]), 10, 0))
.isInstanceOf(ExternalCoverDownloader.Failure.class);
}
@Test
void rejectsPrivateNetworksCredentialsAndUnsafeRedirectTargets() {
for (String value : new String[] {"https://127.0.0.1/a", "https://10.0.0.1/a", "https://169.254.169.254/a",
"https://[::1]/a", "https://[fd00::1]/a", "https://100.64.0.1/a", "https://198.18.0.1/a",
"http://example.com/a", "https://user:pass@example.com/a", "https://example.com:8443/a"})
assertThatThrownBy(() -> ExternalCoverDownloader.validate(URI.create(value)))
.isInstanceOf(ExternalCoverDownloader.Failure.class);
}
@Test
void retriesTransientHandshakesButKeepsCertificateVerificationFailures() throws Exception {
ExternalCoverDownloader downloader = spy(new ExternalCoverDownloader(1024));
String url = "https://raw.example.com/a.png";
ExternalCoverDownloader.Image image = new ExternalCoverDownloader.Image(new byte[1], "image/png", "png");
doThrow(new javax.net.ssl.SSLHandshakeException("transient"))
.doReturn(image).when(downloader).fetch(url);
assertThat(downloader.download(url)).isSameAs(image);
verify(downloader, times(2)).fetch(url);
clearInvocations(downloader);
javax.net.ssl.SSLHandshakeException invalidCertificate = new javax.net.ssl.SSLHandshakeException("untrusted");
invalidCertificate.initCause(new java.security.cert.CertificateException());
doThrow(invalidCertificate).when(downloader).fetch(url);
assertThatThrownBy(() -> downloader.download(url)).isSameAs(invalidCertificate);
verify(downloader).fetch(url);
}
}