Compare commits
2
Commits
8958822545
...
e77ad85be9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e77ad85be9 | ||
|
|
11939fe39e |
@@ -113,5 +113,8 @@ async def generate_with_retry(
|
||||
+ str(exc)[:160]
|
||||
)
|
||||
await asyncio.sleep(wait)
|
||||
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
|
||||
# l'essai suivant est lancé (il peut durer plusieurs minutes).
|
||||
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
|
||||
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
# min(8 + 2, 60) = 10
|
||||
assert slept == [10.0]
|
||||
|
||||
|
||||
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
|
||||
import asyncio
|
||||
|
||||
from app.application.import_status import reset_status_queue, set_status_queue
|
||||
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
token = set_status_queue(queue)
|
||||
try:
|
||||
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
finally:
|
||||
reset_status_queue(token)
|
||||
messages = [queue.get_nowait() for _ in range(queue.qsize())]
|
||||
assert "nouvel essai dans 3s" in messages[0]
|
||||
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
|
||||
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
|
||||
|
||||
@@ -53,7 +53,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
@Value("${brain.base-url}") String baseUrl,
|
||||
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
||||
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
|
||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||
this.importCampaignStreamPath = importCampaignStreamPath;
|
||||
|
||||
@@ -70,7 +70,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
@Value("${brain.paths.import-rules:/import/rules}") String importRulesPath,
|
||||
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
this.baseUrl = baseUrl;
|
||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.codec.ServerSentEvent;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -25,6 +26,21 @@ final class BrainSseImportSupport {
|
||||
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
||||
private static final String MESSAGE_FIELD = "message";
|
||||
|
||||
/**
|
||||
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
|
||||
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
|
||||
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
|
||||
* moment (DataBufferLimitException), après des minutes d'analyse.
|
||||
*/
|
||||
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
|
||||
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
|
||||
return builder.baseUrl(baseUrl)
|
||||
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
BrainSseImportSupport(ObjectMapper objectMapper) {
|
||||
|
||||
@@ -369,4 +369,43 @@ class BrainRulesImportClientTest {
|
||||
assertEquals(java.util.Map.of("Fighting", "d20 roll"), c.done.get().sectionsByLanguage().get("en"));
|
||||
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
|
||||
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
|
||||
* passe pas par les codecs du client, donc ne verrait pas la limite).
|
||||
*/
|
||||
@Test
|
||||
void streaming_acceptsAVeryLargeDoneEvent() throws Exception {
|
||||
String big = "x".repeat(600_000);
|
||||
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"" + big + "\"},\"page_count\":300,"
|
||||
+ "\"ocr_page_count\":0,\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\""
|
||||
+ big + "\"},\"en\":{\"Fighting\":\"" + big + "\"}}}\n\n";
|
||||
byte[] payload = sse.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
com.sun.net.httpserver.HttpServer server =
|
||||
com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/import/rules/stream", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
exchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
|
||||
exchange.sendResponseHeaders(200, payload.length);
|
||||
try (var out = exchange.getResponseBody()) {
|
||||
out.write(payload);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
String url = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
BrainRulesImportClient real = new BrainRulesImportClient(restTemplate, WebClient.builder(), objectMapper,
|
||||
url, 30, "/import/rules", "/import/rules/stream");
|
||||
Collector c = new Collector();
|
||||
real.importRulesStreaming(new byte[]{1}, "r.pdf",
|
||||
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add, c.done::set, c.error::set);
|
||||
|
||||
assertNull(c.error.get());
|
||||
assertNotNull(c.done.get());
|
||||
assertEquals(600_000, c.done.get().sectionsByLanguage().get("en").get("Fighting").length());
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,9 @@
|
||||
@if (importStatus) {
|
||||
<p class="import-status" role="status">{{ importStatus }}</p>
|
||||
}
|
||||
@if (importWaitLabel) {
|
||||
<p class="import-waiting">{{ 'gameSystemEdit.importWaiting' | translate:{ time: importWaitLabel } }}</p>
|
||||
}
|
||||
@if (importFound.length) {
|
||||
<p class="import-found">
|
||||
{{ 'gameSystemEdit.sectionsFound' | translate:{ titles: importFound.join(' · ') } }}
|
||||
|
||||
@@ -173,6 +173,13 @@
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.import-waiting {
|
||||
margin: 0.45rem 0 0;
|
||||
color: var(--text-muted, #9ca3af);
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.import-note {
|
||||
margin: -0.4rem 0 1rem;
|
||||
padding: 0.55rem 0.8rem;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
@@ -52,7 +52,7 @@ type RulesLang = 'fr' | 'en';
|
||||
templateUrl: './game-system-edit.component.html',
|
||||
styleUrls: ['./game-system-edit.component.scss']
|
||||
})
|
||||
export class GameSystemEditComponent implements OnInit {
|
||||
export class GameSystemEditComponent implements OnInit, OnDestroy {
|
||||
readonly Save = Save;
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Dices = Dices;
|
||||
@@ -82,6 +82,14 @@ export class GameSystemEditComponent implements OnInit {
|
||||
* en cours, pas l'historique.
|
||||
*/
|
||||
importStatus: string | null = null;
|
||||
/**
|
||||
* Secondes écoulées depuis le dernier évènement du flux. Un morceau peut occuper
|
||||
* l'IA plusieurs minutes (et un nouvel essai après une erreur autant) : sans ce
|
||||
* compteur, l'écran paraît figé alors que l'import avance.
|
||||
*/
|
||||
importWaitSeconds = 0;
|
||||
private lastImportEventAt = 0;
|
||||
private importWaitTimer?: ReturnType<typeof setInterval>;
|
||||
|
||||
name = '';
|
||||
description = '';
|
||||
@@ -177,9 +185,12 @@ export class GameSystemEditComponent implements OnInit {
|
||||
this.importProgress = null;
|
||||
this.importFound = [];
|
||||
this.importStatus = null;
|
||||
this.startImportWait();
|
||||
|
||||
this.service.importRulesStream(file).subscribe({
|
||||
next: (ev) => {
|
||||
this.lastImportEventAt = Date.now();
|
||||
this.importWaitSeconds = 0;
|
||||
if (ev.type === 'progress') {
|
||||
// Un morceau vient d'aboutir : le message d'attente est obsolète.
|
||||
this.importStatus = null;
|
||||
@@ -254,6 +265,34 @@ export class GameSystemEditComponent implements OnInit {
|
||||
this.importing = false;
|
||||
this.importPhase = '';
|
||||
this.importProgress = null;
|
||||
this.stopImportWait();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.stopImportWait();
|
||||
}
|
||||
|
||||
/** Le compteur ne s'affiche qu'au-delà de quelques secondes sans nouvelle. */
|
||||
get importWaitLabel(): string | null {
|
||||
const s = this.importWaitSeconds;
|
||||
if (s < 15) return null;
|
||||
const m = Math.floor(s / 60);
|
||||
return m > 0 ? `${m} min ${String(s % 60).padStart(2, '0')} s` : `${s} s`;
|
||||
}
|
||||
|
||||
private startImportWait(): void {
|
||||
this.stopImportWait();
|
||||
this.lastImportEventAt = Date.now();
|
||||
this.importWaitSeconds = 0;
|
||||
this.importWaitTimer = setInterval(() => {
|
||||
this.importWaitSeconds = Math.floor((Date.now() - this.lastImportEventAt) / 1000);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
private stopImportWait(): void {
|
||||
if (this.importWaitTimer) clearInterval(this.importWaitTimer);
|
||||
this.importWaitTimer = undefined;
|
||||
this.importWaitSeconds = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1296,7 +1296,8 @@
|
||||
"en": "English"
|
||||
},
|
||||
"langHint": "Rules exist in two versions: the app and the AI use the one matching the interface language (or the other if it's empty). Importing a PDF fills both, whatever its language.",
|
||||
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab."
|
||||
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab.",
|
||||
"importWaiting": "The AI has been working on this chunk for {{time}}. A large chunk can take several minutes per attempt: as long as this counter moves, the import is still running."
|
||||
},
|
||||
"ollamaModelManager": {
|
||||
"installedModels": "Installed models",
|
||||
|
||||
@@ -1296,7 +1296,8 @@
|
||||
"en": "English"
|
||||
},
|
||||
"langHint": "Les règles existent en deux versions : l'appli et l'IA utilisent celle de la langue de l'interface (ou l'autre si elle est vide). Importer un PDF remplit les deux, dans n'importe quelle langue.",
|
||||
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet."
|
||||
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet.",
|
||||
"importWaiting": "L'IA travaille sur ce morceau depuis {{time}}. Un gros morceau peut prendre plusieurs minutes par essai : tant que ce compteur avance, l'import continue."
|
||||
},
|
||||
"ollamaModelManager": {
|
||||
"installedModels": "Modèles installés",
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
"structureFailed": "Structure import failed.",
|
||||
"importExtracting": "Extracting text…",
|
||||
"importAnalyzing": "Analyzing rules… ({{current}}/{{total}})",
|
||||
"importWaiting": "The AI has been working on this chunk for {{time}}. A large chunk can take several minutes per attempt: as long as this counter moves, the import is still running.",
|
||||
"importFailed": "PDF import failed.",
|
||||
"importFailedReason": "Import failed: {{reason}}",
|
||||
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
"structureFailed": "Échec de l'import de la structure.",
|
||||
"importExtracting": "Extraction du texte…",
|
||||
"importAnalyzing": "Analyse des règles… ({{current}}/{{total}})",
|
||||
"importWaiting": "L'IA travaille sur ce morceau depuis {{time}}. Un gros morceau peut prendre plusieurs minutes par essai : tant que ce compteur avance, l'import continue.",
|
||||
"importFailed": "Échec de l'import du PDF.",
|
||||
"importFailedReason": "Échec de l'import : {{reason}}",
|
||||
"importNoRules": "Aucune règle exploitable n'a été extraite de ce PDF (scan sans OCR, ou contenu non reconnu).",
|
||||
|
||||
Reference in New Issue
Block a user