git clone功能
网站登录 → 创建项目 Git Token → clone → 本地修改、commit → push main → 网站工作区刷新后显示最新内容 → 网站手动发布到社区
This commit is contained in:
+95
@@ -0,0 +1,95 @@
|
||||
package com.linkerbot.vibemake.service.config;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Component
|
||||
@Validated
|
||||
@ConfigurationProperties("vibemake.git")
|
||||
public class GitGatewayProperties {
|
||||
private boolean enabled;
|
||||
private String publicBaseUrl = "";
|
||||
private String upstreamUsername = "";
|
||||
private String upstreamToken = "";
|
||||
private Duration timeout = Duration.ofMinutes(10);
|
||||
@Positive private long maxPackBytes = 5L * 1024 * 1024 * 1024;
|
||||
@Positive private long maxLfsObjectBytes = 1024L * 1024 * 1024;
|
||||
|
||||
@Min(1024)
|
||||
@Max(16777216)
|
||||
private int maxMetadataBytes = 8 * 1024 * 1024;
|
||||
|
||||
@Min(1)
|
||||
@Max(500)
|
||||
private int maxBatchObjects = 500;
|
||||
|
||||
@Min(1)
|
||||
@Max(32)
|
||||
private int readConcurrent = 4;
|
||||
|
||||
@Min(1)
|
||||
@Max(32)
|
||||
private int pushConcurrent = 2;
|
||||
|
||||
@Min(1)
|
||||
@Max(64)
|
||||
private int lfsConcurrent = 8;
|
||||
|
||||
@Min(1)
|
||||
@Max(10)
|
||||
private int maxActiveTokens = 10;
|
||||
|
||||
@Min(1)
|
||||
@Max(10000)
|
||||
private int gitRequestsPerMinute = 120;
|
||||
|
||||
@Min(1)
|
||||
@Max(10000)
|
||||
private int lfsRequestsPerMinute = 600;
|
||||
|
||||
@Min(1)
|
||||
@Max(1000)
|
||||
private int authFailuresPerMinute = 20;
|
||||
|
||||
@AssertTrue(message = "Git 网关启用时必须配置公网 HTTPS 基础地址(以 /git 结尾)和独立技术账号凭据")
|
||||
public boolean isConfigurationValid() {
|
||||
if (!enabled) return true;
|
||||
try {
|
||||
URI uri = URI.create(publicBaseUrl);
|
||||
return "https".equals(uri.getScheme())
|
||||
&& uri.getHost() != null
|
||||
&& "/git".equals(uri.getRawPath())
|
||||
&& uri.getRawUserInfo() == null
|
||||
&& uri.getRawQuery() == null
|
||||
&& uri.getRawFragment() == null
|
||||
&& upstreamUsername != null
|
||||
&& !upstreamUsername.isBlank()
|
||||
&& !upstreamUsername.contains(":")
|
||||
&& upstreamToken != null
|
||||
&& !upstreamToken.isBlank();
|
||||
} catch (IllegalArgumentException error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@AssertTrue(message = "Git 请求预算必须在 100 毫秒至 1 小时之间")
|
||||
public boolean isTimeoutValid() {
|
||||
return timeout != null
|
||||
&& timeout.compareTo(Duration.ofMillis(100)) >= 0
|
||||
&& timeout.compareTo(Duration.ofHours(1)) <= 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
/** 只在请求内部使用;不包含凭据明文,不作为 API 响应返回。 */
|
||||
public record GitAccess(
|
||||
long userId, String userCode, String tokenCode, String projectCode, boolean writable) {}
|
||||
@@ -0,0 +1,294 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.linkerbot.vibemake.bean.GitContracts.ConnectionView;
|
||||
import com.linkerbot.vibemake.bean.entity.Project;
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.service.ProjectService;
|
||||
import com.linkerbot.vibemake.service.UserService;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
import com.linkerbot.vibemake.service.gitea.GiteaClient;
|
||||
import com.linkerbot.vibemake.service.write.RepositoryWrites;
|
||||
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GitGateway {
|
||||
private static final Logger log = LoggerFactory.getLogger(GitGateway.class);
|
||||
private final GitTokens tokens;
|
||||
private final GitTransport transport;
|
||||
private final GitGatewayProperties properties;
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final GiteaClient gitea;
|
||||
private final GitPolicy policy;
|
||||
private final RepositoryWrites writes;
|
||||
private final GitLimits limits;
|
||||
|
||||
public ConnectionView connection(long userId, String code) {
|
||||
tokens.enabled();
|
||||
Project project = projects.readyOwner(userId, code);
|
||||
boolean canPush =
|
||||
"IDLE".equals(project.getRepoWriteStatus()) && writes.active(code) == null;
|
||||
if (canPush) {
|
||||
try {
|
||||
policy.verify(project);
|
||||
} catch (BusinessException error) {
|
||||
canPush = false;
|
||||
}
|
||||
}
|
||||
return new ConnectionView(
|
||||
properties.getPublicBaseUrl() + "/projects/" + code + ".git",
|
||||
users.require(userId).getUserCode(),
|
||||
"main",
|
||||
gitea.head(projects.repository(project)),
|
||||
project.getPublishedCommitSha(),
|
||||
project.getRepoWriteStatus(),
|
||||
canPush);
|
||||
}
|
||||
|
||||
public void serve(
|
||||
GitAccess access,
|
||||
String endpoint,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
throws IOException {
|
||||
String service = "info/refs".equals(endpoint) ? request.getParameter("service") : endpoint;
|
||||
boolean advertisement = "info/refs".equals(endpoint);
|
||||
if (!("git-upload-pack".equals(service) || "git-receive-pack".equals(service))
|
||||
|| !(advertisement ? "GET" : "POST").equals(request.getMethod()))
|
||||
throw GitIo.invalid();
|
||||
if (request.getParameterMap().size() != (advertisement ? 1 : 0)) throw GitIo.invalid();
|
||||
boolean push = "git-receive-pack".equals(service);
|
||||
if (push) GitTokens.requireWrite(access);
|
||||
long started = System.nanoTime();
|
||||
java.util.concurrent.atomic.AtomicLong transferred =
|
||||
new java.util.concurrent.atomic.AtomicLong();
|
||||
log.info(
|
||||
"Git 请求开始 projectCode={} userCode={} tokenCode={} endpoint={}",
|
||||
access.projectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
endpoint);
|
||||
try (AutoCloseable permit = limits.acquire(push, false);
|
||||
GitTransport.Budget budget = transport.budget()) {
|
||||
budget.register(request.getInputStream());
|
||||
budget.onTimeout(
|
||||
() -> {
|
||||
if (response.isCommitted()) response.getOutputStream().close();
|
||||
});
|
||||
Project project = projects.readyOwner(access.userId(), access.projectCode());
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put(
|
||||
"Accept",
|
||||
"application/x-" + service + (advertisement ? "-advertisement" : "-result"));
|
||||
if (!push && request.getHeader("Git-Protocol") != null) {
|
||||
if (!request.getHeader("Git-Protocol").matches("version=[012]"))
|
||||
throw GitIo.invalid();
|
||||
headers.put("Git-Protocol", request.getHeader("Git-Protocol"));
|
||||
}
|
||||
String path =
|
||||
transport.repositoryPath(project)
|
||||
+ "/"
|
||||
+ endpoint
|
||||
+ (advertisement ? "?service=" + service : "");
|
||||
if (push && !advertisement) {
|
||||
requireContentType(request, "application/x-git-receive-pack-request");
|
||||
InputStream input =
|
||||
GitIo.counted(
|
||||
decoded(request, properties.getMaxPackBytes(), budget),
|
||||
transferred);
|
||||
GitIo.PushCommand command = GitIo.command(input);
|
||||
if (command == null) {
|
||||
if (input.read() != -1) throw GitIo.invalid();
|
||||
response.setContentType("application/x-git-receive-pack-result");
|
||||
response.setContentLength(0);
|
||||
return;
|
||||
}
|
||||
java.util.concurrent.atomic.AtomicReference<Project> pushing =
|
||||
new java.util.concurrent.atomic.AtomicReference<>();
|
||||
byte[] result =
|
||||
writes.push(
|
||||
access,
|
||||
command,
|
||||
() -> {
|
||||
GitAccess current = tokens.recheck(access);
|
||||
GitTokens.requireWrite(current);
|
||||
Project fresh =
|
||||
projects.readyOwner(
|
||||
current.userId(), current.projectCode());
|
||||
if (!command.oldSha()
|
||||
.equals(gitea.head(projects.repository(fresh))))
|
||||
throw new BusinessException(
|
||||
409, "GIT_STALE_MAIN", "main 已变化,请先 pull、合并后再推送");
|
||||
policy.verify(fresh);
|
||||
budget.check();
|
||||
pushing.set(fresh);
|
||||
return fresh;
|
||||
},
|
||||
() -> {
|
||||
headers.put(
|
||||
"Content-Type",
|
||||
"application/x-git-receive-pack-request");
|
||||
InputStream body =
|
||||
new SequenceInputStream(
|
||||
new ByteArrayInputStream(command.prefix()),
|
||||
input);
|
||||
try (GitTransport.Response upstream =
|
||||
transport.exchange(
|
||||
transport.repositoryPath(pushing.get())
|
||||
+ "/git-receive-pack",
|
||||
"POST",
|
||||
body,
|
||||
-1,
|
||||
headers,
|
||||
budget)) {
|
||||
requireSuccess(
|
||||
upstream, "application/x-git-receive-pack-result");
|
||||
return GitIo.metadata(
|
||||
upstream.input(), properties.getMaxMetadataBytes());
|
||||
} catch (IOException error) {
|
||||
budget.check();
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
});
|
||||
response.setContentType("application/x-git-receive-pack-result");
|
||||
response.setContentLength(result.length);
|
||||
response.getOutputStream().write(result);
|
||||
log.info(
|
||||
"Git 推送响应完成 projectCode={} userCode={} tokenCode={} oldSha={} newSha={}"
|
||||
+ " bytes={} durationMs={}",
|
||||
access.projectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
command.oldSha(),
|
||||
command.newSha(),
|
||||
transferred.get(),
|
||||
(System.nanoTime() - started) / 1000000);
|
||||
} else {
|
||||
InputStream body = null;
|
||||
if (!advertisement) {
|
||||
requireContentType(request, "application/x-git-upload-pack-request");
|
||||
body = decoded(request, properties.getMaxMetadataBytes(), budget);
|
||||
headers.put("Content-Type", "application/x-git-upload-pack-request");
|
||||
}
|
||||
String type =
|
||||
"application/x-" + service + (advertisement ? "-advertisement" : "-result");
|
||||
try (GitTransport.Response upstream =
|
||||
transport.exchange(path, request.getMethod(), body, -1, headers, budget)) {
|
||||
requireSuccess(upstream, type);
|
||||
response.setContentType(type);
|
||||
if (push) {
|
||||
byte[] result =
|
||||
GitIo.receiveAdvertisement(
|
||||
GitIo.metadata(
|
||||
upstream.input(),
|
||||
properties.getMaxMetadataBytes()));
|
||||
response.setContentLength(result.length);
|
||||
response.getOutputStream().write(result);
|
||||
} else {
|
||||
long bytes =
|
||||
copy(
|
||||
upstream.input(),
|
||||
response,
|
||||
properties.getMaxPackBytes(),
|
||||
budget,
|
||||
transferred);
|
||||
log.info(
|
||||
"Git 读取完成 projectCode={} userCode={} tokenCode={} bytes={}"
|
||||
+ " durationMs={}",
|
||||
access.projectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
bytes,
|
||||
(System.nanoTime() - started) / 1000000);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (BusinessException | IOException error) {
|
||||
log.warn(
|
||||
"Git 请求失败或取消 projectCode={} userCode={} tokenCode={} endpoint={} errorType={}"
|
||||
+ " bytes={} durationMs={}",
|
||||
access.projectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
endpoint,
|
||||
error.getClass().getSimpleName(),
|
||||
transferred.get(),
|
||||
(System.nanoTime() - started) / 1000000);
|
||||
throw error;
|
||||
} catch (Exception error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream decoded(
|
||||
HttpServletRequest request, long maximum, GitTransport.Budget budget)
|
||||
throws IOException {
|
||||
if (request.getContentLengthLong() > maximum)
|
||||
throw new BusinessException(413, "GIT_TRANSFER_TOO_LARGE", "Git/LFS 请求过大");
|
||||
InputStream raw = GitIo.limited(request.getInputStream(), maximum);
|
||||
budget.register(raw);
|
||||
String encoding = request.getHeader("Content-Encoding");
|
||||
if (encoding != null && !"identity".equalsIgnoreCase(encoding)) {
|
||||
if (!"gzip".equalsIgnoreCase(encoding)) throw GitIo.invalid();
|
||||
raw = new GZIPInputStream(raw);
|
||||
}
|
||||
return GitIo.limited(raw, maximum);
|
||||
}
|
||||
|
||||
public static void requireContentType(HttpServletRequest request, String type) {
|
||||
if (request.getContentType() == null
|
||||
|| !request.getContentType().split(";", 2)[0].equalsIgnoreCase(type))
|
||||
throw GitIo.invalid();
|
||||
}
|
||||
|
||||
public static void requireSuccess(GitTransport.Response response, String type) {
|
||||
if (response.status() != 200
|
||||
|| !response.headers()
|
||||
.firstValue("Content-Type")
|
||||
.orElse("")
|
||||
.split(";", 2)[0]
|
||||
.equalsIgnoreCase(type)) throw GitIo.upstreamInvalid();
|
||||
}
|
||||
|
||||
public static long copy(
|
||||
InputStream input,
|
||||
HttpServletResponse response,
|
||||
long maximum,
|
||||
GitTransport.Budget budget)
|
||||
throws IOException {
|
||||
return copy(input, response, maximum, budget, new java.util.concurrent.atomic.AtomicLong());
|
||||
}
|
||||
|
||||
public static long copy(
|
||||
InputStream input,
|
||||
HttpServletResponse response,
|
||||
long maximum,
|
||||
GitTransport.Budget budget,
|
||||
java.util.concurrent.atomic.AtomicLong transferred)
|
||||
throws IOException {
|
||||
byte[] buffer = new byte[65536];
|
||||
long total = 0;
|
||||
int count;
|
||||
InputStream bounded = GitIo.limited(input, maximum);
|
||||
while ((count = bounded.read(buffer)) >= 0) {
|
||||
budget.check();
|
||||
response.getOutputStream().write(buffer, 0, count);
|
||||
total += count;
|
||||
transferred.addAndGet(count);
|
||||
}
|
||||
budget.check();
|
||||
return total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
|
||||
/** Git pkt-line 的有界元数据处理;pack 正文始终以流处理。 */
|
||||
public final class GitIo {
|
||||
private GitIo() {}
|
||||
|
||||
public record PushCommand(String oldSha, String newSha, byte[] prefix) {}
|
||||
|
||||
private static final Set<String> PUSH_CAPS = Set.of("report-status", "ofs-delta", "quiet");
|
||||
|
||||
public static InputStream counted(
|
||||
InputStream input, java.util.concurrent.atomic.AtomicLong count) {
|
||||
return new FilterInputStream(input) {
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
byte[] one = new byte[1];
|
||||
return read(one, 0, 1) < 0 ? -1 : one[0] & 255;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
int size = super.read(bytes, offset, length);
|
||||
if (size > 0) count.addAndGet(size);
|
||||
return size;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static InputStream limited(InputStream input, long maximum) {
|
||||
return new FilterInputStream(input) {
|
||||
private long count;
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
byte[] bytes = new byte[1];
|
||||
return read(bytes, 0, 1) < 0 ? -1 : bytes[0] & 255;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
if (length == 0) return 0;
|
||||
long remaining = maximum - count;
|
||||
int size =
|
||||
super.read(
|
||||
bytes, offset, remaining >= length ? length : (int) remaining + 1);
|
||||
if (size > 0 && (count += size) > maximum)
|
||||
throw new BusinessException(413, "GIT_TRANSFER_TOO_LARGE", "Git/LFS 传输超过大小限制");
|
||||
return size;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static byte[] metadata(InputStream input, int maximum) throws IOException {
|
||||
byte[] bytes = input.readNBytes(maximum + 1);
|
||||
if (bytes.length > maximum)
|
||||
throw new BusinessException(413, "GIT_METADATA_TOO_LARGE", "Git/LFS 元数据超过限制");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static byte[] packet(InputStream input) throws IOException {
|
||||
byte[] header = input.readNBytes(4);
|
||||
if (header.length != 4) throw invalid();
|
||||
String hex = new String(header, StandardCharsets.US_ASCII);
|
||||
if (!hex.matches("[0-9a-fA-F]{4}")) throw invalid();
|
||||
int size = Integer.parseInt(hex, 16);
|
||||
if (size == 0) return null;
|
||||
if (size < 4 || size > 65520) throw invalid();
|
||||
byte[] data = input.readNBytes(size - 4);
|
||||
if (data.length != size - 4) throw invalid();
|
||||
return data;
|
||||
}
|
||||
|
||||
public static void packet(OutputStream output, byte[] data) throws IOException {
|
||||
output.write(
|
||||
String.format(java.util.Locale.ROOT, "%04x", data.length + 4)
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
output.write(data);
|
||||
}
|
||||
|
||||
private static boolean capability(String value) {
|
||||
return PUSH_CAPS.contains(value)
|
||||
|| value.matches("agent=[!-~]{1,128}")
|
||||
|| value.equals("object-format=sha1")
|
||||
|| value.equals("object-format=sha256");
|
||||
}
|
||||
|
||||
public static PushCommand command(InputStream input) throws IOException {
|
||||
byte[] first = packet(input);
|
||||
// Smart HTTP 在大 pack 分块上传前会单独 POST 一个 flush 进行认证探测。
|
||||
if (first == null) return null;
|
||||
if (first.length > 4096) throw invalid();
|
||||
String command = new String(first, StandardCharsets.UTF_8).stripTrailing();
|
||||
int nul = command.indexOf('\0');
|
||||
if (nul < 0) throw invalid();
|
||||
String[] fields = command.substring(0, nul).split(" ", -1);
|
||||
if (fields.length != 3 || !"refs/heads/main".equals(fields[2])) throw invalid();
|
||||
String oldSha = com.linkerbot.vibemake.common.FilePaths.sha(fields[0]);
|
||||
String newSha = com.linkerbot.vibemake.common.FilePaths.sha(fields[1]);
|
||||
if (oldSha.length() != newSha.length() || oldSha.matches("0+") || newSha.matches("0+"))
|
||||
throw invalid();
|
||||
// 原生 send-pack 会在 NUL 后的能力列表前保留一个空格。
|
||||
String[] caps = command.substring(nul + 1).strip().split(" ");
|
||||
boolean report = false;
|
||||
for (String cap : caps) {
|
||||
if (!capability(cap)) throw invalid();
|
||||
if (cap.equals("report-status")) report = true;
|
||||
}
|
||||
if (!report || packet(input) != null) throw invalid();
|
||||
ByteArrayOutputStream prefix = new ByteArrayOutputStream();
|
||||
packet(prefix, first);
|
||||
prefix.write("0000".getBytes(StandardCharsets.US_ASCII));
|
||||
return new PushCommand(oldSha, newSha, prefix.toByteArray());
|
||||
}
|
||||
|
||||
public static byte[] receiveAdvertisement(byte[] bytes) throws IOException {
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
|
||||
byte[] service = upstreamPacket(input);
|
||||
if (service == null
|
||||
|| !new String(service, StandardCharsets.US_ASCII)
|
||||
.equals("# service=git-receive-pack\n")
|
||||
|| upstreamPacket(input) != null) throw upstreamInvalid();
|
||||
String main = null;
|
||||
String caps = null;
|
||||
byte[] entry;
|
||||
while ((entry = upstreamPacket(input)) != null) {
|
||||
String line = new String(entry, StandardCharsets.UTF_8).stripTrailing();
|
||||
int nul = line.indexOf('\0');
|
||||
if (nul >= 0) {
|
||||
caps = line.substring(nul + 1);
|
||||
line = line.substring(0, nul);
|
||||
}
|
||||
if (line.matches("[0-9a-fA-F]{40,64} refs/heads/main")) main = line;
|
||||
}
|
||||
if (main == null || caps == null || input.available() != 0) throw upstreamInvalid();
|
||||
StringBuilder filtered = new StringBuilder();
|
||||
for (String cap : caps.split(" ")) if (capability(cap)) filtered.append(cap).append(' ');
|
||||
if (!java.util.Arrays.asList(caps.split(" ")).contains("report-status"))
|
||||
throw upstreamInvalid();
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
packet(output, service);
|
||||
output.write("0000".getBytes(StandardCharsets.US_ASCII));
|
||||
packet(
|
||||
output,
|
||||
(main + "\0" + filtered.toString().trim() + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
output.write("0000".getBytes(StandardCharsets.US_ASCII));
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
public static boolean pushSucceeded(byte[] bytes) throws IOException {
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
|
||||
byte[] unpack = upstreamPacket(input);
|
||||
if (unpack == null) throw upstreamInvalid();
|
||||
String unpackStatus = new String(unpack, StandardCharsets.UTF_8).stripTrailing();
|
||||
byte[] ref = upstreamPacket(input);
|
||||
if (ref == null) throw upstreamInvalid();
|
||||
String refStatus = new String(ref, StandardCharsets.UTF_8).stripTrailing();
|
||||
if (!unpackStatus.startsWith("unpack ")
|
||||
|| !(refStatus.equals("ok refs/heads/main")
|
||||
|| refStatus.startsWith("ng refs/heads/main "))
|
||||
|| upstreamPacket(input) != null
|
||||
|| input.available() != 0) throw upstreamInvalid();
|
||||
return unpackStatus.equals("unpack ok") && refStatus.equals("ok refs/heads/main");
|
||||
}
|
||||
|
||||
private static byte[] upstreamPacket(InputStream input) throws IOException {
|
||||
try {
|
||||
return packet(input);
|
||||
} catch (BusinessException error) {
|
||||
throw upstreamInvalid();
|
||||
}
|
||||
}
|
||||
|
||||
public static BusinessException invalid() {
|
||||
return new BusinessException(400, "GIT_COMMAND_REJECTED", "仅支持一次 main 更新,禁止删除、其他引用及扩展推送选项");
|
||||
}
|
||||
|
||||
public static BusinessException upstreamInvalid() {
|
||||
return new BusinessException(502, "GIT_UPSTREAM_ERROR", "Git 上游响应不完整或格式异常");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.common.state.TransientStateStore;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
@Component
|
||||
public class GitLimits {
|
||||
private final TransientStateStore state;
|
||||
private final GitGatewayProperties properties;
|
||||
private final Semaphore reads;
|
||||
private final Semaphore pushes;
|
||||
private final Semaphore lfs;
|
||||
|
||||
public GitLimits(TransientStateStore state, GitGatewayProperties properties) {
|
||||
this.state = state;
|
||||
this.properties = properties;
|
||||
reads = new Semaphore(properties.getReadConcurrent());
|
||||
pushes = new Semaphore(properties.getPushConcurrent());
|
||||
lfs = new Semaphore(properties.getLfsConcurrent());
|
||||
}
|
||||
|
||||
public void authenticationAllowed(String ip) {
|
||||
String count =
|
||||
state.get("git:auth:" + com.linkerbot.vibemake.common.SecurityHashes.sha256(ip));
|
||||
if (count != null && Long.parseLong(count) >= properties.getAuthFailuresPerMinute())
|
||||
throw busy();
|
||||
}
|
||||
|
||||
public void authenticationFailed(String ip) {
|
||||
state.increment(
|
||||
"git:auth:" + com.linkerbot.vibemake.common.SecurityHashes.sha256(ip),
|
||||
Duration.ofMinutes(1),
|
||||
false);
|
||||
}
|
||||
|
||||
public void request(GitAccess access, boolean isLfs) {
|
||||
int maximum =
|
||||
isLfs ? properties.getLfsRequestsPerMinute() : properties.getGitRequestsPerMinute();
|
||||
if (state.increment(
|
||||
"git:rate:" + (isLfs ? "lfs:" : "git:") + access.userCode(),
|
||||
Duration.ofMinutes(1),
|
||||
false)
|
||||
.count()
|
||||
> maximum) throw busy();
|
||||
}
|
||||
|
||||
public AutoCloseable acquire(boolean push, boolean isLfs) {
|
||||
Semaphore pool = isLfs ? lfs : push ? pushes : reads;
|
||||
if (!pool.tryAcquire()) throw busy();
|
||||
return pool::release;
|
||||
}
|
||||
|
||||
private BusinessException busy() {
|
||||
return new BusinessException(429, "GIT_BUSY", "Git/LFS 请求过于频繁或服务繁忙,请稍后重试");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.bean.entity.Project;
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.service.ProjectService;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
import com.linkerbot.vibemake.service.gitea.GiteaClient;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GitPolicy {
|
||||
private final GiteaClient gitea;
|
||||
private final ProjectService projects;
|
||||
private final GitTransport transport;
|
||||
private final GitGatewayProperties properties;
|
||||
private final ObjectMapper json;
|
||||
|
||||
public void ensure(Project project) {
|
||||
identity(project);
|
||||
gitea.ensureGitProtection(projects.repository(project), properties.getUpstreamUsername());
|
||||
}
|
||||
|
||||
public void provision(Project project) {
|
||||
identity(project);
|
||||
gitea.ensureGitAccess(projects.repository(project), properties.getUpstreamUsername());
|
||||
}
|
||||
|
||||
public void verify(Project project) {
|
||||
identity(project);
|
||||
gitea.verifyGitProtection(projects.repository(project), properties.getUpstreamUsername());
|
||||
}
|
||||
|
||||
private void identity(Project project) {
|
||||
try (GitTransport.Budget budget = transport.budget();
|
||||
GitTransport.Response response =
|
||||
transport.exchange(
|
||||
"/api/v1/user",
|
||||
"GET",
|
||||
null,
|
||||
-1,
|
||||
Map.of("Accept", "application/json"),
|
||||
budget)) {
|
||||
if (response.status() != 200) throw invalid();
|
||||
JsonNode user =
|
||||
json.readTree(
|
||||
GitIo.metadata(response.input(), properties.getMaxMetadataBytes()));
|
||||
if (user == null
|
||||
|| !properties.getUpstreamUsername().equals(user.path("login").asText())
|
||||
|| !user.has("is_admin")
|
||||
|| user.path("is_admin").asBoolean()) throw invalid();
|
||||
GiteaClient.RemoteRepository remote = gitea.inspect(project.getGiteaRepoName());
|
||||
if (!java.util.Objects.equals(project.getGiteaRepoId(), remote.id())
|
||||
|| !project.getGiteaOwner().equals(remote.owner())
|
||||
|| !project.getGiteaRepoName().equals(remote.name())
|
||||
|| !remote.privateRepo()
|
||||
|| remote.mirror()
|
||||
|| remote.empty()
|
||||
|| !"main".equals(remote.defaultBranch()))
|
||||
throw new BusinessException(
|
||||
503, "GIT_POLICY_UNAVAILABLE", "Git 仓库身份或 main 配置不兼容,请联系管理员");
|
||||
budget.check();
|
||||
} catch (IOException error) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessException invalid() {
|
||||
return new BusinessException(503, "GIT_POLICY_UNAVAILABLE", "Git 必须配置身份匹配的独立非管理员技术账号");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.linkerbot.vibemake.bean.GitContracts.*;
|
||||
import com.linkerbot.vibemake.bean.entity.Project;
|
||||
import com.linkerbot.vibemake.bean.entity.ProjectGitToken;
|
||||
import com.linkerbot.vibemake.bean.entity.User;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.service.ProjectService;
|
||||
import com.linkerbot.vibemake.service.UserService;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
import com.linkerbot.vibemake.service.mapper.ProjectGitTokenMapper;
|
||||
import com.linkerbot.vibemake.service.support.ProjectLocks;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GitTokens {
|
||||
private static final Logger log = LoggerFactory.getLogger(GitTokens.class);
|
||||
private final ProjectGitTokenMapper tokens;
|
||||
private final ProjectService projects;
|
||||
private final UserService users;
|
||||
private final ProjectLocks locks;
|
||||
private final GitPolicy policy;
|
||||
private final GitGatewayProperties properties;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public void enabled() {
|
||||
if (!properties.isEnabled())
|
||||
throw new BusinessException(503, "GIT_UNAVAILABLE", "Git 接入尚未启用");
|
||||
}
|
||||
|
||||
public IssuedToken issue(long userId, String code, TokenInput input) {
|
||||
enabled();
|
||||
return locks.serial(
|
||||
code,
|
||||
() -> {
|
||||
Project project = projects.readyOwner(userId, code);
|
||||
User user = users.require(userId);
|
||||
requireRole(user);
|
||||
LocalDateTime now = ProjectSupport.now();
|
||||
long active =
|
||||
tokens.selectCount(
|
||||
new LambdaQueryWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getProjectCode, code)
|
||||
.eq(ProjectGitToken::getOwnerUserId, userId)
|
||||
.eq(
|
||||
ProjectGitToken::getSessionVersion,
|
||||
user.getSessionVersion())
|
||||
.isNull(ProjectGitToken::getRevokedAt)
|
||||
.gt(ProjectGitToken::getExpiresAt, now));
|
||||
if (active >= properties.getMaxActiveTokens())
|
||||
throw BusinessException.conflict("有效 Git 凭据已达上限,请先撤销旧凭据");
|
||||
policy.provision(project);
|
||||
if (input.scope() == Scope.READ_WRITE) policy.ensure(project);
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String secret =
|
||||
"vbg_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
ProjectGitToken token = new ProjectGitToken();
|
||||
token.setTokenCode(Codes.next());
|
||||
token.setProjectCode(code);
|
||||
token.setOwnerUserId(userId);
|
||||
token.setTokenName(input.name().trim());
|
||||
token.setTokenHash(SecurityHashes.sha256(secret));
|
||||
token.setPermission(input.scope().name());
|
||||
token.setSessionVersion(user.getSessionVersion());
|
||||
token.setExpiresAt(
|
||||
now.plusDays(
|
||||
input.expiresInDays() == null ? 90 : input.expiresInDays()));
|
||||
token.setCreatedAt(now);
|
||||
token.setUpdatedAt(now);
|
||||
tokens.insert(token);
|
||||
log.info(
|
||||
"Git 凭据创建 projectCode={} userCode={} tokenCode={} permission={}",
|
||||
code,
|
||||
user.getUserCode(),
|
||||
token.getTokenCode(),
|
||||
token.getPermission());
|
||||
return new IssuedToken(view(token, user.getSessionVersion()), secret);
|
||||
});
|
||||
}
|
||||
|
||||
public PageResponse<TokenView> list(long userId, String code, long page, long size) {
|
||||
projects.owner(userId, code);
|
||||
if (page < 1 || page > 100000 || size < 1 || size > 100)
|
||||
throw BusinessException.badRequest("分页参数不合法");
|
||||
long version = users.require(userId).getSessionVersion();
|
||||
Page<ProjectGitToken> result =
|
||||
tokens.selectPage(
|
||||
new Page<>(page, size),
|
||||
new LambdaQueryWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getProjectCode, code)
|
||||
.eq(ProjectGitToken::getOwnerUserId, userId)
|
||||
.orderByDesc(ProjectGitToken::getCreatedAt)
|
||||
.orderByDesc(ProjectGitToken::getTokenCode));
|
||||
return new PageResponse<>(
|
||||
result.getRecords().stream().map(token -> view(token, version)).toList(),
|
||||
page,
|
||||
size,
|
||||
result.getTotal());
|
||||
}
|
||||
|
||||
public void revoke(long userId, String code, String tokenCode) {
|
||||
projects.owner(userId, code);
|
||||
ProjectGitToken token =
|
||||
tokens.selectOne(
|
||||
new LambdaQueryWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getTokenCode, tokenCode)
|
||||
.eq(ProjectGitToken::getProjectCode, code)
|
||||
.eq(ProjectGitToken::getOwnerUserId, userId));
|
||||
if (token == null) throw BusinessException.notFound();
|
||||
LocalDateTime now = ProjectSupport.now();
|
||||
tokens.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getTokenCode, tokenCode)
|
||||
.isNull(ProjectGitToken::getRevokedAt)
|
||||
.set(ProjectGitToken::getRevokedAt, now)
|
||||
.set(ProjectGitToken::getUpdatedAt, now));
|
||||
log.info("Git 凭据撤销 projectCode={} tokenCode={}", code, tokenCode);
|
||||
}
|
||||
|
||||
public GitAccess authenticate(String username, String secret, String code) {
|
||||
enabled();
|
||||
if (secret == null || !secret.matches("vbg_[A-Za-z0-9_-]{43}")) throw unauthorized();
|
||||
ProjectGitToken token =
|
||||
tokens.selectOne(
|
||||
new LambdaQueryWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getTokenHash, SecurityHashes.sha256(secret)));
|
||||
GitAccess access = validate(token, code);
|
||||
if (!access.userCode().equals(username)) throw unauthorized();
|
||||
touch(token);
|
||||
return access;
|
||||
}
|
||||
|
||||
public GitAccess recheck(GitAccess access) {
|
||||
enabled();
|
||||
ProjectGitToken token =
|
||||
tokens.selectOne(
|
||||
new LambdaQueryWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getTokenCode, access.tokenCode()));
|
||||
GitAccess current = validate(token, access.projectCode());
|
||||
if (current.userId() != access.userId()) throw unauthorized();
|
||||
return current;
|
||||
}
|
||||
|
||||
private GitAccess validate(ProjectGitToken token, String code) {
|
||||
if (token == null
|
||||
|| token.getRevokedAt() != null
|
||||
|| !token.getExpiresAt().isAfter(ProjectSupport.now())) throw unauthorized();
|
||||
if (!token.getProjectCode().equals(code)) throw BusinessException.notFound();
|
||||
User user = users.require(token.getOwnerUserId());
|
||||
requireRole(user);
|
||||
if (!user.getSessionVersion().equals(token.getSessionVersion())) throw unauthorized();
|
||||
projects.readyOwner(user.getId(), code);
|
||||
if (!"READ_ONLY".equals(token.getPermission())
|
||||
&& !"READ_WRITE".equals(token.getPermission())) throw unauthorized();
|
||||
return new GitAccess(
|
||||
user.getId(),
|
||||
user.getUserCode(),
|
||||
token.getTokenCode(),
|
||||
code,
|
||||
"READ_WRITE".equals(token.getPermission()));
|
||||
}
|
||||
|
||||
private void touch(ProjectGitToken token) {
|
||||
LocalDateTime now = ProjectSupport.now();
|
||||
tokens.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<ProjectGitToken>()
|
||||
.eq(ProjectGitToken::getTokenCode, token.getTokenCode())
|
||||
.and(
|
||||
query ->
|
||||
query.isNull(ProjectGitToken::getLastUsedAt)
|
||||
.or()
|
||||
.lt(
|
||||
ProjectGitToken::getLastUsedAt,
|
||||
now.minusMinutes(5)))
|
||||
.set(ProjectGitToken::getLastUsedAt, now));
|
||||
}
|
||||
|
||||
private void requireRole(User user) {
|
||||
if (!"USER".equals(user.getRole()) && !"ADMIN".equals(user.getRole())) throw unauthorized();
|
||||
}
|
||||
|
||||
private TokenView view(ProjectGitToken token, long version) {
|
||||
String status =
|
||||
token.getRevokedAt() != null || token.getSessionVersion() != version
|
||||
? "REVOKED"
|
||||
: token.getExpiresAt().isAfter(ProjectSupport.now()) ? "ACTIVE" : "EXPIRED";
|
||||
return new TokenView(
|
||||
token.getTokenCode(),
|
||||
token.getTokenName(),
|
||||
Scope.valueOf(token.getPermission()),
|
||||
status,
|
||||
token.getCreatedAt(),
|
||||
token.getExpiresAt(),
|
||||
token.getRevokedAt(),
|
||||
token.getLastUsedAt());
|
||||
}
|
||||
|
||||
public static BusinessException unauthorized() {
|
||||
return new BusinessException(401, "GIT_UNAUTHORIZED", "请使用网站用户编码和有效的项目 Git Token");
|
||||
}
|
||||
|
||||
public static void requireWrite(GitAccess access) {
|
||||
if (!access.writable()) throw new BusinessException(403, "GIT_READ_ONLY", "该 Git 凭据仅允许读取");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
import com.linkerbot.vibemake.service.config.VibemakeProperties;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/** 仅访问配置的 Gitea;请求正文与响应正文都不落盘、不完整缓冲。 */
|
||||
@Component
|
||||
public class GitTransport implements AutoCloseable {
|
||||
private final GitGatewayProperties properties;
|
||||
private final VibemakeProperties config;
|
||||
private final HttpClient http;
|
||||
private final ScheduledThreadPoolExecutor timers =
|
||||
new ScheduledThreadPoolExecutor(
|
||||
2, Thread.ofPlatform().daemon().name("git-budget-", 0).factory());
|
||||
|
||||
public GitTransport(GitGatewayProperties properties, VibemakeProperties config) {
|
||||
timers.setRemoveOnCancelPolicy(true);
|
||||
this.properties = properties;
|
||||
this.config = config;
|
||||
this.http =
|
||||
HttpClient.newBuilder()
|
||||
.connectTimeout(config.getGitea().getConnectTimeout())
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
}
|
||||
|
||||
public final class Budget implements AutoCloseable {
|
||||
private final long deadline = System.nanoTime() + properties.getTimeout().toNanos();
|
||||
private final Set<AutoCloseable> resources = ConcurrentHashMap.newKeySet();
|
||||
private final Set<AutoCloseable> timeoutResources = ConcurrentHashMap.newKeySet();
|
||||
private final AtomicBoolean expired = new AtomicBoolean();
|
||||
private final ScheduledFuture<?> timer;
|
||||
|
||||
private Budget() {
|
||||
timer =
|
||||
timers.schedule(
|
||||
() -> {
|
||||
expired.set(true);
|
||||
for (AutoCloseable resource : resources)
|
||||
Thread.startVirtualThread(() -> closeQuietly(resource));
|
||||
for (AutoCloseable resource : timeoutResources)
|
||||
Thread.startVirtualThread(() -> closeQuietly(resource));
|
||||
},
|
||||
properties.getTimeout().toNanos(),
|
||||
TimeUnit.NANOSECONDS);
|
||||
}
|
||||
|
||||
public void check() {
|
||||
if (expired.get() || System.nanoTime() - deadline >= 0) throw timeout();
|
||||
}
|
||||
|
||||
public void register(AutoCloseable resource) {
|
||||
resources.add(resource);
|
||||
if (expired.get()) {
|
||||
closeQuietly(resource);
|
||||
throw timeout();
|
||||
}
|
||||
}
|
||||
|
||||
public void onTimeout(AutoCloseable resource) {
|
||||
timeoutResources.add(resource);
|
||||
if (expired.get()) {
|
||||
closeQuietly(resource);
|
||||
throw timeout();
|
||||
}
|
||||
}
|
||||
|
||||
public java.time.Duration remaining() {
|
||||
check();
|
||||
return java.time.Duration.ofNanos(Math.max(1, deadline - System.nanoTime()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
timer.cancel(false);
|
||||
resources.forEach(GitTransport::closeQuietly);
|
||||
resources.clear();
|
||||
timeoutResources.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public record Response(int status, HttpHeaders headers, InputStream input)
|
||||
implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
closeQuietly(input);
|
||||
}
|
||||
}
|
||||
|
||||
public Budget budget() {
|
||||
return new Budget();
|
||||
}
|
||||
|
||||
private static void closeQuietly(AutoCloseable resource) {
|
||||
try {
|
||||
resource.close();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public URI base() {
|
||||
URI base = URI.create(config.getGitea().getBaseUrl().replaceAll("/+$", ""));
|
||||
if (!("http".equals(base.getScheme()) || "https".equals(base.getScheme()))
|
||||
|| base.getHost() == null
|
||||
|| base.getRawUserInfo() != null
|
||||
|| base.getRawQuery() != null
|
||||
|| base.getRawFragment() != null)
|
||||
throw new BusinessException(503, "GIT_UNAVAILABLE", "Git 上游地址配置不合法");
|
||||
return base;
|
||||
}
|
||||
|
||||
public static String encode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
|
||||
public String repositoryPath(com.linkerbot.vibemake.bean.entity.Project project) {
|
||||
return "/"
|
||||
+ encode(project.getGiteaOwner())
|
||||
+ "/"
|
||||
+ encode(project.getGiteaRepoName())
|
||||
+ ".git";
|
||||
}
|
||||
|
||||
public Response exchange(
|
||||
String path,
|
||||
String method,
|
||||
InputStream body,
|
||||
long length,
|
||||
Map<String, String> headers,
|
||||
Budget budget) {
|
||||
return exchange(path, method, body, length, headers, budget, null);
|
||||
}
|
||||
|
||||
public Response exchange(
|
||||
String path,
|
||||
String method,
|
||||
InputStream body,
|
||||
long length,
|
||||
Map<String, String> headers,
|
||||
Budget budget,
|
||||
Map<String, String> actionHeaders) {
|
||||
budget.check();
|
||||
if (!path.startsWith("/")
|
||||
|| path.startsWith("//")
|
||||
|| path.contains("\\")
|
||||
|| path.contains("#")
|
||||
|| path.contains("/../")
|
||||
|| path.contains("/./")) throw GitIo.upstreamInvalid();
|
||||
URI destination = URI.create(base().toString() + path);
|
||||
String basic =
|
||||
Base64.getEncoder()
|
||||
.encodeToString(
|
||||
(properties.getUpstreamUsername()
|
||||
+ ":"
|
||||
+ properties.getUpstreamToken())
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
HttpRequest.Builder builder =
|
||||
HttpRequest.newBuilder(destination)
|
||||
.timeout(budget.remaining())
|
||||
.header("Authorization", "Basic " + basic);
|
||||
headers.forEach(builder::setHeader);
|
||||
if (actionHeaders != null) actionHeaders.forEach(builder::setHeader);
|
||||
HttpRequest.BodyPublisher publisher = HttpRequest.BodyPublishers.noBody();
|
||||
if (body != null) {
|
||||
budget.register(body);
|
||||
publisher = HttpRequest.BodyPublishers.ofInputStream(() -> body);
|
||||
if (length > 0) publisher = HttpRequest.BodyPublishers.fromPublisher(publisher, length);
|
||||
}
|
||||
CompletableFuture<HttpResponse<InputStream>> future =
|
||||
http.sendAsync(
|
||||
builder.method(method, publisher).build(),
|
||||
HttpResponse.BodyHandlers.ofInputStream());
|
||||
budget.register(() -> future.cancel(true));
|
||||
try {
|
||||
HttpResponse<InputStream> response =
|
||||
future.get(budget.remaining().toNanos(), TimeUnit.NANOSECONDS);
|
||||
budget.register(response.body());
|
||||
budget.check();
|
||||
if (response.statusCode() >= 300 && response.statusCode() < 400)
|
||||
throw GitIo.upstreamInvalid();
|
||||
return new Response(
|
||||
response.statusCode(), response.headers(), checked(response.body(), budget));
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw timeout();
|
||||
} catch (TimeoutException error) {
|
||||
future.cancel(true);
|
||||
throw timeout();
|
||||
} catch (ExecutionException | CancellationException error) {
|
||||
budget.check();
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
}
|
||||
|
||||
private InputStream checked(InputStream input, Budget budget) {
|
||||
return new FilterInputStream(input) {
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
byte[] b = new byte[1];
|
||||
return read(b, 0, 1) < 0 ? -1 : b[0] & 255;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
budget.check();
|
||||
try {
|
||||
int size = super.read(bytes, offset, length);
|
||||
budget.check();
|
||||
return size;
|
||||
} catch (IOException error) {
|
||||
budget.check();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static BusinessException timeout() {
|
||||
return new BusinessException(504, "GIT_TIMEOUT", "Git/LFS 请求超时;涉及推送请先刷新工作区核对结果");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@Override
|
||||
public void close() {
|
||||
timers.shutdownNow();
|
||||
http.shutdownNow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
package com.linkerbot.vibemake.service.git;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.*;
|
||||
import com.linkerbot.vibemake.bean.entity.Project;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.common.state.TransientStateStore;
|
||||
import com.linkerbot.vibemake.service.ProjectService;
|
||||
import com.linkerbot.vibemake.service.config.GitGatewayProperties;
|
||||
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.security.*;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LfsGateway {
|
||||
public static final String MEDIA = "application/vnd.git-lfs+json";
|
||||
private static final Logger log = LoggerFactory.getLogger(LfsGateway.class);
|
||||
private final GitTokens tokens;
|
||||
private final GitTransport transport;
|
||||
private final GitGatewayProperties properties;
|
||||
private final ProjectService projects;
|
||||
private final TransientStateStore state;
|
||||
private final ObjectMapper json;
|
||||
private final GitLimits limits;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public record Action(
|
||||
GitAccess access,
|
||||
String hash,
|
||||
String oid,
|
||||
long size,
|
||||
String method,
|
||||
String path,
|
||||
Map<String, String> headers,
|
||||
Instant expiresAt) {}
|
||||
|
||||
public Action authenticate(String code, String projectCode, String bearer, String method) {
|
||||
if (!code.matches("[a-f0-9]{32}") || bearer == null || !bearer.matches("[A-Za-z0-9_-]{43}"))
|
||||
throw GitTokens.unauthorized();
|
||||
String stored = state.get("git:lfs-action:" + code);
|
||||
try {
|
||||
Action action = stored == null ? null : json.readValue(stored, Action.class);
|
||||
if (action == null
|
||||
|| !MessageDigest.isEqual(
|
||||
action.hash().getBytes(java.nio.charset.StandardCharsets.US_ASCII),
|
||||
SecurityHashes.sha256(bearer)
|
||||
.getBytes(java.nio.charset.StandardCharsets.US_ASCII))
|
||||
|| !action.expiresAt().isAfter(Instant.now())
|
||||
|| !action.access().projectCode().equals(projectCode)
|
||||
|| !action.method().equals(method)) throw GitTokens.unauthorized();
|
||||
GitAccess access = tokens.recheck(action.access());
|
||||
if (!"GET".equals(method)) GitTokens.requireWrite(access);
|
||||
return action;
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException error) {
|
||||
throw GitTokens.unauthorized();
|
||||
}
|
||||
}
|
||||
|
||||
public void serve(
|
||||
GitAccess access,
|
||||
String endpoint,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
throws IOException {
|
||||
try (AutoCloseable permit = limits.acquire(false, true);
|
||||
GitTransport.Budget budget = transport.budget()) {
|
||||
budget.register(request.getInputStream());
|
||||
budget.onTimeout(
|
||||
() -> {
|
||||
if (response.isCommitted()) response.getOutputStream().close();
|
||||
});
|
||||
if ("locks/verify".equals(endpoint) && "POST".equals(request.getMethod())) {
|
||||
GitIo.metadata(
|
||||
GitGateway.decoded(request, properties.getMaxMetadataBytes(), budget),
|
||||
properties.getMaxMetadataBytes());
|
||||
ObjectNode emptyLocks = json.createObjectNode();
|
||||
emptyLocks.set("ours", json.createArrayNode());
|
||||
emptyLocks.set("theirs", json.createArrayNode());
|
||||
write(response, emptyLocks);
|
||||
return;
|
||||
}
|
||||
if (!"objects/batch".equals(endpoint) || !"POST".equals(request.getMethod()))
|
||||
throw new BusinessException(501, "LFS_LOCKS_UNSUPPORTED", "暂不支持 LFS 文件锁或该协议接口");
|
||||
GitGateway.requireContentType(request, MEDIA);
|
||||
JsonNode input = clientJson(request, budget);
|
||||
if (input == null || !input.isObject()) throw invalid();
|
||||
String operation = input.path("operation").asText();
|
||||
if (!("upload".equals(operation) || "download".equals(operation))) throw invalid();
|
||||
if ("upload".equals(operation)) GitTokens.requireWrite(access);
|
||||
JsonNode objects = input.path("objects");
|
||||
if (!objects.isArray()
|
||||
|| objects.isEmpty()
|
||||
|| objects.size() > properties.getMaxBatchObjects()) throw invalid();
|
||||
Map<String, Long> requested = new HashMap<>();
|
||||
for (JsonNode object : objects) {
|
||||
String oid = object.path("oid").asText();
|
||||
long size = object.path("size").asLong(-1);
|
||||
if (!oid.matches("[a-f0-9]{64}")
|
||||
|| !object.path("size").isIntegralNumber()
|
||||
|| !object.path("size").canConvertToLong()
|
||||
|| size < 0) throw invalid();
|
||||
if (size > properties.getMaxLfsObjectBytes())
|
||||
throw new BusinessException(413, "LFS_TOO_LARGE", "LFS 对象超过大小限制");
|
||||
if (requested.put(oid, size) != null) throw invalid();
|
||||
}
|
||||
// 明确协商 Basic Transfer;不向上游传入客户端自定义 transfer、ref 或 action。
|
||||
ObjectNode sanitized = json.createObjectNode().put("operation", operation);
|
||||
sanitized.set("objects", objects);
|
||||
sanitized.putArray("transfers").add("basic");
|
||||
Project project = projects.readyOwner(access.userId(), access.projectCode());
|
||||
byte[] body = json.writeValueAsBytes(sanitized);
|
||||
try (GitTransport.Response upstream =
|
||||
transport.exchange(
|
||||
transport.repositoryPath(project) + "/info/lfs/objects/batch",
|
||||
"POST",
|
||||
new ByteArrayInputStream(body),
|
||||
body.length,
|
||||
Map.of("Accept", MEDIA, "Content-Type", MEDIA),
|
||||
budget)) {
|
||||
GitGateway.requireSuccess(upstream, MEDIA);
|
||||
JsonNode result =
|
||||
json.readTree(
|
||||
GitIo.metadata(upstream.input(), properties.getMaxMetadataBytes()));
|
||||
if (result == null
|
||||
|| !result.path("objects").isArray()
|
||||
|| result.path("objects").size() != requested.size()
|
||||
|| !"basic".equals(result.path("transfer").asText("basic")))
|
||||
throw GitIo.upstreamInvalid();
|
||||
ObjectNode output = json.createObjectNode().put("transfer", "basic");
|
||||
ArrayNode results = output.putArray("objects");
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (JsonNode object : result.path("objects")) {
|
||||
String oid = object.path("oid").asText();
|
||||
Long size = requested.get(oid);
|
||||
if (size == null
|
||||
|| !seen.add(oid)
|
||||
|| !object.path("size").isIntegralNumber()
|
||||
|| !object.path("size").canConvertToLong()
|
||||
|| object.path("size").asLong(-1) != size)
|
||||
throw GitIo.upstreamInvalid();
|
||||
ObjectNode target =
|
||||
results.addObject()
|
||||
.put("oid", oid)
|
||||
.put("size", size)
|
||||
.put("authenticated", true);
|
||||
if (object.has("error")) {
|
||||
// 上游错误正文可能含内部地址,仅返回固定文本与错误码。
|
||||
target.putObject("error")
|
||||
.put("code", object.path("error").path("code").asInt(502))
|
||||
.put("message", "LFS 对象不可用");
|
||||
continue;
|
||||
}
|
||||
JsonNode actions = object.path("actions");
|
||||
if (actions.isObject()) {
|
||||
ObjectNode rewritten = target.putObject("actions");
|
||||
Iterator<String> names = actions.fieldNames();
|
||||
while (names.hasNext()) {
|
||||
String name = names.next();
|
||||
if (!(name.equals(operation)
|
||||
|| name.equals("verify") && operation.equals("upload")))
|
||||
throw GitIo.upstreamInvalid();
|
||||
rewritten.set(
|
||||
name,
|
||||
issue(access, project, oid, size, name, actions.get(name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
write(response, output);
|
||||
log.info(
|
||||
"LFS batch 完成 projectCode={} userCode={} tokenCode={} operation={}"
|
||||
+ " objects={}",
|
||||
access.projectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
operation,
|
||||
requested.size());
|
||||
}
|
||||
} catch (BusinessException | IOException error) {
|
||||
throw error;
|
||||
} catch (Exception error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode issue(
|
||||
GitAccess access, Project project, String oid, long size, String name, JsonNode source)
|
||||
throws IOException {
|
||||
String expectedPath =
|
||||
transport.base().getRawPath()
|
||||
+ transport.repositoryPath(project)
|
||||
+ "/info/lfs/"
|
||||
+ (name.equals("verify")
|
||||
? "verify"
|
||||
: "objects/" + oid + (name.equals("upload") ? "/" + size : ""));
|
||||
URI uri;
|
||||
try {
|
||||
uri = URI.create(source.path("href").asText());
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
URI base = transport.base();
|
||||
if (!Objects.equals(base.getScheme(), uri.getScheme())
|
||||
|| !Objects.equals(base.getHost(), uri.getHost())
|
||||
|| base.getPort() != uri.getPort()
|
||||
|| uri.getRawUserInfo() != null
|
||||
|| uri.getRawQuery() != null
|
||||
|| uri.getRawFragment() != null
|
||||
|| !expectedPath.equals(uri.getRawPath())) throw GitIo.upstreamInvalid();
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
JsonNode sourceHeaders = source.path("header");
|
||||
if (sourceHeaders.isObject()) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = sourceHeaders.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
// Gitea 原生上传 action 会给出此 hop-by-hop 提示。网关使用自己的
|
||||
// BodyPublisher 决定传输方式,不能把上游的 Transfer-Encoding 直接设置到 JDK 客户端。
|
||||
if (name.equals("upload")
|
||||
&& field.getKey().equalsIgnoreCase("Transfer-Encoding")
|
||||
&& field.getValue().isTextual()
|
||||
&& "chunked".equalsIgnoreCase(field.getValue().asText())) continue;
|
||||
if (!Set.of("authorization", "accept", "content-type")
|
||||
.contains(field.getKey().toLowerCase(Locale.ROOT))
|
||||
|| !field.getValue().isTextual()
|
||||
|| field.getValue().asText().length() > 8192
|
||||
|| field.getValue().asText().contains("\n")
|
||||
|| field.getValue().asText().contains("\r")) throw GitIo.upstreamInvalid();
|
||||
headers.put(field.getKey(), field.getValue().asText());
|
||||
}
|
||||
}
|
||||
long ttl = 900;
|
||||
if (source.has("expires_in")) ttl = Math.min(ttl, source.path("expires_in").asLong(0));
|
||||
if (source.has("expires_at")) {
|
||||
try {
|
||||
ttl =
|
||||
Math.min(
|
||||
ttl,
|
||||
Duration.between(
|
||||
Instant.now(),
|
||||
Instant.parse(source.path("expires_at").asText()))
|
||||
.getSeconds());
|
||||
} catch (java.time.format.DateTimeParseException error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
}
|
||||
if (ttl < 1) throw GitIo.upstreamInvalid();
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
String code = Codes.next();
|
||||
String method = name.equals("download") ? "GET" : name.equals("upload") ? "PUT" : "POST";
|
||||
String path =
|
||||
transport.repositoryPath(project)
|
||||
+ "/info/lfs/"
|
||||
+ (name.equals("verify")
|
||||
? "verify"
|
||||
: "objects/" + oid + (name.equals("upload") ? "/" + size : ""));
|
||||
Action action =
|
||||
new Action(
|
||||
access,
|
||||
SecurityHashes.sha256(secret),
|
||||
oid,
|
||||
size,
|
||||
method,
|
||||
path,
|
||||
headers,
|
||||
Instant.now().plusSeconds(ttl));
|
||||
if (!state.putIfAbsent(
|
||||
"git:lfs-action:" + code, json.writeValueAsString(action), Duration.ofSeconds(ttl)))
|
||||
throw GitIo.upstreamInvalid();
|
||||
ObjectNode result =
|
||||
json.createObjectNode()
|
||||
.put(
|
||||
"href",
|
||||
properties.getPublicBaseUrl()
|
||||
+ "/projects/"
|
||||
+ access.projectCode()
|
||||
+ ".git/info/lfs/actions/"
|
||||
+ code)
|
||||
.put("expires_in", ttl);
|
||||
result.putObject("header").put("Authorization", "Bearer " + secret);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void action(Action action, HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException {
|
||||
long started = System.nanoTime();
|
||||
java.util.concurrent.atomic.AtomicLong transferred =
|
||||
new java.util.concurrent.atomic.AtomicLong();
|
||||
Project project =
|
||||
projects.readyOwner(action.access().userId(), action.access().projectCode());
|
||||
String expectedPath =
|
||||
transport.repositoryPath(project)
|
||||
+ "/info/lfs/"
|
||||
+ (action.method().equals("POST")
|
||||
? "verify"
|
||||
: "objects/"
|
||||
+ action.oid()
|
||||
+ (action.method().equals("PUT")
|
||||
? "/" + action.size()
|
||||
: ""));
|
||||
if (!expectedPath.equals(action.path())) throw GitTokens.unauthorized();
|
||||
try (AutoCloseable permit = limits.acquire(false, true);
|
||||
GitTransport.Budget budget = transport.budget()) {
|
||||
budget.register(request.getInputStream());
|
||||
budget.onTimeout(
|
||||
() -> {
|
||||
if (response.isCommitted()) response.getOutputStream().close();
|
||||
});
|
||||
InputStream body = null;
|
||||
long length = -1;
|
||||
String type = "application/octet-stream";
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
if (action.method().equals("PUT")) {
|
||||
if (request.getContentLengthLong() >= 0
|
||||
&& request.getContentLengthLong() != action.size()) throw invalid();
|
||||
if (request.getHeader("Content-Encoding") != null) throw invalid();
|
||||
body =
|
||||
new DigestInputStream(
|
||||
GitIo.counted(
|
||||
GitIo.limited(request.getInputStream(), action.size()),
|
||||
transferred),
|
||||
digest);
|
||||
length = action.size();
|
||||
} else if (action.method().equals("POST")) {
|
||||
JsonNode verification = clientJson(request, budget);
|
||||
if (verification == null
|
||||
|| !action.oid().equals(verification.path("oid").asText())
|
||||
|| !verification.path("size").isIntegralNumber()
|
||||
|| !verification.path("size").canConvertToLong()
|
||||
|| verification.path("size").asLong(-1) != action.size()) throw invalid();
|
||||
byte[] bytes =
|
||||
json.writeValueAsBytes(Map.of("oid", action.oid(), "size", action.size()));
|
||||
body = new ByteArrayInputStream(bytes);
|
||||
length = bytes.length;
|
||||
transferred.set(bytes.length);
|
||||
type = MEDIA;
|
||||
}
|
||||
try (GitTransport.Response upstream =
|
||||
transport.exchange(
|
||||
action.path(),
|
||||
action.method(),
|
||||
body,
|
||||
length,
|
||||
Map.of("Accept", MEDIA, "Content-Type", type),
|
||||
budget,
|
||||
action.headers())) {
|
||||
if (upstream.status() < 200 || upstream.status() >= 300)
|
||||
throw GitIo.upstreamInvalid();
|
||||
if (action.method().equals("GET")) {
|
||||
long size = upstream.headers().firstValueAsLong("Content-Length").orElse(-1);
|
||||
if (size >= 0 && size != action.size()) throw GitIo.upstreamInvalid();
|
||||
response.setContentType("application/octet-stream");
|
||||
response.setContentLengthLong(action.size());
|
||||
long copied =
|
||||
GitGateway.copy(
|
||||
new DigestInputStream(upstream.input(), digest),
|
||||
response,
|
||||
action.size(),
|
||||
budget,
|
||||
transferred);
|
||||
if (copied != action.size()
|
||||
|| !HexFormat.of().formatHex(digest.digest()).equals(action.oid()))
|
||||
throw GitIo.upstreamInvalid();
|
||||
} else {
|
||||
GitIo.metadata(upstream.input(), properties.getMaxMetadataBytes());
|
||||
if (action.method().equals("PUT")
|
||||
&& !HexFormat.of().formatHex(digest.digest()).equals(action.oid()))
|
||||
throw invalid();
|
||||
response.setStatus(200);
|
||||
response.setContentType(MEDIA);
|
||||
response.setContentLength(0);
|
||||
}
|
||||
log.info(
|
||||
"LFS action 完成 projectCode={} userCode={} tokenCode={} method={} oid={}"
|
||||
+ " bytes={} durationMs={}",
|
||||
action.access().projectCode(),
|
||||
action.access().userCode(),
|
||||
action.access().tokenCode(),
|
||||
action.method(),
|
||||
action.oid(),
|
||||
transferred.get(),
|
||||
(System.nanoTime() - started) / 1000000);
|
||||
}
|
||||
} catch (BusinessException | IOException error) {
|
||||
log.warn(
|
||||
"LFS action 失败或取消 projectCode={} tokenCode={} method={} oid={} bytes={}"
|
||||
+ " errorType={}",
|
||||
action.access().projectCode(),
|
||||
action.access().tokenCode(),
|
||||
action.method(),
|
||||
action.oid(),
|
||||
transferred.get(),
|
||||
error.getClass().getSimpleName());
|
||||
throw error;
|
||||
} catch (Exception error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode clientJson(HttpServletRequest request, GitTransport.Budget budget)
|
||||
throws IOException {
|
||||
GitGateway.requireContentType(request, MEDIA);
|
||||
byte[] bytes =
|
||||
GitIo.metadata(
|
||||
GitGateway.decoded(request, properties.getMaxMetadataBytes(), budget),
|
||||
properties.getMaxMetadataBytes());
|
||||
try {
|
||||
return json.reader()
|
||||
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.readTree(bytes);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException error) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessException invalid() {
|
||||
return BusinessException.badRequest("LFS 请求的操作、OID、大小或 JSON 不合法");
|
||||
}
|
||||
|
||||
private void write(HttpServletResponse response, JsonNode value) throws IOException {
|
||||
response.setContentType(MEDIA);
|
||||
byte[] bytes = json.writeValueAsBytes(value);
|
||||
response.setContentLength(bytes.length);
|
||||
response.getOutputStream().write(bytes);
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,19 @@ import java.util.List;
|
||||
import java.time.Duration;
|
||||
|
||||
public interface GiteaClient {
|
||||
default void ensureGitAccess(Repository repository, String username) {
|
||||
throw new UnsupportedOperationException("未实现 Git 技术账号仓库授权");
|
||||
}
|
||||
default String authenticatedUsername() { throw new UnsupportedOperationException("未实现服务账号查询"); }
|
||||
|
||||
default void ensureGitProtection(Repository repository, String username) {
|
||||
throw new UnsupportedOperationException("未实现 Git main 保护初始化");
|
||||
}
|
||||
|
||||
default void verifyGitProtection(Repository repository, String username) {
|
||||
throw new UnsupportedOperationException("未实现 Git main 保护核验");
|
||||
}
|
||||
|
||||
record Repository(long id, String owner, String name) {}
|
||||
|
||||
record StoredFile(String path, String blobSha, byte[] bytes) {}
|
||||
|
||||
+45
@@ -49,6 +49,51 @@ public class RestGiteaClient implements GiteaClient {
|
||||
return "/repos/" + encode(repo.owner()) + "/" + encode(repo.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ensureGitAccess(Repository repo, String username) {
|
||||
String path = repoPath(repo) + "/collaborators/" + encode(username);
|
||||
String permission = "none";
|
||||
try { permission = parse(request("GET", path + "/permission", null).body(), false).path("permission").asText(); }
|
||||
catch (GiteaFailure error) { if (error.status() != 404) throw error; }
|
||||
if ("admin".equals(permission) || "owner".equals(permission)) throw gitPolicyFailure();
|
||||
if (!"write".equals(permission)) request("PUT", path, Map.of("permission", "write"));
|
||||
JsonNode current = parse(request("GET", path + "/permission", null).body(), false);
|
||||
if (!"write".equals(current.path("permission").asText())) throw gitPolicyFailure();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ensureGitProtection(Repository repo, String username) {
|
||||
JsonNode rules = parse(request("GET", repoPath(repo) + "/branch_protections", null).body(), false);
|
||||
if (rules.isArray() && rules.isEmpty()) {
|
||||
request("POST", repoPath(repo) + "/branch_protections", Map.of(
|
||||
"branch_name", "main", "rule_name", "main", "enable_push", true, "enable_force_push", false));
|
||||
}
|
||||
verifyGitProtection(repo, username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void verifyGitProtection(Repository repo, String username) {
|
||||
JsonNode permission = parse(request("GET", repoPath(repo) + "/collaborators/"
|
||||
+ encode(username) + "/permission", null).body(), false);
|
||||
if (!"write".equals(permission.path("permission").asText())) throw gitPolicyFailure();
|
||||
JsonNode rules = parse(request("GET", repoPath(repo) + "/branch_protections", null).body(), false);
|
||||
if (!rules.isArray() || rules.size() != 1) throw gitPolicyFailure();
|
||||
JsonNode rule = rules.get(0);
|
||||
String name = rule.path("rule_name").asText(rule.path("branch_name").asText());
|
||||
if (!"main".equals(name) || !rule.path("enable_push").asBoolean()
|
||||
|| !rule.has("enable_force_push") || rule.path("enable_force_push").asBoolean()) throw gitPolicyFailure();
|
||||
if (rule.path("enable_push_whitelist").asBoolean()) {
|
||||
boolean allowed = false;
|
||||
for (JsonNode member : rule.path("push_whitelist_usernames"))
|
||||
if (username.equals(member.asText())) allowed = true;
|
||||
if (!allowed) throw gitPolicyFailure();
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessException gitPolicyFailure() {
|
||||
return new BusinessException(503, "GIT_POLICY_UNAVAILABLE", "main 保护规则或 Git 技术账号权限不兼容,请联系管理员");
|
||||
}
|
||||
|
||||
private String filePath(String path) {
|
||||
return Arrays.stream(path.split("/"))
|
||||
.map(RestGiteaClient::encode)
|
||||
|
||||
+6
@@ -78,6 +78,11 @@ public class ProjectLocks implements AutoCloseable {
|
||||
}
|
||||
|
||||
public <T> T write(String code, Supplier<T> action) {
|
||||
return write(code, () -> {}, action);
|
||||
}
|
||||
|
||||
/** prepare 在写保护检查后、任何远端写入前执行,用于原子持久化协议写入凭据。 */
|
||||
public <T> T write(String code, Runnable prepare, Supplier<T> action) {
|
||||
return serial(
|
||||
code,
|
||||
() -> {
|
||||
@@ -96,6 +101,7 @@ public class ProjectLocks implements AutoCloseable {
|
||||
markUncertain(code);
|
||||
throw blocked();
|
||||
}
|
||||
prepare.run();
|
||||
state(code, "WRITING");
|
||||
writing.get().add(code);
|
||||
try {
|
||||
|
||||
+294
-93
@@ -6,21 +6,26 @@ import com.linkerbot.vibemake.bean.entity.Project;
|
||||
import com.linkerbot.vibemake.bean.entity.RepositoryWriteOperation;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.service.ProjectService;
|
||||
import com.linkerbot.vibemake.service.git.GitAccess;
|
||||
import com.linkerbot.vibemake.service.git.GitIo;
|
||||
import com.linkerbot.vibemake.service.gitea.*;
|
||||
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
|
||||
import com.linkerbot.vibemake.service.mapper.RepositoryWriteOperationMapper;
|
||||
import com.linkerbot.vibemake.service.support.ProjectActors;
|
||||
import com.linkerbot.vibemake.service.support.ProjectLocks;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** 数据库凭据先于远端写入落盘。未知结果只读取核对,绝不自动重发写请求。 */
|
||||
@Service
|
||||
@@ -37,61 +42,87 @@ public class RepositoryWrites {
|
||||
|
||||
public record Request(String code, String digest) {}
|
||||
|
||||
public CommitView execute(long userId, String projectCode, String key, String digest,
|
||||
Function<Request, CommitView> action) {
|
||||
String operationCode = key == null ? Codes.next() : key.replace("-", "").toLowerCase(java.util.Locale.ROOT);
|
||||
public CommitView execute(
|
||||
long userId,
|
||||
String projectCode,
|
||||
String key,
|
||||
String digest,
|
||||
Function<Request, CommitView> action) {
|
||||
String operationCode =
|
||||
key == null
|
||||
? Codes.next()
|
||||
: key.replace("-", "").toLowerCase(java.util.Locale.ROOT);
|
||||
if (!operationCode.matches("[a-f0-9]{32}"))
|
||||
throw BusinessException.badRequest("操作编码必须为 UUID 或 32 位十六进制编码");
|
||||
return locks.serial(projectCode, () -> {
|
||||
projects.readyOwner(userId, projectCode); // 重放也必须重新鉴权。
|
||||
RepositoryWriteOperation previous = operations.selectById(operationCode);
|
||||
if (previous != null) {
|
||||
if (!projectCode.equals(previous.getProjectCode()) || !digest.equals(previous.getRequestDigest()))
|
||||
throw new BusinessException(409, "IDEMPOTENCY_KEY_REUSED", "操作编码已用于不同请求,请勿复用");
|
||||
return replay(previous);
|
||||
}
|
||||
RepositoryWriteOperation pending = active(projectCode);
|
||||
if (pending != null)
|
||||
throw pending(pending);
|
||||
try {
|
||||
CommitView result = action.apply(new Request(operationCode, digest));
|
||||
RepositoryWriteOperation operation = operations.selectById(operationCode);
|
||||
if (operation == null) throw new IllegalStateException("仓库写入缺少持久化凭据");
|
||||
complete(operation, result.commitSha(), "SUCCEEDED");
|
||||
return result;
|
||||
} catch (RuntimeException error) {
|
||||
RepositoryWriteOperation operation = operations.selectById(operationCode);
|
||||
if (operation == null) throw error; // 参数校验、读取失败发生在任何远端写入之前。
|
||||
if (!projectCode.equals(operation.getProjectCode()) || !digest.equals(operation.getRequestDigest()))
|
||||
throw new BusinessException(409, "IDEMPOTENCY_KEY_REUSED", "操作编码已用于不同请求,请勿复用");
|
||||
boolean definite = error instanceof GiteaFailure remote && !remote.uncertain();
|
||||
if (definite) {
|
||||
BusinessException business = (BusinessException) error;
|
||||
operation.setStatus("FAILED");
|
||||
operation.setFailureStatus(business.status());
|
||||
operation.setLastErrorCode(business.code());
|
||||
save(operation);
|
||||
throw error;
|
||||
}
|
||||
locks.markUncertain(projectCode);
|
||||
operation.setLastErrorCode(error instanceof BusinessException business
|
||||
? business.code() : "WRITE_RESULT_UNKNOWN");
|
||||
save(operation);
|
||||
log.warn("仓库写入转后台核对 projectCode={} operationCode={} errorCode={} errorType={}",
|
||||
projectCode, operationCode, operation.getLastErrorCode(), error.getClass().getSimpleName());
|
||||
if (!(error instanceof BusinessException)) SafeExceptionLog.write(log, "仓库提交结果未知", error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
return locks.serial(
|
||||
projectCode,
|
||||
() -> {
|
||||
projects.readyOwner(userId, projectCode); // 重放也必须重新鉴权。
|
||||
RepositoryWriteOperation previous = operations.selectById(operationCode);
|
||||
if (previous != null) {
|
||||
if (!projectCode.equals(previous.getProjectCode())
|
||||
|| !digest.equals(previous.getRequestDigest()))
|
||||
throw new BusinessException(
|
||||
409, "IDEMPOTENCY_KEY_REUSED", "操作编码已用于不同请求,请勿复用");
|
||||
return replay(previous);
|
||||
}
|
||||
RepositoryWriteOperation pending = active(projectCode);
|
||||
if (pending != null) throw pending(pending);
|
||||
try {
|
||||
CommitView result = action.apply(new Request(operationCode, digest));
|
||||
RepositoryWriteOperation operation = operations.selectById(operationCode);
|
||||
if (operation == null) throw new IllegalStateException("仓库写入缺少持久化凭据");
|
||||
complete(operation, result.commitSha(), "SUCCEEDED");
|
||||
return result;
|
||||
} catch (RuntimeException error) {
|
||||
RepositoryWriteOperation operation = operations.selectById(operationCode);
|
||||
if (operation == null) throw error; // 参数校验、读取失败发生在任何远端写入之前。
|
||||
if (!projectCode.equals(operation.getProjectCode())
|
||||
|| !digest.equals(operation.getRequestDigest()))
|
||||
throw new BusinessException(
|
||||
409, "IDEMPOTENCY_KEY_REUSED", "操作编码已用于不同请求,请勿复用");
|
||||
boolean definite =
|
||||
error instanceof GiteaFailure remote && !remote.uncertain();
|
||||
if (definite) {
|
||||
BusinessException business = (BusinessException) error;
|
||||
operation.setStatus("FAILED");
|
||||
operation.setFailureStatus(business.status());
|
||||
operation.setLastErrorCode(business.code());
|
||||
save(operation);
|
||||
throw error;
|
||||
}
|
||||
locks.markUncertain(projectCode);
|
||||
operation.setLastErrorCode(
|
||||
error instanceof BusinessException business
|
||||
? business.code()
|
||||
: "WRITE_RESULT_UNKNOWN");
|
||||
save(operation);
|
||||
log.warn(
|
||||
"仓库写入转后台核对 projectCode={} operationCode={} errorCode={}"
|
||||
+ " errorType={}",
|
||||
projectCode,
|
||||
operationCode,
|
||||
operation.getLastErrorCode(),
|
||||
error.getClass().getSimpleName());
|
||||
if (!(error instanceof BusinessException))
|
||||
SafeExceptionLog.write(log, "仓库提交结果未知", error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 必须在 ProjectLocks.write 内调用;此处是唯一一次发起远端写请求的位置。 */
|
||||
public CommitView commit(Request request, Project project, String baseSha,
|
||||
List<GiteaClient.Change> changes, String message,
|
||||
ProjectActors.Author author) {
|
||||
public CommitView commit(
|
||||
Request request,
|
||||
Project project,
|
||||
String baseSha,
|
||||
List<GiteaClient.Change> changes,
|
||||
String message,
|
||||
ProjectActors.Author author) {
|
||||
GiteaClient.Repository repository = projects.repository(project);
|
||||
RepositoryWriteOperation operation = new RepositoryWriteOperation();
|
||||
operation.setOperationCode(request.code());
|
||||
operation.setOperationKind("WEB_COMMIT");
|
||||
operation.setProjectCode(project.getProjectCode());
|
||||
operation.setRepositoryId(repository.id());
|
||||
operation.setRepositoryOwner(repository.owner());
|
||||
@@ -109,11 +140,20 @@ public class RepositoryWrites {
|
||||
} catch (org.springframework.dao.DuplicateKeyException collision) {
|
||||
throw new BusinessException(409, "IDEMPOTENCY_KEY_REUSED", "操作编码已用于其他请求,请勿复用");
|
||||
}
|
||||
log.info("仓库写入开始 projectCode={} operationCode={} baseCommitSha={} fileCount={}",
|
||||
project.getProjectCode(), request.code(), baseSha, changes.size());
|
||||
log.info(
|
||||
"仓库写入开始 projectCode={} operationCode={} baseCommitSha={} fileCount={}",
|
||||
project.getProjectCode(),
|
||||
request.code(),
|
||||
baseSha,
|
||||
changes.size());
|
||||
try {
|
||||
CommitView result = gitea.commit(repository, changes,
|
||||
message + WriteReceipt.suffix(request.code(), request.digest()), author.nickname(), author.code());
|
||||
CommitView result =
|
||||
gitea.commit(
|
||||
repository,
|
||||
changes,
|
||||
message + WriteReceipt.suffix(request.code(), request.digest()),
|
||||
author.nickname(),
|
||||
author.code());
|
||||
return new CommitView(result.commitSha(), message);
|
||||
} catch (GiteaFailure error) {
|
||||
if (!error.uncertain()) throw error;
|
||||
@@ -126,23 +166,141 @@ public class RepositoryWrites {
|
||||
|
||||
private CommitView replay(RepositoryWriteOperation operation) {
|
||||
return switch (operation.getStatus()) {
|
||||
case "SUCCEEDED" -> new CommitView(operation.getResultCommitSha(), operation.getCommitMessage());
|
||||
case "FAILED" -> throw new BusinessException(operation.getFailureStatus(),
|
||||
operation.getLastErrorCode(), "该操作已被仓库拒绝,请刷新后使用新的操作编码提交");
|
||||
case "SUCCEEDED" ->
|
||||
new CommitView(operation.getResultCommitSha(), operation.getCommitMessage());
|
||||
case "FAILED" ->
|
||||
throw new BusinessException(
|
||||
operation.getFailureStatus(),
|
||||
operation.getLastErrorCode(),
|
||||
"该操作已被仓库拒绝,请刷新后使用新的操作编码提交");
|
||||
default -> throw pending(operation);
|
||||
};
|
||||
}
|
||||
|
||||
private BusinessException pending(RepositoryWriteOperation operation) {
|
||||
return new BusinessException(409, "REMOTE_RESULT_UNKNOWN", "仓库提交结果正在后台核对,请稍后刷新工作区,暂勿重复提交",
|
||||
return new BusinessException(
|
||||
409,
|
||||
"REMOTE_RESULT_UNKNOWN",
|
||||
"仓库提交结果正在后台核对,请稍后刷新工作区,暂勿重复提交",
|
||||
java.util.Map.of("projectCode", operation.getProjectCode()));
|
||||
}
|
||||
|
||||
public RepositoryWriteOperation active(String code) {
|
||||
return operations.selectOne(new LambdaQueryWrapper<RepositoryWriteOperation>()
|
||||
.eq(RepositoryWriteOperation::getProjectCode, code)
|
||||
.in(RepositoryWriteOperation::getStatus, ACTIVE)
|
||||
.orderByDesc(RepositoryWriteOperation::getCreatedAt).last("LIMIT 1"));
|
||||
return operations.selectOne(
|
||||
new LambdaQueryWrapper<RepositoryWriteOperation>()
|
||||
.eq(RepositoryWriteOperation::getProjectCode, code)
|
||||
.in(RepositoryWriteOperation::getStatus, ACTIVE)
|
||||
.orderByDesc(RepositoryWriteOperation::getCreatedAt)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
/** 实时校验、写入以及命名锁释放全部纳入同一结果核对边界。 */
|
||||
public byte[] push(
|
||||
GitAccess access,
|
||||
GitIo.PushCommand command,
|
||||
Supplier<Project> validate,
|
||||
Supplier<byte[]> transfer) {
|
||||
java.util.concurrent.atomic.AtomicReference<RepositoryWriteOperation> registered =
|
||||
new java.util.concurrent.atomic.AtomicReference<>();
|
||||
try {
|
||||
return locks.serial(
|
||||
access.projectCode(),
|
||||
() -> pushLocked(validate.get(), access, command, transfer, registered::set));
|
||||
} catch (RuntimeException error) {
|
||||
RepositoryWriteOperation operation = registered.get();
|
||||
if (operation != null && operations.selectById(operation.getOperationCode()) != null) {
|
||||
locks.markUncertain(access.projectCode());
|
||||
operation.setStatus("PROCESSING");
|
||||
operation.setLastErrorCode(
|
||||
error instanceof BusinessException business
|
||||
? business.code()
|
||||
: "GIT_RESULT_UNKNOWN");
|
||||
save(operation);
|
||||
log.warn(
|
||||
"Git 推送待核对 projectCode={} operationCode={} oldSha={} newSha={}"
|
||||
+ " errorCode={}",
|
||||
access.projectCode(),
|
||||
operation.getOperationCode(),
|
||||
command.oldSha(),
|
||||
command.newSha(),
|
||||
operation.getLastErrorCode());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** 调用者已在共享项目锁中完成实时鉴权、old SHA 和保护规则校验。 */
|
||||
private byte[] pushLocked(
|
||||
Project project,
|
||||
GitAccess access,
|
||||
GitIo.PushCommand command,
|
||||
Supplier<byte[]> transfer,
|
||||
java.util.function.Consumer<RepositoryWriteOperation> registered) {
|
||||
RepositoryWriteOperation pending = active(project.getProjectCode());
|
||||
if (pending != null) throw pending(pending);
|
||||
GiteaClient.Repository repository = projects.repository(project);
|
||||
RepositoryWriteOperation operation = new RepositoryWriteOperation();
|
||||
operation.setOperationCode(Codes.next());
|
||||
operation.setOperationKind("GIT_PUSH");
|
||||
operation.setProjectCode(project.getProjectCode());
|
||||
operation.setRepositoryId(repository.id());
|
||||
operation.setRepositoryOwner(repository.owner());
|
||||
operation.setRepositoryName(repository.name());
|
||||
operation.setBaseCommitSha(command.oldSha());
|
||||
operation.setTargetCommitSha(command.newSha());
|
||||
operation.setActorUserCode(access.userCode());
|
||||
operation.setGitTokenCode(access.tokenCode());
|
||||
operation.setRequestDigest(
|
||||
SecurityHashes.sha256(
|
||||
repository.id()
|
||||
+ ":refs/heads/main:"
|
||||
+ command.oldSha()
|
||||
+ ":"
|
||||
+ command.newSha()));
|
||||
operation.setCommitMessage("Git push main");
|
||||
operation.setStatus("PROCESSING");
|
||||
operation.setCheckCount(0);
|
||||
operation.setCreatedAt(ProjectSupport.now());
|
||||
operation.setUpdatedAt(operation.getCreatedAt());
|
||||
operation.setNextCheckAt(operation.getCreatedAt().plusSeconds(15));
|
||||
registered.accept(operation);
|
||||
return locks.write(
|
||||
project.getProjectCode(),
|
||||
() ->
|
||||
transactions.executeWithoutResult(
|
||||
transaction -> {
|
||||
operations.insert(operation);
|
||||
project.setRepoWriteStatus("WRITING");
|
||||
if (projectMapper.updateById(project) != 1)
|
||||
throw new IllegalStateException("项目写保护保存失败");
|
||||
}),
|
||||
() -> {
|
||||
log.info(
|
||||
"Git 推送开始 projectCode={} userCode={} tokenCode={} operationCode={}"
|
||||
+ " oldSha={} newSha={}",
|
||||
project.getProjectCode(),
|
||||
access.userCode(),
|
||||
access.tokenCode(),
|
||||
operation.getOperationCode(),
|
||||
command.oldSha(),
|
||||
command.newSha());
|
||||
byte[] result = transfer.get();
|
||||
boolean success;
|
||||
try {
|
||||
success = GitIo.pushSucceeded(result);
|
||||
} catch (java.io.IOException error) {
|
||||
throw GitIo.upstreamInvalid();
|
||||
}
|
||||
if (success && !command.newSha().equals(gitea.head(repository)))
|
||||
throw new BusinessException(503, "REMOTE_RESULT_UNKNOWN", "推送结果尚未核对");
|
||||
operation.setLastErrorCode(success ? null : "GIT_PUSH_REJECTED");
|
||||
operation.setFailureStatus(success ? null : 409);
|
||||
complete(
|
||||
operation,
|
||||
success ? command.newSha() : null,
|
||||
success ? "SUCCEEDED" : "FAILED");
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private boolean slowCheckDue(RepositoryWriteOperation operation) {
|
||||
@@ -151,20 +309,29 @@ public class RepositoryWrites {
|
||||
|
||||
/** 重启后直接扫描数据库,无内存任务队列;多实例由相同项目命名锁串行核对。 */
|
||||
public void reconcileDue() {
|
||||
List<RepositoryWriteOperation> due = operations.selectList(new LambdaQueryWrapper<RepositoryWriteOperation>()
|
||||
.in(RepositoryWriteOperation::getStatus, ACTIVE)
|
||||
.le(RepositoryWriteOperation::getNextCheckAt, ProjectSupport.now())
|
||||
.orderByAsc(RepositoryWriteOperation::getNextCheckAt).last("LIMIT 20"));
|
||||
List<RepositoryWriteOperation> due =
|
||||
operations.selectList(
|
||||
new LambdaQueryWrapper<RepositoryWriteOperation>()
|
||||
.in(RepositoryWriteOperation::getStatus, ACTIVE)
|
||||
.le(RepositoryWriteOperation::getNextCheckAt, ProjectSupport.now())
|
||||
.orderByAsc(RepositoryWriteOperation::getNextCheckAt)
|
||||
.last("LIMIT 20"));
|
||||
for (RepositoryWriteOperation candidate : due) {
|
||||
try {
|
||||
locks.serial(candidate.getProjectCode(), () -> {
|
||||
reconcile(candidate.getOperationCode());
|
||||
return null;
|
||||
});
|
||||
locks.serial(
|
||||
candidate.getProjectCode(),
|
||||
() -> {
|
||||
reconcile(candidate.getOperationCode());
|
||||
return null;
|
||||
});
|
||||
} catch (RuntimeException error) {
|
||||
log.warn("仓库后台核对未完成 projectCode={} operationCode={} errorCode={} errorType={}",
|
||||
candidate.getProjectCode(), candidate.getOperationCode(),
|
||||
error instanceof BusinessException business ? business.code() : "CHECK_FAILED",
|
||||
log.warn(
|
||||
"仓库后台核对未完成 projectCode={} operationCode={} errorCode={} errorType={}",
|
||||
candidate.getProjectCode(),
|
||||
candidate.getOperationCode(),
|
||||
error instanceof BusinessException business
|
||||
? business.code()
|
||||
: "CHECK_FAILED",
|
||||
error.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
@@ -172,10 +339,13 @@ public class RepositoryWrites {
|
||||
|
||||
private void reconcile(String operationCode) {
|
||||
RepositoryWriteOperation operation = operations.selectById(operationCode);
|
||||
if (operation == null || !ACTIVE.contains(operation.getStatus())
|
||||
if (operation == null
|
||||
|| !ACTIVE.contains(operation.getStatus())
|
||||
|| operation.getNextCheckAt().isAfter(ProjectSupport.now())) return;
|
||||
Project project = projectMapper.selectOne(new LambdaQueryWrapper<Project>()
|
||||
.eq(Project::getProjectCode, operation.getProjectCode()));
|
||||
Project project =
|
||||
projectMapper.selectOne(
|
||||
new LambdaQueryWrapper<Project>()
|
||||
.eq(Project::getProjectCode, operation.getProjectCode()));
|
||||
String receipt = project == null ? null : receipt(operation, project);
|
||||
operation.setCheckCount(operation.getCheckCount() + 1);
|
||||
if (receipt != null) {
|
||||
@@ -186,9 +356,13 @@ public class RepositoryWrites {
|
||||
operation.setStatus(overdue ? "NEEDS_REVIEW" : "PROCESSING");
|
||||
operation.setNextCheckAt(ProjectSupport.now().plusSeconds(overdue ? 60 : 15));
|
||||
save(operation);
|
||||
log.info("仓库写入继续核对 projectCode={} operationCode={} status={} checkCount={} errorCode={}",
|
||||
operation.getProjectCode(), operationCode, operation.getStatus(),
|
||||
operation.getCheckCount(), operation.getLastErrorCode());
|
||||
log.info(
|
||||
"仓库写入继续核对 projectCode={} operationCode={} status={} checkCount={} errorCode={}",
|
||||
operation.getProjectCode(),
|
||||
operationCode,
|
||||
operation.getStatus(),
|
||||
operation.getCheckCount(),
|
||||
operation.getLastErrorCode());
|
||||
}
|
||||
|
||||
private String receipt(RepositoryWriteOperation operation, Project project) {
|
||||
@@ -202,34 +376,61 @@ public class RepositoryWrites {
|
||||
if (remote.id() != operation.getRepositoryId()
|
||||
|| !remote.owner().equals(operation.getRepositoryOwner())
|
||||
|| !remote.name().equals(operation.getRepositoryName())
|
||||
|| !remote.privateRepo() || remote.mirror() || remote.empty()
|
||||
|| !remote.privateRepo()
|
||||
|| remote.mirror()
|
||||
|| remote.empty()
|
||||
|| !"main".equals(remote.defaultBranch()))
|
||||
throw new GiteaFailure(409, "WRITE_REPOSITORY_MISMATCH", "远端仓库身份发生变化", false);
|
||||
String sha = gitea.findWriteReceipt(remote.repository(), operation.getBaseCommitSha(),
|
||||
operation.getOperationCode(), operation.getRequestDigest());
|
||||
String sha;
|
||||
if ("GIT_PUSH".equals(operation.getOperationKind())) {
|
||||
String head = gitea.head(remote.repository());
|
||||
sha = Objects.equals(head, operation.getTargetCommitSha()) ? head : null;
|
||||
// main 仍为旧 SHA 不能证明接收任务已经结束,继续保持写保护。
|
||||
} else {
|
||||
sha =
|
||||
gitea.findWriteReceipt(
|
||||
remote.repository(),
|
||||
operation.getBaseCommitSha(),
|
||||
operation.getOperationCode(),
|
||||
operation.getRequestDigest());
|
||||
}
|
||||
if (sha == null) operation.setLastErrorCode("WRITE_RECEIPT_NOT_FOUND");
|
||||
return sha;
|
||||
} catch (RuntimeException error) {
|
||||
operation.setLastErrorCode(error instanceof BusinessException business
|
||||
? business.code() : "WRITE_RECEIPT_READ_FAILED");
|
||||
log.warn("仓库写入凭据读取未确认 projectCode={} operationCode={} errorCode={} errorType={}",
|
||||
operation.getProjectCode(), operation.getOperationCode(), operation.getLastErrorCode(),
|
||||
operation.setLastErrorCode(
|
||||
error instanceof BusinessException business
|
||||
? business.code()
|
||||
: "WRITE_RECEIPT_READ_FAILED");
|
||||
log.warn(
|
||||
"仓库写入凭据读取未确认 projectCode={} operationCode={} errorCode={} errorType={}",
|
||||
operation.getProjectCode(),
|
||||
operation.getOperationCode(),
|
||||
operation.getLastErrorCode(),
|
||||
error.getClass().getSimpleName());
|
||||
if (!(error instanceof BusinessException)) SafeExceptionLog.write(log, "仓库凭据核对异常", error);
|
||||
if (!(error instanceof BusinessException))
|
||||
SafeExceptionLog.write(log, "仓库凭据核对异常", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void complete(RepositoryWriteOperation operation, String sha, String status) {
|
||||
// 项目恢复与操作终态在同一事务提交;任务获得锁后重读终态,旧任务不会清除新操作的保护。
|
||||
transactions.executeWithoutResult(transaction -> {
|
||||
operation.setStatus(status);
|
||||
operation.setResultCommitSha(sha);
|
||||
save(operation);
|
||||
locks.confirmKnownResult(operation.getProjectCode());
|
||||
});
|
||||
log.info("仓库写入结果已落盘 projectCode={} operationCode={} status={} commitSha={}",
|
||||
operation.getProjectCode(), operation.getOperationCode(), status, sha);
|
||||
transactions.executeWithoutResult(
|
||||
transaction -> {
|
||||
operation.setStatus(status);
|
||||
operation.setResultCommitSha(sha);
|
||||
save(operation);
|
||||
// 持锁连接释放异常可能使上一条终态重新进入核对;不能解除另一条操作的保护。
|
||||
if (active(operation.getProjectCode()) == null)
|
||||
locks.confirmKnownResult(operation.getProjectCode());
|
||||
else locks.markUncertain(operation.getProjectCode());
|
||||
});
|
||||
log.info(
|
||||
"仓库写入结果已落盘 projectCode={} operationCode={} status={} commitSha={}",
|
||||
operation.getProjectCode(),
|
||||
operation.getOperationCode(),
|
||||
status,
|
||||
sha);
|
||||
}
|
||||
|
||||
private void save(RepositoryWriteOperation operation) {
|
||||
|
||||
Reference in New Issue
Block a user