mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-05 06:41:50 +09:00
## Problem Assets-backed Builder pages can take 6–7 seconds to become usable even when their Assets resources only request metadata. On the production-derived Blog project, a single Assets query measured 8,703 ms and an immediate repeat measured 8,110 ms. Four sibling Assets resources repeated the same authorization, development-build load/parse, compilation, canonical-asset preparation, runtime metadata load, and document work. ## Architecture The loader now treats remote resources holistically while preserving provider boundaries: - The client scheduler is resource-provider neutral. It versions logical requests, frees capacity when obsolete requests are replaced, ignores stale results, and aborts physical batches only when every member is obsolete. - Ordinary Assets requests in one server resource-loader call use a deferred Assets provider and execute as one repository batch. Independent HTTP, GraphQL, and other resources start immediately instead of waiting for Assets preparation. - Arbitrary remote responses are **not** coalesced or persistently cached. Their auth headers, cookies, upstream freshness, and `Vary` semantics remain isolated. - The Assets provider authorizes and creates its API context once per batch, then loads only `props`, `dataSources`, and `resources` from the development Build. - Queries covered by the saved Build compilation plan reuse that exact plan/artifact, preserving published byte limits, truncation, and pinned-revision behavior. Uncovered unpinned queries use a deterministic literal union and safely fall back to their existing individual path if shared preparation cannot preserve behavior. - Request-scoped document loading uses npm's byte-bounded `lru-cache` so sibling queries do not reread the same referenced author/content files. - Sibling dynamic queries with the same filter, sort, output, and content shape stitch into one document-graph resolution while keeping filter values, pagination windows, results, and failures independent. Aggregate document/byte-limit failures fall back to isolated execution. - Provider-neutral batching lives in the SDK runtime, and project asset-query preview orchestration lives in the shared project package so Builder and MCP paths can reuse the same behavior. - Cancellation flows from the client batch through the SDK/server/build/query path, with checkpoints between expensive phases. - Runtime asset metadata remains conservatively artifact-wide because URL/size filters, structured references, markdown hydration, materialized rows, and saved plans have different reachability rules. To make 1,000-asset artifacts safe, PostgREST `.in(...)` lookups are deduplicated and split into 100-ID chunks with bounded concurrency. ## Implementation checklist - [x] Trace the production Blog resource path and identify repeated work - [x] Copy the production Blog project into an ignored disposable local project - [x] Record production and local baselines - [x] Add provider-neutral client scheduling, stale-result protection, and cancellation - [x] Batch ordinary Assets queries without coupling or caching HTTP/GraphQL responses - [x] Load only Build fields required to create the saved content compilation plan - [x] Preserve saved-plan, truncation, fallback, diagnostics, and revision semantics - [x] Share Assets artifacts, runtime metadata, and revision-keyed document reads per request - [x] Stitch compatible query shapes into one graph resolution with isolated fallback - [x] Extract reusable SDK batching and project preview orchestration for MCP/runtime consumers - [x] Bound large runtime asset metadata lookups for the 1,000-asset project limit - [x] Add regression coverage and demonstrate new tests failing before their fixes - [x] Run focused and broad tests, type checks, lint, format, package-boundary, and diff checks - [x] Review documentation impact; no authoritative `docs/` content changes are required - [x] Regenerate and verify the affected asset-query runtime fixture; no production data is changed - [x] Address all actionable PR review comments - [x] Rerun the final parity-preserving implementation against the copied Blog project ## Measurements Production trace before the change: - Updates Assets query: 8,703 ms - Immediate identical repeat: 8,110 ms - Query artifact: 9,344 bytes / 7 documents - Saved source database: 42,086 bytes / 28 documents Copied-project local baseline: - Builder navigation until resource loading: 5,111 ms - Exact four-resource batches: 1,448 / 797 / 1,377 / 774 / 3,018 ms During implementation, before the final saved-plan parity tightening: - Exact four-resource batch: 174 ms first run, then 51–80 ms - Actual Builder resource-loader requests: 234–246 ms Final parity-preserving copied-project rerun: - Preflight: 10 ms - Exact four-resource batch: 435 ms cold, then 119 / 97 / 90 / 79 ms warm - Every response returned HTTP 200 with the same 16,884-byte payload The final cold batch is 70% faster than the best copied-project cold baseline, and the fastest warm batch is 90% faster than the best warm baseline. The production trace remains the authoritative production baseline; these before/after comparisons use the same disposable local project and captured request payload. ## Verification Passed: - Full package suites: Builder (212 files / 2,496 tests), asset-uploader (22 / 193), content-engine (40 / 274), project (7 / 84), SDK (29 / 508), and project-build (82 / 2,070) - Final focused regressions: Builder preview/API/resource integration (3 files / 42 tests), SDK resource loader (23 tests), and document-graph resolution (6 tests) - Builder, asset-uploader, content-engine, project, SDK, and project-build type checks - Fixture regeneration is deterministic; the generated vendor exactly matches the source runtime bundle - Fixture typecheck and production build - Changed-file Oxfmt, repository Oxlint, and package-boundary checks - `git diff --check` - `git diff --name-only HEAD --exit-code` New behavioral tests were demonstrated to fail before implementation and pass afterward, including Assets batch coordination, saved-plan wiring, truncation and pinned revisions, shared document reads, cancellation checkpoints, stale/replaced client requests, and large PostgREST ID filters. Agent evaluations were not run because they require separate explicit approval. ## Compatibility and remaining work The public resource result/error shape and on-demand diagnostics contract stay compatible. Generic HTTP/GraphQL caching semantics are unchanged. Compilation already in progress is not force-cancelled because safely interrupting shared compilation requires ownership/reference tracking; cancellation prevents later phases from starting. Closes #6003
331 lines
9.2 KiB
TypeScript
331 lines
9.2 KiB
TypeScript
import { atom, computed } from "nanostores";
|
|
import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";
|
|
import { isAssetsResourceRequest } from "@webstudio-is/sdk/runtime";
|
|
import { restResourcesLoader } from "./router-utils";
|
|
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
|
import { fetch } from "./fetch.client";
|
|
import { getResourceKey } from "./resource-utils";
|
|
import { type AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
|
|
import { separateResourceDiagnostics } from "./resource-diagnostics";
|
|
|
|
const MAX_PENDING_RESOURCES = 5;
|
|
|
|
type InFlightResourceBatch = {
|
|
controller: AbortController;
|
|
versions: Map<string, number>;
|
|
};
|
|
|
|
export { getResourceKey };
|
|
|
|
const queue = new Map<string, ResourceRequest>();
|
|
const pending = new Map<string, InFlightResourceBatch>();
|
|
const cache = new Map<string, unknown>();
|
|
const diagnosticsCache = new Map<string, AssetQueryPreviewDiagnostics>();
|
|
const pendingDiagnostics = new Map<string, Promise<void>>();
|
|
const knownRequests = new Map<string, ResourceRequest>();
|
|
const resourceVersions = new Map<string, number>();
|
|
const inFlightBatches = new Set<InFlightResourceBatch>();
|
|
|
|
export const $resourcesCache = atom(cache);
|
|
export const $resourceDiagnosticsCache = atom(diagnosticsCache);
|
|
|
|
const updateCache = () => {
|
|
$resourcesCache.set(new Map(cache));
|
|
$resourceDiagnosticsCache.set(new Map(diagnosticsCache));
|
|
};
|
|
|
|
const $pendingUpdater = atom({});
|
|
|
|
const updatePending = () => {
|
|
$pendingUpdater.set({});
|
|
};
|
|
|
|
export const $hasPendingResources = computed(
|
|
$pendingUpdater,
|
|
() => queue.size > 0 || pending.size > 0
|
|
);
|
|
|
|
const loadResources = async (requestFetch: typeof fetch = fetch) => {
|
|
const availableSlots = MAX_PENDING_RESOURCES - pending.size;
|
|
if (availableSlots <= 0) {
|
|
return;
|
|
}
|
|
const list = Array.from(queue.values()).slice(0, availableSlots);
|
|
if (list.length === 0) {
|
|
return;
|
|
}
|
|
const dispatched = new Map<string, ResourceRequest>();
|
|
const controller = new AbortController();
|
|
const batch = { controller, versions: new Map<string, number>() };
|
|
for (const resource of list) {
|
|
const key = getResourceKey(resource);
|
|
const version = resourceVersions.get(key) ?? 0;
|
|
queue.delete(key);
|
|
pending.set(key, batch);
|
|
dispatched.set(key, resource);
|
|
batch.versions.set(key, version);
|
|
}
|
|
inFlightBatches.add(batch);
|
|
updatePending();
|
|
|
|
try {
|
|
const response = await requestFetch(restResourcesLoader(), {
|
|
method: "POST",
|
|
body: JSON.stringify(list),
|
|
signal: controller.signal,
|
|
});
|
|
if (response.ok === false) {
|
|
return;
|
|
}
|
|
const results = new Map<string, unknown>(await response.json());
|
|
for (const [key, result] of results) {
|
|
const request = dispatched.get(key);
|
|
if (
|
|
request === undefined ||
|
|
pending.get(key) !== batch ||
|
|
knownRequests.has(key) === false ||
|
|
resourceVersions.get(key) !== batch.versions.get(key)
|
|
) {
|
|
continue;
|
|
}
|
|
const separated = separateResourceDiagnostics({ request, result });
|
|
cache.set(key, separated.result);
|
|
if (separated.diagnostics === undefined) {
|
|
diagnosticsCache.delete(key);
|
|
} else {
|
|
diagnosticsCache.set(key, separated.diagnostics);
|
|
}
|
|
}
|
|
} catch {
|
|
if (controller.signal.aborted === false) {
|
|
console.error("Resource batch request failed");
|
|
}
|
|
} finally {
|
|
inFlightBatches.delete(batch);
|
|
for (const key of dispatched.keys()) {
|
|
if (pending.get(key) === batch) {
|
|
pending.delete(key);
|
|
}
|
|
}
|
|
updateCache();
|
|
updatePending();
|
|
// Drain any resources that did not fit in this batch.
|
|
if (controller.signal.aborted === false) {
|
|
startLoading(requestFetch);
|
|
}
|
|
}
|
|
};
|
|
|
|
const startLoading = (requestFetch: typeof fetch = fetch) => {
|
|
if (pending.size >= MAX_PENDING_RESOURCES || queue.size === 0) {
|
|
return;
|
|
}
|
|
void loadResources(requestFetch);
|
|
};
|
|
|
|
const abortObsoleteBatches = () => {
|
|
for (const batch of inFlightBatches) {
|
|
const isObsolete = Array.from(batch.versions).every(
|
|
([key, version]) =>
|
|
knownRequests.has(key) === false ||
|
|
resourceVersions.get(key) !== version
|
|
);
|
|
if (isObsolete) {
|
|
batch.controller.abort();
|
|
}
|
|
}
|
|
};
|
|
|
|
const preloadResource = (resource: ResourceRequest) => {
|
|
const key = getResourceKey(resource);
|
|
knownRequests.set(key, resource);
|
|
if (resourceVersions.has(key) === false) {
|
|
resourceVersions.set(key, 0);
|
|
}
|
|
if (queue.has(key) || pending.has(key) || cache.has(key)) {
|
|
return;
|
|
}
|
|
// deduplicate resources in queue
|
|
queue.set(key, resource);
|
|
updatePending();
|
|
};
|
|
|
|
const invalidateRequestState = (key: string) => {
|
|
diagnosticsCache.delete(key);
|
|
pendingDiagnostics.delete(key);
|
|
resourceVersions.set(key, (resourceVersions.get(key) ?? 0) + 1);
|
|
};
|
|
|
|
const queueResources = (resources: readonly ResourceRequest[]) => {
|
|
const currentKeys = new Set(resources.map(getResourceKey));
|
|
let pendingChanged = false;
|
|
let diagnosticsChanged = false;
|
|
for (const key of knownRequests.keys()) {
|
|
if (currentKeys.has(key) === false) {
|
|
knownRequests.delete(key);
|
|
invalidateRequestState(key);
|
|
diagnosticsChanged = true;
|
|
pendingChanged = queue.delete(key) || pendingChanged;
|
|
pendingChanged = pending.delete(key) || pendingChanged;
|
|
}
|
|
}
|
|
abortObsoleteBatches();
|
|
if (diagnosticsChanged) {
|
|
updateCache();
|
|
}
|
|
if (pendingChanged) {
|
|
updatePending();
|
|
}
|
|
for (const resource of resources) {
|
|
preloadResource(resource);
|
|
}
|
|
};
|
|
|
|
export const preloadResources = (resources: readonly ResourceRequest[]) => {
|
|
queueResources(resources);
|
|
startLoading();
|
|
};
|
|
|
|
const invalidateAndQueueResource = (resource: ResourceRequest) => {
|
|
const key = getResourceKey(resource);
|
|
cache.delete(key);
|
|
invalidateRequestState(key);
|
|
pending.delete(key);
|
|
knownRequests.set(key, resource);
|
|
queue.set(key, resource);
|
|
};
|
|
|
|
const queueInvalidatedResource = (resource: ResourceRequest) => {
|
|
invalidateAndQueueResource(resource);
|
|
abortObsoleteBatches();
|
|
updateCache();
|
|
updatePending();
|
|
};
|
|
|
|
export const invalidateResource = (resource: ResourceRequest) => {
|
|
queueInvalidatedResource(resource);
|
|
startLoading();
|
|
};
|
|
|
|
/**
|
|
* Fetches the diagnostics intentionally omitted from ordinary canvas loads.
|
|
* Called lazily when the Diagnostics tab is opened.
|
|
*/
|
|
export const loadResourceDiagnostics = (
|
|
resource: ResourceRequest,
|
|
requestFetch: typeof fetch = fetch
|
|
) => {
|
|
const key = getResourceKey(resource);
|
|
const existing = pendingDiagnostics.get(key);
|
|
if (existing !== undefined) {
|
|
return existing;
|
|
}
|
|
const version = resourceVersions.get(key) ?? 0;
|
|
const promise = (async () => {
|
|
try {
|
|
const response = await requestFetch(
|
|
restResourcesLoader({ diagnostics: true }),
|
|
{
|
|
method: "POST",
|
|
body: JSON.stringify([resource]),
|
|
}
|
|
);
|
|
if (response.ok === false) {
|
|
return;
|
|
}
|
|
const result = new Map<string, unknown>(await response.json()).get(key);
|
|
const { diagnostics } = separateResourceDiagnostics({
|
|
request: resource,
|
|
result,
|
|
});
|
|
if ((resourceVersions.get(key) ?? 0) !== version) {
|
|
return;
|
|
}
|
|
if (diagnostics === undefined) {
|
|
diagnosticsCache.delete(key);
|
|
} else {
|
|
diagnosticsCache.set(key, diagnostics);
|
|
}
|
|
updateCache();
|
|
} catch {
|
|
console.error("Resource diagnostics request failed");
|
|
} finally {
|
|
if ((resourceVersions.get(key) ?? 0) === version) {
|
|
pendingDiagnostics.delete(key);
|
|
}
|
|
}
|
|
})();
|
|
pendingDiagnostics.set(key, promise);
|
|
return promise;
|
|
};
|
|
|
|
/**
|
|
* Invalidate the assets system resource.
|
|
* Call this when assets are uploaded, deleted, or modified to refresh expressions using assets.
|
|
*/
|
|
export const invalidateAssets = () => {
|
|
for (const request of knownRequests.values()) {
|
|
if (isAssetsResourceRequest(request) === false) {
|
|
continue;
|
|
}
|
|
invalidateAndQueueResource(request);
|
|
}
|
|
abortObsoleteBatches();
|
|
updateCache();
|
|
updatePending();
|
|
startLoading();
|
|
};
|
|
|
|
export const computeResourceRequest = (
|
|
resource: Resource,
|
|
values: Map<DataSource["id"], unknown>
|
|
): ResourceRequest => {
|
|
const request: ResourceRequest = {
|
|
name: resource.name,
|
|
method: resource.method,
|
|
url: computeExpression(resource.url, values),
|
|
searchParams: (resource.searchParams ?? []).map(({ name, value }) => ({
|
|
name,
|
|
value: computeExpression(value, values),
|
|
})),
|
|
headers: resource.headers.map(({ name, value }) => ({
|
|
name,
|
|
value: computeExpression(value, values),
|
|
})),
|
|
};
|
|
if (resource.body !== undefined) {
|
|
request.body = computeExpression(resource.body, values);
|
|
}
|
|
return request;
|
|
};
|
|
|
|
const reset = () => {
|
|
for (const batch of inFlightBatches) {
|
|
batch.controller.abort();
|
|
}
|
|
inFlightBatches.clear();
|
|
queue.clear();
|
|
pending.clear();
|
|
cache.clear();
|
|
diagnosticsCache.clear();
|
|
pendingDiagnostics.clear();
|
|
knownRequests.clear();
|
|
resourceVersions.clear();
|
|
updateCache();
|
|
updatePending();
|
|
};
|
|
|
|
const getLoaderState = () => ({
|
|
queueSize: queue.size,
|
|
pendingSize: pending.size,
|
|
});
|
|
|
|
export const __testing__ = {
|
|
getLoaderState,
|
|
loadResources,
|
|
queueInvalidatedResource,
|
|
queueResources,
|
|
reset,
|
|
startLoading,
|
|
};
|