Commit 8ca07403 authored by tao355667's avatar tao355667

feat: switch article publishing to SSR

parent 6a8442a9
...@@ -6,4 +6,9 @@ CMS_SECRET=replace-with-openssl-rand-hex-32 ...@@ -6,4 +6,9 @@ CMS_SECRET=replace-with-openssl-rand-hex-32
CMS_API_KEY=replace-with-openssl-rand-hex-32 CMS_API_KEY=replace-with-openssl-rand-hex-32
# 本地默认放入已忽略的 .runtime;生产环境请改为 /root/qiyouxue/shared/ 下的绝对路径。 # 本地默认放入已忽略的 .runtime;生产环境请改为 /root/qiyouxue/shared/ 下的绝对路径。
CMS_DATA_DIR=.runtime/cms-data CMS_DATA_DIR=.runtime/cms-data
# 仅供代码部署或人工构建原子替换 dist 使用,CMS 内容操作不会获取此锁。
CMS_BUILD_LOCK=.runtime/site-build.lock CMS_BUILD_LOCK=.runtime/site-build.lock
# CMS 内容写入专用的跨进程非阻塞锁,不要与 CMS_BUILD_LOCK 共用。
CMS_CONTENT_LOCK=.runtime/cms-data/.content-write.lock
# 写进程异常退出后的陈旧锁恢复阈值,单位毫秒,默认 15 分钟。
CMS_CONTENT_LOCK_STALE_MS=900000
# 启优学学习资讯后台 # 启优学学习资讯后台
项目采用与官网同端口的 Astro 内容后台:Markdown 文件负责存储,Astro 同时提供管理 API 与静态页面生成。文章列表、分类页和详情页均预渲染为 HTML,便于 SEO 与 AI 搜索发现 项目采用与官网同端口的 Astro 内容后台:Markdown 文件负责存储,Astro 同时提供管理 API 与文章 SSR。稳定官网页面继续预渲染,文章列表、分类、分页和详情在请求时直接生成完整 HTML,便于 SEO 与 AI 搜索发现,也让发布内容无需重新构建整站即可上线
## 本地使用 ## 本地使用
...@@ -24,7 +24,9 @@ npm start ...@@ -24,7 +24,9 @@ npm start
- `CMS_SECRET`:会话签名密钥 - `CMS_SECRET`:会话签名密钥
- `CMS_API_KEY`:Bearer API 密钥 - `CMS_API_KEY`:Bearer API 密钥
- `CMS_DATA_DIR`:文章、分类与上传文件的持久化目录 - `CMS_DATA_DIR`:文章、分类与上传文件的持久化目录
- `CMS_BUILD_LOCK`:发布重建共享锁 - `CMS_BUILD_LOCK`:仅用于代码部署或人工执行构建时原子替换 `dist/`
- `CMS_CONTENT_LOCK`:CMS 内容写入的跨进程非阻塞锁,默认 `${CMS_DATA_DIR}/.content-write.lock`
- `CMS_CONTENT_LOCK_STALE_MS`:异常退出后的陈旧内容锁恢复阈值,默认 `900000` 毫秒
生产示例: 生产示例:
...@@ -32,6 +34,8 @@ npm start ...@@ -32,6 +34,8 @@ npm start
CMS_PORT=8793 CMS_PORT=8793
CMS_DATA_DIR=/root/qiyouxue/shared/cms-data CMS_DATA_DIR=/root/qiyouxue/shared/cms-data
CMS_BUILD_LOCK=/root/qiyouxue/shared/site-build.lock CMS_BUILD_LOCK=/root/qiyouxue/shared/site-build.lock
CMS_CONTENT_LOCK=/root/qiyouxue/shared/cms-data/.content-write.lock
CMS_CONTENT_LOCK_STALE_MS=900000
``` ```
## 内容工作流 ## 内容工作流
...@@ -44,7 +48,11 @@ CMS_BUILD_LOCK=/root/qiyouxue/shared/site-build.lock ...@@ -44,7 +48,11 @@ CMS_BUILD_LOCK=/root/qiyouxue/shared/site-build.lock
- 支持 Markdown、Word `.docx` 导入和内嵌图片提取 - 支持 Markdown、Word `.docx` 导入和内嵌图片提取
- 支持图片上传、Markdown 预览和后台密码修改 - 支持图片上传、Markdown 预览和后台密码修改
生产环境配置 `CMS_DATA_DIR` 后,内容持久化到仓库外,不随单目录部署被覆盖。发布、下架、删除与分类变更会触发共享锁保护的原子站点重建。 生产环境配置 `CMS_DATA_DIR` 后,内容持久化到仓库外,不随单目录部署被覆盖。发布、下架、删除与分类变更在 `CMS_CONTENT_LOCK` 临界区内通过同目录临时文件和原子 rename 写入;已有写操作进行中时接口立即返回 HTTP 409,不等待整站构建。锁文件记录 PID、创建时间与操作名称,支持异常进程和超时锁恢复。
文章公开入口采用 SSR:下一次请求会读取已发布目录并立即反映新内容。`llms.txt``llms-full.txt``/article-sitemap.xml` 同样动态生成并支持 ETag。进程内缓存使用文件的 `mtimeMs` 与大小校验,多进程也能发现文件替换或删除。
`CMS_BUILD_LOCK``CMS_CONTENT_LOCK` 职责必须分离:前者只允许部署脚本或人工 `npm run build` 使用,后者只允许 CMS 内容变更使用,不要配置成同一路径。
## API ## API
...@@ -74,4 +82,4 @@ Word 导入示例字段: ...@@ -74,4 +82,4 @@ Word 导入示例字段:
- Nginx 配置:`/etc/nginx/conf.d/qiyouxue.conf` - Nginx 配置:`/etc/nginx/conf.d/qiyouxue.conf`
- 公网域名:`qiyouxueedu.com` - 公网域名:`qiyouxueedu.com`
Runner 需具备安装固定 Nginx 配置、执行 `nginx -t` 与 reload 的最小 sudo 权限。生产密钥、上传文件、CMS 数据与构建锁必须位于 `shared/` Runner 需具备安装固定 Nginx 配置、执行 `nginx -t` 与 reload 的最小 sudo 权限。生产密钥、上传文件、CMS 数据、构建锁与内容写锁必须位于 `shared/`。建议内容写锁放在 `CMS_DATA_DIR` 内,确保所有 Node 进程看到同一锁文件
# 启优学企业官网 # 启优学企业官网
启优学一对一品牌官网。项目基于 Astro 5 + Node standalone adapter,包含品牌首页、学科辅导详情、教学服务、常见问题、联系页面、学习资讯 CMS、SEO/AI 可发现性、响应式适配、原子构建与 GitLab/Nginx 部署配置。 启优学一对一品牌官网。项目基于 Astro 5 + Node standalone adapter,稳定官网页面采用 SSG,学习资讯采用运行时 SSR;同时包含内容 CMS、SEO/AI 可发现性、响应式适配、原子构建与 GitLab/Nginx 部署配置。
## 本地运行(Node 20) ## 本地运行(Node 20)
...@@ -42,9 +42,9 @@ npm start ...@@ -42,9 +42,9 @@ npm start
- 页面级标题、描述、关键词、canonical、Open Graph 与 Twitter Card - 页面级标题、描述、关键词、canonical、Open Graph 与 Twitter Card
- EducationalOrganization、WebSite、WebPage、Service、FAQ、Article 和 Breadcrumb 结构化数据 - EducationalOrganization、WebSite、WebPage、Service、FAQ、Article 和 Breadcrumb 结构化数据
- sitemap、robots.txt、语义化页面、分类分页、`llms.txt``llms-full.txt` - 非文章静态 sitemap、动态文章 sitemap、robots.txt、语义化页面、SSR 分类分页、动态 `llms.txt``llms-full.txt`
- Astro 图片优化、响应式图片、移动端适配、减少动态效果偏好 - Astro 图片优化、响应式图片、移动端适配、减少动态效果偏好
- Astro standalone、原子构建、共享锁与 Nginx 反向代理 - Astro standalone、部署构建锁、CMS 内容写锁与 Nginx 反向代理
## 部署 ## 部署
...@@ -53,4 +53,4 @@ npm start ...@@ -53,4 +53,4 @@ npm start
- 站点域名:`qiyouxueedu.com` - 站点域名:`qiyouxueedu.com`
- 服务器目录:`/root/qiyouxue/current``/root/qiyouxue/shared` - 服务器目录:`/root/qiyouxue/current``/root/qiyouxue/shared`
生产部署前需在 `/root/qiyouxue/shared/.env` 配置独立的 `CMS_PASSWORD``CMS_SECRET``CMS_API_KEY``CMS_DATA_DIR``CMS_BUILD_LOCK` 生产部署前需在 `/root/qiyouxue/shared/.env` 配置独立的 `CMS_PASSWORD``CMS_SECRET``CMS_API_KEY``CMS_DATA_DIR``CMS_BUILD_LOCK``CMS_CONTENT_LOCK`。构建锁只保护部署时的 `dist/` 替换;内容锁只保护 CMS 的 Markdown 与分类写入,两者不要共用路径
...@@ -12,6 +12,9 @@ export default defineConfig({ ...@@ -12,6 +12,9 @@ export default defineConfig({
const pathname = new URL(page).pathname; const pathname = new URL(page).pathname;
return pathname !== "/404/" return pathname !== "/404/"
&& pathname !== "/admin/" && pathname !== "/admin/"
&& pathname !== "/articles"
&& !pathname.startsWith("/articles/")
&& pathname !== "/article-sitemap.xml"
&& !pathname.startsWith("/api/") && !pathname.startsWith("/api/")
&& !pathname.startsWith("/uploads/") && !pathname.startsWith("/uploads/")
&& !pathname.endsWith(".txt"); && !pathname.endsWith(".txt");
......
...@@ -439,7 +439,6 @@ function syncStaffRoleFields() { ...@@ -439,7 +439,6 @@ function syncStaffRoleFields() {
$("#teacher-modal-description").textContent = customerService ? "客服负责查看并处理分配给自己的用户咨询" : "运营负责学习资讯的创建、编辑与发布"; $("#teacher-modal-description").textContent = customerService ? "客服负责查看并处理分配给自己的用户咨询" : "运营负责学习资讯的创建、编辑与发布";
} }
$("#teacher-role").addEventListener("change", syncStaffRoleFields); $("#teacher-role").addEventListener("change", syncStaffRoleFields);
$("#close-teacher-modal").addEventListener("click", closeTeacherModal);
$("#cancel-teacher").addEventListener("click", closeTeacherModal); $("#cancel-teacher").addEventListener("click", closeTeacherModal);
$("#teacher-qr-button").addEventListener("click", () => $("#teacher-qr-file").click()); $("#teacher-qr-button").addEventListener("click", () => $("#teacher-qr-file").click());
async function uploadTeacherQr(file) { async function uploadTeacherQr(file) {
...@@ -474,7 +473,7 @@ $("#teacher-form").addEventListener("submit", async (event) => { ...@@ -474,7 +473,7 @@ $("#teacher-form").addEventListener("submit", async (event) => {
event.preventDefault(); event.preventDefault();
const id = $("#teacher-id").value; const id = $("#teacher-id").value;
const body = { role: $("#teacher-role").value, name: $("#teacher-name").value, username: $("#teacher-username").value, wechat: $("#teacher-wechat").value, sort: Number($("#teacher-sort").value || 1), password: $("#teacher-password").value, qrCodeUrl: $("#teacher-qr-url").value, enabled: $("#teacher-enabled").checked }; const body = { role: $("#teacher-role").value, name: $("#teacher-name").value, username: $("#teacher-username").value, wechat: $("#teacher-wechat").value, sort: Number($("#teacher-sort").value || 1), password: $("#teacher-password").value, qrCodeUrl: $("#teacher-qr-url").value, enabled: $("#teacher-enabled").checked };
const submit = event.submitter; const submit = event.submitter || $("#save-teacher");
submit.disabled = true; submit.disabled = true;
$("#teacher-error").textContent = ""; $("#teacher-error").textContent = "";
try { try {
...@@ -609,7 +608,7 @@ function listMoreActions(article) { ...@@ -609,7 +608,7 @@ function listMoreActions(article) {
async function publishFromList(article) { async function publishFromList(article) {
try { try {
await triggerBuild(`/articles/${article.slug}/publish`); await runContentAction(`/articles/${article.slug}/publish`);
await loadArticles(); await loadArticles();
} catch {} } catch {}
} }
...@@ -626,7 +625,7 @@ async function unpublishFromList(article) { ...@@ -626,7 +625,7 @@ async function unpublishFromList(article) {
const detail = article.publishStatus === "edited-draft" ? "未发布的修改会继续保留为草稿。" : "文章内容会继续保留为草稿。"; const detail = article.publishStatus === "edited-draft" ? "未发布的修改会继续保留为草稿。" : "文章内容会继续保留为草稿。";
if (!confirm(`确定将《${article.title}》从官网下架吗?${detail}`)) return; if (!confirm(`确定将《${article.title}》从官网下架吗?${detail}`)) return;
try { try {
await triggerBuild(`/articles/${article.slug}/unpublish`, { action: "下架" }); await runContentAction(`/articles/${article.slug}/unpublish`);
await loadArticles(); await loadArticles();
} catch {} } catch {}
} }
...@@ -637,7 +636,7 @@ async function deleteFromList(article) { ...@@ -637,7 +636,7 @@ async function deleteFromList(article) {
: `确定彻底删除《${article.title}》吗?线上版本和草稿都会删除,且无法恢复。`; : `确定彻底删除《${article.title}》吗?线上版本和草稿都会删除,且无法恢复。`;
if (!confirm(prompt)) return; if (!confirm(prompt)) return;
try { try {
await triggerBuild(`/articles/${article.slug}`, { action: "删除", method: "DELETE" }); await runContentAction(`/articles/${article.slug}`, { method: "DELETE" });
await loadArticles(); await loadArticles();
} catch {} } catch {}
} }
...@@ -703,7 +702,7 @@ async function createCategory() { ...@@ -703,7 +702,7 @@ async function createCategory() {
const name = input.value.trim(); const name = input.value.trim();
$("#category-error").textContent = ""; $("#category-error").textContent = "";
try { try {
await triggerBuild("/categories", { action: "添加分类", body: { name } }); await runContentAction("/categories", { body: { name } });
await loadCategories(); await loadCategories();
input.value = ""; input.value = "";
fillCategories(name); fillCategories(name);
...@@ -747,10 +746,10 @@ function categoryPanel(row, text) { ...@@ -747,10 +746,10 @@ function categoryPanel(row, text) {
return panel; return panel;
} }
async function runCategoryBuild(action, method, body) { async function runCategoryAction(method, body) {
$("#manager-category-error").textContent = ""; $("#manager-category-error").textContent = "";
try { try {
await triggerBuild("/categories", { action, method, body }); await runContentAction("/categories", { method, body });
await loadCategoryManager(); await loadCategoryManager();
await loadArticles(); await loadArticles();
} catch (error) { } catch (error) {
...@@ -778,7 +777,7 @@ function showRenameCategory(row, stat) { ...@@ -778,7 +777,7 @@ function showRenameCategory(row, stat) {
save.onclick = () => { save.onclick = () => {
const name = input.value.trim(); const name = input.value.trim();
if (!name || name === stat.name) return clearCategoryPanels(); if (!name || name === stat.name) return clearCategoryPanels();
runCategoryBuild("更新分类", "PATCH", { current: stat.name, name }); runCategoryAction("PATCH", { current: stat.name, name });
}; };
cancel.onclick = clearCategoryPanels; cancel.onclick = clearCategoryPanels;
input.addEventListener("keydown", (event) => { input.addEventListener("keydown", (event) => {
...@@ -804,7 +803,7 @@ function showDeleteCategory(row, stat) { ...@@ -804,7 +803,7 @@ function showDeleteCategory(row, stat) {
button.type = "button"; button.type = "button";
button.className = stat.count ? "" : "confirm-danger"; button.className = stat.count ? "" : "confirm-danger";
button.textContent = stat.count ? `迁移到“${replacement}”并删除` : "确认删除分类"; button.textContent = stat.count ? `迁移到“${replacement}”并删除` : "确认删除分类";
button.onclick = () => runCategoryBuild("删除分类", "DELETE", { name: stat.name, replacement }); button.onclick = () => runCategoryAction("DELETE", { name: stat.name, replacement });
actions.append(button); actions.append(button);
}); });
const cancel = document.createElement("button"); const cancel = document.createElement("button");
...@@ -866,7 +865,7 @@ $("#manager-add-category").addEventListener("click", async () => { ...@@ -866,7 +865,7 @@ $("#manager-add-category").addEventListener("click", async () => {
const name = input.value.trim(); const name = input.value.trim();
$("#manager-category-error").textContent = ""; $("#manager-category-error").textContent = "";
try { try {
await triggerBuild("/categories", { action: "添加分类", body: { name } }); await runContentAction("/categories", { body: { name } });
input.value = ""; input.value = "";
await loadCategoryManager(); await loadCategoryManager();
} catch (error) { $("#manager-category-error").textContent = error.message; } } catch (error) { $("#manager-category-error").textContent = error.message; }
...@@ -1007,9 +1006,9 @@ $("#publish").addEventListener("click", async () => { ...@@ -1007,9 +1006,9 @@ $("#publish").addEventListener("click", async () => {
$("#message").textContent = "正在保存草稿…"; $("#message").textContent = "正在保存草稿…";
try { try {
const slug = await save(); const slug = await save();
await triggerBuild(`/articles/${slug}/publish`); await runContentAction(`/articles/${slug}/publish`);
setEditorStatus("live"); setEditorStatus("live");
$("#message").textContent = "发布成功,官网已更新"; $("#message").textContent = "发布成功,文章已上线";
} catch (error) { $("#message").textContent = error.message; } } catch (error) { $("#message").textContent = error.message; }
}); });
...@@ -1031,7 +1030,7 @@ $("#unpublish").addEventListener("click", async () => { ...@@ -1031,7 +1030,7 @@ $("#unpublish").addEventListener("click", async () => {
$("#more-actions").open = false; $("#more-actions").open = false;
$("#message").textContent = "正在下架文章…"; $("#message").textContent = "正在下架文章…";
try { try {
await triggerBuild(`/articles/${editingSlug}/unpublish`, { action: "下架" }); await runContentAction(`/articles/${editingSlug}/unpublish`);
setEditorStatus("new-draft"); setEditorStatus("new-draft");
$("#message").textContent = "文章已下架,内容已保留为草稿。"; $("#message").textContent = "文章已下架,内容已保留为草稿。";
} catch (error) { $("#message").textContent = error.message; } } catch (error) { $("#message").textContent = error.message; }
...@@ -1046,7 +1045,7 @@ $("#delete-article").addEventListener("click", async () => { ...@@ -1046,7 +1045,7 @@ $("#delete-article").addEventListener("click", async () => {
$("#more-actions").open = false; $("#more-actions").open = false;
$("#message").textContent = "正在删除文章…"; $("#message").textContent = "正在删除文章…";
try { try {
await triggerBuild(`/articles/${editingSlug}`, { action: "删除", method: "DELETE" }); await runContentAction(`/articles/${editingSlug}`, { method: "DELETE" });
dirty = false; dirty = false;
editingSlug = null; editingSlug = null;
setView(false); setView(false);
...@@ -1101,31 +1100,8 @@ $("#file").addEventListener("change", async (event) => { ...@@ -1101,31 +1100,8 @@ $("#file").addEventListener("change", async (event) => {
} catch (error) { $("#upload-status").textContent = error.message; } } catch (error) { $("#upload-status").textContent = error.message; }
}); });
async function triggerBuild(endpoint, { action = "发布", method = "POST", body } = {}) { async function runContentAction(endpoint, { method = "POST", body } = {}) {
show("#build-modal"); return api(endpoint, { method, body });
hide("#close-modal");
$("#build-title").textContent = `正在${action}…`;
$("#build-log").textContent = "系统正在更新官网,请稍候。";
try {
await api(endpoint, { method, body });
} catch (error) {
$("#build-title").textContent = `${action}失败`;
$("#build-log").textContent = error.message;
show("#close-modal");
throw error;
}
while (true) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const state = await api("/build");
if (state.status === "building") continue;
if (state.ok) { hide("#build-modal"); return; }
$("#build-title").textContent = `${action}失败`;
$("#build-log").textContent = state.log || `${action}失败,请联系技术人员。`;
show("#close-modal");
throw new Error(`${action}失败,原文章已恢复,请检查操作日志。`);
}
} }
$("#close-modal").addEventListener("click", () => hide("#build-modal"));
boot(); boot();
...@@ -155,8 +155,6 @@ input:focus, textarea:focus, select:focus { outline: 2px solid rgba(20,115,230,. ...@@ -155,8 +155,6 @@ input:focus, textarea:focus, select:focus { outline: 2px solid rgba(20,115,230,.
.confirm-danger { color: white; background: var(--danger); } .confirm-danger { color: white; background: var(--danger); }
.replacement-options button { color: var(--primary-dark); background: white; border: 1px solid var(--border); } .replacement-options button { color: var(--primary-dark); background: white; border: 1px solid var(--border); }
.replacement-options button:hover { border-color: var(--primary); background: #eaf3ff; } .replacement-options button:hover { border-color: var(--primary); background: #eaf3ff; }
.build-card { width: min(780px, 100%); }
#build-log { max-height: 62vh; margin: 0; padding: 18px; overflow: auto; color: var(--muted); background: #f5f9fd; white-space: pre-wrap; font-size: 12px; }
.admin-shell { min-height: 100vh; padding-left: 238px; } .admin-shell { min-height: 100vh; padding-left: 238px; }
.sidebar { width: 238px; position: fixed; inset: 0 auto 0 0; z-index: 20; display: flex; flex-direction: column; color: #dbeaff; background: #102f55; box-shadow: 8px 0 28px rgba(10,40,75,.12); } .sidebar { width: 238px; position: fixed; inset: 0 auto 0 0; z-index: 20; display: flex; flex-direction: column; color: #dbeaff; background: #102f55; box-shadow: 8px 0 28px rgba(10,40,75,.12); }
.sidebar-brand { height: 86px; padding: 20px 24px; display: grid; align-content: center; border-bottom: 1px solid rgba(255,255,255,.1); } .sidebar-brand { height: 86px; padding: 20px 24px; display: grid; align-content: center; border-bottom: 1px solid rgba(255,255,255,.1); }
...@@ -239,11 +237,12 @@ input:focus, textarea:focus, select:focus { outline: 2px solid rgba(20,115,230,. ...@@ -239,11 +237,12 @@ input:focus, textarea:focus, select:focus { outline: 2px solid rgba(20,115,230,.
.teacher-card { width: min(760px, 100%); } .teacher-card { width: min(760px, 100%); }
.consultation-user-card { width: min(760px, 100%); } .consultation-user-card { width: min(760px, 100%); }
.teacher-card > .modal-head,.consultation-user-card > .modal-head { flex: 0 0 auto; } .teacher-card > .modal-head,.consultation-user-card > .modal-head { flex: 0 0 auto; }
.teacher-card > .teacher-modal-head { align-items: flex-start; justify-content: flex-start; flex-direction: column; gap: 13px; }
.teacher-modal-head > .teacher-modal-heading { display: grid; gap: 4px; }
.teacher-form { min-height: 0; padding: 20px; display: grid; gap: 18px; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; } .teacher-form { min-height: 0; padding: 20px; display: grid; gap: 18px; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
.teacher-form::-webkit-scrollbar { width: 8px; } .teacher-form::-webkit-scrollbar { width: 8px; }
.teacher-form::-webkit-scrollbar-track { background: #f3f6f9; } .teacher-form::-webkit-scrollbar-track { background: #f3f6f9; }
.teacher-form::-webkit-scrollbar-thumb { background: #bdc9d6; border: 2px solid #f3f6f9; border-radius: 999px; } .teacher-form::-webkit-scrollbar-thumb { background: #bdc9d6; border: 2px solid #f3f6f9; border-radius: 999px; }
.teacher-form > .password-actions { margin-top: 2px; }
.consultation-edit-section { padding: 17px; display: grid; gap: 15px; border: 1px solid var(--border); border-radius: 12px; background: #fbfcfe; } .consultation-edit-section { padding: 17px; display: grid; gap: 15px; border: 1px solid var(--border); border-radius: 12px; background: #fbfcfe; }
.consultation-edit-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; } .consultation-edit-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
.consultation-edit-heading strong { color: #203a57; font-size: 14px; } .consultation-edit-heading strong { color: #203a57; font-size: 14px; }
......
...@@ -4,3 +4,4 @@ Disallow: /admin/ ...@@ -4,3 +4,4 @@ Disallow: /admin/
Disallow: /api/ Disallow: /api/
Sitemap: https://qiyouxueedu.com/sitemap-index.xml Sitemap: https://qiyouxueedu.com/sitemap-index.xml
Sitemap: https://qiyouxueedu.com/article-sitemap.xml
---
import Base from "../layouts/Base.astro";
import Header from "./Header.astro";
import Footer from "./Footer.astro";
import { site } from "../data/site";
import { fmtDate } from "../lib/articles";
import type { PublishedArticleDetail } from "../lib/article-store";
const { entry } = Astro.props as { entry: PublishedArticleDetail };
const article = entry.data;
const date = fmtDate(article.date);
const modified = fmtDate(article.updated || article.date);
const title = `${article.title}|学习资讯|${site.brand.name}`;
const pageUrl = new URL(`/articles/${entry.id}/`, Astro.site).href;
const keywords = [article.category, article.title, "学习方法", "在线一对一", site.brand.name];
const jsonLd = [
{ "@context": "https://schema.org", "@type": "Article", headline: article.title, description: article.excerpt, datePublished: date, dateModified: modified, articleSection: article.category, inLanguage: "zh-CN", author: { "@type": "Organization", name: article.author }, publisher: { "@id": new URL("/#organization", Astro.site).href }, mainEntityOfPage: { "@type": "WebPage", "@id": `${pageUrl}#webpage` }, url: pageUrl },
{ "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: [{ "@type": "ListItem", position: 1, name: "首页", item: Astro.site?.href }, { "@type": "ListItem", position: 2, name: "学习资讯", item: new URL("/articles/", Astro.site).href }, { "@type": "ListItem", position: 3, name: article.title, item: pageUrl }] },
];
---
<Base {title} description={article.excerpt} {keywords} ogType="article" publishedTime={date} modifiedTime={modified} articleSection={article.category} articleAuthor={article.author} {jsonLd}>
<Header />
<main id="main-content" class="article-detail-page"><article><header class="article-detail-head"><div class="container article-detail-head__inner"><div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">学习资讯</a> / {article.category}</div><span class="article-detail-category">{article.category}</span><h1>{article.title}</h1><p>{article.excerpt}</p><div class="article-detail-meta"><time datetime={date}>{date}</time><span>{article.author}</span></div></div></header><div class="container article-detail-layout"><aside><a href="/articles/">← 返回学习资讯</a><p>分享学情判断、学习方法、阶段复习与在线一对一服务说明。</p></aside><div class="article-prose" set:html={entry.html}></div></div></article></main>
<Footer />
</Base>
--- ---
import Base from "../layouts/Base.astro"; import Header from "./Header.astro"; import Footer from "./Footer.astro"; import ArticleListing from "./ArticleListing.astro"; import { site } from "../data/site"; import { PAGE_SIZE, type Article, type CategoryInfo } from "../lib/articles"; import Base from "../layouts/Base.astro"; import Header from "./Header.astro"; import Footer from "./Footer.astro"; import ArticleListing from "./ArticleListing.astro"; import { site } from "../data/site"; import { PAGE_SIZE, type Article, type CategoryInfo } from "../lib/articles";
interface Props { items: Article[]; categories: CategoryInfo[]; totalCount: number; activeSlug: string | null; activeName: string | null; currentPage: number; lastPage: number; basePath: string; } interface Props { items: Article[]; categories: CategoryInfo[]; totalCount: number; activeSlug: string | null; activeName: string | null; currentPage: number; lastPage: number; basePath: string; }
const {items,categories,totalCount,activeSlug,activeName,currentPage,lastPage,basePath}=Astro.props as Props; const heading=activeName??"学习资讯"; const pageSuffix=currentPage>1?`|第${currentPage}页`:""; const title=`${heading}${pageSuffix}|${site.brand.name}`; const description=activeName?`启优学${activeName}分类文章,分享学情判断、学科方法与家庭学习规划。`:"启优学学习资讯:关于小初高学情判断、学习方法、阶段复习和在线一对一服务的公开说明。"; const keywords=[heading,"学习方法","学情诊断","在线一对一",site.brand.name]; const pageUrl=new URL(`${basePath}${currentPage>1?`/page/${currentPage}`:""}/`,Astro.site).href; const jsonLd={"@context":"https://schema.org","@type":"CollectionPage",name:heading,description,url:pageUrl,inLanguage:"zh-CN",mainEntity:{"@type":"ItemList",itemListElement:items.map((item,index)=>({"@type":"ListItem",position:(currentPage-1)*PAGE_SIZE+index+1,name:item.data.title,url:new URL(`/articles/${item.id}/`,Astro.site).href}))}}; const {items,categories,totalCount,activeSlug,activeName,currentPage,lastPage,basePath}=Astro.props as Props; const heading=activeName??"学习资讯"; const pageSuffix=currentPage>1?`|第${currentPage}页`:""; const title=`${heading}${pageSuffix}|${site.brand.name}`; const description=activeName?`启优学${activeName}分类文章,分享学情判断、学科方法与家庭学习规划。`:"启优学学习资讯:关于小初高学情判断、学习方法、阶段复习和在线一对一服务的公开说明。"; const keywords=[heading,"学习方法","学情诊断","在线一对一",site.brand.name]; const pagePath=(page:number)=>`${basePath}${page>1?`/page/${page}`:""}/`; const pageUrl=new URL(pagePath(currentPage),Astro.site).href; const prevUrl=currentPage>1?new URL(pagePath(currentPage-1),Astro.site).href:undefined; const nextUrl=currentPage<lastPage?new URL(pagePath(currentPage+1),Astro.site).href:undefined; const jsonLd={"@context":"https://schema.org","@type":"CollectionPage",name:heading,description,url:pageUrl,inLanguage:"zh-CN",mainEntity:{"@type":"ItemList",itemListElement:items.map((item,index)=>({"@type":"ListItem",position:(currentPage-1)*PAGE_SIZE+index+1,name:item.data.title,url:new URL(`/articles/${item.id}/`,Astro.site).href}))}};
--- ---
<Base {title} {description} {keywords} {jsonLd}><Header /><main id="main-content"><section class="page-hero"><div class="container page-hero__inner" data-reveal><div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">学习资讯</a>{activeName&&` / ${activeName}`}</div><h1>{heading}</h1><p>{description}</p></div></section><section class="section-pad section-blue"><div class="container"><ArticleListing {items} {categories} {totalCount} {activeSlug} {currentPage} {lastPage} {basePath} /></div></section></main><Footer /></Base> <Base {title} {description} {keywords} {prevUrl} {nextUrl} {jsonLd}><Header /><main id="main-content"><section class="page-hero"><div class="container page-hero__inner" data-reveal><div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">学习资讯</a>{activeName&&` / ${activeName}`}</div><h1>{heading}</h1><p>{description}</p></div></section><section class="section-pad section-blue"><div class="container"><ArticleListing {items} {categories} {totalCount} {activeSlug} {currentPage} {lastPage} {basePath} /></div></section></main><Footer /></Base>
---
import Base from "../layouts/Base.astro";
import Header from "./Header.astro";
import Footer from "./Footer.astro";
---
<Base title="页面未找到|启优学" description="你访问的页面不存在。" noindex>
<Header />
<main id="main-content">
<section class="not-found"><div class="container" data-reveal><span>404</span><h1>这一页暂时找不到了</h1><p>可以返回首页,继续了解启优学在线一对一课程与教学服务。</p><a class="button" href="/">返回首页</a></div></section>
</main>
<Footer />
</Base>
...@@ -9,6 +9,8 @@ const articleSchema = z.object({ ...@@ -9,6 +9,8 @@ const articleSchema = z.object({
category: z.string(), category: z.string(),
author: z.string(), author: z.string(),
excerpt: z.string(), excerpt: z.string(),
readingMinutes: z.number().int().positive().optional(),
featured: z.boolean().optional(),
status: z.enum(["draft", "published"]), status: z.enum(["draft", "published"]),
}); });
......
...@@ -5,8 +5,8 @@ import logo from "../../pic/启优学LOGO-透明.png"; ...@@ -5,8 +5,8 @@ import logo from "../../pic/启优学LOGO-透明.png";
import { getImage } from "astro:assets"; import { getImage } from "astro:assets";
import { site } from "../data/site"; import { site } from "../data/site";
import ContactDialog from "../components/ContactDialog.astro"; import ContactDialog from "../components/ContactDialog.astro";
interface Props { title: string; description?: string; keywords?: string | readonly string[]; image?: string; imageAlt?: string; ogType?: "website" | "article"; noindex?: boolean; publishedTime?: string; modifiedTime?: string; articleSection?: string; articleAuthor?: string; jsonLd?: Record<string, unknown> | Record<string, unknown>[]; } interface Props { title: string; description?: string; keywords?: string | readonly string[]; image?: string; imageAlt?: string; ogType?: "website" | "article"; noindex?: boolean; publishedTime?: string; modifiedTime?: string; articleSection?: string; articleAuthor?: string; prevUrl?: string; nextUrl?: string; jsonLd?: Record<string, unknown> | Record<string, unknown>[]; }
const { title, description = site.seo.description, keywords = site.seo.keywords, image = "/og-cover.svg", imageAlt = site.seo.imageAlt, ogType = "website", noindex = false, publishedTime, modifiedTime, articleSection, articleAuthor, jsonLd = [] } = Astro.props; const { title, description = site.seo.description, keywords = site.seo.keywords, image = "/og-cover.svg", imageAlt = site.seo.imageAlt, ogType = "website", noindex = false, publishedTime, modifiedTime, articleSection, articleAuthor, prevUrl, nextUrl, jsonLd = [] } = Astro.props;
const cleanMeta = (value: string) => value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(); const cleanMeta = (value: string) => value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
const metaTitle = cleanMeta(title); const metaDescription = cleanMeta(description); const metaTitle = cleanMeta(title); const metaDescription = cleanMeta(description);
const metaKeywords = (typeof keywords === "string" ? keywords.split(",") : keywords).map((keyword) => cleanMeta(keyword)).filter(Boolean).join(","); const metaKeywords = (typeof keywords === "string" ? keywords.split(",") : keywords).map((keyword) => cleanMeta(keyword)).filter(Boolean).join(",");
...@@ -17,6 +17,6 @@ const websiteLd = { "@context": "https://schema.org", "@type": "WebSite", "@id": ...@@ -17,6 +17,6 @@ const websiteLd = { "@context": "https://schema.org", "@type": "WebSite", "@id":
const webPageLd = { "@context": "https://schema.org", "@type": "WebPage", "@id": `${canonical}#webpage`, url: canonical, name: metaTitle, description: metaDescription, inLanguage: "zh-CN", isPartOf: { "@id": new URL("/#website", Astro.site).href }, about: { "@id": new URL("/#organization", Astro.site).href }, primaryImageOfPage: { "@type": "ImageObject", url: ogImage, caption: imageAlt } }; const webPageLd = { "@context": "https://schema.org", "@type": "WebPage", "@id": `${canonical}#webpage`, url: canonical, name: metaTitle, description: metaDescription, inLanguage: "zh-CN", isPartOf: { "@id": new URL("/#website", Astro.site).href }, about: { "@id": new URL("/#organization", Astro.site).href }, primaryImageOfPage: { "@type": "ImageObject", url: ogImage, caption: imageAlt } };
const pageLd = Array.isArray(jsonLd) ? jsonLd : [jsonLd]; const serializedLd = JSON.stringify([organizationLd, websiteLd, webPageLd, ...pageLd.filter((item) => Object.keys(item).length > 0)]).replace(/</g, "\\u003c"); const pageLd = Array.isArray(jsonLd) ? jsonLd : [jsonLd]; const serializedLd = JSON.stringify([organizationLd, websiteLd, webPageLd, ...pageLd.filter((item) => Object.keys(item).length > 0)]).replace(/</g, "\\u003c");
--- ---
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#1473E6" /><meta name="color-scheme" content="light" /><title>{metaTitle}</title><meta name="description" content={metaDescription} /><meta name="keywords" content={metaKeywords} /><meta name="robots" content={noindex ? "noindex,nofollow" : "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1"} /><link rel="canonical" href={canonical} /><link rel="icon" href="/favicon.png" type="image/png" sizes="512x512" /><link rel="apple-touch-icon" href="/favicon.png" /><link rel="manifest" href="/site.webmanifest" /><link rel="alternate" hreflang="zh-CN" href={canonical} /><link rel="alternate" hreflang="x-default" href={canonical} /><meta property="og:type" content={ogType} /><meta property="og:title" content={metaTitle} /><meta property="og:description" content={metaDescription} /><meta property="og:url" content={canonical} /><meta property="og:image" content={ogImage} /><meta property="og:image:alt" content={imageAlt} /><meta property="og:site_name" content={site.brand.name} /><meta property="og:locale" content="zh_CN" />{publishedTime && <meta property="article:published_time" content={publishedTime} />}{modifiedTime && <meta property="article:modified_time" content={modifiedTime} />}{articleSection && <meta property="article:section" content={articleSection} />}{articleAuthor && <meta property="article:author" content={articleAuthor} />}<meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content={metaTitle} /><meta name="twitter:description" content={metaDescription} /><meta name="twitter:image" content={ogImage} /><script type="application/ld+json" set:html={serializedLd} is:inline></script></head><body><a class="skip-link" href="#main-content">跳到主要内容</a><slot /><ContactDialog /><script is:inline> <!doctype html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#1473E6" /><meta name="color-scheme" content="light" /><title>{metaTitle}</title><meta name="description" content={metaDescription} /><meta name="keywords" content={metaKeywords} /><meta name="robots" content={noindex ? "noindex,nofollow" : "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1"} /><link rel="canonical" href={canonical} />{prevUrl && <link rel="prev" href={prevUrl} />}{nextUrl && <link rel="next" href={nextUrl} />}<link rel="icon" href="/favicon.png" type="image/png" sizes="512x512" /><link rel="apple-touch-icon" href="/favicon.png" /><link rel="manifest" href="/site.webmanifest" /><link rel="alternate" hreflang="zh-CN" href={canonical} /><link rel="alternate" hreflang="x-default" href={canonical} /><meta property="og:type" content={ogType} /><meta property="og:title" content={metaTitle} /><meta property="og:description" content={metaDescription} /><meta property="og:url" content={canonical} /><meta property="og:image" content={ogImage} /><meta property="og:image:alt" content={imageAlt} /><meta property="og:site_name" content={site.brand.name} /><meta property="og:locale" content="zh_CN" />{publishedTime && <meta property="article:published_time" content={publishedTime} />}{modifiedTime && <meta property="article:modified_time" content={modifiedTime} />}{articleSection && <meta property="article:section" content={articleSection} />}{articleAuthor && <meta property="article:author" content={articleAuthor} />}<meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content={metaTitle} /><meta name="twitter:description" content={metaDescription} /><meta name="twitter:image" content={ogImage} /><script type="application/ld+json" set:html={serializedLd} is:inline></script></head><body><a class="skip-link" href="#main-content">跳到主要内容</a><slot /><ContactDialog /><script is:inline>
const header=document.querySelector('[data-header]');const syncHeader=()=>header?.classList.toggle('is-scrolled',scrollY>12);addEventListener('scroll',syncHeader,{passive:true});syncHeader();const observer='IntersectionObserver'in window?new IntersectionObserver(entries=>entries.forEach(entry=>{if(entry.isIntersecting){entry.target.classList.add('is-visible');observer.unobserve(entry.target)}}),{threshold:.08}):null;document.querySelectorAll('[data-reveal]').forEach(el=>observer?observer.observe(el):el.classList.add('is-visible'));document.querySelectorAll('[data-mobile-nav] a').forEach(link=>link.addEventListener('click',()=>link.closest('details')?.removeAttribute('open')));const dialog=document.querySelector('[data-contact-dialog]');const teacherDialog=document.querySelector('[data-teacher-dialog]');const form=dialog?.querySelector('[data-consultation-form]');const copyWechat=teacherDialog?.querySelector('[data-copy-teacher-wechat]');const resetConsultation=()=>{form?.reset();const error=dialog?.querySelector('[data-consultation-error]');if(error)error.textContent=''};document.addEventListener('click',event=>{const trigger=event.target.closest('[data-open-contact]');if(!dialog||!trigger)return;event.preventDefault();resetConsultation();dialog.showModal();dialog.querySelector('#consultation-phone')?.focus()});dialog?.querySelector('[data-contact-dialog-close]')?.addEventListener('click',()=>dialog.close());teacherDialog?.querySelector('[data-teacher-dialog-close]')?.addEventListener('click',()=>teacherDialog.close());[dialog,teacherDialog].forEach(item=>item?.addEventListener('click',event=>{if(event.target===item)item.close()}));copyWechat?.addEventListener('click',async()=>{const value=teacherDialog.querySelector('[data-teacher-wechat]').textContent.trim();if(!value)return;try{await navigator.clipboard.writeText(value);copyWechat.textContent='已复制';setTimeout(()=>{copyWechat.textContent='复制'},1600)}catch{copyWechat.textContent='复制失败';setTimeout(()=>{copyWechat.textContent='复制'},1600)}});form?.addEventListener('submit',async event=>{event.preventDefault();const phone=String(new FormData(form).get('phone')||'').replace(/\s+/g,'');const error=dialog.querySelector('[data-consultation-error]');const submit=form.querySelector('button[type="submit"]');error.textContent='';if(!/^1[3-9]\d{9}$/.test(phone)){error.textContent='请输入正确的 11 位手机号';return}submit.disabled=true;submit.textContent='正在领取…';try{const response=await fetch('/api/cms/consultations/claim',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({phone,source:'免费领取学情分析',page:location.href})});const result=await response.json();if(!response.ok)throw new Error(result.error||'提交失败,请稍后重试');teacherDialog.querySelector('[data-teacher-name]').textContent=result.teacher.name;teacherDialog.querySelector('[data-teacher-title]').textContent=result.teacher.title;teacherDialog.querySelector('[data-teacher-qr]').src=result.teacher.qrCodeUrl;teacherDialog.querySelector('[data-teacher-wechat]').textContent=result.teacher.wechat||'';teacherDialog.querySelector('[data-teacher-wechat-wrap]').classList.toggle('hidden',!result.teacher.wechat);copyWechat.textContent='复制';dialog.close();teacherDialog.showModal()}catch(requestError){error.textContent=requestError.message}finally{submit.disabled=false;submit.textContent='立即领取'}}); const header=document.querySelector('[data-header]');const syncHeader=()=>header?.classList.toggle('is-scrolled',scrollY>12);addEventListener('scroll',syncHeader,{passive:true});syncHeader();const observer='IntersectionObserver'in window?new IntersectionObserver(entries=>entries.forEach(entry=>{if(entry.isIntersecting){entry.target.classList.add('is-visible');observer.unobserve(entry.target)}}),{threshold:.08}):null;document.querySelectorAll('[data-reveal]').forEach(el=>observer?observer.observe(el):el.classList.add('is-visible'));document.querySelectorAll('[data-mobile-nav] a').forEach(link=>link.addEventListener('click',()=>link.closest('details')?.removeAttribute('open')));const dialog=document.querySelector('[data-contact-dialog]');const teacherDialog=document.querySelector('[data-teacher-dialog]');const form=dialog?.querySelector('[data-consultation-form]');const copyWechat=teacherDialog?.querySelector('[data-copy-teacher-wechat]');const resetConsultation=()=>{form?.reset();const error=dialog?.querySelector('[data-consultation-error]');if(error)error.textContent=''};document.addEventListener('click',event=>{const trigger=event.target.closest('[data-open-contact]');if(!dialog||!trigger)return;event.preventDefault();resetConsultation();dialog.showModal();dialog.querySelector('#consultation-phone')?.focus()});dialog?.querySelector('[data-contact-dialog-close]')?.addEventListener('click',()=>dialog.close());teacherDialog?.querySelector('[data-teacher-dialog-close]')?.addEventListener('click',()=>teacherDialog.close());[dialog,teacherDialog].forEach(item=>item?.addEventListener('click',event=>{if(event.target===item)item.close()}));copyWechat?.addEventListener('click',async()=>{const value=teacherDialog.querySelector('[data-teacher-wechat]').textContent.trim();if(!value)return;try{await navigator.clipboard.writeText(value);copyWechat.textContent='已复制';setTimeout(()=>{copyWechat.textContent='复制'},1600)}catch{copyWechat.textContent='复制失败';setTimeout(()=>{copyWechat.textContent='复制'},1600)}});form?.addEventListener('submit',async event=>{event.preventDefault();const phone=String(new FormData(form).get('phone')||'').replace(/\s+/g,'');const error=dialog.querySelector('[data-consultation-error]');const submit=form.querySelector('button[type="submit"]');error.textContent='';if(!/^1[3-9]\d{9}$/.test(phone)){error.textContent='请输入正确的 11 位手机号';return}submit.disabled=true;submit.textContent='正在领取…';try{const response=await fetch('/api/cms/consultations/claim',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({phone,source:'免费领取学情分析',page:location.href})});const result=await response.json();if(!response.ok)throw new Error(result.error||'提交失败,请稍后重试');teacherDialog.querySelector('[data-teacher-name]').textContent=result.teacher.name;teacherDialog.querySelector('[data-teacher-title]').textContent=result.teacher.title;teacherDialog.querySelector('[data-teacher-qr]').src=result.teacher.qrCodeUrl;teacherDialog.querySelector('[data-teacher-wechat]').textContent=result.teacher.wechat||'';teacherDialog.querySelector('[data-teacher-wechat-wrap]').classList.toggle('hidden',!result.teacher.wechat);copyWechat.textContent='复制';dialog.close();teacherDialog.showModal()}catch(requestError){error.textContent=requestError.message}finally{submit.disabled=false;submit.textContent='立即领取'}});
</script></body></html> </script></body></html>
This diff is collapsed.
...@@ -3,7 +3,6 @@ import { marked } from "marked"; ...@@ -3,7 +3,6 @@ import { marked } from "marked";
import { import {
StoreError, StoreError,
addCategory, addCategory,
createContentSnapshot,
deleteArticle, deleteArticle,
discardDraft, discardDraft,
generateSlug, generateSlug,
...@@ -36,7 +35,7 @@ import { ...@@ -36,7 +35,7 @@ import {
updateConsultationTeacher, updateConsultationTeacher,
verifyTeacherCredentials, verifyTeacherCredentials,
} from "./consultation-store"; } from "./consultation-store";
import { buildSiteAtomic, tryAcquireSiteBuildLock, withSiteBuildLock } from "../../scripts/site-build.mjs"; import { ContentWriteLockBusyError, withContentWriteLock } from "./content-lock";
const SECRET = process.env.CMS_SECRET || crypto.randomBytes(32).toString("hex"); const SECRET = process.env.CMS_SECRET || crypto.randomBytes(32).toString("hex");
const API_KEY = process.env.CMS_API_KEY || ""; const API_KEY = process.env.CMS_API_KEY || "";
...@@ -49,15 +48,6 @@ const loginAttempts = new Map<string, { count: number; first: number; blockedUnt ...@@ -49,15 +48,6 @@ const loginAttempts = new Map<string, { count: number; first: number; blockedUnt
type AuthContext = type AuthContext =
| { role: "admin"; id: "admin"; name: "管理员" } | { role: "admin"; id: "admin"; name: "管理员" }
| { role: "customer_service" | "operator"; id: string; name: string }; | { role: "customer_service" | "operator"; id: string; name: string };
type BuildState = {
status: "idle" | "building" | "success" | "error";
ok: boolean | null;
log: string;
startedAt: string | null;
finishedAt: string | null;
};
let buildState: BuildState = { status: "idle", ok: null, log: "", startedAt: null, finishedAt: null };
const json = (data: unknown, status = 200, headers?: HeadersInit) => Response.json(data, { status, headers }); const json = (data: unknown, status = 200, headers?: HeadersInit) => Response.json(data, { status, headers });
const safeEqual = (leftValue: unknown, rightValue: unknown): boolean => { const safeEqual = (leftValue: unknown, rightValue: unknown): boolean => {
...@@ -188,51 +178,6 @@ function requireSlug(value: string | undefined): string { ...@@ -188,51 +178,6 @@ function requireSlug(value: string | undefined): string {
return slug; return slug;
} }
async function startContentBuild(change: () => Promise<void>): Promise<boolean> {
if (buildState.status === "building") return false;
const releaseLock = await tryAcquireSiteBuildLock();
if (!releaseLock) return false;
buildState = { status: "building", ok: null, log: "", startedAt: new Date().toISOString(), finishedAt: null };
void (async () => {
const snapshot = await createContentSnapshot();
try {
await change();
const log = await buildSiteAtomic();
buildState = { status: "success", ok: true, log, startedAt: buildState.startedAt, finishedAt: new Date().toISOString() };
} catch (error) {
let rollbackMessage = "";
try { await snapshot.restore(); } catch (rollbackError) {
rollbackMessage = `\n内容回滚失败:${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`;
}
const message = error instanceof Error ? error.message : String(error);
const log = typeof error === "object" && error && "log" in error ? String(error.log || "") : "";
buildState = {
status: "error",
ok: false,
log: `${log}${log ? "\n" : ""}${message}${rollbackMessage}`,
startedAt: buildState.startedAt,
finishedAt: new Date().toISOString(),
};
}
})().finally(releaseLock).catch((error) => {
buildState = {
status: "error",
ok: false,
log: error instanceof Error ? error.message : String(error),
startedAt: buildState.startedAt,
finishedAt: new Date().toISOString(),
};
});
return true;
}
async function startOrConflict(change: () => Promise<void>): Promise<Response> {
if (!await startContentBuild(change)) {
return json({ error: "网站正在部署或生成静态页面,本次操作未受理,请稍后重试" }, 409, { "Retry-After": "5" });
}
return json({ ok: true, status: "building" });
}
export async function handleCmsApi(request: Request, routeValue: string, clientAddress = "unknown"): Promise<Response> { export async function handleCmsApi(request: Request, routeValue: string, clientAddress = "unknown"): Promise<Response> {
const route = routeValue.replace(/^\/+|\/+$/g, ""); const route = routeValue.replace(/^\/+|\/+$/g, "");
const parts = route.split("/").filter(Boolean); const parts = route.split("/").filter(Boolean);
...@@ -358,26 +303,26 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -358,26 +303,26 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
if (method === "GET") return json({ categories: await getCategoryNames(), stats: await getCategoryStats() }); if (method === "GET") return json({ categories: await getCategoryNames(), stats: await getCategoryStats() });
const body = await bodyOf(request); const body = await bodyOf(request);
if (method === "POST") { if (method === "POST") {
return startOrConflict(async () => { await addCategory(body.name); }); return json({ ok: true, categories: await withContentWriteLock("添加文章分类", () => addCategory(body.name)) }, 201);
} }
if (method === "PATCH") { if (method === "PATCH") {
return startOrConflict(async () => { await renameCategory(body.current, body.name); }); return json({ ok: true, categories: await withContentWriteLock("重命名文章分类", () => renameCategory(body.current, body.name)) });
} }
if (method === "DELETE") { if (method === "DELETE") {
return startOrConflict(async () => { await removeCategory(body.name, body.replacement); }); return json({ ok: true, categories: await withContentWriteLock("删除文章分类", () => removeCategory(body.name, body.replacement)) });
} }
} }
if (route === "build" && method === "GET") return json(buildState);
if (route === "articles") { if (route === "articles") {
if (method === "GET") return json(await listWorkingArticles()); if (method === "GET") return json(await listWorkingArticles());
if (method === "POST") { if (method === "POST") {
const body = await bodyOf(request); const body = await bodyOf(request);
if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题"); if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题");
if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文"); if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文");
const { slug, article } = await withContentWriteLock("新建文章草稿", async () => {
const slug = await generateSlug(body.category); const slug = await generateSlug(body.category);
const article = await withSiteBuildLock(() => writeArticle(slug, body, true)); return { slug, article: await writeArticle(slug, body, true) };
});
return json({ ok: true, slug, publishStatus: await getPublishStatus(article) }, 201); return json({ ok: true, slug, publishStatus: await getPublishStatus(article) }, 201);
} }
} }
...@@ -395,7 +340,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -395,7 +340,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
return url; return url;
}); });
const title = String(body.title || "").trim() || converted.suggestedTitle; const title = String(body.title || "").trim() || converted.suggestedTitle;
const imported = await withSiteBuildLock(async () => { const imported = await withContentWriteLock("导入文章草稿", async () => {
const slug = await generateSlug(body.category); const slug = await generateSlug(body.category);
createdSlug = slug; createdSlug = slug;
const article = await writeArticle(slug, { title, category: body.category, body: converted.body }, true); const article = await writeArticle(slug, { title, category: body.category, body: converted.body }, true);
...@@ -411,7 +356,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -411,7 +356,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
}, 201); }, 201);
} catch (error) { } catch (error) {
if (createdSlug) { if (createdSlug) {
await withSiteBuildLock(() => discardDraft(createdSlug as string)).catch(() => {}); await withContentWriteLock("清理导入失败的文章草稿", () => discardDraft(createdSlug as string)).catch(() => {});
} }
await Promise.allSettled(uploadedUrls.map((url) => removeUpload(url))); await Promise.allSettled(uploadedUrls.map((url) => removeUpload(url)));
throw error; throw error;
...@@ -421,13 +366,15 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -421,13 +366,15 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
if (parts[0] === "articles" && parts[1]) { if (parts[0] === "articles" && parts[1]) {
const slug = requireSlug(parts[1]); const slug = requireSlug(parts[1]);
if (parts.length === 3 && parts[2] === "draft" && method === "DELETE") { if (parts.length === 3 && parts[2] === "draft" && method === "DELETE") {
return json({ ok: true, ...await withSiteBuildLock(() => discardDraft(slug)) }); return json({ ok: true, ...await withContentWriteLock("放弃文章草稿修改", () => discardDraft(slug)) });
} }
if (parts.length === 3 && parts[2] === "publish" && method === "POST") { if (parts.length === 3 && parts[2] === "publish" && method === "POST") {
return startOrConflict(async () => { await publishArticle(slug); }); await withContentWriteLock("发布文章", () => publishArticle(slug));
return json({ ok: true, publishStatus: "live", message: "发布成功,文章已上线" });
} }
if (parts.length === 3 && parts[2] === "unpublish" && method === "POST") { if (parts.length === 3 && parts[2] === "unpublish" && method === "POST") {
return startOrConflict(async () => { await unpublishArticle(slug); }); await withContentWriteLock("下架文章", () => unpublishArticle(slug));
return json({ ok: true, publishStatus: "new-draft", message: "文章已下架" });
} }
if (parts.length === 2 && method === "GET") { if (parts.length === 2 && method === "GET") {
const article = await readWorkingArticle(slug); const article = await readWorkingArticle(slug);
...@@ -437,11 +384,12 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -437,11 +384,12 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
const body = await bodyOf(request); const body = await bodyOf(request);
if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题"); if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题");
if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文"); if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文");
const article = await withSiteBuildLock(() => writeArticle(slug, body)); const article = await withContentWriteLock("保存文章草稿", () => writeArticle(slug, body));
return json({ ok: true, slug, publishStatus: await getPublishStatus(article) }); return json({ ok: true, slug, publishStatus: await getPublishStatus(article) });
} }
if (parts.length === 2 && method === "DELETE") { if (parts.length === 2 && method === "DELETE") {
return startOrConflict(async () => { await deleteArticle(slug); }); await withContentWriteLock("删除文章", () => deleteArticle(slug));
return json({ ok: true, message: "文章已删除" });
} }
} }
...@@ -457,6 +405,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA ...@@ -457,6 +405,7 @@ export async function handleCmsApi(request: Request, routeValue: string, clientA
return json({ error: "接口不存在" }, 404); return json({ error: "接口不存在" }, 404);
} catch (error) { } catch (error) {
if (error instanceof ContentWriteLockBusyError) return json({ error: error.message, ...error.details }, 409, { "Retry-After": "1" });
if (error instanceof StoreError) return json({ error: error.message, ...error.details }, error.status); if (error instanceof StoreError) return json({ error: error.message, ...error.details }, error.status);
if ((error as NodeJS.ErrnoException).code === "ENOENT") return json({ error: "文章不存在" }, 404); if ((error as NodeJS.ErrnoException).code === "ENOENT") return json({ error: "文章不存在" }, 404);
console.error(error); console.error(error);
......
import crypto from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
const ROOT = process.cwd();
const DATA_ROOT = path.resolve(process.env.CMS_DATA_DIR || path.join(ROOT, ".runtime", "cms-data"));
export const CONTENT_LOCK_FILE = path.resolve(process.env.CMS_CONTENT_LOCK || path.join(DATA_ROOT, ".content-write.lock"));
const RECOVERY_LOCK_FILE = `${CONTENT_LOCK_FILE}.recovery`;
const parsedStaleMs = Number(process.env.CMS_CONTENT_LOCK_STALE_MS || 15 * 60 * 1000);
const STALE_MS = Number.isFinite(parsedStaleMs) && parsedStaleMs >= 30_000 ? parsedStaleMs : 15 * 60 * 1000;
interface LockRecord {
token: string;
pid: number;
hostname: string;
createdAt: string;
operation: string;
}
export class ContentWriteLockBusyError extends Error {
status = 409;
details = { retryAfter: 1 };
constructor(operation?: string) {
super(operation ? `另一项内容操作正在进行(${operation}),请稍后重试` : "另一项内容操作正在进行,请稍后重试");
this.name = "ContentWriteLockBusyError";
}
}
function processIsAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try { process.kill(pid, 0); return true; } catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
async function readLock(): Promise<LockRecord | null> {
try {
const parsed = JSON.parse(await fs.readFile(CONTENT_LOCK_FILE, "utf8")) as Partial<LockRecord>;
if (!parsed.token || !parsed.createdAt) return null;
return parsed as LockRecord;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
return null;
}
}
function isStale(lock: LockRecord | null): boolean {
if (!lock) return false;
const age = Date.now() - new Date(lock.createdAt).valueOf();
if (!Number.isFinite(age) || age > STALE_MS) return true;
return lock.hostname === os.hostname() && !processIsAlive(Number(lock.pid));
}
async function unreadableLockIsStale(): Promise<boolean> {
try {
const stat = await fs.stat(CONTENT_LOCK_FILE);
return Date.now() - stat.mtimeMs > STALE_MS;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "ENOENT";
}
}
async function recoverStaleLock(): Promise<boolean> {
let recoveryHandle: fs.FileHandle | null = null;
try {
recoveryHandle = await fs.open(RECOVERY_LOCK_FILE, "wx");
const before = await readLock();
if (before ? !isStale(before) : !await unreadableLockIsStale()) return false;
const current = await readLock();
const currentIsStale = current ? isStale(current) : await unreadableLockIsStale();
if ((before?.token || null) !== (current?.token || null) || !currentIsStale) return false;
await fs.unlink(CONTENT_LOCK_FILE).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
});
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") return false;
throw error;
} finally {
if (recoveryHandle) {
await recoveryHandle.close().catch(() => {});
await fs.unlink(RECOVERY_LOCK_FILE).catch(() => {});
}
}
}
async function acquireContentWriteLock(operation: string): Promise<() => Promise<void>> {
await fs.mkdir(path.dirname(CONTENT_LOCK_FILE), { recursive: true });
const record: LockRecord = {
token: crypto.randomBytes(16).toString("hex"),
pid: process.pid,
hostname: os.hostname(),
createdAt: new Date().toISOString(),
operation,
};
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
const handle = await fs.open(CONTENT_LOCK_FILE, "wx");
await handle.writeFile(`${JSON.stringify(record)}\n`);
await handle.close();
return async () => {
const current = await readLock();
if (current?.token === record.token) {
await fs.unlink(CONTENT_LOCK_FILE).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
});
}
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
if (attempt === 0 && await recoverStaleLock()) continue;
const current = await readLock();
throw new ContentWriteLockBusyError(current?.operation);
}
}
throw new ContentWriteLockBusyError();
}
export async function withContentWriteLock<T>(operation: string, task: () => Promise<T>): Promise<T> {
const release = await acquireContentWriteLock(operation);
try {
return await task();
} finally {
await release();
}
}
import crypto from "node:crypto";
export function etagOf(content: string): string {
return `"${crypto.createHash("sha256").update(content).digest("base64url")}"`;
}
export function conditionalTextResponse(request: Request, content: string, contentType: string): Response {
const etag = etagOf(content);
const headers = {
"Cache-Control": "public, max-age=60, must-revalidate",
"Content-Type": contentType,
ETag: etag,
};
if (request.headers.get("if-none-match")?.split(",").map((value) => value.trim()).includes(etag)) {
return new Response(null, { status: 304, headers });
}
return new Response(content, { headers });
}
--- ---
import Base from "../layouts/Base.astro"; import Header from "../components/Header.astro"; import Footer from "../components/Footer.astro"; import NotFoundPage from "../components/NotFoundPage.astro";
--- ---
<Base title="页面未找到|启优学" description="你访问的页面不存在。" noindex><Header /><main id="main-content"><section class="not-found"><div class="container" data-reveal><span>404</span><h1>这一页暂时找不到了</h1><p>可以返回首页,继续了解启优学在线一对一课程与教学服务。</p><a class="button" href="/">返回首页</a></div></section></main><Footer /></Base> <NotFoundPage />
...@@ -132,7 +132,10 @@ ...@@ -132,7 +132,10 @@
<div id="teacher-modal" class="modal hidden"> <div id="teacher-modal" class="modal hidden">
<div class="modal-card teacher-card"> <div class="modal-card teacher-card">
<div class="modal-head"><div><strong id="teacher-modal-title">添加后台账号</strong><small id="teacher-modal-description">按职责分配客服或运营权限</small></div><button id="close-teacher-modal" class="ghost small" type="button">关闭</button></div> <div class="modal-head teacher-modal-head">
<div class="teacher-modal-heading"><strong id="teacher-modal-title">添加后台账号</strong><small id="teacher-modal-description">按职责分配客服或运营权限</small></div>
<div class="modal-head-actions"><button id="cancel-teacher" class="ghost small" type="button">取消</button><button id="save-teacher" class="primary small" type="submit" form="teacher-form">保存账号</button></div>
</div>
<form id="teacher-form" class="teacher-form"> <form id="teacher-form" class="teacher-form">
<input id="teacher-id" type="hidden" /> <input id="teacher-id" type="hidden" />
<div class="form-grid"> <div class="form-grid">
...@@ -150,7 +153,6 @@ ...@@ -150,7 +153,6 @@
</label> </label>
<label class="switch-row"><input id="teacher-enabled" type="checkbox" checked /><span id="teacher-enabled-label">启用并参与轮询分配</span></label> <label class="switch-row"><input id="teacher-enabled" type="checkbox" checked /><span id="teacher-enabled-label">启用并参与轮询分配</span></label>
<p id="teacher-error" class="error"></p> <p id="teacher-error" class="error"></p>
<div class="password-actions"><button id="cancel-teacher" class="ghost" type="button">取消</button><button class="primary" type="submit">保存账号</button></div>
</form> </form>
</div> </div>
</div> </div>
...@@ -206,12 +208,6 @@ ...@@ -206,12 +208,6 @@
</form> </form>
</div> </div>
</div> </div>
<div id="build-modal" class="modal hidden">
<div class="modal-card build-card">
<div><strong id="build-title">正在处理</strong><button id="close-modal" class="ghost small hidden" type="button">关闭</button></div>
<pre id="build-log">系统正在更新官网,请稍候。</pre>
</div>
</div>
<script is:inline src="/admin/app.js"></script> <script is:inline src="/admin/app.js"></script>
</body> </body>
</html> </html>
import type { APIRoute } from "astro";
import { getCategoryNames, getCategories, getPublishedArticles, lastPageOf } from "../lib/articles";
import { conditionalTextResponse } from "../lib/http-cache";
export const prerender = false;
const escapeXml = (value: string) => value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&apos;");
export const GET: APIRoute = async ({ request, site }) => {
const origin = site ?? new URL("https://qiyouxueedu.com");
const articles = await getPublishedArticles();
const categories = getCategories(articles, await getCategoryNames());
const paths = new Set<string>(["/articles/"]);
for (let page = 2; page <= lastPageOf(articles.length); page += 1) paths.add(`/articles/page/${page}/`);
for (const article of articles) paths.add(`/articles/${article.id}/`);
for (const category of categories) {
paths.add(`/articles/topic/${category.slug}/`);
for (let page = 2; page <= lastPageOf(category.count); page += 1) paths.add(`/articles/topic/${category.slug}/page/${page}/`);
}
const rows = [...paths].map((pathname) => ` <url><loc>${escapeXml(new URL(pathname, origin).href)}</loc></url>`);
const xml = [`<?xml version="1.0" encoding="UTF-8"?>`, `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`, ...rows, `</urlset>`, ""].join("\n");
return conditionalTextResponse(request, xml, "application/xml; charset=utf-8");
};
--- ---
import Base from "../../layouts/Base.astro"; import Header from "../../components/Header.astro"; import Footer from "../../components/Footer.astro"; import { site } from "../../data/site"; import { getPublishedArticle, getPublishedArticles } from "../../lib/article-store"; import { fmtDate } from "../../lib/articles"; import ArticleDetailView from "../../components/ArticleDetailView.astro";
type ArticleDetail = NonNullable<Awaited<ReturnType<typeof getPublishedArticle>>>; import NotFoundPage from "../../components/NotFoundPage.astro";
export async function getStaticPaths() { const articles = await getPublishedArticles(); return Promise.all(articles.map(async (article) => ({ params: { slug: article.id }, props: { entry: await getPublishedArticle(article.id) } }))); } import { getPublishedArticle, safeSlug } from "../../lib/article-store";
const { entry } = Astro.props as { entry: ArticleDetail }; const article = entry.data; const date = fmtDate(article.date); const title = `${article.title}|学习资讯|${site.brand.name}`; const pageUrl = new URL(`/articles/${entry.id}/`, Astro.site).href;
const modified = fmtDate(article.updated || article.date); export const prerender = false;
const keywords = [article.category, article.title, "学习方法", "在线一对一", site.brand.name];
const jsonLd = [{ "@context": "https://schema.org", "@type": "Article", headline: article.title, description: article.excerpt, datePublished: date, dateModified: modified, articleSection: article.category, inLanguage: "zh-CN", author: { "@type": "Organization", name: article.author }, publisher: { "@id": new URL("/#organization", Astro.site).href }, mainEntityOfPage: { "@type": "WebPage", "@id": `${pageUrl}#webpage` }, url: pageUrl }, { "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: [{ "@type": "ListItem", position: 1, name: "首页", item: Astro.site?.href }, { "@type": "ListItem", position: 2, name: "学习资讯", item: new URL("/articles/", Astro.site).href }, { "@type": "ListItem", position: 3, name: article.title, item: pageUrl }] }]; const slug = safeSlug(Astro.params.slug);
const entry = slug ? await getPublishedArticle(slug) : null;
if (!entry) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
--- ---
<Base {title} description={article.excerpt} {keywords} ogType="article" publishedTime={date} modifiedTime={modified} articleSection={article.category} articleAuthor={article.author} {jsonLd}><Header /><main id="main-content" class="article-detail-page"><article><header class="article-detail-head"><div class="container article-detail-head__inner"><div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">学习资讯</a> / {article.category}</div><span class="article-detail-category">{article.category}</span><h1>{article.title}</h1><p>{article.excerpt}</p><div class="article-detail-meta"><time datetime={date}>{date}</time><span>{article.author}</span></div></div></header><div class="container article-detail-layout"><aside><a href="/articles/">← 返回学习资讯</a><p>分享学情判断、学习方法、阶段复习与在线一对一服务说明。</p></aside><div class="article-prose" set:html={entry.html}></div></div></article></main><Footer /></Base> {entry ? <ArticleDetailView {entry} /> : <NotFoundPage />}
...@@ -2,8 +2,11 @@ ...@@ -2,8 +2,11 @@
import ArticlesView from "../../components/ArticlesView.astro"; import ArticlesView from "../../components/ArticlesView.astro";
import { getPublishedArticles, getCategoryNames, getCategories, pageSlice, lastPageOf } from "../../lib/articles"; import { getPublishedArticles, getCategoryNames, getCategories, pageSlice, lastPageOf } from "../../lib/articles";
export const prerender = false;
const all = await getPublishedArticles(); const all = await getPublishedArticles();
const categories = getCategories(all, await getCategoryNames()); const categories = getCategories(all, await getCategoryNames());
const items = pageSlice(all, 1); const items = pageSlice(all, 1);
Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
--- ---
<ArticlesView items={items} categories={categories} totalCount={all.length} activeSlug={null} activeName={null} currentPage={1} lastPage={lastPageOf(all.length)} basePath="/articles" /> <ArticlesView items={items} categories={categories} totalCount={all.length} activeSlug={null} activeName={null} currentPage={1} lastPage={lastPageOf(all.length)} basePath="/articles" />
--- ---
import ArticlesView from "../../../components/ArticlesView.astro"; import ArticlesView from "../../../components/ArticlesView.astro";
import NotFoundPage from "../../../components/NotFoundPage.astro";
import { getPublishedArticles, getCategoryNames, getCategories, pageSlice, lastPageOf } from "../../../lib/articles"; import { getPublishedArticles, getCategoryNames, getCategories, pageSlice, lastPageOf } from "../../../lib/articles";
export async function getStaticPaths() { export const prerender = false;
const articles = await getPublishedArticles();
return Array.from({ length: Math.max(0, lastPageOf(articles.length) - 1) }, (_, index) => ({
params: { page: String(index + 2) },
}));
}
const all = await getPublishedArticles(); const all = await getPublishedArticles();
const page = Number(Astro.params.page); const pageValue = String(Astro.params.page || "");
const page = /^\d+$/.test(pageValue) ? Number(pageValue) : 0;
const lastPage = lastPageOf(all.length);
const valid = Number.isSafeInteger(page) && page >= 2 && page <= lastPage;
if (!valid) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
const categories = valid ? getCategories(all, await getCategoryNames()) : [];
--- ---
<ArticlesView items={pageSlice(all, page)} categories={getCategories(all, await getCategoryNames())} totalCount={all.length} activeSlug={null} activeName={null} currentPage={page} lastPage={lastPageOf(all.length)} basePath="/articles" /> {valid
? <ArticlesView items={pageSlice(all, page)} {categories} totalCount={all.length} activeSlug={null} activeName={null} currentPage={page} {lastPage} basePath="/articles" />
: <NotFoundPage />}
--- ---
import ArticlesView from "../../../../components/ArticlesView.astro"; import ArticlesView from "../../../../components/ArticlesView.astro";
import { categoryToSlug, getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../lib/articles"; import NotFoundPage from "../../../../components/NotFoundPage.astro";
import { getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../lib/articles";
export async function getStaticPaths() { export const prerender = false;
return (await getCategoryNames()).map((categoryName) => ({
params: { slug: categoryToSlug(categoryName) },
props: { categoryName },
}));
}
const all = await getPublishedArticles(); const all = await getPublishedArticles();
const categories = getCategories(all, await getCategoryNames()); const categoryNames = await getCategoryNames();
const categoryName = String(Astro.props.categoryName || slugToCategory(Astro.params.slug!, categories.map((item) => item.name)) || ""); const categories = getCategories(all, categoryNames);
const filtered = all.filter((item) => item.data.category === categoryName); const routeSlug = String(Astro.params.slug || "");
const categoryName = slugToCategory(routeSlug, categoryNames);
const valid = Boolean(categoryName);
const filtered = valid ? all.filter((item) => item.data.category === categoryName) : [];
if (!valid) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
--- ---
<ArticlesView items={pageSlice(filtered, 1)} categories={categories} totalCount={all.length} activeSlug={Astro.params.slug!} activeName={categoryName} currentPage={1} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${Astro.params.slug}`} /> {valid
? <ArticlesView items={pageSlice(filtered, 1)} {categories} totalCount={all.length} activeSlug={routeSlug} activeName={categoryName!} currentPage={1} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${routeSlug}`} />
: <NotFoundPage />}
--- ---
import ArticlesView from "../../../../../components/ArticlesView.astro"; import ArticlesView from "../../../../../components/ArticlesView.astro";
import NotFoundPage from "../../../../../components/NotFoundPage.astro";
import { getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../../lib/articles"; import { getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../../lib/articles";
export async function getStaticPaths() { export const prerender = false;
const articles = await getPublishedArticles();
const categories = getCategories(articles, await getCategoryNames());
const paths: Array<{ params: { slug: string; page: string }; props: { categoryName: string } }> = [];
for (const category of categories) {
for (let page = 2; page <= lastPageOf(category.count); page += 1) {
paths.push({ params: { slug: category.slug, page: String(page) }, props: { categoryName: category.name } });
}
}
return paths;
}
const all = await getPublishedArticles(); const all = await getPublishedArticles();
const categories = getCategories(all, await getCategoryNames()); const categoryNames = await getCategoryNames();
const categoryName = String(Astro.props.categoryName || slugToCategory(Astro.params.slug!, categories.map((item) => item.name)) || ""); const categories = getCategories(all, categoryNames);
const filtered = all.filter((item) => item.data.category === categoryName); const routeSlug = String(Astro.params.slug || "");
const page = Number(Astro.params.page); const categoryName = slugToCategory(routeSlug, categoryNames);
const filtered = categoryName ? all.filter((item) => item.data.category === categoryName) : [];
const pageValue = String(Astro.params.page || "");
const page = /^\d+$/.test(pageValue) ? Number(pageValue) : 0;
const lastPage = lastPageOf(filtered.length);
const valid = Boolean(categoryName) && Number.isSafeInteger(page) && page >= 2 && page <= lastPage;
if (!valid) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
--- ---
<ArticlesView items={pageSlice(filtered, page)} categories={categories} totalCount={all.length} activeSlug={Astro.params.slug!} activeName={categoryName} currentPage={page} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${Astro.params.slug}`} /> {valid
? <ArticlesView items={pageSlice(filtered, page)} {categories} totalCount={all.length} activeSlug={routeSlug} activeName={categoryName!} currentPage={page} {lastPage} basePath={`/articles/topic/${routeSlug}`} />
: <NotFoundPage />}
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { site } from "../data/site"; import { site } from "../data/site";
import { getPublishedArticles } from "../lib/articles"; import { getPublishedArticles } from "../lib/articles";
import { getPublishedArticleSource } from "../lib/article-store";
import { conditionalTextResponse } from "../lib/http-cache";
export const prerender = true; export const prerender = false;
export const GET: APIRoute = async ({ site: configuredSite }) => { export const GET: APIRoute = async ({ request, site: configuredSite }) => {
const articles = await getPublishedArticles(); const articles = await getPublishedArticles();
const details = (await Promise.all(articles.map((article) => getPublishedArticleSource(article.id))))
.filter((article): article is NonNullable<Awaited<ReturnType<typeof getPublishedArticleSource>>> => article !== null);
const origin = configuredSite ?? new URL("https://qiyouxueedu.com"); const origin = configuredSite ?? new URL("https://qiyouxueedu.com");
const url = (pathname: string) => new URL(pathname, origin).href; const url = (pathname: string) => new URL(pathname, origin).href;
const lines = [ const lines = [
...@@ -20,8 +24,8 @@ export const GET: APIRoute = async ({ site: configuredSite }) => { ...@@ -20,8 +24,8 @@ export const GET: APIRoute = async ({ site: configuredSite }) => {
"## 教学服务能力", "", ...site.about.technologies.map((technology) => `- ${technology}`), "", "## 教学服务能力", "", ...site.about.technologies.map((technology) => `- ${technology}`), "",
"## 学习服务流程", "", ...site.workflow.map((step) => `- ${step.title}${step.desc}`), "", "## 学习服务流程", "", ...site.workflow.map((step) => `- ${step.title}${step.desc}`), "",
"## 常见问题", "", `常见问题页面:${url("/faq/")}`, "", ...site.faq.flatMap((item) => [`### ${item.q}`, "", item.a, ""]), "## 常见问题", "", `常见问题页面:${url("/faq/")}`, "", ...site.faq.flatMap((item) => [`### ${item.q}`, "", item.a, ""]),
"## 学习资讯全文", "", ...articles.flatMap((article) => [`### ${article.data.title}`, "", `页面:${url(`/articles/${article.id}/`)}`, `分类:${article.data.category}`, `作者:${article.data.author}`, `发布日期:${article.data.date.toISOString().slice(0, 10)}`, `更新时间:${article.data.updated.toISOString().slice(0, 10)}`, "", article.data.excerpt, "", article.body, ""]), "## 学习资讯全文", "", ...details.flatMap((article) => [`### ${article.data.title}`, "", `页面:${url(`/articles/${article.id}/`)}`, `分类:${article.data.category}`, `作者:${article.data.author}`, `发布日期:${article.data.date.toISOString().slice(0, 10)}`, `更新时间:${article.data.updated.toISOString().slice(0, 10)}`, "", article.data.excerpt, "", article.body, ""]),
"## 联系方式", "", `联系页面:${url("/contact/")}`, `咨询电话:${site.contact.phone}`, `联系邮箱:${site.contact.email}`, `公司地址:${site.contact.address}`, `内容矩阵:${site.contact.socials.join("、")}`, "", "## 联系方式", "", `联系页面:${url("/contact/")}`, `咨询电话:${site.contact.phone}`, `联系邮箱:${site.contact.email}`, `公司地址:${site.contact.address}`, `内容矩阵:${site.contact.socials.join("、")}`, "",
]; ];
return new Response(lines.join("\n"), { headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" } }); return conditionalTextResponse(request, lines.join("\n"), "text/plain; charset=utf-8");
}; };
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { site } from "../data/site"; import { site } from "../data/site";
import { getPublishedArticles } from "../lib/articles"; import { getPublishedArticles } from "../lib/articles";
import { conditionalTextResponse } from "../lib/http-cache";
export const prerender = true; export const prerender = false;
export const GET: APIRoute = async ({ site: configuredSite }) => { export const GET: APIRoute = async ({ request, site: configuredSite }) => {
const articles = await getPublishedArticles(); const articles = await getPublishedArticles();
const origin = configuredSite ?? new URL("https://qiyouxueedu.com"); const origin = configuredSite ?? new URL("https://qiyouxueedu.com");
const url = (pathname: string) => new URL(pathname, origin).href; const url = (pathname: string) => new URL(pathname, origin).href;
...@@ -31,5 +32,5 @@ export const GET: APIRoute = async ({ site: configuredSite }) => { ...@@ -31,5 +32,5 @@ export const GET: APIRoute = async ({ site: configuredSite }) => {
`- [完整站点内容](${url("/llms-full.txt")})`, `- [完整站点内容](${url("/llms-full.txt")})`,
"", `咨询电话:${site.contact.phone}`, `联系邮箱:${site.contact.email}`, `公司地址:${site.contact.address}`, "", `咨询电话:${site.contact.phone}`, `联系邮箱:${site.contact.email}`, `公司地址:${site.contact.address}`,
]; ];
return new Response(lines.join("\n"), { headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" } }); return conditionalTextResponse(request, lines.join("\n"), "text/plain; charset=utf-8");
}; };
This diff is collapsed.
import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import fs from "node:fs/promises";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { after, test } from "node:test";
const dataDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "qiyouxue-article-ssr-"));
const buildLock = path.join(dataDirectory, "site-build.lock");
const contentLock = path.join(dataDirectory, ".content-write.lock");
process.env.CMS_DATA_DIR = dataDirectory;
process.env.CMS_BUILD_LOCK = buildLock;
process.env.CMS_CONTENT_LOCK = contentLock;
process.env.CMS_CONTENT_LOCK_STALE_MS = "30000";
process.env.CMS_API_KEY = "article-ssr-test-key";
process.env.CMS_SECRET = "article-ssr-test-secret";
process.env.CMS_PASSWORD = "article-ssr-test-password";
await fs.writeFile(buildLock, "deployment-build-lock-sentinel\n");
const [{ handleCmsApi }, articleStore, { categoryToSlug }, { withContentWriteLock }] = await Promise.all([
import("../src/lib/cms-api.ts"),
import("../src/lib/article-store.ts"),
import("../src/lib/articles.ts"),
import("../src/lib/content-lock.ts"),
]);
function apiRequest(route: string, method = "GET", body?: Record<string, unknown>): Promise<Response> {
return handleCmsApi(new Request(`http://localhost/api/cms/${route}`, {
method,
headers: { Authorization: `Bearer ${process.env.CMS_API_KEY}`, ...(body ? { "Content-Type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined,
}), route);
}
async function availablePort(): Promise<number> {
const server = net.createServer();
await new Promise<void>((resolve, reject) => server.once("error", reject).listen(0, "127.0.0.1", resolve));
const address = server.address();
const port = typeof address === "object" && address ? address.port : 0;
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
return port;
}
let devServer: ChildProcess | null = null;
let serverOutput = "";
const port = await availablePort();
const origin = `http://127.0.0.1:${port}`;
async function startDevServer(): Promise<void> {
const astro = path.join(process.cwd(), "node_modules", "astro", "astro.js");
devServer = spawn(process.execPath, [astro, "dev", "--host", "127.0.0.1", "--port", String(port)], {
cwd: process.cwd(),
env: { ...process.env },
stdio: ["ignore", "pipe", "pipe"],
});
devServer.stdout?.on("data", (chunk) => { serverOutput += chunk.toString(); });
devServer.stderr?.on("data", (chunk) => { serverOutput += chunk.toString(); });
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
if (devServer.exitCode !== null) throw new Error(`Astro dev server exited early:\n${serverOutput}`);
try {
const response = await fetch(`${origin}/articles/`);
if (response.ok) return;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`Astro dev server did not start:\n${serverOutput}`);
}
await startDevServer();
after(async () => {
if (devServer && devServer.exitCode === null) {
devServer.kill("SIGTERM");
await new Promise((resolve) => devServer?.once("exit", resolve));
}
await fs.rm(dataDirectory, { recursive: true, force: true });
});
test("article lists read metadata without rendering every Markdown body", async () => {
articleStore.resetArticleStoreDiagnostics();
const articles = await articleStore.getPublishedArticles();
assert.ok(articles.length > 0);
assert.equal(articleStore.getArticleStoreDiagnostics().markdownRenderCount, 0);
assert.equal("body" in articles[0], false);
});
test("drafts and invalid public article routes return real 404 responses", async () => {
const created = await apiRequest("articles", "POST", {
title: "SSR 即时发布验收文章",
category: "学习方法",
body: "# SSR 完整正文\n\n这是无需构建即可上线的唯一正文标记。",
});
assert.equal(created.status, 201);
const result = await created.json() as { slug: string };
assert.match(result.slug, /^[a-z0-9]+(?:-[a-z0-9]+)*$/);
process.env.TEST_ARTICLE_SLUG = result.slug;
for (const pathname of [
`/articles/${result.slug}/`,
"/articles/not_valid/",
"/articles/does-not-exist/",
"/articles/page/1/",
"/articles/page/9999/",
"/articles/topic/not-a-category/",
]) {
const response = await fetch(`${origin}${pathname}`);
assert.equal(response.status, 404, pathname);
}
});
test("publishing is immediately visible in SSR HTML, lists, category, llms and sitemap without a build", async () => {
const slug = process.env.TEST_ARTICLE_SLUG!;
const published = await apiRequest(`articles/${slug}/publish`, "POST");
assert.equal(published.status, 200);
assert.deepEqual(await published.json(), { ok: true, publishStatus: "live", message: "发布成功,文章已上线" });
const detail = await fetch(`${origin}/articles/${slug}/`);
const detailHtml = await detail.text();
assert.equal(detail.status, 200);
assert.match(detail.headers.get("content-type") || "", /^text\/html/);
assert.match(detailHtml, /<div class="article-prose"[^>]*>[\s\S]*<h1>SSR 完整正文<\/h1>/);
assert.match(detailHtml, /<link rel="canonical" href="https:\/\/qiyouxueedu\.com\/articles\//);
assert.match(detailHtml, /"@type":"Article"/);
assert.match(detailHtml, /"@type":"BreadcrumbList"/);
const listHtml = await (await fetch(`${origin}/articles/`)).text();
assert.match(listHtml, /SSR 即时发布验收文章/);
const categorySlug = categoryToSlug("学习方法");
const category = await fetch(`${origin}/articles/topic/${categorySlug}/`);
assert.equal(category.status, 200);
assert.match(await category.text(), /SSR 即时发布验收文章/);
const llms = await fetch(`${origin}/llms.txt`);
assert.match(llms.headers.get("content-type") || "", /^text\/plain; charset=utf-8/);
assert.match(await llms.text(), /SSR 即时发布验收文章/);
const full = await fetch(`${origin}/llms-full.txt`);
const etag = full.headers.get("etag");
assert.ok(etag);
assert.match(await full.text(), /这是无需构建即可上线的唯一正文标记/);
const notModified = await fetch(`${origin}/llms-full.txt`, { headers: { "If-None-Match": etag! } });
assert.equal(notModified.status, 304);
const sitemap = await fetch(`${origin}/article-sitemap.xml`);
assert.equal(sitemap.headers.get("content-type"), "application/xml; charset=utf-8");
assert.match(await sitemap.text(), new RegExp(`/articles/${slug}/`));
assert.equal(await fs.readFile(buildLock, "utf8"), "deployment-build-lock-sentinel\n");
assert.equal((await apiRequest("build")).status, 404);
});
test("the content write lock returns 409 without changing the draft or acquiring the build lock", async () => {
const slug = process.env.TEST_ARTICLE_SLUG!;
const draftFile = path.join(dataDirectory, "articles", `${slug}.md`);
const before = await fs.readFile(draftFile, "utf8");
let releaseHold!: () => void;
const held = withContentWriteLock("并发锁验收", () => new Promise<void>((resolve) => { releaseHold = resolve; }));
const deadline = Date.now() + 3000;
while (Date.now() < deadline) {
try { await fs.access(contentLock); break; } catch { await new Promise((resolve) => setTimeout(resolve, 10)); }
}
const conflict = await apiRequest(`articles/${slug}`, "PUT", {
title: "不应写入的并发修改",
category: "学习方法",
body: "不应写入",
});
assert.equal(conflict.status, 409);
assert.match((await conflict.json() as { error: string }).error, /内容操作正在进行/);
releaseHold();
await held;
assert.equal(await fs.readFile(draftFile, "utf8"), before);
assert.equal(await fs.readFile(buildLock, "utf8"), "deployment-build-lock-sentinel\n");
});
test("a stale content lock is recovered without deleting a newer owner's lock", async () => {
await fs.writeFile(contentLock, JSON.stringify({
token: "stale-test-token",
pid: 99999999,
hostname: os.hostname(),
createdAt: new Date(Date.now() - 60_000).toISOString(),
operation: "已退出的写操作",
}));
let entered = false;
await withContentWriteLock("陈旧锁恢复验收", async () => { entered = true; });
assert.equal(entered, true);
await assert.rejects(fs.access(contentLock), { code: "ENOENT" });
});
test("unpublishing and deleting immediately removes an article from every public entry", async () => {
const slug = process.env.TEST_ARTICLE_SLUG!;
const unpublished = await apiRequest(`articles/${slug}/unpublish`, "POST");
assert.equal(unpublished.status, 200);
assert.equal((await fetch(`${origin}/articles/${slug}/`)).status, 404);
assert.doesNotMatch(await (await fetch(`${origin}/articles/`)).text(), /SSR 即时发布验收文章/);
assert.doesNotMatch(await (await fetch(`${origin}/articles/topic/${categoryToSlug("学习方法")}/`)).text(), /SSR 即时发布验收文章/);
assert.doesNotMatch(await (await fetch(`${origin}/llms.txt`)).text(), /SSR 即时发布验收文章/);
assert.doesNotMatch(await (await fetch(`${origin}/llms-full.txt`)).text(), /这是无需构建即可上线的唯一正文标记/);
assert.doesNotMatch(await (await fetch(`${origin}/article-sitemap.xml`)).text(), new RegExp(`/articles/${slug}/`));
const deleted = await apiRequest(`articles/${slug}`, "DELETE");
assert.equal(deleted.status, 200);
assert.equal((await apiRequest(`articles/${slug}`)).status, 404);
assert.equal(await fs.readFile(buildLock, "utf8"), "deployment-build-lock-sentinel\n");
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment