Explorar el Código

fix(sync): restore direct gateway isolated runtime compatibility

彭峰 hace 18 horas
padre
commit
8765c85931

+ 2 - 1
scripts/lib/legacy-direct-bundle.mjs

@@ -1,6 +1,7 @@
 import {readFileSync} from 'node:fs';
 import {specs} from './legacy-direct-specs.mjs';
 import {legacyAddonFields} from './legacy-direct-projection.mjs';
+import {withXiaoshuRuntime} from './xiaoshu-runtime-compat.mjs';
 export function buildDirectBundle(columns,windows=[],company='7pIbDBJmKx') {
  const definitions=structuredClone(specs);
  for(const [m,s] of Object.entries(definitions)){
@@ -12,5 +13,5 @@ export function buildDirectBundle(columns,windows=[],company='7pIbDBJmKx') {
  const userSource=readFileSync(new URL('../backfill-legacy-users.mjs',import.meta.url),'utf8');
  const userProjection=userSource.slice(userSource.indexOf('function text(value)'),userSource.indexOf('function requestGroups('));
  const prefix='const company={__type:"Pointer",className:"Company",objectId:'+JSON.stringify(company)+'};\n'+userProjection;
- return (prefix+['legacy-finance','legacy-direct-supplement','legacy-direct-control','legacy-direct-sync'].map(n=>readFileSync(new URL('../cloud/'+n+'.js',import.meta.url),'utf8')).join('\n')).replaceAll('__SPECS__',JSON.stringify(definitions)).replaceAll('__WINDOWS__',JSON.stringify(windows)).replaceAll('__COMPANY_ID__',JSON.stringify(company));
+ return withXiaoshuRuntime((prefix+['legacy-finance','legacy-direct-supplement','legacy-direct-control','legacy-direct-sync'].map(n=>readFileSync(new URL('../cloud/'+n+'.js',import.meta.url),'utf8')).join('\n')).replaceAll('__SPECS__',JSON.stringify(definitions)).replaceAll('__WINDOWS__',JSON.stringify(windows)).replaceAll('__COMPANY_ID__',JSON.stringify(company)));
 }

+ 54 - 0
scripts/repair-direct-sync-runtime.mjs

@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+import {readFileSync,writeFileSync,mkdirSync,statSync} from 'node:fs';
+import {createHash} from 'node:crypto';
+import {join} from 'node:path';
+import {withXiaoshuRuntime} from './lib/xiaoshu-runtime-compat.mjs';
+
+const keyFile=process.env.XIAOSHU_MASTER_KEY_FILE;
+const token=process.env.XIAOSHU_SYNC_OPERATOR_TOKEN;
+const backupDir=process.env.XIAOSHU_DIRECT_DEPLOY_REPORT_DIR;
+if(!keyFile||!token||!backupDir)throw Error('Private key file, operator session, and backup directory required');
+if((statSync(keyFile).mode&0o077)!==0)throw Error('Master key file must be private');
+const key=readFileSync(keyFile,'utf8').trim();
+if(!key)throw Error('Master key file is empty');
+const base=(process.env.XIAOSHU_PARSE_URL||'https://server.xiaoshu.pro/parse').replace(/\/$/,'');
+const app=process.env.XIAOSHU_PARSE_APP_ID||'7pIbDBJmKx_main';
+const headers={'Content-Type':'application/json','X-Parse-Application-Id':app,'X-Parse-Master-Key':key};
+const hash=s=>createHash('sha256').update(s).digest('hex');
+async function api(path,method='GET',body){
+ const response=await fetch(base+path,{method,headers,...(body?{body:JSON.stringify(body)}:{}),signal:AbortSignal.timeout(60000)});
+ const result=await response.json();
+ if(!response.ok||result.error)throw Error('Parse function API HTTP '+response.status);
+ return result;
+}
+const name='xiaoshu.sync.direct-v1';
+const found=(await api('/classes/Function?'+new URLSearchParams({where:JSON.stringify({name}),limit:'2'}))).results;
+if(found.length!==1||found[0].path!=='xiaoshu/sync/direct-v1'||found[0].enabled!==true)throw Error('Unexpected direct sync function');
+const current=await api('/classes/Function/'+found[0].objectId);
+if(!current.code?.includes('await u.fetch({useMasterKey:true})'))throw Error('Unknown direct sync source');
+if(current.code.includes('XIAOSHU_ISOLATED_RUNTIME_COMPAT_V1'))throw Error('Runtime compatibility already installed');
+const updated=withXiaoshuRuntime(current.code);
+new Function(updated);
+mkdirSync(backupDir,{recursive:true,mode:0o700});
+if((statSync(backupDir).mode&0o077)!==0)throw Error('Backup directory must be private');
+const backup=join(backupDir,'function-before.json');
+writeFileSync(backup,JSON.stringify(current),{mode:0o600,flag:'wx'});
+let changed=false;
+try{
+ await api('/classes/Function/'+current.objectId,'PUT',{code:updated});changed=true;
+ const actual=await api('/classes/Function/'+current.objectId);
+ if(actual.code!==updated)throw Error('Deployed function readback mismatch');
+ const url=base.replace(/\/parse$/,'/api/functions/xiaoshu/sync/direct-v1');
+ const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token,params:{action:'status'}}),signal:AbortSignal.timeout(60000)});
+ const result=await response.json();
+ if(!response.ok||!result.success||result.data?.source!=='old-api/WXAPP'||result.data?.bridgeUsed!==false)throw Error('Direct sync status smoke failed');
+ writeFileSync(join(backupDir,'function-after.json'),JSON.stringify(actual),{mode:0o600,flag:'wx'});
+ console.log(JSON.stringify({deployed:true,before:hash(current.code),after:hash(updated),statusHttp:response.status,backup}));
+}catch(error){
+ if(changed){
+  await api('/classes/Function/'+current.objectId,'PUT',{code:current.code});
+  const restored=await api('/classes/Function/'+current.objectId);
+  if(restored.code!==current.code)throw Error('Direct sync rollback readback failed; backup at '+backup);
+ }
+ throw error;
+}

