README 外链图片转存 OSS

This commit is contained in:
lxp
2026-11-03 17:27:22 +08:00
parent c5be9835bf
commit 175c49e0e7
35 changed files with 1557 additions and 99 deletions
@@ -15,7 +15,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/** 仅加载资源路径配置,不初始化在线安全、AI 或 OSS 客户端。 */
/** 仅加载导入所需服务,不启动在线安全或 AI;README OSS 客户端按需初始化。 */
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@MapperScan("com.linkerbot.vibemake.service.mapper")
@@ -28,6 +28,10 @@ import org.springframework.context.annotation.Import;
ProjectLocks.class,
OssProperties.class,
OssResourcePaths.class,
com.linkerbot.vibemake.service.config.ReadmeImageProperties.class,
com.linkerbot.vibemake.service.readme.ImageOssUploader.class,
com.linkerbot.vibemake.service.readme.ReadmeImages.class,
com.linkerbot.vibemake.service.readme.ReadmeRepository.class,
ProjectResourceFiles.class
})
public class DatabaseConfiguration {}
@@ -91,6 +91,11 @@ public final class ImportApplication {
}
public static void main(String[] args) {
if (args.length > 0 && "readme-images".equals(args[0])) {
int status = com.linkerbot.vibemake.importer.readme.ReadmeMigrationApplication.runCli(Arrays.copyOfRange(args, 1, args.length));
if (status != 0) System.exit(status);
return;
}
if (args.length > 0 && "covers".equals(args[0])) {
int status = com.linkerbot.vibemake.importer.cover.CoverMigrationApplication.runCli(
Arrays.copyOfRange(args, 1, args.length));
@@ -234,7 +239,8 @@ public final class ImportApplication {
context.getBean(OssResourcePaths.class),
store,
owner,
options.migrationTimeout()).locks(context.getBean(com.linkerbot.vibemake.service.support.ProjectLocks.class));
options.migrationTimeout()).locks(context.getBean(com.linkerbot.vibemake.service.support.ProjectLocks.class))
.readmes(context.getBean(com.linkerbot.vibemake.service.readme.ReadmeRepository.class));
try (ExecutorService executor =
Executors.newFixedThreadPool(options.concurrency())) {
try {
@@ -34,6 +34,12 @@ public final class ImportCoordinator {
private final User owner;
private final Duration timeout;
private final String batch;
private com.linkerbot.vibemake.service.readme.ReadmeRepository readmes;
public ImportCoordinator readmes(com.linkerbot.vibemake.service.readme.ReadmeRepository readmes) {
this.readmes = readmes;
return this;
}
private com.linkerbot.vibemake.service.support.ProjectLocks sharedLocks =
new com.linkerbot.vibemake.service.support.ProjectLocks();
@@ -46,7 +52,7 @@ public final class ImportCoordinator {
return entry.phase == Phase.REVIEW
&& entry.receipt != null
&& entry.targetSha != null
&& "NORMALIZING".equals(entry.failedPhase)
&& ("NORMALIZING".equals(entry.failedPhase) || entry.readmeImages != null)
&& !"SOURCE_CHANGED".equals(entry.errorCode)
&& !"DUPLICATE_SOURCE".equals(entry.errorCode);
}
@@ -160,14 +166,14 @@ public final class ImportCoordinator {
if (!Objects.equals(
project.getGiteaRepoId(),
entry.receipt == null ? null : entry.receipt.id())
|| !Objects.equals(project.getPublishedCommitSha(), entry.targetSha))
|| !Objects.equals(project.getPublishedCommitSha(), entry.readmeImages == null ? entry.targetSha : entry.readmeImages.resultSha))
throw new ImportFailure("PUBLICATION_CONFLICT", "已发布项目与导入收据不一致");
store.phase(entry, Phase.PUBLISHED);
return;
}
}
if (entry.phase == Phase.REVIEW) {
if (entry.phase == Phase.REVIEW && entry.readmeImages == null) {
RemoteRepository confirmed = gitea.inspect(repoName);
validateRemote(entry, confirmed);
boolean applied =
@@ -205,7 +211,13 @@ public final class ImportCoordinator {
gitea, config.getGitea().getOwner());
com.linkerbot.vibemake.service.migration.RepositoryMigration.Result migrated;
try {
migrated =
if (entry.readmeImages != null) {
RemoteRepository confirmed = engine.verifyReceipt(entry.source.url(), repoName, entry.receipt);
if (readmes == null) throw new ImportFailure("README_COMPONENT_MISSING", "缺少 README 处理组件");
readmes.resume(entry.projectCode, confirmed.repository(), entry.readmeImages, state -> checkpointReadme(entry, state));
sharedLocks.confirmKnownResult(entry.projectCode);
migrated = new com.linkerbot.vibemake.service.migration.RepositoryMigration.Result(confirmed, entry.targetSha);
} else migrated =
sharedLocks.write(
entry.projectCode,
() -> {
@@ -256,6 +268,17 @@ public final class ImportCoordinator {
RemoteRepository remote = migrated.remote();
String sourceSha = migrated.sha();
if (readmes != null) {
com.linkerbot.vibemake.service.readme.ReadmeRepository.Prepared prepared = entry.readmeImages == null
? readmes.prepare(entry.projectCode, remote.repository(), sourceSha, true) : null;
String baseSha = sourceSha;
com.linkerbot.vibemake.service.readme.ReadmeRepository.State state = sharedLocks.write(entry.projectCode,
() -> readmes.apply(entry.projectCode, remote.repository(), baseSha, "main", prepared, entry.readmeImages,
next -> checkpointReadme(entry, next)));
sourceSha = state.resultSha;
if (!sourceSha.equals(gitea.head(remote.repository())))
throw new ImportFailure("README_MAIN_CHANGED", "README 处理后的 main 已变化");
}
project.setGiteaRepoId(remote.id());
project.setRepoStatus("READY");
@@ -271,6 +294,8 @@ public final class ImportCoordinator {
} catch (RuntimeException warningFailure) {
warnings = List.of("兼容性扫描未完成;请人工检查大文件、LFS、子模块和符号链接");
}
warnings = new ArrayList<>(warnings);
if (entry.readmeImages != null) warnings.addAll(entry.readmeImages.warnings);
List<String> checkedWarnings = warnings;
store.update(entry, e -> e.warnings = new ArrayList<>(checkedWarnings));
store.phase(entry, Phase.PUBLISHING);
@@ -388,4 +413,9 @@ public final class ImportCoordinator {
WorkbookReader.repositoryKey(entry.candidate.repositoryUrl()))))
throw new ImportFailure("REPOSITORY_CONFLICT", "目标仓库归属、来源、可见性或内容不符合迁移要求");
}
private void checkpointReadme(Entry entry, com.linkerbot.vibemake.service.readme.ReadmeRepository.State state) {
try { store.update(entry, current -> { current.readmeImages = state; current.phase = Phase.README_IMAGES; }); }
catch (IOException error) { throw new java.io.UncheckedIOException(error); }
}
}
@@ -39,6 +39,7 @@ public final class ImportModels {
MIGRATED,
NORMALIZING,
BRANCH_READY,
README_IMAGES,
LINKED,
PUBLISHING,
PUBLISHED,
@@ -55,6 +56,7 @@ public final class ImportModels {
public String reservedAt;
public RemoteRepository receipt;
public String targetSha;
public com.linkerbot.vibemake.service.readme.ReadmeRepository.State readmeImages;
public String errorCode;
public String failedPhase;
public String message;
@@ -1,72 +1,19 @@
package com.linkerbot.vibemake.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.vibemake.service.config.OssProperties;
import java.io.ByteArrayInputStream;
import java.util.Map;
import com.linkerbot.vibemake.service.readme.ExternalImageDownloader;
import com.linkerbot.vibemake.service.readme.ImageOssUploader;
/** 封面和 README 复用同一套 OSS 摘要核验上传。 */
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");
private final ImageOssUploader uploader;
CoverOssUploader(OssProperties properties) { uploader = new ImageOssUploader(properties); }
@Override public void upload(String key, ExternalCoverDownloader.Image image, String sha256) {
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());
uploader.upload(key, new ExternalImageDownloader.Image(image.bytes(), image.contentType(), image.extension()), sha256);
} catch (ExternalImageDownloader.Failure error) {
throw new ExternalCoverDownloader.Failure(error.code());
}
}
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(); }
@Override public void close() { uploader.close(); }
}
@@ -0,0 +1,296 @@
package com.linkerbot.vibemake.importer.readme;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.*;
import com.linkerbot.vibemake.service.gitea.*;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import com.linkerbot.vibemake.service.readme.*;
import com.linkerbot.vibemake.service.support.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
import org.mybatis.spring.annotation.MapperScan;
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;
/** 存量 README 运维入口;备份与逐阶段收据先于远端写入持久化。 */
public final class ReadmeMigrationApplication {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@MapperScan("com.linkerbot.vibemake.service.mapper")
@Import({MybatisConfiguration.class, VibemakeProperties.class, OssProperties.class, OssResourcePaths.class,
ReadmeImageProperties.class, RestGiteaClient.class, ProjectLocks.class,
ImageOssUploader.class, ReadmeImages.class, ReadmeRepository.class})
public static class Config {}
public record Options(boolean execute, int limit, Set<String> codes, Path directory) {
public static Options parse(String[] args) {
boolean execute = false, dryRun = false;
int limit = Integer.MAX_VALUE;
Path directory = Path.of("logs/readme-image-migration");
Set<String> codes = new LinkedHashSet<>();
for (int index = 0; index < args.length; index++) {
String argument = args[index];
if (argument.equals("--execute")) execute = true;
else if (argument.equals("--dry-run")) dryRun = true;
else {
if (++index == args.length) throw new IllegalArgumentException("缺少参数值");
switch (argument) {
case "--limit" -> limit = Integer.parseInt(args[index]);
case "--project-code" -> codes.add(args[index]);
case "--state-dir" -> directory = Path.of(args[index]);
default -> throw new IllegalArgumentException("不支持的参数");
}
}
}
if (execute && dryRun || limit < 1 || codes.stream().anyMatch(code -> !code.matches("[A-Za-z0-9_-]{1,64}")))
throw new IllegalArgumentException("参数不合法");
return new Options(execute, limit, Set.copyOf(codes), directory);
}
}
public static class Job {
public String code;
public String runCode;
public Long repositoryId;
public String owner;
public String name;
public String originalMain;
public String originalPublished;
public String publishStatus;
public ReadmeRepository.State main;
public ReadmeRepository.State published;
public String status;
public String errorCode;
}
private final Options options;
private final ObjectMapper json;
private final JdbcTemplate jdbc;
private final ProjectMapper projects;
private final GiteaClient gitea;
private final ProjectLocks locks;
private final ReadmeRepository readmes;
public ReadmeMigrationApplication(Options options, ConfigurableApplicationContext context) {
this.options = options;
json = context.getBean(ObjectMapper.class);
jdbc = context.getBean(JdbcTemplate.class);
projects = context.getBean(ProjectMapper.class);
gitea = context.getBean(GiteaClient.class);
locks = context.getBean(ProjectLocks.class);
readmes = context.getBean(ReadmeRepository.class);
}
public static int runCli(String[] args) {
if (Arrays.asList(args).contains("--help")) {
System.out.println("用法:readme-images [--dry-run | --execute] [--limit N] [--project-code 编码] [--state-dir logs/readme-image-migration]");
return 0;
}
try {
Options options = Options.parse(args);
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE).logStartupInfo(false).run()) {
return new ReadmeMigrationApplication(options, context).run(context.getBean(VibemakeProperties.class), context.getBean(OssProperties.class));
}
} catch (Exception error) {
System.err.println("README 迁移终止 code=" + code(error));
return 1;
}
}
int run(VibemakeProperties config, OssProperties oss) throws IOException {
Files.createDirectories(options.directory());
restrict(options.directory(), "rwx------");
try (FileChannel channel = FileChannel.open(options.directory().resolve(".lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
FileLock ignored = channel.tryLock()) {
if (ignored == null) throw new IllegalStateException("状态目录正在使用");
restrict(options.directory().resolve(".lock"), "rw-------");
Map<String, String> binding = Map.of("gitea", config.getGitea().getBaseUrl(), "organization", config.getGitea().getOwner(),
"bucket", oss.getBucket(), "root", oss.getRootDirectory(), "publicBase", oss.publicBaseUrl());
Path manifest = options.directory().resolve("environment.json");
if (Files.exists(manifest) && !json.readTree(Files.readString(manifest)).equals(json.valueToTree(binding)))
throw new IllegalStateException("状态目录绑定的环境已变化");
write(manifest, json.writeValueAsBytes(binding));
List<Project> candidates = projects.selectList(new LambdaQueryWrapper<Project>().eq(Project::getDeleted, false).orderByAsc(Project::getProjectCode));
List<Map<String, Object>> report = new ArrayList<>();
int processed = 0;
for (Project project : candidates) {
String code = project.getProjectCode();
if (!options.codes().isEmpty() && !options.codes().contains(code)) continue;
if (!"READY".equals(project.getRepoStatus())) {
report.add(Map.of("projectCode", code, "status", "SKIPPED", "reason", "REPOSITORY_NOT_READY"));
continue;
}
if (processed >= options.limit()) break;
try {
Map<String, Object> result = process(project);
report.add(result);
if (Boolean.TRUE.equals(result.get("candidate")) && !"ALREADY_DONE".equals(result.get("status"))) processed++;
System.out.printf("README projectCode=%s status=%s candidates=%s replaced=%s failed=%s%n", code,
result.get("status"), result.getOrDefault("images", 0), result.getOrDefault("replaced", 0), result.getOrDefault("failed", 0));
} catch (RuntimeException error) {
report.add(Map.of("projectCode", code, "status", "FAILED", "errorCode", code(error)));
System.err.printf("README projectCode=%s status=FAILED code=%s%n", code, code(error));
}
write(options.directory().resolve(options.execute() ? "report.json" : "preview.json"), json.writerWithDefaultPrettyPrinter().writeValueAsBytes(report));
}
write(options.directory().resolve(options.execute() ? "report.json" : "preview.json"), json.writerWithDefaultPrettyPrinter().writeValueAsBytes(report));
System.out.printf("README 批次结束 projects=%d candidates=%d reportDirectory=%s%n", report.size(), processed, options.directory().toAbsolutePath());
return report.stream().anyMatch(item -> "FAILED".equals(item.get("status"))) ? 2 : 0;
}
}
private Map<String, Object> process(Project project) {
String code = project.getProjectCode();
GiteaClient.Repository repository = new GiteaClient.Repository(project.getGiteaRepoId(), project.getGiteaOwner(), project.getGiteaRepoName());
Path stateFile = options.directory().resolve(code + ".json");
Job job = options.execute() && Files.exists(stateFile) ? read(stateFile, Job.class) : null;
if (job != null && "DONE".equals(job.status) && "IDLE".equals(project.getRepoWriteStatus()))
return result(job, "ALREADY_DONE");
if (job == null) {
job = new Job();
job.code = code;
job.runCode = UUID.randomUUID().toString().substring(0, 8);
job.repositoryId = repository.id(); job.owner = repository.owner(); job.name = repository.name();
job.originalMain = gitea.head(repository);
job.originalPublished = project.getPublishedCommitSha();
job.publishStatus = project.getPublishStatus();
}
Job current = job;
if (!Objects.equals(job.repositoryId, project.getGiteaRepoId()) || !job.owner.equals(project.getGiteaOwner()) || !job.name.equals(project.getGiteaRepoName()))
throw BusinessException.conflict("仓库身份已变化");
GiteaClient.RemoteRepository remote = gitea.inspect(repository.name());
if (remote.id() != repository.id() || !remote.owner().equals(repository.owner()) || !remote.privateRepo() || remote.mirror() || remote.empty())
throw BusinessException.conflict("远端仓库身份已变化");
boolean same = Objects.equals(job.originalMain, job.originalPublished);
ReadmeRepository.Prepared main = job.main == null ? readmes.prepare(code, repository, job.originalMain, false) : null;
ReadmeRepository.Prepared published = job.originalPublished == null || same || job.published != null ? null
: readmes.prepare(code, repository, job.originalPublished, false);
if (main != null && main.path() == null && main.result().failed() > 0
|| published != null && published.path() == null && published.result().failed() > 0)
throw new ExternalImageDownloader.Failure("README_SCAN_FAILED");
int images = (main == null ? 0 : main.scan().images().size()) + (published == null ? 0 : published.scan().images().size());
int badges = (main == null ? 0 : main.scan().badges()) + (published == null ? 0 : published.scan().badges());
if (!options.execute() || images == 0 && job.main == null && job.published == null)
return Map.of("projectCode", code, "candidate", images > 0, "status", images > 0 ? "PREVIEW" : "SKIPPED",
"images", images, "badges", badges, "publishedDifferent", job.originalPublished != null && !same);
save(stateFile, job);
backup(code + "-main-original.md", main);
backup(code + "-published-original.md", published);
// 所有外网图片下载和上传均在项目锁之外。
ReadmeRepository.Prepared mainReady = main == null ? null : readmes.prepare(code, repository, job.originalMain, true);
ReadmeRepository.Prepared publishedReady = published == null ? null : readmes.prepare(code, repository, job.originalPublished, true);
try {
locks.serial(code, () -> {
Project fresh = projects.selectOne(new LambdaQueryWrapper<Project>().eq(Project::getProjectCode, code));
if (fresh == null || Boolean.TRUE.equals(fresh.getDeleted()) || !"READY".equals(fresh.getRepoStatus())
|| !Objects.equals(fresh.getGiteaRepoId(), current.repositoryId) || !fresh.getGiteaOwner().equals(current.owner)
|| !fresh.getGiteaRepoName().equals(current.name) || !fresh.getPublishStatus().equals(current.publishStatus))
throw BusinessException.conflict("项目状态已变化");
Long active = jdbc.queryForObject("SELECT COUNT(*) FROM repository_write_operation WHERE project_code = ? AND status IN ('PROCESSING','NEEDS_REVIEW')", Long.class, code);
if (active != null && active > 0) throw BusinessException.conflict("项目存在待核对操作");
if (!"IDLE".equals(fresh.getRepoWriteStatus())) {
if (!"REVIEW".equals(fresh.getRepoWriteStatus()) || current.main == null && current.published == null)
throw BusinessException.conflict("项目存在其他待核对写入");
if (current.main != null) readmes.resume(code, repository, current.main, state -> { current.main = state; save(stateFile, current); });
if (current.published != null && !same) readmes.resume(code, repository, current.published, state -> { current.published = state; save(stateFile, current); });
locks.confirmKnownResult(code);
}
String expectedMain = current.main == null || current.main.resultSha == null ? current.originalMain : current.main.resultSha;
if (!expectedMain.equals(gitea.head(repository))) throw BusinessException.conflict("main 已变化,跳过本次处理");
String expectedPublished = same && current.main != null ? current.main.resultSha : current.published == null || current.published.resultSha == null ? current.originalPublished : current.published.resultSha;
if (!Objects.equals(fresh.getPublishedCommitSha(), current.originalPublished) && !Objects.equals(fresh.getPublishedCommitSha(), expectedPublished))
throw BusinessException.conflict("发布版本已变化,跳过本次处理");
return locks.write(code, () -> {
current.main = readmes.apply(code, repository, current.originalMain, "main", mainReady, current.main,
state -> { current.main = state; save(stateFile, current); });
if (same) current.published = current.main;
else if (current.originalPublished != null)
current.published = readmes.apply(code, repository, current.originalPublished,
"maintenance/readme-oss/" + code + "/" + current.runCode, publishedReady, current.published,
state -> { current.published = state; save(stateFile, current); });
if (current.published != null && !current.originalPublished.equals(current.published.resultSha)
&& !Objects.equals(fresh.getPublishedCommitSha(), current.published.resultSha)) {
int changed = jdbc.update("UPDATE project SET published_commit_sha = ?, updated_at = ? WHERE project_code = ? AND deleted = 0"
+ " AND repo_status = 'READY' AND publish_status = ? AND HEX(published_commit_sha) = HEX(?) AND gitea_repo_id = ?",
current.published.resultSha, ProjectSupport.now(), code, current.publishStatus, current.originalPublished, current.repositoryId);
if (changed != 1) throw BusinessException.conflict("发布引用已变化");
}
current.status = "DONE";
save(stateFile, current);
return null;
});
});
} catch (RuntimeException error) {
current.status = "FAILED";
current.errorCode = code(error);
save(stateFile, current);
throw error;
}
return result(current, "DONE");
}
private Map<String, Object> result(Job job, String status) {
boolean same = Objects.equals(job.originalMain, job.originalPublished);
int replaced = job.main.replaced + (same || job.published == null ? 0 : job.published.replaced);
int failed = job.main.failed + (same || job.published == null ? 0 : job.published.failed);
int badges = job.main.badges + (same || job.published == null ? 0 : job.published.badges);
return Map.of("projectCode", job.code, "candidate", true, "status", status, "images", replaced + failed,
"replaced", replaced, "failed", failed, "badges", badges,
"mainSha", job.main.resultSha, "publishedSha", job.published == null ? "" : job.published.resultSha);
}
private void backup(String name, ReadmeRepository.Prepared prepared) {
if (prepared == null || prepared.path() == null) return;
Path path = options.directory().resolve(name);
if (!Files.exists(path)) writeUnchecked(path, prepared.original().getBytes(StandardCharsets.UTF_8));
}
private <T> T read(Path path, Class<T> type) {
try { return json.readValue(Files.readAllBytes(path), type); }
catch (IOException error) { throw new UncheckedIOException(error); }
}
private void save(Path path, Object value) {
try { write(path, json.writerWithDefaultPrettyPrinter().writeValueAsBytes(value)); }
catch (IOException error) { throw new UncheckedIOException(error); }
}
private static void writeUnchecked(Path path, byte[] bytes) {
try { write(path, bytes); } catch (IOException error) { throw new UncheckedIOException(error); }
}
private static void write(Path path, byte[] bytes) throws IOException {
Path temporary = Files.createTempFile(path.getParent(), ".readme-", ".tmp");
try {
restrict(temporary, "rw-------");
try (FileChannel output = FileChannel.open(temporary, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) { directory.force(true); }
} finally { Files.deleteIfExists(temporary); }
}
private static void restrict(Path path, String mode) throws IOException {
if (Files.getFileStore(path).supportsFileAttributeView("posix")) Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode));
}
private static String code(Throwable error) {
if (error instanceof BusinessException business) return business.code();
if (error instanceof ExternalImageDownloader.Failure failure) return failure.code();
return error.getClass().getSimpleName();
}
}
@@ -17,8 +17,12 @@ mybatis-plus:
configuration:
map-underscore-to-camel-case: true
vibemake:
readme-images:
enabled: ${README_IMAGES_ENABLED:true}
max-bytes: ${README_IMAGE_MAX_BYTES:20971520}
concurrency: ${README_IMAGE_CONCURRENCY:2}
oss:
# 导入只转换资源地址,永不启用 OSS SDK 或校验上传凭据。
# 常规资源仅转换地址;README 转存按需单独校验凭据,预览不初始化 OSS SDK。
enabled: false
region: ${OSS_REGION:cn-beijing}
bucket: ${OSS_BUCKET:linkerbot}
@@ -18,6 +18,8 @@ import com.linkerbot.vibemake.service.oss.OssObjectStore;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.AdditionalAnswers;
import org.springframework.beans.factory.annotation.Autowired;
@@ -178,6 +180,39 @@ class ImportCoordinatorTest {
Duration.ofMinutes(30));
}
@ParameterizedTest
@ValueSource(strings = {"master", "main"})
void readmeCommitIsPublishedWhileOriginalMigrationShaRemainsFrozen(String sourceBranch) throws Exception {
if (sourceBranch.equals("main")) {
entry.source = new GitHubRepository(entry.source.id(), entry.source.url(), "main");
main.set(true);
remote = new GiteaClient.RemoteRepository(remote.id(), remote.owner(), remote.name(), true, false, false, remote.originalUrl(), "main");
store.save();
}
com.linkerbot.vibemake.service.readme.ReadmeRepository readmes = mock(com.linkerbot.vibemake.service.readme.ReadmeRepository.class);
String imageSha = "b".repeat(40);
when(readmes.apply(anyString(), any(), eq(SHA), eq("main"), any(), isNull(), any())).thenAnswer(call -> {
com.linkerbot.vibemake.service.readme.ReadmeRepository.State state = new com.linkerbot.vibemake.service.readme.ReadmeRepository.State();
state.baseSha = SHA; state.resultSha = imageSha; state.branch = "main"; state.stage = "DONE";
com.linkerbot.vibemake.service.readme.ReadmeRepository.Checkpoint checkpoint = call.getArgument(6);
checkpoint.save(state);
when(gitea.head(any())).thenReturn(imageSha);
when(gitea.branch(any(), eq("main"))).thenReturn(imageSha);
return state;
});
worker(projects, service).readmes(readmes).run(entry);
assertThat(entry.phase).isEqualTo(Phase.PUBLISHED);
assertThat(entry.targetSha).isEqualTo(SHA);
assertThat(entry.readmeImages.resultSha).isEqualTo(imageSha);
assertThat(service.published(entry.projectCode).getPublishedCommitSha()).isEqualTo(imageSha);
// 模拟发布已成功、批次终态尚未落盘时重启。
entry.phase = Phase.PUBLISHING;
store.save();
worker(projects, service).readmes(readmes).run(entry);
assertThat(entry.phase).isEqualTo(Phase.PUBLISHED);
verify(gitea, times(1)).migrate(anyString(), anyString(), any(Duration.class));
}
@Test
void migrationBindsShortCodeAdaptsMasterAndPublishesWithoutEmptyRepository() throws Exception {
Instant before = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS);