Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions packages/logger/lib/loggers/Serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,15 @@ class Serve extends Logger {
this.#emitStatus("serve-building", {}, `Building...`);
}

buildDone(hrtime) {
buildDone(hrtime, builtProjects = []) {
if (!Array.isArray(hrtime) || hrtime.length !== 2 ||
typeof hrtime[0] !== "number" || typeof hrtime[1] !== "number") {
throw new Error("loggers/Serve#buildDone: Missing or incorrect hrtime parameter");
}
this.#emitStatus("serve-build-done", {hrtime},
if (!Array.isArray(builtProjects)) {
throw new Error("loggers/Serve#buildDone: Missing or incorrect builtProjects parameter");
}
this.#emitStatus("serve-build-done", {hrtime, builtProjects},
`Build finished in ${prettyHrtime(hrtime)}`);
}

Expand Down
100 changes: 90 additions & 10 deletions packages/logger/lib/writers/InteractiveConsole.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@ import {
SPINNING_STATES, enableBuildPlaceholders, setDegraded, clearDegraded,
} from "./interactiveConsole/state/build.js";
import {
renderHeaderRegion, renderProjectRegion, renderServerRegion, renderBuildRegion,
createInspectState, setInspectNow, recordRequestStart, recordRequestEnd,
recordBuildStart, recordBuildProject, recordBuildDone, needsInspectTick,
} from "./interactiveConsole/state/inspect.js";
import {
renderHeaderRegion, renderProjectRegion, renderServerRegion, renderBuildRegion, renderInspectRegion,
} from "./interactiveConsole/render.js";

// Spinner tick interval while in `building` or `validating` state.
const BUILDING_TICK_MS = 120;

// Slower tick that animates the inspect waterfall while requests are in flight but no build spinner
// is already driving renders. In-flight bars grow at this cadence.
const INSPECT_TICK_MS = 250;

