diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d169fd..ad6af29f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,20 @@ platform API version. seven graphs of a real design. The estimate is good to about a factor of two. +- **The layout rates of a product** (`DiagramProfile.elkServer.rates`, + `ElkServerOptions.rates`). The rates of the platform were measured with its + own layout options, and a product that lays out with other options can be + far from them. mlir-viewer has a configurator of its own: one function of + 6,172 nodes, 5,960 of them in one block, is 24 s on elkjs by the middle + rates and 12 min by the rates mlir measured, and elkjs was still on it + after 35 minutes. A product that measured its layout names its rates + beside its jar. `auto` then chooses the engine by them, a layout elkjs is + not to take is refused by them, and the log gives their estimate beside + the time a layout took. One set prices every layout of the product, so a + product that lays out with the presets of the platform names none, and is + priced as before. Rates that are not four numbers for each engine, one of + them above zero, are said in the log and left out. + - **A `ram` flow symbol.** The flow symbols (`FlowSymbols`, the dataflow pictograms a product draws a node as) have a 29th kind, `ram`, in the memory family: a memory itself, with no operand and one result. `memory` @@ -148,18 +162,52 @@ platform API version. nodes. Every layout logs its estimate beside the time it took (`[dialogram layout] elkjs: 40 nodes, 110 edges in 229 ms (estimated 228 ms)`). -- **A layout the ELK server did not answer is refused when elkjs would not - finish it in the same time.** The server's timeout - (`.layout.serverTimeoutMs`, 120 s) or failure used to - hand any graph to elkjs, which runs on the extension host's thread: a - graph the server could not finish in two minutes held every diagram, and - the host, for many times that. Such a layout now fails with a - `LayoutRefusedError`, and the diagram says on its status line that it was - not laid out, with the estimate. A graph elkjs is estimated to finish - within the timeout still falls back to it, or within a minute when the - timeout is shorter (`elkjsTakeoverMs`), and so does every graph when there - is no server to ask (no Java, no jar): elkjs is all there is then. A Free - Ports layout is refused at its probe, so the server is asked once. +- **elkjs takes no layout it would hold the host for: such a graph is the + ELK server's alone.** elkjs runs on the extension host's thread. A graph + the server could not finish in two minutes, or one opened without Java, + went to elkjs and held every diagram, and the host, for many times that: + one function of 6,172 nodes in mlir-viewer was still on elkjs after 35 + minutes. Whoever was to lay a graph out, elkjs now takes it only when it is + estimated to finish within a minute (`ELKJS_BUDGET_MS`), whatever the + server's timeout. That holds for a server that timed out or failed, for one + that is not running (no Java, no jar), and with `layout.engine` set to + `elkjs`, where the switch now stands before elkjs too and starts no server. + Past the estimate the layout fails with a `LayoutRefusedError`, and the + diagram says on its status line that it was not laid out, why the server + did not lay it out, and what elkjs would have taken. A diagram that was + never laid out stays so, with that line. A Free Ports layout is refused at + its probe, so the server is asked once. A server that cannot start says + what it failed on (`ElkServerProcess.failure`): a `java` that is not there + could not be run, with the error of the system, and one that ends at once + (a Java before 17, an option it does not know) exited, with the line that + names the error, where both were reported as a server slow to start. A + graph of another algorithm than layered has no estimate, and is not + refused by this rule. + +- **A server a layout timed out on is ended.** A layout that ran past its + time cannot be taken back from the ELK server, which stayed on it with + nobody waiting: a core and a gigabyte of heap, for minutes on a graph of + thousands of nodes, while the next layouts queued behind it. A server that + had a minute or more for the layout (`ELK_SERVER_STUCK_MS`) is retired, as + one that overflowed its stack is. It answers what else it was asked and is + then ended, and the next layout starts another. With a shorter timeout the + server is left to finish, so that a JVM is not ended at every layout. An + answer that arrived while the host was busy is read before the timeout is + called. + +- **The status line is read without the pointer.** What the server says of + a diagram (a `StatusAction`: a layout that was refused, one that was run + roughly) was an icon in the top left corner, under the controls of a + product, with its words shown only under the pointer. A warning or an + error is now a line at the bottom left of the canvas, over the crumbs, in + the look of the loading pill, with the words in it. It keeps clear of the + property panel and of an open outline panel, goes to the top left while + the chat card is shown, and a fit keeps the drawing clear of it. GLSP's + own progress in the same place ("Model loading in progress") is not + drawn: the loading indicator tells it. The note of a rough layout is a + warning now, so that it is on the line. The rules are `status-line.css`, + which a product with a stylesheet of its own imports alone. + - **A layout that fails leaves the diagram as it was.** The layout commands clear every edge route before ELK is asked, and Untangled and Free Ports move the ports first. A layout that then failed, for any reason, left the diff --git a/packages/diagram-client/src/canvas-overlays.ts b/packages/diagram-client/src/canvas-overlays.ts index 1d821f83..e1c03a6a 100644 --- a/packages/diagram-client/src/canvas-overlays.ts +++ b/packages/diagram-client/src/canvas-overlays.ts @@ -36,6 +36,8 @@ export const CANVAS_OVERLAYS = [ '.minimize-palette-button', '.floating-tool-btn', '.workflow-breadcrumb-overlay', + // The status line (status-line.css): not drawn, and so not counted, without words. + '.sprotty-status', '.workflow-fab-stack', '.property-panel.floating:not(.collapsed)', '.workflow-chat-panel.visible', diff --git a/packages/diagram-client/src/diagram-client.css b/packages/diagram-client/src/diagram-client.css index 30791268..b39499a2 100644 --- a/packages/diagram-client/src/diagram-client.css +++ b/packages/diagram-client/src/diagram-client.css @@ -22,6 +22,7 @@ @import './floating-buttons.css'; @import './hierarchy-outline.css'; @import './diagram-find.css'; +@import './status-line.css'; :root { --sprotty-background: var(--vscode-editor-background, #1e1e1e); diff --git a/packages/diagram-client/src/status-line.css b/packages/diagram-client/src/status-line.css new file mode 100644 index 00000000..51008317 --- /dev/null +++ b/packages/diagram-client/src/status-line.css @@ -0,0 +1,103 @@ +/** + * The status line: what the diagram's server says of the diagram (GLSP's + * status overlay, a `StatusAction`). Its own stylesheet, as the loading + * indicator has, so a product with a stylesheet of its own imports it alone: + * `import '@dialogram/diagram-client/status-line.css'`. + * @imported by diagram-client.css, so the stock webview bundle has it. + */ +/* GLSP draws an icon in the top left corner and keeps the words for the + pointer that finds it. What is said here is why a layout was not run, or + that it was run roughly: nobody looks for that under an icon, and in the + top left corner the icon lies under other controls. So a status that has + words is a line at the bottom left of the canvas, over the crumbs (one row + of them, at the same left edge), in the look of the loading pill. + + Only a warning or an error is a line. GLSP says its own progress in the + same place ("Model loading in progress", "Validate Model..."), which the + loading indicator already tells better: those are not drawn at all. */ +.sprotty-status { + position: fixed; + top: auto; + right: auto; + left: 12px; + bottom: calc(var(--workflow-wf-nav-height, 0px) + 44px); + z-index: 1001; + display: flex; + align-items: flex-start; + gap: 8px; + box-sizing: border-box; + /* Clear of the buttons at the bottom right, and inside a narrow editor. */ + max-width: min(640px, calc(100vw - 120px)); + padding: 6px 12px; + border: 1px solid var(--vscode-editorWidget-border, #454545); + border-radius: 4px; + background: var(--vscode-editorWidget-background, #252526); + box-shadow: 0 2px 8px var(--vscode-widget-shadow, rgb(0 0 0 / 35%)); + color: var(--vscode-foreground, #cccccc); + font-family: var(--vscode-font-family, sans-serif); + font-size: 12px; + line-height: 1.4; +} + +.sprotty-status:has(> .sprotty-status-message:empty), +.sprotty-status:not(:has(> .sprotty-status-message:is(.warning, .error, .fatal))) { + display: none; +} + +/* The chat card has the bottom of the canvas, at its middle and as wide as + half of it or more. With the card shown the line is at the top left, under + the row of buttons there and under the bar of a stale graph. */ +body:has(.workflow-chat-panel.visible) .sprotty-status { + top: calc(var(--wf-stale-bar-height, 0px) + 52px); + bottom: auto; +} + +/* With the property panel open the line starts where the crumbs do, clear of + the panel. */ +body.workflow-properties-visible .sprotty-status { + left: calc(var(--workflow-property-panel-width, 0px) + 10px); + max-width: min(640px, calc(100vw - var(--workflow-property-panel-width, 0px) - 120px)); +} + +/* An open outline panel takes the bottom right, beside its button and up to + half the editor (hierarchy-outline.css). The line keeps to what is left of + it, and wraps. */ +body:has(.workflow-hierarchy-outline:not([hidden])) .sprotty-status { + max-width: calc(100vw - 86px - min(380px, 50vw)); +} + +.sprotty-status .sprotty-status-message { + visibility: visible; + min-width: 0; + padding-left: 0; + /* The words are the reason: they can be selected and copied. */ + user-select: text; + overflow-wrap: anywhere; +} + +/* The icon keeps the line height of the words it stands beside. */ +.sprotty-status > .codicon { + flex: none; + line-height: 1.4; +} + +.sprotty-status .fatal, +.sprotty-status .error { + color: var(--vscode-editorError-foreground, #f14c4c); +} + +.sprotty-status .warning { + color: var(--vscode-editorWarning-foreground, #cca700); +} + +/* The words are read in the text colour: the icon carries the severity. */ +.sprotty-status .sprotty-status-message.fatal, +.sprotty-status .sprotty-status-message.error, +.sprotty-status .sprotty-status-message.warning { + color: var(--vscode-foreground, #cccccc); +} + +.sprotty-status:has(> .sprotty-status-message.error), +.sprotty-status:has(> .sprotty-status-message.fatal) { + border-color: var(--vscode-inputValidation-errorBorder, var(--vscode-editorError-foreground, #f14c4c)); +} diff --git a/packages/diagram-client/test/status-line-css-split.test.ts b/packages/diagram-client/test/status-line-css-split.test.ts new file mode 100644 index 00000000..f9a8bc60 --- /dev/null +++ b/packages/diagram-client/test/status-line-css-split.test.ts @@ -0,0 +1,97 @@ +/** + * The status line's rules live in their own stylesheet, which a product with + * a stylesheet of its own imports alone. diagram-client.css @imports it, so + * the stock bundle keeps every rule, and holds none of them itself. + * + * GLSP hides the words of a status until the pointer is on its icon. A + * status is why a layout was not run: the words of a warning or an error are + * shown, and GLSP's own progress, which the loading indicator tells, is not + * drawn. + */ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import * as path from 'node:path'; +import { describe, it, expect } from 'vitest'; + +const SRC = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../src'); +const read = (file: string) => readFileSync(path.join(SRC, file), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ''); + +function statusSelectors(css: string): string[] { + return [...css.matchAll(/([^{}]+)\{[^{}]*\}/g)] + .map(match => match[1].trim()) + .filter(selector => selector.includes('.sprotty-status')); +} + +describe('status-line.css', () => { + it('shows the words of a status without the pointer, and draws nothing for a status without words', () => { + const css = read('status-line.css'); + expect(css).toMatch(/\.sprotty-status \.sprotty-status-message\s*\{[^}]*visibility:\s*visible/); + expect(css).toMatch(/\.sprotty-status:has\(> \.sprotty-status-message:empty\),[^{]*\{[^}]*display:\s*none/); + }); + + it('is a line at the bottom left, over the crumbs and clear of the top left corner the controls of a product take', () => { + const css = read('status-line.css'); + const line = /\.sprotty-status\s*\{([^}]*)\}/.exec(css)?.[1] ?? ''; + expect(line).toMatch(/position:\s*fixed/); + expect(line).toMatch(/top:\s*auto/); + expect(line).toMatch(/max-width:/); + // The crumbs are at the bottom left too: the line has their left edge, a row higher. + const crumbs = /\.workflow-breadcrumb-overlay\s*\{([^}]*)\}/.exec(read('diagram-client.css'))?.[1] ?? ''; + expect(crumbs).toMatch(/left:\s*12px/); + expect(crumbs).toMatch(/bottom:\s*calc\(var\(--workflow-wf-nav-height, 28px\) \+ 16px\)/); + expect(line).toMatch(/left:\s*12px/); + expect(line).toMatch(/bottom:\s*calc\(var\(--workflow-wf-nav-height, 0px\) \+ 44px\)/); + }); + + it('moves clear of the property panel as the crumbs do', () => { + const css = read('status-line.css'); + expect(css).toMatch( + /body\.workflow-properties-visible \.sprotty-status\s*\{[^}]*left:\s*calc\(var\(--workflow-property-panel-width, 0px\) \+ 10px\)/ + ); + }); + + it('draws a warning or an error only: GLSP says its own progress in the same place', () => { + const css = read('status-line.css'); + expect(css).toMatch( + /\.sprotty-status:not\(:has\(> \.sprotty-status-message:is\(\.warning, \.error, \.fatal\)\)\)\s*\{[^}]*display:\s*none/ + ); + expect(css).not.toMatch(/\.info\b/); + }); + + it('goes to the top left, under the buttons and the bar of a stale graph, while the chat card has the bottom', () => { + const css = read('status-line.css'); + expect(css).toMatch( + /body:has\(\.workflow-chat-panel\.visible\) \.sprotty-status\s*\{[^}]*top:\s*calc\(var\(--wf-stale-bar-height, 0px\) \+ 52px\);[^}]*bottom:\s*auto/ + ); + // The class the chat card is shown by, and the height the bar gives the page. + expect(read('chat-panel.css')).toMatch(/\.workflow-chat-panel\.visible\s*\{/); + expect(readFileSync(path.join(SRC, 'graph-status.ts'), 'utf8')).toContain("'--wf-stale-bar-height'"); + }); + + it('is an overlay a fit keeps the drawing clear of', () => { + expect(readFileSync(path.join(SRC, 'canvas-overlays.ts'), 'utf8')).toMatch(/'\.sprotty-status',/); + }); + + it('keeps to the left of an open outline panel, which has the bottom right', () => { + const css = read('status-line.css'); + const outline = read('hierarchy-outline.css'); + // The width and the place the line reckons with are the panel's own. + expect(outline).toMatch(/\.workflow-hierarchy-outline\s*\{[^}]*right:\s*60px[^}]*width:\s*min\(380px, 50vw\)/); + expect(css).toMatch( + /body:has\(\.workflow-hierarchy-outline:not\(\[hidden\]\)\) \.sprotty-status\s*\{[^}]*max-width:\s*calc\(100vw - 86px - min\(380px, 50vw\)\)/ + ); + }); + + it('takes its colours from the theme alone', () => { + const css = read('status-line.css'); + // A literal colour is a fallback inside var(), or the shadow's. + const bare = css.replace(/var\([^()]*(\([^()]*\)[^()]*)*\)/g, '').match(/#[0-9a-f]{3,8}\b/gi) ?? []; + expect(bare).toEqual([]); + }); + + it('is @imported by diagram-client.css, which keeps no status rule of its own', () => { + const stock = read('diagram-client.css'); + expect(stock).toMatch(/@import '\.\/status-line\.css';/); + expect(statusSelectors(stock)).toEqual([]); + }); +}); diff --git a/packages/diagram-server/resources/elk-server/README.md b/packages/diagram-server/resources/elk-server/README.md index b13f0224..98b60154 100644 --- a/packages/diagram-server/resources/elk-server/README.md +++ b/packages/diagram-server/resources/elk-server/README.md @@ -15,7 +15,8 @@ copying this file into its extension and naming it in its profile jar's ELK together. - SHA-256: `230f85d9db016031c0af74e3645dc90224de8a7abe4b4c64da12b90964de7da3` - Needs: Java 17 or later (class file version 61) on the machine, since ELK - 0.10 is built for it. Without it every layout stays on elkjs. + 0.10 is built for it. Without it elkjs lays out what it finishes in time, + and a larger graph is not laid out. - Run: `java -jar elk-server-0.3.0-all.jar --socket`, port from the `ELK_SERVER_PORT` environment variable. Talk to it only in the framed mode (`GZ10`, a 4-byte big-endian length, a gzip body, both ways): the plain JSON diff --git a/packages/diagram-server/src/server/elk-layout-engine.ts b/packages/diagram-server/src/server/elk-layout-engine.ts index 42d6d677..3644a36e 100644 --- a/packages/diagram-server/src/server/elk-layout-engine.ts +++ b/packages/diagram-server/src/server/elk-layout-engine.ts @@ -267,7 +267,7 @@ export class WorkflowElkLayoutEngine extends GlspElkLayoutEngine { // status line, since the result looks nothing like a usual layout. if (tier === 'fast' && this.actionDispatcher) { const message = `${size.nodes} nodes: laid out roughly. Run Layout for the full layout.`; - void Promise.resolve(this.actionDispatcher.dispatch(StatusAction.create(message, { severity: 'INFO', timeout: 10000 }))) + void Promise.resolve(this.actionDispatcher.dispatch(StatusAction.create(message, { severity: 'WARNING', timeout: 10000 }))) .catch(e => console.warn('[cal-elk] layout status not shown:', e)); } return root; diff --git a/packages/diagram-server/src/server/elk-server/elk-server-client.ts b/packages/diagram-server/src/server/elk-server/elk-server-client.ts index 50f01de9..94ba1310 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-client.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-client.ts @@ -33,6 +33,18 @@ export async function encodeFrame(json: string): Promise { return Buffer.concat([header, body]); } +/** + * A layout the server did not answer within its time. The server is still on + * it: a layout cannot be taken back from it ({@link ElkServerProcess.during} + * ends a server that has nothing else to answer). + */ +export class ElkServerTimeoutError extends Error { + constructor(readonly timeoutMs: number) { + super(`the ELK server took longer than ${timeoutMs} ms`); + this.name = 'ElkServerTimeoutError'; + } +} + /** * Lay `graph` out on the server at `port`, writing the positions, sizes and * routes back into it (as elkjs would) and resolving with it. @@ -54,10 +66,10 @@ export function layoutOnServer(port: number, graph: ElkNode, timeoutMs: number): resolve(result!); } }; - const timer = setTimeout( - () => finish(new Error(`the ELK server took longer than ${timeoutMs} ms`)), - timeoutMs - ); + // A host kept busy (by an elkjs layout of another diagram, say) runs + // this timer before it reads an answer that arrived meanwhile: the + // answer is read first, and only a server that has none timed out. + const timer = setTimeout(() => setImmediate(() => finish(new ElkServerTimeoutError(timeoutMs))), timeoutMs); const chunks: Buffer[] = []; let received = 0; diff --git a/packages/diagram-server/src/server/elk-server/elk-server-options.ts b/packages/diagram-server/src/server/elk-server/elk-server-options.ts index 89d415ff..ce7d0484 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-options.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-options.ts @@ -14,13 +14,15 @@ * and 1.2 s. */ +import type { LayoutEngineName, LayoutRates } from '../layout-cost'; + /** Which engine lays a graph out. */ export type LayoutEngineChoice = - /** The server for a graph elkjs is estimated to be slow on (`layout-cost.ts`), elkjs for the rest and whenever the server is not there. */ + /** The server for a graph elkjs is estimated to be slow on (`layout-cost.ts`), elkjs for the rest, and for what it may take when the server did not lay a graph out. */ | 'auto' - /** elkjs only; the server is never started. */ + /** elkjs only; the server is never started, and a graph elkjs is not to take (`ELKJS_BUDGET_MS`) is not laid out. */ | 'elkjs' - /** The server for every graph, elkjs only when the server is not there. */ + /** The server for every graph, elkjs only when the server did not lay a graph out and elkjs may take it. */ | 'elk-server'; export interface ElkServerOptions { @@ -32,12 +34,23 @@ export interface ElkServerOptions { /** JVM options, split on whitespace (e.g. `-Xmx2g`). The server's threads get a 64 MB stack unless `-Xss` is among them. */ javaOpts?: string; /** - * How long one layout may take on the server. Past it elkjs takes the - * layout over when it is estimated to finish within the same time, or - * within a minute when the timeout is shorter, and the layout is refused - * otherwise. Default 120 s. + * How long one layout may take on the server. Past it the layout goes to + * elkjs when elkjs is estimated to finish it within a minute + * (`ELKJS_BUDGET_MS`), and is refused otherwise. Default 120 s. */ timeoutMs?: number; + /** + * The rates the estimate of a layout turns a graph into milliseconds with + * (`layout-cost.ts`), on each engine: what `auto` chooses the engine by, + * and what a layout the server did not answer is refused by. For a product + * that lays out with options of its own and measured them. Without them + * the rates are those of the preset a graph asks for, which were measured + * with the options of the platform. One set prices every layout of the + * product, so a product that lays out with the presets of the platform + * (the default, the middle and the fast one, Untangled) names none: those + * differ by a factor of three and more, and the platform has a set each. + */ + rates?: Readonly>; } export const DEFAULT_ELK_SERVER_TIMEOUT_MS = 120_000; diff --git a/packages/diagram-server/src/server/elk-server/elk-server-process.ts b/packages/diagram-server/src/server/elk-server/elk-server-process.ts index 18464530..552b0b92 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-process.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-process.ts @@ -6,9 +6,11 @@ * `ELK_SERVER_PORT` (it has no flag for it), so a free one is picked here, and * the process is ready once it prints that it is listening. A process that * dies, or runs out of heap (it keeps running, broken, so it is killed), is - * started again by the next layout that asks for it; until then layouts go to - * elkjs. Nothing waits on a server that cannot start: no Java, no jar, or no - * "listening" within the start timeout, and the layout goes to elkjs. + * started again by the next layout that asks for it. Nothing waits on a + * server that cannot start: no Java, no jar, or no "listening" within the + * start timeout. Without a server elkjs takes the layouts it may + * (`ELKJS_BUDGET_MS`), and the others are refused with what the start failed + * on ({@link ElkServerProcess.failure}). * * A layout that overflows the stack of its thread is the other failure the * server does not answer: it catches the error, logs it and leaves the @@ -19,13 +21,28 @@ * answers what else it was asked ({@link ElkServerProcess.during}), and is * ended when the layouts that overflowed are all it has left. Ending it is * what ends them, with the reason ({@link ELK_SERVER_OUT_OF_STACK}). + * + * A layout that ran past its time is the same to the server: nobody waits + * for it, and the server stays on it, a core and a heap of a gigabyte for + * minutes on a graph of thousands of nodes. It cannot be told to stop. A + * server that had a minute or more for a layout ({@link ELK_SERVER_STUCK_MS}) + * is retired too, and ended once it has nothing else to answer. One that was + * given less is left to finish: a short timeout is a person's wish to see + * elkjs sooner, and a JVM that is ended at every layout never gets warm. */ import * as cp from 'node:child_process'; import * as fs from 'node:fs'; import * as net from 'node:net'; import * as path from 'node:path'; +import { ElkServerTimeoutError } from './elk-server-client'; import type { ElkServerOptions } from './elk-server-options'; +/** + * The time after which a server that has not answered a layout is taken to + * be on it for long, and is ended when that layout times out. + */ +export const ELK_SERVER_STUCK_MS = 60_000; + /** How long a starting server has to say it is listening. */ export const ELK_SERVER_START_TIMEOUT_MS = 15_000; @@ -71,12 +88,32 @@ interface StartedServer { asked: number; /** How many of them it said overflowed the stack, which it will never answer. */ overflowed: number; + /** The layouts that timed out, which it is still on with nobody waiting. */ + abandoned: number; /** No longer the server new layouts go to. */ retired: boolean; /** Ended because the layouts that overflowed were all it had left. */ endedForStack: boolean; } +/** + * What a JVM that ended as it started said of it, for the reason. The line + * that names an exception is the one, wherever it stands: the last line is a + * frame of the stack as often as not. A JVM that names none (an option it + * does not know, a heap it cannot reserve) says it in its first two lines. + * That the server needs Java 17 is added when that is what the error says. + */ +function whyItEnded(said: string): string { + const lines = said + .split('\n') + .map(line => line.trim()) + .filter(Boolean); + const named = lines.find(line => /\b[\w.$]+(Error|Exception)\b:/.test(line)); + const why = (named ?? lines.slice(0, 2).join(' ')).slice(0, 200); + const tooOld = /UnsupportedClassVersionError/.test(said) ? '; it needs Java 17 or later' : ''; + return `${why ? ` (${why})` : ''}${tooOld}`; +} + export type SpawnFunction = (command: string, args: string[], options: cp.SpawnOptions) => cp.ChildProcess; export class ElkServerProcess { @@ -118,6 +155,8 @@ export class ElkServerProcess { * that server has still to answer. A server that said a layout overflowed * its stack is ended once the layouts it cannot answer are all it has * left, and those fail with the reason, not with the closed connection. + * A server a layout timed out on is still working on it: it is ended once + * it has nothing else to answer, and the next layout starts another. */ async during(port: number, layout: () => Promise): Promise { const server = this.servers.get(port); @@ -135,6 +174,13 @@ export class ElkServerProcess { // by its timeout say, is taken for the one that overflowed. if (server.overflowed > 0) { server.overflowed--; + } else if (error instanceof ElkServerTimeoutError) { + // Still on it: an overflow it says later is this layout's, not one of those still waited for. + server.abandoned++; + if (error.timeoutMs >= ELK_SERVER_STUCK_MS && !server.retired) { + console.warn('[dialogram layout] the ELK server is still on the layout that timed out; the next layout starts another server'); + this.retire(server); + } } throw error; } finally { @@ -143,6 +189,15 @@ export class ElkServerProcess { } } + /** No new layout goes to `server`: the next one starts another. */ + private retire(server: StartedServer): void { + server.retired = true; + if (this.child === server.child) { + this.child = undefined; + this.port = undefined; + } + } + /** Ends a retired server that has nothing left it can answer. */ private endWhenDone(server: StartedServer): void { if (!server.retired || server.asked > server.overflowed || server.child.exitCode !== null || server.child.killed) { @@ -160,17 +215,18 @@ export class ElkServerProcess { server.child.kill('SIGKILL'); } else if (STACK_OVERFLOW_LINE.test(line)) { console.error('[dialogram layout] the ELK server ran out of stack on a layout; the next layout starts another server'); - server.overflowed++; - server.retired = true; - if (this.child === server.child) { - this.child = undefined; - this.port = undefined; + if (server.abandoned > 0) { + // The layout nobody waits for any more: no layout still asked is ended for it. + server.abandoned--; + } else { + server.overflowed++; } + this.retire(server); this.endWhenDone(server); } } - /** Stop the process for good; later layouts go to elkjs. */ + /** Stop the process for good; later layouts find no server. */ dispose(): void { this.disposed = true; this.stop(); @@ -212,7 +268,7 @@ export class ElkServerProcess { return this.failed(`could not run ${this.javaPath()}: ${String(error)}`); } this.child = child; - const server: StartedServer = { child, asked: 0, overflowed: 0, retired: false, endedForStack: false }; + const server: StartedServer = { child, asked: 0, overflowed: 0, abandoned: 0, retired: false, endedForStack: false }; child.on('exit', () => { for (const [port, started] of this.servers) { if (started === server) { @@ -235,10 +291,35 @@ export class ElkServerProcess { } }); + // A `java` that is not there is an error of the spawn, and one that is + // too old ends at once with its reason on stderr: neither is a server + // that is slow to start, and a refused layout says which it was. + let notRun: Error | undefined; + let ended: string | undefined; + let said = ''; + child.once('error', error => { + notRun = error; + }); + child.once('exit', (code, signal) => { + ended = signal ? `was ended by ${signal}` : `exited with code ${code}`; + }); + child.stderr?.on('data', data => { + said = (said + String(data)).slice(-8192); + }); const listening = await this.waitForListening(child); if (listening === undefined) { + if (ended) { + // The exit can come before the last words on the error stream are read. + await new Promise(resolve => setImmediate(resolve)); + } + // Read before the process is stopped: stopping it is an exit too. + const reason = notRun + ? `the ELK server could not be run with ${this.javaPath()} (${notRun.message}; is Java 17 or later installed?)` + : ended + ? `the ELK server ${ended} as it started${whyItEnded(said)}` + : `the ELK server did not start within ${this.startTimeoutMs} ms (is Java 17 or later installed?)`; this.stop(); - return this.failed(`the ELK server did not start within ${this.startTimeoutMs} ms (is Java 17 or later installed?)`); + return this.failed(reason); } this.port = listening; this.servers.set(listening, server); @@ -288,9 +369,14 @@ export class ElkServerProcess { return 'java'; } + /** Why the server is not running, after a start that failed: what a refused layout says. */ + get failure(): string | undefined { + return this.lastFailure; + } + private failed(reason: string): undefined { if (reason !== this.lastFailure) { - console.warn(`[dialogram layout] ${reason}; laying out with elkjs`); + console.warn(`[dialogram layout] ${reason}; elkjs lays out what it can`); this.lastFailure = reason; } return undefined; diff --git a/packages/diagram-server/src/server/elk-server/index.ts b/packages/diagram-server/src/server/elk-server/index.ts index 0dcff89f..887707cf 100644 --- a/packages/diagram-server/src/server/elk-server/index.ts +++ b/packages/diagram-server/src/server/elk-server/index.ts @@ -14,15 +14,14 @@ export * from './elk-server-options'; export { ELK_SERVER_OUT_OF_STACK, ELK_SERVER_STACK, ElkServerProcess, jvmArguments } from './elk-server-process'; export { AUTO_ELKJS_BUDGET_MS, - ELKJS_TAKEOVER_BUDGET_MS, + ELKJS_BUDGET_MS, LayoutRefusedError, SwitchingElk, elkGraphSize, - elkjsTakeoverMs, goesToServer, serverCanLayOut } from './switching-elk'; -export { layoutOnServer } from './elk-server-client'; +export { ElkServerTimeoutError, layoutOnServer } from './elk-server-client'; const processes = new Map(); @@ -45,14 +44,21 @@ export function disposeElkServers(): void { processes.clear(); } +/** The server of a product whose person chose elkjs: none, and none is started. */ +const NO_SERVER = { ensureStarted: async (): Promise => undefined }; + /** * An ELK factory for the layout engine: elkjs with these defaults, behind the - * server when the options ask for it. + * switch when the product ships a server. The switch sends a graph to the + * server as the options say, and keeps from elkjs what elkjs is not to take. */ export function createElkFactory(elkjsOptions: { algorithms: string[]; defaultLayoutOptions: LayoutOptions }, server?: ElkServerOptions): () => ELK { const elkjs = (): ELK => new (ElkConstructor as any)(elkjsOptions); - if (!server || server.engine === 'elkjs') { + if (!server) { return elkjs; } - return () => new SwitchingElk(elkjs(), sharedElkServerProcess(server), server); + // With elkjs chosen no server is ever started, and the switch still stands + // before elkjs: it refuses the layout elkjs is not to take. + const process = server.engine === 'elkjs' ? NO_SERVER : sharedElkServerProcess(server); + return () => new SwitchingElk(elkjs(), process, server); } diff --git a/packages/diagram-server/src/server/elk-server/switching-elk.ts b/packages/diagram-server/src/server/elk-server/switching-elk.ts index 24854f58..8e07cf72 100644 --- a/packages/diagram-server/src/server/elk-server/switching-elk.ts +++ b/packages/diagram-server/src/server/elk-server/switching-elk.ts @@ -13,13 +13,14 @@ * (`SERVER_ALGORITHMS`: an automaton placed by stress) stays on elkjs, which * has them all. * - * A server that is not there (no Java, no jar) leaves every graph to elkjs. - * One that was asked and did not answer, in time or at all, leaves the graph - * to elkjs only when elkjs is estimated to finish in the time a layout may - * take ({@link elkjsTakeoverMs}). elkjs runs on the extension host's thread: a - * graph the server could not lay out in two minutes would hold every diagram, - * and the host, for many times that. Such a layout is refused - * ({@link LayoutRefusedError}) and the diagram stays as it was. + * elkjs takes a graph only when it is estimated to finish within a minute + * ({@link ELKJS_BUDGET_MS}), whoever was to lay the graph out: a server that + * was asked and did not answer, in time or at all, one that is not there (no + * Java, no jar), or elkjs itself by the person's choice. elkjs runs on the extension host's thread, and a graph of thousands + * of nodes holds every diagram, and the host, for minutes or for an hour. + * Past that estimate a graph is the server's alone: without its answer the + * layout is refused ({@link LayoutRefusedError}), with the reason the server + * did not lay it out, and the diagram stays as it was. */ import type { ELK, ElkLayoutArguments, ElkNode } from 'elkjs'; import { LAYOUT_TIER_MIDDLE_NODES } from '../layout-configurator'; @@ -86,26 +87,18 @@ export function goesToServer(engine: ElkServerOptions['engine'], estimate: Pick< } /** - * What elkjs may take for a layout the server did not answer, whatever the - * server's timeout: a minute. + * What elkjs may be estimated to take for a layout, at most: a minute, + * whoever was to lay the graph out and whatever the timeout of the server. A + * long timeout says how long a layout may take on the server, where nothing + * waits on it, and is no leave for elkjs to hold the host as long. The + * estimate is good to a factor of two, so the minute is half a minute to two + * of a host that answers nothing. */ -export const ELKJS_TAKEOVER_BUDGET_MS = 60_000; +export const ELKJS_BUDGET_MS = 60_000; /** - * What elkjs may be estimated to take for a layout the server was asked for - * and did not answer: the server's timeout, and no less than a minute. The - * timeout says how long a layout may take on the server, where nothing waits - * on it. A short one (a slow server is to hand over soon) is no reason to - * refuse a graph elkjs lays out in ten seconds, and the estimate is good to a - * factor of two. - */ -export function elkjsTakeoverMs(timeoutMs: number): number { - return Math.max(timeoutMs, ELKJS_TAKEOVER_BUDGET_MS); -} - -/** - * A layout that was not run: the server did not answer, and elkjs would hold - * the host for longer than a layout may take. + * A layout that was not run: the server did not lay it out, and elkjs would + * hold the host for longer than a layout may take. */ export class LayoutRefusedError extends Error { constructor( @@ -124,20 +117,30 @@ type LaidOut = Awaited> & Omit & Partial>, - private readonly options: Pick, + private readonly server: Pick & Partial>, + private readonly options: Pick, private readonly layoutOnPort: typeof layoutOnServer = layoutOnServer ) {} async layout(graph: T, args?: ElkLayoutArguments): Promise> { const size = elkGraphSize(graph); - const estimate = estimateElkLayout(graph); + // By the rates of the product when it measured its own, else by those of the preset the graph asks for. + const estimate = estimateElkLayout(graph, this.options.rates); const what = `${size.nodes} nodes, ${size.edges} edges`; - if (goesToServer(this.options.engine, estimate) && serverCanLayOut(graph)) { + const timeoutMs = this.options.timeoutMs ?? DEFAULT_ELK_SERVER_TIMEOUT_MS; + /** Why the server does not lay this graph out: what a refusal says, when elkjs may not take it either. */ + let reason: string; + if (!goesToServer(this.options.engine, estimate)) { + // Under `auto` this is a graph elkjs is quick on: only a person's choice of elkjs keeps a slow one here. + reason = this.options.engine === 'elkjs' ? 'the layout engine is set to elkjs' : 'the ELK server was not asked'; + } else if (!serverCanLayOut(graph)) { + reason = 'the ELK server has not the algorithm this graph asks for'; + } else { const port = await this.server.ensureStarted(); - if (port !== undefined) { + if (port === undefined) { + reason = this.server.failure ?? 'the ELK server is not running'; + } else { const started = Date.now(); - const timeoutMs = this.options.timeoutMs ?? DEFAULT_ELK_SERVER_TIMEOUT_MS; try { // The server's layout is written into the graph it was given, as elkjs's is. // Through the process, which knows by it what its server has still to answer. @@ -146,17 +149,20 @@ export class SwitchingElk implements ELK { console.log(`[dialogram layout] ELK server: ${what} in ${Date.now() - started} ms (estimated ${estimate.serverMs} ms, elkjs ${estimate.elkjsMs} ms)`); return result as LaidOut; } catch (error) { - const reason = error instanceof Error ? error.message : String(error); - if (estimate.elkjsMs > elkjsTakeoverMs(timeoutMs)) { - throw new LayoutRefusedError( - `Not laid out: ${reason}, and elkjs would take about ${formatLayoutMs(estimate.elkjsMs)} for ${what}, with every diagram waiting.`, - estimate.elkjsMs - ); + reason = error instanceof Error ? error.message : String(error); + if (estimate.elkjsMs <= ELKJS_BUDGET_MS) { + console.warn(`[dialogram layout] ${reason}; laying out with elkjs`); } - console.warn(`[dialogram layout] ${reason}; laying out with elkjs`); } } } + // Past what elkjs may take, a graph is the server's alone. + if (estimate.elkjsMs > ELKJS_BUDGET_MS) { + throw new LayoutRefusedError( + `Not laid out: ${reason}, and elkjs would take about ${formatLayoutMs(estimate.elkjsMs)} for ${what}, with every diagram waiting.`, + estimate.elkjsMs + ); + } const started = Date.now(); const result = await this.elkjs.layout(graph, args); console.log(`[dialogram layout] elkjs: ${what} in ${Date.now() - started} ms (estimated ${estimate.elkjsMs} ms)`); diff --git a/packages/diagram-server/src/server/server-module.ts b/packages/diagram-server/src/server/server-module.ts index 835bc1ff..46961ed2 100644 --- a/packages/diagram-server/src/server/server-module.ts +++ b/packages/diagram-server/src/server/server-module.ts @@ -176,8 +176,10 @@ export function createWorkflowServerModules( additionalModules.push(elkLayoutModule); // Large graphs on the Java ELK server, when the product ships it: the - // engine's ELK becomes one that sends them there and keeps the rest on elkjs. - if (options?.elkServer && options.elkServer.engine !== 'elkjs') { + // engine's ELK becomes one that sends them there and keeps the rest on + // elkjs. With elkjs chosen it sends none, and still refuses the layout + // elkjs would hold the host for. + if (options?.elkServer) { const elkFactory = createElkFactory(elkDefaults, options.elkServer); additionalModules.push(new ContainerModule((_bind, _unbind, _isBound, rebind) => { rebind(ElkFactory).toConstantValue(elkFactory); diff --git a/packages/diagram-server/test/elk-server.test.ts b/packages/diagram-server/test/elk-server.test.ts index 81d8b7e8..46fd59a7 100644 --- a/packages/diagram-server/test/elk-server.test.ts +++ b/packages/diagram-server/test/elk-server.test.ts @@ -20,19 +20,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import ElkConstructor from 'elkjs/lib/elk.bundled.js'; import type { ELK, ElkNode } from 'elkjs'; import { DefaultElementFilter } from '@eclipse-glsp/layout-elk'; -import { FRAME_HEADER_BYTES, FRAME_MAGIC, encodeFrame, layoutOnServer } from '../src/server/elk-server/elk-server-client'; -import { ELK_SERVER_OUT_OF_STACK, ELK_SERVER_STACK, ElkServerProcess, jvmArguments, type SpawnFunction } from '../src/server/elk-server/elk-server-process'; +import { ElkServerTimeoutError, FRAME_HEADER_BYTES, FRAME_MAGIC, encodeFrame, layoutOnServer } from '../src/server/elk-server/elk-server-client'; +import { ELK_SERVER_OUT_OF_STACK, ELK_SERVER_STACK, ELK_SERVER_STUCK_MS, ElkServerProcess, jvmArguments, type SpawnFunction } from '../src/server/elk-server/elk-server-process'; import { AUTO_ELKJS_BUDGET_MS, - ELKJS_TAKEOVER_BUDGET_MS, + ELKJS_BUDGET_MS, LayoutRefusedError, SwitchingElk, elkGraphSize, - elkjsTakeoverMs, goesToServer, serverCanLayOut } from '../src/server/elk-server/switching-elk'; -import { estimateElkLayout } from '../src/server/layout-cost'; +import { estimateElkLayout, type LayoutEngineName, type LayoutRates } from '../src/server/layout-cost'; import { createElkFactory, disposeElkServers, sharedElkServerProcess } from '../src/server/elk-server/index'; import { GraphGModelSource } from '../src/model/graph-gmodel-source'; import { convertToGModelRoot } from '../src/server/gmodel-convert'; @@ -257,6 +256,88 @@ describe('the ELK server process', () => { process.dispose(); }); + it('ends a server a layout timed out on, which is still on that layout, and starts another for the next', async () => { + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const timedOut = process.during(port, () => Promise.reject(new ElkServerTimeoutError(120_000))); + + await expect(timedOut).rejects.toThrow('the ELK server took longer than 120000 ms'); + expect(children[0].killed).toBe(true); + expect(warned.mock.calls.map(call => String(call[0])).join('\n')).toMatch(/still on the layout that timed out/); + expect(await process.ensureStarted()).toBe(5301); + expect(children[1].killed).toBe(false); + process.dispose(); + } finally { + warned.mockRestore(); + } + }); + + it('lets a server a layout timed out on answer the other layouts it was asked, then ends it', async () => { + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const other = inFlight(children[0]); + const answered = process.during(port, other.layout); + const timedOut = process.during(port, () => Promise.reject(new ElkServerTimeoutError(120_000))); + + await expect(timedOut).rejects.toBeInstanceOf(ElkServerTimeoutError); + // Still answering the other diagram, and no longer the server new layouts go to. + expect(children[0].killed).toBe(false); + expect(await process.ensureStarted()).toBe(5301); + + other.answer(); + await expect(answered).resolves.toBe('laid out'); + expect(children[0].killed).toBe(true); + expect(children[1].killed).toBe(false); + process.dispose(); + } finally { + warned.mockRestore(); + } + }); + + it('leaves a server that had less than a minute for the layout: a short timeout is a wish for elkjs, and a JVM ended at every layout never gets warm', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + expect(ELK_SERVER_STUCK_MS).toBe(60_000); + + await expect(process.during(port, () => Promise.reject(new ElkServerTimeoutError(5000)))).rejects.toBeInstanceOf(ElkServerTimeoutError); + expect(children[0].killed).toBe(false); + expect(await process.ensureStarted()).toBe(port); + process.dispose(); + }); + + it('does not end a layout still asked for when the one that timed out overflows later', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const other = inFlight(children[0]); + const answered = process.during(port, other.layout); + await expect(process.during(port, () => Promise.reject(new ElkServerTimeoutError(5000)))).rejects.toBeInstanceOf(ElkServerTimeoutError); + + // The server is still on the layout that timed out, and now says it overflowed. + children[0].stderr.write(OVERFLOW); + await settle(); + expect(children[0].killed).toBe(false); + + other.answer(); + await expect(answered).resolves.toBe('laid out'); + // Retired by the overflow, and with nothing left to answer. + expect(children[0].killed).toBe(true); + process.dispose(); + }); + + it('keeps a server whose layout failed otherwise: only one still at work is ended', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + + await expect(process.during(port, () => Promise.reject(new Error('the ELK server closed the connection')))).rejects.toThrow(); + expect(children[0].killed).toBe(false); + expect(await process.ensureStarted()).toBe(port); + process.dispose(); + }); + it('hears the line when the pipe hands it over in pieces, and not the word inside another line', async () => { const { process, children } = started(); await process.ensureStarted(); @@ -301,12 +382,80 @@ describe('the ELK server process', () => { process.dispose(); }); - it('gives up, without throwing, when there is no jar or the server never says it listens', async () => { + it('gives up, without throwing, when there is no jar or the server never says it listens, and says which', async () => { const never = new ElkServerProcess({ jar }, () => fakeChild(undefined), 50); const nojar = new ElkServerProcess({ jar: path.join(__dirname, 'no-such.jar') }, () => fakeChild('listening on /127.0.0.1:1')); expect(await never.ensureStarted()).toBeUndefined(); expect(await nojar.ensureStarted()).toBeUndefined(); + expect(never.failure).toBe('the ELK server did not start within 50 ms (is Java 17 or later installed?)'); + expect(nojar.failure).toMatch(/^no ELK server jar at .+no-such\.jar$/); + }); + + it('says a java that is not there could not be run, at once, not that the server was slow to start', async () => { + const missing = (): ChildProcess => { + const child = fakeChild(undefined); + setTimeout(() => child.emit('error', new Error('spawn /opt/none/java ENOENT')), 5); + return child; + }; + const process = new ElkServerProcess({ jar, javaPath: '/opt/none/java' }, missing, 60_000); + + expect(await process.ensureStarted()).toBeUndefined(); + expect(process.failure).toBe('the ELK server could not be run with /opt/none/java (spawn /opt/none/java ENOENT; is Java 17 or later installed?)'); + }); + + it('says a java that ends as it starts did so, with its last word, not that the server was slow to start', async () => { + const tooOld = (): ChildProcess => { + const child = fakeChild(undefined); + setTimeout(() => { + child.stderr!.write('Error: LinkageError occurred while loading main class\n\tjava.lang.UnsupportedClassVersionError: class file version 61.0\n'); + setTimeout(() => { + (child as any).exitCode = 1; + child.emit('exit', 1, null); + }, 5); + }, 5); + return child; + }; + const process = new ElkServerProcess({ jar }, tooOld, 60_000); + + expect(await process.ensureStarted()).toBeUndefined(); + expect(process.failure).toBe( + 'the ELK server exited with code 1 as it started (java.lang.UnsupportedClassVersionError: class file version 61.0); it needs Java 17 or later' + ); + }); + + it('names the exception of a JVM that ends as it starts, not the frame under it, and Java 17 only where that is the reason', async () => { + const ending = (said: string) => (): ChildProcess => { + const child = fakeChild(undefined); + setTimeout(() => { + // The exit comes first, the words after it. + (child as any).exitCode = 1; + child.emit('exit', 1, null); + child.stderr!.write(said); + }, 5); + return child; + }; + const java8 = new ElkServerProcess( + { jar }, + ending('Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version\n\tat java.lang.ClassLoader.defineClass1(Native Method)\n'), + 60_000 + ); + expect(await java8.ensureStarted()).toBeUndefined(); + expect(java8.failure).toBe( + 'the ELK server exited with code 1 as it started (Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version); it needs Java 17 or later' + ); + + const option = new ElkServerProcess({ jar }, ending('Unrecognized option: -Xfoo\nError: Could not create the Java Virtual Machine.\nError: A fatal exception has occurred. Program will exit.\n'), 60_000); + expect(await option.ensureStarted()).toBeUndefined(); + expect(option.failure).toBe('the ELK server exited with code 1 as it started (Unrecognized option: -Xfoo Error: Could not create the Java Virtual Machine.)'); + }); + + it('has no failure to tell once a server runs', async () => { + const process = new ElkServerProcess({ jar }, () => fakeChild('listening on /127.0.0.1:5310')); + + expect(await process.ensureStarted()).toBe(5310); + expect(process.failure).toBeUndefined(); + process.dispose(); }); it('stays stopped once disposed', async () => { @@ -450,7 +599,7 @@ describe('the engine a graph goes to', () => { expect(failing.calls).toBe(1); }); - it('refuses a layout the server did not answer and elkjs would not finish within the same time', async () => { + it('refuses a layout the server did not answer and elkjs would not finish within the minute', async () => { const js = elkjs(); const graph = longEdges(300); const estimated = estimateElkLayout(graph).elkjsMs; @@ -463,45 +612,163 @@ describe('the engine a graph goes to', () => { expect(js.calls).toBe(0); }); - it('leaves the same graph to elkjs when elkjs is estimated to finish within the time the server had', async () => { + it('refuses it whatever the timeout of the server: a long one is no leave for elkjs to hold the host as long', async () => { const js = elkjs(); const graph = longEdges(300); const failing = async (): Promise => { throw new Error('the ELK server closed the connection'); }; - await new SwitchingElk(js, server(5000), { engine: 'auto', timeoutMs: estimateElkLayout(graph).elkjsMs }, failing).layout(graph); + // The server had ten times what elkjs is estimated to need. + const refused = new SwitchingElk(js, server(5000), { engine: 'auto', timeoutMs: 10 * estimateElkLayout(graph).elkjsMs }, failing).layout(graph); - expect(js.calls).toBe(1); + await expect(refused).rejects.toBeInstanceOf(LayoutRefusedError); + expect(js.calls).toBe(0); }); it('does not refuse by a short timeout a graph elkjs lays out within the minute', async () => { - expect(elkjsTakeoverMs(5000)).toBe(ELKJS_TAKEOVER_BUDGET_MS); - expect(elkjsTakeoverMs(120_000)).toBe(120_000); + expect(ELKJS_BUDGET_MS).toBe(60_000); // The server is to hand over after 100 ms, and elkjs needs seconds. const js = elkjs(); const graph = longEdges(60); const estimated = estimateElkLayout(graph).elkjsMs; expect(estimated).toBeGreaterThan(100); - expect(estimated).toBeLessThan(ELKJS_TAKEOVER_BUDGET_MS); + expect(estimated).toBeLessThan(ELKJS_BUDGET_MS); const timedOut = async (): Promise => { throw new Error('the ELK server took longer than 100 ms'); }; await new SwitchingElk(js, server(5000), { engine: 'elk-server', timeoutMs: 100 }, timedOut).layout(graph); expect(js.calls).toBe(1); }); - it('never refuses a graph when there is no server to ask: elkjs is all there is', async () => { + describe('with the rates of a product that measured its own layout', () => { + // Its elkjs goes with the square of the nodes of a pass, where the platform's options are near linear. + const rates: Readonly> = { + elkjs: { msPerSpanUnit: 0, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 10 }, + 'elk-server': { msPerSpanUnit: 0, msPerSpanUnitSquared: 0, msPerNode: 1, msPerNodeSquared: 0 } + }; + + it('chooses the engine by them: a chain the platform keeps on elkjs goes to the server', async () => { + const js = elkjs(); + const sent: number[] = []; + await new SwitchingElk(js, server(5000), { engine: 'auto', rates }, async (port, g) => { sent.push(port); return g; }).layout(chain(20)); + + expect(estimateElkLayout(chain(20)).elkjsMs).toBeLessThan(AUTO_ELKJS_BUDGET_MS); + expect(estimateElkLayout(chain(20), rates).elkjsMs).toBe(4000); + expect(sent).toEqual([5000]); + expect(js.calls).toBe(0); + }); + + it('refuses by them a layout the server did not answer, which the rates of the platform leave to elkjs', async () => { + const graph = chain(100); + expect(estimateElkLayout(graph).elkjsMs).toBeLessThan(ELKJS_BUDGET_MS); + const timedOut = async (): Promise => { throw new Error('the ELK server took longer than 100 ms'); }; + + const byPlatform = elkjs(); + await new SwitchingElk(byPlatform, server(5000), { engine: 'elk-server', timeoutMs: 100 }, timedOut).layout(graph); + const byProduct = elkjs(); + const refused = new SwitchingElk(byProduct, server(5000), { engine: 'elk-server', timeoutMs: 100, rates }, timedOut).layout(graph); + + expect(byPlatform.calls).toBe(1); + await expect(refused).rejects.toBeInstanceOf(LayoutRefusedError); + await expect(refused).rejects.toMatchObject({ estimateMs: 100_000 }); + await expect(refused).rejects.toThrow(/elkjs would take about 2 min for 100 nodes, 99 edges/); + expect(byProduct.calls).toBe(0); + }); + + it('says their estimate beside what the layout took', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + try { + await new SwitchingElk(elkjs(), server(5000), { engine: 'elk-server', rates }, async (_port, g) => g).layout(chain(20)); + expect(log.mock.calls.map(call => String(call[0])).join('\n')).toMatch(/ELK server: 20 nodes, 19 edges in \d+ ms \(estimated 20 ms, elkjs 4000 ms\)/); + } finally { + log.mockRestore(); + } + }); + }); + + describe('with no server to lay a graph out', () => { + it('refuses the graph elkjs is not to take, and says why there is no server', async () => { + const js = elkjs(); + const noJava = { ...server(undefined), failure: 'the ELK server could not be run with java (spawn java ENOENT; is Java 17 or later installed?)' }; + const refused = new SwitchingElk(js, noJava, { engine: 'auto' }).layout(longEdges(300)); + + await expect(refused).rejects.toBeInstanceOf(LayoutRefusedError); + await expect(refused).rejects.toThrow( + /^Not laid out: the ELK server could not be run with java \(spawn java ENOENT; is Java 17 or later installed\?\), and elkjs would take about .+ for 300 nodes, \d+ edges, with every diagram waiting\.$/ + ); + expect(js.calls).toBe(0); + }); + + it('says so when the server gave no reason', async () => { + const refused = new SwitchingElk(elkjs(), server(undefined), { engine: 'elk-server' }).layout(longEdges(300)); + + await expect(refused).rejects.toThrow(/^Not laid out: the ELK server is not running, and elkjs would take about /); + }); + + it('still hands elkjs the graph it finishes in time', async () => { + const js = elkjs(); + const graph = longEdges(60); + expect(estimateElkLayout(graph).elkjsMs).toBeGreaterThan(AUTO_ELKJS_BUDGET_MS); + await new SwitchingElk(js, server(undefined), { engine: 'auto' }).layout(graph); + + expect(js.calls).toBe(1); + }); + }); + + it('does not blame a choice of elkjs nobody made, for options that name no engine it knows', async () => { + const refused = new SwitchingElk(elkjs(), server(5000), { engine: undefined as never }, async g => g).layout(longEdges(300)); + + await expect(refused).rejects.toThrow(/^Not laid out: the ELK server was not asked, and elkjs would take about /); + }); + + describe('with elkjs chosen', () => { + it('never asks for the server, and lays out what elkjs finishes in time', async () => { + const js = elkjs(); + const java = server(5000); + await new SwitchingElk(js, java, { engine: 'elkjs' }, async g => g).layout(longEdges(60)); + + expect(js.calls).toBe(1); + expect(java.starts).toBe(0); + }); + + it('refuses the graph elkjs would hold the host for, which is the server’s alone', async () => { + const js = elkjs(); + const java = server(5000); + const refused = new SwitchingElk(js, java, { engine: 'elkjs' }, async g => g).layout(longEdges(300)); + + await expect(refused).rejects.toBeInstanceOf(LayoutRefusedError); + await expect(refused).rejects.toThrow(/^Not laid out: the layout engine is set to elkjs, and elkjs would take about .+ for 300 nodes, \d+ edges, with every diagram waiting\.$/); + expect(js.calls).toBe(0); + expect(java.starts).toBe(0); + }); + }); + + it('refuses a graph of an algorithm the server has not when elkjs would hold the host for its layered part', async () => { const js = elkjs(); - await new SwitchingElk(js, server(undefined), { engine: 'auto', timeoutMs: 1 }).layout(longEdges(300)); + const java = server(5000); + const graph = longEdges(300); + graph.children!.push({ id: 'automaton', layoutOptions: { 'elk.algorithm': 'stress' }, children: [{ id: 's0', width: 10, height: 10 }] }); + const refused = new SwitchingElk(js, java, { engine: 'elk-server' }, async g => g).layout(graph); - expect(js.calls).toBe(1); + await expect(refused).rejects.toThrow(/^Not laid out: the ELK server has not the algorithm this graph asks for, and elkjs would take about /); + expect(java.starts).toBe(0); }); }); describe('the ELK factory a diagram server gets', () => { const defaults = { algorithms: ['layered'], defaultLayoutOptions: {} }; - it('is plain elkjs without a server, or with elkjs chosen', () => { + it('is plain elkjs for a product that ships no server', () => { expect(createElkFactory(defaults)()).not.toBeInstanceOf(SwitchingElk); - expect(createElkFactory(defaults, { engine: 'elkjs', jar: '/x.jar' })()).not.toBeInstanceOf(SwitchingElk); + }); + + it('is the switch with elkjs chosen too: elkjs lays out, and what it is not to take is refused', async () => { + const elk = createElkFactory(defaults, { engine: 'elkjs', jar: '/no/such.jar' }); + + expect(elk()).toBeInstanceOf(SwitchingElk); + // elkjs itself: with no jar at that path, a server could not have answered. + const laidOut = await elk().layout({ id: 'root', children: [{ id: 'a', width: 10, height: 10 }] }); + expect(laidOut.children?.[0].x).toBeTypeOf('number'); + // Plain elkjs would have started on this one. + await expect(elk().layout(longEdges(300))).rejects.toThrow(/^Not laid out: the layout engine is set to elkjs/); }); it('is the switch otherwise, every session sharing one process per jar and JVM', () => { diff --git a/packages/diagram-server/test/layout-tier.test.ts b/packages/diagram-server/test/layout-tier.test.ts index f9f2e1c7..6affc11e 100644 --- a/packages/diagram-server/test/layout-tier.test.ts +++ b/packages/diagram-server/test/layout-tier.test.ts @@ -167,6 +167,8 @@ describe('WorkflowElkLayoutEngine and the tier', () => { if (tier === 'fast') { expect(dispatched).toHaveLength(1); expect(dispatched[0].kind).toBe('status'); + // A warning: the status line draws nothing less (status-line.css). + expect(dispatched[0].severity).toBe('WARNING'); expect(dispatched[0].message).toBe(`${nodes} nodes: laid out roughly. Run Layout for the full layout.`); } else { expect(dispatched).toHaveLength(0); diff --git a/packages/extension-core/src/api.ts b/packages/extension-core/src/api.ts index 983ce7a1..dbb1f480 100644 --- a/packages/extension-core/src/api.ts +++ b/packages/extension-core/src/api.ts @@ -519,6 +519,19 @@ export interface DiagramViewOptions { /** The ELK server settings a profile can name former keys for (`DiagramProfile.elkServer`). */ export type ElkServerSettingName = 'engine' | 'javaPath' | 'javaOpts' | 'serverTimeoutMs'; +/** + * What a layout costs on one engine, for `DiagramProfile.elkServer.rates`: + * milliseconds for each layer an edge spans and for each node of a pass, and + * for the square of each. The shape of `LayoutRates` in diagram-server + * `layout-cost.ts`, which says how the rates of the platform were fitted. + */ +export interface ElkEngineRates { + msPerSpanUnit: number; + msPerSpanUnitSquared: number; + msPerNode: number; + msPerNodeSquared: number; +} + /** * v2 diagram profile — the complete activation contract at * `DIALOGRAM_API_VERSION` 0.3.0. It carries everything the platform needs to @@ -804,8 +817,21 @@ export interface DiagramProfile { * these settings before (`{ engine: 'elk.layoutEngine' }`): a former key a * person has set is read while the new one is not, so their setting keeps * working while they move to the new name. + * + * `rates` are for a product that lays out with ELK options of its own: what + * a layout costs on each engine, as it measured them (`LayoutRates` of + * diagram-server `layout-cost.ts`). `auto` then chooses the engine by them, + * and a layout elkjs is not to take is refused by them. Absent, the rates + * are the ones the platform measured with its own options, which a graph + * laid out with other options can be far from. One set prices every layout + * of the product: a product that lays out with the presets of the platform + * names none, since the platform has the rates of each. */ - elkServer?: { jar: string; formerKeys?: Partial> }; + elkServer?: { + jar: string; + formerKeys?: Partial>; + rates?: Readonly>; + }; /** Run driver factory; when absent no run/stop commands or live glow are wired. */ runDriver?: DiagramRunDriverFactory; /** Node states from a report the product's tool makes, shown on demand with diff --git a/packages/extension-core/src/extension/diagram/profile-elk-server-options.ts b/packages/extension-core/src/extension/diagram/profile-elk-server-options.ts index 110852b1..c418996e 100644 --- a/packages/extension-core/src/extension/diagram/profile-elk-server-options.ts +++ b/packages/extension-core/src/extension/diagram/profile-elk-server-options.ts @@ -3,7 +3,8 @@ * * The product says where its jar is (`DiagramProfile.elkServer`); the person * says which engine and which JVM, in the product's settings - * (`.layout.*`). Read once, when the diagram server starts: + * (`.layout.*`). The rates of a product that measured its + * own layout (`elkServer.rates`) go through as they are. Read once, when the diagram server starts: * a change takes effect after a window reload. * * A product that renamed these settings names the keys it used before @@ -27,6 +28,40 @@ const KEYS: Readonly> = { /** JVM options when the setting is empty: enough heap for a few thousand nodes. */ export const DEFAULT_ELK_SERVER_JAVA_OPTS = '-Xmx2g'; +const ENGINE_NAMES = ['elkjs', 'elk-server'] as const; +const RATE_NAMES = ['msPerSpanUnit', 'msPerSpanUnitSquared', 'msPerNode', 'msPerNodeSquared'] as const; + +/** + * The rates a profile names, when they can price a layout: both engines, each + * with its four rates, finite, not negative and not all zero. A profile reaches the + * platform across the extension API, from code no compiler of ours has seen. + * Rates with one missing would fail every layout, and one that is not a + * number would make every estimate one too: no graph would go to the server, + * and none would be refused. Such rates are said once and left out, and the + * layouts are priced with the rates of the platform. + */ +export function usableRates(rates: unknown): ElkServerOptions['rates'] { + if (rates === undefined) { + return undefined; + } + const usable = ENGINE_NAMES.every(engine => { + const ofEngine = (rates as Record | null)?.[engine] as Record | undefined; + const numbers = RATE_NAMES.map(name => ofEngine?.[name]); + // Rates that are all zero price every graph at nothing: none would go to the server, and none be refused. + return numbers.every(rate => typeof rate === 'number' && Number.isFinite(rate) && rate >= 0) && numbers.some(rate => (rate as number) > 0); + }); + if (!usable) { + console.warn('[dialogram layout] the layout rates of the profile (elkServer.rates) are not four numbers, one of them above zero, for each of elkjs and elk-server: layouts are priced with the rates of the platform'); + return undefined; + } + return rates as ElkServerOptions['rates']; +} + +/** The rates of a profile are declared in the API beside the ones the diagram server reads: one shape, both ways. */ +type Same = [A] extends [B] ? ([B] extends [A] ? true : never) : never; +const RATES_ARE_ONE_SHAPE: Same['rates']>, NonNullable> = true; +void RATES_ARE_ONE_SHAPE; + /** * `setting` answers a key's value, its default included; `isSet` whether the * person set it, which a default does not count as (`isSetIn`). Both are @@ -49,12 +84,15 @@ export function composeElkServerOptions( }; const engine = read('engine'); const timeoutMs = read('serverTimeoutMs'); + const rates = usableRates(profile.elkServer.rates); return { engine: ENGINES.includes(engine as LayoutEngineChoice) ? (engine as LayoutEngineChoice) : 'auto', jar: path.resolve(extensionPath, profile.elkServer.jar), javaPath: read('javaPath') || undefined, javaOpts: read('javaOpts') || DEFAULT_ELK_SERVER_JAVA_OPTS, - timeoutMs: typeof timeoutMs === 'number' && timeoutMs > 0 ? timeoutMs : undefined + timeoutMs: typeof timeoutMs === 'number' && timeoutMs > 0 ? timeoutMs : undefined, + // The product's own, not a setting: they belong to the options it lays out with. + ...(rates ? { rates } : {}) }; } diff --git a/packages/extension-core/src/index.ts b/packages/extension-core/src/index.ts index 21ec7a7c..b226e6eb 100644 --- a/packages/extension-core/src/index.ts +++ b/packages/extension-core/src/index.ts @@ -11,6 +11,7 @@ export { type DialogramApi, type DiagramProfile, type DiagramProfileHandle, + type ElkEngineRates, type ElkServerSettingName, type ChatPayload, type ChatMessageSink, diff --git a/packages/extension-core/test/profile-elk-server-options.test.ts b/packages/extension-core/test/profile-elk-server-options.test.ts index d6a1b5a5..d7c4970d 100644 --- a/packages/extension-core/test/profile-elk-server-options.test.ts +++ b/packages/extension-core/test/profile-elk-server-options.test.ts @@ -8,7 +8,7 @@ * the new one is not set, and only then. */ import * as path from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { DEFAULT_ELK_SERVER_JAVA_OPTS, composeElkServerOptions, @@ -50,6 +50,40 @@ describe('composeElkServerOptions', () => { expect(chosen).toMatchObject({ engine: 'elkjs', jar: '/abs/elk.jar', javaPath: '/opt/java/bin/java', javaOpts: '-Xmx6g', timeoutMs: 30000 }); expect(unknown?.engine).toBe('auto'); }); + + it('hands on the rates of a product that measured its own layout, and names none for one that did not', () => { + const rates = { + elkjs: { msPerSpanUnit: 1.4, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 0.02 }, + 'elk-server': { msPerSpanUnit: 0.16, msPerSpanUnitSquared: 0, msPerNode: 4.5, msPerNodeSquared: 0 } + }; + const measured = composeElkServerOptions({ elkServer: { jar: '/abs/elk.jar', rates } }, '/ext', settings({}), setIn({})); + const platform = composeElkServerOptions({ elkServer: { jar: '/abs/elk.jar' } }, '/ext', settings({}), setIn({})); + + expect(measured?.rates).toBe(rates); + expect(platform).not.toHaveProperty('rates'); + }); + + it('leaves out rates that cannot price a layout, and says so: an engine missing, a rate that is no number', () => { + const elkjs = { msPerSpanUnit: 1.4, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 0.02 }; + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const compose = (rates: unknown): unknown => + composeElkServerOptions({ elkServer: { jar: '/abs/elk.jar', rates: rates as never } }, '/ext', settings({}), setIn({})); + + expect(compose({ elkjs })).not.toHaveProperty('rates'); + expect(compose({ elkjs, 'elk-server': { ...elkjs, msPerNode: Number.NaN } })).not.toHaveProperty('rates'); + expect(compose({ elkjs, 'elk-server': { ...elkjs, msPerNode: -1 } })).not.toHaveProperty('rates'); + expect(compose({ elkjs, 'elk-server': { msPerSpanUnit: 1 } })).not.toHaveProperty('rates'); + expect(compose(null)).not.toHaveProperty('rates'); + // All zero prices every graph at nothing. + const zero = { msPerSpanUnit: 0, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 0 }; + expect(compose({ elkjs: zero, 'elk-server': elkjs })).not.toHaveProperty('rates'); + expect(warned).toHaveBeenCalledTimes(6); + expect(String(warned.mock.calls[0][0])).toContain('elkServer.rates'); + } finally { + warned.mockRestore(); + } + }); }); describe('former keys', () => { diff --git a/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts b/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts index f8363e9f..6d90470d 100644 --- a/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts +++ b/packages/sidecar-toolkit/src/sidecar-diagram-profile.ts @@ -296,7 +296,10 @@ export interface SidecarProfileInput { /** * The Java ELK server the product ships, for large graphs: its fat jar, * relative to the extension's root. Threaded onto `profile.elkServer`; the - * engine is the person's choice, under `.layout.*`. + * engine is the person's choice, under `.layout.*`. No + * rates are named here (`DiagramProfile.elkServer.rates`): a sidecar + * product lays out with the presets of the platform, which has the rates + * of each. */ elkServer?: { jar: string };