| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- /** One resumable collector and one serial publisher; uncertain writes stop. */
- import fs from 'node:fs';
- import path from 'node:path';
- import {spawn} from 'node:child_process';
- import {work,load,save,unwrap,verifyBatch,publicApi,updateProgress,needsProductEnrichment} from './lib/research-enrichment.mjs';
- const root=process.cwd(),python='C:/Users/JSHY/AppData/Local/Python/bin/python.exe';
- const stateFile=path.join(work,'pipeline-state.json'),lockFile=path.join(work,'pipeline.lock.json');
- const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
- const safe=s=>s.replace(/[^a-z0-9_-]/gi,'_');
- const alive=pid=>{try{process.kill(pid,0);return true;}catch{return false;}};
- if(fs.existsSync(lockFile)){
- const old=load(lockFile);if(alive(old.pid))throw Error('PIPELINE_ALREADY_RUNNING');
- fs.renameSync(lockFile,path.join(work,'pipeline.lock.stale-'+Date.now()+'.json'));
- }
- fs.writeFileSync(lockFile,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()}),{flag:'wx'});
- const prior=fs.existsSync(stateFile)?load(stateFile):{};
- save(path.join(work,'pipeline-state.before-resume-'+Date.now()+'.json'),prior);
- const state={...prior,schema:'ksf.enrichment-pipeline.v2',startedAt:prior.startedAt||new Date().toISOString(),resumedAt:new Date().toISOString(),pid:process.pid,
- status:'running',stage:'startup',publishedBatches:prior.publishedBatches||[],unfilledProducts:prior.unfilledProducts||[],attemptedProductIds:prior.attemptedProductIds||[],batchSize:100};
- delete state.errorCode;
- function update(){state.updatedAt=new Date().toISOString();save(stateFile,state);}
- function run(exe,args,log,onStart){
- return new Promise((resolve,reject)=>{
- const fd=fs.openSync(path.join(work,log),'a'),p=spawn(exe,args,{cwd:root,windowsHide:true,stdio:['ignore',fd,fd]});
- let closed=false;const close=()=>{if(!closed){closed=true;fs.closeSync(fd);}};
- onStart?.(p.pid);p.on('error',e=>{close();reject(e)});p.on('close',code=>{close();resolve(code)});
- });
- }
- function published(){
- const result=new Set(),base=path.join(work,'batches');
- result.coverage=new Map();
- for(const name of fs.readdirSync(base)){
- const p=path.join(base,name,'apply-result.json');if(!fs.existsSync(p))continue;
- const value=unwrap(load(p));
- if(value.ok&&value.applied&&value.allRowsVerified){
- for(const row of load(path.join(base,name,'receipt.json')).products){
- result.add(row.id);const coverage=result.coverage.get(row.id)||{reviews:0,specs:0,prices:0};
- for(const field of ['reviews','specs','prices'])coverage[field]+=row[field]||0;
- result.coverage.set(row.id,coverage);
- }
- if(!state.publishedBatches.includes(name))state.publishedBatches.push(name);
- }
- }
- return result;
- }
- function ready(p){
- const family=p.platform==='jd'?'jd':'taobao',eps=[];
- if(p.missingVerifiedSpec||p.missingPrice)eps.push(family==='jd'?'jd.get_item_detail_v1':'taobao.get_item_detail_v6');
- if(p.missingReviews)eps.push(family==='jd'?'jd.get_item_comments_v1':'taobao.get_item_comment_v3');
- return eps.every(ep=>{
- const file=path.join(work,'collected',safe(p.productId)+'--'+safe(ep)+'.meta.json');
- if(!fs.existsSync(file))return false;
- try{return load(file).ok===true||collectorDone;}catch{return false;}
- });
- }
- async function status(name){
- const code=await run(process.execPath,['scripts/publish-research-enrichment.mjs',name,'status'],name+'-status.log');
- if(code!==0)throw Error('PUBLICATION_STATUS_UNAVAILABLE');
- return unwrap(load(path.join(work,'batches',name,'status-result.json')));
- }
- async function publish(name){
- const base=path.join(work,'batches',name),applied=path.join(base,'apply-result.json'),attempt=path.join(base,'apply-attempt.json');
- if(fs.existsSync(applied)&&unwrap(load(applied)).ok){
- state.stage='verify:'+name;update();const v=await verifyBatch(name);updateProgress(v.summary,state);return v;
- }
- // Never replay an unacknowledged apply. Preserve status for review.
- if(fs.existsSync(attempt)){
- state.publicationStatus=await status(name);state.stage='uncertain:'+name;update();
- throw Error('PREVIOUS_APPLY_REQUIRES_REVIEW');
- }
- state.stage='plan:'+name;update();
- if(await run(process.execPath,['scripts/publish-research-enrichment.mjs',name,'plan'],name+'-plan.log')!==0)throw Error('PLAN_CHECK_REQUIRED');
- const planned=unwrap(load(path.join(base,'plan-result.json')));
- if(!planned.ok||!planned.mergePlan?.ok)throw Error('PLAN_CHECK_REQUIRED');
- state.stage='apply:'+name;update();save(attempt,{attemptedAt:new Date().toISOString(),archiveSha256:load(path.join(base,'receipt.json')).archiveSha256,plannedGeneration:planned.mergePlan.plannedGeneration});
- const code=await run(process.execPath,['scripts/publish-research-enrichment.mjs',name,'apply'],name+'-apply.log');
- state.publicationStatus=await status(name);update();
- if(code!==0)throw Error('PUBLICATION_CHECK_REQUIRED');
- const result=unwrap(load(applied));
- if(!state.publicationStatus.publicationFound||state.publicationStatus.publishedGeneration!==result.generation)throw Error('PUBLICATION_STATUS_MISMATCH');
- state.stage='verify:'+name;update();const verified=await verifyBatch(name);
- state.currentGeneration=verified.generation;state.counts=verified.summary.counts;state.quality=verified.summary.quality;
- if(!state.publishedBatches.includes(name))state.publishedBatches.push(name);update();updateProgress(verified.summary,state);return verified;
- }
- let collectorDone=false,collectorCode,collectorPromise;
- try{
- update();
- if(prior.collectorPid&&alive(prior.collectorPid))throw Error('EXISTING_COLLECTOR_REQUIRES_REVIEW');
- // All successful originals are SHA-checked and reused by collect.cjs.
- collectorPromise=run(process.execPath,[path.join(work,'collect.cjs'),'--all'],'collection-resumed.log',pid=>{state.collectorPid=pid;update()}).then(code=>{collectorDone=true;collectorCode=code;});
- const queue=load(path.join(work,'product-queue.json')),handled=new Set();let number=1;
- for(const name of fs.readdirSync(path.join(work,'batches')).filter(n=>/^wave-\d+$/.test(n)).sort()){
- const base=path.join(work,'batches',name);number=Math.max(number,Number(name.split('-')[1])+1);
- if(!fs.existsSync(path.join(base,'transport.zip')))continue;
- const r=path.join(base,'pipeline-readback.json');
- if(!fs.existsSync(r)||!load(r).publicReadbackPassed)await publish(name);
- }
- while(true){
- const imported=published(),rows=queue.filter(p=>needsProductEnrichment(p,imported.coverage.get(p.productId))&&!handled.has(p.productId)&&ready(p));
- state.collectionFinished=collectorDone;state.readyProducts=rows.length;state.importedProductCount=imported.size;state.stage='collection';update();
- if(rows.length>=state.batchSize||(collectorDone&&rows.length)){
- const group=rows.slice(0,state.batchSize),name='wave-'+String(number++).padStart(2,'0');
- const selection=path.join(work,name+'-selection.json');save(selection,group.map(p=>p.productId));
- state.stage='normalize:'+name;update();
- if(await run(python,['-B','-X','utf8','scripts/enrich-research-library.py','--selection',selection,'--name',name],name+'-build.log')!==0)throw Error('NORMALIZATION_CHECK_REQUIRED');
- const receipt=load(path.join(work,'batches',name,'receipt.json')),good=new Set(receipt.products.map(p=>p.id));
- for(const p of group){handled.add(p.productId);if(!good.has(p.productId)&&!state.unfilledProducts.includes(p.productId))state.unfilledProducts.push(p.productId);}
- state.attemptedProductIds=[...handled];update();
- if(receipt.empty)continue;
- await publish(name);continue;
- }
- if(collectorDone)break;
- await wait(15000);
- }
- await collectorPromise;
- state.stage='social-audit';update();
- if(await run(python,['-B','-X','utf8','scripts/audit-social-enrichment.py'],'social-audit.log')!==0)throw Error('SOCIAL_AUDIT_FAILED');
- if(await run(python,['-B','-X','utf8','scripts/audit-unavailable-research.py'],'unavailable-audit.log')!==0)throw Error('SOURCE_AVAILABILITY_AUDIT_FAILED');
- if(await run(python,['-B','-X','utf8','scripts/audit-enrichment-coverage.py'],'coverage-audit.log')!==0)throw Error('COVERAGE_AUDIT_FAILED');
- state.stage='final-readback';update();
- const summary=await publicApi({op:'summary'});save(path.join(work,'summary-after.json'),summary);
- state.currentGeneration=summary.generation;state.counts=summary.counts;state.quality=summary.quality;
- const metadata=fs.readdirSync(path.join(work,'collected')).filter(n=>n.endsWith('.meta.json')).map(n=>load(path.join(work,'collected',n))),failures=metadata.filter(m=>!m.ok);
- save(path.join(work,'collection-failures.json'),failures);
- const stop=path.join(work,'collection-stop-reason.json');
- state.collection={jobs:metadata.length,succeeded:metadata.length-failures.length,failed:failures.length,exitCode:collectorCode,stopReason:fs.existsSync(stop)?load(stop):null,
- queueComplete:collectorCode===0&&!fs.existsSync(stop)};
- state.social=load(path.join(work,'social-body-audit.json')).summary;
- state.status='finished-with-remaining-gaps';state.stage='finished';state.finishedAt=new Date().toISOString();update();updateProgress(summary,state);
- }catch(error){
- state.status='stopped-for-review';state.errorCode=/^[A-Z][A-Z0-9_:.-]{0,250}$/.test(error.message)?error.message:'PIPELINE_OPERATION_FAILED';update();
- // Keep preserving collection originals; never start a second publisher here.
- process.exitCode=1;
- }finally{
- if(collectorPromise)await collectorPromise;
- if(fs.existsSync(lockFile)&&load(lockFile).pid===process.pid)fs.unlinkSync(lockFile);
- }
|