sysobjects.py
14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""系统对象:预警事件、动作记录、流程运行。
决策和处置本身也是本体里的数据(decisions as data):每个本体空间都自动拥有这三类只读对象,
和它们涉及的业务对象之间自动有关系边(库存位 ← 预警事件 ← 流程运行 → 动作记录 → 库存位)。
于是「这个配件这个月被预警了几次、怎么处理的」「哪条规则的自动处理率最高」都能用同一套
对象查询、指标、遍历来回答,不需要另外的报表。
它们读的是本系统自己的表(经「本体存储」数据源),按本体空间过滤;只读,改它们只能经由各自的业务入口。
效果指标(预警数、平均恢复用时、自动处理率、复发率、动作执行数)也作为内置聚合函数放进运行时。
"""
from __future__ import annotations
from .sqlutil import ident, lit
# 属性:(属性名, 显示名, 数据类型, 取值 SQL, 额外定义)
_ACTION_STATUS = ("CASE status WHEN 'pending_approval' THEN '待审批' WHEN 'executing' THEN '执行中' "
"WHEN 'done' THEN '已完成' WHEN 'failed' THEN '失败' WHEN 'rejected' THEN '已驳回' "
"WHEN 'cancelled' THEN '已撤回' WHEN 'reverted' THEN '已撤销' ELSE status END")
_INITIATOR = ("CASE initiator_kind WHEN 'user' THEN '人' WHEN 'ai' THEN 'AI' WHEN 'sop' THEN '流程卡' "
"WHEN 'watch' THEN '预警规则' ELSE initiator_kind END")
_SOP_STATUS = ("CASE status WHEN 'running' THEN '进行中' WHEN 'waiting' THEN '等待中' WHEN 'done' THEN '已完成' "
"WHEN 'failed' THEN '失败' WHEN 'cancelled' THEN '已取消' ELSE status END")
TYPES: dict[str, dict] = {
"alert_event": {
"id": "sys_alert_event", "name": "预警事件", "table": "otlg_alert_event",
"synonyms": ["预警", "告警", "异常事件"],
"description": "预警规则每命中一个对象就开一条事件,从发现、处置到恢复(或忽略)全程留在这里",
"key": "编号", "label": "标题",
"props": [
("编号", "", "string", "id", {"is_key": True}),
("标题", "", "string", "title", {}),
("规则", "", "string", "rule_title", {"is_dimension": True}),
("严重度", "", "enum", "severity", {"is_dimension": True, "enum_values": ["高", "中", "低"],
"format": "status", "tones": {"高": "danger", "中": "warn", "低": "info"}}),
("状态", "", "enum", "status", {"is_dimension": True,
"enum_values": ["新发现", "处置中", "待验证", "已恢复", "已忽略"],
"format": "status",
"tones": {"新发现": "danger", "处置中": "warn", "待验证": "info",
"已恢复": "ok", "已忽略": "neutral"}}),
("对象类型", "", "string", "object_type_name", {"is_dimension": True}),
("对象主键", "", "string", "object_key", {}),
("对象", "", "string", "object_label", {}),
("数值", "", "number", "value", {}),
("基线", "", "number", "baseline", {}),
("偏离", "", "number", "deviation", {}),
("处置方式", "", "string", "handling", {"is_dimension": True}),
("自动处理", "", "boolean", "auto_handled", {}),
("复发", "", "boolean", "is_recurrence", {}),
("负责角色", "", "string", "owner_role", {"is_dimension": True}),
("发现时间", "", "datetime", "first_seen_at", {"is_time": True}),
("恢复时间", "", "datetime", "recovered_at", {}),
("恢复用时", "恢复用时(小时)", "number", "recover_hours", {"unit": "小时"}),
("触发次数", "", "integer", "fire_count", {}),
]},
"action_run": {
"id": "sys_action_run", "name": "动作记录", "table": "otlg_action_run",
"synonyms": ["审批单", "动作单"],
"description": "每一次动作(提议、审批、执行、撤销)都是一条记录:谁发起、为什么、改了什么、结果如何",
"key": "编号", "label": "动作",
"props": [
("编号", "", "string", "id", {"is_key": True}),
("动作", "", "string", "action_name", {"is_dimension": True}),
("状态", "", "enum", _ACTION_STATUS, {"is_dimension": True,
"enum_values": ["待审批", "执行中", "已完成", "失败", "已驳回", "已撤回", "已撤销"]}),
("发起方", "", "enum", _INITIATOR, {"is_dimension": True, "enum_values": ["人", "AI", "流程卡", "预警规则"]}),
("优先级", "", "string", "priority", {"is_dimension": True}),
("对象类型", "", "string", "target_type", {}),
("对象主键", "", "string", "target_key", {}),
("对象", "", "string", "target_label", {}),
("原因", "", "text", "reason", {}),
("错误", "", "text", "error", {}),
("提交时间", "", "datetime", "created_at", {"is_time": True}),
("完成时间", "", "datetime", "finished_at", {}),
]},
"sop_run": {
"id": "sys_sop_run", "name": "流程运行", "table": "otlg_sop_run",
"synonyms": ["流程记录"],
"description": "流程卡的每一次运行:处理的是哪个对象 / 哪条预警、走到哪一步、结果如何",
"key": "编号", "label": "流程",
"props": [
("编号", "", "string", "id", {"is_key": True}),
("流程", "", "string", "title", {"is_dimension": True}),
("状态", "", "enum", _SOP_STATUS, {"is_dimension": True,
"enum_values": ["进行中", "等待中", "已完成", "失败", "已取消"]}),
("触发方式", "", "string", "`trigger`", {"is_dimension": True}),
("对象类型", "", "string", "subject_type", {}),
("对象主键", "", "string", "subject_key", {}),
("对象", "", "string", "subject_label", {}),
("预警事件", "", "string", "event_id", {}),
("结果", "", "string", "outcome", {}),
("开始时间", "", "datetime", "created_at", {"is_time": True}),
("结束时间", "", "datetime", "finished_at", {}),
]},
}
# 系统关系边:(关系 id, 显示名, 系统对象, 指向的对象类型列, 指向的主键列)
LINKS = {
"sys_link_alert": {"name": "预警对象", "inverse": "预警事件", "from": "alert_event"},
"sys_link_action": {"name": "作用对象", "inverse": "动作记录", "from": "action_run"},
"sys_link_sop": {"name": "处理对象", "inverse": "流程运行", "from": "sop_run"},
"sys_link_sop_event": {"name": "处置的预警", "inverse": "处置流程", "from": "sop_run"},
}
BY_ID = {t["id"]: name for name, t in TYPES.items()}
def table_names() -> set[str]:
return {t["table"] for t in TYPES.values()}
def binding_ref(name: str) -> dict:
t = TYPES[name]
return {"table": t["table"], "key_column": t["key"], "label_column": t["label"],
"columns": {p[0]: p[0] for p in t["props"]}}
def from_sql(name: str, workspace: str) -> str:
t = TYPES[name]
sel = [f"{expr} AS {ident(p)}" for p, _, _, expr, _ in t["props"]]
where = f"workspace = {lit(workspace)}"
if name == "sop_run":
where += " AND kind = 'main' AND version > 0" # 只算正式运行,不算试运行和逐行的子运行
return f"(SELECT {', '.join(sel)} FROM {ident(t['table'])} WHERE {where})"
def _concept(name: str, ds_id: int) -> dict:
t = TYPES[name]
props = [{"name": p, "display_name": dn, "data_type": dt, "description": "", "is_key": False, "is_time": False,
"is_dimension": False, "is_writable": False, "enum_values": [], "format": "", "unit": "",
"expression": "", "tones": {}, **extra}
for p, dn, dt, _, extra in t["props"]]
return {"id": t["id"], "kind": "object_type", "kind_label": "对象", "name": t["name"], "display_name": "",
"description": t["description"], "synonyms": t["synonyms"], "status": "published", "origin": "system",
"version": 1, "category": "", "object_type": "", "domain": "系统",
"spec": {"properties": props, "key_property": t["key"], "label_property": t["label"],
"title_template": "", "system": name, "domain": "系统"},
"bindings": [{"id": f"bd_{t['id']}", "concept_id": t["id"], "ds_id": ds_id, "target_kind": "table",
"ref": {"kind": "system", "system": name, **binding_ref(name)}}]}
# 内置效果指标:(名称, 别名, 系统对象, 表达式, 时间列, 维度, 单位, 方向, 说明)
_METRICS = [
("预警数", ["预警次数", "告警数"], "alert_event", "COUNT(*)", "发现时间",
["规则", "严重度", "状态", "对象类型", "处置方式", "负责角色"], "条", "lower_better", "开出的预警事件条数"),
("平均恢复用时", ["平均处理时长", "恢复时长"], "alert_event", "AVG(CASE WHEN `状态` = '已恢复' THEN `恢复用时` END)",
"发现时间", ["规则", "严重度", "对象类型", "处置方式"], "小时", "lower_better", "已恢复的预警从发现到恢复平均用了多久"),
("自动处理率", ["自动化率"], "alert_event", "AVG(CASE WHEN `自动处理` = 1 THEN 1.0 ELSE 0 END)",
"发现时间", ["规则", "严重度", "对象类型"], "", "higher_better", "预警的处置没经过人工就完成的比例"),
("复发率", ["重复预警率"], "alert_event", "AVG(CASE WHEN `复发` = 1 THEN 1.0 ELSE 0 END)",
"发现时间", ["规则", "对象类型"], "", "lower_better", "恢复后又在短期内再次命中的预警占比"),
("动作执行数", ["动作次数"], "action_run", "SUM(CASE WHEN `状态` = '已完成' THEN 1 ELSE 0 END)",
"提交时间", ["动作", "发起方", "对象类型"], "次", "neutral", "执行完成的动作次数"),
]
def _metric(i: int, m: tuple, ds_id: int) -> dict:
name, syn, sysname, expr, tcol, dims, unit, direction, desc = m
t = TYPES[sysname]
fid = f"sys_fn_{i}"
return {"id": fid, "kind": "function", "kind_label": "函数·聚合", "name": name, "display_name": "",
"description": desc, "synonyms": syn, "status": "published", "origin": "system", "version": 1,
"category": "aggregate", "object_type": t["id"], "domain": "系统",
"spec": {"category": "aggregate", "object_type": t["id"], "unit": unit, "direction": direction,
"format": "percent" if "率" in name else "", "calibre_rule": "",
"period": {"grain": "month", "week_start": 1, "start_month": 1, "start_day": 1,
"start_month_offset": 0, "end_day": "last", "end_month_offset": 0, "label": ""},
"dimensions": dims, "formula_text": desc, "inputs": [], "compare": "",
"history": {"enabled": False, "every": "daily", "dimensions": []}, "tests": [], "domain": "系统"},
"bindings": [{"id": f"bd_{fid}", "concept_id": fid, "ds_id": ds_id, "target_kind": "metric_expr",
"ref": {"base_table": "", "base_object": t["id"], "base_set": "", "expression": expr,
"time_column": tcol, "object_key_column": "", "filters": [],
"dimensions": {d: d for d in dims}, "dimension_types": {}}}]}
def concepts() -> list[dict]:
"""运行时里的系统元素(三类系统对象 + 内置效果指标)。本体存储数据源还没建好时返回空。"""
from . import storage
ds_id = storage.datasource_id()
if not ds_id:
return []
out = [_concept(n, ds_id) for n in TYPES]
out += [_metric(i, m, ds_id) for i, m in enumerate(_METRICS, 1)]
return out
def edges(workspace: str) -> list[dict]:
"""系统对象到业务对象的关系边(建索引时一起物化)。"""
from sqlalchemy import select
from ..capability.models import ActionRun
from ..core.dbx import session
from ..sop.models import SopRun
from ..watch.models import AlertEvent
out: list[dict] = []
with session() as s:
for e in s.scalars(select(AlertEvent).where(AlertEvent.workspace == workspace,
AlertEvent.object_type != "")).all():
out.append(_edge(workspace, "sys_link_alert", TYPES["alert_event"]["id"], e.id, e.object_type, e.object_key))
for r in s.scalars(select(ActionRun).where(ActionRun.workspace == workspace, ActionRun.target_type != "")).all():
out.append(_edge(workspace, "sys_link_action", TYPES["action_run"]["id"], r.id, r.target_type, r.target_key))
for r in s.scalars(select(SopRun).where(SopRun.workspace == workspace, SopRun.kind == "main",
SopRun.version > 0)).all():
if r.subject_type:
out.append(_edge(workspace, "sys_link_sop", TYPES["sop_run"]["id"], r.id, r.subject_type, r.subject_key))
if r.event_id:
out.append(_edge(workspace, "sys_link_sop_event", TYPES["sop_run"]["id"], r.id,
TYPES["alert_event"]["id"], r.event_id))
return out
def _edge(ws: str, link_id: str, ft: str, fk: str, tt: str, tk: str) -> dict:
return {"workspace": ws, "link_id": link_id, "from_type": ft, "from_key": str(fk),
"to_type": tt, "to_key": str(tk), "props_json": ""}
def add_edge(link_id: str, from_name: str, from_key: str, to_type: str, to_key: str) -> None:
"""新开一条事件 / 动作 / 流程运行时立刻补上它的关系边,不等下一次建索引。"""
if not to_type or not to_key:
return
from ..core import identity
from ..core.dbx import session
from .models import LinkEdge
try:
with session() as s:
s.add(LinkEdge(**_edge(identity.current().workspace, link_id, TYPES[from_name]["id"], from_key,
to_type, to_key)))
s.commit()
except Exception: # noqa: BLE001 边只是索引,补不上等下次建索引
pass