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

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


The following commit(s) were added to refs/heads/main by this push:
     new 804e27d77a2 Add Camel Dev UI trace and message history pages
804e27d77a2 is described below

commit 804e27d77a2d34e72be8de08682aaa7780fa4d06
Author: James Netherton <[email protected]>
AuthorDate: Mon Nov 30 16:58:26 2026 +0000

    Add Camel Dev UI trace and message history pages
    
    The Trace page wraps the trace dev console. It turns backlog tracing on
    and off, lists the recently traced exchanges, and steps through each
    processor of a selected exchange, showing the body, headers, variables,
    properties, exception and elapsed time. A pause button freezes the
    list. A selected exchange stays visible after the trace buffer evicts
    it, and exchanges whose start was evicted are marked partial.
    
    The Message History page wraps the message-history dev console. It
    shows the steps of the latest completed exchange, which Camel captures
    while tracing is on standby.
    
    Dev mode already applies the Camel dev profile, which puts the backlog
    tracer on standby and enables message history, so CQ needs no extra
    defaults.
    
    The trace page allows dump=true and enabled=true|false. Dumped traces
    contain message bodies, headers, properties and variables, the same
    data the message-history and errors consoles already return, capped by
    camel.trace.bodyMaxChars and the console buffer. The Dev UI JSON-RPC
    bridge only exists in dev mode and accepts localhost connections only,
    and getConsoleJSON is not enabled in Dev MCP by default. enabled only
    switches the dev-mode backlog tracer, which is on standby.
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../devui/CamelCoreDevConsoleProcessor.java        |  13 +
 .../dev-ui/qwc-camel-core-message-history.js       |  90 +++++
 .../resources/dev-ui/qwc-camel-core-trace-steps.js | 289 ++++++++++++++++
 .../main/resources/dev-ui/qwc-camel-core-trace.js  | 364 +++++++++++++++++++++
 .../devui/CamelQuarkusCoreDevUITraceTest.java      | 129 ++++++++
 5 files changed, 885 insertions(+)

diff --git 
a/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
 
b/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
index 76d778e708c..ecad1a7a707 100644
--- 
a/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
+++ 
b/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
@@ -85,6 +85,12 @@ public class CamelCoreDevConsoleProcessor {
                 .componentLink("qwc-camel-core-inflight-exchanges.js")
                 .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, 
"inflight"));
 
+        cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+                .title("Message History")
+                .icon("font-awesome-solid:clock-rotate-left")
+                .componentLink("qwc-camel-core-message-history.js")
+                .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, 
"message-history"));
+
         cardPageBuildItem.addPage(Page.webComponentPageBuilder()
                 .title("REST")
                 .icon("font-awesome-solid:circle-nodes")
@@ -98,6 +104,13 @@ public class CamelCoreDevConsoleProcessor {
                 .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, "route")
                 .metadata(CamelDevUIConstants.ALLOWED_OPTIONS_METADATA_KEY, 
"limit=*"));
 
