flow

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 10 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package flow 是 go-wind-flow 的核心引擎:一个持久化驱动的、 基于 Token 状态机的轻量流程引擎。

设计原则(与 go-wind 家族一致——积木盒而非全家桶):

  • 核心零第三方依赖:表达式、脚本、身份、存储全部为 SPI 接口, 具体实现位于 store/、format/、contrib/ 等独立包中按需组装;
  • 对齐 BPMN:节点类型、网关语义、条件表达式风格与 BPMN 2.0 互认, 通过 format/bpmn 可无缝导入导出;
  • 持久化驱动:每次流转都落库,崩溃可恢复,不做内存态执行;
  • 定义不可变:部署即版本化,在途实例锁定其部署版本。

最小用法:

eng := flow.New(
    flow.WithStore(memstore.New()),
    flow.WithImporters(bpmn.Importer{}),
)
def, _ := eng.Deploy(ctx, flow.DeployRequest{Key: "leave", Data: bpmnBytes})
inst, _ := eng.Start(ctx, flow.StartRequest{Key: "leave", StarterID: "u1"})

Index

Constants

View Source
const (
	OutcomeApprove = "APPROVE"
	OutcomeReject  = "REJECT"
)

Outcome 办结动作(v0 两个值,后续可扩展转办/退回指定节点等)。

View Source
const SystemActor = "flow:timer"

SystemActor 系统操作者标识(定时器自动动作等引擎自驱行为的历史署名)。

Variables

View Source
var (
	// ErrNotFound 资源不存在(定义/实例/任务/令牌)。
	ErrNotFound = errors.New("flow: not found")
	// ErrInvalidDefinition 定义不合法(校验失败)。
	ErrInvalidDefinition = errors.New("flow: invalid definition")
	// ErrInvalidState 非法状态迁移(如对已办结任务 Complete)。
	ErrInvalidState = errors.New("flow: invalid state")
	// ErrForbidden 操作者无权执行该操作(如非办理人办结任务)。
	ErrForbidden = errors.New("flow: forbidden")
	// ErrNotConfigured 缺少必要的 SPI 实现(如未装配 IdentityProvider 却遇到 LEADER 规则)。
	ErrNotConfigured = errors.New("flow: capability not configured")
	// ErrExpression 求值失败(表达式语法/运行错误,引擎按 fail-closed 处理)。
	ErrExpression = errors.New("flow: expression error")
	// ErrScript 脚本任务执行失败。
	ErrScript = errors.New("flow: script error")
)

核心哨兵错误。宿主可用 errors.Is 判断;包装后仍可识别。

Functions

func ValidateDefinition

func ValidateDefinition(def *Definition) error

ValidateDefinition 部署前校验。规则对齐 go-wind-oa/im 引擎的既有约束并泛化:

  • 恰一个 startEvent;至少一个 endEvent;
  • start:0 入 1 出;end:≥1 入 0 出;
  • userTask/scriptTask/serviceTask/callActivity:1 入 1 出;
  • 排他网关:≥2 出,非默认出边必须带条件,至多一条默认流,默认流必须存在;
  • 并行/包容网关:分叉 ≥2 出(出边无条件)或汇合 ≥2 入(1 出),二选一或兼有;
  • 脚本任务必须带 ScriptSpec;callActivity 必须指定 SubprocessKey;
  • 全节点自 start 可达,且均可达某 end(活性保证)。

Types

type ApprovalSpec

type ApprovalSpec struct {
	Strategy   Strategy   `json:"strategy,omitempty"`   // 缺省 = ALL 会签
	RejectMode RejectMode `json:"rejectMode,omitempty"` // 缺省 = TERMINATE
	// Sequential 顺序多实例(BPMN isSequential=true):办理人列表串行逐个审批
	//(按解析顺序),全部通过才推进;中途驳回按 RejectMode。串行隐含 ALL 语义。
	Sequential bool `json:"sequential,omitempty"`
	// Collection 多实例集合表达式(求值结果须为字符串数组):
	//   - 并行多实例:每项一个任务(项即办理人,ElementVar 不生效);
	//   - 顺序多实例 + ElementVar:串行逐项,项写入令牌局部变量(非保留键),
	//     后续节点/条件可读;ElementVar 缺省 "item"。
	// 设置后覆盖 Approver 规则解析。
	Collection string `json:"collection,omitempty"`
	ElementVar string `json:"elementVar,omitempty"`
}

ApprovalSpec 审批行为配置。

