mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-05 23:01:36 +09:00
## Summary Introduce a document graph architecture for Assets resources so structured documents can reference one another while keeping full document payloads on CDN-backed storage. The content database will retain the searchable index and dependency graph. At runtime, the server will select a root document, determine its complete dependency set before performing I/O, fetch each unique document concurrently, and assemble the final result server-side. ## Implementation todos ### Document graph foundation - [x] Add normalized internal reference contracts for whole documents, JSON paths, Markdown body, and Markdown frontmatter. - [x] Add an immutable graph abstraction with deterministic ordering, dependency traversal, revision validation, and cycle detection. - [x] Add a storage-independent resolver with dependency closure, bounded parallel loading, shared-content deduplication, representation selection, assembly hooks, cancellation, and structured errors. - [x] Add focused unit coverage for the isolated document-graph abstraction. - [x] Define and validate the external remote-document reference syntax. - [x] Add a pure graph compiler that resolves canonical document URLs into IDs and revisions and validates missing, duplicate, and cyclic dependencies. ### Build-time graph - [x] Add a storage-independent source-catalog compiler for bounded parallel reference discovery and deterministic graph compilation. - [x] Add a versioned deterministic document graph artifact with canonical serialization and integrity verification. - [x] Discover and normalize statically declared references while Assets resources are processed. - [x] Resolve document identities and revisions and report missing, stale, or cyclic dependencies with document context. - [x] Persist document nodes and dependency edges alongside searchable resource metadata. - [x] Include persisted graph data in artifact integrity and size validation. ### Document representations - [x] Add a standalone JSON document adapter for exact reference markers, compiler occurrences, JSON path selection, and immutable assembly. - [x] Add a standalone Markdown document adapter for bounded decoding, frontmatter references, immutable assembly, and source, body, and frontmatter selection. - [x] Parse fetched JSON and Markdown documents through format-specific adapters. - [x] Select complete documents, JSON fragments, Markdown body, and Markdown frontmatter through the shared reference model. - [x] Assemble nested and shared references into the final server-side value. ### Runtime resolution - [x] Enforce reachable-document, per-document byte, and aggregate-byte limits before parsing and assembly. - [x] Add a revision-keyed bounded source-cache wrapper with replayable bytes, stale-entry fallback, and in-flight deduplication. - [x] Add a storage-neutral loaded-source contract that rejects revision mismatches before parsing. - [x] Resolve graph-backed property paths before filtering, sorting, pagination, and projection; skip graph loading for unrelated queries. - [x] Add an injected HTTP/CDN document loader with revision metadata validation. - [x] Apply runtime payload limits, bounded concurrency, caching, and structured failure mapping. - [x] Ensure shared documents are fetched and parsed once per resolution. ### Product integration - [x] Integrate equivalent behavior in local preview, SSR, SSG, and published runtime paths. - [x] Preserve existing embedded Assets resource behavior without requiring migration. - [x] Add observability for graph loading, document fetching, caching, and resolution failures. - [x] Document the public reference and resolution behavior. ### Review hardening - [x] Enforce graph, artifact, cache, and published-storage identity consistency. - [x] Compile only graph sources reachable from selected build entries. - [x] Resolve graph-backed fields before query evaluation and avoid unnecessary graph loading. - [x] Consolidate duplicated graph schemas, utilities, and document content-type detection. - [x] Correct runtime documentation and use structural evaluation validation. ### Verification - [x] Keep a deterministic high-impact agent evaluation for Markdown-to-JSON references across the dynamic blog overview and article routes. - [x] Add a separate discoverability evaluation that must learn the reference workflow from MCP guidance without prompt-supplied syntax, queries, bindings, or call order. - [ ] Re-run the complete local agent evaluation suite after the discoverability fixture change and compare every fixture with its accepted baseline. - [x] Add integration coverage for CDN-backed hydration, parallel fetching, caching, and shared dependencies. - [x] Add integration coverage for missing references, cycles, revision changes, limits, and cancellation. - [x] Verify equivalent behavior across preview, SSR, SSG, and published deployments. - [x] Verify that existing embedded Assets resources retain their current behavior. ## Intended outcome - Storage-backed documents do not require their complete payloads to be embedded in the content database. - The server knows the complete statically discoverable dependency set before fetching document content. - Shared dependencies are fetched once per resolution and independent resources can be fetched in parallel. - JSON fragments and Markdown body/frontmatter representations use the same document-resolution system. - Reference and payload revisions cannot be mixed silently. - Existing Assets resources continue to work without migration. ## Verification results - `@webstudio-is/content-engine`: 37 files / 244 tests passed; typecheck passed. - `@webstudio-is/asset-uploader`: 22 files / 182 tests passed; typecheck passed. - CLI: 57 files / 925 tests passed, including generated SSR and SSG build/prerender coverage; typecheck passed. - Repository-wide `pnpm oxfmt --check` passed across 2,757 files. - Package-boundary validation passed. - Previous `pnpm evaluations` run: all 4 original high-impact fixtures passed. The complete 5-fixture rerun is pending explicit approval after adding the discoverability fixture.
226 lines
6.8 KiB
TypeScript
226 lines
6.8 KiB
TypeScript
import { compareStrings } from "../canonical-json";
|
|
import { createDocumentReference, type DocumentReference } from "./reference";
|
|
import {
|
|
documentGraphEdgeSchema,
|
|
documentGraphNodeSchema,
|
|
} from "./graph-schema";
|
|
import { getDocumentGraphEdgesBySourceId } from "./graph-utils";
|
|
|
|
export type DocumentGraphNode = Readonly<{
|
|
id: string;
|
|
revision: string;
|
|
contentRef: string;
|
|
format?: "json" | "markdown";
|
|
}>;
|
|
|
|
export type DocumentGraphEdge = Readonly<{
|
|
sourceId: string;
|
|
referenceId: string;
|
|
reference: DocumentReference;
|
|
}>;
|
|
|
|
export type DocumentGraph = Readonly<{
|
|
nodes: readonly DocumentGraphNode[];
|
|
edges: readonly DocumentGraphEdge[];
|
|
}>;
|
|
|
|
export type DocumentGraphErrorCode =
|
|
| "DUPLICATE_NODE"
|
|
| "CONTENT_IDENTITY_CONFLICT"
|
|
| "DUPLICATE_REFERENCE"
|
|
| "SOURCE_NOT_FOUND"
|
|
| "TARGET_NOT_FOUND"
|
|
| "TARGET_REVISION_MISMATCH"
|
|
| "ROOT_NOT_FOUND"
|
|
| "CYCLE";
|
|
|
|
export class DocumentGraphError extends Error {
|
|
readonly code: DocumentGraphErrorCode;
|
|
readonly documentIds: readonly string[];
|
|
|
|
constructor({
|
|
code,
|
|
message,
|
|
documentIds = [],
|
|
}: {
|
|
code: DocumentGraphErrorCode;
|
|
message: string;
|
|
documentIds?: readonly string[];
|
|
}) {
|
|
super(message);
|
|
this.name = "DocumentGraphError";
|
|
this.code = code;
|
|
this.documentIds = Object.freeze([...documentIds]);
|
|
}
|
|
}
|
|
|
|
const compareEdges = (left: DocumentGraphEdge, right: DocumentGraphEdge) =>
|
|
compareStrings(left.sourceId, right.sourceId) ||
|
|
compareStrings(left.referenceId, right.referenceId);
|
|
|
|
export const createDocumentGraph = ({
|
|
nodes: nodeInputs,
|
|
edges: edgeInputs,
|
|
}: {
|
|
nodes: readonly unknown[];
|
|
edges: readonly unknown[];
|
|
}): DocumentGraph => {
|
|
const nodes = nodeInputs
|
|
.map((input) => Object.freeze(documentGraphNodeSchema.parse(input)))
|
|
.sort((left, right) => compareStrings(left.id, right.id));
|
|
const nodesById = new Map<string, DocumentGraphNode>();
|
|
const nodesByContentRef = new Map<string, DocumentGraphNode>();
|
|
for (const node of nodes) {
|
|
if (nodesById.has(node.id)) {
|
|
throw new DocumentGraphError({
|
|
code: "DUPLICATE_NODE",
|
|
message: `Document graph contains duplicate node ${node.id}`,
|
|
documentIds: [node.id],
|
|
});
|
|
}
|
|
nodesById.set(node.id, node);
|
|
const previousContent = nodesByContentRef.get(node.contentRef);
|
|
if (
|
|
previousContent !== undefined &&
|
|
(previousContent.revision !== node.revision ||
|
|
previousContent.format !== node.format)
|
|
) {
|
|
throw new DocumentGraphError({
|
|
code: "CONTENT_IDENTITY_CONFLICT",
|
|
message: `Document graph content reference ${node.contentRef} has conflicting identities`,
|
|
documentIds: [previousContent.id, node.id],
|
|
});
|
|
}
|
|
nodesByContentRef.set(node.contentRef, node);
|
|
}
|
|
|
|
const edges = edgeInputs
|
|
.map((input) => {
|
|
const edge = documentGraphEdgeSchema.parse(input);
|
|
return Object.freeze({
|
|
...edge,
|
|
reference: createDocumentReference(edge.reference),
|
|
});
|
|
})
|
|
.sort(compareEdges);
|
|
const referenceKeys = new Set<string>();
|
|
for (const edge of edges) {
|
|
const source = nodesById.get(edge.sourceId);
|
|
if (source === undefined) {
|
|
throw new DocumentGraphError({
|
|
code: "SOURCE_NOT_FOUND",
|
|
message: `Document graph source ${edge.sourceId} does not exist`,
|
|
documentIds: [edge.sourceId],
|
|
});
|
|
}
|
|
const target = nodesById.get(edge.reference.documentId);
|
|
if (target === undefined) {
|
|
throw new DocumentGraphError({
|
|
code: "TARGET_NOT_FOUND",
|
|
message: `Document graph target ${edge.reference.documentId} does not exist`,
|
|
documentIds: [edge.sourceId, edge.reference.documentId],
|
|
});
|
|
}
|
|
if (target.revision !== edge.reference.revision) {
|
|
throw new DocumentGraphError({
|
|
code: "TARGET_REVISION_MISMATCH",
|
|
message: `Document graph target ${target.id} revision does not match its reference`,
|
|
documentIds: [edge.sourceId, target.id],
|
|
});
|
|
}
|
|
const referenceKey = `${edge.sourceId}\0${edge.referenceId}`;
|
|
if (referenceKeys.has(referenceKey)) {
|
|
throw new DocumentGraphError({
|
|
code: "DUPLICATE_REFERENCE",
|
|
message: `Document ${edge.sourceId} contains duplicate reference ID ${edge.referenceId}`,
|
|
documentIds: [edge.sourceId],
|
|
});
|
|
}
|
|
referenceKeys.add(referenceKey);
|
|
}
|
|
|
|
return Object.freeze({
|
|
nodes: Object.freeze(nodes),
|
|
edges: Object.freeze(edges),
|
|
});
|
|
};
|
|
|
|
const getNodesById = (graph: DocumentGraph) =>
|
|
new Map(graph.nodes.map((node) => [node.id, node]));
|
|
|
|
export const getDocumentGraphDependencies = (
|
|
graph: DocumentGraph,
|
|
documentId: string
|
|
): readonly DocumentGraphNode[] => {
|
|
const nodesById = getNodesById(graph);
|
|
if (nodesById.has(documentId) === false) {
|
|
throw new DocumentGraphError({
|
|
code: "ROOT_NOT_FOUND",
|
|
message: `Document graph node ${documentId} does not exist`,
|
|
documentIds: [documentId],
|
|
});
|
|
}
|
|
const dependencies = new Map<string, DocumentGraphNode>();
|
|
for (const edge of graph.edges) {
|
|
if (edge.sourceId === documentId) {
|
|
const target = nodesById.get(edge.reference.documentId);
|
|
if (target !== undefined) {
|
|
dependencies.set(target.id, target);
|
|
}
|
|
}
|
|
}
|
|
return Object.freeze([...dependencies.values()]);
|
|
};
|
|
|
|
/** Returns each reachable node once, with dependencies before their consumers. */
|
|
export const getDocumentGraphClosure = ({
|
|
graph,
|
|
rootIds,
|
|
}: {
|
|
graph: DocumentGraph;
|
|
rootIds: readonly string[];
|
|
}): readonly DocumentGraphNode[] => {
|
|
const nodesById = getNodesById(graph);
|
|
const edgesBySourceId = getDocumentGraphEdgesBySourceId(graph.edges);
|
|
const state = new Map<string, "visiting" | "visited">();
|
|
const stack: string[] = [];
|
|
const ordered: DocumentGraphNode[] = [];
|
|
|
|
const visit = (documentId: string) => {
|
|
const node = nodesById.get(documentId);
|
|
if (node === undefined) {
|
|
throw new DocumentGraphError({
|
|
code: "ROOT_NOT_FOUND",
|
|
message: `Document graph root ${documentId} does not exist`,
|
|
documentIds: [documentId],
|
|
});
|
|
}
|
|
const nodeState = state.get(documentId);
|
|
if (nodeState === "visited") {
|
|
return;
|
|
}
|
|
if (nodeState === "visiting") {
|
|
const cycleStart = stack.indexOf(documentId);
|
|
const cycle = [...stack.slice(cycleStart), documentId];
|
|
throw new DocumentGraphError({
|
|
code: "CYCLE",
|
|
message: `Document graph contains a cycle: ${cycle.join(" -> ")}`,
|
|
documentIds: cycle,
|
|
});
|
|
}
|
|
state.set(documentId, "visiting");
|
|
stack.push(documentId);
|
|
for (const edge of edgesBySourceId.get(documentId) ?? []) {
|
|
visit(edge.reference.documentId);
|
|
}
|
|
stack.pop();
|
|
state.set(documentId, "visited");
|
|
ordered.push(node);
|
|
};
|
|
|
|
for (const rootId of [...new Set(rootIds)].sort(compareStrings)) {
|
|
visit(rootId);
|
|
}
|
|
return Object.freeze(ordered);
|
|
};
|