This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch event-graph-ui in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 1d32c10828ca55a002ffe72ca13683bcd1e83b53 Author: Yasith Jayawardana <[email protected]> AuthorDate: Wed Nov 4 01:54:06 2026 -0500 Show the event graph in the portal --- web/package.json | 1 + web/pnpm-lock.yaml | 8 + .../(portal)/admin/events/graph/page.tsx} | 21 +- .../features/core/events/__fixtures__/graph.json | 360 +++++++++++++++++ .../features/core/events/__tests__/graph.test.ts | 190 +++++++++ web/src/features/core/events/api.ts | 7 +- .../core/events/components/EventGraphCanvas.tsx | 445 +++++++++++++++++++++ .../core/events/components/EventGraphDetails.tsx | 289 +++++++++++++ .../core/events/components/EventGraphPage.tsx | 367 +++++++++++++++++ .../features/core/events/components/EventsPage.tsx | 10 +- web/src/features/core/events/graph.ts | 420 +++++++++++++++++++ web/src/features/core/events/queries.ts | 18 +- web/src/features/core/events/schemas.ts | 36 ++ web/src/features/core/events/types.ts | 6 + web/src/mocks/handlers/events.ts | 3 + 15 files changed, 2165 insertions(+), 16 deletions(-) diff --git a/web/package.json b/web/package.json index acf2590c5..8ff773f79 100644 --- a/web/package.json +++ b/web/package.json @@ -29,6 +29,7 @@ "@tanstack/react-query": "^5.100.11", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "elkjs": "0.10.0", "lucide-react": "^1.16.0", "next": "16.4.2", "next-auth": "5.0.0-beta.32", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 82601bff2..4c9e1da4d 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -184,6 +184,9 @@ importers: clsx: specifier: ^2.1.1 version: 2.1.1 + elkjs: + specifier: 0.10.0 + version: 0.10.0 lucide-react: specifier: ^1.16.0 version: 1.61.0(@types/[email protected])([email protected]) @@ -1681,6 +1684,9 @@ packages: [email protected]: resolution: {integrity: sha512-nVWNU6ltFjopvOdD44J4zoBkgO0M+WZiFKKFV7EjebOH9z0KNphk6bCEjplXtJofL21ARIuuwWOCsFkBVklm6w==} + [email protected]: + resolution: {integrity: sha512-v/3r+3Bl2NMrWmVoRTMBtHtWvRISTix/s9EfnsfEWApNrsmNjqgqJOispCGg46BPwIFdkag3N/HYSxJczvCm6w==} + [email protected]: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -3760,6 +3766,8 @@ snapshots: [email protected]: optional: true + [email protected]: {} + [email protected]: {} [email protected]: diff --git a/web/src/features/core/events/types.ts b/web/src/app/(portal)/admin/events/graph/page.tsx similarity index 59% copy from web/src/features/core/events/types.ts copy to web/src/app/(portal)/admin/events/graph/page.tsx index 674e43e69..f7365bd8c 100644 --- a/web/src/features/core/events/types.ts +++ b/web/src/app/(portal)/admin/events/graph/page.tsx @@ -15,18 +15,13 @@ // specific language governing permissions and limitations // under the License. -import type { z } from "zod"; -import type { - deliveryDetailSchema, - deliverySchema, - historyEntrySchema, - subscriptionListSchema, -} from "./schemas"; +import { EventGraphPage } from "@/features/core/events/components/EventGraphPage"; +import type { Metadata } from "next"; -export type Delivery = z.infer<typeof deliverySchema>; -export type DeliveryDetail = z.infer<typeof deliveryDetailSchema>; -export type HistoryEntry = z.infer<typeof historyEntrySchema>; -export type Subscription = z.infer<typeof subscriptionListSchema>["items"][number]; +export const metadata: Metadata = { + title: "Event graph — Admin", +}; -// The list view a tab shows. "waiting" is every delivery not finished yet. -export type DeliveryView = "all" | "waiting" | "failed"; +export default function AdminEventGraphPage() { + return <EventGraphPage />; +} diff --git a/web/src/features/core/events/__fixtures__/graph.json b/web/src/features/core/events/__fixtures__/graph.json new file mode 100644 index 000000000..905abd2ca --- /dev/null +++ b/web/src/features/core/events/__fixtures__/graph.json @@ -0,0 +1,360 @@ +{ + "events": [ + { + "id": "compute_allocation::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-allocations" + }, + { + "kind": "amie-processor", + "label": "amie.LoadConnector$3" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.Run" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.processPendingEvents" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocations/{id}" + } + ], + "subs": 3 + }, + { + "id": "compute_allocation::group_provision", + "entry": [], + "subs": 1 + }, + { + "id": "compute_allocation::update", + "entry": [ + { + "kind": "amie-processor", + "label": "amie.LoadConnector$3" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.Run" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.processPendingEvents" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation_membership::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-allocation-memberships" + }, + { + "kind": "amie-processor", + "label": "amie.LoadConnector$3" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.Run" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "temp-account", + "label": "POST /connectors/temp-account/assign-allocation" + } + ], + "subs": 3 + }, + { + "id": "compute_allocation_membership::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocation-memberships/{id}" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation_membership::update", + "entry": [ + { + "kind": "API", + "label": "PUT /compute-allocation-memberships/{id}" + }, + { + "kind": "API", + "label": "PUT /compute-allocation-memberships/{id}/status" + }, + { + "kind": "amie-processor", + "label": "amie.LoadConnector$3" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.Run" + }, + { + "kind": "amie-processor", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "temp-account", + "label": "POST /connectors/temp-account/update-allocation" + } + ], + "subs": 3 + } + ], + "edges": [ + { + "from": "compute_allocation::create", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleComputeAllocationChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:73 \u2192 pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleComputeAllocationChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation::update", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleComputeAllocationChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:74 \u2192 pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleComputeAllocationChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:76 \u2192 pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::delete", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:78 \u2192 pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:77 \u2192 pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + } + ], + "terms": [ + { + "from": "compute_allocation::create", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:67", + "effects": ["client.Client.CreateAccount", "client.Client.do"], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "comanage-identity-provisioner", + "actor": "comanage-identity-provisioner.Subscriber.handleComputeAllocationDeleted", + "site": "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:75", + "effects": [ + "client.Client.DeleteCoGroup", + "client.Client.DeleteUnixClusterGroup", + "client.Client.Do", + "client.Client.FindCoGroupByName", + "client.Client.FindUnixClusterGroup", + "client.Client.doOnce" + ], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationDeleted", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:68", + "effects": [ + "client.Client.DeleteAssociation", + "client.Client.ListAssociations", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "vast-storage-provisioner", + "actor": "vast-storage-provisioner.StorageSubscriber.markAllocation", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:89", + "effects": ["folders.Registry.MarkFoldersForDeletion"], + "cond": true + }, + { + "from": "compute_allocation::group_provision", + "conn": "vast-storage-provisioner", + "actor": "vast-storage-provisioner.StorageSubscriber.ensureAllocation", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:85", + "effects": [ + "client.Client.CreateFolder", + "client.Client.CreateQuota", + "client.Client.CreateView", + "client.Client.do", + "folders.Registry.Record" + ], + "cond": true + }, + { + "from": "compute_allocation::update", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationUpdated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:69", + "effects": [ + "client.Client.CreateAccount", + "client.Client.DeleteAssociation", + "client.Client.ListAssociations", + "client.Client.SetDefaultAccount", + "client.Client.UpsertAssociation", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationMembershipCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:70", + "effects": [ + "client.Client.CreateAccount", + "client.Client.ListAssociations", + "client.Client.SetDefaultAccount", + "client.Client.UpsertAssociation", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "conn": "vast-storage-provisioner", + "actor": "vast-storage-provisioner.StorageSubscriber.ensureMember", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:86", + "effects": [ + "client.Client.CreateFolder", + "client.Client.CreateQuota", + "client.Client.CreateView", + "client.Client.do", + "folders.Registry.Record" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::delete", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationMembershipDeleted", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:72", + "effects": [ + "client.Client.DeleteAssociation", + "client.Client.ListAssociations", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "conn": "slurm-association-mapper", + "actor": "slurm-association-mapper.AssociationSubscriber.handleComputeAllocationMembershipUpdated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:71", + "effects": [ + "client.Client.CreateAccount", + "client.Client.DeleteAssociation", + "client.Client.ListAssociations", + "client.Client.SetDefaultAccount", + "client.Client.UpsertAssociation", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "conn": "vast-storage-provisioner", + "actor": "vast-storage-provisioner.StorageSubscriber.ensureMember", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:87", + "effects": [ + "client.Client.CreateFolder", + "client.Client.CreateQuota", + "client.Client.CreateView", + "client.Client.do", + "folders.Registry.Record" + ], + "cond": true + } + ] +} diff --git a/web/src/features/core/events/__tests__/graph.test.ts b/web/src/features/core/events/__tests__/graph.test.ts new file mode 100644 index 000000000..8622aff25 --- /dev/null +++ b/web/src/features/core/events/__tests__/graph.test.ts @@ -0,0 +1,190 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { describe, expect, it } from "vitest"; +import graphFixture from "../__fixtures__/graph.json"; +import { + DEFAULT_GRAPH_OPTIONS, + entityOf, + layoutGraph, + neighbourhood, + selectGraph, + splitActor, + traceGraph, +} from "../graph"; +import { eventGraphSchema } from "../schemas"; +import type { EventGraph, GraphEdge } from "../types"; +import type { LaidEdge, Layout } from "../graph"; + +const edge = ( + from: string, + to: string, + actor: string, + extra: Partial<GraphEdge> = {}, +): GraphEdge => ({ + from, + to, + kind: "conn", + conn: "c", + actor, + sites: [], + chain: [], + cond: false, + ...extra, +}); + +const ev = (id: string, subs = 1) => ({ id, entry: [], subs }); + +describe("selectGraph", () => { + it("drops order-only arrows and arrows into dead ends", () => { + const graph: EventGraph = { + events: [ev("a::x"), ev("a::y"), ev("a::dead", 0), ev("a::z")], + edges: [ + edge("a::x", "a::y", "c.H.f"), + edge("a::x", "a::dead", "c.H.g"), + edge("a::y", "a::z", "core.f", { kind: "core", order: true }), + ], + terms: [], + }; + const sel = selectGraph(graph, DEFAULT_GRAPH_OPTIONS); + expect(sel.edges.map((e) => e.to)).toEqual(["a::y"]); + expect(sel.events.map((e) => e.id)).toEqual(["a::x", "a::y"]); + }); + + it("merges handlers of one connector between the same two events", () => { + const graph: EventGraph = { + events: [ev("a::x"), ev("a::y")], + edges: [edge("a::x", "a::y", "c.H.f", { cond: true }), edge("a::x", "a::y", "c.H.g")], + terms: [], + }; + const [merged] = selectGraph(graph, DEFAULT_GRAPH_OPTIONS).edges; + expect(merged?.actor).toBe("c.H.f / c.H.g"); + expect(merged?.cond).toBe(false); + }); +}); + +describe("traceGraph", () => { + const graph: EventGraph = { + events: [ + { id: "a::x", entry: [{ kind: "API", label: "POST /a" }], subs: 1 }, + { id: "a::y", entry: [{ kind: "amie", label: "loop" }], subs: 1 }, + ev("a::z"), + ev("b::w"), + ], + edges: [ + edge("a::x", "a::y", "c.H.f"), + edge("a::y", "a::z", "c.H.g"), + edge("b::w", "a::z", "c.H.h"), + ], + terms: [{ from: "a::z", conn: "c", actor: "c.H.end", site: "", effects: [], cond: false }], + }; + const sel = selectGraph(graph, DEFAULT_GRAPH_OPTIONS); + const ids = (s: ReturnType<typeof traceGraph>) => s.events.map((e) => e.id); + + it("keeps everything downstream of a trigger and only that trigger's arrows", () => { + const down = traceGraph(sel, { from: "in:API" }); + expect(ids(down)).toEqual(["a::x", "a::y", "a::z"]); + expect(down.events.flatMap((e) => e.entry.map((x) => x.kind))).toEqual(["API"]); + expect(down.terms).toHaveLength(1); + }); + + it("keeps only the paths between two events and drops end steps past the end", () => { + const path = traceGraph(sel, { from: "a::x", to: "a::z" }); + expect(ids(path)).toEqual(["a::x", "a::y", "a::z"]); + expect(path.edges.map((e) => e.actor)).toEqual(["c.H.f", "c.H.g"]); + expect(path.terms).toHaveLength(0); + expect(path.events.every((e) => e.entry.length === 0)).toBe(true); + }); + + it("keeps everything upstream of an event, triggers included", () => { + const up = traceGraph(sel, { to: "a::y" }); + expect(ids(up)).toEqual(["a::x", "a::y"]); + expect(up.events.flatMap((e) => e.entry.map((x) => x.kind)).sort()).toEqual(["API", "amie"]); + }); + + it("is empty when nothing connects the two ends", () => { + expect(ids(traceGraph(sel, { from: "a::z", to: "a::x" }))).toEqual([]); + }); +}); + +describe("splitActor", () => { + it("puts the owner on one line and the function on the next", () => { + expect(splitActor("vast-storage-provisioner.Subscriber.ensureUser")).toEqual([ + "vast-storage-provisioner.Subscriber", + "ensureUser", + ]); + expect(splitActor("f")).toEqual(["", "f"]); + }); +}); + +describe("layoutGraph", () => { + it("places every node inside its entity block and routes every arrow", async () => { + const graph = eventGraphSchema.parse(graphFixture); + const layout = await layoutGraph(selectGraph(graph, DEFAULT_GRAPH_OPTIONS)); + const block = new Map(layout.groups.map((g) => [g.label, g])); + for (const n of layout.nodes) { + if (n.kind === "entry") continue; + const g = block.get(entityOf(n.kind === "end" ? n.from : n.id)); + expect(g).toBeDefined(); + if (!g) continue; + expect(n.x).toBeGreaterThanOrEqual(g.x); + expect(n.y).toBeGreaterThanOrEqual(g.y); + expect(n.x + n.width).toBeLessThanOrEqual(g.x + g.width); + expect(n.y + n.height).toBeLessThanOrEqual(g.y + g.height); + } + expect(layout.nodes.filter((n) => n.kind === "entry").map((n) => n.id)).toContain("in:API"); + for (const e of layout.edges) expect(e.points.length).toBeGreaterThanOrEqual(2); + const lit = neighbourhood(layout, "compute_allocation::create"); + expect(lit.nodes).toContain("in:API"); + expect(lit.nodes).toContain("end:compute_allocation::create"); + }); +}); + +describe("neighbourhood", () => { + it("lights every path into and out of a node", () => { + const edge = (from: string, to: string, kind: "entry" | "end" = "entry") => + ({ id: `${from}>${to}`, from, to, kind, routes: [], points: [], label: null }) as LaidEdge; + const layout: Layout = { + width: 0, + height: 0, + groups: [], + nodes: [], + edges: [ + edge("in:API", "a"), + edge("a", "b"), + edge("x", "b"), + edge("b", "c"), + edge("b", "end:b", "end"), + ], + }; + expect([...neighbourhood(layout, "b").nodes].sort()).toEqual([ + "a", + "b", + "c", + "end:b", + "in:API", + "x", + ]); + expect([...neighbourhood(layout, "a").nodes].sort()).toEqual([ + "a", + "b", + "c", + "end:b", + "in:API", + ]); + }); +}); diff --git a/web/src/features/core/events/api.ts b/web/src/features/core/events/api.ts index b13a8b7ac..5ad698631 100644 --- a/web/src/features/core/events/api.ts +++ b/web/src/features/core/events/api.ts @@ -20,10 +20,11 @@ import { apiFetch } from "@/shared/api/client"; import { deliveryDetailSchema, deliveryListSchema, + eventGraphSchema, subscriptionListSchema, userNameSchema, } from "./schemas"; -import type { Delivery, DeliveryDetail, Subscription } from "./types"; +import type { Delivery, DeliveryDetail, EventGraph, Subscription } from "./types"; // The backend caps one page at 200 rows and has no paging yet. export const DELIVERY_PAGE_SIZE = 200; @@ -60,3 +61,7 @@ export async function listSubscriptions(): Promise<Subscription[]> { const raw = await apiFetch("/events/subscriptions"); return subscriptionListSchema.parse(raw).items; } + +export async function getEventGraph(): Promise<EventGraph> { + return eventGraphSchema.parse(await apiFetch("/events/graph")); +} diff --git a/web/src/features/core/events/components/EventGraphCanvas.tsx b/web/src/features/core/events/components/EventGraphCanvas.tsx new file mode 100644 index 000000000..dc9bbefff --- /dev/null +++ b/web/src/features/core/events/components/EventGraphCanvas.tsx @@ -0,0 +1,445 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import { cn } from "@/lib/utils"; +import * as React from "react"; +import { + END_GAP, + endLines, + entityOf, + type LaidEdge, + type LaidNode, + type Layout, + LINE, + SIZE, + verbOf, +} from "../graph"; +import type { GraphTerm } from "../types"; + +export const COLOR = { + core: "var(--tone-accent-fg)", + conn: "var(--tone-warn-fg)", + entry: "var(--tone-info-fg)", + end: "var(--tone-warn-fg)", +} as const; + +export type Pick = + | { type: "node"; id: string } + | { type: "edge"; id: string } + | { type: "term"; from: string; term: GraphTerm }; + +export type Lit = { edges: Set<string> | null; nodes: Set<string> | null }; + +// The size the layout measured with; the canvas renders in the mono font throughout. +const font = (key: keyof typeof SIZE): React.CSSProperties => ({ + fontSize: SIZE[key], + fontWeight: key === "label" ? 400 : 600, +}); + +type View = { k: number; x: number; y: number }; + +// Below this scale the in-block titles are too small to read. +const ZOOMED_OUT = 0.7; + +// Fills the canvas height and starts at the left; the rest pans into view. +function fitView(layout: Layout, el: SVGSVGElement): View { + const { clientWidth: w, clientHeight: h } = el; + const k = Math.min(1.5, (h - 8) / layout.height); + const x = k * layout.width > w - 8 ? 4 : (w - k * layout.width) / 2; + return { k, x, y: (h - k * layout.height) / 2 }; +} + +const groupOf = (n: LaidNode) => entityOf(n.kind === "end" ? n.from : n.id); + +// One hue per block, so neighbouring entities read apart in both themes. +const HUES = [ + "var(--chart-1)", + "var(--chart-2)", + "var(--chart-3)", + "var(--chart-4)", + "var(--tone-error-fg)", + "var(--chart-5)", +]; +const tint = (hue: string, pct: number) => `color-mix(in oklab, ${hue} ${pct}%, var(--background))`; + +export function EventGraphCanvas({ + layout, + lit, + marked, + onPick, + onClear, +}: { + layout: Layout; + lit: Lit; + marked: Set<string>; + onPick: (p: Pick) => void; + onClear: () => void; +}) { + const svg = React.useRef<SVGSVGElement>(null); + const [view, setView] = React.useState<View>({ k: 1, x: 0, y: 0 }); + const drag = React.useRef<{ x: number; y: number; moved: boolean } | null>(null); + + // Pans stop where the content's edge meets the canvas margin; content that fits stays centred. + const pan = React.useCallback( + (dx: number, dy: number) => { + const el = svg.current; + if (!el) return; + const axis = (at: number, content: number, size: number) => + content + 8 <= size ? (size - content) / 2 : Math.min(4, Math.max(size - 4 - content, at)); + setView((v) => ({ + k: v.k, + x: axis(v.x + dx, v.k * layout.width, el.clientWidth), + y: axis(v.y + dy, v.k * layout.height, el.clientHeight), + })); + }, + [layout], + ); + const refit = React.useCallback(() => { + if (svg.current) setView(fitView(layout, svg.current)); + }, [layout]); + + React.useLayoutEffect(() => { + const el = svg.current; + if (!el) return; + refit(); + const observer = new ResizeObserver(refit); + observer.observe(el); + return () => observer.disconnect(); + }, [refit]); + + // React registers wheel listeners as passive, so panning binds natively to stop page scroll. + React.useEffect(() => { + const el = svg.current; + if (!el) return; + const onWheel = (e: WheelEvent) => { + e.preventDefault(); + pan(-e.deltaX, -e.deltaY); + }; + el.addEventListener("wheel", onWheel, { passive: false }); + return () => el.removeEventListener("wheel", onWheel); + }, [pan]); + + const order = layout.groups.map((g) => g.label).sort(); + const hue = (label: string) => HUES[order.indexOf(label) % HUES.length] ?? "var(--chart-5)"; + const litGroups = lit.nodes + ? new Set(layout.nodes.filter((n) => lit.nodes?.has(n.id) && n.kind !== "entry").map(groupOf)) + : null; + const dim = (set: Set<string> | null, id: string) => + set && !set.has(id) ? "opacity-[.12]" : undefined; + const picked = (p: Pick) => (e: React.MouseEvent) => { + e.stopPropagation(); + onPick(p); + }; + + return ( + <svg + ref={svg} + role="img" + aria-label="Event state machine" + className="block h-full w-full cursor-grab touch-none select-none font-mono" + onPointerDown={(e) => { + drag.current = { x: e.clientX, y: e.clientY, moved: false }; + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || (!d.moved && Math.hypot(e.clientX - d.x, e.clientY - d.y) < 3)) return; + // Capture only once moving, so a plain click still reaches the box under it. + if (!d.moved) e.currentTarget.setPointerCapture(e.pointerId); + pan(e.clientX - d.x, e.clientY - d.y); + drag.current = { x: e.clientX, y: e.clientY, moved: true }; + }} + onClickCapture={(e) => { + if (drag.current?.moved) e.stopPropagation(); + drag.current = null; + }} + onClick={onClear} + > + <defs> + <style>{"@keyframes eg-flow { to { stroke-dashoffset: var(--eg-period); } }"}</style> + {(["core", "conn", "entry"] as const).map((k) => ( + <marker + key={k} + id={`eg-${k}`} + viewBox="0 -4 8 8" + refX={8} + refY={0} + markerWidth={7} + markerHeight={7} + orient="auto" + > + <path d="M0,-4L8,0L0,4" style={{ fill: COLOR[k] }} /> + </marker> + ))} + </defs> + <g transform={`translate(${view.x},${view.y}) scale(${view.k})`}> + {layout.groups.map((g) => ( + <g key={g.id} className={dim(litGroups, g.label)}> + <rect + x={g.x} + y={g.y} + width={g.width} + height={g.height} + rx={10} + style={{ fill: tint(hue(g.label), 9), stroke: tint(hue(g.label), 55) }} + /> + <text + x={g.x + 12} + y={g.y + 21} + visibility={view.k < ZOOMED_OUT ? "hidden" : undefined} + style={{ ...font("group"), fill: tint(hue(g.label), 85) }} + > + {g.label} + </text> + </g> + ))} + {layout.edges.map((e) => ( + <EdgeView + key={e.id} + edge={e} + className={dim(lit.edges, e.id)} + flowing={lit.edges?.has(e.id) ?? true} + onClick={picked( + e.kind === "entry" ? { type: "node", id: e.to } : { type: "edge", id: e.id }, + )} + /> + ))} + {layout.nodes.map((n) => ( + <NodeView + key={n.id} + node={n} + marked={marked.has(n.id)} + className={dim(lit.nodes, n.id)} + picked={picked} + /> + ))} + {layout.edges.map((e) => + e.label ? ( + <EdgeLabel key={`${e.id}:label`} edge={e} className={dim(lit.edges, e.id)} /> + ) : null, + )} + {view.k < ZOOMED_OUT + ? // Zoomed out, block names keep a readable on-screen size above their blocks. + layout.groups.map((g) => ( + <text + key={`${g.id}:title`} + x={g.x} + y={g.y - 4 / view.k} + className={cn("pointer-events-none stroke-background", dim(litGroups, g.label))} + style={{ + ...font("group"), + fill: tint(hue(g.label), 85), + fontSize: 12 / view.k, + strokeWidth: 4 / view.k, + paintOrder: "stroke", + }} + > + {g.label} + </text> + )) + : null} + </g> + </svg> + ); +} + +const pathOf = (e: LaidEdge) => `M${e.points.map((p) => `${p.x},${p.y}`).join("L")}`; + +function EdgeView({ + edge, + className, + flowing, + onClick, +}: { + edge: LaidEdge; + className?: string | undefined; + flowing: boolean; + onClick: (e: React.MouseEvent) => void; +}) { + const d = pathOf(edge); + const cond = (edge.kind === "core" || edge.kind === "conn") && edge.transition.cond; + // The line itself flows source to target: its dashes march; a solid arrow dashes only while flowing. + const [dash, period] = + edge.kind === "entry" ? ["4 3", 7] : cond ? ["2 3", 5] : flowing ? ["9 3", 12] : [undefined, 0]; + return ( + <g className={className}> + <path + d={d} + fill="none" + style={{ stroke: COLOR[edge.kind], ["--eg-period" as string]: `-${period}px` }} + strokeWidth={edge.kind === "entry" ? 1.2 : 1.6} + strokeDasharray={dash} + markerEnd={edge.kind === "end" ? undefined : `url(#eg-${edge.kind})`} + className={flowing ? "motion-safe:animate-[eg-flow_0.8s_linear_infinite]" : undefined} + /> + {edge.kind === "end" ? null : ( + <path + d={d} + fill="none" + stroke="transparent" + strokeWidth={12} + className="cursor-pointer" + onClick={onClick} + > + <title> + {edge.kind === "entry" + ? edge.routes.join("\n") + : edge.transition.multi.map((a) => a.actor).join("\n")} + </title> + </path> + )} + </g> + ); +} + +function EdgeLabel({ edge, className }: { edge: LaidEdge; className?: string | undefined }) { + if (!edge.label) return null; + const { x, y, lines, width, height } = edge.label; + return ( + <g transform={`translate(${x},${y})`} className={cn("pointer-events-none", className)}> + <rect + x={-width / 2} + y={-height / 2} + width={width} + height={height} + rx={3} + className="fill-background/90" + /> + <text textAnchor="middle" style={{ ...font("label"), fill: COLOR[edge.kind] }}> + {lines.map((l, i) => ( + <tspan key={`${i}:${l}`} x={0} y={-height / 2 + 12 + i * LINE}> + {l} + </tspan> + ))} + </text> + </g> + ); +} + +function NodeView({ + node, + marked, + className, + picked, +}: { + node: LaidNode; + marked: boolean; + className?: string | undefined; + picked: (p: Pick) => (e: React.MouseEvent) => void; +}) { + const ring = marked ? ( + <rect + x={-4} + y={-4} + width={node.width + 8} + height={node.height + 8} + rx={9} + fill="none" + className="stroke-brand" + strokeWidth={2} + /> + ) : null; + if (node.kind === "event") { + const { event } = node; + return ( + <g + transform={`translate(${node.x},${node.y})`} + className={cn("cursor-pointer", className)} + onClick={picked({ type: "node", id: node.id })} + > + <title>{event.id}</title> + {ring} + <rect + width={node.width} + height={node.height} + rx={6} + className="fill-card" + style={{ stroke: event.entry.length ? COLOR.entry : "var(--color-muted-foreground)" }} + strokeWidth={event.entry.length ? 2 : 1.2} + strokeDasharray={event.subs ? undefined : "3 2"} + /> + <text + x={node.width / 2} + y={node.height / 2 + 4.5} + textAnchor="middle" + className="fill-foreground" + style={font("event")} + > + {verbOf(event.id)} + </text> + </g> + ); + } + if (node.kind === "entry") { + return ( + <g + transform={`translate(${node.x},${node.y})`} + className={cn("cursor-pointer", className)} + onClick={picked({ type: "node", id: node.id })} + > + {ring} + <rect + width={node.width} + height={node.height} + rx={14} + className="fill-card" + style={{ stroke: COLOR.entry }} + /> + <text + x={node.width / 2} + y={node.height / 2 + 4.5} + textAnchor="middle" + style={{ ...font("entry"), fill: COLOR.entry }} + > + {node.label} + </text> + </g> + ); + } + return ( + <g transform={`translate(${node.x},${node.y})`} className={className}> + <rect + width={node.width} + height={node.height} + rx={4} + className="fill-card" + style={{ stroke: COLOR.end }} + strokeDasharray="3 2" + /> + {node.terms.map((term, i) => { + const before = node.terms.slice(0, i).flatMap(endLines).length; + const top = 2 + before * LINE + i * END_GAP; + return ( + <text + key={term.actor} + className="cursor-pointer" + style={{ ...font("label"), fill: COLOR.end }} + onClick={picked({ type: "term", from: node.from, term })} + > + <title>{`${node.from} ⊣ ${term.actor}`}</title> + {endLines(term).map((l, j) => ( + <tspan key={`${j}:${l}`} x={8} y={top + 13 + j * LINE} xmlSpace="preserve"> + {l} + </tspan> + ))} + </text> + ); + })} + </g> + ); +} diff --git a/web/src/features/core/events/components/EventGraphDetails.tsx b/web/src/features/core/events/components/EventGraphDetails.tsx new file mode 100644 index 000000000..89edea8fe --- /dev/null +++ b/web/src/features/core/events/components/EventGraphDetails.tsx @@ -0,0 +1,289 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import { Button } from "@/shared/ui/button"; +import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import * as React from "react"; +import { type LaidEdge, type Layout, splitActor, type Trace } from "../graph"; +import type { GraphTerm } from "../types"; +import { COLOR, type Pick } from "./EventGraphCanvas"; + +export function EventGraphDetails({ + layout, + pick, + open, + onOpen, + onTrace, +}: { + layout: Layout; + pick: Pick; + open: boolean; + onOpen: (open: boolean) => void; + onTrace: (trace: Trace) => void; +}) { + // Share of the canvas height; the top edge drags or steps with the arrow keys. + const [share, setShare] = React.useState(0.5); + const resize = (next: number) => setShare(Math.min(0.9, Math.max(0.15, next))); + const title = + pick.type === "term" + ? `${pick.from} ⊣ ${splitActor(pick.term.actor)[1]}` + : pick.type === "edge" + ? pick.id.split("|")[0] + : pick.id.replace(/^in:/, ""); + if (!open) { + return ( + <Button + variant="outline" + size="sm" + className="absolute bottom-3 left-1/2 z-10 max-w-[60%] -translate-x-1/2 shadow-sm" + onClick={() => onOpen(true)} + > + <ChevronUpIcon /> + <span className="truncate font-mono text-xs">{title}</span> + </Button> + ); + } + return ( + <aside + className="absolute inset-x-0 bottom-0 z-10 flex animate-in flex-col rounded-t-lg border-t bg-card text-sm shadow-lg duration-200 slide-in-from-bottom" + style={{ height: `${share * 100}%` }} + aria-label="Details" + > + {/* biome-ignore lint/a11y/useSemanticElements: a focusable, draggable separator is a widget; hr is static. */} + <div + role="separator" + aria-orientation="horizontal" + aria-label="Resize details" + aria-valuenow={Math.round(share * 100)} + tabIndex={0} + className="flex h-3 shrink-0 cursor-row-resize touch-none items-center justify-center outline-none focus-visible:bg-muted" + onPointerDown={(e) => e.currentTarget.setPointerCapture(e.pointerId)} + onPointerMove={(e) => { + const frame = e.currentTarget.parentElement?.parentElement; + if (!frame || !e.currentTarget.hasPointerCapture(e.pointerId)) return; + const r = frame.getBoundingClientRect(); + resize((r.bottom - e.clientY) / r.height); + }} + onKeyDown={(e) => { + if (e.key === "ArrowUp" || e.key === "ArrowDown") { + e.preventDefault(); + resize(share + (e.key === "ArrowUp" ? 0.05 : -0.05)); + } + }} + > + <span className="h-1 w-10 rounded-full bg-border" /> + </div> + <Button + variant="ghost" + size="icon-sm" + aria-label="Close details" + className="absolute top-1 right-2" + onClick={() => onOpen(false)} + > + <ChevronDownIcon /> + </Button> + <div className="min-h-0 flex-1 overflow-auto px-3 pb-3"> + {pick.type === "term" ? ( + <TermDetails from={pick.from} term={pick.term} /> + ) : pick.type === "edge" ? ( + <EdgeDetails edge={layout.edges.find((e) => e.id === pick.id)} /> + ) : ( + <NodeDetails layout={layout} id={pick.id} onTrace={onTrace} /> + )} + </div> + </aside> + ); +} + +const Key = ({ children }: { children: React.ReactNode }) => ( + <div className="mt-2 text-xs text-muted-foreground">{children}</div> +); +const Mono = ({ children }: { children: React.ReactNode }) => ( + <code className="font-mono text-xs break-all">{children}</code> +); +const Dot = ({ kind }: { kind: keyof typeof COLOR }) => ( + <span style={{ color: COLOR[kind] }}>● </span> +); + +function TermDetails({ from, term }: { from: string; term: GraphTerm }) { + return ( + <> + <h2 className="font-mono text-sm font-semibold break-all"> + {from} ⊣ {splitActor(term.actor)[1]} + </h2> + <div className="text-xs text-muted-foreground"> + connector end step{term.cond ? " · conditional subscription" : ""} + </div> + <Key>Handled by</Key> + <div> + <Dot kind="end" /> + <Mono>{term.actor}</Mono> + </div> + <div className="font-mono text-[11.5px] break-all text-muted-foreground">{term.site}</div> + <Key>External effects</Key> + {term.effects.length ? ( + <ul className="list-disc pl-5"> + {term.effects.map((x) => ( + <li key={x}> + <Mono>{x}</Mono> + </li> + ))} + </ul> + ) : ( + <div className="text-xs text-muted-foreground">none recorded</div> + )} + </> + ); +} + +function EdgeDetails({ edge }: { edge: LaidEdge | undefined }) { + if (!edge || (edge.kind !== "core" && edge.kind !== "conn")) return null; + const t = edge.transition; + return ( + <> + <h2 className="font-mono text-sm font-semibold break-all"> + {t.from} → {t.to} + </h2> + <div className="text-xs text-muted-foreground"> + {t.kind === "core" ? "core transition (automatic)" : `connector transition · ${t.conn}`} + {t.cond ? " · conditional" : ""} + </div> + <Key>Performed by</Key> + {t.multi.map((a) => ( + <div key={a.actor} className="mt-1.5"> + <Dot kind={a.kind} /> + <Mono>{a.actor}</Mono> + {a.cond ? <span className="text-xs text-muted-foreground"> conditional</span> : null} + <ul className="list-disc pl-5 font-mono text-[11.5px] break-all text-muted-foreground"> + {a.sites.map((s) => ( + <li key={s}>{s}</li> + ))} + </ul> + <div className="font-mono text-[11.5px] break-all text-muted-foreground"> + {a.chain.join(" → ")} + </div> + </div> + ))} + </> + ); +} + +function TraceButtons({ + id, + onTrace, + to = true, +}: { + id: string; + onTrace: (t: Trace) => void; + to?: boolean; +}) { + return ( + <div className="mt-2 flex gap-2"> + <Button variant="outline" size="xs" onClick={() => onTrace({ from: id })}> + Trace from here + </Button> + {to ? ( + <Button variant="outline" size="xs" onClick={() => onTrace({ to: id })}> + Trace to here + </Button> + ) : null} + </div> + ); +} + +function NodeDetails({ + layout, + id, + onTrace, +}: { + layout: Layout; + id: string; + onTrace: (t: Trace) => void; +}) { + const node = layout.nodes.find((n) => n.id === id); + if (!node) return null; + const into = layout.edges.filter((e) => e.to === id); + const outOf = layout.edges.filter((e) => e.from === id); + if (node.kind === "entry") { + return ( + <> + <h2 className="text-sm font-semibold">{node.label}</h2> + <div className="text-xs text-muted-foreground">external trigger</div> + <TraceButtons id={id} onTrace={onTrace} to={false} /> + <Key>Starts</Key> + <ul className="list-disc pl-5"> + {outOf.map((e) => ( + <li key={e.id}> + <Mono>{e.to}</Mono> + {e.kind === "entry" ? ( + <div className="font-mono text-[11.5px] text-muted-foreground"> + {e.routes.join(", ")} + </div> + ) : null} + </li> + ))} + </ul> + </> + ); + } + if (node.kind !== "event") return null; + const { event } = node; + const transitions = (edges: LaidEdge[], side: "from" | "to") => { + const ts = edges.flatMap((e) => (e.kind === "core" || e.kind === "conn" ? [e.transition] : [])); + return ts.length ? ( + <ul className="list-disc pl-5"> + {ts.map((t) => ( + <li key={`${t[side]}|${t.actor}`}> + <Dot kind={t.kind} /> + <Mono>{t[side]}</Mono> <span className="text-xs text-muted-foreground">via</span>{" "} + <Mono>{t.actor}</Mono> + {t.cond ? <span className="text-xs text-muted-foreground"> conditional</span> : null} + </li> + ))} + </ul> + ) : ( + <div className="text-xs text-muted-foreground">none</div> + ); + }; + return ( + <> + <h2 className="font-mono text-sm font-semibold break-all">{event.id}</h2> + <div className="text-xs text-muted-foreground"> + {event.subs ? `${event.subs} subscription${event.subs > 1 ? "s" : ""}` : "no subscriber"} + </div> + <TraceButtons id={id} onTrace={onTrace} /> + <Key>Started by</Key> + {event.entry.length ? ( + <ul className="list-disc pl-5"> + {event.entry.map((x) => ( + <li key={`${x.kind}|${x.label}`}> + <span className="text-xs text-muted-foreground">{x.kind}</span> <Mono>{x.label}</Mono> + </li> + ))} + </ul> + ) : ( + <div className="text-xs text-muted-foreground">only by other events</div> + )} + <Key>Follows from</Key> + {transitions(into, "from")} + <Key>Leads to</Key> + {transitions(outOf, "to")} + </> + ); +} diff --git a/web/src/features/core/events/components/EventGraphPage.tsx b/web/src/features/core/events/components/EventGraphPage.tsx new file mode 100644 index 000000000..48e781875 --- /dev/null +++ b/web/src/features/core/events/components/EventGraphPage.tsx @@ -0,0 +1,367 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import { cn } from "@/lib/utils"; +import { ApiError } from "@/shared/api/client"; +import { + replaceShallowSearchParams, + useShallowSearchParams, +} from "@/shared/hooks/useShallowSearchParams"; +import { Button } from "@/shared/ui/button"; +import { EmptyState } from "@/shared/ui/EmptyState"; +import { ErrorState } from "@/shared/ui/ErrorState"; +import { Input } from "@/shared/ui/input"; +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectTrigger, + SelectValue, +} from "@/shared/ui/select"; +import { Skeleton } from "@/shared/ui/skeleton"; +import { ArrowLeftRightIcon, ArrowRightIcon } from "lucide-react"; +import * as React from "react"; +import { + DEFAULT_GRAPH_OPTIONS, + entityOf, + type GraphOptions, + type Layout, + layoutGraph, + neighbourhood, + pathsThrough, + type Selected, + selectGraph, + type Trace, + traceGraph, + triggerId, + verbOf, +} from "../graph"; +import { useEventGraph } from "../queries"; +import { COLOR, EventGraphCanvas, type Lit, type Pick } from "./EventGraphCanvas"; +import { EventGraphDetails } from "./EventGraphDetails"; + +const ANY = "*"; + +const SHOW: { + key: keyof GraphOptions; + label: string; + swatch: React.ReactNode; +}[] = [ + { key: "core", label: "Core", swatch: <Line color={COLOR.core} /> }, + { key: "connector", label: "Connector", swatch: <Line color={COLOR.conn} /> }, + { key: "ends", label: "End steps", swatch: <span style={{ color: COLOR.end }}>⊣</span> }, + { key: "entries", label: "Triggers", swatch: <Line color={COLOR.entry} dashed /> }, +]; + +function Line({ color, dashed = false }: { color: string; dashed?: boolean }) { + return ( + <span + className="inline-block h-0 w-4 border-t-2 align-middle" + style={{ borderColor: color, borderTopStyle: dashed ? "dashed" : "solid" }} + /> + ); +} + +function useTrace(): [Trace, (t: Trace) => void] { + const params = useShallowSearchParams(); + const trace = { from: params.get("from") ?? undefined, to: params.get("to") ?? undefined }; + const setTrace = (t: Trace) => { + const next = new URLSearchParams(params.toString()); + for (const key of ["from", "to"] as const) { + const value = t[key]; + if (value) next.set(key, value); + else next.delete(key); + } + replaceShallowSearchParams(next); + }; + return [trace, setTrace]; +} + +export function EventGraphPage() { + const graph = useEventGraph(); + const [options, setOptions] = React.useState(DEFAULT_GRAPH_OPTIONS); + const [trace, setTrace] = useTrace(); + const [layout, setLayout] = React.useState<Layout>(); + const [pick, setPick] = React.useState<Pick>(); + const [open, setOpen] = React.useState(false); + const [query, setQuery] = React.useState(""); + + const selected = React.useMemo( + () => (graph.data ? selectGraph(graph.data, options) : undefined), + [graph.data, options], + ); + const { from, to } = trace; + const traced = React.useMemo( + () => (selected ? traceGraph(selected, { from, to }) : undefined), + [selected, from, to], + ); + + React.useEffect(() => { + if (!traced) return; + let live = true; + layoutGraph(traced).then((l) => { + if (live) setLayout(l); + }); + setPick(undefined); + return () => { + live = false; + }; + }, [traced]); + + const lit = React.useMemo( + () => (layout ? highlight(layout, pick, query) : undefined), + [layout, pick, query], + ); + const marked = React.useMemo( + () => new Set([from, to].filter((x): x is string => Boolean(x))), + [from, to], + ); + + return ( + <div className="-mx-10 -mb-8 flex h-[calc(100vh-6rem)] min-h-[520px] flex-col gap-2"> + {selected ? ( + <Toolbar + selected={selected} + options={options} + onOptions={setOptions} + trace={trace} + onTrace={setTrace} + query={query} + onQuery={setQuery} + /> + ) : null} + + <div className="relative min-h-0 flex-1 overflow-hidden border-t bg-background"> + {graph.isError ? ( + graph.error instanceof ApiError && graph.error.status === 404 ? ( + <EmptyState + className="h-full border-0" + heading="No event graph" + description="This server was built without one. Run `go generate ./cmd/server/` and rebuild." + /> + ) : ( + <ErrorState message={graph.error.message} /> + ) + ) : traced && !traced.events.length ? ( + <EmptyState + className="h-full border-0" + heading="No path" + description="Nothing connects these two with the current filters. Turn on more arrow kinds or pick other ends." + /> + ) : layout && lit ? ( + <> + <EventGraphCanvas + layout={layout} + lit={lit} + marked={marked} + onPick={setPick} + // An empty click folds the open drawer first, then drops the selection. + onClear={() => { + if (open) return setOpen(false); + setPick(undefined); + setQuery(""); + }} + /> + {pick ? ( + <EventGraphDetails + layout={layout} + pick={pick} + open={open} + onOpen={setOpen} + onTrace={(t) => setTrace({ ...trace, ...t })} + /> + ) : null} + </> + ) : ( + <Skeleton className="h-full w-full" /> + )} + </div> + </div> + ); +} + +function Toolbar({ + selected, + options, + onOptions, + trace, + onTrace, + query, + onQuery, +}: { + selected: Selected; + options: GraphOptions; + onOptions: (o: GraphOptions) => void; + trace: Trace; + onTrace: (t: Trace) => void; + query: string; + onQuery: (q: string) => void; +}) { + // Trace ends come from what the filters show, so a pick always has something to trace. + const triggers = [...new Set(selected.events.flatMap((e) => e.entry.map((x) => x.kind)))].sort(); + const byEntity = [...Map.groupBy(selected.events, (e) => entityOf(e.id))] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([entity, events]) => ({ entity, events: events.map((e) => e.id) })); + + return ( + <div className="flex flex-wrap items-center gap-2 px-10 xl:flex-nowrap"> + <h1 className="mr-2 shrink-0 text-lg font-semibold tracking-tight whitespace-nowrap"> + Event graph + </h1> + <EndPicker + label="From" + value={trace.from} + onChange={(from) => onTrace({ ...trace, from })} + triggers={triggers} + groups={byEntity} + /> + <ArrowRightIcon aria-hidden="true" className="size-4 text-muted-foreground" /> + <EndPicker + label="To" + value={trace.to} + onChange={(to) => onTrace({ ...trace, to })} + groups={byEntity} + /> + <Button + variant="ghost" + size="icon-sm" + aria-label="Swap start and end" + disabled={Boolean(trace.from?.startsWith("in:"))} + onClick={() => onTrace({ from: trace.to, to: trace.from })} + > + <ArrowLeftRightIcon /> + </Button> + {trace.from || trace.to ? ( + <Button variant="ghost" size="sm" onClick={() => onTrace({})}> + Clear + </Button> + ) : null} + {SHOW.map(({ key, label, swatch }) => ( + <Button + key={key} + variant="outline" + size="sm" + aria-pressed={options[key]} + onClick={() => onOptions({ ...options, [key]: !options[key] })} + className={cn(!options[key] && "text-muted-foreground opacity-60")} + > + {swatch} + {label} + </Button> + ))} + <Input + type="search" + value={query} + onChange={(e) => onQuery(e.target.value)} + placeholder="Highlight…" + aria-label="Highlight event or handler" + className="ml-auto h-8 w-60 min-w-28 shrink" + /> + </div> + ); +} + +function EndPicker({ + label, + value, + onChange, + triggers = [], + groups, +}: { + label: string; + value: string | undefined; + onChange: (value: string | undefined) => void; + triggers?: string[]; + groups: { entity: string; events: string[] }[]; +}) { + const name = (id: string) => (id.startsWith("in:") ? id.slice(3) : id); + return ( + <Select value={value ?? ANY} onValueChange={(v) => onChange(!v || v === ANY ? undefined : v)}> + <SelectTrigger aria-label={label} className="h-8 w-56 min-w-32 shrink px-3"> + <SelectValue> + {(v: string) => ( + <span className="truncate"> + <span className="text-muted-foreground">{label}: </span> + <span className="font-mono text-xs">{v === ANY ? "any" : name(v)}</span> + </span> + )} + </SelectValue> + </SelectTrigger> + <SelectContent className="max-h-96"> + <SelectItem value={ANY}>any</SelectItem> + {triggers.length ? ( + <SelectGroup> + <SelectLabel>Triggers</SelectLabel> + {triggers.map((t) => ( + <SelectItem key={t} value={triggerId(t)}> + {t} + </SelectItem> + ))} + </SelectGroup> + ) : null} + {groups.map(({ entity, events }) => ( + <SelectGroup key={entity}> + <SelectLabel className="font-mono">{entity}</SelectLabel> + {events.map((id) => ( + <SelectItem key={id} value={id} className="pl-5 font-mono text-xs"> + {verbOf(id)} + </SelectItem> + ))} + </SelectGroup> + ))} + </SelectContent> + </Select> + ); +} + +function highlight(layout: Layout, pick: Pick | undefined, query: string): Lit { + if (pick?.type === "node") return neighbourhood(layout, pick.id); + if (pick?.type === "term") { + const e = layout.edges.find((x) => x.kind === "end" && x.from === pick.from); + return pathsThrough(layout, pick.from, `end:${pick.from}`, e?.id); + } + if (pick?.type === "edge") { + const e = layout.edges.find((x) => x.id === pick.id); + return e ? pathsThrough(layout, e.from, e.to, e.id) : { edges: null, nodes: null }; + } + const s = query.trim().toLowerCase(); + if (!s) return { edges: null, nodes: null }; + const hit = (x: string) => x.toLowerCase().includes(s); + return { + edges: new Set( + layout.edges + .filter((e) => + [ + e.from, + e.to, + ...(e.kind === "entry" ? e.routes : []), + ...(e.kind === "core" || e.kind === "conn" ? [e.transition.actor] : []), + ].some(hit), + ) + .map((e) => e.id), + ), + nodes: new Set( + layout.nodes + .filter((n) => hit(n.id) || (n.kind === "end" && n.terms.some((t) => hit(t.actor)))) + .map((n) => n.id), + ), + }; +} diff --git a/web/src/features/core/events/components/EventsPage.tsx b/web/src/features/core/events/components/EventsPage.tsx index 316e9ad76..3e9cbef9d 100644 --- a/web/src/features/core/events/components/EventsPage.tsx +++ b/web/src/features/core/events/components/EventsPage.tsx @@ -28,6 +28,7 @@ import { TableSkeleton } from "@/shared/ui/Loading"; import { Button } from "@/shared/ui/button"; import { Label } from "@/shared/ui/label"; import { RefreshCwIcon, UnplugIcon } from "lucide-react"; +import Link from "next/link"; import * as React from "react"; import { toast } from "sonner"; import { DELIVERY_PAGE_SIZE } from "../api"; @@ -128,7 +129,14 @@ export function EventsPage() { <h1 className="text-2xl font-bold tracking-tight">Events</h1> <p className="text-sm text-muted-foreground"> Each event is sent to every connector that listens for it. A failed delivery is retried up - to 10 times, then waits here for an admin. + to 10 times, then waits here for an admin.{" "} + <Link + href="/admin/events/graph" + className="text-brand underline-offset-4 hover:underline" + > + See which events lead to which + </Link> + . </p> </header> diff --git a/web/src/features/core/events/graph.ts b/web/src/features/core/events/graph.ts new file mode 100644 index 000000000..cbf99a1a7 --- /dev/null +++ b/web/src/features/core/events/graph.ts @@ -0,0 +1,420 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Event state machine from GET /events/graph, laid out by ELK layered. +// Events are grouped in one block per entity (the part before `::`); each external trigger +// (API, a connector loop) is one box whose arrows carry the routes that start an event. +// Arrows are core transitions (core function) or connector transitions (Connector.handler); +// an end card lists handlers that take an event and emit nothing. +// A trace keeps only what lies on a path from one node to another, so it lays out small and legible. +// All text is monospace, so a box is sized from its text length alone. +// Coordinates are absolute and top-left; ELK reports them relative to the enclosing block. + +import ELK, { type ElkExtendedEdge, type ElkNode } from "elkjs/lib/elk.bundled.js"; +import type { EventGraph, GraphEdge, GraphEvent, GraphTerm } from "./types"; + +export type GraphOptions = { core: boolean; connector: boolean; ends: boolean; entries: boolean }; + +export const DEFAULT_GRAPH_OPTIONS: GraphOptions = { + core: true, + connector: true, + ends: true, + entries: true, +}; + +// One arrow; handlers of one connector between the same two events share it. +type Transition = GraphEdge & { multi: GraphEdge[] }; + +export type Selected = { events: GraphEvent[]; edges: Transition[]; terms: GraphTerm[] }; + +export const entityOf = (id: string) => id.split("::")[0] ?? id; +export const verbOf = (id: string) => id.split("::")[1] ?? id; +export const triggerId = (kind: string) => `in:${kind}`; +const endId = (event: string) => `end:${event}`; + +export function selectGraph(graph: EventGraph, o: GraphOptions): Selected { + const byId = new Map(graph.events.map((e) => [e.id, e])); + const terms = o.ends ? graph.terms : []; + // Order-only: A was published in a helper and B later in its caller; sequence, not cause. + let edges = graph.edges.filter((e) => (e.kind === "core" ? o.core : o.connector) && !e.order); + // Drop transitions into events nobody handles and that lead nowhere, until none remain. + for (let n = -1; n !== edges.length; ) { + n = edges.length; + const out = new Set([...edges.map((e) => e.from), ...terms.map((t) => t.from)]); + edges = edges.filter((e) => byId.get(e.to)?.subs || out.has(e.to)); + } + const merged = new Map<string, Transition>(); + for (const e of edges) { + const key = `${e.from}→${e.to}|${e.kind}|${e.conn}`; + const m = merged.get(key); + if (m) m.multi.push(e); + else merged.set(key, { ...e, multi: [e] }); + } + const transitions = [...merged.values()].map((e) => + e.multi.length > 1 + ? { ...e, actor: e.multi.map((a) => a.actor).join(" / "), cond: e.multi.every((a) => a.cond) } + : e, + ); + const used = new Set([ + ...transitions.flatMap((e) => [e.from, e.to]), + ...terms.map((t) => t.from), + ]); + return { + events: graph.events + .filter((e) => used.has(e.id)) + .map((e) => (o.entries ? e : { ...e, entry: [] })), + edges: transitions, + terms, + }; +} + +export type Trace = { from?: string | undefined; to?: string | undefined }; + +// Keeps what lies on some path from `from` and on some path to `to`; either end may be open. +export function traceGraph(sel: Selected, { from, to }: Trace): Selected { + if (!from && !to) return sel; + const next = new Map<string, string[]>(); + const prev = new Map<string, string[]>(); + const link = (a: string, b: string) => { + next.set(a, [...(next.get(a) ?? []), b]); + prev.set(b, [...(prev.get(b) ?? []), a]); + }; + for (const e of sel.events) for (const x of e.entry) link(triggerId(x.kind), e.id); + for (const t of sel.edges) link(t.from, t.to); + for (const t of sel.terms) link(t.from, endId(t.from)); + const reach = (start: string | undefined, adj: Map<string, string[]>) => { + if (!start) return null; + const seen = new Set([start]); + for (const queue = [start]; queue.length; ) { + for (const n of adj.get(queue.shift() ?? "") ?? []) { + if (!seen.has(n)) { + seen.add(n); + queue.push(n); + } + } + } + return seen; + }; + const down = reach(from, next); + const up = reach(to, prev); + const keep = (id: string) => (!down || down.has(id)) && (!up || up.has(id)); + return { + events: sel.events + .filter((e) => keep(e.id)) + .map((e) => ({ ...e, entry: e.entry.filter((x) => keep(triggerId(x.kind))) })), + edges: sel.edges.filter((t) => keep(t.from) && keep(t.to)), + terms: sel.terms.filter((t) => keep(t.from) && keep(endId(t.from))), + }; +} + +// A handler A.B.fn splits into where it lives (A.B) and the function (fn). +export function splitActor(actor: string): [string, string] { + const i = actor.lastIndexOf("."); + return i < 0 ? ["", actor] : [actor.slice(0, i), actor.slice(i + 1)]; +} + +// Long names break at camelCase and separator boundaries, so a label grows taller, not wider. +export function wrap(name: string, max = 16): string[] { + const lines: string[] = []; + for (const token of name.split(/(?=[A-Z])|(?<=[._-])/)) { + const last = lines.length - 1; + if (last >= 0 && (lines[last] ?? "").length + token.length <= max) lines[last] += token; + else lines.push(token); + } + return lines; +} + +export const SIZE = { event: 12.5, entry: 12, group: 13, label: 11 } as const; +const textWidth = (lines: string[], size: number) => + Math.max(0, ...lines.map((l) => l.length)) * size * 0.61; + +export const LINE = 14; +// Gap between handlers on an end card. +export const END_GAP = 4; +const PAD = 8; + +type Point = { x: number; y: number }; +type Box = { x: number; y: number; width: number; height: number }; + +export type LaidNode = Box & + ( + | { kind: "event"; id: string; event: GraphEvent } + | { kind: "entry"; id: string; label: string } + | { kind: "end"; id: string; from: string; terms: GraphTerm[] } + ); + +export type LaidEdge = { + id: string; + from: string; + to: string; + points: Point[]; + label: (Point & { lines: string[]; width: number; height: number }) | null; +} & ( + | { kind: "core" | "conn"; transition: Transition } + | { kind: "entry"; routes: string[] } + | { kind: "end" } +); + +export type Layout = { + width: number; + height: number; + groups: (Box & { id: string; label: string })[]; + nodes: LaidNode[]; + edges: LaidEdge[]; +}; + +type Spec = (LaidEdge extends infer E + ? E extends LaidEdge + ? Omit<E, "points" | "label"> + : never + : never) & { + lines: string[]; +}; + +const elk = new ELK(); + +// Left to right, so each step of a chain is a column. +export async function layoutGraph(sel: Selected): Promise<Layout> { + const base = { + "elk.algorithm": "layered", + "elk.direction": "RIGHT", + "elk.edgeRouting": "ORTHOGONAL", + "elk.hierarchyHandling": "INCLUDE_CHILDREN", + "elk.layered.spacing.nodeNodeBetweenLayers": "12", + "elk.layered.spacing.edgeNodeBetweenLayers": "6", + "elk.spacing.nodeNode": "8", + "elk.spacing.edgeNode": "8", + "elk.spacing.edgeEdge": "4", + "elk.spacing.edgeLabel": "3", + // Labels sit above their arrow, so a long name adds height instead of stretching the arrow. + "elk.edgeLabels.inline": "false", + "elk.layered.edgeLabels.sideSelection": "ALWAYS_UP", + "elk.layered.mergeEdges": "false", + "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX", + // Pulls nodes along their layer to shorten long arrows; about 3% narrower at no cost. + "elk.layered.compaction.postCompaction.strategy": "EDGE_LENGTH", + }; + const meta = new Map<string, LaidNode>(); + const groups = new Map<string, ElkNode>(); + const parent = new Map<string, string>(); + const root: ElkNode = { id: "root", layoutOptions: base, children: [], edges: [] }; + const containers = new Map<string, ElkNode>([["root", root]]); + + const place = (node: LaidNode, entity?: string) => { + meta.set(node.id, node); + // One port in, one port out: arrows into a box meet at a single arrowhead, and arrows out leave as a trunk. + const port = (side: string, dir: string) => ({ + id: `${node.id}:${dir}`, + width: 0, + height: 0, + layoutOptions: { "elk.port.side": side }, + }); + const elkNode: ElkNode = { + id: node.id, + width: node.width, + height: node.height, + layoutOptions: { "elk.portConstraints": "FIXED_SIDE" }, + ports: [port("WEST", "in"), port("EAST", "out")], + }; + if (!entity) { + root.children?.push(elkNode); + return; + } + const gid = `grp:${entity}`; + let g = groups.get(gid); + if (!g) { + g = { + id: gid, + layoutOptions: { + ...base, + "elk.padding": "[top=32,left=10,bottom=10,right=10]", + // Wide enough for the block's title. + "elk.nodeSize.constraints": "MINIMUM_SIZE", + "elk.nodeSize.minimum": `(${Math.ceil(textWidth([entity], SIZE.group) + 24)},0)`, + }, + children: [], + edges: [], + }; + groups.set(gid, g); + containers.set(gid, g); + root.children?.push(g); + } + g.children?.push(elkNode); + parent.set(node.id, gid); + }; + + const box = { x: 0, y: 0 }; + for (const event of sel.events) { + const width = textWidth([verbOf(event.id)], SIZE.event) + 2 * PAD + 6; + place({ ...box, kind: "event", id: event.id, event, width, height: 28 }, entityOf(event.id)); + } + + const specs: Spec[] = []; + for (const event of sel.events) { + const byKind = new Map<string, string[]>(); + for (const x of event.entry) byKind.set(x.kind, [...(byKind.get(x.kind) ?? []), x.label]); + for (const [kind, routes] of byKind) { + const id = triggerId(kind); + if (!meta.has(id)) { + place({ + ...box, + kind: "entry", + id, + label: kind, + width: textWidth([kind], SIZE.entry) + 2 * PAD + 8, + height: 28, + }); + } + // A connector loop's root is a function, the same for every event it starts; only routes are worth a label. + // Routes are "METHOD /path"; the method alone keeps the label short, the path is in the details. + const methods = new Set( + routes.filter((r) => r.includes(" /")).map((r) => r.split(" ")[0] ?? r), + ); + const lines = methods.size ? [[...methods].join(" · ")] : []; + specs.push({ id: `${id}→${event.id}`, kind: "entry", from: id, to: event.id, routes, lines }); + } + } + for (const t of sel.edges) { + specs.push({ + id: `${t.from}→${t.to}|${t.actor}`, + kind: t.kind, + from: t.from, + to: t.to, + transition: t, + lines: t.multi.flatMap((a) => wrap(splitActor(a.actor)[1])), + }); + } + const termsByEvent = new Map<string, GraphTerm[]>(); + for (const t of sel.terms) termsByEvent.set(t.from, [...(termsByEvent.get(t.from) ?? []), t]); + for (const [from, terms] of termsByEvent) { + if (!meta.has(from)) continue; + const id = endId(from); + const lines = terms.map(endLines); + const width = textWidth(lines.flat(), SIZE.label) + 2 * PAD; + const height = lines.flat().length * LINE + terms.length * END_GAP + 4; + place({ ...box, kind: "end", id, from, terms, width, height }, entityOf(from)); + specs.push({ id: `${from}⊣`, kind: "end", from, to: id, lines: [] }); + } + + const unit = (id: string) => parent.get(id) ?? "root"; + const labelBox = (lines: string[]) => ({ + width: textWidth(lines, SIZE.label) + 6, + height: lines.length * LINE + 2, + }); + specs.forEach((s, i) => { + const a = unit(s.from); + const edge: ElkExtendedEdge = { + id: `e${i}`, + sources: [`${s.from}:out`], + targets: [`${s.to}:in`], + // ELK ignores a label whose text is empty, so it carries the real lines. + labels: s.lines.length + ? [{ id: `l${i}`, text: s.lines.join("\n"), ...labelBox(s.lines) }] + : [], + }; + containers.get(a === unit(s.to) ? a : "root")?.edges?.push(edge); + }); + + const out = await elk.layout(root); + const absolute = new Map<string, Box>(); + const routed = new Map<string, ElkExtendedEdge>(); + const walk = (n: ElkNode, ox: number, oy: number) => { + for (const e of n.edges ?? []) { + for (const s of e.sections ?? []) { + s.startPoint = { x: s.startPoint.x + ox, y: s.startPoint.y + oy }; + s.endPoint = { x: s.endPoint.x + ox, y: s.endPoint.y + oy }; + s.bendPoints = (s.bendPoints ?? []).map((p) => ({ x: p.x + ox, y: p.y + oy })); + } + for (const l of e.labels ?? []) { + l.x = (l.x ?? 0) + ox; + l.y = (l.y ?? 0) + oy; + } + routed.set(e.id, e); + } + for (const c of n.children ?? []) { + const x = (c.x ?? 0) + ox; + const y = (c.y ?? 0) + oy; + absolute.set(c.id, { x, y, width: c.width ?? 0, height: c.height ?? 0 }); + walk(c, x, y); + } + }; + walk(out, 0, 0); + + const nodes = [...meta.values()].map((n) => ({ ...n, ...absolute.get(n.id) }) as LaidNode); + const edges = specs.map((s, i) => { + const { lines, ...rest } = s; + const e = routed.get(`e${i}`); + const sec = e?.sections?.[0]; + const points = sec ? [sec.startPoint, ...(sec.bendPoints ?? []), sec.endPoint] : []; + const l = e?.labels?.[0]; + const at = { x: (l?.x ?? 0) + (l?.width ?? 0) / 2, y: (l?.y ?? 0) + (l?.height ?? 0) / 2 }; + return { + ...rest, + points, + label: lines.length ? { ...at, ...labelBox(lines), lines } : null, + } as LaidEdge; + }); + + return { + width: out.width ?? 0, + height: out.height ?? 0, + groups: [...groups.keys()].map((id) => ({ + id, + label: id.slice(4), + ...(absolute.get(id) as Box), + })), + nodes, + edges, + }; +} + +export const endLines = (t: GraphTerm) => + wrap(splitActor(t.actor)[1]).map((l, i) => `${i ? " " : "⊣ "}${l}`); + +type Lit = { nodes: Set<string>; edges: Set<string> }; + +// Everything on a path into `id` ("up") or out of it ("down"), with the arrows between. +function reach(layout: Layout, id: string, dir: "up" | "down", lit: Lit) { + lit.nodes.add(id); + for (const queue = [id]; queue.length; ) { + const at = queue.shift(); + for (const e of layout.edges) { + const [near, far] = dir === "up" ? [e.to, e.from] : [e.from, e.to]; + if (near !== at) continue; + lit.edges.add(e.id); + if (!lit.nodes.has(far)) queue.push(lit.nodes.add(far) && far); + } + } + return lit; +} + +// What stays lit when a node is picked: every path through it, from its triggers to its end steps. +export function neighbourhood(layout: Layout, nodeId: string) { + return reach( + layout, + nodeId, + "down", + reach(layout, nodeId, "up", { nodes: new Set(), edges: new Set() }), + ); +} + +// A handler or arrow lights the paths into where it starts, itself, and the paths out of where it lands. +export function pathsThrough(layout: Layout, from: string, to: string, edgeId?: string) { + const lit = reach(layout, from, "up", { nodes: new Set(), edges: new Set() }); + if (edgeId) lit.edges.add(edgeId); + return reach(layout, to, "down", lit); +} diff --git a/web/src/features/core/events/queries.ts b/web/src/features/core/events/queries.ts index cd9cd7410..b73be244e 100644 --- a/web/src/features/core/events/queries.ts +++ b/web/src/features/core/events/queries.ts @@ -19,7 +19,14 @@ import type { EventDeliveryStatus } from "@/generated/core/zod.gen"; import { skipToken, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { getDelivery, getUserName, listDeliveries, listSubscriptions, retryDelivery } from "./api"; +import { + getDelivery, + getEventGraph, + getUserName, + listDeliveries, + listSubscriptions, + retryDelivery, +} from "./api"; export const eventKeys = { all: ["events"] as const, @@ -27,6 +34,7 @@ export const eventKeys = { [...eventKeys.all, "deliveries", status ?? "ALL"] as const, delivery: (id: string) => [...eventKeys.all, "delivery", id] as const, subscriptions: () => [...eventKeys.all, "subscriptions"] as const, + graph: () => [...eventKeys.all, "graph"] as const, userName: (id: string) => [...eventKeys.all, "user-name", id] as const, }; @@ -70,3 +78,11 @@ export function useRetryDelivery() { onSuccess: () => client.invalidateQueries({ queryKey: eventKeys.all }), }); } + +export function useEventGraph() { + return useQuery({ + queryKey: eventKeys.graph(), + queryFn: getEventGraph, + staleTime: Number.POSITIVE_INFINITY, + }); +} diff --git a/web/src/features/core/events/schemas.ts b/web/src/features/core/events/schemas.ts index fe9c04288..875aa9d38 100644 --- a/web/src/features/core/events/schemas.ts +++ b/web/src/features/core/events/schemas.ts @@ -59,3 +59,39 @@ export const deliveryDetailSchema = zGetEventsDeliveriesByIdResponse.extend({ export const subscriptionListSchema = zGetEventsSubscriptionsResponse.extend({ items: z.array(zSubscription.pick({ subscriber: true, event_type: true, loaded: true })), }); + +// Go marshals a nil slice as null. +const list = <T extends z.ZodType>(item: T) => + z + .array(item) + .nullable() + .transform((xs) => xs ?? []); + +const graphEntrySchema = z.object({ kind: z.string(), label: z.string() }); + +export const eventGraphSchema = z.object({ + events: z.array(z.object({ id: z.string(), entry: list(graphEntrySchema), subs: z.number() })), + edges: z.array( + z.object({ + from: z.string(), + to: z.string(), + kind: z.enum(["core", "conn"]), + conn: z.string(), + actor: z.string(), + sites: list(z.string()), + chain: list(z.string()), + cond: z.boolean(), + order: z.boolean().optional(), + }), + ), + terms: z.array( + z.object({ + from: z.string(), + conn: z.string(), + actor: z.string(), + site: z.string(), + effects: list(z.string()), + cond: z.boolean(), + }), + ), +}); diff --git a/web/src/features/core/events/types.ts b/web/src/features/core/events/types.ts index 674e43e69..aa7bd4d57 100644 --- a/web/src/features/core/events/types.ts +++ b/web/src/features/core/events/types.ts @@ -19,6 +19,7 @@ import type { z } from "zod"; import type { deliveryDetailSchema, deliverySchema, + eventGraphSchema, historyEntrySchema, subscriptionListSchema, } from "./schemas"; @@ -30,3 +31,8 @@ export type Subscription = z.infer<typeof subscriptionListSchema>["items"][numbe // The list view a tab shows. "waiting" is every delivery not finished yet. export type DeliveryView = "all" | "waiting" | "failed"; + +export type EventGraph = z.infer<typeof eventGraphSchema>; +export type GraphEvent = EventGraph["events"][number]; +export type GraphEdge = EventGraph["edges"][number]; +export type GraphTerm = EventGraph["terms"][number]; diff --git a/web/src/mocks/handlers/events.ts b/web/src/mocks/handlers/events.ts index e53b479ed..6f2ce1ec7 100644 --- a/web/src/mocks/handlers/events.ts +++ b/web/src/mocks/handlers/events.ts @@ -19,6 +19,7 @@ import { deliveryFixtures, subscriptionFixtures, } from "@/features/core/events/__fixtures__/deliveries"; +import graphFixture from "@/features/core/events/__fixtures__/graph.json"; import type { DeliveryDetail } from "@/features/core/events/types"; import { http, HttpResponse } from "msw"; @@ -26,6 +27,8 @@ import { http, HttpResponse } from "msw"; const deliveries: DeliveryDetail[] = structuredClone(deliveryFixtures); export const eventsHandlers = [ + http.get("/api/v1/events/graph", () => HttpResponse.json(graphFixture)), + http.get("/api/v1/events/deliveries", ({ request }) => { const status = new URL(request.url).searchParams.get("status"); const items = deliveries