+        cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+                .title("Trace")
+                .icon("font-awesome-solid:shoe-prints")
+                .componentLink("qwc-camel-core-trace.js")
+                .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, "trace")
+                .metadata(CamelDevUIConstants.ALLOWED_OPTIONS_METADATA_KEY, 
"dump=true;enabled=true|false"));
+
         cardPageBuildItem.addPage(Page.webComponentPageBuilder()
                 .title("Variables")
                 .icon("font-awesome-solid:code")
diff --git 
a/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-message-history.js
 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-message-history.js
new file mode 100644
index 00000000000..a1530638663
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-message-history.js
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import {css, html} from 'qwc-hot-reload-element';
+import {QwcCamelCore} from "./qwc-camel-core.js";
+import '@vaadin/vertical-layout';
+import '@qomponent/qui-badge';
+import './qwc-camel-core-trace-steps.js';
+
+export class QwcCamelCoreMessageHistory extends QwcCamelCore {
+
+    static styles = [QwcCamelCore.styles, css`
+        .summary {
+            align-items: baseline;
+        }
+
+        qwc-camel-core-trace-steps {
+            padding: 0 10px 10px 10px;
+        }
+    `];
+
+    constructor() {
+        super('message-history');
+        this._events = [];
+    }
+
+    willUpdate(changed) {
+        super.willUpdate?.(changed);
+        if (changed.has('_consoleData')) {
+            const events = [...(this.consoleData()['traces'] ?? [])].sort((a, 
b) => a.uid - b.uid);
+            // Only hand the step viewer new steps when they changed, so it 
keeps its scroll position and focus
+            const same = events.length === this._events.length && 
events.every((event, i) =>
+                event.uid === this._events[i].uid && event.done === 
this._events[i].done && event.failed === this._events[i].failed);
+            if (!same) {
+                this._events = events;
+            }
+        }
+    }
+
+    render() {
+        const data = this.consoleData();
+        if (data['name'] === undefined) {
+            if (this._consoleData === undefined) {
+                return super.redenderNoDataAvailableMessage();
+            }
+            return html`
+                <vaadin-horizontal-layout class="empty-container">
+                    Message history is not available because Camel tracing is 
not set up. Set camel.trace.standby=true to capture it.
+                </vaadin-horizontal-layout>`;
+        }
+        const events = this._events;
+        if (events.length === 0) {
+            // The console cannot tell these two cases apart
+            return html`
+                <vaadin-horizontal-layout class="empty-container">
+                    No completed exchange yet. Message history also needs 
camel.main.messageHistory=true, which dev mode sets by default.
+                </vaadin-horizontal-layout>`;
+        }
+        const first = events[0];
+        const last = events.findLast(event => event.last && event.routeId === 
first.routeId);
+        return html`
+            <vaadin-horizontal-layout theme="spacing padding" class="summary">
+                <span>Latest completed exchange</span>
+                ${super.codeStyleRenderer(first.exchangeId)}
+                <span>from route</span>
+                ${super.codeStyleRenderer(first.routeId)}
+                ${last?.elapsed !== undefined ? 
html`<span>in</span>${super.codeStyleRenderer(last.elapsed + ' ms')}` : ''}
+                ${events.some(event => event.failed)
+                    ? html`<qui-badge small 
level="error"><span>Failed</span></qui-badge>`
+                    : html`<qui-badge small 
level="success"><span>Completed</span></qui-badge>`}
+            </vaadin-horizontal-layout>
+            <qwc-camel-core-trace-steps 
.events="${events}"></qwc-camel-core-trace-steps>
+        `;
+    }
+}
+
+customElements.define('qwc-camel-core-message-history', 
QwcCamelCoreMessageHistory);
diff --git 
a/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace-steps.js
 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace-steps.js
new file mode 100644
index 00000000000..8c4c2b3f155
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace-steps.js
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import {LitElement, css, html} from 'lit';
+import {columnBodyRenderer} from '@vaadin/grid/lit.js';
+import '@vaadin/grid';
+import '@vaadin/button';
+import '@vaadin/horizontal-layout';
+import '@qomponent/qui-badge';
+
+/**
+ * Steps through the events Camel's backlog tracer captured for an exchange: 
one event per processor, each holding
+ * a snapshot of the message at that point.
+ */
+export class QwcCamelCoreTraceSteps extends LitElement {
+
+    static styles = css`
+        :host {
+            display: flex;
+            gap: 10px;
+            min-height: 0;
+            flex: 1;
+        }
+
+        .steps {
+            flex: 0 0 40%;
+            min-width: 0;
+        }
+
+        .steps vaadin-grid {
+            height: 100%;
+        }
+
+        .details {
+            flex: 1;
+            min-width: 0;
+            overflow: auto;
+            display: flex;
+            flex-direction: column;
+            gap: 10px;
+            padding: 0 10px 15px 0;
+        }
+
+        h4 {
+            margin: 0;
+        }
+
+        pre {
+            margin: 0;
+            font-size: 85%;
+            white-space: pre-wrap;
+            word-break: break-all;
+        }
+
+        pre.body {
+            max-height: 300px;
+            overflow: auto;
+        }
+
+        table {
+            border-collapse: collapse;
+            font-size: 85%;
+        }
+
+        td {
+            padding: 2px 15px 2px 0;
+            vertical-align: top;
+        }
+
+        code {
+            font-size: 85%;
+        }
+
+        .note {
+            color: var(--lumo-secondary-text-color);
+            font-size: 85%;
+            font-style: italic;
+        }
+
+        .match {
+            font-weight: bold;
+            background: var(--lumo-primary-color-10pct);
+        }
+    `;
+
+    static properties = {
+        events: {type: Array},
+        _selectedUid: {state: true},
+    };
+
+    constructor() {
+        super();
+        this.events = [];
+        this._selectedUid = undefined;
+    }
+
+    willUpdate(changed) {
+        // Keep the selected step across stream updates, unless it is gone, 
e.g. a different exchange was selected
+        if (changed.has('events') && !this.events.some(event => event.uid === 
this._selectedUid)) {
+            this._selectedUid = this.events[0]?.uid;
+        }
+    }
+
+    render() {
+        const index = this._selectedIndex();
+        return html`
+            <div class="steps">
+                <vaadin-grid .items="${this.events}"
+                             .selectedItems="${index >= 0 ? 
[this.events[index]] : []}"
+                             theme="compact no-border row-stripes"
+                             @active-item-changed="${e => 
this._select(e.detail.value)}">
+                    <vaadin-grid-column
+                            header="#"
+                            auto-width
+                            flex-grow="0"
+                            ${columnBodyRenderer((event) => 
html`${this.events.indexOf(event) + 1}`, [this.events])}>
+                    </vaadin-grid-column>
+                    <vaadin-grid-column
+                            header="Route"
+                            auto-width
+                            ${columnBodyRenderer((event) => 
html`<code>${event.routeId ?? ''}</code>`, [])}
+                            resizable>
+                    </vaadin-grid-column>
+                    <vaadin-grid-column
+                            header="Processor"
+                            ${columnBodyRenderer((event) => 
this._processorRenderer(event), [])}
+                            resizable>
+                    </vaadin-grid-column>
+                    <vaadin-grid-column
+                            header="Elapsed"
+                            auto-width
+                            flex-grow="0"
+                            ${columnBodyRenderer((event) => 
html`<code>${event.elapsed} ms</code>`, [])}>
+                    </vaadin-grid-column>
+                    <span slot="empty-state">No steps</span>
+                </vaadin-grid>
+            </div>
+            <div class="details">
+                ${index >= 0 ? this._renderStep(this.events[index], index) : 
''}
+            </div>
+        `;
+    }
+
+    _processorRenderer(event) {
+        const indent = Math.max(0, (event.nodeLevel ?? 1) - 1);
+        return html`
+            <code style="padding-left: 
${indent}em">${this._label(event)}</code>
+            ${event.failed ? html`<qui-badge small 
level="error"><span>Failed</span></qui-badge>` : ''}`;
+    }
+
+    _label(event) {
+        if (event.first) {
+            return `from ${event.endpointUri ?? ''}`;
+        }
+        if (event.last && !event.nodeLabel) {
+            return 'end';
+        }
+        return event.nodeLabel ?? event.nodeShortName ?? event.nodeId ?? '';
+    }
+
+    _renderStep(event, index) {
+        const message = event.message ?? {};
+        return html`
+            <vaadin-horizontal-layout theme="spacing" style="align-items: 
baseline">
+                <vaadin-button theme="small" ?disabled="${index === 0}"
+                               @click="${() => this._select(this.events[index 
- 1])}">Previous</vaadin-button>
+                <vaadin-button theme="small" ?disabled="${index === 
this.events.length - 1}"
+                               @click="${() => this._select(this.events[index 
+ 1])}">Next</vaadin-button>
+                <span>Step ${index + 1} of ${this.events.length}</span>
+            </vaadin-horizontal-layout>
+            <table>
+                ${this._detailRow('Route', event.routeId)}
+                ${this._detailRow('Node ID', event.nodeId)}
+                ${this._detailRow('Processor', this._label(event))}
+                ${this._detailRow('Endpoint', event.endpointUri)}
+                ${this._detailRow('Source', event.location)}
+                ${this._detailRow('Exchange ID', event.exchangeId)}
+                ${this._detailRow('Timestamp', this._toDate(event.timestamp))}
+                ${this._detailRow('Elapsed', event.elapsed !== undefined ? 
event.elapsed + ' ms' : undefined)}
+                ${this._detailRow('Thread', event.threadName)}
+            </table>
+            ${this._renderCode(event.code)}
+            ${this._renderException(event.exception)}
+            ${this._renderBody(message.body)}
+            ${this._renderKeyValues('Headers', message.headers)}
+            ${this._renderKeyValues('Exchange variables', 
message.exchangeVariables)}
+            ${this._renderKeyValues('Exchange properties', 
message.exchangeProperties)}
+        `;
+    }
+
+    _renderBody(body) {
+        if (!body) {
+            return '';
+        }
+        // Camel clips a body longer than camel.trace.bodyMaxChars and says so 
at the end of the value
+        const value = body.value === undefined || body.value === null ? 
undefined : this._unescape(body.value);
+        return html`
+            <h4>Body <code>${body.type ?? ''}</code>${body.size !== undefined 
? html` <code>(${body.size} bytes)</code>` : ''}</h4>
+            ${value !== undefined ? html`<pre class="body">${value}</pre>` : 
html`<span class="note">No body</span>`}`;
+    }
+
+    _renderException(exception) {
+        if (!exception) {
+            return '';
+        }
+        return html`
+            <h4>Exception <code>${exception.type ?? ''}</code></h4>
+            ${exception.message ? html`<pre>${exception.message}</pre>` : ''}
+            ${exception.stackTrace ? html`<pre 
class="body">${this._unescape(exception.stackTrace)}</pre>` : ''}`;
+    }
+
+    _renderCode(code) {
+        if (!code || code.length === 0) {
+            return '';
+        }
+        return html`
+            <h4>Source</h4>
+            <pre>${code.map(line => html`<span class="${line.match ? 'match' : 
''}">${String(line.line).padStart(4)}  
${this._unescape(line.code)}</span>\n`)}</pre>`;
+    }
+
+    _renderKeyValues(title, entries) {
+        if (!entries || entries.length === 0) {
+            return '';
+        }
+        return html`
+            <h4>${title}</h4>
+            <table>
+                ${entries.map(entry => html`
+                    <tr>
+                        <td><code>${entry.key}</code></td>
+                        <td><code>${entry.type ?? ''}</code></td>
+                        <td><code>${typeof entry.value === 'string' ? 
entry.value : JSON.stringify(entry.value)}</code></td>
+                    </tr>`)}
+            </table>`;
+    }
+
+    _detailRow(label, value) {
+        if (value === undefined || value === null || value === '') {
+            return '';
+        }
+        return html`<tr><td>${label}</td><td><code>${value}</code></td></tr>`;
+    }
+
+    _select(event) {
+        // The grid deselects when the active row is clicked again, so keep 
the current step in that case
+        if (event) {
+            this._selectedUid = event.uid;
+        }
+    }
+
+    _selectedIndex() {
+        return this.events.findIndex(event => event.uid === this._selectedUid);
+    }
+
+    _toDate(value) {
+        return value ? new Date(value).toLocaleString().replace(',', '') : '';
+    }
+
+    // Camel escapes the body value, source code lines and stack traces for 
JSON before the console JSON is serialized.
+    // Other values, such as headers and the exception message, are not 
escaped, so must be shown as they are
+    _unescape(value) {
+        if (typeof value !== 'string') {
+            return value ?? '';
+        }
+        return value.replace(/\\(u[0-9a-fA-F]{4}|.)/g, (match, escaped) => {
+            if (escaped.length === 5) {
+                return String.fromCharCode(parseInt(escaped.substring(1), 16));
+            }
+            return this._escapes[escaped] ?? escaped;
+        });
+    }
+
+    _escapes = {'n': '\n', 'r': '\r', 't': '\t', 'b': '\b', 'f': '\f'};
+}
+
+customElements.define('qwc-camel-core-trace-steps', QwcCamelCoreTraceSteps);
diff --git 
a/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace.js
 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace.js
