仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
114 lines
4.1 KiB
JavaScript
114 lines
4.1 KiB
JavaScript
'use strict';
|
||
const { today, AUTOMATIC_SNAPSHOT_LAST_SUCCESS, automaticSnapshotKey } = require('./ledger');
|
||
const TIME_ZONE = 'Asia/Shanghai',
|
||
DAILY_TIME = '23:50',
|
||
RETRY_MS = 60000;
|
||
const recordDTO = value =>
|
||
value && typeof value.date === 'string' && typeof value.scheduledFor === 'string' && typeof value.savedAt === 'string'
|
||
? { date: value.date, scheduledFor: value.scheduledFor, savedAt: value.savedAt }
|
||
: null;
|
||
|
||
class InventorySnapshotScheduler {
|
||
constructor(
|
||
ledger,
|
||
{ clock = () => new Date(), logger = console.error, setTimer = setTimeout, clearTimer = clearTimeout } = {},
|
||
) {
|
||
this.ledger = ledger;
|
||
this.clock = clock;
|
||
this.logger = logger;
|
||
this.setTimer = setTimer;
|
||
this.clearTimer = clearTimer;
|
||
this.running = false;
|
||
this.busy = false;
|
||
this.timer = null;
|
||
this.lastError = null;
|
||
this.retry = null;
|
||
}
|
||
moment() {
|
||
const actual = new Date(this.clock());
|
||
if (!Number.isFinite(actual.getTime())) throw new Error('自动库存快照时钟无效');
|
||
const date = today(actual),
|
||
scheduledFor = date + 'T' + DAILY_TIME + ':00+08:00';
|
||
return { actual, date, scheduledFor, dueAt: Date.parse(scheduledFor) };
|
||
}
|
||
start() {
|
||
if (this.running) return false;
|
||
this.running = true;
|
||
this.tick();
|
||
this.arm();
|
||
return true;
|
||
}
|
||
stop() {
|
||
this.running = false;
|
||
if (this.timer !== null) this.clearTimer(this.timer);
|
||
this.timer = null;
|
||
}
|
||
arm() {
|
||
if (!this.running || this.timer !== null) return;
|
||
const { actual, dueAt, date } = this.moment(),
|
||
retryAt = this.retry?.date === date ? this.retry.at : null;
|
||
const target =
|
||
actual.getTime() < dueAt ? dueAt : retryAt && retryAt > actual.getTime() ? retryAt : actual.getTime() + RETRY_MS;
|
||
this.timer = this.setTimer(
|
||
() => {
|
||
this.timer = null;
|
||
this.tick();
|
||
this.arm();
|
||
},
|
||
Math.min(RETRY_MS, Math.max(1, target - actual.getTime())),
|
||
);
|
||
this.timer?.unref?.();
|
||
}
|
||
tick() {
|
||
if (!this.running || this.busy) return { saved: false, reason: 'stopped-or-busy' };
|
||
const { actual, date, dueAt } = this.moment(),
|
||
instant = actual.getTime();
|
||
if (instant < dueAt) return { saved: false, reason: 'not-due' };
|
||
if (this.retry?.date === date && instant < this.retry.at) return { saved: false, reason: 'retry-wait' };
|
||
this.busy = true;
|
||
try {
|
||
const result = this.ledger.saveAutomaticInventorySnapshot(date, this.clock);
|
||
this.lastError = null;
|
||
this.retry = null;
|
||
return result;
|
||
} catch (error) {
|
||
const failedAt = new Date(this.clock());
|
||
this.lastError = {
|
||
date,
|
||
attemptedAt: failedAt.toISOString(),
|
||
message: '自动库存快照保存失败,请检查磁盘空间或目录权限;系统会在当日每分钟重试。',
|
||
};
|
||
this.retry = { date, at: failedAt.getTime() + RETRY_MS };
|
||
try {
|
||
this.logger(`自动库存快照保存失败(${date},${error.code || '保存未完成'}),当日每分钟重试。`);
|
||
} catch {}
|
||
return { saved: false, reason: 'failed' };
|
||
} finally {
|
||
this.busy = false;
|
||
}
|
||
}
|
||
status() {
|
||
const { actual, date, dueAt } = this.moment(),
|
||
completed = recordDTO(this.ledger.meta(automaticSnapshotKey(date))),
|
||
lastSuccess = recordDTO(this.ledger.meta(AUTOMATIC_SNAPSHOT_LAST_SUCCESS));
|
||
const lastError = !completed && this.lastError?.date === date ? { ...this.lastError } : null;
|
||
let nextAttemptAt = null;
|
||
if (this.running && !completed) {
|
||
const target = actual.getTime() < dueAt ? dueAt : this.retry?.date === date ? this.retry.at : actual.getTime();
|
||
// 跨过午夜就等待新一天,不能把第二天的重试伪装成前一天的定时快照。
|
||
if (today(new Date(target)) === date) nextAttemptAt = new Date(target).toISOString();
|
||
}
|
||
return {
|
||
enabled: this.running,
|
||
time: DAILY_TIME,
|
||
timeZone: TIME_ZONE,
|
||
date,
|
||
status: !this.running ? 'stopped' : completed ? 'saved' : lastError ? 'failed' : 'waiting',
|
||
lastSuccess,
|
||
lastError,
|
||
nextAttemptAt,
|
||
};
|
||
}
|
||
}
|
||
module.exports = { InventorySnapshotScheduler, TIME_ZONE, DAILY_TIME, RETRY_MS };
|