CmvrControlStation/scripts/generate_taskflow_schema.py

66 lines
6.5 KiB
Python
Raw Normal View History

"""Generate the external JSON Schema from the catalog exported by taskapi_test or the Qt app."""
import json
from pathlib import Path
root=Path("docs/task-flow")
catalog=json.loads((root/"task_operations.json").read_text(encoding="utf-8"))
ref=lambda name:{"$ref":"#/$defs/"+name}
msgref=lambda name:{"$ref":"#/$defs/message."+name}
def scalar(f):
if "messageType" in f:return msgref(f["messageType"])
if "enumType" in f:return {"enum":[x["name"] for x in catalog["enums"][f["enumType"]]]+[x["number"] for x in catalog["enums"][f["enumType"]]]}
t=f["type"]
if t in ["string","bytes"]:return {"type":"string",**({"contentEncoding":"base64"} if t=="bytes" else {})}
if t=="bool":return {"type":"boolean"}
if t in ["int64","sint64","sfixed64"]:return {"type":"string","pattern":"^-?[0-9]+$"}
if t in ["uint64","fixed64"]:return {"type":"string","pattern":"^[0-9]+$"}
if t in ["float","double"]:return {"type":"number"}
unsigned=t in ["uint32","fixed32"]
return {"type":"integer","minimum":0 if unsigned else -2147483648,"maximum":4294967295 if unsigned else 2147483647}
messages={}
for name,m in catalog["messages"].items():
if name=="google.protobuf.Timestamp":messages[name]={"type":"string","format":"date-time"};continue
props={};rules=[];unions={}
for f in m["fields"]:
if f["map"]:
entry=catalog["messages"][f["messageType"]]["fields"]
field={"type":"object","additionalProperties":scalar(next(x for x in entry if x["name"]=="value"))}
elif f["repeated"]:field={"type":"array","items":scalar(f)}
else:field=scalar(f)
props[f["name"]]=field
if f["name"]!=f["jsonName"]:
props[f["jsonName"]]=field;rules.append({"not":{"required":[f["name"],f["jsonName"]]}})
if f.get("oneof"):unions.setdefault(f["oneof"],[]).append(f)
for union in unions.values():
for i,a in enumerate(union):
for b in union[i+1:]:
for ak in set([a["name"],a["jsonName"]]):
for bk in set([b["name"],b["jsonName"]]):rules.append({"not":{"required":[ak,bk]}})
messages[name]={"type":"object","properties":props,"additionalProperties":False,**({"allOf":rules} if rules else {})}
policy={"order":"sequential","onError":"stop","automaticRetry":False,"waitStartsAfter":"operation_success","stopBehavior":"stop_scheduling_and_cancel_active_unary"}
methods=[m for s in catalog["services"] for m in s["methods"] if not m["clientStreaming"] and not m["serverStreaming"]]
common={"id":{"type":"string","minLength":1},"name":{"type":"string"}}
task={"type":"object","required":["id","name","kind","deviceType","deviceId","action","parameters","operationId","execution","waitMs","waitUnit"],"properties":{
**common,"kind":{"const":"task"},"deviceType":{"type":"string"},"deviceId":{"type":"string","minLength":1},"action":{"type":"string","minLength":1},
"parameters":{"type":"object"},"operationId":{"type":"string"},"waitMs":{"type":"integer","minimum":0,"maximum":2147483647},"waitUnit":{"enum":["ms","s"]},
"execution":{"oneOf":[ref("rpc"),ref("adapter")]}},"allOf":[]}
for m in methods:
request=msgref(m["requestType"])
task["allOf"].append({"if":{"properties":{"operationId":{"const":m["id"]}}},"then":{"properties":{
"parameters":{"type":"object","required":["service","method","request"],"properties":{"service":{"const":m["service"]},"method":{"const":m["method"]},"request":request,"timeoutMs":{"type":"integer","minimum":100,"maximum":1800000}}},
"execution":{"properties":{"kind":{"const":"grpc_unary"},"service":{"const":m["service"]},"method":{"const":m["method"]},"request":request}}}}})
for a in catalog["clientAdapters"]:
task["allOf"].append({"if":{"properties":{"operationId":{"const":a["id"]}}},"then":{"properties":{
"deviceType":{"const":a["deviceType"]},"action":{"const":a["action"]},"parameters":a["parametersSchema"],
"execution":{"properties":{"kind":{"const":"client_adapter"},"adapter":{"const":a["id"]},"parameters":a["parametersSchema"]}}}}})
task["properties"]["operationId"]={"enum":[m["id"] for m in methods]+[a["id"] for a in catalog["clientAdapters"]]}
schema={"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"urn:cmvr:task-flow","title":"CMVR portable task flow","type":"object","required":["format","executionPolicy","groups"],"properties":{
"format":{"const":"cmvr.task-flow"},"executionPolicy":{"const":policy},"groups":{"type":"array","items":ref("group")}},"$defs":{
**{"message."+name:value for name,value in messages.items()},"node":{"oneOf":[ref("task"),ref("loop")]},"task":task,
"group":{"type":"object","required":["id","name","nodes"],"properties":{**common,"nodes":{"type":"array","items":ref("node")}}},
"loop":{"type":"object","required":["id","name","kind","count","children"],"properties":{**common,"kind":{"const":"loop"},"count":{"type":"integer","minimum":1,"maximum":100000},"collapsed":{"type":"boolean"},"waitMs":{"type":"integer","minimum":0,"maximum":2147483647},"children":{"type":"array","items":ref("node")}}},
"rpc":{"type":"object","required":["kind","service","method","request","timeoutMs","completion"],"properties":{"kind":{"const":"grpc_unary"},"service":{"type":"string"},"method":{"type":"string"},"request":{"type":"object"},"timeoutMs":{"type":"integer","minimum":100,"maximum":1800000},"completion":{"const":"rpc_response"}}},
"adapter":{"type":"object","required":["kind","adapter","deviceId","parameters","completion"],"properties":{"kind":{"const":"client_adapter"},"adapter":{"type":"string"},"deviceId":{"type":"string"},"parameters":{"type":"object"},"completion":{"const":"adapter_callback"}}}}}
task["properties"]["serverCalls"]={"type":"array","minItems":1,"items":{"type":"object","required":["service","method","rpcPath","requestType","responseType","clientStreaming","serverStreaming","mode","request"],"properties":{"service":{"type":"string"},"method":{"type":"string"},"rpcPath":{"type":"string"},"requestType":{"type":"string"},"responseType":{"type":"string"},"clientStreaming":{"type":"boolean"},"serverStreaming":{"type":"boolean"},"mode":{"enum":["unary","open_stream","close_stream"]},"request":{"type":"object"},"sessionKey":{"type":"string"},"runtimeRequestFields":{"type":"array","items":{"type":"string"}},"runtimeHeaderFields":{"type":"array","items":{"type":"string"}}}}}
(root/"task-flow.schema.json").write_text(json.dumps(schema,ensure_ascii=False,indent=2)+"\n",encoding="utf-8")
print("Generated schema for",len(methods),"unary methods and",len(catalog["clientAdapters"]),"client adapters")