Skip to content
Merged
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
60 changes: 60 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,32 @@ platform API version.

### Added

- **An estimate of a layered layout, before it runs**
(`@dialogram/diagram-server/server/layout-cost`). A layout is costed pass
by pass: a pass is what one container lays out, its nodes and the edges
among them, with no positions and no sizes. `layerSpan` layers the nodes by
their longest path, as ELK does, and sums the layers each edge spans (every
layer an edge skips is a dummy node to ELK, which is where its time goes).
The edges of a cycle are turned round as ELK turns them, by its greedy
order, and a port of a container that an edge of the inside ends on is a
node of the pass, as it is to ELK. Nodes another algorithm lays out (a
force, a tree) are in no estimate, and are counted (`unpriced`).
`estimatePassMs` turns a pass into milliseconds with the rates of an engine,
and `estimateElkLayout` does both for the ELK graph about to be laid out,
with the rates of the preset the graph asks for (`LAYOUT_RATES`: elkjs and
the ELK server on the default, middle and fast presets, and on the default
one with the options of Untangled and Free Ports). A product costs
what it has not laid out yet the same way (what opening a collapsed
container would take): it builds the passes from its own model, says which
edges only order the layers (`counted: false`) or run against the flow
(`orders: false`), and gives the rates it measured on its own layout
options. The rates of the platform are measured by
`test/layout-rates.measure.test.ts` and fitted by
`scripts/fit-layout-rates.mjs`, on 84 generated networks of 30 to 10,000
nodes and 24 of them again as Untangled lays them out, and checked on
seven graphs of a real design. The estimate is good to about a factor of
two.

- **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`
Expand Down Expand Up @@ -109,6 +135,40 @@ platform API version.

### Changed

- **`auto` chooses the layout engine by what a layout is estimated to take**,
not by 150 nodes or 400 edges. A graph goes to the Java ELK server when
elkjs is estimated to need more than a second for it (`AUTO_ELKJS_BUDGET_MS`),
and stays on elkjs otherwise. Size said little: of two graphs of 150 nodes
on the default preset, elkjs laid one out in 0.7 s and the other in 21 s,
with the host waiting, and both stayed on elkjs (the server takes 0.2 s
and 2.5 s). The engines lay a graph out alike, so the diagram does not
show which one took it. A diagram elkjs lays out within the second stays
on it as before, and a graph another algorithm than the layered one lays
out, which the estimate does not cost, still goes to the server past 150
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
(`<settingsNamespace>.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.
- **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
edges as straight lines and the ports in their new order, and the next
save kept them. The routes (`layoutFromClearedRoutes`) and the ports are
now put back, and the options a layout command sets for its own run are
taken off the nodes again in every command (the boundary-flow and
serpentine ones left them on).

- **The palette's loupe opens find**, not GLSP's field. That field
filtered the tools and the lines of the view options, and said "No
results found." when it matched neither. The text of find filters the
Expand Down
12 changes: 8 additions & 4 deletions packages/diagram-server/src/operations/boundary-flow-layout.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { GPort, LayoutEngine } from '@eclipse-glsp/server';
import { isBoundaryNodeType, WorkflowDiagramMetadata, WorkflowDiagramTypes } from '@dialogram/shared';
import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes';
import { layoutFromClearedRoutes } from '../routing/clear-edge-routes';

/**
* Shared boundary-flow layout routine.
Expand Down Expand Up @@ -205,7 +205,11 @@ export function restoreNodeLayoutOptions(
*/
export async function runBoundaryFlowLayout(root: any, layoutEngine: LayoutEngine): Promise<void> {
const previousLayoutOptionsByNodeId = applyBoundaryFlowLayerConstraints(root, new Set<string>(), false);
clearAllEdgeRoutingPoints(root);
await layoutEngine.layout();
restoreNodeLayoutOptions(root, previousLayoutOptionsByNodeId);
try {
await layoutFromClearedRoutes(root, async () => layoutEngine.layout());
} finally {
// Also when the layout was refused or failed: the constraints are this
// run's, and left on the nodes they would pin the next layout too.
restoreNodeLayoutOptions(root, previousLayoutOptionsByNodeId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from '@eclipse-glsp/server';
import { inject, injectable, optional } from 'inversify';
import { LayoutPersistenceService } from '../services/layout-persistence-service';
import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes';
import { layoutFromClearedRoutes } from '../routing/clear-edge-routes';
import { applyBoundaryFlowLayerConstraints, restoreNodeLayoutOptions } from './boundary-flow-layout';
import {
WORKFLOW_REROUTE_EDGES_AVOID_OVERLAPS_OPERATION_KIND,
Expand Down Expand Up @@ -80,10 +80,13 @@ export class WorkflowLayoutBoundaryFlowOperationHandler extends OperationHandler

const previousLayoutOptionsByNodeId = applyBoundaryFlowLayerConstraints(this.modelState.root, selectedMovableNodeIds, hasSelection);

clearAllEdgeRoutingPoints(this.modelState.root);
await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds));

restoreNodeLayoutOptions(this.modelState.root, previousLayoutOptionsByNodeId);
try {
await layoutFromClearedRoutes(this.modelState.root, async () => this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds)));
} finally {
// Also when the layout was refused or failed: the constraints are
// this run's, and left on the nodes they would pin the next layout.
restoreNodeLayoutOptions(this.modelState.root, previousLayoutOptionsByNodeId);
}

