loggin added
This commit is contained in:
@@ -27,6 +27,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
import kz.konturai.parser.dto.PageResponse;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/parser/report")
|
||||
@@ -74,56 +75,58 @@ public class ReportController {
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<byte[]> generateResearchReport(@Validated @RequestBody ResearchReportRequest request) {
|
||||
try {
|
||||
// Валидация входных данных
|
||||
if (request.getQuery() == null || request.getQuery().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
// Подготовка запроса для deep-research API
|
||||
DeepResearchRequest deepRequest = new DeepResearchRequest(
|
||||
request.getQuery(),
|
||||
request.getLang(),
|
||||
request.getDepth(),
|
||||
request.getBreadth(),
|
||||
request.getReportType());
|
||||
|
||||
// Вызов deep-research API
|
||||
DeepResearchResponse researchResponse = deepResearchService.generateReport(deepRequest);
|
||||
|
||||
if (researchResponse == null || researchResponse.getMainContent().trim().isEmpty()) {
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
|
||||
// Генерация PDF
|
||||
byte[] pdfBytes = researchPdfService.generatePdfReport(request.getQuery(), researchResponse);
|
||||
|
||||
// Формирование имени файла
|
||||
String filename = "research_report_" + System.currentTimeMillis() + ".pdf";
|
||||
|
||||
// Сохранение в историю отчётов
|
||||
saveResearchReportToHistory(request, filename, pdfBytes, researchResponse);
|
||||
|
||||
// Возврат PDF файла
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + filename + "\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
.body(pdfBytes);
|
||||
|
||||
} catch (Exception e) {
|
||||
// Логирование ошибки
|
||||
System.err.println("Error generating research report: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
|
||||
// Возврат ошибки в зависимости от типа исключения
|
||||
if (e.getMessage() != null && e.getMessage().contains("timeout")) {
|
||||
return ResponseEntity.status(504).build(); // Gateway Timeout
|
||||
} else {
|
||||
return ResponseEntity.status(500).build(); // Internal Server Error
|
||||
}
|
||||
public ResponseEntity<ApiResponse<ReportGenerationResponse>> generateResearchReport(
|
||||
@Validated @RequestBody ResearchReportRequest request) {
|
||||
// Валидация входных данных
|
||||
if (request.getQuery() == null || request.getQuery().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
// Подготовка запроса для deep-research API
|
||||
DeepResearchRequest deepRequest = new DeepResearchRequest(
|
||||
request.getQuery(),
|
||||
request.getLang(),
|
||||
request.getDepth(),
|
||||
request.getBreadth(),
|
||||
request.getReportType());
|
||||
|
||||
// Генерация уникального ID задачи
|
||||
String taskId = UUID.randomUUID().toString();
|
||||
|
||||
// Предполагаемое время завершения
|
||||
LocalDateTime estimatedCompletion = LocalDateTime.now().plusMinutes(8);
|
||||
|
||||
// Запускаем асинхронный процесс: deep-research -> PDF -> сохранение
|
||||
deepResearchService.generateReportAsync(deepRequest)
|
||||
.publishOn(Schedulers.boundedElastic())
|
||||
.map(researchResponse -> {
|
||||
if (researchResponse == null
|
||||
|| researchResponse.getMainContent() == null
|
||||
|| researchResponse.getMainContent().trim().isEmpty()) {
|
||||
throw new RuntimeException("Empty research response content");
|
||||
}
|
||||
|
||||
byte[] pdfBytes = researchPdfService.generatePdfReport(request.getQuery(),
|
||||
researchResponse);
|
||||
String filename = "research_report_" + System.currentTimeMillis() + ".pdf";
|
||||
saveResearchReportToHistory(request, filename, pdfBytes, researchResponse);
|
||||
return true;
|
||||
})
|
||||
.doOnError(e -> {
|
||||
System.err.println("Error generating research report async: " + e.getMessage());
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
ReportGenerationResponse response = new ReportGenerationResponse(
|
||||
taskId,
|
||||
"Исследование запущено в фоновом режиме. Ожидаемое время завершения: "
|
||||
+ estimatedCompletion
|
||||
.format(java.time.format.DateTimeFormatter.ofPattern(
|
||||
"HH:mm")),
|
||||
estimatedCompletion,
|
||||
"PROCESSING");
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success("Исследовательский отчёт поставлен в очередь", response));
|
||||
}
|
||||
|
||||
private void saveResearchReportToHistory(ResearchReportRequest request, String filename,
|
||||
|
||||
@@ -2,6 +2,9 @@ package kz.konturai.parser.service;
|
||||
|
||||
import kz.konturai.parser.dto.DeepResearchRequest;
|
||||
import kz.konturai.parser.dto.DeepResearchResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -17,6 +20,8 @@ public class DeepResearchService {
|
||||
|
||||
private final WebClient webClient;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DeepResearchService.class);
|
||||
|
||||
@Value("${deep-research.api.url:http://185.35.223.45:3051}")
|
||||
private String apiUrl;
|
||||
|
||||
@@ -52,12 +57,15 @@ public class DeepResearchService {
|
||||
/**
|
||||
* Асинхронный вызов deep-research API
|
||||
*/
|
||||
|
||||
public Mono<DeepResearchResponse> generateReportAsync(DeepResearchRequest request) {
|
||||
return webClient.post()
|
||||
.uri(apiUrl + "/api/research")
|
||||
.bodyValue(request)
|
||||
.retrieve()
|
||||
.bodyToMono(DeepResearchResponse.class)
|
||||
// 👇 Log the successful response object here
|
||||
.doOnSuccess(response -> log.info("Deep research API response: {}", response))
|
||||
.timeout(Duration.ofMillis(timeoutMs))
|
||||
.onErrorMap(WebClientResponseException.class,
|
||||
e -> new RuntimeException("Deep research API error: " + e.getResponseBodyAsString(), e))
|
||||
|
||||
Reference in New Issue
Block a user