This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 55ad25c9a4ce CAMEL-26932: camel-jbang-mcp - camel_render_route_diagram 
calls at the same time all work, and each is a second faster (#30019)
55ad25c9a4ce is described below

commit 55ad25c9a4ce5386d72bacf832e370507101f979
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 15 16:44:23 2026 +0100

    CAMEL-26932: camel-jbang-mcp - camel_render_route_diagram calls at the same 
time all work, and each is a second faster (#30019)
    
    - The routes of a source file are dumped into a work directory of its own 
for each call. All the calls of the MCP
      server shared one directory per pid, which each deleted at its start: of 
three calls at once one failed with
      NoSuchFileException and one timed out.
    - The transform run that dumps the routes stops once Camel has started 
(camel.main.durationMaxSeconds=-1), as the
      routes are dumped while Camel starts; a --max-seconds of 1 overrode that, 
so each diagram waited a second for
      nothing. camel cmd route-diagram of a source file: 2.8 s -> 1.55 s, with 
the same text and the same PNG.
    - A text diagram without outputFile is only returned, not left in a 
temporary file for each call, and the message of
      an image says once where it is saved.
    
    CAMEL-26932: camel-jbang-mcp - a failed text diagram does not name the 
temporary file it deleted (review)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../core/commands/action/ActionBaseCommand.java    | 28 ++++++--
 .../jbang/core/commands/mcp/RouteDiagramTools.java | 39 +++++++++--
 .../core/commands/mcp/RouteDiagramToolsTest.java   | 78 ++++++++++++++++++++++
 3 files changed, 133 insertions(+), 12 deletions(-)

diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
index 356709fb8402..1b41bb5c1bf5 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
@@ -263,11 +263,28 @@ abstract class ActionBaseCommand extends CamelCommand {
             }
         }
 
-        Path workDir = CommandLineHelper.getWorkDir().resolve(workDirPrefix + 
ProcessHandle.current().pid());
-        PathUtils.deleteDirectory(workDir);
+        // a directory of its own for each dump: the MCP server renders 
diagrams in one JVM, also at the same time,
+        // and a directory per pid, deleted at the start of each dump, made 
the calls fail each other (CAMEL-26932)
+        Path parent = CommandLineHelper.getWorkDir();
+        Files.createDirectories(parent);
+        Path workDir = Files.createTempDirectory(parent, workDirPrefix + 
ProcessHandle.current().pid() + "-");
+        SourceDump answer = null;
+        try {
+            answer = dumpRoutesFromSource(sourceFiles, workDir, 
ignoreLoadingError, compile);
+            return answer;
+        } finally {
+            if (answer == null) {
+                // the caller deletes the directory of a dump
+                PathUtils.deleteDirectory(workDir);
+            }
+        }
+    }
+
+    private SourceDump dumpRoutesFromSource(
+            List<String> sourceFiles, Path workDir, boolean 
ignoreLoadingError, boolean compile)
+            throws Exception {
         final String target = workDir.toString();
-        // anything this boot dumps must be newer than this: guards readers 
against a stale dump left over from a
-        // previous --watch iteration whose cleanup above raced with (or lost 
against) a slow filesystem
+        // anything this boot dumps must be newer than this: guards readers 
against a stale dump
         Instant bootStart = Instant.now();
 
         if (!compile && TransformJavaRoutes.applies(sourceFiles)) {
@@ -291,7 +308,8 @@ abstract class ActionBaseCommand extends CamelCommand {
             }
         };
         run.files = sourceFiles;
