fix(cms): publish saved content through queued rebuild and SFTP
DC CMS qualification / qualify (push) Successful in 2m26s
DC CMS qualification / qualify (push) Successful in 2m26s
This commit is contained in:
+78
-27
@@ -1,5 +1,6 @@
|
||||
import { createReadStream, statSync } from "node:fs";
|
||||
import { appendFile, copyFile, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { appendFile, copyFile, cp, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { extname, join, normalize, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn } from "node:child_process";
|
||||
@@ -17,6 +18,7 @@ const activeProjectId = projectId;
|
||||
const projectConfigPath = join(projectsRoot, `${activeProjectId}.json`);
|
||||
const projectSecretsPath = join(projectsRoot, `${activeProjectId}.secrets.json`);
|
||||
const publishLogPath = join(projectsRoot, `${activeProjectId}.publish.log.jsonl`);
|
||||
const publishStatePath = join(projectsRoot, `${activeProjectId}.publish-state.json`);
|
||||
const publishJobs = new Map();
|
||||
const PUBLISH_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -1778,17 +1780,29 @@ async function ensureRemoteDirectory(client, path, cache) {
|
||||
cache.add(normalized);
|
||||
}
|
||||
|
||||
async function shouldSkipRemoteFile(client, localFile, remotePath) {
|
||||
async function fileDigest(path) {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
async function shouldSkipRemoteFile(client, localFile, remotePath, previous) {
|
||||
// SFTP timestamps have second precision: equal size + mtime loses one-letter edits.
|
||||
if (previous?.sha256 !== localFile.sha256) return false;
|
||||
try {
|
||||
const remoteStat = await client.stat(remotePath);
|
||||
if (!remoteStat || Number(remoteStat.size) !== localFile.size) return false;
|
||||
const remoteMtime = Number(remoteStat.modifyTime || remoteStat.mtime || 0);
|
||||
return remoteMtime && remoteMtime >= localFile.mtimeMs - 1000;
|
||||
return Number(remoteStat.size) === localFile.size
|
||||
&& Number(remoteStat.modifyTime || remoteStat.mtime || 0) === previous.remoteMtime;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function buildPublicSite() {
|
||||
await runNodeScript("render-home.mjs");
|
||||
await runNodeScript("render-knowledge.mjs");
|
||||
}
|
||||
|
||||
function publishJobPercent(job) {
|
||||
if (job.state === "completed") return 100;
|
||||
if (!job.totalBytes) return 0;
|
||||
@@ -1801,6 +1815,7 @@ function publicPublishJob(job) {
|
||||
id: job.id,
|
||||
state: job.state,
|
||||
rendered: job.rendered,
|
||||
pendingChanges: Boolean(job.rerunRequested),
|
||||
host: job.host,
|
||||
remoteRoot: job.remoteRoot,
|
||||
totalFiles: job.totalFiles,
|
||||
@@ -1865,7 +1880,9 @@ async function publishProject(options = {}) {
|
||||
publishing = true;
|
||||
try {
|
||||
await hooks.validateDeploy(activeProjectId, projectConfig);
|
||||
return await performPublish(options);
|
||||
if (options.job) touchPublishJob(options.job, { state: "building" });
|
||||
await buildPublicSite();
|
||||
return await performPublish({ ...options, rendered: true });
|
||||
} finally { publishing = false; }
|
||||
}
|
||||
|
||||
@@ -1874,7 +1891,17 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
||||
const files = await collectPublicDeployFiles();
|
||||
if (!files.length) throw new Error("Нет публичных файлов для публикации");
|
||||
|
||||
const client = new SftpClient();
|
||||
const client = hooks.createSftpClient ? hooks.createSftpClient() : new SftpClient();
|
||||
const destination = createHash("sha256").update(JSON.stringify([
|
||||
deployConfig.host, deployConfig.port, deployConfig.username, deployConfig.remoteRoot,
|
||||
])).digest("hex");
|
||||
const savedState = await readFile(publishStatePath, "utf8").then(JSON.parse).catch((error) => {
|
||||
if (error.code === "ENOENT" || error instanceof SyntaxError) return {};
|
||||
throw error;
|
||||
});
|
||||
const previousFiles = savedState.destination === destination ? savedState.files || {} : {};
|
||||
const nextFiles = {};
|
||||
const snapshotRoot = await mkdtemp(join(tmpdir(), "dc-cms-publish-"));
|
||||
const directoryCache = new Set();
|
||||
const report = {
|
||||
ok: true,
|
||||
@@ -1903,6 +1930,18 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Freeze bytes for this pass. Edits arriving during transfer schedule a new pass.
|
||||
if (job) touchPublishJob(job, { state: "scanning", rendered: true });
|
||||
for (const file of files) {
|
||||
const snapshotPath = join(snapshotRoot, file.relativePath);
|
||||
await mkdir(dirname(snapshotPath), { recursive: true });
|
||||
await copyFile(file.absolutePath, snapshotPath);
|
||||
file.absolutePath = snapshotPath;
|
||||
file.size = (await stat(snapshotPath)).size;
|
||||
file.sha256 = await fileDigest(snapshotPath);
|
||||
}
|
||||
report.totalBytes = files.reduce((sum, file) => sum + file.size, 0);
|
||||
if (job) touchPublishJob(job, { state: "connecting", totalBytes: report.totalBytes });
|
||||
await client.connect({
|
||||
host: deployConfig.host,
|
||||
port: deployConfig.port,
|
||||
@@ -1927,7 +1966,8 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
||||
}
|
||||
await ensureRemoteDirectory(client, remoteParent(remotePath), directoryCache);
|
||||
|
||||
if (await shouldSkipRemoteFile(client, file, remotePath)) {
|
||||
if (await shouldSkipRemoteFile(client, file, remotePath, previousFiles[file.relativePath])) {
|
||||
nextFiles[file.relativePath] = previousFiles[file.relativePath];
|
||||
report.skippedFiles += 1;
|
||||
report.skippedBytes += file.size;
|
||||
report.processedFiles += 1;
|
||||
@@ -1954,6 +1994,12 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
||||
});
|
||||
},
|
||||
});
|
||||
const remoteStat = await client.stat(remotePath);
|
||||
if (Number(remoteStat.size) !== file.size) throw new Error(`Неполная передача: ${file.relativePath}`);
|
||||
nextFiles[file.relativePath] = {
|
||||
sha256: file.sha256,
|
||||
remoteMtime: Number(remoteStat.modifyTime || remoteStat.mtime || 0),
|
||||
};
|
||||
report.uploadedFiles += 1;
|
||||
report.uploadedBytes += file.size;
|
||||
report.processedFiles += 1;
|
||||
@@ -1969,19 +2015,26 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
const nextStatePath = `${publishStatePath}.tmp`;
|
||||
await writeFile(nextStatePath, JSON.stringify({ destination, files: nextFiles }), { mode: 0o600 });
|
||||
await rename(nextStatePath, publishStatePath);
|
||||
report.totalLabel = formatProjectSize(report.totalBytes);
|
||||
report.uploadedLabel = formatProjectSize(report.uploadedBytes);
|
||||
report.skippedLabel = formatProjectSize(report.skippedBytes);
|
||||
return report;
|
||||
} finally {
|
||||
await client.end().catch(() => {});
|
||||
await rm(snapshotRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function startPublishJob({ rendered = false } = {}) {
|
||||
cleanupPublishJobs();
|
||||
const activeJob = activePublishJob();
|
||||
if (activeJob) return { job: publicPublishJob(activeJob), reused: true };
|
||||
if (activeJob) {
|
||||
touchPublishJob(activeJob, { rerunRequested: true });
|
||||
return { job: publicPublishJob(activeJob), reused: true };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const job = {
|
||||
@@ -2011,8 +2064,16 @@ function startPublishJob({ rendered = false } = {}) {
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
touchPublishJob(job, { state: "scanning" });
|
||||
const report = await publishProject({ rendered, job });
|
||||
let report;
|
||||
do {
|
||||
touchPublishJob(job, {
|
||||
state: "building", rerunRequested: false,
|
||||
processedFiles: 0, processedBytes: 0, uploadedFiles: 0, uploadedBytes: 0,
|
||||
skippedFiles: 0, skippedBytes: 0, totalFiles: 0, totalBytes: 0,
|
||||
currentFile: "", currentFileBytes: 0, currentFileSize: 0,
|
||||
});
|
||||
report = await publishProject({ rendered, job });
|
||||
} while (job.rerunRequested);
|
||||
touchPublishJob(job, {
|
||||
state: "completed",
|
||||
processedFiles: report.totalFiles,
|
||||
@@ -2061,19 +2122,11 @@ async function recentPublishLog(limit = 20) {
|
||||
.reverse();
|
||||
}
|
||||
|
||||
async function maybePublishAfterRender(renderResult) {
|
||||
if (!projectConfig.deploy?.enabled || !projectConfig.deploy?.deployOnRender) {
|
||||
return {
|
||||
publish: null,
|
||||
...renderResult,
|
||||
};
|
||||
async function renderAndMaybePublish(scriptName) {
|
||||
if (projectConfig.deploy?.enabled && projectConfig.deploy?.deployOnRender) {
|
||||
return { publish: null, publishJob: startPublishJob().job };
|
||||
}
|
||||
|
||||
const publish = await publishProject({ rendered: true });
|
||||
return {
|
||||
publish,
|
||||
...renderResult,
|
||||
};
|
||||
return { publish: null, ...(await runNodeScript(scriptName)) };
|
||||
}
|
||||
|
||||
function resolveBrowserEntry(value) {
|
||||
@@ -2954,15 +3007,13 @@ async function handle(req, res) {
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/render/home") {
|
||||
if (!ensureSiteReady(res)) return;
|
||||
const result = await runNodeScript("render-home.mjs");
|
||||
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
|
||||
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-home.mjs")) });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/render/knowledge") {
|
||||
if (!ensureSiteReady(res)) return;
|
||||
const result = await runNodeScript("render-knowledge.mjs");
|
||||
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
|
||||
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-knowledge.mjs")) });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user