type ApproverKind

type ApproverKind string

ApproverKind 办理人规则类型。静态类型(USER/STARTER)核心内置可解析; 动态类型(LEADER/POSITION/ROLE/EXPR)要求宿主装配 IdentityProvider。

const (
	ApproverUser     ApproverKind = "USER"     // Value = 用户 ID
	ApproverStarter  ApproverKind = "STARTER"  // 发起人
	ApproverLeader   ApproverKind = "LEADER"   // 发起人主组织负责人
	ApproverPosition ApproverKind = "POSITION" // Value = 职位编码
	ApproverRole     ApproverKind = "ROLE"     // Value = 角色编码
	ApproverExpr     ApproverKind = "EXPR"     // Value = 表达式(返回用户 ID 或 ID 数组)
	ApproverGroup    ApproverKind = "GROUP"    // Value = 组编码:创建候选组任务,组内成员认领后办理
)

type ApproverRule

type ApproverRule struct {
	Kind  ApproverKind `json:"kind"`
	Value string       `json:"value,omitempty"`
}

ApproverRule 单条办理人规则。

type ApproverSpec

type ApproverSpec struct {
	Rules []ApproverRule `json:"rules,omitempty"`
}

ApproverSpec 办理人规格:多条规则依序解析、去重保序。

type Clock

type Clock interface {
	Now() time.Time
}

Clock 时钟接口,测试可注入假时钟。

type CompleteTaskRequest

type CompleteTaskRequest struct {
	TaskID  string
	ActorID string
	// Outcome: OutcomeApprove / OutcomeReject
	Outcome string
	Comment string
	// Variables 办结时回写的业务变量(如表单字段),进实例级。
	Variables Vars
	// LocalVariables 办结时写入令牌级局部变量(仅当前分支后续节点可读)。
	LocalVariables Vars
}

type Definition

type Definition struct {
	Key       string
	Name      string
	Version   int
	TenantID  string
	Format    string // 来源格式:bpmn-xml / wind-json-v2 / 自定义
	Source    []byte // 原始定义文本(审计与导出用)
	CreatedAt time.Time

	Nodes map[string]*Node
	Edges []*Edge
}

Definition 一份已部署的流程定义。不可变:部署生成新版本,修改需重新部署。

func (*Definition) Clone

func (d *Definition) Clone() *Definition

Clone 深拷贝(部署侧内存复用需隔离时使用)。

func (*Definition) Edge

func (d *Definition) Edge(id string) *Edge

Edge 返回指定 ID 的边。

func (*Definition) InDegree

func (d *Definition) InDegree(nodeID string) int

InDegree 节点入度。

func (*Definition) OutEdges

func (d *Definition) OutEdges(nodeID string) []*Edge

OutEdges 返回节点出边(保持定义顺序)。

type DefinitionStore

type DefinitionStore interface {
	Save(ctx context.Context, def *Definition) error
	// Get version<=0 表示取最新版本。
	Get(ctx context.Context, tenantID, key string, version int) (*Definition, error)
	MaxVersion(ctx context.Context, tenantID, key string) (int, error)
	// List 按租户列出定义;key 为空表示全部,结果按 (key, version) 排序。
	List(ctx context.Context, tenantID, key string) ([]*Definition, error)
}

DefinitionStore 定义存储。按 (tenantID, key, version) 唯一。

type DeployRequest

type DeployRequest struct {
	TenantID string
	Key      string
	Name     string
	// Format 为空时按内容嗅探('<' → bpmn-xml,否则 wind-json-v2)。
	Format string
	Data   []byte
}

type Duration

type Duration time.Duration

Duration 兼容 JSON 字符串("24h")与数值秒的时间跨度。

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (Duration) Std

func (d Duration) Std() time.Duration

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

type Edge

type Edge struct {
	ID        string `json:"id"`
	From      string `json:"from"`
	To        string `json:"to"`
	Name      string `json:"name,omitempty"`
	Condition string `json:"condition,omitempty"` // 布尔表达式(裸表达式,非 UEL 包裹)
	IsDefault bool   `json:"isDefault,omitempty"` // 排他网关默认流
}

Edge 定义图中的顺序流。

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine 流程引擎。

并发约定:引擎自身无锁。同一实例的引擎入口调用(Start/CompleteTask/ Withdraw/Abort)必须由宿主串行化——进程内按 instanceID 加锁,或由 存储层事务/行级锁保证。子流程经由父实例调用链天然串行。

func New

