Update storage.js via upload script - 2026-11-04 09:41:37

This commit is contained in:
mike 2026-11-04 09:41:42 +08:00
parent dfe169d7d4
commit 17d1b41c82
1 changed files with 18 additions and 4 deletions

View File

@ -37,15 +37,21 @@ async function putNow(key, value) {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value, baseVersion: versions[key] }), body: JSON.stringify({ value, baseVersion: versions[key] }),
}); });
const body = await res.json().catch(() => ({})); const body = await res.json().catch(() => null);
if (!res.ok) { if (!res.ok) {
const e = new Error(body.error || `storage set failed: ${res.status}`); // 响应不是 JSON 的 413:请求在 Nginx 就被拦下了(client_max_body_size 比这份数据小),Node 根本没收到
const tooBig = res.status === 413;
const kb = Math.round(JSON.stringify(value).length / 1024);
const e = new Error(tooBig
? `数据太大(约 ${kb.toLocaleString()} KB),被服务器拒收(HTTP 413)。需要把 Nginx 的 client_max_body_size 调大,或者减少 HTML 片段里嵌入的图片`
: ((body && body.error) || `storage set failed: ${res.status}`));
e.key = key; e.key = key;
e.status = res.status; e.status = res.status;
e.conflict = !!body.conflict; e.conflict = !!(body && body.conflict);
e.tooBig = tooBig;
throw e; throw e;
} }
if (body.version !== undefined) versions[key] = Number(body.version); if (body && body.version !== undefined) versions[key] = Number(body.version);
lastSaved[key] = value; lastSaved[key] = value;
return body; return body;
} }
@ -58,8 +64,10 @@ async function pump(key) {
st.next = null; st.next = null;
try { try {
const r = job.value === lastSaved[key] ? { ok: true, unchanged: true } : await putNow(key, job.value); const r = job.value === lastSaved[key] ? { ok: true, unchanged: true } : await putNow(key, job.value);
delete failed[key];
job.waiters.forEach((w) => w.resolve(r)); job.waiters.forEach((w) => w.resolve(r));
} catch (e) { } catch (e) {
failed[key] = true;
job.waiters.forEach((w) => w.reject(e)); job.waiters.forEach((w) => w.reject(e));
} finally { } finally {
st.running = false; st.running = false;
@ -67,6 +75,12 @@ async function pump(key) {
} }
} }
// 还没存上的修改:正在发送 / 排队中的键,以及最近一次保存失败的键(保存成功后自动清掉)
const failed = {};
export function hasUnsavedChanges() {
return Object.values(saveState).some((st) => st.running || st.next) || Object.keys(failed).length > 0;
}
export function storageSet(key, value) { export function storageSet(key, value) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const st = saveState[key] || (saveState[key] = { running: false, next: null }); const st = saveState[key] || (saveState[key] = { running: false, next: null });