-        run.executionLimitOptions.maxSeconds = 1;
+        // the routes are dumped while Camel starts, and a transform run stops 
once Camel has started
+        // (camel.main.durationMaxSeconds=-1): a run of a fixed second only 
made each diagram a second slower
         int exit = run.runTransform(ignoreLoadingError);
         if (exit != 0) {
             return null;
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramTools.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramTools.java
index c28cd72062d0..27c4905c03b6 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramTools.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramTools.java
@@ -17,9 +17,11 @@
 package org.apache.camel.dsl.jbang.core.commands.mcp;
 
 import java.io.File;
+import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import jakarta.enterprise.context.ApplicationScoped;
 
@@ -57,7 +59,7 @@ public class RouteDiagramTools {
     public RouteDiagramResult camel_render_route_diagram(
             @ToolArg(description = "Absolute or relative path to the Camel 
route source file (YAML, XML, Java, ...)") String sourceFile,
             @ToolArg(description = "Optional output file path. For image 
themes a PNG is written; for text themes a .txt "
-                                   + "file is written. If not specified, a 
temporary file is created.",
+                                   + "file is written. If not specified, a PNG 
goes to a temporary file, and a text diagram is only returned.",
                      required = false) String outputFile,
             @ToolArg(description = "Color theme: 'light' (default), 'dark', 
'transparent', 'ascii' (plain ASCII art), "
                                    + "'unicode' (box-drawing characters), or a 
custom spec like "
@@ -89,6 +91,8 @@ public class RouteDiagramTools {
         boolean textMode = theme != null && 
TEXT_THEMES.contains(theme.toLowerCase());
 
         String resolvedOutput;
+        // a text diagram is returned as text: a file of its own only when the 
caller asks for one
+        boolean tempText = textMode && (outputFile == null || 
outputFile.isBlank());
         try {
             if (outputFile == null || outputFile.isBlank()) {
                 String suffix = textMode ? ".txt" : ".png";
@@ -127,34 +131,55 @@ public class RouteDiagramTools {
             if (textMode) {
                 String asciiContent = success ? Files.readString(out.toPath()) 
: null;
                 String message = success
-                        ? withNotes("ASCII diagram generated (" + size + " 
bytes)", capturingPrinter)
+                        ? withNotes("ASCII diagram generated (" + size + " 
bytes)", capturingPrinter, resolvedOutput)
                         : "Failed to render diagram (exit code " + exit + "): 
" + capturingPrinter.getOutput();
+                if (tempText) {
+                    // the diagram is in the answer: no file is left behind 
for each call (CAMEL-26932)
+                    Files.deleteIfExists(out.toPath());
+                    return new RouteDiagramResult(success, null, size, 
message, asciiContent);
+                }
                 return new RouteDiagramResult(success, resolvedOutput, size, 
message, asciiContent);
             }
 
             String message = success
-                    ? withNotes("Diagram saved to: " + resolvedOutput, 
capturingPrinter)
+                    ? withNotes("Diagram saved to: " + resolvedOutput, 
capturingPrinter, resolvedOutput)
                     : "Failed to render diagram (exit code " + exit + "): " + 
capturingPrinter.getOutput();
             return new RouteDiagramResult(success, resolvedOutput, size, 
message, null);
         } catch (CliException e) {
             // an expected failure, such as a source file without routes, or a 
filter that matches no route
+            deleteTempText(tempText, resolvedOutput);
             return new RouteDiagramResult(
-                    false, resolvedOutput, 0L,
+                    false, tempText ? null : resolvedOutput, 0L,
                     "Failed to render diagram (exit code " + e.getExitCode() + 
"): " + e.getMessage(), null);
         } catch (Throwable e) {
+            deleteTempText(tempText, resolvedOutput);
             throw new ToolCallException(
                     "Failed to render route diagram (" + 
e.getClass().getName() + "): " + e.getMessage(), null);
         }
     }
 
     /**
-     * The message, followed by what the command printed, such as the parts of 
a Java route the parser could not read.
+     * The message, followed by what the command printed, such as the parts of 
a Java route the parser could not read,
+     * without the line that says where the diagram is saved, which the 
message already says (or which is a file of the
+     * tool's own).
      */
-    private static String withNotes(String message, CapturingPrinter printer) {
-        String notes = printer.getOutput();
+    private static String withNotes(String message, CapturingPrinter printer, 
String output) {
+        String saved = "Diagram saved to: " + output;
+        String notes = printer.getOutput().lines().filter(line -> 
!line.strip().equals(saved))
+                .collect(Collectors.joining("\n")).strip();
         return notes.isEmpty() ? message : message + "\n" + notes;
     }
 
+    private static void deleteTempText(boolean tempText, String file) {
+        if (tempText && file != null) {
+            try {
+                Files.deleteIfExists(Path.of(file));
+            } catch (IOException e) {
+                // a file in the temporary directory
+            }
+        }
+    }
+
     /**
      * @param asciiDiagram plain-text diagram content for ascii/unicode 
themes; null for image themes
      */
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramToolsTest.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramToolsTest.java
index 95966074082d..a4012d158db4 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramToolsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/RouteDiagramToolsTest.java
@@ -18,6 +18,13 @@ package org.apache.camel.dsl.jbang.core.commands.mcp;
 
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
 
 import io.quarkiverse.mcp.server.ToolCallException;
 import org.junit.jupiter.api.Test;
@@ -102,4 +109,75 @@ class RouteDiagramToolsTest {
         assertThat(Files.readAllBytes(png)).startsWith(0x89, 'P', 'N', 'G');
         assertThat(result.asciiDiagram()).isNull();
     }
+
+    @Test
+    void theMessageSaysOnceWhereTheImageIs(@TempDir Path dir) throws Exception 
{
+        Path png = dir.resolve("orders.png");
+
+        RouteDiagramTools.RouteDiagramResult result = new 
RouteDiagramTools().camel_render_route_diagram(
+                route(dir, "orders").toString(), png.toString(), null, null, 
null, null, null, null, null);
+
+        assertThat(result.success()).isTrue();
+        assertThat(result.message()).isEqualTo("Diagram saved to: " + 
png.toAbsolutePath());
+    }
+
+    @Test
+    void aTextDiagramLeavesNoFileBehind(@TempDir Path dir) throws Exception {
+        Path source = route(dir, "orders");
+        List<Path> before = tempDiagrams();
+
+        RouteDiagramTools.RouteDiagramResult result = new 
RouteDiagramTools().camel_render_route_diagram(
+                source.toString(), null, "ascii", null, null, null, null, 
null, null);
+
+        assertThat(result.success()).isTrue();
+        assertThat(result.asciiDiagram()).contains("orders");
+        assertThat(result.outputFile()).isNull();
+        assertThat(result.message()).doesNotContain("saved to");
+        // CAMEL-26932: a temporary file was left for each call
+        assertThat(tempDiagrams()).isEqualTo(before);
+    }
+
+    @Test
+    void callsAtTheSameTime(@TempDir Path dir) throws Exception {
+        // CAMEL-26932: the calls shared one work directory, which each 
deleted at its start, so of three calls at
+        // once one failed with NoSuchFileException and one timed out
+        List<String> routes = List.of("first", "second", "third");
+        RouteDiagramTools tools = new RouteDiagramTools();
+        ExecutorService executor = Executors.newFixedThreadPool(routes.size());
+        try {
+            List<Future<RouteDiagramTools.RouteDiagramResult>> calls = new 
ArrayList<>();
+            for (String id : routes) {
+                Path source = route(dir, id);
+                calls.add(executor.submit(() -> 
tools.camel_render_route_diagram(
+                        source.toString(), null, "ascii", null, null, null, 
null, null, null)));
+            }
+            for (int i = 0; i < routes.size(); i++) {
+                RouteDiagramTools.RouteDiagramResult result = 
calls.get(i).get(60, TimeUnit.SECONDS);
+                assertThat(result.success()).as(result.message()).isTrue();
+                assertThat(result.asciiDiagram()).contains(routes.get(i));
+            }
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    private static Path route(Path dir, String id) throws Exception {
+        Path source = dir.resolve(id + ".camel.yaml");
+        Files.writeString(source, """
+                - route:
+                    id: %s
+                    from:
+                      uri: timer:%s
+                      steps:
+                        - to:
+                            uri: log:%s
+                """.formatted(id, id, id));
+        return source;
+    }
+
+    private static List<Path> tempDiagrams() throws Exception {
+        try (Stream<Path> files = 
Files.list(Path.of(System.getProperty("java.io.tmpdir")))) {
+            return files.filter(f -> 
f.getFileName().toString().startsWith("camel-route-diagram-")).sorted().toList();
+        }
+    }
 }

Reply via email to