153 lines
5.1 KiB
Python
153 lines
5.1 KiB
Python
"""Token bookkeeping for parallel / merge / split gateways.
|
||
|
||
A direct port of the ticket counting idea from O2OA's
|
||
``com.x.processplatform.core.entity.content.Work#getTickets``: every fork
|
||
registers how many branches must arrive before a join may continue.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import math
|
||
import uuid
|
||
|
||
|
||
def new_token() -> str:
|
||
return uuid.uuid4().hex
|
||
|
||
|
||
def required_votes(expected: int, pass_count: int = 0, pass_ratio: float = 0) -> int:
|
||
"""汇聚要等几张票。
|
||
|
||
默认全到(``expected``)。配了「到几张就放行」或「到多少比例就放行」时按配额算,
|
||
并夹在 ``[1, expected]`` 之间:配额比分支数还大等于永远等不齐,那种配置按全到处理
|
||
比静默卡死友好得多。比例既收 0.6 也收 60,界面上填百分数不用再除一遍。
|
||
"""
|
||
total = max(int(expected or 0), 0)
|
||
if total <= 0:
|
||
return 1
|
||
count = int(pass_count or 0)
|
||
if count > 0:
|
||
return min(max(count, 1), total)
|
||
ratio = float(pass_ratio or 0)
|
||
if ratio > 0:
|
||
if ratio > 1:
|
||
ratio = ratio / 100
|
||
ratio = min(max(ratio, 0.0), 1.0)
|
||
return min(max(int(math.ceil(total * ratio)), 1), total)
|
||
return total
|
||
|
||
|
||
def join_key(prefix: str, merge_activity: str) -> str:
|
||
return f"{prefix}|{merge_activity}" if prefix else merge_activity
|
||
|
||
|
||
def register_join(
|
||
joins: dict,
|
||
key: str,
|
||
expected: int,
|
||
merge_activity: str,
|
||
token: str,
|
||
*,
|
||
pass_count: int = 0,
|
||
pass_ratio: float = 0,
|
||
) -> dict:
|
||
state = joins.get(key)
|
||
if state is None:
|
||
state = {"expected": expected, "arrived": 0, "merge": merge_activity, "token": token, "routes": []}
|
||
joins[key] = state
|
||
else:
|
||
state["expected"] = max(int(state.get("expected") or 0), expected)
|
||
# 配额写在汇聚环节上,分叉时抄一份进票箱:退回重跑时没有汇聚节点可查,
|
||
# 只认票箱里这份,才能保证「等 2/3 票」在第二次走的时候还是等 2/3。
|
||
if pass_count or pass_ratio:
|
||
state["passCount"] = int(pass_count or 0)
|
||
state["passRatio"] = float(pass_ratio or 0)
|
||
state["required"] = required_votes(
|
||
int(state["expected"]), int(state.get("passCount") or 0), float(state.get("passRatio") or 0)
|
||
)
|
||
return state
|
||
|
||
|
||
def join_required(state: dict) -> int:
|
||
"""这张票箱要收几张票;老数据没有 required 就退回全到。"""
|
||
return int(state.get("required") or state.get("expected") or 1)
|
||
|
||
|
||
def arrive_join(joins: dict, key: str, route_name: str = "") -> tuple[bool, dict | None]:
|
||
"""Increase the arrival counter, returns ``(ready, state)``.
|
||
|
||
``required`` 存在时到够票数就放行,不再强求所有分支都走到汇聚。
|
||
"""
|
||
state = joins.get(key)
|
||
if state is None:
|
||
return True, None
|
||
state["arrived"] = int(state.get("arrived") or 0) + 1
|
||
if route_name and route_name not in state.setdefault("routes", []):
|
||
state["routes"].append(route_name)
|
||
if int(state["arrived"]) >= join_required(state):
|
||
return True, dict(state)
|
||
joins[key] = state
|
||
return False, None
|
||
|
||
|
||
def clear_join(joins: dict, key: str) -> None:
|
||
joins.pop(key, None)
|
||
|
||
|
||
def token_path(tokens: list[dict], activity: str, prefix: str = "") -> str:
|
||
return f"{prefix}/{activity}" if prefix else activity
|
||
|
||
|
||
def add_token(tokens: list[dict], activity: str, prefix: str = "", **extra) -> dict:
|
||
token = {
|
||
"id": new_token(),
|
||
"activity": activity,
|
||
"path": token_path(tokens, activity, prefix),
|
||
}
|
||
token.update({k: v for k, v in extra.items() if v not in (None, "")})
|
||
tokens.append(token)
|
||
return token
|
||
|
||
|
||
def take_tokens(tokens: list[dict], activity: str) -> list[dict]:
|
||
"""Remove and return every token sitting on ``activity``."""
|
||
taken = [t for t in tokens if t.get("activity") == activity]
|
||
if not taken:
|
||
return []
|
||
remaining = [t for t in tokens if t.get("activity") != activity]
|
||
tokens.clear()
|
||
tokens.extend(remaining)
|
||
return taken
|
||
|
||
|
||
def find_token(tokens: list[dict], activity: str) -> dict | None:
|
||
for item in tokens:
|
||
if item.get("activity") == activity:
|
||
return item
|
||
return None
|
||
|
||
|
||
def unique_path(tokens: list[dict], path: str) -> str:
|
||
"""让每条 token 的路径在存活期间互不相同。
|
||
|
||
并行分叉的两条支线可能各自绕过一个分支判断、落到同一个环节(B1→二级分支→B4 和
|
||
B5→二级分支→B4 都得到 ``n_par/n_b4``)。路径一样就等于同一张票:一人办结会把
|
||
另一条支线的待办当成"同级待办"一起结掉,那条 token 从此停在原地,流程既不推进
|
||
也没有待办,看起来就像悄悄卡死。
|
||
"""
|
||
taken = {str(item.get("path") or "") for item in tokens}
|
||
if path not in taken:
|
||
return path
|
||
index = 2
|
||
while f"{path}@{index}" in taken:
|
||
index += 1
|
||
return f"{path}@{index}"
|
||
|
||
|
||
def prefix_of(path: str, activity: str) -> str:
|
||
"""Strip the trailing activity segment: ``a/b/merge`` -> ``a/b``."""
|
||
suffix = f"/{activity}"
|
||
if path.endswith(suffix):
|
||
return path[: -len(suffix)]
|
||
return ""
|