Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(web): 表面切换取消它发起的读请求,批量标记改有界并发

longmeidao34bc92baa2b9
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 3eb8a0fe9..193cb6c13 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -1435,7 +1435,8 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("data-follow-remove")
def test_reader_management_is_locked_and_points_to_the_writer(self):
- self.assertPageContains("api('/healthz')")
+ # 读请求带上表面的 signal(surfaceApi),切页时会被取消。
+ self.assertPageContains("surfaceApi(surface,'/healthz')")
self.assertPageContains("followRuntime?.ledger_read_only")
self.assertPageContains("前往写入端管理关注")
self.assertPageContains("#followAdd textarea,#followAdd button")
@@ -2248,7 +2249,7 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageLacks("已显示可读取附件;F95 登录会话已保存")
self.assertPageLacks("这条旧记录的受保护资源会在下次检查重新解析")
self.assertPageContains("followCredentialProviders=new Set")
- self.assertPageContains("api('/api/follow/credentials').catch")
+ self.assertPageContains("surfaceApi(surface,'/api/follow/credentials').catch")
self.assertPageLacks("个外部文件页;视频列表未取得")
self.assertPageContains("function followMediaIssue(item)")
self.assertPageContains('class="fnote followmediaissue"')
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index ddb57ebf5..e1f9614ed 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -501,6 +501,51 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(".toast{pointer-events:auto;box-sizing:border-box;display:flex;align-items:center;")
self.assertPageLacks(".toasts{position:fixed;right:16px;bottom:22px;z-index:var(--layer-popover);display:grid;gap:8px;")
+ def test_leaving_a_surface_cancels_the_reads_it_started(self):
+ """以前离开一个表面只是把结果丢掉,请求本身照跑到底。
+
+ 切三四页就有三四份读请求同时占着浏览器对同一 host 的 6 条连接,最后停留
+ 的那一页反而排在队尾。写操作不带 signal——切页不能撤掉一次真实写入。
+ """
+ self.assertPageContains("surfaceRequests?.abort();")
+ self.assertPageContains("surfaceRequests=new AbortController();")
+ self.assertPageContains("const surfaceToken=path=>({epoch:surfaceEpoch,path,signal:surfaceRequests?.signal})")
+ self.assertPageContains("const surfaceApi=(token,path,options)=>api(path,{...options,signal:token.signal})")
+ # 取消不是失败:abort 只可能来自 claimSurface,而它已经推进了 epoch,
+ # 调用点紧随其后的过期判定会接住它。
+ self.assertPageContains("const isAbort=error=>error?.name==='AbortError'")
+ self.assertPageContains("if(isAbort(error))return null;throw error")
+ self.assertPageContains("if(signal)init.signal=signal")
+ # 用响应体之前必须先过期判定:被取消时 surfaceApi 返回的是 null。
+ load_body = self.page.split("async function load(reset)", 1)[1].split("const loadObserver", 1)[0]
+ guard = load_body.index("if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;\n cache")
+ self.assertLess(guard, load_body.index("cache(d.items)"))
+
+ def test_bulk_follow_updates_run_with_bounded_concurrency(self):
+ """一千条串行 POST 全靠往返等,界面按住不放;一次全发出去又会挤满连接。"""
+ self.assertPageContains("const mapLimit=async(items,limit,run)=>")
+ self.assertPageContains("const workers=Math.min(Math.max(1,limit),list.length)")
+ # 某一项失败只记下原因,不中断整批。
+ self.assertPageContains("catch(error){results[index]={ok:false,error}}")
+ bulk = self.app_js.split("root.querySelectorAll('[data-follow-bulk]')", 1)[1]
+ bulk = bulk.split("root.querySelectorAll('[data-follow-view]')", 1)[0]
+ self.assertIn("await mapLimit(ids,6,id=>", bulk)
+ # 撤销那两处仍是单条 POST,不该被这条契约波及。
+ self.assertNotIn("for(const id of ids)", bulk)
+ self.assertPageContains("actionFailure(`批量更新 ${failed.length}/${ids.length} 项`")
+
+ def test_immerse_stream_does_not_pretend_to_paginate_a_random_sample(self):
+ """`sort=rand` 在服务端是未加种子的 `RANDOM()`,偏移量在它上面没有意义。
+
+ 原先每续取一次就把一个 `tokOffset` 加 60,再传给一个从不使用这个参数的
+ `fetchTok(off)`——读代码的人会以为这条流是翻页来的。
+ """
+ self.assertPageLacks("tokOffset")
+ self.assertPageContains("async function fetchTok()")
+ self.assertPageContains("const more=await fetchTok()")
+ # 去重靠调用点的 seen 集合。
+ self.assertPageContains("const seen=new Set(tokList.map(x=>x.id))")
+
def test_scrollbar_gutter_is_reserved_so_overlays_do_not_shift_the_page(self):
"""设置面板给 body 加 overflow:hidden,滚动条一消失整页就横向跳一次。"""
self.assertPageContains("scrollbar-gutter:stable}")
@@ -1601,7 +1646,8 @@ class WebUiSourceTests(unittest.TestCase):
def test_surface_navigation_clears_stale_panels_and_ignores_late_responses(self):
"""跨页面请求返回较慢时,旧统计/复核响应不能覆盖当前页面。"""
- self.assertPageContains("const claimSurface=path=>{surfaceEpoch++;return surfaceToken(path)}")
+ self.assertPageContains("const claimSurface=path=>{")
+ self.assertPageContains("surfaceEpoch++;return surfaceToken(path)}")
self.assertPageContains("const surfaceCurrent=token=>token.epoch===surfaceEpoch&&surfacePath()===token.path")
self.assertPageContains("const surface=reset?claimSurface(surfacePath()):surfaceToken(surfacePath())")
self.assertPageContains("if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return")
@@ -1683,10 +1729,9 @@ class WebUiSourceTests(unittest.TestCase):
def test_junk_empty_state_only_appears_after_the_loading_request_finishes(self):
"""待判断为空是请求终态;加载期间只能显示 Loading Dots,不能先闪空态。"""
branch = self.app_js.split("if(state.state==='ads'){", 1)[1].split("adsBatch=null;", 1)[0]
- self.assertLess(branch.index("loadingDotsHtml('正在读取垃圾文件…')"),
- branch.index("const nextAds=await api('/api/ads?'+junkQuery)"))
- self.assertLess(branch.index("const nextAds=await api('/api/ads?'+junkQuery)"),
- branch.index("emptyState('check'"))
+ request = "const nextAds=await surfaceApi(surface,'/api/ads?'+junkQuery)"
+ self.assertLess(branch.index("loadingDotsHtml('正在读取垃圾文件…')"), branch.index(request))
+ self.assertLess(branch.index(request), branch.index("emptyState('check'"))
self.assertPageContains("$('#loadSentinel').hidden=true")
def test_junk_review_and_trash_render_every_physical_resource_type(self):
@@ -2495,7 +2540,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const cacheFresh=cached&&Date.now()-cachedEntry.at<TASTE_CACHE_FRESH_MS;")
self.assertPageContains("if(cached)renderTaste(cached);")
self.assertPageContains("if(!cacheFresh)")
- self.assertPageContains("void api('/api/taste?window='+requestedWindow).then(data=>")
+ self.assertPageContains("void surfaceApi(surface,'/api/taste?window='+requestedWindow).then(data=>")
self.assertPageContains("tasteCacheSet(requestedWindow,data);")
self.assertPageContains("if(request===tasteRequest&&tasteWindow===requestedWindow&&surfaceCurrent(surface))renderTaste(data)")
self.assertPageContains("if(!cached&&request===tasteRequest&&surfaceCurrent(surface))")
@@ -2631,7 +2676,8 @@ class WebUiSourceTests(unittest.TestCase):
def test_data_cleanup_groups_junk_duplicates_and_empty_folders_in_fieldsets(self):
self.assertPageContains("async function openDataCleanup(push=true)")
self.assertPageContains("route('/data-cleanup')")
- self.assertPageContains("api('/api/ads?limit=1'),api('/api/duplicates?limit=1'),api('/api/sources')")
+ for path in ("'/api/ads?limit=1'", "'/api/duplicates?limit=1'", "'/api/sources'"):
+ self.assertPageContains(path)
# 标题是正文区的第一行,不用原生 legend——legend 会在上边框上开个缺口,
# 三张卡内容高度不同时那道缺口的位置也跟着不齐。
for title in ("fieldsetTitle('cleanupJunkTitle','垃圾文件')",
@@ -2828,7 +2874,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("reviewCategory==='fc2_similarity'?''")
def test_reader_review_uses_the_writer_mirror_without_offering_fake_writes(self):
- self.assertPageContains("const runtime=await api('/healthz')")
+ self.assertPageContains("const runtime=await surfaceApi(surface,'/healthz')")
self.assertPageContains("reviewRuntime=runtime;reviewData=next")
self.assertPageContains("正在显示写入端的实时复核队列")
self.assertPageContains("前往写入端复核")
diff --git a/web/app.js b/web/app.js
index 07a8e0520..d0e442753 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1,4 +1,4 @@
-import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, linkHost, linkMarkUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, pageTitle, realDuration} from './js/core.js';
+import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, isAbort, mapLimit, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, linkHost, linkMarkUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, pageTitle, realDuration} from './js/core.js';
import { imageFallbackAttrs, wireImageFallbacks } from './js/image-fallback.js';
import { initMiddleTruncate } from './js/middle-truncate.js';
import { tagLabel } from './js/tags.js';
@@ -156,9 +156,23 @@ function paintNav(){
let surfaceEpoch=0;
const surfacePath=()=>decodeURIComponent(location.pathname);
let lastRoutePath=surfacePath();
-const surfaceToken=path=>({epoch:surfaceEpoch,path});
+/* 每个表面自带一个 AbortController。以前离开一个表面只是把结果丢掉(`surfaceCurrent`
+ 判过期),请求本身照跑到底:切三四页就有三四份读请求同时占着那 6 条连接,最后
+ 停留的那一页反而排在队尾。现在 claimSurface 先作废上一屏的读请求再推进 epoch。
+ 只有拿到 token 的读请求会被取消;写操作不带 signal,切页不会撤掉一次真实写入。 */
+let surfaceRequests=null;
+const surfaceToken=path=>({epoch:surfaceEpoch,path,signal:surfaceRequests?.signal});
const surfaceCurrent=token=>token.epoch===surfaceEpoch&&surfacePath()===token.path;
-const claimSurface=path=>{surfaceEpoch++;return surfaceToken(path)};
+const claimSurface=path=>{
+ surfaceRequests?.abort();
+ surfaceRequests=new AbortController();
+ surfaceEpoch++;return surfaceToken(path)};
+/* 表面级读请求:带上这个表面的 signal,被取消时返回 null 而不是抛错。
+ 取消只可能由 claimSurface 触发,而它已经推进了 epoch,所以调用点紧随其后的
+ `surfaceCurrent()` 必然为假、走的还是原来那条过期分支——不用给每个表面套一层
+ try/catch,也不会多出一条没人接的 rejection。 */
+const surfaceApi=(token,path,options)=>api(path,{...options,signal:token.signal})
+ .catch(error=>{if(isAbort(error))return null;throw error});
const route=(path,replace=false)=>{
surfaceEpoch++;
history[replace?'replaceState':'pushState']({},'',path);syncPageTitle(path);
@@ -1970,7 +1984,7 @@ async function openStats(push=true){
enterManagementSurface();
disposeStage(false);
showManagementBody({placeholder:managementPlaceholder('/stats')});
- const d=await api('/api/stats');
+ const d=await surfaceApi(surface,'/api/stats');
if(!surfaceCurrent(surface))return;
showManagementBody();
const a=d.attribution, cs=d.consumption;
@@ -2400,7 +2414,7 @@ async function openTaste(push=true){
if(!cacheFresh){
const request=++tasteRequest;
const requestedWindow=tasteWindow;
- void api('/api/taste?window='+requestedWindow).then(data=>{
+ void surfaceApi(surface,'/api/taste?window='+requestedWindow).then(data=>{
tasteCacheSet(requestedWindow,data);
if(request===tasteRequest&&tasteWindow===requestedWindow&&surfaceCurrent(surface))renderTaste(data)
}).catch(error=>{
@@ -2465,7 +2479,7 @@ async function openPlaylists(push=true){
if(push)route('/playlists');
const surface=claimSurface('/playlists');
showManagementBody({manage:false,placeholder:managementPlaceholder('/playlists')});
- const data=await api('/api/playlists');
+ const data=await surfaceApi(surface,'/api/playlists');
if(!surfaceCurrent(surface))return;
showManagementBody({manage:false});
const cards=(data.items||[]).map(list=>{const resume=list.current_asset_id||list.preview_asset_id;
@@ -2509,7 +2523,8 @@ async function openDataCleanup(push=true){
const surface=claimSurface('/data-cleanup');
showManagementBody({placeholder:managementPlaceholder('/data-cleanup')});
const [junk,duplicates,sources]=await Promise.all([
- api('/api/ads?limit=1'),api('/api/duplicates?limit=1'),api('/api/sources'),
+ surfaceApi(surface,'/api/ads?limit=1'),surfaceApi(surface,'/api/duplicates?limit=1'),
+ surfaceApi(surface,'/api/sources'),
]);
if(!surfaceCurrent(surface))return;
paintManageLede();
@@ -2624,7 +2639,7 @@ async function openDuplicates(push=true){
if(push)route('/duplicates');
const surface=claimSurface('/duplicates');
showManagementBody({placeholder:managementPlaceholder('/duplicates')});
- const next=await api('/api/duplicates?limit=120');
+ const next=await surfaceApi(surface,'/api/duplicates?limit=120');
if(!surfaceCurrent(surface))return;
dupData=next;
renderDuplicates();
@@ -2702,7 +2717,7 @@ async function openReview(push=true){
if(push)route('/review');
const surface=claimSurface('/review');
showManagementBody({placeholder:managementPlaceholder('/review')});
- const runtime=await api('/healthz');
+ const runtime=await surfaceApi(surface,'/healthz');
if(!surfaceCurrent(surface))return;
/* ADR-0018:确定的那部分先落库再取队列。reader 明知不能写就不要制造一次 409;
它改为读取 writer 的严格 CA HTTPS 镜像,判定按钮也一起锁住。 */
@@ -2711,7 +2726,7 @@ async function openReview(push=true){
if(!surfaceCurrent(surface))return;
if(auto&&auto.applied)console.info(`自动落库 ${auto.applied} 条(ADR-0018)`);
}catch(e){console.info('自动落库未执行:'+e.message)}
- const next=await api('/api/review');
+ const next=await surfaceApi(surface,'/api/review');
if(!surfaceCurrent(surface))return;
reviewRuntime=runtime;reviewData=next;
const render=()=>{
@@ -3633,8 +3648,8 @@ async function openFollow(push=true,renderForDetail=false){
showManagementBody({manage:false,
placeholder:followSkeletonHtml('正在读取关注内容')});
const [data,credentials]=await Promise.all([
- api(followPageUrl(0)),
- api('/api/follow/credentials').catch(()=>({providers:[]})),
+ surfaceApi(surface,followPageUrl(0)),
+ surfaceApi(surface,'/api/follow/credentials').catch(()=>({providers:[]})),
]);
if(!surfaceCurrent(surface))return;
followData=data;
@@ -3949,7 +3964,8 @@ async function openFollowManage(push=true){
const surface=claimSurface('/follow-manage');
showManagementBody({placeholder:managementPlaceholder('/follow-manage')});
const [data,credentials,runtime]=await Promise.all([
- api('/api/follow?limit=1'),api('/api/follow/credentials'),api('/healthz')]);
+ surfaceApi(surface,'/api/follow?limit=1'),surfaceApi(surface,'/api/follow/credentials'),
+ surfaceApi(surface,'/healthz')]);
if(!surfaceCurrent(surface))return;
followData=data;followRuntime=runtime;
renderFollowManage(credentials);
@@ -4224,10 +4240,14 @@ function wireFollowManage(){
const pending=await api('/api/follow?status=new&limit=1000');
const ids=(pending.groups||[]).flatMap(g=>[g.primary,...g.variants,...g.duplicates])
.filter(item=>item.status==='new').map(item=>item.id);
- for(const id of ids){
- await api('/api/follow/status',{method:'POST',body:JSON.stringify({item:id,to})});
- }
- await openFollowManage(false);actionReceipt(`已批量标记 ${ids.length} 项`);
+ /* 一千条串行发是实测的卡点:请求之间的往返全靠等,界面按住不放。
+ 这里的每一条都是独立的写入,彼此没有顺序要求,交给有界并发。 */
+ const results=await mapLimit(ids,6,id=>
+ api('/api/follow/status',{method:'POST',body:JSON.stringify({item:id,to})}));
+ const failed=results.filter(result=>!result.ok);
+ await openFollowManage(false);
+ if(failed.length)actionFailure(`批量更新 ${failed.length}/${ids.length} 项`,failed[0].error);
+ else actionReceipt(`已批量标记 ${ids.length} 项`);
}catch(error){button.disabled=false;actionFailure('批量更新关注状态',error)}
});
root.querySelectorAll('[data-follow-view]').forEach(button=>
@@ -5558,7 +5578,8 @@ async function load(reset){
$('#loadSentinel').hidden=true;
}
if(reset||!adsBatch){const junkQuery=new URLSearchParams({limit:'200',status:junkView});if(junkKind)junkQuery.set('kind',junkKind);
- const nextAds=await api('/api/ads?'+junkQuery);if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
+ const nextAds=await surfaceApi(surface,'/api/ads?'+junkQuery);
+ if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
adsBatch=nextAds;cache(adsBatch.items)}
const batch=adsBatch.items.slice(offset,offset+appSettings.batchSize);
const html=batch.map(junkCardHtml).join('');
@@ -5578,8 +5599,9 @@ async function load(reset){
if(state.jav==='1')p.set('exclude_vertical','1');
p.set('limit',appSettings.batchSize); p.set('offset',offset);
if(!reset)p.set('count','0');
- const d=await api('/api/items?'+p);cache(d.items);
+ const d=await surfaceApi(surface,'/api/items?'+p);
if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
+ cache(d.items);
if(reset)total=d.total;
buildManageBar();
const html=state.state==='trash'?d.items.map(resourceCardHtml).join('')
@@ -5710,7 +5732,7 @@ async function loadShorts(requestSeq=loadRequestSeq,surface=surfaceToken(surface
const p=new URLSearchParams(Object.entries(state).filter(([,v])=>v));
/* 排序跟着主列表走,不再写死 sort=new;换一批时竖屏条也要一起换。 */
p.set('orient','竖屏');p.set('limit',18);p.set('offset',0);
- const d=await api('/api/items?'+p);
+ const d=await surfaceApi(surface,'/api/items?'+p);
if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
if(!d.items.length){$('#shortsSec').hidden=true;return}
cache(d.items);
@@ -5843,8 +5865,9 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
activeQueue=queueContext;
if(push&&!queueContext)route('/item/'+id);
const detailSurface=surfaceToken(surfacePath());
- const it=await api('/api/item?id='+id); if(it.error)return;
+ const it=await surfaceApi(detailSurface,'/api/item?id='+id);
if(!surfaceCurrent(detailSurface))return;
+ if(it.error)return;
current=it; CACHE[it.id]=it;
barsContext={type:'item',id:it.id,filters:returnBars?.type==='entity'
? {...returnBars.filters}:emptyEntityFilters()};
@@ -6267,8 +6290,11 @@ function disposeTokVideo(video,remove=false){
}
/* 沉浸模式 = 滚动刷新的连续流,横屏竖屏都进(不是「短片模式」)。
队列滚到尾自动续取下一页,形成无限流。 */
-let tokOffset=0, tokLoading=false;
-async function fetchTok(off){
+let tokLoading=false;
+/* 没有 offset 参数:`sort=rand` 在服务端是未加种子的 `RANDOM()`(web_contract.py),
+ 每次请求都是一次全新的随机抽样,翻页偏移在它上面没有意义——带上去只会随机跳过
+ 若干行。续取靠的是调用点那个 `seen` 集合去重,不是偏移量。 */
+async function fetchTok(){
const p=new URLSearchParams(Object.entries(state).filter(([,v])=>v));
p.delete('orient'); // 不限画幅
p.set('sort','rand'); // ⚠️ 随机,不是顺序播前 60 个
@@ -6340,8 +6366,7 @@ async function openTok(startId,push=true){
if(push)route('/immerse');
$('#tok').hidden=false;document.body.style.overflow='hidden';setTokLoading(true,'加载内容…');
try{
- tokOffset=0;
- tokList=await fetchTok(0);
+ tokList=await fetchTok();
if(startId&&!tokList.some(x=>x.id===startId)){
const selectedItem=await api('/api/item?id='+startId);
if(selectedItem.id)tokList=[selectedItem,...tokList.filter(x=>x.id!==startId)];
@@ -6448,8 +6473,8 @@ async function tokNext(d){
setTokLoading(true,'切换中…',tokList[tokIdx]);
// 滚到尾部就续取下一页 —— 无限流
if(tokIdx>=tokList.length-3 && !tokLoading){
- tokLoading=true; tokOffset+=60;
- const more=await fetchTok(tokOffset); // 每次都是新的随机抽样
+ tokLoading=true;
+ const more=await fetchTok(); // 每次都是新的随机抽样
if(more.length){const seen=new Set(tokList.map(x=>x.id));
tokList=tokList.concat(more.filter(x=>!seen.has(x.id)))}
tokLoading=false;
diff --git a/web/js/core.js b/web/js/core.js
index 2cffa0344..afdae0130 100644
--- a/web/js/core.js
+++ b/web/js/core.js
@@ -6,8 +6,13 @@
`route()` 没有放进来:它要调 syncHeaderActions/paintListTitle,那是 UI 层的事。 */
const $=s=>document.querySelector(s);
const icon=(name,cls='')=>`<svg${cls?` class="${cls}"`:''} viewBox="0 0 24 24" aria-hidden="true"><use href="#i-${name}"/></svg>`;
+/* `signal` 写成显式的一项,不靠 Object.assign 顺带透传:表面切换要能作废上一屏
+ 还没读完的请求,「这个请求可被取消」得在签名上看得见。 */
const api=async(p,o)=>{
- const response=await fetch(p,Object.assign({headers:{'Content-Type':'application/json'}},o||{}));
+ const {signal=null,...rest}=o||{};
+ const init={headers:{'Content-Type':'application/json'},...rest};
+ if(signal)init.signal=signal;
+ const response=await fetch(p,init);
let payload=null;
try{payload=await response.json()}catch(_e){}
if(!response.ok){
@@ -16,6 +21,28 @@ const api=async(p,o)=>{
}
return payload;
};
+/* 取消不是失败。abort 只可能来自表面切换,调用点本来就有一条「已过期」分支要走,
+ 不该顺手弹一个「请求失败」的错误提示。 */
+const isAbort=error=>error?.name==='AbortError';
+/* 有界并发的批量请求。串行发一千次 POST 是实测的卡点(批量标记「已看」要几分钟,
+ 界面全程按住),而一次全发出去等于自己挤自己:浏览器对同一 host 只有 6 条
+ HTTP/1.1 连接,多出来的排在队里,连同一时间的正常浏览请求一起等。所以固定几个
+ 工人按序取任务。返回值顺序与输入一致;某一项失败只记下原因,不中断整批——
+ 批量操作里一条失败不该把其余几百条一起放弃。 */
+const mapLimit=async(items,limit,run)=>{
+ const list=[...items],results=new Array(list.length);
+ let next=0;
+ const worker=async()=>{
+ while(next<list.length){
+ const index=next++;
+ try{results[index]={ok:true,value:await run(list[index],index)}}
+ catch(error){results[index]={ok:false,error}}
+ }
+ };
+ const workers=Math.min(Math.max(1,limit),list.length);
+ await Promise.all(Array.from({length:workers},worker));
+ return results;
+};
const pageTitle=path=>{
const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);
const fixed={stats:'统计',taste:'口味',review:'人工复核','data-cleanup':'数据管理',duplicates:'重复文件','quality-goals':'高清版',
@@ -86,6 +113,8 @@ export {
realDuration,
icon,
api,
+ isAbort,
+ mapLimit,
pageTitle,
STATE_ROUTES,
ROUTE_STATES,