func New(opts ...Option) *Engine

func (*Engine) Abort

func (e *Engine) Abort(ctx context.Context, instanceID, actorID string) error

Abort 管理员强制终止。不向父流程传播。

func (*Engine) AddTaskApprovers

func (e *Engine) AddTaskApprovers(ctx context.Context, taskID, actorID string, userIDs []string) ([]*Task, error)

AddTaskApprovers 加签:向待办任务所在节点动态追加办理人(会签式—— 新任务与既有待办并行,ALL/ANY 语义照常)。

委托叠加与任务创建时的解析一致;已是该节点待办办理人的用户自动去重。 返回本次新创建的任务。

func (*Engine) CheckDueTasks

func (e *Engine) CheckDueTasks(ctx context.Context, now time.Time) ([]*Task, error)

CheckDueTasks 扫描到期任务并广播 EventTaskDue(催办/升级/超时自动处理由监听器承接)。 由宿主定时任务驱动;返回本次扫描到的到期任务。

func (*Engine) ClaimTask

func (e *Engine) ClaimTask(ctx context.Context, taskID, userID string) error

ClaimTask 认领候选组任务:任务须待办、未分派(Assignee 为空)且 操作者属于任一候选组(经 IdentityProvider.ResolveGroupsForUser 鉴权)。

func (*Engine) CompleteTask

func (e *Engine) CompleteTask(ctx context.Context, req CompleteTaskRequest) error

CompleteTask 办结用户任务。会签/或签语义由定义驱动;驳回按 RejectMode 处理。

func (*Engine) Deploy

func (e *Engine) Deploy(ctx context.Context, req DeployRequest) (*Definition, error)

Deploy 部署(或升版)一份流程定义。定义不可变:每次 Deploy 生成新版本。

func (*Engine) ExportDefinition

func (e *Engine) ExportDefinition(ctx context.Context, tenantID, key string, version int, format string) ([]byte, error)

ExportDefinition 以指定格式导出定义。

func (*Engine) ForwardTask

func (e *Engine) ForwardTask(ctx context.Context, taskID, actorID, toUserID string) error

ForwardTask 转办:把待办任务移交他人。

func (*Engine) GetDefinition

func (e *Engine) GetDefinition(ctx context.Context, tenantID, key string, version int) (*Definition, error)

GetDefinition 查询定义;version<=0 取最新。

func (*Engine) GetInstance

func (e *Engine) GetInstance(ctx context.Context, id string) (*Instance, error)

func (*Engine) ListCandidateTasks

func (e *Engine) ListCandidateTasks(ctx context.Context, tenantID, userID string) ([]*Task, error)

ListCandidateTasks 列出用户可认领的组待办。

func (*Engine) ListHistory

func (e *Engine) ListHistory(ctx context.Context, instanceID string) ([]*HistoryEvent, error)

func (*Engine) ListInstanceTasks

func (e *Engine) ListInstanceTasks(ctx context.Context, instanceID string) ([]*Task, error)

func (*Engine) ListInstancesByStatus

func (e *Engine) ListInstancesByStatus(ctx context.Context, tenantID string, status InstanceStatus) ([]*Instance, error)

ListInstancesByStatus 按租户与状态列出实例(子流程错误终结等场景的查询口)。

func (*Engine) ListPendingTasks

func (e *Engine) ListPendingTasks(ctx context.Context, tenantID, assignee string) ([]*Task, error)

func (*Engine) ResumeDueTimers

func (e *Engine) ResumeDueTimers(ctx context.Context, now time.Time) ([]*Token, error)

ResumeDueTimers 扫描到期的定时器令牌并触发(宿主 cron 驱动)。 按令牌所在节点类型分派:

  • intermediateTimerEvent:令牌沿出边续走(引擎自驱);
  • boundaryEvent:边界定时器触发——中断型取消挂接节点任务并接管流程, 非中断型只派生升级分支(原任务照常)。

任务到期(task.due)走 CheckDueTasks,由监听器自决。 返回本次续跑的令牌;单个令牌推进失败立即返回(fail-closed)。

func (*Engine) ReturnTo

func (e *Engine) ReturnTo(ctx context.Context, taskID, actorID, targetNodeID, comment string) error

ReturnTo 驳回指定节点:实例退回到更早的 userTask 重新走(如退回发起人重新提交)。

约束(fail-closed):

  • 目标必须是当前节点的 userTask 祖先(当前节点自目标可达);
  • 实例在途并行分支多于一条时不支持(避免 fork/汇合态回滚的语义难题)。