new file mode 100644
index 00000000000..de3cb09be3a
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-trace.js
@@ -0,0 +1,364 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import {css, html} from 'qwc-hot-reload-element';
+import {QwcCamelCore} from "./qwc-camel-core.js";
+import {columnBodyRenderer} from '@vaadin/grid/lit.js';
+import '@vaadin/grid';
+import '@vaadin/grid/vaadin-grid-sort-column.js';
+import '@vaadin/button';
+import '@vaadin/checkbox';
+import '@vaadin/split-layout';
+import '@vaadin/vertical-layout';
+import '@qomponent/qui-badge';
+import './qwc-camel-core-trace-steps.js';
+
+export class QwcCamelCoreTrace extends QwcCamelCore {
+
+    static styles = [QwcCamelCore.styles, css`
+        .content {
+            flex: 1;
+            min-height: 0;
+            display: flex;
+            flex-direction: column;
+        }
+
+        .content > vaadin-grid, .pane > vaadin-grid {
+            flex: 1;
+            min-height: 0;
+        }
+
+        .pane {
+            display: flex;
+            flex-direction: column;
+            min-height: 0;
+            overflow: hidden;
+        }
+
+        .status {
+            align-items: baseline;
+        }
+
+        .note {
+            color: var(--lumo-secondary-text-color);
+            font-size: 85%;
+        }
+
+        .note.evicted {
+            padding: 0 10px;
+            font-style: italic;
+        }
+
+        qwc-camel-core-trace-steps {
+            padding: 10px;
+            min-height: 0;
+        }
+    `];
+
+    static properties = {
+        filterText: {state: true},
+        _status: {state: true},
+        _selectedExchangeId: {state: true},
+        _pausedTraces: {state: true},
+    };
+
+    constructor() {
+        super('trace', {'dump': 'true'});
+        this.filterText = '';
+        this._status = undefined;
+        this._selectedExchangeId = undefined;
+        // Set while the list is paused: the traces it shows
+        this._pausedTraces = undefined;
+        // The selected exchange as last seen. The trace buffer is small, so 
on a busy route an exchange may be
+        // evicted, in whole or in part, while it is being inspected
+        this._selectedSnapshot = undefined;
+        // Exchange summaries by exchange id, reused while their steps are 
unchanged. The grids reset their scroll
+        // position and focus when given new objects, so only hand them new 
ones when something actually changed
+        this._summaries = new Map();
+        // All exchanges in the buffer, and the ones the filter lets through
+        this._allExchanges = [];
+        this._exchangeList = [];
+        this._selectedExchange = undefined;
+    }
+
+    willUpdate(changed) {
+        super.willUpdate?.(changed);
+        const tracesChanged = changed.has('_consoleData') || 
changed.has('_pausedTraces');
+        if (tracesChanged) {
+            this._allExchanges = this._exchanges();
+        }
+        if (tracesChanged || changed.has('filterText')) {
+            const text = this.filterText.toLowerCase();
+            this._exchangeList = this._allExchanges.filter(exchange => !text
+                || (exchange.routeId ?? '').toLowerCase().includes(text)
+                || exchange.exchangeId.toLowerCase().includes(text));
+        }
+        // Look the selection up in every exchange, so filtering it out of the 
list does not look like an eviction
+        if (tracesChanged || changed.has('_selectedExchangeId')) {
+            this._selectedExchange = this._selected(this._allExchanges);
+        }
+    }
+
+    hotReload() {
+        super.hotReload();
+        // Tracing is turned off again when the application restarts, so 
refresh the status too
+        this._updateStatus({});
+    }
+
+    _updateStatus(options) {
+        this.jsonRpc.getConsoleJSON({'id': 'trace', 'options': 
options}).then(response => {
+            this._status = JSON.parse(response.result);
+        });
+    }
+
+    _enabled() {
+        // The streamed dump carries the current state, so it also reflects 
changes made elsewhere
+        return this.consoleData()['enabled'] ?? this._status?.enabled;
+    }
+
+    _traces() {
+        return this._pausedTraces ?? this.consoleData()['traces'] ?? [];
+    }
+
+    _togglePause() {
+        this._pausedTraces = this._pausedTraces ? undefined : 
[...(this.consoleData()['traces'] ?? [])];
+    }
+
+    _exchanges() {
+        const byExchange = new Map();
+        this._traces().forEach(event => {
+            if (!byExchange.has(event.exchangeId)) {
+                byExchange.set(event.exchangeId, []);
+            }
+            byExchange.get(event.exchangeId).push(event);
+        });
+        const summaries = [...byExchange.entries()].map(([exchangeId, events]) 
=> this._reuse(this._summarise(exchangeId, events)));
+        // Forget exchanges that have left the buffer
+        this._summaries = new Map(summaries.map(summary => 
[summary.exchangeId, summary]));
+        return summaries.sort((a, b) => b.timestamp - a.timestamp);
+    }
+
+    // Camel records a step when its processor starts, and sets done, elapsed 
and any exception when it finishes, so a
+    // step seen in flight must be refreshed once it completes
+    static _sameStep(a, b) {
+        return a !== undefined && a.uid === b.uid && a.done === b.done && 
a.failed === b.failed;
+    }
+
+    _reuse(summary) {
+        const previous = this._summaries.get(summary.exchangeId);
+        const unchanged = previous
+            && previous.steps === summary.steps
+            && summary.events.every((event, i) => 
QwcCamelCoreTrace._sameStep(previous.events[i], event));
+        if (unchanged) {
+            return previous;
+        }
+        this._summaries.set(summary.exchangeId, summary);
+        return summary;
+    }
+
+    _summarise(exchangeId, events) {
+        events.sort((a, b) => a.uid - b.uid);
+        const first = events[0];
+        // The buffer evicts the oldest events first, so an exchange may have 
lost its start. Its first remaining
+        // event may then belong to a sub-route, so the route, completion and 
elapsed time of the exchange are unknown
+        const partial = !first.first;
+        const last = partial ? undefined : events.findLast(event => event.last 
&& event.routeId === first.routeId);
+        return {
+            exchangeId: exchangeId,
+            routeId: partial ? undefined : first.routeId,
+            timestamp: first.timestamp,
+            steps: events.length,
+            elapsed: last?.elapsed,
+            failed: events.some(event => event.failed),
+            done: last !== undefined,
+            partial: partial,
+            events: events,
+        };
+    }
+
+    _selected(exchanges) {
+        if (this._selectedExchangeId === undefined) {
+            return undefined;
+        }
+        const current = exchanges.find(exchange => exchange.exchangeId === 
this._selectedExchangeId);
+        const previous = this._selectedSnapshot?.exchangeId === 
this._selectedExchangeId ? this._selectedSnapshot : undefined;
+        if (!current) {
+            if (previous && !previous.evicted) {
+                // Same steps as before, so the step viewer keeps its position
+                this._selectedSnapshot = {...previous, evicted: true};
+            }
+            return previous ? this._selectedSnapshot : undefined;
+        }
+        if (previous && !previous.evicted
+            && current.events.every(event => 
QwcCamelCoreTrace._sameStep(previous.byUid.get(event.uid), event))) {
+            return previous;
+        }
+        // Keep steps seen earlier that have since been evicted, and add or 
refresh the current ones
+        const events = new Map((previous?.events ?? []).map(event => 
[event.uid, event]));
+        current.events.forEach(event => events.set(event.uid, event));
+        const snapshot = this._summarise(current.exchangeId, 
[...events.values()]);
+        snapshot.byUid = events;
+        this._selectedSnapshot = snapshot;
+        return snapshot;
+    }
+
+    render() {
+        if (this._status !== undefined && this._status['enabled'] === 
undefined) {
+            return html`
+                <vaadin-horizontal-layout class="empty-container">
+                    Camel tracing is not available. Set 
camel.trace.standby=true to allow tracing to be turned on at runtime.
+                </vaadin-horizontal-layout>`;
+        }
+        const exchanges = this._exchangeList;
+        const selected = this._selectedExchange;
+        return html`
+            <vaadin-horizontal-layout theme="spacing padding" class="status">
+                <vaadin-checkbox
+                        label="Tracing enabled"
+                        .checked="${this._enabled() === true}"
+                        @change="${e => this._updateStatus({'enabled': 
String(e.target.checked)})}">
+                </vaadin-checkbox>
+                <vaadin-button theme="small" @click="${() => 
this._togglePause()}">
+                    <vaadin-icon slot="prefix" 
icon="font-awesome-solid:${this._pausedTraces ? 'play' : 
'pause'}"></vaadin-icon>
+                    ${this._pausedTraces ? 'Resume' : 'Pause'}
+                </vaadin-button>
+                ${this._status?.bodyMaxChars !== undefined ? html`
+                    <span class="note">Message bodies longer than 
${this._status.bodyMaxChars} characters are clipped 
(camel.trace.bodyMaxChars)</span>` : ''}
+            </vaadin-horizontal-layout>
+            <vaadin-horizontal-layout theme="spacing padding">
+                <vaadin-text-field
+                        style="width: 100%"
+                        placeholder="Filter by route or exchange ID"
+                        @input=${e => this.filterText = e.target.value}
+                        clear-button-visible>
+                    <vaadin-icon slot="prefix" 
icon="font-awesome-solid:magnifying-glass"></vaadin-icon>
+                </vaadin-text-field>
+            </vaadin-horizontal-layout>
+            ${this._renderContent(exchanges, selected)}
+        `;
+    }
+
+    _renderContent(exchanges, selected) {
+        const list = exchanges.length === 0 ? this._renderEmpty() : 
this._renderExchanges(exchanges, selected);
+        if (!selected) {
+            return html`<div class="content">${list}</div>`;
+        }
+        // Split the height between the exchange list and the steps of the 
selected exchange
+        return html`
+            <vaadin-split-layout orientation="vertical" class="content">
+                <div class="pane" style="flex: 0 0 35%">${list}</div>
+                <div class="pane">${this._renderSelected(selected)}</div>
+            </vaadin-split-layout>`;
+    }
+
+    _renderSelected(selected) {
+        const notes = [];
+        if (selected.evicted) {
+            notes.push('This exchange is no longer in the trace buffer, 
showing the steps captured earlier.');
+        }
+        if (selected.partial) {
+            notes.push('Earlier steps of this exchange were evicted from the 
trace buffer before they could be shown.');
+        }
+        return html`
+            ${notes.map(note => html`<span class="note 
evicted">${note}</span>`)}
+            <qwc-camel-core-trace-steps 
.events="${selected.events}"></qwc-camel-core-trace-steps>`;
+    }
+
+    _renderEmpty() {
+        const message = this._enabled()
+            ? 'Waiting for exchanges to be traced'
+            : 'Tracing is disabled. Enable it to capture exchanges.';
+        return html`
+            <vaadin-horizontal-layout class="empty-container">
+                ${message}
+            </vaadin-horizontal-layout>`;
+    }
+
+    _renderExchanges(exchanges, selected) {
+        return html`
+            <vaadin-grid .items="${exchanges}"
+                         .selectedItems="${selected ? [selected] : []}"
+                         item-id-path="exchangeId"
+                         theme="no-border row-stripes"
+                         @active-item-changed="${e => 
this._select(e.detail.value)}">
+                <vaadin-grid-sort-column
+                        path="timestamp"
+                        auto-width
+                        header="Started"
+                        ${columnBodyRenderer((exchange) => 
super.codeStyleRenderer(super.toDate(exchange.timestamp)), [])}
+                        resizable>
+                </vaadin-grid-sort-column>
+                <vaadin-grid-sort-column
+                        path="routeId"
+                        auto-width
+                        header="Route ID"
+                        ${columnBodyRenderer((exchange) => 
super.codeStyleRenderer(exchange.routeId), [])}
+                        resizable>
+                </vaadin-grid-sort-column>
+                <vaadin-grid-sort-column
+                        path="exchangeId"
+                        header="Exchange ID"
+                        ${columnBodyRenderer((exchange) => 
super.codeStyleRenderer(exchange.exchangeId), [])}
+                        resizable>
+                </vaadin-grid-sort-column>
+                <vaadin-grid-sort-column
+                        path="steps"
+                        auto-width
+                        header="Steps"
+                        ${columnBodyRenderer((exchange) => 
super.numericPillStyleRenderer(exchange.steps), [])}
+                        resizable>
+                </vaadin-grid-sort-column>
+                <vaadin-grid-sort-column
+                        path="elapsed"
+                        auto-width
+                        header="Elapsed"
+                        ${columnBodyRenderer((exchange) => 
super.codeStyleRenderer(exchange.elapsed !== undefined ? exchange.elapsed + ' 
ms' : ''), [])}
+                        resizable>
+                </vaadin-grid-sort-column>
+                <vaadin-grid-column
+                        auto-width
+                        header="Status"
+                        ${columnBodyRenderer((exchange) => 
this._statusRenderer(exchange), [])}
+                        resizable>
+                </vaadin-grid-column>
+            </vaadin-grid>
+        `;
+    }
+
+    _statusRenderer(exchange) {
+        const partial = exchange.partial ? html` <qui-badge small 
level="warning"><span>Partial</span></qui-badge>` : '';
+        if (exchange.failed) {
+            return html`<qui-badge small 
level="error"><span>Failed</span></qui-badge>${partial}`;
+        }
+        if (exchange.partial) {
+            // Whether it completed is unknown without the start of the 
exchange
+            return partial;
+        }
+        if (exchange.done) {
+            return html`<qui-badge small 
level="success"><span>Completed</span></qui-badge>`;
+        }
+        return html`<qui-badge small><span>In progress</span></qui-badge>`;
+    }
+
+    _select(exchange) {
+        // The grid deselects when the active row is clicked again, so keep 
the current exchange in that case
+        if (exchange) {
+            this._selectedExchangeId = exchange.exchangeId;
+        }
+    }
+}
+
+customElements.define('qwc-camel-core-trace', QwcCamelCoreTrace);
diff --git 
a/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUITraceTest.java
 
b/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUITraceTest.java
new file mode 100644
index 00000000000..9cdda41f5d6
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUITraceTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.quarkus.core.deployment.devui;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+
+import io.quarkus.devui.tests.DevUIJsonRPCTest;
+import io.quarkus.test.QuarkusDevModeTest;
+import io.vertx.core.json.Json;
+import io.vertx.core.json.JsonArray;
+import io.vertx.core.json.JsonObject;
+import org.apache.camel.builder.RouteBuilder;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class CamelQuarkusCoreDevUITraceTest extends DevUIJsonRPCTest {
+    @RegisterExtension
+    static final QuarkusDevModeTest CONFIG = new QuarkusDevModeTest()
+            .withApplicationRoot(jar -> jar
+                    .addClass(TracedRoute.class)
+                    .addAsResource(new 
StringAsset("camel.trace.bodyMaxChars=20"), "application.properties"));
+
+    public CamelQuarkusCoreDevUITraceTest() {
+        super("org.apache.camel.quarkus.camel-quarkus-core");
+    }
+
+    @Test
+    void traceCanBeToggledAndDumped() throws Exception {
+        // Dev mode puts the tracer on standby, so it can be turned on at 
runtime
+        JsonObject status = trace(Map.of());
+        assertTrue(status.getBoolean("standby"));
+        assertFalse(status.getBoolean("enabled"));
+        assertEquals(20, status.getInteger("bodyMaxChars"));
+
+        // Values other than true and false are stripped, so they do not 
change the state
+        assertFalse(trace(Map.of("enabled", "maybe")).getBoolean("enabled"));
+
+        assertTrue(trace(Map.of("enabled", "true")).getBoolean("enabled"));
+        try {
+            List<JsonObject> events = 
await().atMost(Duration.ofSeconds(10)).until(
+                    () -> traces(trace(Map.of("dump", "true"))),
+                    traces -> traces.stream().anyMatch(event -> 
event.getBoolean("last")));
+
+            assertTrue(events.stream().allMatch(event -> 
"traced".equals(event.getString("routeId"))));
+            JsonObject message = events.stream()
+                    .map(event -> event.getJsonObject("message"))
+                    .filter(m -> m.getJsonObject("body").getString("value", 
"").startsWith("01234567890123456789"))
+                    .findFirst()
+                    .orElseThrow();
+            
assertTrue(message.getJsonObject("body").getString("value").contains("Body 
clipped after 20 chars"));
+            assertTrue(containsKey(message.getJsonArray("headers"), 
"greeting"));
+            assertTrue(containsKey(message.getJsonArray("exchangeVariables"), 
"colour"));
+        } finally {
+            assertFalse(trace(Map.of("enabled", 
"false")).getBoolean("enabled"));
+        }
+    }
+
+    @Test
+    void messageHistoryIsCapturedWithTracingOnStandby() {
+        JsonObject history = await().atMost(Duration.ofSeconds(10)).until(
+                () -> console("message-history", Map.of()),
+                json -> json.getJsonArray("traces") != null && 
!json.getJsonArray("traces").isEmpty());
+
+        assertEquals("camel-1", history.getString("name"));
+        List<JsonObject> events = traces(history);
+        assertTrue(events.stream().allMatch(event -> 
"traced".equals(event.getString("routeId"))));
+        assertTrue(events.stream().anyMatch(event -> 
event.getBoolean("last")));
+    }
+
+    private JsonObject trace(Map<String, Object> options) throws Exception {
+        return console("trace", options);
+    }
+
+    private JsonObject console(String id, Map<String, Object> options) throws 
Exception {
+        String result = super.executeJsonRPCMethod(String.class, 
"getConsoleJSON", Map.of("id", id, "options", options));
+        return (JsonObject) Json.decodeValue(result);
+    }
+
+    private static List<JsonObject> traces(JsonObject console) {
+        JsonArray traces = console.getJsonArray("traces");
+        if (traces == null) {
+            return List.of();
+        }
+        return traces.stream().map(JsonObject.class::cast).toList();
+    }
+
+    private static boolean containsKey(JsonArray entries, String key) {
+        return entries != null && entries.stream()
+                .map(JsonObject.class::cast)
+                .anyMatch(entry -> key.equals(entry.getString("key")));
+    }
+
+    public static class TracedRoute extends RouteBuilder {
+        // Longer than camel.trace.bodyMaxChars, so the tracer clips it
+        static final String BODY = "0123456789".repeat(10);
+
+        @Override
+        public void configure() {
+            from("timer:trace?period=200")
+                    .routeId("traced")
+                    .setHeader("greeting", constant("hello"))
+                    .setVariable("colour", constant("blue"))
+                    .setBody(constant(BODY)).id("body")
+                    .log("${body}");
+        }
+    }
+}

Reply via email to