// Module names whose info-level logs duplicate state the banner already renders
// via named build events (ui5.build-metadata / ui5.build-status). Their info
// lines are suppressed so they don't scroll above the live region. Warnings and
Expand Down Expand Up @@ -78,6 +86,10 @@ class InteractiveConsole {
#projectState;
#serverState;
#buildState;
#inspectState;
// Opt-in debug waterfall. Read once from UI5_CLI_INSPECT; when false the region never renders
// and the `ui5.serve-request` listener is never attached. See state/inspect.js.
#inspectEnabled = !!process.env.UI5_CLI_INSPECT;

#tickTimer = null;
#columns;
Expand Down Expand Up @@ -114,6 +126,7 @@ class InteractiveConsole {
#onServerListening;
#onStopConsole;
#onResize;
#onServeRequest;

// Termination-signal handlers (plus an `exit` catch-all), keyed by event
// name, so disable() detaches exactly what enable() registered.
Expand All @@ -125,6 +138,7 @@ class InteractiveConsole {
this.#projectState = createProjectState();
this.#serverState = createServerState();
this.#buildState = createBuildState();
this.#inspectState = createInspectState();
this.#columns = stderr.columns;
}

Expand Down Expand Up @@ -231,14 +245,27 @@ class InteractiveConsole {
...renderServerRegion(this.#serverState),
...renderBuildRegion(this.#buildState),
];
let inspectLines = [];
if (this.#inspectEnabled) {
// Stamp the render clock on the shared process.hrtime() scale so the selector and renderer
// stay pure, then append the waterfall below the other regions.
setInspectNow(this.#inspectState, process.hrtime());
// Cap the reader rows to the space left below the banner so the banner is never clipped by
// log-update. The inspect region spends two lines on its blank separator and header before
// any reader row. A non-TTY stderr has no `rows`; leave it uncapped there.
const rows = this.#stderr.rows;
const maxDataRows = rows ? Math.max(0, rows - lines.length - 2) : Infinity;
inspectLines = renderInspectRegion(this.#inspectState, this.#columns, maxDataRows);
lines.push(...inspectLines);
}
if (lines.length === 0) {
return "";
}
// `log-update` wraps long lines onto additional rows; the last line is
// designed to fit on a single row when it's a status line, so clip it
// to the terminal width. `this.#columns` is undefined when stderr isn't
// a TTY — sliceAnsi treats that as "no limit" and returns unchanged.
if (this.#buildState.state !== STATES.INITIAL) {
// `log-update` wraps long lines onto additional rows; the last line is designed to fit on a
// single row (the status line, or an inspect bar line), so clip it to the terminal width.
// `this.#columns` is undefined when stderr isn't a TTY. sliceAnsi treats that as "no limit"
// and returns unchanged.
if (this.#buildState.state !== STATES.INITIAL || inspectLines.length > 0) {
lines[lines.length - 1] = sliceAnsi(lines[lines.length - 1], 0, this.#columns);
}
return lines.join("\n");
Expand Down Expand Up @@ -306,6 +333,7 @@ class InteractiveConsole {
this.#onServerListening = (evt) => this.#handleServerListening(evt);
this.#onStopConsole = () => this.disable();
this.#onResize = () => this.#handleResize();
this.#onServeRequest = (evt) => this.#handleServeRequest(evt);

process.on("ui5.log", this.#onLog);
process.on("ui5.build-metadata", this.#onBuildMetadata);
Expand All @@ -320,6 +348,11 @@ class InteractiveConsole {
process.on("ui5.project-resolve-failed", this.#onProjectResolveFailed);
process.on("ui5.server-listening", this.#onServerListening);
process.on("ui5.log.stop-console", this.#onStopConsole);
// The request feed is high-frequency on the serve hot path, so subscribe only when inspect
// mode is on. Its producer (BuildReader) is likewise gated, so nothing is emitted when off.
if (this.#inspectEnabled) {
process.on("ui5.serve-request", this.#onServeRequest);
}
if (typeof this.#stderr.on === "function") {
this.#stderr.on("resize", this.#onResize);
}
Expand All @@ -339,6 +372,9 @@ class InteractiveConsole {
process.off("ui5.project-resolve-failed", this.#onProjectResolveFailed);
process.off("ui5.server-listening", this.#onServerListening);
process.off("ui5.log.stop-console", this.#onStopConsole);
if (this.#inspectEnabled) {
process.off("ui5.serve-request", this.#onServeRequest);
}
if (typeof this.#stderr.off === "function") {
this.#stderr.off("resize", this.#onResize);
}
Expand Down Expand Up @@ -430,8 +466,11 @@ class InteractiveConsole {
}
}

#handleProjectBuildStatus({taskName, status}) {
#handleProjectBuildStatus({projectName, taskName, status}) {
if (status === "task-start") {
if (this.#inspectEnabled) {
recordBuildProject(this.#inspectState, projectName);
}
setTask(this.#buildState, taskName);
this.#render();
}
Expand Down Expand Up @@ -467,6 +506,11 @@ class InteractiveConsole {
break;
case "serve-building":
beginBuild(this.#buildState, this.#buildState.projectOrder);
if (this.#inspectEnabled) {
// Stamp the cycle start on the shared process.hrtime() clock so the inspect selector
// can overlap it against in-flight request intervals.
recordBuildStart(this.#inspectState, process.hrtime());
}
this.#transitionTo(STATES.BUILDING);
break;
case "serve-validating":
Expand All @@ -475,6 +519,10 @@ class InteractiveConsole {
break;
case "serve-build-done":
this.#buildState.lastBuildHrtime = Array.isArray(evt.hrtime) ? evt.hrtime : null;
if (this.#inspectEnabled) {
recordBuildDone(
this.#inspectState, process.hrtime(), this.#buildState.lastBuildHrtime);
}
this.#transitionTo(STATES.READY);
break;
case "serve-error":
Expand All @@ -495,6 +543,19 @@ class InteractiveConsole {
this.#render();
}

// Feeds the `ui5.serve-request` lifecycle into the inspect waterfall. A `start` arriving while the
// banner is otherwise idle has no spinner driving renders, so #scheduleTick is nudged to animate
// the in-flight bars until they resolve.
#handleServeRequest(evt) {
if (evt.phase === "start") {
recordRequestStart(this.#inspectState, evt);
} else if (evt.phase === "end") {
recordRequestEnd(this.#inspectState, evt);
}
this.#render();
this.#scheduleTick();
}

#transitionTo(newState) {
if (this.#buildState.state === newState) {
this.#render();
Expand All @@ -506,20 +567,38 @@ class InteractiveConsole {
this.#render();
}

// Whether a tick is warranted right now: a spinning build state, growing inspect bars, or a
// completed inspect wave that has not reached its quiet-gap marker.
#needsTick() {
if (SPINNING_STATES.has(this.#buildState.state)) {
return true;
}
return this.#inspectEnabled && needsInspectTick(this.#inspectState);
}

#scheduleTick() {
/* istanbul ignore if — defensive: #scheduleTick is only reached from
event handlers (detached on disable), so #stopped is always false
here in practice. */
if (this.#stopped) {
if (this.#stopped || this.#tickTimer) {
return;
}
if (!SPINNING_STATES.has(this.#buildState.state)) {
if (!this.#needsTick()) {
return;
}
// A spinning build drives the fast spinner cadence. Inspect-only animation ticks slower.
const interval = SPINNING_STATES.has(this.#buildState.state) ? BUILDING_TICK_MS : INSPECT_TICK_MS;
this.#tickTimer = setInterval(() => {
if (!this.#needsTick()) {
// Nothing left to animate (requests resolved, build settled): stop and paint the
// final frame once, so an in-flight bar lands on its resolved width.
this.#clearTick();
this.#render();
return;
}
this.#buildState.spinFrame++;
this.#render();
}, BUILDING_TICK_MS);
}, interval);
// Don't keep the event loop alive purely for the banner spinner.
if (typeof this.#tickTimer.unref === "function") {
this.#tickTimer.unref();
Expand Down Expand Up @@ -629,6 +708,7 @@ class InteractiveConsole {
project: this.#projectState,
server: this.#serverState,
build: this.#buildState,
inspect: this.#inspectState,
};
}
}
Expand Down
140 changes: 140 additions & 0 deletions packages/logger/lib/writers/interactiveConsole/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import chalk from "chalk";
import figures from "figures";
import prettyHrtime from "pretty-hrtime";
import {STATES} from "./state/build.js";
import {buildInspectRows, isNewWaveReady} from "./state/inspect.js";
import {brand, accent, accentBold, arrow, placeholder} from "./format.js";
import {REMOTE_CONNECTIONS_WARNING_LINES} from "./remoteConnectionsWarning.js";

Expand Down Expand Up @@ -216,3 +217,142 @@ function renderStatusLine(state) {
return label;
}
}

// Cap the project-name column so one long name can't crowd out the bar.
const INSPECT_NAME_CAP = 24;
// Floor on the bar width so a narrow terminal still shows a bar rather than nothing.
const INSPECT_MIN_BAR = 8;
// Default width when stderr is not a TTY (`columns` is undefined), so the selector still produces
// readable bars in captured output.
const INSPECT_DEFAULT_COLUMNS = 80;
const INSPECT_BAR_OFFSET = "░";
const INSPECT_BAR_ACTIVE = "█";

// Renders the inspect waterfall: one header line plus one line per project reader or indirectly built
// dependency for the current wave, in the stable first-seen order the selector produces. Each row is
// color-coded by state (orange while stale/building, dimmed grey once ready, red on error). The
// bracket after the name holds the build duration(s). Returns [] when there is nothing to show, so
// the region collapses like the others. `columns` scales the bars to the terminal width. `maxRows`
// caps the number of data lines to what fits below the banner. The overflow collapses into a trailing
// "+N more readers" line so the banner is never clipped. Pass Infinity (or omit) for no cap.
export function renderInspectRegion(inspectState, columns, maxRows = Infinity) {
const allRows = buildInspectRows(inspectState);
if (allRows.length === 0 || maxRows < 1) {
return [];
}
// Keep as many rows as fit; when some don't, give up one row slot to the "+N more" summary.
let rows = allRows;
let overflow = 0;
if (allRows.length > maxRows) {
const shown = Math.max(0, maxRows - 1);
rows = allRows.slice(0, shown);
overflow = allRows.length - shown;
}
const nameWidth = Math.min(
INSPECT_NAME_CAP, rows.reduce((max, row) => Math.max(max, row.name.length), 0));
// The label widens to fit a built reader's time(s) (e.g. "(built 1.2 s)" or
// "(built 30 ms, 45 ms)"), so size it to the content.
const labelWidth = rows.reduce((max, row) => Math.max(max, inspectLabel(row).length), 0);
// The request count sits in front of the bar; size its column to the widest count so the bars line
// up in one column regardless of how many digits each count needs.
const countWidth = rows.reduce((max, row) => Math.max(max, inspectCount(row).length), 0);
const totalWidth = columns || INSPECT_DEFAULT_COLUMNS;
const prefixWidth = 1 + nameWidth + 1 + labelWidth + 2 + countWidth + 2;
const barWidth = Math.max(INSPECT_MIN_BAR, totalWidth - prefixWidth);
const ready = isNewWaveReady(inspectState) ?
`${chalk.dim("|")} ${chalk.yellow(`${figures.info} new wave on next request`)}` : "";
const lines = ["", `${chalk.dim("Inspect")} ${ready}`];
for (const row of rows) {
lines.push(renderInspectRow(row, nameWidth, labelWidth, countWidth, barWidth));
}
if (overflow > 0) {
lines.push(` ${chalk.dim(`+${overflow} more readers`)}`);
}
return lines;
}

// The color applied to a reader's name and bar: dim grey for a ready reader, yellow for a completed
// miss, red for an errored one, and the brand color for anything still stale or building.
function inspectColor(row) {
if (row.notFound) {
return chalk.yellow;
}
const {klass} = row;
if (klass === "ready") {
return chalk.dim;
}
if (klass === "error") {
return chalk.red;
}
return brand;
}

// The label shown between the name and the request count. When the reader's requests triggered a
// build, it holds the build duration(s) so the timing always reads in one place; otherwise it names
// the request outcome or reader state. A reader served straight from a warm cache (no build) reads
// as "(cached)".
function inspectLabel(row) {
if (row.dependency) {
if (row.buildHrs.length > 0) {
return `(dependency built ${row.buildHrs.map((hr) => prettyHrtime(hr)).join(", ")})`;
}
return row.building ? "(dependency building)" : "(dependency built)";
}
if (row.buildHrs.length > 0) {
return `(built ${row.buildHrs.map((hr) => prettyHrtime(hr)).join(", ")})`;
}
if (row.notFound) {
return "(not found)";
}
if (row.klass === "ready") {
return "(cached)";
}
return `(${row.klass})`;
}

// The build duration(s) turn red once a reader was built more than once in a wave: a repeated build
// of the same project within one request wave is the expensive pattern this view exists to surface.
// A single build, or a plain state label, keeps the row's own color.
function inspectLabelColor(row, color) {
return row.buildHrs.length >= 2 ? chalk.red : color;
}

function inspectCount(row) {
if (row.dependency) {
return "";
}
return `${row.reqCount} req${row.reqCount === 1 ? "" : "s"}`;
}

// Paints a reader's bar: one block of █ per request segment, dim ░ for the lead-in and for the gaps
// between segments. Several bursts to the same reader within a wave therefore show as several blocks.
// A reader row always carries at least one request, so `segments` is never empty.
function inspectBar(segments, barWidth, color) {
const active = new Array(barWidth).fill(false);
let lastCell = 0;
for (const segment of segments) {
const start = Math.min(barWidth, Math.max(0, Math.round(segment.startFrac * barWidth)));
let end = Math.min(barWidth, Math.round(segment.endFrac * barWidth));
if (end <= start) {
end = Math.min(barWidth, start + 1);
}
for (let i = start; i < end; i++) {
active[i] = true;
}
lastCell = Math.max(lastCell, end);
}
let bar = "";
for (let i = 0; i < lastCell; i++) {
bar += active[i] ? color(INSPECT_BAR_ACTIVE) : chalk.dim(INSPECT_BAR_OFFSET);
}
return bar;
}

function renderInspectRow(row, nameWidth, labelWidth, countWidth, barWidth) {
const color = inspectColor(row);
const name = row.name.length > nameWidth ? row.name.slice(0, nameWidth) : row.name.padEnd(nameWidth);
const label = inspectLabel(row).padEnd(labelWidth);
const count = inspectCount(row).padStart(countWidth);
const bar = inspectBar(row.segments, barWidth, color);
return ` ${color(name)} ${inspectLabelColor(row, color)(label)} ${chalk.dim(count)} ${bar}`;
}
Loading
Loading