语义:取消全部待办与在途令牌,实例保持 RUNNING,自目标节点生成新令牌 重走——动态办理人规则届时重新解析。历史完整保留。

func (*Engine) SendMessage

func (e *Engine) SendMessage(ctx context.Context, instanceID, messageName string, payload Vars) (bool, error)

SendMessage 向实例投递消息:解锁阻塞在同名消息事件上的令牌, payload 并入实例变量后续走。 返回是否投递成功(实例不存在/未运行/无同名等待令牌均返回 false,由调用方 决定重试或丢弃——消息语义是调用方自决,引擎不缓存)。

func (*Engine) Start

func (e *Engine) Start(ctx context.Context, req StartRequest) (*Instance, []string, error)

Start 启动流程实例:创建实例 + 根令牌,同步推进到首个阻塞点。 返回实例与首个阻塞处创建的用户任务 ID 列表(可能为空)。

func (*Engine) UnclaimTask

func (e *Engine) UnclaimTask(ctx context.Context, taskID, actorID string) error

UnclaimTask 退认:把已认领的候选组任务放回待认领池。

func (*Engine) Withdraw

func (e *Engine) Withdraw(ctx context.Context, instanceID, actorID string) error

Withdraw 发起人撤回。仅发起人可撤回(权限细化由宿主在上层拦截)。

type Event

type Event struct {
	Type       EventType
	TenantID   string
	InstanceID string
	TokenID    string
	TaskID     string
	NodeID     string
	ActorID    string
	// Status 流程终态(仅 EventProcessEnded 时有值)。
	Status InstanceStatus
	// Vars 事件时刻的实例变量快照(只读约定)。
	Vars Vars
	At   time.Time
}

Event 监听器事件。

type EventType

type EventType string

EventType 生命周期事件类型(历史记录与监听器共用)。

const (
	EventProcessStarted    EventType = "process.started"
	EventProcessEnded      EventType = "process.ended"
	EventTokenMoved        EventType = "token.moved"
	EventGatewayDecided    EventType = "gateway.decided"
	EventTaskCreated       EventType = "task.created"
	EventTaskCompleted     EventType = "task.completed"
	EventTaskForwarded     EventType = "task.forwarded"
	EventTaskApproverAdded EventType = "task.approver_added" // 加签
	EventTaskDue           EventType = "task.due"
	EventTaskClaimed       EventType = "task.claimed"      // 候选组任务认领/退认
	EventTimerFired        EventType = "timer.fired"       // 定时器节点到期续跑
	EventMessageReceived   EventType = "message.received"  // 消息投递解锁令牌
	EventInstanceReturned  EventType = "instance.returned" // 退回指定节点
	EventVariableChanged   EventType = "variable.changed"
)

type Exporter

type Exporter interface {
	Format() string
	Export(def *Definition) ([]byte, error)
}

Exporter 定义导出器:把 Definition 序列化为目标格式。 典型用途:把设计器 JSON 导出为 BPMN 交由 bpmn-js / Camunda Modeler 打开。

type ExpressionEvaluator

type ExpressionEvaluator interface {
	EvalBool(ctx context.Context, expression string, env Vars) (bool, error)
}

ExpressionEvaluator 布尔表达式求值器(网关条件、动态办理人等)。

约定:

  • 表达式为裸表达式(BPMN conditionExpression 的 ${...} 由导入器剥壳);
  • 求值必须无副作用、确定性、禁止 I/O(安全要求);
  • 求值失败返回 error,引擎一律 fail-closed(不误走分支)。

内置 SimpleEvaluator 覆盖常见比较/逻辑运算;生产可换 contrib/exprlang (expr-lang,与 go-wind-oa/im 现行为一致)或 go-scripts 的 CEL/Expr 引擎。

type FormatRegistry

type FormatRegistry struct {
	// contains filtered or unexported fields
}

FormatRegistry 导入/导出器注册表。

func NewFormatRegistry

func NewFormatRegistry() *FormatRegistry

func (*FormatRegistry) RegisterExporter

func (r *FormatRegistry) RegisterExporter(ex Exporter) *FormatRegistry

RegisterExporter 注册导出器,同格式覆盖。

func (*FormatRegistry) RegisterImporter

func (r *FormatRegistry) RegisterImporter(im Importer) *FormatRegistry

RegisterImporter 注册导入器,同格式覆盖。

func (*FormatRegistry) ResolveImport

