feat: implement call graph construction methods (fromCallEvents, updateFromEvent, addCall, addDependency, updateStatus, updateCall, removeCall)
This commit is contained in:
@@ -1,13 +1,16 @@
|
||||
import { DirectedGraph } from "graphology";
|
||||
import type { TSchema, Static } from "@alkdev/typebox";
|
||||
import { Value } from "@alkdev/typebox/value";
|
||||
import { willCreateCycle, topologicalSort, hasCycle } from "graphology-dag";
|
||||
import {
|
||||
DuplicateNodeError,
|
||||
DuplicateEdgeError,
|
||||
NodeNotFoundError,
|
||||
CycleError,
|
||||
InvalidInputError,
|
||||
InvalidTransitionError,
|
||||
} from "../error/index.js";
|
||||
import type { CallStatus, AnyValidationError } from "../error/index.js";
|
||||
import type { CallStatus, AnyValidationError, ValidationError } from "../error/index.js";
|
||||
import {
|
||||
findCycles,
|
||||
reachableFrom as reachableFromFn,
|
||||
@@ -16,8 +19,12 @@ import { validate as _validate } from "./validation.js";
|
||||
import {
|
||||
OperationNodeAttrs as OperationNodeAttrsSchema,
|
||||
OperationEdgeAttrs as OperationEdgeAttrsSchema,
|
||||
OperationGraphSerialized,
|
||||
CallGraphSerialized,
|
||||
CallNodeAttrs as CallNodeAttrsSchema,
|
||||
CallEdgeAttrs as CallEdgeAttrsSchema,
|
||||
} from "../schema/index.js";
|
||||
import type { OperationNodeAttrs } from "../schema/index.js";
|
||||
import type { OperationNodeAttrs, FlowGraphSerialized, CallNodeAttrs } from "../schema/index.js";
|
||||
import { typeCompat, type TypeCompatResult } from "../analysis/type-compat.js";
|
||||
|
||||
export interface FlowGraphOptions {
|
||||
@@ -37,8 +44,55 @@ export interface OperationSpec {
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface CallRequestedEvent {
|
||||
type: "call.requested";
|
||||
requestId: string;
|
||||
operationId: string;
|
||||
input: unknown;
|
||||
timestamp: string;
|
||||
parentRequestId?: string;
|
||||
identity?: { id: string; scopes: string[]; resources?: Record<string, string[]> };
|
||||
startedAt?: string;
|
||||
}
|
||||
|
||||
export interface CallRespondedEvent {
|
||||
type: "call.responded";
|
||||
requestId: string;
|
||||
output: unknown;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallErrorEvent {
|
||||
type: "call.error";
|
||||
requestId: string;
|
||||
error: { code: string; message: string; details?: unknown };
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallAbortedEvent {
|
||||
type: "call.aborted";
|
||||
requestId: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallCompletedEvent {
|
||||
type: "call.completed";
|
||||
requestId: string;
|
||||
output?: unknown;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export type CallEventMapValue =
|
||||
| CallRequestedEvent
|
||||
| CallRespondedEvent
|
||||
| CallErrorEvent
|
||||
| CallAbortedEvent
|
||||
| CallCompletedEvent;
|
||||
|
||||
type OperationGraph = FlowGraph<typeof OperationNodeAttrsSchema, typeof OperationEdgeAttrsSchema>;
|
||||
|
||||
type CallGraph = FlowGraph<typeof CallNodeAttrsSchema, typeof CallEdgeAttrsSchema>;
|
||||
|
||||
type TypedEdgeAttrs = {
|
||||
edgeType: "typed";
|
||||
compatible: boolean;
|
||||
@@ -48,6 +102,14 @@ type TypedEdgeAttrs = {
|
||||
|
||||
type Attrs = Record<string, unknown>;
|
||||
|
||||
const VALID_TRANSITIONS: Record<CallStatus, CallStatus[]> = {
|
||||
pending: ["running", "aborted"],
|
||||
running: ["completed", "failed", "aborted"],
|
||||
completed: [],
|
||||
failed: [],
|
||||
aborted: [],
|
||||
};
|
||||
|
||||
export class FlowGraph<
|
||||
NodeAttrs extends TSchema = TSchema,
|
||||
EdgeAttrs extends TSchema = TSchema,
|
||||
@@ -314,6 +376,145 @@ export class FlowGraph<
|
||||
return chain;
|
||||
}
|
||||
|
||||
updateFromEvent(event: CallEventMapValue): void {
|
||||
switch (event.type) {
|
||||
case "call.requested": {
|
||||
const attrs: CallNodeAttrs = {
|
||||
requestId: event.requestId,
|
||||
operationId: event.operationId,
|
||||
status: "pending",
|
||||
input: event.input,
|
||||
...(event.parentRequestId !== undefined ? { parentRequestId: event.parentRequestId } : {}),
|
||||
...(event.identity !== undefined ? { identity: event.identity } : {}),
|
||||
...(event.startedAt !== undefined ? { startedAt: event.startedAt } : {}),
|
||||
};
|
||||
this.addCall(attrs);
|
||||
break;
|
||||
}
|
||||
case "call.responded": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "completed",
|
||||
output: event.output,
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.error": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "failed",
|
||||
error: event.error,
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.aborted": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "aborted",
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.completed": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed") {
|
||||
if (!current.completedAt) {
|
||||
this._graph.mergeNodeAttributes(event.requestId, { completedAt: event.timestamp } as Attrs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "completed",
|
||||
...(event.output !== undefined ? { output: event.output } : {}),
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addCall(attrs: CallNodeAttrs): void {
|
||||
if (this._graph.hasNode(attrs.requestId)) return;
|
||||
this._graph.addNode(attrs.requestId, attrs as Attrs);
|
||||
if (attrs.parentRequestId !== undefined) {
|
||||
if (this._graph.hasNode(attrs.parentRequestId)) {
|
||||
if (willCreateCycle(this._graph, attrs.parentRequestId, attrs.requestId)) {
|
||||
this._graph.dropNode(attrs.requestId);
|
||||
const path = this._findPath(attrs.requestId, attrs.parentRequestId);
|
||||
const cycle = [attrs.parentRequestId, ...path, attrs.parentRequestId];
|
||||
throw new CycleError([cycle]);
|
||||
}
|
||||
const edgeKey = this._edgeKey(attrs.parentRequestId, attrs.requestId);
|
||||
this._graph.addEdgeWithKey(edgeKey, attrs.parentRequestId, attrs.requestId, { edgeType: "triggered" } as Attrs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addDependency(source: string, target: string): void {
|
||||
if (!this._graph.hasNode(source)) {
|
||||
throw new NodeNotFoundError(source);
|
||||
}
|
||||
if (!this._graph.hasNode(target)) {
|
||||
throw new NodeNotFoundError(target);
|
||||
}
|
||||
const edgeKey = `${source}->${target}:depends_on`;
|
||||
if (this._graph.hasEdge(edgeKey)) return;
|
||||
if (willCreateCycle(this._graph, source, target)) {
|
||||
const path = this._findPath(target, source);
|
||||
const cycle = [source, ...path, source];
|
||||
throw new CycleError([cycle]);
|
||||
}
|
||||
this._graph.addEdgeWithKey(edgeKey, source, target, { edgeType: "depends_on" } as Attrs);
|
||||
}
|
||||
|
||||
updateStatus(requestId: string, status: CallStatus, extra?: Partial<CallNodeAttrs>): void {
|
||||
if (!this._graph.hasNode(requestId)) {
|
||||
throw new NodeNotFoundError(requestId);
|
||||
}
|
||||
const current = this._graph.getNodeAttributes(requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === status) return;
|
||||
const allowed = VALID_TRANSITIONS[currentStatus];
|
||||
if (!allowed || !allowed.includes(status)) {
|
||||
throw new InvalidTransitionError(requestId, currentStatus, status);
|
||||
}
|
||||
const update: Record<string, unknown> = { status };
|
||||
if (extra) {
|
||||
for (const [key, value] of Object.entries(extra)) {
|
||||
if (value !== undefined) {
|
||||
update[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._graph.mergeNodeAttributes(requestId, update as Attrs);
|
||||
}
|
||||
|
||||
updateCall(requestId: string, attrs: Partial<CallNodeAttrs>): void {
|
||||
if (!this._graph.hasNode(requestId)) {
|
||||
throw new NodeNotFoundError(requestId);
|
||||
}
|
||||
this._graph.mergeNodeAttributes(requestId, attrs as Attrs);
|
||||
}
|
||||
|
||||
removeCall(requestId: string): void {
|
||||
if (!this._graph.hasNode(requestId)) return;
|
||||
this._graph.dropNode(requestId);
|
||||
}
|
||||
|
||||
validate(schema: TSchema): AnyValidationError[] {
|
||||
return _validate(this, schema as NodeAttrs);
|
||||
}
|
||||
@@ -361,16 +562,72 @@ export class FlowGraph<
|
||||
return graph;
|
||||
}
|
||||
|
||||
static fromCallEvents(
|
||||
_events: unknown[],
|
||||
): FlowGraph<TSchema, TSchema> {
|
||||
throw new Error("not implemented");
|
||||
static fromCallEvents(events: CallEventMapValue[]): CallGraph {
|
||||
const graph = new FlowGraph<typeof CallNodeAttrsSchema, typeof CallEdgeAttrsSchema>();
|
||||
for (const event of events) {
|
||||
graph.updateFromEvent(event);
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
|
||||
export(): FlowGraphSerialized {
|
||||
return this._graph.export() as unknown as FlowGraphSerialized;
|
||||
}
|
||||
|
||||
toJSON(): FlowGraphSerialized {
|
||||
return this.export();
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return JSON.stringify(this.export());
|
||||
}
|
||||
|
||||
static fromJSON(
|
||||
_data: unknown,
|
||||
data: FlowGraphSerialized,
|
||||
): FlowGraph<TSchema, TSchema> {
|
||||
throw new Error("not implemented");
|
||||
const opCheck = Value.Check(OperationGraphSerialized, data);
|
||||
const callCheck = Value.Check(CallGraphSerialized, data);
|
||||
if (!opCheck && !callCheck) {
|
||||
const errors: ValidationError[] = [];
|
||||
const opIter = Value.Errors(OperationGraphSerialized, data as Record<string, unknown>);
|
||||
for (const err of opIter) {
|
||||
errors.push({
|
||||
type: "schema",
|
||||
nodeKey: "",
|
||||
field: err.path.replace(/^\//, "") || err.path,
|
||||
message: err.message,
|
||||
value: err.value,
|
||||
});
|
||||
}
|
||||
if (errors.length === 0) {
|
||||
const callIter = Value.Errors(CallGraphSerialized, data as Record<string, unknown>);
|
||||
for (const err of callIter) {
|
||||
errors.push({
|
||||
type: "schema",
|
||||
nodeKey: "",
|
||||
field: err.path.replace(/^\//, "") || err.path,
|
||||
message: err.message,
|
||||
value: err.value,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new InvalidInputError(errors);
|
||||
}
|
||||
|
||||
const fg = new FlowGraph<TSchema, TSchema>();
|
||||
for (const node of data.nodes) {
|
||||
fg._graph.addNode(node.key, node.attributes as Attrs);
|
||||
}
|
||||
for (const edge of data.edges) {
|
||||
fg._graph.addEdgeWithKey(edge.key, edge.source, edge.target, edge.attributes as Attrs);
|
||||
}
|
||||
|
||||
if (hasCycle(fg._graph)) {
|
||||
const cycles = findCycles(fg._graph);
|
||||
throw new CycleError(cycles);
|
||||
}
|
||||
|
||||
return fg;
|
||||
}
|
||||
|
||||
private _findPath(from: string, to: string): string[] {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec } from "./construction.js";
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec, type CallEventMapValue, type CallRequestedEvent, type CallRespondedEvent, type CallErrorEvent, type CallAbortedEvent, type CallCompletedEvent } from "./construction.js";
|
||||
export {
|
||||
topologicalOrder,
|
||||
hasCycles,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from "./error/index.js";
|
||||
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec } from "./graph/index.js";
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec, type CallEventMapValue, type CallRequestedEvent, type CallRespondedEvent, type CallErrorEvent, type CallAbortedEvent, type CallCompletedEvent } from "./graph/index.js";
|
||||
export {
|
||||
validateSchema,
|
||||
validateGraph,
|
||||
|
||||
Reference in New Issue
Block a user