diff --git a/backend/package.json b/backend/package.json index 068dd2dd..9f691334 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.23.17", + "version": "2.23.18", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/restful/artifacts.js b/backend/src/restful/artifacts.js index 5742f216..037d3927 100644 --- a/backend/src/restful/artifacts.js +++ b/backend/src/restful/artifacts.js @@ -20,6 +20,10 @@ import { } from '@/restful/errors'; import Gist from '@/utils/gist'; import { archiveArtifact } from '@/utils/archive'; +import { + normalizeArtifactCron, + refreshArtifactCronJobs, +} from '@/utils/artifact-cron'; const ARTIFACT_GIST_PLACEHOLDER_FILENAME = '.sub-store-placeholder'; const ARTIFACT_GIST_PLACEHOLDER_CONTENT = [ @@ -109,6 +113,7 @@ async function restoreArtifacts(_, res) { } }); $.write(allArtifacts, ARTIFACTS_KEY); + refreshArtifactCronJobs(); } catch (err) { $.error(`查找 Sub-Store Gist 时发生错误: ${err.message ?? err}`); throw err; @@ -133,9 +138,15 @@ function getAllArtifacts(req, res) { } function replaceArtifact(req, res) { - const allArtifacts = req.body; - $.write(allArtifacts, ARTIFACTS_KEY); - success(res); + try { + const allArtifacts = req.body; + allArtifacts.forEach(normalizeArtifactCron); + $.write(allArtifacts, ARTIFACTS_KEY); + refreshArtifactCronJobs(); + success(res); + } catch (error) { + failed(res, error); + } } async function getArtifact(req, res) { @@ -188,8 +199,15 @@ function updateArtifact(req, res) { ); return; } + try { + normalizeArtifactCron(newArtifact); + } catch (error) { + failed(res, error); + return; + } updateByName(allArtifacts, oldName, newArtifact); $.write(allArtifacts, ARTIFACTS_KEY); + refreshArtifactCronJobs(); success(res, newArtifact); } else { failed( @@ -244,6 +262,7 @@ function createArtifactItem(artifact) { } $.info(`正在创建远程配置:${artifact.name}`); + normalizeArtifactCron(artifact); const allArtifacts = $.read(ARTIFACTS_KEY); if (findByName(allArtifacts, artifact.name)) { throw new RequestInvalidError( @@ -253,6 +272,7 @@ function createArtifactItem(artifact) { } insertByPosition(allArtifacts, artifact, getCreateItemPosition()); $.write(allArtifacts, ARTIFACTS_KEY); + refreshArtifactCronJobs(); return artifact; } @@ -299,6 +319,7 @@ async function deleteArtifactItem(name) { } deleteByName(allArtifacts, name); $.write(allArtifacts, ARTIFACTS_KEY); + refreshArtifactCronJobs(); return { artifact, remote, diff --git a/backend/src/restful/index.js b/backend/src/restful/index.js index 804687ac..cdd698ac 100644 --- a/backend/src/restful/index.js +++ b/backend/src/restful/index.js @@ -4,9 +4,14 @@ import express from '@/vendor/express'; import $ from '@/core/app'; import migrate from '@/utils/migration'; import download, { downloadFile } from '@/utils/download'; -import { syncArtifacts, produceArtifact } from '@/restful/sync'; +import { + syncArtifacts, + produceArtifact, + syncArtifactItem, +} from '@/restful/sync'; import { gistBackupAction } from '@/restful/miscs'; import { TOKENS_KEY, SETTINGS_KEY } from '@/constants'; +import { startArtifactCronJobs } from '@/utils/artifact-cron'; import registerSubscriptionRoutes from './subscriptions'; import registerCollectionRoutes from './collections'; @@ -145,6 +150,8 @@ export default function serve() { $app.start(); if ($.env.isNode) { + startArtifactCronJobs(syncArtifactItem); + // Deprecated: SUB_STORE_BACKEND_CRON, SUB_STORE_CRON const backend_sync_cron = eval( 'process.env.SUB_STORE_BACKEND_SYNC_CRON', @@ -158,7 +165,7 @@ export default function serve() { async function () { try { $.info(`[SYNC CRON] ${backend_sync_cron} started`); - await syncArtifacts(); + await syncArtifacts({ skipCronArtifacts: true }); $.info(`[SYNC CRON] ${backend_sync_cron} finished`); } catch (e) { $.error( diff --git a/backend/src/restful/sync.js b/backend/src/restful/sync.js index 6bab632a..b9ed1107 100644 --- a/backend/src/restful/sync.js +++ b/backend/src/restful/sync.js @@ -9,7 +9,11 @@ import { } from '@/constants'; import { failed, success } from '@/restful/response'; import { InternalServerError, ResourceNotFoundError } from '@/restful/errors'; -import { findByName } from '@/utils/database'; +import { + formatArtifactLogName, + shouldSyncArtifactInGlobalCron, +} from '@/utils/artifact-cron'; +import { findByName, updateByName } from '@/utils/database'; import download from '@/utils/download'; import { ProxyUtils } from '@/core/proxy-utils'; import { RuleUtils } from '@/core/rule-utils'; @@ -764,6 +768,20 @@ function markArtifactProducedWithoutUpload(artifact) { delete artifact.url; } +function patchArtifactSyncResult(name, patcher) { + const latestArtifacts = $.read(ARTIFACTS_KEY); + const currentArtifact = findByName(latestArtifacts, name); + if (!currentArtifact) { + $.info(`远程配置 ${name} 已不存在, 跳过同步结果写入`); + return null; + } + + const nextArtifact = patcher({ ...currentArtifact }); + updateByName(latestArtifacts, name, nextArtifact); + $.write(latestArtifacts, ARTIFACTS_KEY); + return nextArtifact; +} + async function uploadArtifactBatches({ allArtifacts, files, valid, invalid }) { const settings = $.read(SETTINGS_KEY) || {}; const batchSize = normalizeArtifactSyncBatchSize( @@ -841,7 +859,15 @@ async function uploadArtifactBatches({ allArtifacts, files, valid, invalid }) { return uploaded; } -async function syncArtifacts() { +function shouldSyncArtifact(artifact, { skipCronArtifacts = false } = {}) { + return ( + artifact.sync && + artifact.source && + (!skipCronArtifacts || shouldSyncArtifactInGlobalCron(artifact)) + ); +} + +async function syncArtifacts(options = {}) { $.info('开始同步所有远程配置...'); const allArtifacts = $.read(ARTIFACTS_KEY); const files = {}; @@ -855,7 +881,7 @@ async function syncArtifacts() { const subNames = []; let enabledCount = 0; allArtifacts.map((artifact) => { - if (artifact.sync && artifact.source) { + if (shouldSyncArtifact(artifact, options)) { enabledCount++; if (artifact.type === 'subscription') { const subName = artifact.source; @@ -903,8 +929,12 @@ async function syncArtifacts() { await Promise.all( allArtifacts.map(async (artifact) => { try { - if (artifact.sync && artifact.source) { - $.info(`正在同步云配置:${artifact.name}...`); + if (shouldSyncArtifact(artifact, options)) { + $.info( + `正在同步云配置:${formatArtifactLogName( + artifact, + )}...`, + ); const useMihomoExternal = artifact.platform === 'SurgeMac'; @@ -942,7 +972,9 @@ async function syncArtifacts() { } } catch (e) { $.error( - `生成同步配置 ${artifact.name} 发生错误: ${ + `生成同步配置 ${formatArtifactLogName( + artifact, + )} 发生错误: ${ e.message ?? e }`, ); @@ -1018,94 +1050,123 @@ async function syncAllArtifacts(_, res) { } } -async function syncArtifact(req, res) { - let { name } = req.params; - $.info(`开始同步远程配置 ${name}...`); +async function syncArtifactItem(name) { const allArtifacts = $.read(ARTIFACTS_KEY); const artifact = findByName(allArtifacts, name); if (!artifact) { $.error(`找不到远程配置 ${name}`); - failed( - res, - new ResourceNotFoundError( - 'RESOURCE_NOT_FOUND', - `找不到远程配置 ${name}`, - ), - 404, + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `找不到远程配置 ${name}`, ); - return; } if (!artifact.source) { - $.error(`远程配置 ${name} 未设置来源`); - failed( - res, - new ResourceNotFoundError( - 'RESOURCE_HAS_NO_SOURCE', - `远程配置 ${name} 未设置来源`, - ), - 404, + $.error(`远程配置 ${formatArtifactLogName(artifact)} 未设置来源`); + throw new ResourceNotFoundError( + 'RESOURCE_HAS_NO_SOURCE', + `远程配置 ${formatArtifactLogName(artifact)} 未设置来源`, ); - return; } - try { - const useMihomoExternal = artifact.platform === 'SurgeMac'; + $.info(`开始同步远程配置 ${formatArtifactLogName(artifact)}...`); - if (useMihomoExternal) { - $.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`); - } - const output = await produceArtifact({ - type: artifact.type, - name: artifact.source, - platform: artifact.platform, - produceOpts: { - 'include-unsupported-proxy': artifact.includeUnsupportedProxy, - useMihomoExternal, - prettyYaml: artifact.prettyYaml, - }, - }); + const useMihomoExternal = artifact.platform === 'SurgeMac'; - // if (!output || output.length === 0) - // throw new Error('该配置的结果为空 不进行上传'); - if (!shouldUploadArtifact(artifact)) { - $.info(`配置 ${artifact.name} 已关闭上传, 仅更新执行时间`); - markArtifactProducedWithoutUpload(artifact); - $.write(allArtifacts, ARTIFACTS_KEY); - success(res, artifact); - return; - } + if (useMihomoExternal) { + $.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`); + } + const output = await produceArtifact({ + type: artifact.type, + name: artifact.source, + platform: artifact.platform, + produceOpts: { + 'include-unsupported-proxy': artifact.includeUnsupportedProxy, + useMihomoExternal, + prettyYaml: artifact.prettyYaml, + }, + }); + // if (!output || output.length === 0) + // throw new Error('该配置的结果为空 不进行上传'); + if (!shouldUploadArtifact(artifact)) { $.info( - `正在上传配置:${artifact.name}\n>>>${JSON.stringify( + `配置 ${formatArtifactLogName( artifact, - null, - 2, - )}`, + )} 已关闭上传, 仅更新执行时间`, ); - const resp = await syncToGist({ - [encodeURIComponent(artifact.name)]: { - content: output, + const updated = new Date().getTime(); + const patchedArtifact = patchArtifactSyncResult( + name, + (currentArtifact) => { + currentArtifact.updated = updated; + delete currentArtifact.url; + return currentArtifact; }, - }); - artifact.updated = new Date().getTime(); - const body = JSON.parse(resp.body); + ); + if (patchedArtifact) return patchedArtifact; - logUploadResponse(body); - const new_url = resolveArtifactUploadUrl(body, artifact.name); - artifact.url = new_url; - $.write(allArtifacts, ARTIFACTS_KEY); + const fallbackArtifact = { + ...artifact, + updated, + }; + delete fallbackArtifact.url; + return fallbackArtifact; + } + + $.info( + `正在上传配置:${formatArtifactLogName(artifact)}\n>>>${JSON.stringify( + artifact, + null, + 2, + )}`, + ); + const resp = await syncToGist({ + [encodeURIComponent(artifact.name)]: { + content: output, + }, + }); + const updated = new Date().getTime(); + const body = JSON.parse(resp.body); + + logUploadResponse(body); + const new_url = resolveArtifactUploadUrl(body, artifact.name); + const patchedArtifact = patchArtifactSyncResult( + name, + (currentArtifact) => ({ + ...currentArtifact, + updated, + url: new_url, + }), + ); + return ( + patchedArtifact || { + ...artifact, + updated, + url: new_url, + } + ); +} + +async function syncArtifact(req, res) { + let { name } = req.params; + + try { + const artifact = await syncArtifactItem(name); success(res, artifact); } catch (err) { - $.error(`远程配置 ${artifact.name} 发生错误: ${err.message ?? err}`); + $.error(`远程配置 ${name} 发生错误: ${err.message ?? err}`); failed( res, - new InternalServerError( - `FAILED_TO_SYNC_ARTIFACT`, - `Failed to sync artifact ${name}`, - `Reason: ${err}`, - ), + err instanceof ResourceNotFoundError + ? err + : new InternalServerError( + `FAILED_TO_SYNC_ARTIFACT`, + `Failed to sync artifact ${name}`, + `Reason: ${err}`, + ), + err instanceof ResourceNotFoundError ? 404 : undefined, ); } } @@ -1114,6 +1175,7 @@ export { markArtifactProducedWithoutUpload, produceArtifact, shouldUploadArtifact, + syncArtifactItem, syncArtifacts, uploadArtifactBatches, }; diff --git a/backend/src/test/restful/sync.spec.js b/backend/src/test/restful/sync.spec.js index 92a108fb..551b3191 100644 --- a/backend/src/test/restful/sync.spec.js +++ b/backend/src/test/restful/sync.spec.js @@ -164,6 +164,39 @@ describe('sync routes', function () { expect(state[ARTIFACTS_KEY][0]).to.not.have.property('url'); }); + it('preserves artifact edits made while a single artifact sync is running', async function () { + const startedAt = new Date().getTime(); + let artifactReads = 0; + $.read = (key) => { + if (key === ARTIFACTS_KEY) { + artifactReads++; + if (artifactReads === 2) { + state[ARTIFACTS_KEY] = [ + { + ...state[ARTIFACTS_KEY][0], + remark: 'edited while syncing', + cron: '55 23 * * *', + }, + ]; + } + } + return state[key] || []; + }; + + const res = await requestSyncArtifact('local-artifact'); + + expect(res.statusCode).to.equal(200); + expect(res.body.status).to.equal('success'); + expect(res.body.data.remark).to.equal('edited while syncing'); + expect(res.body.data.cron).to.equal('55 23 * * *'); + expect(res.body.data.updated).to.be.at.least(startedAt); + expect(res.body.data).to.not.have.property('url'); + expect(state[ARTIFACTS_KEY][0].remark).to.equal('edited while syncing'); + expect(state[ARTIFACTS_KEY][0].cron).to.equal('55 23 * * *'); + expect(state[ARTIFACTS_KEY][0].updated).to.be.at.least(startedAt); + expect(state[ARTIFACTS_KEY][0]).to.not.have.property('url'); + }); + it('does not try to delete a remote file when only run time exists', async function () { delete state[ARTIFACTS_KEY][0].url; diff --git a/backend/src/test/utils/artifact-cron.spec.js b/backend/src/test/utils/artifact-cron.spec.js new file mode 100644 index 00000000..5cc6b06d --- /dev/null +++ b/backend/src/test/utils/artifact-cron.spec.js @@ -0,0 +1,127 @@ +import { expect } from 'chai'; +import { afterEach, beforeEach, describe, it } from 'mocha'; + +import $ from '@/core/app'; +import { + formatArtifactLogName, + hasArtifactCron, + normalizeArtifactCron, + runArtifactCron, + shouldSyncArtifactInGlobalCron, + startArtifactCronJobs, + stopArtifactCronJobs, + validateArtifactCron, +} from '@/utils/artifact-cron'; + +describe('artifact cron policy', function () { + let read; + let info; + let error; + + beforeEach(function () { + read = $.read; + info = $.info; + error = $.error; + + $.read = () => []; + $.info = () => {}; + $.error = () => {}; + }); + + afterEach(function () { + stopArtifactCronJobs(); + $.read = read; + $.info = info; + $.error = error; + }); + + it('treats blank cron as unset', function () { + const artifact = { name: 'demo', cron: ' ' }; + + normalizeArtifactCron(artifact); + + expect(artifact).to.not.have.property('cron'); + expect(hasArtifactCron(artifact)).to.equal(false); + expect(shouldSyncArtifactInGlobalCron(artifact)).to.equal(true); + }); + + it('keeps valid cron and removes it from global cron eligibility', function () { + const artifact = { name: 'demo', cron: ' 55 23 * * * ' }; + + normalizeArtifactCron(artifact); + + expect(artifact.cron).to.equal('55 23 * * *'); + expect(hasArtifactCron(artifact)).to.equal(true); + expect(shouldSyncArtifactInGlobalCron(artifact)).to.equal(false); + }); + + it('rejects invalid cron expressions', function () { + expect(() => validateArtifactCron('not a cron')).to.throw( + /Artifact cron not a cron is invalid/, + ); + }); + + it('formats display name for logs when available', function () { + expect( + formatArtifactLogName({ + name: 'demo', + displayName: 'Demo Display', + }), + ).to.equal('demo (Demo Display)'); + expect( + formatArtifactLogName({ + name: 'legacy', + 'display-name': 'Legacy Display', + }), + ).to.equal('legacy (Legacy Display)'); + expect( + formatArtifactLogName({ + name: 'same', + displayName: 'same', + }), + ).to.equal('same'); + }); + + it('skips overlapping runs for the same artifact', async function () { + const calls = []; + const logs = []; + let releaseFirstRun; + let firstRunStarted; + let runCount = 0; + + const firstRunPromise = new Promise((resolve) => { + firstRunStarted = resolve; + }); + + $.info = (message) => { + logs.push(message); + }; + startArtifactCronJobs(async (name) => { + calls.push(name); + runCount++; + if (runCount === 1) { + firstRunStarted(); + await new Promise((resolve) => { + releaseFirstRun = resolve; + }); + } + }); + + const firstRun = runArtifactCron('demo', 'demo', '* * * * * *'); + await firstRunPromise; + + await runArtifactCron('demo', 'demo', '* * * * * *'); + + expect(calls).to.deep.equal(['demo']); + expect(logs).to.include( + '[ARTIFACT CRON] demo * * * * * * skipped: previous run is still running', + ); + + releaseFirstRun(); + await firstRun; + + await runArtifactCron('demo', 'demo', '* * * * * *'); + + expect(calls).to.deep.equal(['demo', 'demo']); + }); +}); diff --git a/backend/src/utils/artifact-cron.js b/backend/src/utils/artifact-cron.js new file mode 100644 index 00000000..064abc3c --- /dev/null +++ b/backend/src/utils/artifact-cron.js @@ -0,0 +1,151 @@ +import $ from '@/core/app'; +import { ARTIFACTS_KEY } from '@/constants'; +import { RequestInvalidError } from '@/restful/errors'; + +const artifactCronJobs = new Map(); +const runningArtifactCronNames = new Set(); +let syncArtifactByName; + +function getArtifactCron(artifact) { + const cron = artifact?.cron == null ? '' : `${artifact.cron}`.trim(); + return cron; +} + +function hasArtifactCron(artifact) { + return getArtifactCron(artifact).length > 0; +} + +function getArtifactDisplayName(artifact) { + const displayName = artifact?.displayName ?? artifact?.['display-name']; + return displayName == null ? '' : `${displayName}`.trim(); +} + +function formatArtifactLogName(artifact) { + if (!artifact || typeof artifact !== 'object') return `${artifact}`; + + const name = artifact.name == null ? '' : `${artifact.name}`; + const displayName = getArtifactDisplayName(artifact); + if (!displayName || displayName === name) return name; + + return `${name} (${displayName})`; +} + +function shouldSyncArtifactInGlobalCron(artifact) { + return !hasArtifactCron(artifact); +} + +function validateArtifactCron(cron) { + if (!cron || !$.env.isNode) return; + + try { + const { CronTime } = eval(`require("cron")`); + new CronTime(cron); + } catch (e) { + throw new RequestInvalidError( + 'INVALID_ARTIFACT_CRON', + `Artifact cron ${cron} is invalid.`, + `Reason: ${e.message ?? e}`, + ); + } +} + +function normalizeArtifactCron(artifact) { + if (!artifact || typeof artifact !== 'object') return artifact; + + const cron = getArtifactCron(artifact); + if (!cron) { + delete artifact.cron; + return artifact; + } + + validateArtifactCron(cron); + artifact.cron = cron; + return artifact; +} + +function stopArtifactCronJobs() { + artifactCronJobs.forEach((job) => job.stop()); + artifactCronJobs.clear(); +} + +async function runArtifactCron(name, logName, cron) { + if (runningArtifactCronNames.has(name)) { + $.info( + `[ARTIFACT CRON] ${logName} ${cron} skipped: previous run is still running`, + ); + return; + } + + runningArtifactCronNames.add(name); + try { + $.info(`[ARTIFACT CRON] ${logName} ${cron} started`); + await syncArtifactByName(name); + $.info(`[ARTIFACT CRON] ${logName} ${cron} finished`); + } catch (e) { + $.error( + `[ARTIFACT CRON] ${logName} ${cron} error: ${e.message ?? e}`, + ); + } finally { + runningArtifactCronNames.delete(name); + } +} + +function scheduleArtifactCron(artifact) { + const cron = getArtifactCron(artifact); + const name = artifact.name; + const logName = formatArtifactLogName(artifact); + const { CronJob } = eval(`require("cron")`); + + try { + const job = new CronJob( + cron, + async function () { + await runArtifactCron(name, logName, cron); + }, + null, + true, + ); + artifactCronJobs.set(name, job); + $.info(`[ARTIFACT CRON] ${logName} ${cron} scheduled`); + } catch (e) { + $.error( + `[ARTIFACT CRON] ${logName} ${cron} schedule error: ${ + e.message ?? e + }`, + ); + } +} + +function refreshArtifactCronJobs() { + if (!$.env.isNode || !syncArtifactByName) return; + + stopArtifactCronJobs(); + + const storedArtifacts = $.read(ARTIFACTS_KEY); + const artifacts = Array.isArray(storedArtifacts) ? storedArtifacts : []; + artifacts + .filter((artifact) => artifact.sync && artifact.source) + .filter(hasArtifactCron) + .forEach(scheduleArtifactCron); +} + +function startArtifactCronJobs(handler) { + if (!$.env.isNode) return; + + syncArtifactByName = handler; + refreshArtifactCronJobs(); +} + +export { + formatArtifactLogName, + getArtifactDisplayName, + getArtifactCron, + hasArtifactCron, + normalizeArtifactCron, + refreshArtifactCronJobs, + runArtifactCron, + shouldSyncArtifactInGlobalCron, + startArtifactCronJobs, + stopArtifactCronJobs, + validateArtifactCron, +};