func (r *FormatRegistry) ResolveImport(format string, data []byte) (Importer, error)

ResolveImport 按 format 选择导入器;format 为空时依次尝试嗅探与缺省。

func (*FormatRegistry) SetDefault

func (r *FormatRegistry) SetDefault(format string) *FormatRegistry

SetDefault 设置 Format 为空时的缺省格式。

func (*FormatRegistry) SetDetector

func (r *FormatRegistry) SetDetector(fn func(data []byte) string) *FormatRegistry

SetDetector 设置内容嗅探器(Format 为空时先于 defaultFmt 生效)。

type HistoryEvent

type HistoryEvent struct {
	ID         string
	InstanceID string
	Type       EventType
	NodeID     string
	TaskID     string
	ActorID    string
	Payload    Vars
	CreatedAt  time.Time
}

HistoryEvent 流转历史(append-only,审计与时间线渲染)。

type HistoryStore

type HistoryStore interface {
	Append(ctx context.Context, ev *HistoryEvent) error
	ListByInstance(ctx context.Context, instanceID string) ([]*HistoryEvent, error)
}

HistoryStore 历史存储(append-only)。

type IDGen

type IDGen func() string

IDGen 标识生成器。默认 crypto/rand 随机 hex。

type IdentityProvider

type IdentityProvider interface {
	ResolveApprovers(ctx context.Context, req ResolveRequest) ([]string, error)
	// ResolveDelegate 返回 userID 的受托人;无委托时返回 userID 本身。
	ResolveDelegate(ctx context.Context, tenantID, userID string) (string, error)
	// ResolveGroupsForUser 返回用户所属的组编码列表(候选组任务的
	// Claim 鉴权与组待办可见性)。M2 起为必选方法——存量实现需补齐;
	// 无组体系的宿主返回 (nil, nil) 即可。
	ResolveGroupsForUser(ctx context.Context, tenantID, userID string) ([]string, error)
}

IdentityProvider 身份解析 SPI:把 ApproverRule 解析为具体用户 ID 列表, 并提供委托(delegation)代办的叠加解析。

静态规则(USER/STARTER)核心内置可解析;动态规则(LEADER/POSITION/ROLE/EXPR) 必须由宿主实现本接口,未装配时引擎 fail-closed 报 ErrNotConfigured。

type Importer

type Importer interface {
	// Format 返回格式标识,如 "bpmn-xml"、"wind-json-v2"。
	Format() string
	// Import 解析并构建 Definition(不含 Key/TenantID/Version,由 Deploy 填充)。
	Import(data []byte) (*Definition, error)
}

Importer 定义导入器:把一种序列化格式转换为引擎内部 Definition。

这是 BPMN 兼容的正式接口——format/bpmn(BPMN 2.0 XML)与 format/windjson (go-wind-oa/im 的 node_config v2 JSON)都实现本接口;宿主也可注册自有 格式(如钉钉风格审批流 JSON),对引擎完全透明。

type Instance

type Instance struct {
	ID                string
	TenantID          string
	DefinitionKey     string
	DefinitionVersion int
	BusinessKey       string // 业务单据 ID
	BusinessType      string // 业务单据类型(监听器路由用)
	StarterID         string
	Status            InstanceStatus
	Variables         Vars
	// 子流程链接:本实例由父实例的 ParentTokenID 令牌在 callActivity 节点发起。
	ParentInstanceID string
	ParentTokenID    string
	CreatedAt        time.Time
	EndedAt          *time.Time
}

Instance 流程实例。

type InstanceStatus

type InstanceStatus string

InstanceStatus 实例状态。

const (
	InstanceRunning   InstanceStatus = "RUNNING"
	InstanceApproved  InstanceStatus = "APPROVED"  // 正常走完 END
	InstanceRejected  InstanceStatus = "REJECTED"  // 驳回终结(fail-closed)
	InstanceWithdrawn InstanceStatus = "WITHDRAWN" // 发起人撤回
	InstanceAborted   InstanceStatus = "ABORTED"   // 管理员强制终止
)

func (InstanceStatus) Live

func (s InstanceStatus) Live() bool

Live 报告实例是否仍在运行。

type InstanceStore

type InstanceStore interface {
	Save(ctx context.Context, inst *Instance) error
	Get(ctx context.Context, id string) (*Instance, error)
	Update(ctx context.Context, inst *Instance) error
	ListByStatus(ctx context.Context, status InstanceStatus) ([]*Instance, error)
	// List 按租户列出实例(全状态),按创建时间升序。
	List(ctx context.Context, tenantID string) ([]*Instance, error)
}