+ 1 - 1
scripts/tests/direct-nightly-sync.test.mjs

@@ -39,7 +39,7 @@ before(async()=>{
  await db.exec(lessonSource.match(/CREATE OR REPLACE VIEW xs_review_task_link AS[\s\S]*?;/)[0]);
  await db.exec(readFileSync(new URL('../sql/legacy-review-sync.sql',import.meta.url),'utf8'));
  const columns=await sql("SELECT table_name,column_name FROM information_schema.columns WHERE table_schema='public'");
- context={Psql,Parse:{Config:{get:async()=>({get:k=>({legacyScheduleApiUrl:'https://legacy.invalid/api',legacyScheduleApiId:'test',legacyScheduleApiKey:'test'}[k])})}},fetch:async()=>({ok:true,json:async()=>({retcode:0,result:[{GeneralID:101,kcid:'5',xxcs:1}],page:{itemCount:1,pageCount:1}})}),AbortSignal,Date,console};
+ context={Psql,Parse:{User:function(){},Config:{get:async()=>({get:k=>({legacyScheduleApiUrl:'https://legacy.invalid/api',legacyScheduleApiId:'test',legacyScheduleApiKey:'test'}[k])})}},fetch:async()=>({ok:true,json:async()=>({retcode:0,result:[{GeneralID:101,kcid:'5',xxcs:1}],page:{itemCount:1,pageCount:1}})}),AbortSignal,Date,console};
  vm.createContext(context);vm.runInContext(buildDirectBundle(columns,[],'co'),context);
  const r=await call({action:'claim',proposedRunId:'test-run-00001'});assert.equal(r.success,true,JSON.stringify(r));runId=r.data.runId;
 });