if (hasSelection && preNodePositionsById && preEdgeRoutesById) {
restoreUnselectedLayout(this.modelState.index, this.modelState.root, selectedMovableNodeIds, preNodePositionsById, preEdgeRoutesById);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,13 @@ export class WorkflowLayoutSerpentineMeshOperationHandler extends OperationHandl

const previousGraphLayoutOptions = this.applySerpentineMeshPlacement(this.modelState.root, selectedMovableNodeIds, hasSelection);

await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds));

(this.modelState.root as any).layoutOptions = previousGraphLayoutOptions ? { ...previousGraphLayoutOptions } : undefined;
try {
await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds));
} finally {
// Also when the layout was refused or failed: the placement is this
// run's, not the graph's.
(this.modelState.root as any).layoutOptions = previousGraphLayoutOptions ? { ...previousGraphLayoutOptions } : undefined;
}

if (hasSelection && preNodePositionsById && preEdgeRoutesById) {
restoreUnselectedLayout(this.modelState.index, this.modelState.root, selectedMovableNodeIds, preNodePositionsById, preEdgeRoutesById);
Expand Down
46 changes: 46 additions & 0 deletions packages/diagram-server/src/routing/clear-edge-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,49 @@ export function clearAllEdgeRoutingPoints(root: any): void {
};
visit(root);
}