InstanceStore 实例存储。

type Listener

type Listener interface {
	OnFlowEvent(ctx context.Context, ev *Event)
}

Listener 监听器。回调 panic 由引擎 recover 保护,不影响状态机结果。

type ListenerFunc

type ListenerFunc func(ctx context.Context, ev *Event)

ListenerFunc 函数式监听器适配。

func (ListenerFunc) OnFlowEvent

func (f ListenerFunc) OnFlowEvent(ctx context.Context, ev *Event)

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

Logger 引擎最小日志门面。宿主可用 slog / zap / kratos log 适配。

type Node

type Node struct {
	ID   string   `json:"id"`
	Name string   `json:"name,omitempty"`
	Type NodeType `json:"type"`

	// UserTask
	Approver *ApproverSpec `json:"approver,omitempty"`
	Approval ApprovalSpec  `json:"approval,omitempty"`
	Timer    *TimerSpec    `json:"timer,omitempty"`

	// ScriptTask / ServiceTask
	Script *ScriptSpec `json:"script,omitempty"`

	// CallActivity
	SubprocessKey     string `json:"subprocessKey,omitempty"`
	SubprocessVersion int    `json:"subprocessVersion,omitempty"` // 0 = latest

	// ExclusiveGateway 默认出边 ID(无条件命中时兜底,fail-closed:必须存在)。
	DefaultEdge string `json:"defaultEdge,omitempty"`

	// BoundaryEvent 专用:挂接的目标 userTask/callActivity;Interrupting 缺省
	// true(到期取消原任务并接管流程),false = 非中断(只派生升级分支)。
	// ErrorCode 非空 = 错误边界(捕获 callActivity 子流程抛出的错误码,
	// 空串通配);Timer 非空 = 定时边界。
	AttachedTo   string `json:"attachedTo,omitempty"`
	Interrupting *bool  `json:"interrupting,omitempty"`
	ErrorCode    string `json:"errorCode,omitempty"`

	// MessageEvent 专用:消息名(SendMessage 按实例 + 消息名投递解锁)。
	Message string `json:"message,omitempty"`

	Documentation string `json:"documentation,omitempty"`
}

Node 定义图中的节点。

func (*Node) IsInterrupting

func (n *Node) IsInterrupting() bool

IsInterrupting 边界事件是否中断型(缺省 true,BPMN cancelActivity 默认语义)。

type NodeType

type NodeType string

NodeType 节点类型。命名对齐 BPMN 2.0 元素,便于与 BPMN 工具链互认。

const (
	NodeStartEvent       NodeType = "startEvent"
	NodeEndEvent         NodeType = "endEvent"
	NodeUserTask         NodeType = "userTask"
	NodeScriptTask       NodeType = "scriptTask"
	NodeServiceTask      NodeType = "serviceTask"              // v0 与 ScriptTask 同语义(回调由宿主监听器承接)
	NodeTimerEvent       NodeType = "intermediateTimerEvent"   // 中间定时器:令牌阻塞至到期,宿主 cron 驱动续跑
	NodeMessageEvent     NodeType = "intermediateMessageEvent" // 中间消息:令牌阻塞等外部投递(SendMessage 解锁)
	NodeErrorEndEvent    NodeType = "errorEndEvent"            // 错误结束:终结实例并抛出错误码(父 callActivity 错误边界可捕获)
	NodeBoundaryEvent    NodeType = "boundaryEvent"            // 边界事件:挂接在 userTask/callActivity 上,到期或错误触发升级/接管分支
	NodeExclusiveGateway NodeType = "exclusiveGateway"
	NodeParallelGateway  NodeType = "parallelGateway" // 分叉/汇合同型,按出入度区分(BPMN 惯例)
	NodeInclusiveGateway NodeType = "inclusiveGateway"
	NodeCallActivity     NodeType = "callActivity" // 子流程
)

type Option

type Option func(*Engine)

func WithClock

func WithClock(c Clock) Option

func WithEvaluator

func WithEvaluator(v ExpressionEvaluator) Option

func WithExporters

func WithExporters(ex ...Exporter) Option

WithExporters 注册定义导出器。

func WithIDGen

func WithIDGen(g IDGen) Option

func WithIdentity

func WithIdentity(p IdentityProvider) Option

func WithImporters

func WithImporters(im ...Importer) Option

