CmvrControlStation/docs/task-flow/task-flow.mjs

143 lines
12 KiB
JavaScript
Raw Permalink Normal View History

// Transport-independent reference. No connection or device command is made on import.
export const executionPolicy = Object.freeze({order:'sequential',onError:'stop',automaticRetry:false,
waitStartsAfter:'operation_success',stopBehavior:'stop_scheduling_and_cancel_active_unary'});
const equal=(a,b)=>canonical(a)===canonical(b);
function canonical(v){return JSON.stringify(Array.isArray(v)?v.map(sort):sort(v));}
function sort(v){if(Array.isArray(v))return v.map(sort);if(v&&typeof v==='object')return Object.fromEntries(Object.keys(v).sort().map(k=>[k,sort(v[k])]));return v;}
const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
function check(ok,message){if(!ok)throw new Error(message);}
function integer(v,min,max){return Number.isInteger(v)&&v>=min&&v<=max;}
export function validateMessage(value,type,catalog,depth=0){
check(depth<=32,'Message nesting exceeds 32');
if(type==='google.protobuf.Timestamp'){check(typeof value==='string'&&!Number.isNaN(Date.parse(value)),'Invalid Timestamp');return;}
if(type==='google.protobuf.Duration'){check(typeof value==='string'&&/^-?\d+(\.\d{1,9})?s$/.test(value),'Invalid Duration');return;}
check(object(value),`Expected message ${type}`);const message=catalog.messages[type];check(message,`Unknown message ${type}`);
const seen=new Set(),oneofs=new Set();
function scalar(v,f){
if(f.messageType){validateMessage(v,f.messageType,catalog,depth+1);return;}
if(f.enumType){check((catalog.enums[f.enumType]||[]).some(e=>e.name===v||e.number===v),`Invalid enum ${f.name}`);return;}
if(f.type==='string'){check(typeof v==='string',`Invalid string ${f.name}`);return;}
if(f.type==='bytes'){check(typeof v==='string'&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(v),`Invalid Base64 ${f.name}`);return;}
if(f.type==='bool'){check(typeof v==='boolean',`Invalid boolean ${f.name}`);return;}
if(['int64','sint64','sfixed64','uint64','fixed64'].includes(f.type)){
check(typeof v==='string'&&/^-?\d+$/.test(v),`Use a decimal string for ${f.name}`);
const number=BigInt(v),unsigned=f.type==='uint64'||f.type==='fixed64';
check(number>=(unsigned?0n:-(1n<<63n))&&number<=(unsigned?(1n<<64n)-1n:(1n<<63n)-1n),`64-bit overflow ${f.name}`);return;
}
check(typeof v==='number'&&Number.isFinite(v),`Invalid number ${f.name}`);
if(!['float','double'].includes(f.type)){const unsigned=f.type==='uint32'||f.type==='fixed32';check(integer(v,unsigned?0:-2147483648,unsigned?4294967295:2147483647),`32-bit overflow ${f.name}`);}
}
for(const [key,v] of Object.entries(value)){
const f=message.fields.find(f=>f.name===key||f.jsonName===key);check(f,`Unknown field ${type}.${key}`);
check(!seen.has(f.name),`Duplicate field alias ${key}`);seen.add(f.name);
if(f.oneof){check(!oneofs.has(f.oneof),`Mutually exclusive fields in ${f.oneof}`);oneofs.add(f.oneof);}
if(f.map){
check(object(v),`Map must be an object: ${key}`);const fields=catalog.messages[f.messageType].fields,keyField=fields.find(f=>f.name==='key'),entry=fields.find(f=>f.name==='value');
for(const [k,item] of Object.entries(v)){
const mapKey=keyField.type==='bool'?(k==='true'?true:k==='false'?false:k):keyField.type==='string'||keyField.type.includes('64')?k:Number(k);
scalar(mapKey,keyField);scalar(item,entry);
}
}else if(f.repeated){check(Array.isArray(v),`List required ${key}`);for(const item of v)scalar(item,f);}
else scalar(v,f);
}
}
// Validate the entire plan before executing the first node. Returned order is authoritative.
export function flatten(document,catalog,groupId){
check(document.format==='cmvr.task-flow'&&!Object.hasOwn(document,'version'),'Expected cmvr.task-flow without version; normalize legacy files using Qt');
check(equal(document.executionPolicy,executionPolicy),'Unsupported execution policy');
check(Array.isArray(document.groups),'groups must be an array');const ids=new Set(),result=new Map();
const methods=new Map(catalog.services.flatMap(s=>s.methods.map(m=>[m.id,{...m,deviceType:s.deviceType}])));
const adapters=new Map(catalog.clientAdapters.map(a=>[a.id,a]));
const identify=n=>{check(typeof n.id==='string'&&n.id&&!ids.has(n.id),'Missing or duplicate id');ids.add(n.id);};
function visit(nodes,depth){
check(depth<=32&&Array.isArray(nodes),'Invalid children or excessive nesting');const steps=[];
for(const node of nodes){
check(object(node),'Node must be an object');identify(node);
if(node.kind==='loop'){
check(integer(node.count,1,100000)&&Array.isArray(node.children)&&node.children.length>0,'Invalid repeat count or empty loop');const children=visit(node.children,depth+1);
check(steps.length+children.length*node.count<=100000,'Expanded plan exceeds 100000 steps');
for(let iteration=0;iteration<node.count;iteration++)for(const entry of children)steps.push({node:entry.node,iterationPath:[{loopId:node.id,iteration},...entry.iterationPath]});
check(integer(node.waitMs??0,0,2147483647),'Invalid loop post-completion delay');
if(node.waitMs){const last=steps.at(-1);const waitMs=last.node.waitMs+node.waitMs;check(integer(waitMs,0,2147483647),'Accumulated delay exceeds limit');last.node={...last.node,waitMs};}
}else{
check(node.kind==='task'&&typeof node.deviceId==='string'&&node.deviceId,'Invalid task or deviceId');
check(integer(node.waitMs,0,2147483647)&&['ms','s'].includes(node.waitUnit),'Invalid post-completion delay');
const ex=node.execution,p=node.parameters;check(object(ex)&&object(p),'Missing execution or parameters');
if(ex.kind==='grpc_unary'){
const m=methods.get(node.operationId);check(m&&!m.clientStreaming&&!m.serverStreaming,'Unknown or streaming operation');
check(m.service===ex.service&&m.method===ex.method&&p.service===m.service&&p.method===m.method,'Conflicting RPC identity');
check(node.deviceType==='通用RPC'||(node.deviceType===m.deviceType&&node.action===`接口 · ${m.method}`),'Conflicting display action/device type');
check(integer(ex.timeoutMs,100,1800000)&&ex.timeoutMs===(p.timeoutMs??180000),'Invalid RPC timeout');
const expected=structuredClone(p.request||{}),fields=catalog.messages[m.requestType].fields;
if(fields.some(f=>f.name==='header')){expected.header={...expected.header,device_id:node.deviceId};delete expected.header.deviceId;}
else if(fields.some(f=>f.name==='device_id')){delete expected.deviceId;expected.device_id=node.deviceId;}
check(ex.completion==='rpc_response'&&equal(expected,ex.request),'Conflicting RPC payload');validateMessage(ex.request,m.requestType,catalog);
}else{
const a=adapters.get(node.operationId);check(ex.kind==='client_adapter'&&a&&ex.adapter===a.id,'Unknown client adapter');
check(a.deviceType===node.deviceType&&a.action===node.action&&ex.deviceId===node.deviceId&&equal(p,ex.parameters)&&ex.completion==='adapter_callback','Conflicting adapter payload');
}
steps.push({node,iterationPath:[]});check(steps.length<=100000,'Expanded plan exceeds 100000 steps');
}
}return steps;
}
for(const group of document.groups){identify(group);result.set(group.id,visit(group.nodes,0));}
check(result.has(groupId),'Group not found');check(result.get(groupId).length>0,'No executable tasks');return result.get(groupId);
}
function succeeded(response){
const header=response?.header??response;
check(header?.success===true,header?.error_message||header?.errorMessage||'Missing/false business success');
return response;
}
function delay(ms,signal){return new Promise((resolve,reject)=>{
if(signal?.aborted){reject(new Error('Canceled'));return;}
const abort=()=>{clearTimeout(timer);reject(new Error('Canceled'));};
const timer=setTimeout(()=>{signal?.removeEventListener('abort',abort);resolve();},ms);
signal?.addEventListener('abort',abort,{once:true});
});}
// Inject transport/adapters. The reference has no built-in gRPC-Web connection.
// rpc(service,method,request,{signal,timeoutMs}) => Promise<decoded Protobuf-JSON response>
// adapters[id](parameters,{deviceId,signal}) => Promise<{success:true,...}>
export async function execute(document,catalog,groupId,{rpc,adapters={},signal,onEvent=()=>{}}){
const steps=flatten(document,catalog,groupId);
for(const {node} of steps)if(node.execution.kind==='client_adapter')check(typeof adapters[node.execution.adapter]==='function',`Missing adapter ${node.execution.adapter}`);
for(let index=0;index<steps.length;index++){
const {node,iterationPath}=steps[index],context={nodeId:node.id,index,iterationPath};let timer,detach=()=>{};
try{
check(!signal?.aborted,'Canceled');onEvent({...context,state:'running'});const ex=node.execution;let response;
if(ex.kind==='grpc_unary'){
check(typeof rpc==='function','RPC transport required');const controller=new AbortController();
const canceled=()=>controller.abort();signal?.addEventListener('abort',canceled,{once:true});detach=()=>signal?.removeEventListener('abort',canceled);
const request=structuredClone(ex.request),m=catalog.services.flatMap(s=>s.methods).find(m=>m.id===node.operationId);
const nested=catalog.messages[m.requestType].fields.some(f=>f.name==='header');const h=nested?(request.header??={}):request;
delete h.commandId;h.command_id=globalThis.crypto.randomUUID();h.timestamp=new Date().toISOString();
const interrupted=new Promise((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new Error('Canceled or deadline exceeded; physical stop not confirmed')),{once:true}));
timer=setTimeout(()=>controller.abort(),ex.timeoutMs);
if(ex.service==='cmvr.api.ArmService'&&ex.method==='moveL'&&
(request.user_coordinate_name||request.userCoordinateName||'user_frame_pose' in request||'userFramePose' in request||'tcp_offset' in request||'tcpOffset' in request)){
let probeTimer;
try{
const probe=await Promise.race([rpc(ex.service,'ExecuteJsonCommand',{header:{device_id:node.deviceId},request_json:'{"command":"get_active_tcp_offset"}'},{signal:controller.signal,timeoutMs:3000}),interrupted,
new Promise((_,reject)=>{probeTimer=setTimeout(()=>reject(new Error('Coordinate capability probe timed out; no motion sent')),3000);})]);
succeeded(probe);const capability=JSON.parse(probe.response_json??probe.responseJson??'{}');
check(capability.coordinate_api_version>=4&&capability.movel_target_mode==='absolute_selected_frame','Absolute selected-frame MoveL unsupported; no motion sent');
}finally{clearTimeout(probeTimer);}
}
response=await Promise.race([Promise.resolve().then(()=>rpc(ex.service,ex.method,request,{signal:controller.signal,timeoutMs:ex.timeoutMs})),interrupted]);
}else {
const interrupted=new Promise((_,reject)=>{
const abort=()=>reject(new Error('Canceled; adapter/device stop not confirmed'));
signal?.addEventListener('abort',abort,{once:true});detach=()=>signal?.removeEventListener('abort',abort);
});
response=await Promise.race([Promise.resolve().then(()=>adapters[ex.adapter](structuredClone(ex.parameters),{deviceId:node.deviceId,signal})),interrupted]);
}
clearTimeout(timer);detach();succeeded(response);check(!signal?.aborted,'Canceled');
onEvent({...context,state:'succeeded',response});
if(node.waitMs){onEvent({...context,state:'waiting',waitMs:node.waitMs});await delay(node.waitMs,signal);}
}catch(error){clearTimeout(timer);detach();onEvent({...context,state:signal?.aborted?'canceled':'failed',error:String(error)});throw error;}
}
onEvent({state:'completed',completedSteps:steps.length});return {success:true,completedSteps:steps.length};
}