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:
@@ -14,3 +14,5 @@ projects/*.publish.log.jsonl
|
|||||||
|
|
||||||
# Persistent independent site workspaces are runtime data.
|
# Persistent independent site workspaces are runtime data.
|
||||||
projects/sites/
|
projects/sites/
|
||||||
|
|
||||||
|
projects/*.publish-state.json*
|
||||||
|
|||||||
+24
-24
File diff suppressed because one or more lines are too long
+5
-1
@@ -6,7 +6,11 @@
|
|||||||
|
|
||||||
Перенос деплоя сначала отключает исходный проект, затем переносит зашифрованный секрет и параметры хостинга. Получатель остаётся отключённым до явного включения. Два проекта не могут одновременно публиковать в одну или вложенную папку на одном SFTP-аккаунте. После прерывания возможны два отключённых проекта, но не два включённых публикационных направления.
|
Перенос деплоя сначала отключает исходный проект, затем переносит зашифрованный секрет и параметры хостинга. Получатель остаётся отключённым до явного включения. Два проекта не могут одновременно публиковать в одну или вложенную папку на одном SFTP-аккаунте. После прерывания возможны два отключённых проекта, но не два включённых публикационных направления.
|
||||||
|
|
||||||
Сохранение и пересборка отделены от публикации. Автоматическая публикация после пересборки требует двух флагов: `enabled` и `deployOnRender`. Старые настройки без второго флага переходят в ручной режим публикации.
|
«Сохранить» записывает контент или SEO/базу знаний и запускает пересборку. Когда включены `deploy.enabled` и «Публиковать при сохранении» (`deployOnRender`), CMS ставит фоновое задание: собирает главную и базу знаний, фиксирует копию публичных файлов и отправляет её по SFTP. Прогресс и ошибки доступны в редакторе и настройках проекта. Сохранение во время передачи ставит ещё один проход с последней версией; изменения не теряются. Без этих флагов обновляется только предпросмотр.
|
||||||
|
|
||||||
|
«Опубликовать» также сначала собирает обе части сайта. Файлы пропускаются только при совпадении SHA-256 с последней успешной публикацией и метаданных на хостинге; размер и время сами по себе недостаточны для сравнения. Частный файл `projects/<id>.publish-state.json` привязан к конкретному SFTP-направлению, не попадает в сайт и не содержит паролей. Первая публикация после обновления передаёт все файлы, следующие — только изменения. Ошибку передачи можно повторить кнопкой «Опубликовать».
|
||||||
|
|
||||||
|
ZIP нужен для обновления кода и шаблонов локально. Для обычного редактирования текста и изображений повторный импорт не нужен. Новые изображения получают уникальный URL, поэтому кеш браузера не скрывает замену.
|
||||||
|
|
||||||
## Git
|
## Git
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -61,7 +61,7 @@ def main():
|
|||||||
files=tracked_payload()
|
files=tracked_payload()
|
||||||
for name in files:
|
for name in files:
|
||||||
if name.endswith(('.js','.mjs')): run(['node','--check',name])
|
if name.endswith(('.js','.mjs')): run(['node','--check',name])
|
||||||
run(['node','--test','test/multisite.test.mjs'])
|
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs'])
|
||||||
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
|
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
|
||||||
# The ordinary release cannot change its build, dependency or deployment foundation.
|
# The ordinary release cannot change its build, dependency or deployment foundation.
|
||||||
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
|
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
|
||||||
|
|||||||
+78
-27
@@ -1,5 +1,6 @@
|
|||||||
import { createReadStream, statSync } from "node:fs";
|
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 { extname, join, normalize, relative, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
@@ -17,6 +18,7 @@ const activeProjectId = projectId;
|
|||||||
const projectConfigPath = join(projectsRoot, `${activeProjectId}.json`);
|
const projectConfigPath = join(projectsRoot, `${activeProjectId}.json`);
|
||||||
const projectSecretsPath = join(projectsRoot, `${activeProjectId}.secrets.json`);
|
const projectSecretsPath = join(projectsRoot, `${activeProjectId}.secrets.json`);
|
||||||
const publishLogPath = join(projectsRoot, `${activeProjectId}.publish.log.jsonl`);
|
const publishLogPath = join(projectsRoot, `${activeProjectId}.publish.log.jsonl`);
|
||||||
|
const publishStatePath = join(projectsRoot, `${activeProjectId}.publish-state.json`);
|
||||||
const publishJobs = new Map();
|
const publishJobs = new Map();
|
||||||
const PUBLISH_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;
|
const PUBLISH_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
@@ -1778,17 +1780,29 @@ async function ensureRemoteDirectory(client, path, cache) {
|
|||||||
cache.add(normalized);
|
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 {
|
try {
|
||||||
const remoteStat = await client.stat(remotePath);
|
const remoteStat = await client.stat(remotePath);
|
||||||
if (!remoteStat || Number(remoteStat.size) !== localFile.size) return false;
|
return Number(remoteStat.size) === localFile.size
|
||||||
const remoteMtime = Number(remoteStat.modifyTime || remoteStat.mtime || 0);
|
&& Number(remoteStat.modifyTime || remoteStat.mtime || 0) === previous.remoteMtime;
|
||||||
return remoteMtime && remoteMtime >= localFile.mtimeMs - 1000;
|
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function buildPublicSite() {
|
||||||
|
await runNodeScript("render-home.mjs");
|
||||||
|
await runNodeScript("render-knowledge.mjs");
|
||||||
|
}
|
||||||
|
|
||||||
function publishJobPercent(job) {
|
function publishJobPercent(job) {
|
||||||
if (job.state === "completed") return 100;
|
if (job.state === "completed") return 100;
|
||||||
if (!job.totalBytes) return 0;
|
if (!job.totalBytes) return 0;
|
||||||
@@ -1801,6 +1815,7 @@ function publicPublishJob(job) {
|
|||||||
id: job.id,
|
id: job.id,
|
||||||
state: job.state,
|
state: job.state,
|
||||||
rendered: job.rendered,
|
rendered: job.rendered,
|
||||||
|
pendingChanges: Boolean(job.rerunRequested),
|
||||||
host: job.host,
|
host: job.host,
|
||||||
remoteRoot: job.remoteRoot,
|
remoteRoot: job.remoteRoot,
|
||||||
totalFiles: job.totalFiles,
|
totalFiles: job.totalFiles,
|
||||||
@@ -1865,7 +1880,9 @@ async function publishProject(options = {}) {
|
|||||||
publishing = true;
|
publishing = true;
|
||||||
try {
|
try {
|
||||||
await hooks.validateDeploy(activeProjectId, projectConfig);
|
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; }
|
} finally { publishing = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1874,7 +1891,17 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
|||||||
const files = await collectPublicDeployFiles();
|
const files = await collectPublicDeployFiles();
|
||||||
if (!files.length) throw new Error("Нет публичных файлов для публикации");
|
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 directoryCache = new Set();
|
||||||
const report = {
|
const report = {
|
||||||
ok: true,
|
ok: true,
|
||||||
@@ -1903,6 +1930,18 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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({
|
await client.connect({
|
||||||
host: deployConfig.host,
|
host: deployConfig.host,
|
||||||
port: deployConfig.port,
|
port: deployConfig.port,
|
||||||
@@ -1927,7 +1966,8 @@ async function performPublish({ rendered = false, job = null } = {}) {
|
|||||||
}
|
}
|
||||||
await ensureRemoteDirectory(client, remoteParent(remotePath), directoryCache);
|
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.skippedFiles += 1;
|
||||||
report.skippedBytes += file.size;
|
report.skippedBytes += file.size;
|
||||||
report.processedFiles += 1;
|
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.uploadedFiles += 1;
|
||||||
report.uploadedBytes += file.size;
|
report.uploadedBytes += file.size;
|
||||||
report.processedFiles += 1;
|
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.totalLabel = formatProjectSize(report.totalBytes);
|
||||||
report.uploadedLabel = formatProjectSize(report.uploadedBytes);
|
report.uploadedLabel = formatProjectSize(report.uploadedBytes);
|
||||||
report.skippedLabel = formatProjectSize(report.skippedBytes);
|
report.skippedLabel = formatProjectSize(report.skippedBytes);
|
||||||
return report;
|
return report;
|
||||||
} finally {
|
} finally {
|
||||||
await client.end().catch(() => {});
|
await client.end().catch(() => {});
|
||||||
|
await rm(snapshotRoot, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startPublishJob({ rendered = false } = {}) {
|
function startPublishJob({ rendered = false } = {}) {
|
||||||
cleanupPublishJobs();
|
cleanupPublishJobs();
|
||||||
const activeJob = activePublishJob();
|
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 now = new Date().toISOString();
|
||||||
const job = {
|
const job = {
|
||||||
@@ -2011,8 +2064,16 @@ function startPublishJob({ rendered = false } = {}) {
|
|||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
touchPublishJob(job, { state: "scanning" });
|
let report;
|
||||||
const report = await publishProject({ rendered, job });
|
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, {
|
touchPublishJob(job, {
|
||||||
state: "completed",
|
state: "completed",
|
||||||
processedFiles: report.totalFiles,
|
processedFiles: report.totalFiles,
|
||||||
@@ -2061,19 +2122,11 @@ async function recentPublishLog(limit = 20) {
|
|||||||
.reverse();
|
.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function maybePublishAfterRender(renderResult) {
|
async function renderAndMaybePublish(scriptName) {
|
||||||
if (!projectConfig.deploy?.enabled || !projectConfig.deploy?.deployOnRender) {
|
if (projectConfig.deploy?.enabled && projectConfig.deploy?.deployOnRender) {
|
||||||
return {
|
return { publish: null, publishJob: startPublishJob().job };
|
||||||
publish: null,
|
|
||||||
...renderResult,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
return { publish: null, ...(await runNodeScript(scriptName)) };
|
||||||
const publish = await publishProject({ rendered: true });
|
|
||||||
return {
|
|
||||||
publish,
|
|
||||||
...renderResult,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveBrowserEntry(value) {
|
function resolveBrowserEntry(value) {
|
||||||
@@ -2954,15 +3007,13 @@ async function handle(req, res) {
|
|||||||
|
|
||||||
if (req.method === "POST" && url.pathname === "/api/render/home") {
|
if (req.method === "POST" && url.pathname === "/api/render/home") {
|
||||||
if (!ensureSiteReady(res)) return;
|
if (!ensureSiteReady(res)) return;
|
||||||
const result = await runNodeScript("render-home.mjs");
|
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-home.mjs")) });
|
||||||
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method === "POST" && url.pathname === "/api/render/knowledge") {
|
if (req.method === "POST" && url.pathname === "/api/render/knowledge") {
|
||||||
if (!ensureSiteReady(res)) return;
|
if (!ensureSiteReady(res)) return;
|
||||||
const result = await runNodeScript("render-knowledge.mjs");
|
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-knowledge.mjs")) });
|
||||||
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { once } from 'node:events';
|
||||||
|
import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { createSiteApplication } from '../server/site-app.mjs';
|
||||||
|
|
||||||
|
const deferred = () => { let resolve; const promise = new Promise(r => resolve = r); return { promise, resolve }; };
|
||||||
|
|
||||||
|
test('save/render publication builds current content and reliably sends changes', async t => {
|
||||||
|
const root = await mkdtemp(join(tmpdir(), 'cms-publication-test-'));
|
||||||
|
const site = join(root, 'site');
|
||||||
|
const configPath = join(root, 'mission.json');
|
||||||
|
const fixtures = {
|
||||||
|
'content/pages/home.json': JSON.stringify({ title: 'Alpha', seo: 'SEO A', regions: [] }),
|
||||||
|
'content/knowledge.json': JSON.stringify({ title: 'Knowledge A' }),
|
||||||
|
'content/block-templates/home.json': '[]',
|
||||||
|
'templates/pages/home/shell.html': '<html></html>',
|
||||||
|
'tools/render-home.mjs': 'import {readFile,writeFile} from "node:fs/promises";const p=JSON.parse(await readFile("content/pages/home.json"));await writeFile("index.html",`<title>${p.seo}</title><h1>${p.title}</h1><img src="assets/photo.png">`);',
|
||||||
|
'tools/render-knowledge.mjs': 'import {readFile,writeFile,mkdir} from "node:fs/promises";const k=JSON.parse(await readFile("content/knowledge.json"));await mkdir("knowledge",{recursive:true});await writeFile("knowledge/index.html",`<h1>${k.title}</h1>`);',
|
||||||
|
'index.html': 'stale HTML',
|
||||||
|
'assets/photo.png': 'image-a',
|
||||||
|
};
|
||||||
|
for (const [path, value] of Object.entries(fixtures)) {
|
||||||
|
await mkdir(dirname(join(site, path)), { recursive: true });
|
||||||
|
await writeFile(join(site, path), value);
|
||||||
|
}
|
||||||
|
await writeFile(configPath, JSON.stringify({ id: 'mission', name: 'Mission', siteRoot: site, deploy: { enabled: false } }));
|
||||||
|
const remote = new Map(); const uploads = [];
|
||||||
|
let connectCount = 0, failTransfer = false, gate = null;
|
||||||
|
const app = await createSiteApplication({ projectId: 'mission', projectRoot: site, projectsRoot: root, hooks: {
|
||||||
|
transaction: fn => fn(), validateDeploy: async () => {},
|
||||||
|
writeConfig: async (_id, value) => writeFile(configPath, JSON.stringify(value)),
|
||||||
|
createSftpClient: () => ({
|
||||||
|
connect: async () => { connectCount++; }, mkdir: async () => {}, end: async () => {},
|
||||||
|
stat: async path => { if (!remote.has(path)) throw new Error('missing'); return { size: remote.get(path).length, modifyTime: 1000 }; },
|
||||||
|
fastPut: async (local, path, options) => {
|
||||||
|
if (failTransfer) throw new Error('fixture SFTP rejected transfer');
|
||||||
|
if (gate) { const current = gate; gate = null; current.entered.resolve(); await current.release.promise; }
|
||||||
|
const data = await readFile(local); remote.set(path, data); uploads.push(path); options.step(data.length);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
} });
|
||||||
|
const server = createServer(app.handle); server.listen(0, '127.0.0.1'); await once(server, 'listening');
|
||||||
|
t.after(async () => { await new Promise(resolve => server.close(resolve)); await rm(root, { recursive: true, force: true }); });
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
async function api(path, method = 'GET', body) {
|
||||||
|
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||||
|
const payload = await response.json(); assert.ok(response.ok, JSON.stringify(payload)); return payload;
|
||||||
|
}
|
||||||
|
async function configure(enabled = true, automatic = true) {
|
||||||
|
const config = await api('/api/project/config');
|
||||||
|
return api('/api/project/config', 'PUT', { ...config, deploy: { ...config.deploy, enabled, deployOnRender: automatic, method: 'sftp', host: 'fixture.invalid', port: 22, username: 'test', password: 'test-only', remotePath: 'httpdocs' } });
|
||||||
|
}
|
||||||
|
async function finished(id) {
|
||||||
|
const deadline = Date.now() + 10000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
const { job } = await api(`/api/project/publish/status?jobId=${id}`);
|
||||||
|
if (['completed', 'failed'].includes(job.state)) return job;
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 15));
|
||||||
|
}
|
||||||
|
throw new Error('publication timeout');
|
||||||
|
}
|
||||||
|
const text = path => remote.get(`httpdocs/${path}`)?.toString();
|
||||||
|
await configure();
|
||||||
|
await t.test('manual Publish builds both pages instead of uploading stale HTML', async () => {
|
||||||
|
const { job } = await api('/api/project/publish/start', 'POST');
|
||||||
|
assert.equal((await finished(job.id)).state, 'completed');
|
||||||
|
assert.match(text('index.html'), /Alpha/); assert.equal(text('knowledge/index.html'), '<h1>Knowledge A</h1>');
|
||||||
|
assert.equal(text('assets/photo.png'), 'image-a');
|
||||||
|
assert.ok(![...remote.keys()].some(path => /content|secrets|publish-state/.test(path)));
|
||||||
|
});
|
||||||
|
await t.test('one-letter content/SEO and same-size image edits are not skipped; unchanged files are', async () => {
|
||||||
|
const before = uploads.length;
|
||||||
|
await api('/api/page/home', 'PUT', { title: 'Alphb', seo: 'SEO B', regions: [] });
|
||||||
|
await writeFile(join(site, 'assets/photo.png'), 'image-b');
|
||||||
|
const result = await api('/api/render/home', 'POST');
|
||||||
|
assert.ok(result.publishJob.id); const job = await finished(result.publishJob.id);
|
||||||
|
assert.equal(job.state, 'completed'); assert.equal(job.uploadedFiles, 2); assert.equal(job.skippedFiles, 1);
|
||||||
|
assert.match(text('index.html'), /Alphb/); assert.match(text('index.html'), /SEO B/);
|
||||||
|
assert.equal(text('assets/photo.png'), 'image-b'); assert.equal(uploads.length - before, 2);
|
||||||
|
});
|
||||||
|
await t.test('knowledge Save/render publishes its updated page', async () => {
|
||||||
|
await api('/api/knowledge', 'PUT', { title: 'Knowledge B' });
|
||||||
|
const result = await api('/api/render/knowledge', 'POST'); const job = await finished(result.publishJob.id);
|
||||||
|
assert.equal(job.state, 'completed'); assert.equal(job.uploadedFiles, 1);
|
||||||
|
assert.equal(text('knowledge/index.html'), '<h1>Knowledge B</h1>');
|
||||||
|
});
|
||||||
|
await t.test('edits saved during an active transfer trigger another pass and preserve newest revision', async () => {
|
||||||
|
await api('/api/page/home', 'PUT', { title: 'First', seo: 'SEO C', regions: [] });
|
||||||
|
const blocked = { entered: deferred(), release: deferred() }; gate = blocked;
|
||||||
|
const first = await api('/api/render/home', 'POST');
|
||||||
|
await blocked.entered.promise;
|
||||||
|
await api('/api/page/home', 'PUT', { title: 'Latest', seo: 'SEO D', regions: [] });
|
||||||
|
await writeFile(join(site, 'assets/photo.png'), 'image-c');
|
||||||
|
const second = await api('/api/render/home', 'POST');
|
||||||
|
assert.equal(first.publishJob.id, second.publishJob.id); assert.equal(second.publishJob.pendingChanges, true);
|
||||||
|
blocked.release.resolve();
|
||||||
|
assert.equal((await finished(first.publishJob.id)).state, 'completed');
|
||||||
|
assert.match(text('index.html'), /Latest/); assert.match(text('index.html'), /SEO D/); assert.equal(text('assets/photo.png'), 'image-c');
|
||||||
|
});
|
||||||
|
await t.test('SFTP failure is terminal and visible; retry rebuilds and sends pending changes', async () => {
|
||||||
|
await api('/api/knowledge', 'PUT', { title: 'Knowledge C' }); failTransfer = true;
|
||||||
|
const result = await api('/api/render/knowledge', 'POST'); const failed = await finished(result.publishJob.id);
|
||||||
|
assert.equal(failed.state, 'failed'); assert.match(failed.error, /SFTP rejected/);
|
||||||
|
assert.equal(text('knowledge/index.html'), '<h1>Knowledge B</h1>');
|
||||||
|
failTransfer = false;
|
||||||
|
const retry = await api('/api/project/publish/start', 'POST'); assert.equal((await finished(retry.job.id)).state, 'completed');
|
||||||
|
assert.equal(text('knowledge/index.html'), '<h1>Knowledge C</h1>');
|
||||||
|
});
|
||||||
|
await t.test('build failure never transfers stale pages', async () => {
|
||||||
|
const before = connectCount; await writeFile(join(site, 'tools/render-home.mjs'), 'throw new Error("broken template")');
|
||||||
|
const { job } = await api('/api/project/publish/start', 'POST');
|
||||||
|
assert.equal((await finished(job.id)).state, 'failed'); assert.equal(connectCount, before);
|
||||||
|
await writeFile(join(site, 'tools/render-home.mjs'), fixtures['tools/render-home.mjs']);
|
||||||
|
});
|
||||||
|
await t.test('disabled Agent-style deployment only rebuilds preview', async () => {
|
||||||
|
await configure(false); const before = connectCount;
|
||||||
|
await api('/api/page/home', 'PUT', { title: 'Local', seo: '', regions: [] });
|
||||||
|
const result = await api('/api/render/home', 'POST');
|
||||||
|
assert.equal(result.publish, null); assert.equal(result.publishJob, undefined); assert.equal(connectCount, before);
|
||||||
|
assert.match(await readFile(join(site, 'index.html'), 'utf8'), /Local/); assert.match(text('index.html'), /Latest/);
|
||||||
|
});
|
||||||
|
});
|
||||||
+35
-31
@@ -575,7 +575,9 @@ function setDirty(isDirty, message = null) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let contentRevision = 0;
|
||||||
function markDirty(message = null) {
|
function markDirty(message = null) {
|
||||||
|
contentRevision += 1;
|
||||||
setDirty(true, message);
|
setDirty(true, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -772,6 +774,7 @@ function publishJobRunning(job = state.publishJob) {
|
|||||||
function publishStateLabel(job) {
|
function publishStateLabel(job) {
|
||||||
const labels = {
|
const labels = {
|
||||||
queued: "Публикация поставлена в очередь",
|
queued: "Публикация поставлена в очередь",
|
||||||
|
building: "Собираем страницы сайта",
|
||||||
scanning: "Считаем файлы и общий объём",
|
scanning: "Считаем файлы и общий объём",
|
||||||
connecting: "Подключаемся к хостингу",
|
connecting: "Подключаемся к хостингу",
|
||||||
publishing: "Передаём файлы по SFTP",
|
publishing: "Передаём файлы по SFTP",
|
||||||
@@ -857,7 +860,16 @@ async function fetchPublishJob(jobId = "") {
|
|||||||
return payload.job || null;
|
return payload.job || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pollPublishJob(jobId) {
|
const publishPolls = new Map();
|
||||||
|
function pollPublishJob(jobId) {
|
||||||
|
if (!publishPolls.has(jobId)) {
|
||||||
|
const polling = watchPublishJob(jobId).finally(() => publishPolls.delete(jobId));
|
||||||
|
publishPolls.set(jobId, polling);
|
||||||
|
}
|
||||||
|
return publishPolls.get(jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function watchPublishJob(jobId) {
|
||||||
while (true) {
|
while (true) {
|
||||||
const job = await fetchPublishJob(jobId);
|
const job = await fetchPublishJob(jobId);
|
||||||
if (!job) throw new Error("Сервер потерял состояние публикации");
|
if (!job) throw new Error("Сервер потерял состояние публикации");
|
||||||
@@ -990,7 +1002,7 @@ function updateAdminModeSurface() {
|
|||||||
}
|
}
|
||||||
if (el.save) {
|
if (el.save) {
|
||||||
el.save.textContent = "Сохранить";
|
el.save.textContent = "Сохранить";
|
||||||
el.save.title = isKnowledge ? "Записать дерево в content/knowledge.json" : "Записать текущую модель в content/pages/home.json";
|
el.save.title = state.projectConfig?.deploy?.enabled && state.projectConfig?.deploy?.deployOnRender ? "Сохранить изменения и опубликовать на сайте" : "Сохранить изменения и пересобрать страницы";
|
||||||
el.save.disabled = !hasSite && !isProjectSettingsSelected();
|
el.save.disabled = !hasSite && !isProjectSettingsSelected();
|
||||||
}
|
}
|
||||||
if (el.render) {
|
if (el.render) {
|
||||||
@@ -2474,7 +2486,7 @@ function renderProjectSettings() {
|
|||||||
fields: [
|
fields: [
|
||||||
transferButton,
|
transferButton,
|
||||||
createProjectField({ path: "deploy.enabled", label: "Включить деплой", type: "checkbox" }),
|
createProjectField({ path: "deploy.enabled", label: "Включить деплой", type: "checkbox" }),
|
||||||
createProjectField({ path: "deploy.deployOnRender", label: "Публиковать после пересборки", type: "checkbox" }),
|
createProjectField({ path: "deploy.deployOnRender", label: "Публиковать при сохранении", type: "checkbox" }),
|
||||||
createProjectField({ path: "deploy.method", label: "Метод", options: ["sftp", "ftp"] }),
|
createProjectField({ path: "deploy.method", label: "Метод", options: ["sftp", "ftp"] }),
|
||||||
createProjectField({ path: "deploy.host", label: "FTP / SFTP host", placeholder: "a0000.ftp.mchost.ru" }),
|
createProjectField({ path: "deploy.host", label: "FTP / SFTP host", placeholder: "a0000.ftp.mchost.ru" }),
|
||||||
createProjectField({ path: "deploy.port", label: "Порт", type: "number", placeholder: "22" }),
|
createProjectField({ path: "deploy.port", label: "Порт", type: "number", placeholder: "22" }),
|
||||||
@@ -5809,24 +5821,29 @@ async function persistKnowledge() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function saveKnowledge() {
|
async function saveKnowledge() {
|
||||||
await persistKnowledge();
|
return renderKnowledge();
|
||||||
setDirty(false);
|
|
||||||
setStatus("База знаний сохранена в content/knowledge.json.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renderKnowledge() {
|
async function renderKnowledge() {
|
||||||
await persistKnowledge();
|
return saveAndRender(persistKnowledge, "knowledge");
|
||||||
const response = await siteFetch("/api/render/knowledge", { method: "POST" });
|
}
|
||||||
const payload = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok || !payload.ok) {
|
async function saveAndRender(persist, page) {
|
||||||
throw new Error(payload.error || "Render failed");
|
const revision = contentRevision;
|
||||||
|
setStatus("Сохраняем изменения...");
|
||||||
|
await persist();
|
||||||
|
const response = await siteFetch(`/api/render/${page}`, { method: "POST" });
|
||||||
|
const payload = await readApiJson(response, "Изменения сохранены, но сборка не выполнена");
|
||||||
|
if (!payload.ok) throw new Error(payload.error || "Ошибка сборки");
|
||||||
|
if (revision === contentRevision) setDirty(false);
|
||||||
|
if (payload.publishJob?.id) {
|
||||||
|
state.publishJob = payload.publishJob;
|
||||||
|
updatePublishProgressSurface();
|
||||||
|
setStatus("Изменения сохранены. Публикуем на сайте...");
|
||||||
|
await pollPublishJob(payload.publishJob.id);
|
||||||
|
} else {
|
||||||
|
setStatus("Изменения сохранены, страницы пересобраны. Автопубликация для этого сайта выключена.");
|
||||||
}
|
}
|
||||||
|
|
||||||
setDirty(false);
|
|
||||||
setStatus(
|
|
||||||
`${payload.stdout ? `База знаний сохранена. ${payload.stdout}` : "База знаний сохранена и пересобрана."}${publishStatusText(payload)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPage() {
|
async function loadPage() {
|
||||||
@@ -5873,24 +5890,11 @@ async function persistPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function savePage() {
|
async function savePage() {
|
||||||
await persistPage();
|
return renderHome();
|
||||||
setDirty(false);
|
|
||||||
setStatus("Модель сохранена в content/pages/home.json. Для публичной страницы нажмите «Обновить index.html».");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renderHome() {
|
async function renderHome() {
|
||||||
await persistPage();
|
return saveAndRender(persistPage, "home");
|
||||||
const response = await siteFetch("/api/render/home", { method: "POST" });
|
|
||||||
const payload = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok || !payload.ok) {
|
|
||||||
throw new Error(payload.error || "Render failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
setDirty(false);
|
|
||||||
setStatus(
|
|
||||||
`${payload.stdout ? `Модель сохранена. ${payload.stdout}` : "Модель сохранена, index.html пересобран."}${publishStatusText(payload)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveSelected(delta) {
|
function moveSelected(delta) {
|
||||||
|
|||||||
Reference in New Issue
Block a user