WithImporters 注册定义导入器(bpmn.Importer、windjson.Importer 等)。

func WithListener

func WithListener(l ...Listener) Option

WithListener 注册全局监听器(按注册顺序调用)。

func WithLogger

func WithLogger(l Logger) Option

func WithMaxSteps

func WithMaxSteps(n int) Option

func WithScripts

func WithScripts(s ScriptRunner) Option

func WithStore

func WithStore(s Store) Option

type RejectMode

type RejectMode string

RejectMode 驳回语义。

const (
	// RejectTerminate 驳回即终结实例(REJECTED),与 go-wind-oa/im 现行为一致(默认)。
	RejectTerminate RejectMode = "TERMINATE"
	// RejectStay 驳回后停留(任务标 REJECTED,实例继续),留给宿主自行接线后续处理。
	RejectStay RejectMode = "STAY"
)

type ResolveRequest

type ResolveRequest struct {
	TenantID     string
	InstanceID   string
	DefinitionID string
	NodeID       string
	StarterID    string
	InstanceVars Vars
	Rules        []ApproverRule
}

ResolveRequest 办理人解析请求。

type ScriptRunner

type ScriptRunner interface {
	Run(ctx context.Context, spec *ScriptSpec, env Vars) (any, error)
}

ScriptRunner 脚本执行器(脚本任务与脚本监听器)。 实现方负责沙箱、超时(context deadline)与并发隔离(引擎池)。

type ScriptSpec

type ScriptSpec struct {
	Lang  string `json:"lang,omitempty"`
	Code  string `json:"code,omitempty"`
	Scope string `json:"scope,omitempty"` // "" | "instance" | "local"
}

ScriptSpec 脚本任务/监听器脚本规格。Lang 由 ScriptRunner 实现方约定 (contrib/goscripts: js/lua/python/go/cel/expr...)。

Scope 决定脚本返回 map 的落点:

  • "" / "instance"(默认)→ 实例变量(业务数据可见);
  • "local" → 令牌级局部变量(仅当前分支的后续节点可读,不污染业务数据)。

type SimpleEvaluator

type SimpleEvaluator struct{}

func NewSimpleEvaluator

func NewSimpleEvaluator() *SimpleEvaluator

func (SimpleEvaluator) EvalAny

func (SimpleEvaluator) EvalAny(_ context.Context, expression string, env Vars) (any, error)

EvalAny 实现 ValueEvaluator:求值任意表达式(多实例 collection 等)。

func (SimpleEvaluator) EvalBool

func (SimpleEvaluator) EvalBool(ctx context.Context, expression string, env Vars) (bool, error)

type StartRequest

type StartRequest struct {
	TenantID     string
	Key          string
	Version      int // 0 = latest
	BusinessKey  string
	BusinessType string
	StarterID    string
	Variables    Vars
	// ParentInstanceID / ParentTokenID 子流程链接:由引擎在 callActivity
	// 处自动填充;宿主直接调用时不应设置。
	ParentInstanceID string
	ParentTokenID    string
}

type Store

type Store interface {
	Definitions() DefinitionStore
	Instances() InstanceStore
	Tokens() TokenStore
	Tasks() TaskStore
	History() HistoryStore
}

Store 持久化 SPI。每次状态迁移引擎都会调用对应写方法, 实现方应保证:同实例内调用按发生顺序可见( 单实例串行)。 生产实现(ent)建议在每个引擎入口(Start/CompleteTask/...)包一层事务。

type Strategy

type Strategy string

Strategy 多实例审批策略(对应 BPMN multiInstanceLoopCharacteristics 的完成语义)。

const (
	// StrategyAll 会签:全员通过才推进,任一驳回即驳回(默认,fail-closed)。
	StrategyAll Strategy = "ALL"
	// StrategyAny 或签:任一通过即推进(其余任务取消),全员驳回才驳回。
	StrategyAny Strategy = "ANY"
)

type Task

type Task struct {
	ID         string
	InstanceID string
	TenantID   string
	NodeID     string
	TokenID    string
	Name       string
	Assignee   string
	// CandidateGroups 候选组(Assignee 为空时任务待认领,组内成员可 Claim)。
	CandidateGroups []string
	Status          TaskStatus
	Outcome         string
	Comment         string
	DueAt           *time.Time
	CreatedAt       time.Time
	EndedAt         *time.Time
}

Task 用户任务。

type TaskStatus

type TaskStatus string

TaskStatus 任务状态。

