diff --git a/deploy/erp_datahub_sync_draft.json b/deploy/erp_datahub_sync_draft.json new file mode 100644 index 0000000..23d8984 --- /dev/null +++ b/deploy/erp_datahub_sync_draft.json @@ -0,0 +1 @@ +{"graph":{"nodes":[{"id":"9000000000001","type":"custom","position":{"x":40,"y":260},"positionAbsolute":{"x":40,"y":260},"width":242,"height":108,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"start","title":"开始","desc":"","selected":false,"variables":[{"type":"text-input","variable":"force","label":"force(填true强制全量重同步)","required":false,"options":[],"default":"","hint":"","placeholder":""}]}},{"id":"9000000000002","type":"custom","position":{"x":340,"y":260},"positionAbsolute":{"x":340,"y":260},"width":242,"height":180,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"code","title":"采集输入指纹","desc":"","code_language":"python3","code":"import requests, json, hashlib, base64\n\nGITEA = \"http://gitea:3000\"\nERP = \"http://mini-erp-app:8000\"\nREPO = \"admin/mini-erp-fabric-demo\"\nGH = {\"Authorization\": \"token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c\"}\n\ndef sha256(s):\n return hashlib.sha256(s.encode(\"utf-8\")).hexdigest()\n\ndef main(force: str):\n tables = requests.get(ERP + \"/api/governance/tables\", timeout=15).json()[\"tables\"]\n docs = \"\"\n for f in [\"01-\\u7cfb\\u7edf\\u4ecb\\u7ecd\", \"03-\\u4e1a\\u52a1\\u8bf4\\u660e\"]:\n r = requests.get(GITEA + \"/\" + REPO + \"/raw/branch/main/docs/\" + f + \".md\", headers=GH, timeout=15)\n if r.status_code == 200:\n docs += \"\\n\\n## \" + f + \"\\n\" + r.text\n su = GITEA + \"/api/v1/repos/\" + REPO + \"/contents/05_sync/erp_datahub_state.json\"\n state, state_sha = {}, \"\"\n rr = requests.get(su, headers=GH, timeout=15)\n if rr.status_code == 200:\n jj = rr.json()\n state = json.loads(base64.b64decode(jj[\"content\"]).decode(\"utf-8\"))\n state_sha = jj.get(\"sha\", \"\")\n table_hashes = {t[\"table_name\"]: sha256(json.dumps(t, ensure_ascii=False, sort_keys=True)) for t in tables}\n global_hash = sha256(json.dumps(tables, ensure_ascii=False, sort_keys=True) + \"||\" + docs)\n docs_hash = sha256(docs)\n prev = state.get(\"table_hashes\", {})\n changed = sorted([t[\"table_name\"] for t in tables if prev.get(t[\"table_name\"]) != table_hashes[t[\"table_name\"]]])\n force_on = (force or \"\").strip().lower() == \"true\"\n skip = (not force_on) and state.get(\"global_hash\") == global_hash\n return {\n \"skip\": skip,\n \"tables_json\": json.dumps(tables, ensure_ascii=False),\n \"docs_text\": docs,\n \"changed_tables\": changed,\n \"global_hash\": global_hash,\n \"docs_hash\": docs_hash,\n \"table_hashes_json\": json.dumps(table_hashes),\n \"state_sha\": state_sha,\n \"prev_state_json\": json.dumps(state, ensure_ascii=False),\n }","variables":[{"variable":"force","value_selector":["9000000000001","force"],"value_type":"string"}],"outputs":{"skip":{"type":"boolean","children":null},"tables_json":{"type":"string","children":null},"docs_text":{"type":"string","children":null},"changed_tables":{"type":"array[string]","children":null},"global_hash":{"type":"string","children":null},"docs_hash":{"type":"string","children":null},"table_hashes_json":{"type":"string","children":null},"state_sha":{"type":"string","children":null},"prev_state_json":{"type":"string","children":null}},"selected":false}},{"id":"9000000000003","type":"custom","position":{"x":700,"y":260},"positionAbsolute":{"x":700,"y":260},"width":242,"height":130,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"if-else","title":"需要更新?","desc":"","selected":false,"cases":[{"case_id":"true","logical_operator":"and","conditions":[{"id":"cond_skip","varType":"boolean","variable_selector":["9000000000002","skip"],"comparison_operator":"is","value":"false"}]}]}},{"id":"9000000000004","type":"custom","position":{"x":1040,"y":460},"positionAbsolute":{"x":1040,"y":460},"width":242,"height":100,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"end","title":"无变更结束","desc":"","selected":false,"outputs":[{"variable":"result","value_type":"string","value_selector":["9000000000002","global_hash"]}]}},{"id":"9000000000005","type":"custom","position":{"x":1040,"y":180},"positionAbsolute":{"x":1040,"y":180},"width":242,"height":120,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"llm","title":"生成治理规格","desc":"","selected":false,"model":{"provider":"langgenius/siliconflow/siliconflow","name":"Pro/moonshotai/Kimi-K2.5","mode":"chat","completion_params":{"temperature":0.1}},"prompt_template":[{"role":"system","text":"你是数据治理与 DataHub 元数据专家。阅读【ERP库表结构】(information_schema 导出, 含表/字段中文注释)与【治理底稿】(系统介绍+业务说明, 含状态码映射/指标口径/敏感字段规则), 产出 DataHub 治理规格。\n\n只输出一个严格 JSON 对象(不要 markdown 代码围栏、不要任何解释), 结构:\n{\"domains\":[{\"key\":\"master\",\"name\":\"ERP主数据域\",\"description\":\"一句话\"}],\n \"tags\":[{\"key\":\"erp_xxx\",\"name\":\"erp_xxx\",\"description\":\"一句话\"}],\n \"terms\":[{\"key\":\"erp_xxx\",\"name\":\"中文术语名\",\"description\":\"含口径/枚举值\"}],\n \"datasets\":[{\"table\":\"表名\",\"description\":\"2-3句业务描述\",\"domain_key\":\"master\",\"tags\":[\"tag_key\"],\"term_fields\":[{\"field\":\"字段名\",\"term_key\":\"term_key\"}]}]}\n\n硬性规则:\n1. domains 固定5个: master(主数据)/purchase(采购)/sales(销售)/inventory(库存)/governance(治理), key 即上述英文。\n2. datasets 必须覆盖全部10张表, table 用真实表名, 按前缀归域: md_/mdm_→master, po_→purchase, so_→sales, inv_→inventory。\n3. tags 至少含: erp_master, erp_purchase, erp_sales, erp_inventory, erp_sensitive(敏感字段表), erp_demo。\n4. terms 从底稿提炼: 至少包含 状态机术语(主数据状态/采购单状态/销售单状态)与指标口径(采购入库金额/销售出库金额)与敏感字段规则(联系电话脱敏), key 用 erp_ 前缀蛇形英文。\n5. 含 contact_phone 的表(md_supplier/md_customer)必须打 erp_sensitive 标签, 且该字段关联敏感术语。\n6. 全部中文描述, 术语口径必须与底稿一致, 禁止编造。"},{"role":"user","text":"【ERP库表结构】\n{{#9000000000002.tables_json#}}\n\n【治理底稿】\n{{#9000000000002.docs_text#}}"}],"context":{"enabled":false,"variable_selector":[]},"vision":{"enabled":false},"reasoning_format":"separated","variables":[],"retry_config":{"retry_enabled":true,"max_retries":2,"retry_interval":1000}}},{"id":"9000000000006","type":"custom","position":{"x":1400,"y":180},"positionAbsolute":{"x":1400,"y":180},"width":242,"height":180,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"code","title":"创建治理实体","desc":"","code_language":"python3","code":"import requests, json, re\n\nDH = \"http://datahub-datahub-gms-1:8080\"\nHDRS = {\"Authorization\": \"Bearer app-iBQEBasOC4aVSn2xZRxPk5zW\", \"Content-Type\": \"application/json\"}\n\ndef gql(q, v=None):\n r = requests.post(DH + \"/api/graphql\", headers=HDRS, json={\"query\": q, \"variables\": v or {}}, timeout=20)\n j = r.json()\n if \"errors\" in j:\n raise Exception(str(j[\"errors\"][0][\"message\"])[:200])\n return j[\"data\"]\n\ndef parse_json(t):\n t = t.strip().replace(\"```json\", \"\").replace(\"```\", \"\").strip()\n s, e = t.find(\"{\"), t.rfind(\"}\")\n return json.loads(t[s:e + 1])\n\ndef exists_aspect(urn, aspect):\n from urllib.parse import quote\n r = requests.get(DH + \"/aspects/\" + quote(urn, safe=\"\") + \"?aspect=\" + aspect + \"&version=0\", headers=HDRS, timeout=15)\n return r.status_code == 200\n\ndef main(spec_text: str, docs_hash: str, prev_state_json: str):\n spec = parse_json(spec_text)\n prev = json.loads(prev_state_json) if prev_state_json else {}\n urns = {\"domains\": {}, \"tags\": {}, \"terms\": {}}\n created = {\"domains\": 0, \"tags\": 0, \"terms\": 0}\n dl = gql('query{ listDomains(input:{start:0,count:100}) { domains { urn properties { name } } } }')\n existing = {}\n for d in dl[\"listDomains\"][\"domains\"]:\n p = d.get(\"properties\") or {}\n if p.get(\"name\"):\n existing[p[\"name\"]] = d[\"urn\"]\n for dom in spec.get(\"domains\", []):\n if dom[\"name\"] in existing:\n urns[\"domains\"][dom[\"key\"]] = existing[dom[\"name\"]]\n else:\n u = gql('mutation($i:CreateDomainInput!){ createDomain(input:$i) }', {\"i\": {\"name\": dom[\"name\"], \"description\": dom.get(\"description\", \"\")}})[\"createDomain\"]\n urns[\"domains\"][dom[\"key\"]] = u\n created[\"domains\"] += 1\n for tg in spec.get(\"tags\", []):\n u = \"urn:li:tag:\" + tg[\"key\"]\n if not exists_aspect(u, \"tagProperties\"):\n gql('mutation($i:CreateTagInput!){ createTag(input:$i) }', {\"i\": {\"id\": tg[\"key\"], \"name\": tg[\"key\"], \"description\": tg.get(\"description\", \"\")}})\n created[\"tags\"] += 1\n urns[\"tags\"][tg[\"key\"]] = u\n reuse_terms = prev.get(\"term_urns\", {}) if prev.get(\"docs_hash\") == docs_hash else {}\n for tm in spec.get(\"terms\", []):\n key = tm[\"key\"]\n if key in reuse_terms:\n urns[\"terms\"][key] = reuse_terms[key]\n continue\n u = \"urn:li:glossaryTerm:\" + key\n if not exists_aspect(u, \"glossaryTerm\"):\n gql('mutation($i:CreateGlossaryEntityInput!){ createGlossaryTerm(input:$i) }', {\"i\": {\"id\": key, \"name\": tm[\"name\"], \"description\": tm.get(\"description\", \"\")}})\n created[\"terms\"] += 1\n urns[\"terms\"][key] = u\n return {\n \"urns_json\": json.dumps(urns),\n \"spec_json\": json.dumps(spec, ensure_ascii=False),\n \"created_json\": json.dumps(created),\n }","variables":[{"variable":"spec_text","value_selector":["9000000000005","text"],"value_type":"string"},{"variable":"docs_hash","value_selector":["9000000000002","docs_hash"],"value_type":"string"},{"variable":"prev_state_json","value_selector":["9000000000002","prev_state_json"],"value_type":"string"}],"outputs":{"urns_json":{"type":"string","children":null},"spec_json":{"type":"string","children":null},"created_json":{"type":"string","children":null}},"selected":false}},{"id":"9000000000007","type":"custom","position":{"x":1760,"y":180},"positionAbsolute":{"x":1760,"y":180},"width":242,"height":180,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"code","title":"组装同步任务","desc":"","code_language":"python3","code":"import json\n\ndef main(tables_json: str, spec_json: str, urns_json: str, changed_tables: list):\n tables = json.loads(tables_json)\n spec = json.loads(spec_json)\n urns = json.loads(urns_json)\n ds_spec = {d[\"table\"]: d for d in spec.get(\"datasets\", [])}\n tag_map = urns[\"tags\"]\n dom_map = urns[\"domains\"]\n ops = []\n for t in tables:\n if t[\"table_name\"] not in changed_tables:\n continue\n d = ds_spec.get(t[\"table_name\"], {})\n cols = [{\"name\": c[\"name\"], \"type\": c[\"type\"], \"nullable\": c[\"nullable\"], \"comment\": c[\"comment\"]} for c in t[\"columns\"]]\n ops.append(json.dumps({\n \"table\": t[\"table_name\"],\n \"comment\": t.get(\"table_comment\") or \"\",\n \"columns\": cols,\n \"description\": d.get(\"description\") or t.get(\"table_comment\") or \"\",\n \"domain_urn\": dom_map.get(d.get(\"domain_key\", \"\")),\n \"tag_urns\": [tag_map[k] for k in d.get(\"tags\", []) if k in tag_map],\n }, ensure_ascii=False))\n return {\"ops\": ops}","variables":[{"variable":"tables_json","value_selector":["9000000000002","tables_json"],"value_type":"string"},{"variable":"spec_json","value_selector":["9000000000006","spec_json"],"value_type":"string"},{"variable":"urns_json","value_selector":["9000000000006","urns_json"],"value_type":"string"},{"variable":"changed_tables","value_selector":["9000000000002","changed_tables"],"value_type":"array[string]"}],"outputs":{"ops":{"type":"array[string]","children":null}},"selected":false}},{"id":"9000000000008","type":"custom","position":{"x":2120,"y":160},"positionAbsolute":{"x":2120,"y":160},"width":620,"height":220,"selected":false,"sourcePosition":"right","targetPosition":"left","zIndex":1,"data":{"type":"iteration","title":"逐表同步DataHub","desc":"","selected":false,"is_parallel":false,"parallel_nums":4,"error_handle_mode":"continue-on-error","iterator_selector":["9000000000007","ops"],"iterator_input_type":"array[string]","output_selector":["9000000000009","result"],"output_type":"array[string]","is_iterating":true,"flatten_output":false,"start_node_id":"9000000000008start","width":620,"height":220}},{"id":"9000000000008start","type":"custom-iteration-start","parentId":"9000000000008","position":{"x":24,"y":68},"positionAbsolute":{"x":2144,"y":228},"width":44,"height":48,"selected":false,"draggable":false,"selectable":false,"sourcePosition":"right","targetPosition":"left","zIndex":1002,"data":{"type":"iteration-start","title":"","desc":"","isInIteration":true,"selected":false}},{"id":"9000000000009","type":"custom","position":{"x":2200,"y":228},"positionAbsolute":{"x":2200,"y":228},"width":242,"height":180,"selected":false,"sourcePosition":"right","targetPosition":"left","parentId":"9000000000008","zIndex":1002,"data":{"type":"code","title":"执行单表同步","desc":"","code_language":"python3","code":"import requests, json, time\nfrom urllib.parse import quote\n\nDH = \"http://datahub-datahub-gms-1:8080\"\nHDRS = {\"Authorization\": \"Bearer app-iBQEBasOC4aVSn2xZRxPk5zW\", \"Content-Type\": \"application/json\"}\n\ndef type_union(t):\n t = (t or \"\").lower()\n if any(k in t for k in [\"datetime\", \"timestamp\"]) or t in (\"date\", \"year\"):\n return {\"com.linkedin.schema.DateType\": {}}\n if t == \"time\":\n return {\"com.linkedin.schema.TimeType\": {}}\n if any(k in t for k in [\"int\", \"decimal\", \"float\", \"double\", \"numeric\"]):\n return {\"com.linkedin.schema.NumberType\": {}}\n if any(k in t for k in [\"blob\", \"binary\", \"varbinary\", \"json\"]):\n return {\"com.linkedin.schema.BytesType\": {}}\n return {\"com.linkedin.schema.StringType\": {}}\n\ndef propose(aspect_name, urn, value):\n body = {\"proposal\": {\"entityType\": \"dataset\", \"entityUrn\": urn, \"changeType\": \"UPSERT\", \"aspectName\": aspect_name,\n \"aspect\": {\"contentType\": \"application/json\", \"value\": json.dumps(value)}}}\n r = requests.post(DH + \"/aspects?action=ingestProposal\", headers=HDRS, json=body, timeout=25)\n return (\"ok\" if r.status_code == 200 and \"success\" in r.text else \"err\", r.text[:100])\n\ndef gql(q, v):\n r = requests.post(DH + \"/api/graphql\", headers=HDRS, json={\"query\": q, \"variables\": v}, timeout=25)\n j = r.json()\n if \"errors\" in j:\n return (\"err\", str(j[\"errors\"][0][\"message\"])[:100])\n return (\"ok\", \"\")\n\ndef main(item: str):\n op = json.loads(item)\n tbl = op[\"table\"]\n urn = \"urn:li:dataset:(urn:li:dataPlatform:mysql,mini_erp.\" + tbl + \",PROD)\"\n ts = int(time.time() * 1000)\n who = {\"actor\": \"urn:li:corpuser:datahub\", \"time\": ts}\n fields = [{\"fieldPath\": c[\"name\"], \"type\": {\"type\": type_union(c[\"type\"])}, \"nativeType\": c[\"type\"],\n \"nativeDataType\": c[\"type\"], \"nullable\": bool(c[\"nullable\"]),\n \"description\": c[\"comment\"] or c[\"name\"]} for c in op[\"columns\"]]\n sm = {\"platform\": \"urn:li:dataPlatform:mysql\", \"schemaName\": \"mini_erp.\" + tbl,\n \"platformSchema\": {\"com.linkedin.schema.MySqlDDL\": {\"tableSchema\": \"\"}},\n \"fields\": fields, \"hash\": \"\", \"version\": 0, \"created\": who, \"lastModified\": who}\n dp = {\"schemaName\": \"mini_erp.\" + tbl, \"description\": op[\"description\"],\n \"customProperties\": {\"database\": \"mini_erp\", \"table\": tbl, \"table_comment\": op[\"comment\"]},\n \"qualifiedName\": \"mysql.mini_erp.\" + tbl, \"platform\": \"urn:li:dataPlatform:mysql\",\n \"version\": 0, \"created\": who, \"lastModified\": who}\n r1 = propose(\"schemaMetadata\", urn, sm)\n r2 = propose(\"datasetProperties\", urn, dp)\n r3 = gql(\"mutation($e:String!,$d:String!){ setDomain(entityUrn:$e, domainUrn:$d) }\", {\"e\": urn, \"d\": op[\"domain_urn\"]}) if op.get(\"domain_urn\") else (\"skip\", \"\")\n r4 = gql(\"mutation($i:AddTagsInput!){ addTags(input:$i) }\", {\"i\": {\"tagUrns\": op[\"tag_urns\"], \"resourceUrn\": urn}}) if op.get(\"tag_urns\") else (\"skip\", \"\")\n return {\"result\": json.dumps({\"table\": tbl, \"schemaMetadata\": r1[0], \"datasetProperties\": r2[0],\n \"domain\": r3[0], \"tags\": r4[0],\n \"detail\": [r1[1], r2[1], r3[1], r4[1]]}, ensure_ascii=False)}","variables":[{"variable":"item","value_selector":["9000000000008","item"],"value_type":"string"}],"outputs":{"result":{"type":"string","children":null}},"selected":false,"isInIteration":true,"iteration_id":"9000000000008"}},{"id":"9000000000010","type":"custom","position":{"x":2820,"y":180},"positionAbsolute":{"x":2820,"y":180},"width":242,"height":200,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"code","title":"回写同步状态","desc":"","code_language":"python3","code":"import requests, json, base64\nfrom datetime import datetime\n\nGITEA = \"http://gitea:3000\"\nREPO = \"admin/mini-erp-fabric-demo\"\nGH = {\"Authorization\": \"token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c\", \"Content-Type\": \"application/json\"}\n\ndef main(global_hash: str, docs_hash: str, table_hashes_json: str, urns_json: str, created_json: str,\n prev_state_json: str, state_sha: str, sync_results: list, changed_tables: list):\n prev = json.loads(prev_state_json) if prev_state_json else {}\n results = [json.loads(x) for x in sync_results if x]\n ok_tables = [r[\"table\"] for r in results if r.get(\"schemaMetadata\") == \"ok\" and r.get(\"datasetProperties\") == \"ok\"]\n state = {\n \"global_hash\": global_hash,\n \"docs_hash\": docs_hash,\n \"table_hashes\": json.loads(table_hashes_json),\n \"term_urns\": json.loads(urns_json)[\"terms\"],\n \"last_created\": json.loads(created_json),\n \"last_ok_tables\": ok_tables,\n \"updated_at\": datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"runs\": int(prev.get(\"runs\", 0)) + 1,\n }\n content = base64.b64encode(json.dumps(state, ensure_ascii=True, indent=2).encode(\"utf-8\")).decode()\n url = GITEA + \"/api/v1/repos/\" + REPO + \"/contents/05_sync/erp_datahub_state.json\"\n payload = {\"content\": content, \"branch\": \"main\", \"message\": \"chore(sync): 更新 DataHub 同步状态快照\"}\n if state_sha:\n payload[\"sha\"] = state_sha\n r = requests.put(url, headers=GH, json=payload, timeout=20)\n else:\n r = requests.post(url, headers=GH, json=payload, timeout=20)\n status = \"ok\" if r.status_code in (200, 201) else \"err\"\n summary = {\"state_saved\": status, \"written_ok\": ok_tables, \"http\": r.status_code, \"resp\": r.text[:150] if status == \"err\" else \"\"}\n return {\"status\": json.dumps(summary, ensure_ascii=False)}","variables":[{"variable":"global_hash","value_selector":["9000000000002","global_hash"],"value_type":"string"},{"variable":"docs_hash","value_selector":["9000000000002","docs_hash"],"value_type":"string"},{"variable":"table_hashes_json","value_selector":["9000000000002","table_hashes_json"],"value_type":"string"},{"variable":"urns_json","value_selector":["9000000000006","urns_json"],"value_type":"string"},{"variable":"created_json","value_selector":["9000000000006","created_json"],"value_type":"string"},{"variable":"prev_state_json","value_selector":["9000000000002","prev_state_json"],"value_type":"string"},{"variable":"state_sha","value_selector":["9000000000002","state_sha"],"value_type":"string"},{"variable":"sync_results","value_selector":["9000000000008","output"],"value_type":"array[string]"},{"variable":"changed_tables","value_selector":["9000000000002","changed_tables"],"value_type":"array[string]"}],"outputs":{"status":{"type":"string","children":null}},"selected":false}},{"id":"9000000000011","type":"custom","position":{"x":3180,"y":180},"positionAbsolute":{"x":3180,"y":180},"width":242,"height":120,"selected":false,"sourcePosition":"right","targetPosition":"left","data":{"type":"end","title":"同步结果","desc":"","selected":false,"outputs":[{"variable":"summary","value_type":"string","value_selector":["9000000000010","status"]},{"variable":"created","value_type":"string","value_selector":["9000000000006","created_json"]}]}}],"edges":[{"id":"9000000000001-source-9000000000002-target","source":"9000000000001","target":"9000000000002","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"start","targetType":"code","isInIteration":false,"isInLoop":false}},{"id":"9000000000002-source-9000000000003-target","source":"9000000000002","target":"9000000000003","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"code","targetType":"if-else","isInIteration":false,"isInLoop":false}},{"id":"9000000000003-true-9000000000005-target","source":"9000000000003","target":"9000000000005","sourceHandle":"true","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"if-else","targetType":"llm","isInIteration":false,"isInLoop":false}},{"id":"9000000000003-false-9000000000004-target","source":"9000000000003","target":"9000000000004","sourceHandle":"false","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"if-else","targetType":"end","isInIteration":false,"isInLoop":false}},{"id":"9000000000005-source-9000000000006-target","source":"9000000000005","target":"9000000000006","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"llm","targetType":"code","isInIteration":false,"isInLoop":false}},{"id":"9000000000006-source-9000000000007-target","source":"9000000000006","target":"9000000000007","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"code","targetType":"code","isInIteration":false,"isInLoop":false}},{"id":"9000000000007-source-9000000000008-target","source":"9000000000007","target":"9000000000008","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"code","targetType":"iteration","isInIteration":false,"isInLoop":false}},{"id":"9000000000008start-source-9000000000009-target","source":"9000000000008start","target":"9000000000009","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"iteration-start","targetType":"code","isInIteration":false,"isInLoop":false}},{"id":"9000000000008-source-9000000000010-target","source":"9000000000008","target":"9000000000010","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"iteration","targetType":"code","isInIteration":false,"isInLoop":false}},{"id":"9000000000010-source-9000000000011-target","source":"9000000000010","target":"9000000000011","sourceHandle":"source","targetHandle":"target","type":"custom","zIndex":0,"data":{"sourceType":"code","targetType":"end","isInIteration":false,"isInLoop":false}}],"viewport":{"x":0,"y":0,"zoom":0.5}},"features":{"file_upload":{"enabled":false,"allowed_file_upload_methods":["local_file","remote_url"],"allowed_file_types":["image"],"allowed_file_extensions":[]},"opening_statement":"","suggested_questions":[]},"conversation_variables":[],"environment_variables":[]} diff --git a/deploy/gen_workflow_draft.js b/deploy/gen_workflow_draft.js new file mode 100644 index 0000000..f7ee1a2 --- /dev/null +++ b/deploy/gen_workflow_draft.js @@ -0,0 +1,345 @@ +// 生成「ERP→DataHub 元数据同步」Dify 工作流 draft JSON +// 用法: node gen_workflow_draft.js > erp_datahub_sync_draft.json +const N = { + start: "9000000000001", + collect: "9000000000002", + ifelse: "9000000000003", + endNoChange: "9000000000004", + llm: "9000000000005", + ensure: "9000000000006", + buildOps: "9000000000007", + iteration: "9000000000008", + iterStart: "9000000000008start", + exec: "9000000000009", + saveState: "9000000000010", + endSummary: "9000000000011", +}; + +const CODE_COLLECT = `import requests, json, hashlib, base64 + +GITEA = "http://gitea:3000" +ERP = "http://mini-erp-app:8000" +REPO = "admin/mini-erp-fabric-demo" +GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c"} + +def sha256(s): + return hashlib.sha256(s.encode("utf-8")).hexdigest() + +def main(force: str): + tables = requests.get(ERP + "/api/governance/tables", timeout=15).json()["tables"] + docs = "" + for f in ["01-\\u7cfb\\u7edf\\u4ecb\\u7ecd", "03-\\u4e1a\\u52a1\\u8bf4\\u660e"]: + r = requests.get(GITEA + "/" + REPO + "/raw/branch/main/docs/" + f + ".md", headers=GH, timeout=15) + if r.status_code == 200: + docs += "\\n\\n## " + f + "\\n" + r.text + su = GITEA + "/api/v1/repos/" + REPO + "/contents/05_sync/erp_datahub_state.json" + state, state_sha = {}, "" + rr = requests.get(su, headers=GH, timeout=15) + if rr.status_code == 200: + jj = rr.json() + state = json.loads(base64.b64decode(jj["content"]).decode("utf-8")) + state_sha = jj.get("sha", "") + table_hashes = {t["table_name"]: sha256(json.dumps(t, ensure_ascii=False, sort_keys=True)) for t in tables} + global_hash = sha256(json.dumps(tables, ensure_ascii=False, sort_keys=True) + "||" + docs) + docs_hash = sha256(docs) + prev = state.get("table_hashes", {}) + changed = sorted([t["table_name"] for t in tables if prev.get(t["table_name"]) != table_hashes[t["table_name"]]]) + force_on = (force or "").strip().lower() == "true" + skip = (not force_on) and state.get("global_hash") == global_hash + return { + "skip": skip, + "tables_json": json.dumps(tables, ensure_ascii=False), + "docs_text": docs, + "changed_tables": changed, + "global_hash": global_hash, + "docs_hash": docs_hash, + "table_hashes_json": json.dumps(table_hashes), + "state_sha": state_sha, + "prev_state_json": json.dumps(state, ensure_ascii=False), + }`; + +const SYS_PROMPT = `你是数据治理与 DataHub 元数据专家。阅读【ERP库表结构】(information_schema 导出, 含表/字段中文注释)与【治理底稿】(系统介绍+业务说明, 含状态码映射/指标口径/敏感字段规则), 产出 DataHub 治理规格。 + +只输出一个严格 JSON 对象(不要 markdown 代码围栏、不要任何解释), 结构: +{"domains":[{"key":"master","name":"ERP主数据域","description":"一句话"}], + "tags":[{"key":"erp_xxx","name":"erp_xxx","description":"一句话"}], + "terms":[{"key":"erp_xxx","name":"中文术语名","description":"含口径/枚举值"}], + "datasets":[{"table":"表名","description":"2-3句业务描述","domain_key":"master","tags":["tag_key"],"term_fields":[{"field":"字段名","term_key":"term_key"}]}]} + +硬性规则: +1. domains 固定5个: master(主数据)/purchase(采购)/sales(销售)/inventory(库存)/governance(治理), key 即上述英文。 +2. datasets 必须覆盖全部10张表, table 用真实表名, 按前缀归域: md_/mdm_→master, po_→purchase, so_→sales, inv_→inventory。 +3. tags 至少含: erp_master, erp_purchase, erp_sales, erp_inventory, erp_sensitive(敏感字段表), erp_demo。 +4. terms 从底稿提炼: 至少包含 状态机术语(主数据状态/采购单状态/销售单状态)与指标口径(采购入库金额/销售出库金额)与敏感字段规则(联系电话脱敏), key 用 erp_ 前缀蛇形英文。 +5. 含 contact_phone 的表(md_supplier/md_customer)必须打 erp_sensitive 标签, 且该字段关联敏感术语。 +6. 全部中文描述, 术语口径必须与底稿一致, 禁止编造。`; + +const CODE_ENSURE = `import requests, json, re + +DH = "http://datahub-datahub-gms-1:8080" +HDRS = {"Authorization": "Bearer app-iBQEBasOC4aVSn2xZRxPk5zW", "Content-Type": "application/json"} + +def gql(q, v=None): + r = requests.post(DH + "/api/graphql", headers=HDRS, json={"query": q, "variables": v or {}}, timeout=20) + j = r.json() + if "errors" in j: + raise Exception(str(j["errors"][0]["message"])[:200]) + return j["data"] + +def parse_json(t): + t = t.strip().replace("\`\`\`json", "").replace("\`\`\`", "").strip() + s, e = t.find("{"), t.rfind("}") + return json.loads(t[s:e + 1]) + +def exists_aspect(urn, aspect): + from urllib.parse import quote + r = requests.get(DH + "/aspects/" + quote(urn, safe="") + "?aspect=" + aspect + "&version=0", headers=HDRS, timeout=15) + return r.status_code == 200 + +def main(spec_text: str, docs_hash: str, prev_state_json: str): + spec = parse_json(spec_text) + prev = json.loads(prev_state_json) if prev_state_json else {} + urns = {"domains": {}, "tags": {}, "terms": {}} + created = {"domains": 0, "tags": 0, "terms": 0} + dl = gql('query{ listDomains(input:{start:0,count:100}) { domains { urn properties { name } } } }') + existing = {} + for d in dl["listDomains"]["domains"]: + p = d.get("properties") or {} + if p.get("name"): + existing[p["name"]] = d["urn"] + for dom in spec.get("domains", []): + if dom["name"] in existing: + urns["domains"][dom["key"]] = existing[dom["name"]] + else: + u = gql('mutation($i:CreateDomainInput!){ createDomain(input:$i) }', {"i": {"name": dom["name"], "description": dom.get("description", "")}})["createDomain"] + urns["domains"][dom["key"]] = u + created["domains"] += 1 + for tg in spec.get("tags", []): + u = "urn:li:tag:" + tg["key"] + if not exists_aspect(u, "tagProperties"): + gql('mutation($i:CreateTagInput!){ createTag(input:$i) }', {"i": {"id": tg["key"], "name": tg["key"], "description": tg.get("description", "")}}) + created["tags"] += 1 + urns["tags"][tg["key"]] = u + reuse_terms = prev.get("term_urns", {}) if prev.get("docs_hash") == docs_hash else {} + for tm in spec.get("terms", []): + key = tm["key"] + if key in reuse_terms: + urns["terms"][key] = reuse_terms[key] + continue + u = "urn:li:glossaryTerm:" + key + if not exists_aspect(u, "glossaryTerm"): + gql('mutation($i:CreateGlossaryEntityInput!){ createGlossaryTerm(input:$i) }', {"i": {"id": key, "name": tm["name"], "description": tm.get("description", "")}}) + created["terms"] += 1 + urns["terms"][key] = u + return { + "urns_json": json.dumps(urns), + "spec_json": json.dumps(spec, ensure_ascii=False), + "created_json": json.dumps(created), + }`; + +const CODE_BUILD_OPS = `import json + +def main(tables_json: str, spec_json: str, urns_json: str, changed_tables: list): + tables = json.loads(tables_json) + spec = json.loads(spec_json) + urns = json.loads(urns_json) + ds_spec = {d["table"]: d for d in spec.get("datasets", [])} + tag_map = urns["tags"] + dom_map = urns["domains"] + ops = [] + for t in tables: + if t["table_name"] not in changed_tables: + continue + d = ds_spec.get(t["table_name"], {}) + cols = [{"name": c["name"], "type": c["type"], "nullable": c["nullable"], "comment": c["comment"]} for c in t["columns"]] + ops.append(json.dumps({ + "table": t["table_name"], + "comment": t.get("table_comment") or "", + "columns": cols, + "description": d.get("description") or t.get("table_comment") or "", + "domain_urn": dom_map.get(d.get("domain_key", "")), + "tag_urns": [tag_map[k] for k in d.get("tags", []) if k in tag_map], + }, ensure_ascii=False)) + return {"ops": ops}`; + +const CODE_EXEC = `import requests, json, time +from urllib.parse import quote + +DH = "http://datahub-datahub-gms-1:8080" +HDRS = {"Authorization": "Bearer app-iBQEBasOC4aVSn2xZRxPk5zW", "Content-Type": "application/json"} + +def type_union(t): + t = (t or "").lower() + if any(k in t for k in ["datetime", "timestamp"]) or t in ("date", "year"): + return {"com.linkedin.schema.DateType": {}} + if t == "time": + return {"com.linkedin.schema.TimeType": {}} + if any(k in t for k in ["int", "decimal", "float", "double", "numeric"]): + return {"com.linkedin.schema.NumberType": {}} + if any(k in t for k in ["blob", "binary", "varbinary", "json"]): + return {"com.linkedin.schema.BytesType": {}} + return {"com.linkedin.schema.StringType": {}} + +def propose(aspect_name, urn, value): + body = {"proposal": {"entityType": "dataset", "entityUrn": urn, "changeType": "UPSERT", "aspectName": aspect_name, + "aspect": {"contentType": "application/json", "value": json.dumps(value)}}} + r = requests.post(DH + "/aspects?action=ingestProposal", headers=HDRS, json=body, timeout=25) + return ("ok" if r.status_code == 200 and "success" in r.text else "err", r.text[:100]) + +def gql(q, v): + r = requests.post(DH + "/api/graphql", headers=HDRS, json={"query": q, "variables": v}, timeout=25) + j = r.json() + if "errors" in j: + return ("err", str(j["errors"][0]["message"])[:100]) + return ("ok", "") + +def main(item: str): + op = json.loads(item) + tbl = op["table"] + urn = "urn:li:dataset:(urn:li:dataPlatform:mysql,mini_erp." + tbl + ",PROD)" + ts = int(time.time() * 1000) + who = {"actor": "urn:li:corpuser:datahub", "time": ts} + fields = [{"fieldPath": c["name"], "type": {"type": type_union(c["type"])}, "nativeType": c["type"], + "nativeDataType": c["type"], "nullable": bool(c["nullable"]), + "description": c["comment"] or c["name"]} for c in op["columns"]] + sm = {"platform": "urn:li:dataPlatform:mysql", "schemaName": "mini_erp." + tbl, + "platformSchema": {"com.linkedin.schema.MySqlDDL": {"tableSchema": ""}}, + "fields": fields, "hash": "", "version": 0, "created": who, "lastModified": who} + dp = {"schemaName": "mini_erp." + tbl, "description": op["description"], + "customProperties": {"database": "mini_erp", "table": tbl, "table_comment": op["comment"]}, + "qualifiedName": "mysql.mini_erp." + tbl, "platform": "urn:li:dataPlatform:mysql", + "version": 0, "created": who, "lastModified": who} + r1 = propose("schemaMetadata", urn, sm) + r2 = propose("datasetProperties", urn, dp) + r3 = gql("mutation($e:String!,$d:String!){ setDomain(entityUrn:$e, domainUrn:$d) }", {"e": urn, "d": op["domain_urn"]}) if op.get("domain_urn") else ("skip", "") + r4 = gql("mutation($i:AddTagsInput!){ addTags(input:$i) }", {"i": {"tagUrns": op["tag_urns"], "resourceUrn": urn}}) if op.get("tag_urns") else ("skip", "") + return {"result": json.dumps({"table": tbl, "schemaMetadata": r1[0], "datasetProperties": r2[0], + "domain": r3[0], "tags": r4[0], + "detail": [r1[1], r2[1], r3[1], r4[1]]}, ensure_ascii=False)}`; + +const CODE_SAVE_STATE = `import requests, json, base64 +from datetime import datetime + +GITEA = "http://gitea:3000" +REPO = "admin/mini-erp-fabric-demo" +GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c", "Content-Type": "application/json"} + +def main(global_hash: str, docs_hash: str, table_hashes_json: str, urns_json: str, created_json: str, + prev_state_json: str, state_sha: str, sync_results: list, changed_tables: list): + prev = json.loads(prev_state_json) if prev_state_json else {} + results = [json.loads(x) for x in sync_results if x] + ok_tables = [r["table"] for r in results if r.get("schemaMetadata") == "ok" and r.get("datasetProperties") == "ok"] + state = { + "global_hash": global_hash, + "docs_hash": docs_hash, + "table_hashes": json.loads(table_hashes_json), + "term_urns": json.loads(urns_json)["terms"], + "last_created": json.loads(created_json), + "last_ok_tables": ok_tables, + "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "runs": int(prev.get("runs", 0)) + 1, + } + content = base64.b64encode(json.dumps(state, ensure_ascii=True, indent=2).encode("utf-8")).decode() + url = GITEA + "/api/v1/repos/" + REPO + "/contents/05_sync/erp_datahub_state.json" + payload = {"content": content, "branch": "main", "message": "chore(sync): 更新 DataHub 同步状态快照"} + if state_sha: + payload["sha"] = state_sha + r = requests.put(url, headers=GH, json=payload, timeout=20) + else: + r = requests.post(url, headers=GH, json=payload, timeout=20) + status = "ok" if r.status_code in (200, 201) else "err" + summary = {"state_saved": status, "written_ok": ok_tables, "http": r.status_code, "resp": r.text[:150] if status == "err" else ""} + return {"status": json.dumps(summary, ensure_ascii=False)}`; + +function node(id, data, x, y, extra = {}) { + return { id, type: "custom", position: { x, y }, positionAbsolute: { x, y }, + width: extra.width || 242, height: extra.height || 100, selected: false, + sourcePosition: "right", targetPosition: "left", ...extra, data }; +} +function codeData(title, code, variables, outputs) { + return { type: "code", title, desc: "", code_language: "python3", code, + variables: variables.map(v => ({ variable: v.name, value_selector: v.sel, value_type: v.type || "string" })), + outputs: Object.fromEntries(Object.entries(outputs).map(([k, t]) => [k, { type: t, children: null }])), + selected: false }; +} +function edge(src, tgt, sh, th, extra = {}) { + return { id: src + "-" + sh + "-" + tgt + "-" + th, source: src, target: tgt, + sourceHandle: sh, targetHandle: th, type: "custom", zIndex: 0, + data: { sourceType: extra.st, targetType: extra.tt, isInIteration: false, isInLoop: false } }; +} + +const graph = { + nodes: [ + node(N.start, { type: "start", title: "开始", desc: "", selected: false, + variables: [{ type: "text-input", variable: "force", label: "force(填true强制全量重同步)", required: false, options: [], default: "", hint: "", placeholder: "" }] }, 40, 260, { height: 108 }), + node(N.collect, codeData("采集输入指纹", CODE_COLLECT, + [{ name: "force", sel: [N.start, "force"] }], + { skip: "boolean", tables_json: "string", docs_text: "string", changed_tables: "array[string]", global_hash: "string", docs_hash: "string", table_hashes_json: "string", state_sha: "string", prev_state_json: "string" }), 340, 260, { height: 180 }), + node(N.ifelse, { type: "if-else", title: "需要更新?", desc: "", selected: false, + cases: [{ case_id: "true", logical_operator: "and", conditions: [{ id: "cond_skip", varType: "boolean", variable_selector: [N.collect, "skip"], comparison_operator: "is", value: "false" }] }] }, 700, 260, { height: 130 }), + node(N.endNoChange, { type: "end", title: "无变更结束", desc: "", selected: false, + outputs: [{ variable: "result", value_type: "string", value_selector: [N.collect, "global_hash"] }] }, 1040, 460, { height: 100 }), + node(N.llm, { type: "llm", title: "生成治理规格", desc: "", selected: false, + model: { provider: "langgenius/siliconflow/siliconflow", name: "Pro/moonshotai/Kimi-K2.5", mode: "chat", completion_params: { temperature: 0.1 } }, + prompt_template: [ + { role: "system", text: SYS_PROMPT }, + { role: "user", text: "【ERP库表结构】\n{{#" + N.collect + ".tables_json#}}\n\n【治理底稿】\n{{#" + N.collect + ".docs_text#}}" }], + context: { enabled: false, variable_selector: [] }, vision: { enabled: false }, + reasoning_format: "separated", variables: [], + retry_config: { retry_enabled: true, max_retries: 2, retry_interval: 1000 } }, 1040, 180, { height: 120 }), + node(N.ensure, codeData("创建治理实体", CODE_ENSURE, + [{ name: "spec_text", sel: [N.llm, "text"] }, { name: "docs_hash", sel: [N.collect, "docs_hash"] }, { name: "prev_state_json", sel: [N.collect, "prev_state_json"] }], + { urns_json: "string", spec_json: "string", created_json: "string" }), 1400, 180, { height: 180 }), + node(N.buildOps, codeData("组装同步任务", CODE_BUILD_OPS, + [{ name: "tables_json", sel: [N.collect, "tables_json"] }, { name: "spec_json", sel: [N.ensure, "spec_json"] }, { name: "urns_json", sel: [N.ensure, "urns_json"] }, { name: "changed_tables", sel: [N.collect, "changed_tables"], type: "array[string]" }], + { ops: "array[string]" }), 1760, 180, { height: 180 }), + node(N.iteration, { type: "iteration", title: "逐表同步DataHub", desc: "", selected: false, + is_parallel: false, parallel_nums: 4, error_handle_mode: "continue-on-error", + iterator_selector: [N.buildOps, "ops"], iterator_input_type: "array[string]", + output_selector: [N.exec, "result"], output_type: "array[string]", + is_iterating: true, flatten_output: false, start_node_id: N.iterStart, + width: 620, height: 220 }, 2120, 160, { width: 620, height: 220, zIndex: 1 }), + { id: N.iterStart, type: "custom-iteration-start", parentId: N.iteration, + position: { x: 24, y: 68 }, positionAbsolute: { x: 2144, y: 228 }, + width: 44, height: 48, selected: false, draggable: false, selectable: false, + sourcePosition: "right", targetPosition: "left", zIndex: 1002, + data: { type: "iteration-start", title: "", desc: "", isInIteration: true, selected: false } }, + node(N.exec, { ...codeData("执行单表同步", CODE_EXEC, [{ name: "item", sel: [N.iteration, "item"] }], { result: "string" }), + isInIteration: true, iteration_id: N.iteration }, 2200, 228, { parentId: N.iteration, zIndex: 1002, height: 180 }), + node(N.saveState, codeData("回写同步状态", CODE_SAVE_STATE, + [{ name: "global_hash", sel: [N.collect, "global_hash"] }, { name: "docs_hash", sel: [N.collect, "docs_hash"] }, + { name: "table_hashes_json", sel: [N.collect, "table_hashes_json"] }, { name: "urns_json", sel: [N.ensure, "urns_json"] }, + { name: "created_json", sel: [N.ensure, "created_json"] }, { name: "prev_state_json", sel: [N.collect, "prev_state_json"] }, + { name: "state_sha", sel: [N.collect, "state_sha"] }, { name: "sync_results", sel: [N.iteration, "output"], type: "array[string]" }, + { name: "changed_tables", sel: [N.collect, "changed_tables"], type: "array[string]" }], + { status: "string" }), 2820, 180, { height: 200 }), + node(N.endSummary, { type: "end", title: "同步结果", desc: "", selected: false, + outputs: [ + { variable: "summary", value_type: "string", value_selector: [N.saveState, "status"] }, + { variable: "created", value_type: "string", value_selector: [N.ensure, "created_json"] }] }, 3180, 180, { height: 120 }), + ], + edges: [ + edge(N.start, N.collect, "source", "target", { st: "start", tt: "code" }), + edge(N.collect, N.ifelse, "source", "target", { st: "code", tt: "if-else" }), + edge(N.ifelse, N.llm, "true", "target", { st: "if-else", tt: "llm" }), + edge(N.ifelse, N.endNoChange, "false", "target", { st: "if-else", tt: "end" }), + edge(N.llm, N.ensure, "source", "target", { st: "llm", tt: "code" }), + edge(N.ensure, N.buildOps, "source", "target", { st: "code", tt: "code" }), + edge(N.buildOps, N.iteration, "source", "target", { st: "code", tt: "iteration" }), + edge(N.iterStart, N.exec, "source", "target", { st: "iteration-start", tt: "code" }), + edge(N.iteration, N.saveState, "source", "target", { st: "iteration", tt: "code" }), + edge(N.saveState, N.endSummary, "source", "target", { st: "code", tt: "end" }), + ], + viewport: { x: 0, y: 0, zoom: 0.5 }, +}; + +const draft = { + graph, + features: { + file_upload: { enabled: false, allowed_file_upload_methods: ["local_file", "remote_url"], allowed_file_types: ["image"], allowed_file_extensions: [] }, + opening_statement: "", suggested_questions: [], + }, + conversation_variables: [], + environment_variables: [], +}; +console.log(JSON.stringify(draft)); \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 24947e0..286d269 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,6 +5,9 @@ services: image: mysql:8.0 container_name: mini-erp-mysql restart: unless-stopped + networks: + - default + - fabric environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-erp_root_123} MYSQL_DATABASE: ${MYSQL_DATABASE:-mini_erp} @@ -35,6 +38,9 @@ services: build: ./backend container_name: mini-erp-app restart: unless-stopped + networks: + - default + - fabric # 与 Dify/DataHub 等演示栈同网,供工作流经 ssrf_proxy 直访 environment: DB_HOST: mysql DB_PORT: "3306" @@ -50,4 +56,9 @@ services: - "${ERP_PORT:-8000}:8000" volumes: - mysql_data: \ No newline at end of file + mysql_data: + +networks: + fabric: + name: docker_default + external: true \ No newline at end of file