单文件下载改为流式传输

This commit is contained in:
lxp
2026-11-05 15:40:02 +08:00
parent 3141169a35
commit 366426d98a
22 changed files with 1101 additions and 51 deletions
@@ -4,12 +4,15 @@ import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.security.CurrentUser;
import com.linkerbot.vibemake.service.*;
import com.linkerbot.vibemake.service.download.FileDownloadService;
import com.linkerbot.vibemake.service.download.FileDownloadResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
@@ -24,6 +27,7 @@ import java.util.List;
public class VibemakeController {
private final ProjectService projects;
private final FileService files;
private final FileDownloadService downloads;
private final InteractionService interactions;
@GetMapping("/api/project-types")
@@ -71,12 +75,13 @@ public class VibemakeController {
@PathVariable String projectCode,
@RequestParam String path,
@RequestParam(defaultValue = "false") boolean download,
@RequestParam(required = false) String commitSha) {
@RequestParam(required = false) String commitSha,
HttpServletResponse response) {
rejectRef(commitSha);
return download
? WorkspaceController.download(files.vibemakeFile(projectCode, path))
: ResponseEntity.ok(
ApiResponse.success(files.vibemakeFileView(projectCode, path)));
if (!download)
return ResponseEntity.ok(ApiResponse.success(files.vibemakeFileView(projectCode, path)));
FileDownloadResponse.write(response, destination -> downloads.community(projectCode, path, destination));
return null;
}
private void rejectRef(String sha) {
@@ -4,12 +4,14 @@ import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.security.CurrentUser;
import com.linkerbot.vibemake.service.*;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import com.linkerbot.vibemake.service.download.FileDownloadService;
import com.linkerbot.vibemake.service.download.FileDownloadResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
@@ -17,7 +19,6 @@ import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import java.util.List;
@RestController
@@ -27,6 +28,7 @@ import java.util.List;
public class WorkspaceController {
private final ProjectService projects;
private final FileService files;
private final FileDownloadService downloads;
@GetMapping
@Operation(summary = "我的项目列表")
@@ -82,25 +84,14 @@ public class WorkspaceController {
@PathVariable String projectCode,
@RequestParam String path,
@RequestParam(required = false) String commitSha,
@RequestParam(defaultValue = "false") boolean download) {
@RequestParam(defaultValue = "false") boolean download,
HttpServletResponse response) {
long user = CurrentUser.required();
if (!download)
return ResponseEntity.ok(
ApiResponse.success(files.ownerFileView(user, projectCode, path, commitSha)));
return download(files.ownerFile(user, projectCode, path, commitSha));
}
public static ResponseEntity<byte[]> download(GiteaClient.StoredFile file) {
String name = file.path().substring(file.path().lastIndexOf('/') + 1);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(
HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment()
.filename(name, StandardCharsets.UTF_8)
.build()
.toString())
.body(file.bytes());
FileDownloadResponse.write(response, destination -> downloads.owner(user, projectCode, path, commitSha, destination));
return null;
}
@PostMapping("/{projectCode}/commits")
@@ -127,6 +127,9 @@ vibemake:
max-text-bytes: 1048576
max-file-bytes: 52428800
max-request-bytes: 209715200
file-download:
max-bytes: ${FILE_DOWNLOAD_MAX_BYTES:1073741824}
timeout: ${FILE_DOWNLOAD_TIMEOUT:5m}
gitea:
connect-timeout: 5s
request-timeout: 30s
@@ -145,6 +145,16 @@ final class FakeGiteaClient implements GiteaClient {
return new StoredFile(path, blob(bytes), bytes.clone());
}
@Override
public synchronized FileDownload openFile(Repository repository, String sha, String path,
Duration timeout, long maxBytes) {
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
byte[] bytes = snapshot == null ? null : snapshot.get(path);
if (bytes == null) throw new GiteaFailure(404, "NOT_FOUND", "文件不存在", false);
if (bytes.length > maxBytes) throw new GiteaFailure(413, "FILE_TOO_LARGE", "文件超过下载限制", false);
return new FileDownload(new ByteArrayInputStream(bytes), bytes.length);
}
@Override
public synchronized CommitView commit(
Repository repository,
@@ -0,0 +1,244 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.FileDownloadProperties;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:filedownloads;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.ai.enabled=false", "vibemake.oss.enabled=false",
"vibemake.limits.enabled=false", "vibemake.limits.file-concurrent=1",
"vibemake.repository-write.worker-enabled=false", "logging.level.root=WARN"})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(WorkflowTest.Config.class)
@Timeout(20)
class FileDownloadApiTest {
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired FileDownloadProperties properties;
@MockitoSpyBean FakeGiteaClient gitea;
@BeforeEach
void resetState() throws Exception {
reset(gitea);
gitea.reset();
properties.setMaxBytes(1024L * 1024 * 1024);
SchemaSupport.reset(jdbc);
}
private JsonNode call(MockHttpServletRequestBuilder request) throws Exception {
return json.readTree(mvc.perform(request).andExpect(status().isOk()).andReturn()
.getResponse().getContentAsByteArray()).path("data");
}
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object input) throws Exception {
return request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsBytes(input));
}
private MockHttpServletRequestBuilder auth(MockHttpServletRequestBuilder request, String token) {
return request.header("Authorization", "Bearer " + token);
}
private String login(String email) throws Exception {
String captcha = call(get("/api/auth/captcha")).path("captchaCode").asText();
return call(body(post("/api/auth/login"), Map.of("email", email,
"captchaCode", captcha, "captchaAnswer", "ABCDE"))).path("token").asText();
}
private String create(String token) throws Exception {
return call(body(auth(post("/api/workspace/projects"), token),
Map.of("name", "文件下载测试", "projectType", "GENERAL"))).path("projectCode").asText();
}
private String head(String token, String code) throws Exception {
return call(auth(get("/api/workspace/projects/" + code + "/tree"), token)).path("commitSha").asText();
}
private String commit(String token, String code, String sha, String action, String path, String content) throws Exception {
return call(body(auth(post("/api/workspace/projects/" + code + "/commits"), token),
Map.of("expectedCommitSha", sha, "message", "更新文件", "changes", List.of(
Map.of("action", action, "path", path, "content", content)))))
.path("commitSha").asText();
}
@Test
void downloadsFrozenPublishedCurrentAndHistoricalFilesWithChineseNames() throws Exception {
String token = login("file-versions@example.invalid");
String code = create(token);
String path = "doc/动画 空格.gif";
String first = commit(token, code, head(token, code), "CREATE_FILE", path, "发布版本");
call(body(auth(put("/api/workspace/projects/" + code + "/publication"), token), Map.of("commitSha", first)));
commit(token, code, first, "UPDATE_FILE", path, "工作区版本");
for (String context : List.of("community", "workspace", "history")) {
String content = context.equals("workspace") ? "工作区版本" : "发布版本";
MockHttpServletRequestBuilder request = get("/api/" + (context.equals("community") ? "community" : "workspace")
+ "/projects/" + code + "/files").param("path", path).param("download", "true")
.header("Origin", "https://dev-vibemake.robotquan.com");
if (!context.equals("community")) auth(request, token);
if (context.equals("history")) request.param("commitSha", first);
mvc.perform(request).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
.andExpect(content().bytes(content.getBytes(StandardCharsets.UTF_8)))
.andExpect(header().string("Content-Length", Integer.toString(content.getBytes(StandardCharsets.UTF_8).length)))
.andExpect(header().string("Content-Disposition", containsString("filename*=")))
.andExpect(header().string("Cache-Control", "no-store"))
.andExpect(header().exists("X-Request-Id"))
.andExpect(header().string("Access-Control-Expose-Headers", containsString("Content-Disposition")));
}
}
@Test
void permissionsReadinessAndCommunityRefRestrictionsRemainEnforced() throws Exception {
String token = login("file-owner@example.invalid");
String other = login("file-other@example.invalid");
String code = create(token);
String workspace = "/api/workspace/projects/" + code + "/files";
String community = "/api/community/projects/" + code + "/files";
mvc.perform(get(workspace).param("path", "README.md").param("download", "true")).andExpect(status().isUnauthorized());
mvc.perform(auth(get(workspace).param("path", "README.md").param("download", "true"), other)).andExpect(status().isNotFound());
mvc.perform(get(community).param("path", "README.md").param("download", "true")).andExpect(status().isNotFound());
call(body(auth(put("/api/workspace/projects/" + code + "/publication"), token), Map.of("commitSha", head(token, code))));
for (String ref : List.of("", "a".repeat(40)))
mvc.perform(get(community).param("path", "README.md").param("download", "true").param("commitSha", ref))
.andExpect(status().isBadRequest());
mvc.perform(auth(get(workspace).param("path", "../README.md").param("download", "true"), token)).andExpect(status().isBadRequest());
jdbc.update("UPDATE project SET repo_status='CREATING' WHERE project_code=?", code);
mvc.perform(auth(get(workspace).param("path", "README.md").param("download", "true"), token)).andExpect(status().isConflict());
jdbc.update("UPDATE project SET repo_status='READY' WHERE project_code=?", code);
call(auth(delete("/api/workspace/projects/" + code + "/publication"), token));
mvc.perform(get(community).param("path", "README.md").param("download", "true")).andExpect(status().isNotFound());
call(auth(delete("/api/workspace/projects/" + code), token));
mvc.perform(auth(get(workspace).param("path", "README.md").param("download", "true"), token)).andExpect(status().isNotFound());
}
@Test
void downloadBypassesJsonReaderAndAppliesItsOwnLimit() throws Exception {
String token = login("file-limits@example.invalid");
String code = create(token);
String endpoint = "/api/workspace/projects/" + code + "/files";
doThrow(new BusinessException(413, "FILE_TOO_LARGE", "文件超过读取限制"))
.when(gitea).file(any(), anyString(), eq("README.md"));
mvc.perform(auth(get(endpoint).param("path", "README.md"), token)).andExpect(status().isPayloadTooLarge());
mvc.perform(auth(get(endpoint).param("path", "README.md").param("download", "true"), token))
.andExpect(status().isOk()).andExpect(content().string("initial"));
verify(gitea, times(1)).file(any(), anyString(), anyString());
properties.setMaxBytes(1);
mvc.perform(auth(get(endpoint).param("path", "README.md").param("download", "true"), token))
.andExpect(status().isPayloadTooLarge()).andExpect(jsonPath("$.code").value("FILE_TOO_LARGE"))
.andExpect(header().doesNotExist("Content-Disposition")).andExpect(header().doesNotExist("Content-Length"));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void errorsCloseUpstreamAndNeverAppendJsonToCommittedFile(boolean commit) throws Exception {
String token = login("file-failure@example.invalid");
String code = create(token);
AtomicBoolean closed = new AtomicBoolean();
InputStream failing = new InputStream() {
private boolean sent;
@Override public int read() { throw new UnsupportedOperationException(); }
@Override public int read(byte[] bytes, int offset, int length) {
if (commit && !sent) {
sent = true;
int size = Math.min(length, 16384);
java.util.Arrays.fill(bytes, offset, offset + size, (byte) 'x');
return size;
}
throw new GiteaFailure(504, "FILE_DOWNLOAD_TIMEOUT", "timeout", false);
}
@Override public void close() { closed.set(true); }
};
doReturn(new GiteaClient.FileDownload(failing, 100000)).when(gitea)
.openFile(any(), anyString(), anyString(), any(), anyLong());
MvcResult result = mvc.perform(auth(get("/api/workspace/projects/" + code + "/files")
.param("path", "README.md").param("download", "true"), token)).andReturn();
assertThat(closed.get()).isTrue();
if (commit) {
assertThat(result.getResponse().getStatus()).isEqualTo(200);
assertThat(result.getResponse().getContentAsString()).isEqualTo("x".repeat(16384));
} else {
assertThat(result.getResponse().getStatus()).isEqualTo(504);
assertThat(result.getResponse().getHeader("Content-Disposition")).isNull();
assertThat(result.getResponse().getHeader("Content-Length")).isNull();
assertThat(json.readTree(result.getResponse().getContentAsByteArray()).path("code").asText()).isEqualTo("FILE_DOWNLOAD_TIMEOUT");
}
}
@Test
void concurrentPermitIsHeldDuringStreamingAndReleasedAfterFailure() throws Exception {
String token = login("file-concurrency@example.invalid");
String code = create(token);
String endpoint = "/api/workspace/projects/" + code + "/files";
CountDownLatch reading = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean closed = new AtomicBoolean();
InputStream blocking = new InputStream() {
@Override public int read() { throw new UnsupportedOperationException(); }
@Override public int read(byte[] bytes, int offset, int length) {
reading.countDown();
try { if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("下载未释放"); }
catch (InterruptedException error) { throw new AssertionError(error); }
throw new GiteaFailure(502, "GITEA_ERROR", "fixture", false);
}
@Override public void close() { closed.set(true); }
};
doReturn(new GiteaClient.FileDownload(blocking, 10)).when(gitea)
.openFile(any(), anyString(), anyString(), any(), anyLong());
try (ExecutorService worker = Executors.newVirtualThreadPerTaskExecutor()) {
Future<MvcResult> first = worker.submit(() -> mvc.perform(auth(get(endpoint)
.param("path", "README.md").param("download", "true"), token)).andReturn());
try {
assertThat(reading.await(5, TimeUnit.SECONDS)).isTrue();
mvc.perform(auth(get(endpoint).param("path", "README.md").param("download", "true"), token))
.andExpect(status().isTooManyRequests()).andExpect(jsonPath("$.code").value("FILE_BUSY"))
.andExpect(header().exists("Retry-After"));
} finally { release.countDown(); }
assertThat(first.get(5, TimeUnit.SECONDS).getResponse().getStatus()).isEqualTo(502);
}
assertThat(closed.get()).isTrue();
doCallRealMethod().when(gitea).openFile(any(), anyString(), anyString(), any(), anyLong());
mvc.perform(auth(get(endpoint).param("path", "README.md").param("download", "true"), token)).andExpect(status().isOk());
}
}