const (
	TaskPending   TaskStatus = "PENDING"
	TaskApproved  TaskStatus = "APPROVED"
	TaskRejected  TaskStatus = "REJECTED"
	TaskCancelled TaskStatus = "CANCELLED"
	TaskForwarded TaskStatus = "FORWARDED"
)

type TaskStore

type TaskStore interface {
	Save(ctx context.Context, t *Task) error
	Update(ctx context.Context, t *Task) error
	Get(ctx context.Context, id string) (*Task, error)
	ListByInstance(ctx context.Context, instanceID string) ([]*Task, error)
	ListByToken(ctx context.Context, tokenID string) ([]*Task, error)
	ListPendingByAssignee(ctx context.Context, tenantID, assignee string) ([]*Task, error)
	// ListUnclaimedByGroups 列出分派给任一候选组、尚未认领的待办
	//(PENDING + Assignee 为空 + CandidateGroups 与给定组有交集)。
	ListUnclaimedByGroups(ctx context.Context, tenantID string, groups []string) ([]*Task, error)
	ListDue(ctx context.Context, now time.Time) ([]*Task, error)
}

TaskStore 任务存储。

type TimerAction

type TimerAction string

TimerAction 任务到期动作(缺省仅广播 task.due,由监听器自决)。

const (
	TimerActionNone        TimerAction = ""
	TimerActionAutoApprove TimerAction = "auto_approve" // 到期自动通过(系统操作者 flow:timer)
	TimerActionAutoReject  TimerAction = "auto_reject"  // 到期自动驳回(按节点 RejectMode 终结/停留)
)

type TimerSpec

type TimerSpec struct {
	Duration Duration    `json:"duration,omitempty"` // 如 "24h"、"30m"
	Action   TimerAction `json:"action,omitempty"`   // "" | auto_approve | auto_reject
}

TimerSpec 超时规格:任务创建后 DueAt = now + Duration。 调度由宿主 cron 驱动 CheckDueTasks:Action 为空时仅广播 task.due 事件 (催办/升级由监听器承接),非空时引擎直接执行对应动作。

type Token

type Token struct {
	ID          string
	InstanceID  string
	NodeID      string
	Status      TokenStatus
	ParentID    string     // fork 产生的子令牌指向分叉源令牌
	ChildInstID string     // 阻塞于 callActivity 时记录子流程实例
	DueAt       *time.Time // 阻塞于定时器节点时的到期时刻
	// Locals 令牌级局部变量(变量作用域):并行分支各持一份(fork 时快照
	// 克隆),读取时叠加在实例变量之上(同名覆盖),不回写业务数据。
	Locals    Vars
	CreatedAt time.Time
}

Token 执行令牌:实例在图中的游标。

type TokenStatus

type TokenStatus string

TokenStatus 令牌状态。

const (
	TokenRunning TokenStatus = "RUNNING" // 正在推进
	TokenWaiting TokenStatus = "WAITING" // 阻塞于用户任务/子流程/汇合点
	TokenEnded   TokenStatus = "ENDED"
)

type TokenStore

type TokenStore interface {
	Save(ctx context.Context, tk *Token) error
	Update(ctx context.Context, tk *Token) error
	Delete(ctx context.Context, id string) error
	Get(ctx context.Context, id string) (*Token, error)
	ListByInstance(ctx context.Context, instanceID string) ([]*Token, error)
	// ListDueTimers 列出到期的定时器令牌(WAITING 且 DueAt <= now)。
	ListDueTimers(ctx context.Context, now time.Time) ([]*Token, error)
}

TokenStore 令牌存储。

type ValueEvaluator

type ValueEvaluator interface {
	EvalAny(ctx context.Context, expression string, env Vars) (any, error)
}

ValueEvaluator 可选能力接口:求值非布尔表达式(多实例 collection 等)。 内置 SimpleEvaluator 与 contrib/exprlang 均实现;未实现该接口的求值器 遇到 collection 时引擎 fail-closed 报 ErrNotConfigured。

type Vars

type Vars map[string]any

Vars 变量环境:实例级变量 + 表单数据的统一命名空间。 表达式、脚本、监听器共享同一环境;键名建议采用业务字段名(如 days、amount)。

func (Vars) Clone

func (v Vars) Clone() Vars

Clone 深拷贝(只拷贝顶层,值 presumed 不可变)。

func (Vars) Merge

func (v Vars) Merge(src Vars) Vars

Merge 将 src 合并进 v(src 优先),返回 v。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL