Files
webstudio/packages/cli/src/filesystem-content-source.ts
T
Oleg Isonen b9319a3891 perf: share CLI startup for user-site publishing (#6704)
This PR reduces user-site publish time by sharing CLI startup between
sync and build, reducing asset downloads when hosted builds do not need
them, and testing smaller publish artifacts. The paired [SaaS PR
#685](https://github.com/webstudio-is/webstudio-saas/pull/685) uses the
combined CLI path when the Builder artifact advertises support; older
artifacts keep the existing split path.

The paired staging publish served HTML and JavaScript successfully. The
combined CLI step took 4 s versus about 8 s for the previous split steps
in that run; total publish time remained about 40 s. This is one
observation, not a controlled benchmark or a large-site measurement.
Local artifact pruning reduced the compressed archive from 119 MiB to
111 MiB (6.7%); it was not adopted. The full artifact is still
downloaded and extracted on every publish.

## Checklist

- [x] Preserve standalone sync/build behavior and gate combined
sync/build with an artifact capability marker.
- [x] Skip hosted asset downloads only when content indexing does not
need them; preserve static and MDX-required downloads.
- [x] Test CLI startup, synthetic build, and artifact-size
opportunities; record why no riskier change was adopted.
- [x] Verify the paired staging publish and review Builder
documentation.
- [x] Keep only the E2E schema snapshot matching current inputs; no
migration source or migration was added.
- [x] Retry the failing `pages-drag` shard: all 17 tests passed,
including the drag-and-nest test.
- [x] Resolve the two outdated review threads; current code retains
finding details and closes diagnostics on element navigation.
- [x] Required CI on the cleanup commit passed, including all Builder
E2E shards, visual regression, and the existing migration-chain check.
- [ ] Run the agent evaluation suite only after separate approval;
remind the user before merging.

No large-site publish or production release has been tested.
2026-11-17 14:04:00 +01:00

366 lines
11 KiB
TypeScript

import { open, realpath, stat, type FileHandle } from "node:fs/promises";
import { isAbsolute, relative, resolve, sep } from "node:path";
import {
computeCanonicalAssetRevision,
createCanonicalAssetFileEntry,
createContentSourceFile,
decodeUtf8,
normalizeAssetFileDocument,
prepareCanonicalContentMetadata,
type ContentSource,
} from "@webstudio-is/content-engine/compiler";
import {
getDocumentFormatByContentType,
isContentDocumentCandidate,
prepareContentCompilerEntries,
getContentCompilationMetadataRequirements,
type ContentCompilationPlan,
} from "@webstudio-is/content-engine";
import {
createAssetFolderHierarchy,
createAssetContentRevision,
formatAssetName,
getFileNameParts,
getMimeTypeByFilename,
type Asset,
type AssetFolders,
} from "@webstudio-is/sdk";
import { getLocalAssetPath, LOCAL_ASSETS_DIR } from "./asset-files";
type FileIdentity = {
device: bigint;
inode: bigint;
size: bigint;
modifiedAt: bigint;
changedAt: bigint;
};
const toFileIdentity = (metadata: {
dev: bigint;
ino: bigint;
size: bigint;
mtimeNs: bigint;
ctimeNs: bigint;
}): FileIdentity => ({
device: metadata.dev,
inode: metadata.ino,
size: metadata.size,
modifiedAt: metadata.mtimeNs,
changedAt: metadata.ctimeNs,
});
const getFileIdentity = async (path: string): Promise<FileIdentity> => {
const metadata = await stat(path, { bigint: true });
if (metadata.isFile() === false) {
throw new Error(`Content source entry is not a file: ${path}`);
}
return toFileIdentity(metadata);
};
const serializeFileIdentity = (identity: FileIdentity) =>
[
identity.device,
identity.inode,
identity.size,
identity.modifiedAt,
identity.changedAt,
].join(":");
const isSameFileIdentity = (left: FileIdentity, right: FileIdentity) =>
left.device === right.device &&
left.inode === right.inode &&
left.size === right.size &&
left.modifiedAt === right.modifiedAt &&
left.changedAt === right.changedAt;
const resolveContentFilePath = async ({
assetsDirectoryPath,
filePath,
}: {
assetsDirectoryPath: string;
filePath: string;
}) => {
const path = await realpath(filePath);
const relativePath = relative(assetsDirectoryPath, path);
if (
relativePath === "" ||
relativePath === ".." ||
relativePath.startsWith(`..${sep}`) ||
isAbsolute(relativePath)
) {
throw new Error("Content source file is outside the assets directory");
}
return path;
};
const readFromHandle = async ({
handle,
maximumBytes,
}: {
handle: FileHandle;
maximumBytes: number;
}) => {
const bytes = new Uint8Array(maximumBytes);
let offset = 0;
while (offset < maximumBytes) {
const { bytesRead } = await handle.read(
bytes,
offset,
maximumBytes - offset,
offset
);
if (bytesRead === 0) {
break;
}
offset += bytesRead;
}
return bytes.subarray(0, offset);
};
const readSnapshotFile = async ({
path,
identity,
maximumBytes,
}: {
path: string;
identity: FileIdentity;
maximumBytes: number;
}) => {
const handle = await open(path, "r");
try {
const before = await handle.stat({ bigint: true });
const beforeIdentity = toFileIdentity(before);
if (isSameFileIdentity(identity, beforeIdentity) === false) {
throw new Error("Content source file changed before it could be read");
}
const bytes = await readFromHandle({ handle, maximumBytes });
const after = await handle.stat({ bigint: true });
const afterIdentity = toFileIdentity(after);
if (isSameFileIdentity(identity, afterIdentity) === false) {
throw new Error("Content source file changed while it was being read");
}
return bytes;
} finally {
await handle.close();
}
};
export const createFileSystemContentSource = ({
projectId,
assets,
folders,
assetsDirectory = LOCAL_ASSETS_DIR,
metadataOnlyNonDocumentAssets = false,
}: {
projectId: string;
assets: readonly Asset[];
folders: AssetFolders;
assetsDirectory?: string;
metadataOnlyNonDocumentAssets?: boolean;
}): ContentSource => ({
openSnapshot: async () => {
const hierarchy = createAssetFolderHierarchy(folders);
const requestedAssetsDirectoryPath = resolve(assetsDirectory);
const hasLocalFiles = assets.some(
(asset) =>
metadataOnlyNonDocumentAssets === false ||
getDocumentFormatByContentType(getMimeTypeByFilename(asset.name)) !==
undefined
);
const assetsDirectoryPath =
hasLocalFiles === false
? requestedAssetsDirectoryPath
: await realpath(requestedAssetsDirectoryPath);
const captured = await Promise.all(
assets.map(async (asset) => {
const mimeType = getMimeTypeByFilename(asset.name);
const metadataOnly =
metadataOnlyNonDocumentAssets &&
getDocumentFormatByContentType(mimeType) === undefined;
const sourcePath = getLocalAssetPath(asset.name, assetsDirectory);
const filePath = metadataOnly
? undefined
: await resolveContentFilePath({
assetsDirectoryPath,
filePath: sourcePath,
});
const identity =
filePath === undefined ? undefined : await getFileIdentity(filePath);
const revision =
identity === undefined
? createAssetContentRevision({
storageName: asset.name,
updatedAt: asset.updatedAt ?? asset.createdAt,
size: asset.size,
})
: `fs:${serializeFileIdentity(identity)}`;
const name = formatAssetName(asset);
const extension = getFileNameParts(asset.name).extension.toLowerCase();
const folderId = hierarchy.resolveFolderId(asset.folderId);
const folderNames = hierarchy
.getPath(folderId)
.map((folder) => folder.name);
const entry = createCanonicalAssetFileEntry({
projectId,
metadataRequirements: {
structuredProperties: false,
excerpt: false,
},
document: normalizeAssetFileDocument({
asset: {
id: asset.id,
name,
...(asset.description === null
? {}
: { description: asset.description }),
...(extension === "" ? {} : { extension }),
...(folderId === undefined ? {} : { folderId, folderNames }),
mimeType,
size: identity === undefined ? asset.size : Number(identity.size),
createdAt: asset.createdAt,
revision,
contentRef: asset.name,
},
properties: {},
}),
});
return { entry, sourcePath, filePath, identity };
})
);
const revision = await computeCanonicalAssetRevision(
captured.map(({ entry }) => entry)
);
const capturedById = new Map(
captured.map((item) => [item.entry.assetId, item])
);
return {
revision,
files: captured.map(({ entry }) => createContentSourceFile(entry)),
loadDocumentSources: async () =>
captured.flatMap(({ entry, filePath, identity }) => {
if (
getDocumentFormatByContentType(entry.document.mimeType) ===
undefined
) {
return [];
}
if (filePath === undefined || identity === undefined) {
throw new Error("Content source document is missing");
}
return [
{
id: entry.assetId,
source: {
async *[Symbol.asyncIterator]() {
const bytes = await readSnapshotFile({
path: filePath,
identity,
maximumBytes: entry.document.size,
});
if (bytes.byteLength !== entry.document.size) {
throw new Error("Content source file size changed");
}
yield bytes;
},
},
},
];
}),
loadEntries: async (
plan?: ContentCompilationPlan,
options?: { maximumContentBytes: number }
) => {
const candidates =
plan === undefined
? captured
: captured.filter(({ entry: { document } }) =>
isContentDocumentCandidate({
document,
plan,
available: "base",
})
);
const requirements = getContentCompilationMetadataRequirements(plan);
const prepared = await Promise.all(
candidates.map(({ entry, filePath, identity }) =>
requirements.structuredProperties === false &&
requirements.excerpt === false
? entry
: prepareCanonicalContentMetadata({
base: entry,
requirements,
readBytes: (maximumBytes) =>
filePath === undefined || identity === undefined
? Promise.reject(
new Error("Content source file is missing")
)
: readSnapshotFile({
path: filePath,
identity,
maximumBytes,
}),
})
)
);
return await prepareContentCompilerEntries({
entries: prepared,
plan,
loadContent: async (entry) => {
const capturedFile = capturedById.get(entry.assetId);
if (
capturedFile?.filePath === undefined ||
capturedFile.identity === undefined
) {
throw new Error("Content source snapshot is incomplete");
}
const bytes = await readSnapshotFile({
path: capturedFile.filePath,
identity: capturedFile.identity,
maximumBytes: entry.document.size,
});
if (bytes.byteLength !== entry.document.size) {
throw new Error("Content source file size changed");
}
try {
return decodeUtf8(bytes);
} catch {
throw new Error(
`Selected content source file is not valid UTF-8: ${entry.document.path}`
);
}
},
maximumContentBytes: options?.maximumContentBytes,
});
},
isCurrent: async () => {
try {
if (
hasLocalFiles &&
(await realpath(requestedAssetsDirectoryPath)) !==
assetsDirectoryPath
) {
return false;
}
return (
await Promise.all(
captured.map(
async ({ sourcePath, filePath, identity }) =>
filePath === undefined ||
identity === undefined ||
((await realpath(sourcePath)) === filePath &&
isSameFileIdentity(
identity,
await getFileIdentity(filePath)
))
)
)
).every(Boolean);
} catch {
return false;
}
},
};
},
});