/**
* Runs a layout that starts from cleared edge routes, and puts the routes back
* when the layout fails: refused, or an error of the engine.
*
* The routes are cleared so that ELK routes every edge anew. A layout that
* does not run puts nothing in their place, and the model would go on with
* every edge a straight line between nodes that never moved. So the diagram
* stays as it was.
*/
export async function layoutFromClearedRoutes<T>(root: any, layout: () => Promise<T>): Promise<T> {
const routes: Array<{ edge: any; routingPoints: unknown; manual: unknown; hadManual: boolean }> = [];
const visit = (element: any): void => {
if (!element) {
return;
}
if (element instanceof GEdge) {
const args = (element as any).args as Record<string, unknown> | undefined;
const hadManual = !!args && typeof args === 'object' && 'cal:manualRoute' in args;
routes.push({ edge: element, routingPoints: (element as any).routingPoints, manual: hadManual ? args!['cal:manualRoute'] : undefined, hadManual });
}
const children = element.children as any[] | undefined;
if (Array.isArray(children)) {
for (const child of children) {
visit(child);
}
}
};
visit(root);
clearAllEdgeRoutingPoints(root);
try {
return await layout();
} catch (error) {
for (const { edge, routingPoints, manual, hadManual } of routes) {
if (routingPoints === undefined) {
delete edge.routingPoints;
} else {
edge.routingPoints = routingPoints;
}
if (hadManual && edge.args && typeof edge.args === 'object') {
edge.args['cal:manualRoute'] = manual;
}
}
throw error;
}
}
8 changes: 4 additions & 4 deletions packages/diagram-server/src/server/diagram-action-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import {
WorkflowRerouteEdgesAvoidOverlapsOperationHandler,
WORKFLOW_REROUTE_EDGES_AVOID_OVERLAPS_OPERATION_KIND
} from '../operations/reroute-edges-avoid-overlaps-handler';
import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes';
import { layoutFromClearedRoutes } from '../routing/clear-edge-routes';
import { releaseBoundaryNodeConstraints, restoreNodeLayoutOptions, runBoundaryFlowLayout } from '../operations/boundary-flow-layout';
import { perfNow } from './graph-load-perf';
import { type FreshNode, type NodeLink, type PlacedNode, placeBesideNeighbours, routeCrosses } from './incremental-placement';
Expand Down Expand Up @@ -1631,8 +1631,8 @@ export class WorkflowLayoutOperationHandler extends OperationHandler {

// When a user triggers a manual auto-layout, we want ELK to fully recompute edge routing.
// Existing routing points (from previous ELK runs or manual routing) can otherwise
// constrain routing and lead to stale/unstable layouts.
clearAllEdgeRoutingPoints(this.modelState.root);
// constrain routing and lead to stale/unstable layouts. They are cleared for the
// layout below, and put back when it does not run (layoutFromClearedRoutes).

// What makes this the COMPACT layout rather than a second boundary-flow
// one: the network's input and output pills are released from their
Expand All @@ -1645,7 +1645,7 @@ export class WorkflowLayoutOperationHandler extends OperationHandler {
// not to one layout run, so the boundary-flow layout still gets them.
const previousBoundaryOptions = releaseBoundaryNodeConstraints(this.modelState.root);
try {
await this.layoutEngine?.layout(operation);
await layoutFromClearedRoutes(this.modelState.root, async () => this.layoutEngine?.layout(operation));
} finally {
restoreNodeLayoutOptions(this.modelState.root, previousBoundaryOptions);
}
Expand Down
39 changes: 38 additions & 1 deletion packages/diagram-server/src/server/elk-layout-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { drawInSourceOrder, givenPortOrders, gportSide, onePortOrderPerDefinitio
import { FAST_LAYOUT_OPTIONS, countLayoutElements, layoutTierFor, type LayoutGraphSize, type LayoutTier } from './layout-configurator';
import { isRowsLayout } from '../model/group-edges';
import { joinPinToPinEdges, splitPinToPinEdges } from './pin-to-pin-edges';
import { LayoutRefusedError } from './elk-server/switching-elk';
import * as os from 'node:os';
import * as path from 'node:path';
import { mkdir, writeFile } from 'node:fs/promises';
Expand Down Expand Up @@ -219,6 +220,12 @@ export class WorkflowElkLayoutEngine extends GlspElkLayoutEngine {
try {
await this.orderPortsAgainstCrossings(root, tier);
} catch (e) {
// A probe the engines refused is the layout refused: the
// layout after it would ask the server for the same graph
// and wait its timeout a second time.
if (e instanceof LayoutRefusedError) {
throw e;
}
console.warn('[cal-elk] port ordering skipped:', e);
}
} else if (this.portsInSourceOrder(root)) {
Expand Down Expand Up @@ -265,7 +272,37 @@ export class WorkflowElkLayoutEngine extends GlspElkLayoutEngine {
}
return root;
};
return run();
// A layout that fails leaves the diagram as it was. Before ELK is
// asked, the ports may have been put in another order (Free Ports, or
// back in the source's): they go back where they were. A layout the
// engines refused is told where the reader looks, once for the probe,
// the layout and the band of pinned groups alike. The log is not it.
const ports = this.portPlaces(root);
return run().catch(error => {
for (const [port, position] of ports) {
port.position = position;
}
if (error instanceof LayoutRefusedError && this.actionDispatcher) {
void Promise.resolve(this.actionDispatcher.dispatch(StatusAction.create(error.message, { severity: 'ERROR' })))
.catch(e => console.warn('[cal-elk] layout status not shown:', e));
}
throw error;
});
}

/** Where every port of the diagram is drawn on its node. */
private portPlaces(root: GGraph): Array<[GPort, GPort['position']]> {
const places: Array<[GPort, GPort['position']]> = [];
const visit = (element: GModelElement): void => {
if (element instanceof GPort) {
places.push([element, element.position ? { ...element.position } : element.position]);
}
for (const child of element.children ?? []) {
visit(child);
}
};
visit(root);
return places;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@

/** Which engine lays a graph out. */
export type LayoutEngineChoice =
/** The server above the size where the platform's cheaper presets start, elkjs below and whenever the server is unavailable. */
/** 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. */
| 'auto'
/** elkjs only; the server is never started. */
| 'elkjs'
/** The server for every graph, elkjs only when the server is unavailable. */
/** The server for every graph, elkjs only when the server is not there. */
| 'elk-server';

export interface ElkServerOptions {
Expand All @@ -31,7 +31,12 @@ export interface ElkServerOptions {
javaPath?: string;
/** JVM options, split on whitespace (e.g. `-Xmx2g`). */
javaOpts?: string;
/** How long one layout may take on the server before elkjs takes it over. Default 120 s. */
/**
* 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.
*/
timeoutMs?: number;
}

Expand Down
11 changes: 10 additions & 1 deletion packages/diagram-server/src/server/elk-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,16 @@ import { SwitchingElk } from './switching-elk';

export * from './elk-server-options';
export { ElkServerProcess } from './elk-server-process';
export { SwitchingElk, elkGraphSize, goesToServer, serverCanLayOut } from './switching-elk';
export {
AUTO_ELKJS_BUDGET_MS,
ELKJS_TAKEOVER_BUDGET_MS,
LayoutRefusedError,
SwitchingElk,
elkGraphSize,
elkjsTakeoverMs,
goesToServer,
serverCanLayOut
} from './switching-elk';
export { layoutOnServer } from './elk-server-client';

const processes = new Map<string, ElkServerProcess>();
Expand Down
Loading
Loading