16 KiB
GFlow Engine
English | 简体中文
GFlow — AI pre-screens · Humans approve · Automation follows
GFlow Engine is a lightweight, embeddable approval workflow engine built on RuleGo. Process definitions reuse the RuleGo rule-chain DSL (JSON), while tasks, process instances and history are persisted to a relational database by the engine itself — no separate process middleware to deploy. Approval nodes and automation nodes (rule chains, HTTP calls, AI agents, sub-processes) live in the same process DSL — downstream actions run automatically once approved; Chinese-style approval semantics (any-sign, all-sign, threshold vote, sequential approval, dynamic add/remove signers, return) work out of the box.
Note: the DSL is a BPMN-style approval flow in JSON form; it does not parse BPMN 2.0 XML.
Features
- Chinese-style approval semantics out of the box: any-sign, all-sign (unanimous with one-vote veto), threshold vote (majority/percent/count), sequential approval, dynamic add/remove signers, transfer, delegation, claim, return, withdraw, overdue handling — no extra development. Definitions are versioned: running instances stay on the version they started with.
- Approvals and automation in one flow: the process DSL is a
RuleGorule chain — approval nodes mix freely with gateways, parallel branches, rule chains, HTTP calls, AI agents and sub-processes. Once approved, downstream actions run automatically (booking, notifications, writing back to your systems). - Embeds in your host, identity stays yours: integrate as a pure Go library with no user-store coupling; approvers resolve by user/role/department/manager hierarchy via
IdentityService; every operation is permission-checked against the actor, with multi-tenancy end to end. - Lightweight and dependable: no mandatory middleware; PostgreSQL / MySQL out of the box (pluggable dialects for Dameng, Kingbase, ...); runtime/history table split keeps audits off the hot path; 18 task event hooks drive notifications and other side effects (docs/events.md).
GFlow Platform (Enterprise Edition)
GFlow Platform (极风工作流) is a ready-to-run approval workflow platform built on GFlow Engine (the enterprise edition of GFlow), with both frontend and backend included:
-
Approval center: initiate requests; to-do / done / CC'd to me; approval statistics
-
Process designer + form designer: business staff build flows and forms by drag & drop, zero code
-
AI approval: AI agents join the approval flow and pre-screen requests
-
IM integration: approval to-dos pushed in real time as work-notify cards to DingTalk / WeCom / Feishu; tap the card to land on the approval detail with passwordless sign-in; directory sync and account binding out of the box
-
Admin console: process definitions, instances, tasks, automation, organization & permissions
-
Live demo: http://8.134.32.225:8081 (
admin/admin123)
Screenshots
Real screenshots of GFlow Platform (极风工作流).
Process Designer — tree-style canvas + approval configuration drawer, zero code for business admins
Workbench · New Request — to-dos at a glance; pick a template, fill the form, done in a minute
Approval Inbox · Approval Detail — inbox-style to-dos; the timeline shows condition hits and every upcoming approver
Mobile H5 — start, approve and track requests right from your phone
IM Work Notifications — approval to-dos pushed to DingTalk / WeCom / Feishu; tap the card to handle it with passwordless sign-in
Installation
go get github.com/rulego/gflow-engine
Requires Go 1.24+ and RuleGo v0.37+. Initialize the workflow tables with scripts/00.init_bpm_pg.sql (PostgreSQL) or scripts/00.init_bpm_mysql.sql (MySQL); initialization and upgrade guidance lives in docs/migration.md.
Database setup
The engine manages only its own workflow tables; users, roles and departments belong to the host application.
PostgreSQL:
createdb gflow # create the database first (or: psql -c "CREATE DATABASE gflow")
psql -d gflow -f scripts/00.init_bpm_pg.sql
MySQL:
mysql -u root -p -e "CREATE DATABASE gflow DEFAULT CHARACTER SET utf8mb4"
mysql --default-character-set=utf8mb4 -u root -p gflow < scripts/00.init_bpm_mysql.sql
The engine owns 7 wf_-prefixed tables: process definitions, instances and tasks (runtime + history each), the candidate pool, and approval comments — see docs/migration.md for column details.
Quick start
Run the complete example before integrating it yourself (deploy → start → approve → inspect instance status in one go, zero-dependency on in-memory SQLite):
go run ./examples/leave_approval
Minimal integration code:
package main
import (
"context"
"log"
"github.com/rulego/gflow-engine/components"
"github.com/rulego/gflow-engine/config"
"github.com/rulego/gflow-engine/model"
"github.com/rulego/gflow-engine/service"
)
func main() {
ctx := context.Background()
// 1. Configure the database and start the engine
cfg := &config.Config{
Database: &config.DatabaseConfig{
Driver: "postgres",
Dsn: "host=127.0.0.1 user=postgres password=postgres dbname=gflow port=5432 sslmode=disable",
},
}
engine, err := service.NewWorkflowEngineBuilder().
SetName("demo").
SetConfig(cfg).
SetIDGenerator(service.NewIDGenerator()).
Build()
if err != nil {
log.Fatalf("build engine: %v", err)
}
if err := engine.Start(ctx); err != nil {
log.Fatalf("start engine: %v", err)
}
defer engine.Stop(ctx)
// 2. Register workflow node components (userTask/serviceTask/automation/...)
// Dependencies are pulled from the engine itself; register your host service
// functions via WithServiceFuncs — see docs/components.md.
// Note: engine.Start must have succeeded first, otherwise registration
// fails fast with an error.
if err := components.RegisterFromEngine(engine); err != nil {
log.Fatalf("register components: %v", err)
}
// 3. Deploy a process definition (the DSL is a rulego rule chain JSON,
// see examples/leave_approval). All mutating operations take an explicit
// actor — the operator identity used for auditing and permission checks.
admin := service.Actor{UserID: "admin", UserName: "admin", TenantID: "default"}
_, err = engine.GetProcessService().Deploy(ctx, admin, &model.WfProcess{
ProcessKey: "leave_approval",
Name: "Leave Approval",
DefinitionJSON: leaveApprovalDSL, // process DSL JSON; see examples/leave_approval/dsl.json for reference
TenantID: "default",
CreatedBy: "admin",
}, true)
if err != nil {
log.Fatalf("deploy process: %v", err)
}
// 4. Start a process instance (pass service.WithDraft() as a variadic
// option to start in draft mode; omit it for a normal start)
instanceID, err := engine.GetRuntimeService().StartProcessInstanceByKey(
ctx,
service.Actor{UserID: "emp001", UserName: "Zhang San", TenantID: "default"},
"leave_approval",
"leave_emp001_1", // business key
map[string]interface{}{"days": 5, "managerId": "mgr001", "reason": "family affairs"},
)
if err != nil {
log.Fatalf("start instance: %v", err)
}
log.Printf("instance started: %s", instanceID)
}
Handling a pending task (also import github.com/rulego/gflow-engine/types/dto and .../types/enums):
tasks, _, err := engine.GetTaskService().GetTaskList(ctx, service.Actor{
UserID: "mgr001",
TenantID: "default",
}, &dto.TaskQuery{
Assignee: "mgr001",
PageRequest: dto.PageRequest{
Status: []string{string(enums.TaskStatusPending), string(enums.TaskStatusActive)},
PageSize: 10,
},
})
if err != nil || len(tasks) == 0 {
return
}
err = engine.GetTaskService().CompleteWithApproval(ctx, service.Actor{
UserID: "mgr001",
TenantID: "default",
}, &service.ApprovalRequest{
TaskID: tasks[0].ID,
ApprovalResult: enums.ApprovalResultApproved,
Comment: "approved",
})
A complete runnable example (single sign-off, all-sign, sequential approval) lives in examples/leave_approval — it runs zero-dependency on an in-memory SQLite database by default (GFLOW_DSN switches to PostgreSQL/MySQL). An httpCall + switch combination example (query an external API, map the response into process variables, route by the result) lives in examples/http_call. The engine ships with an in-memory mock identity service for tests only — inject your own IdentityService as described in the next section for production.
Identity integration (organizational data)
The engine does not bind to any user system. Tasks offered to roles, departments or managers resolve their assignees through the service.IdentityService interface — in production you must inject an implementation backed by your own user/role/department tables (the built-in in-memory mock is for tests only):
// Implement all 9 methods of service.IdentityService against your org tables
type OrgIdentityService struct {
db *gorm.DB // host application data source
}
// Users by role (role candidate tasks); the other methods follow the same pattern
func (s *OrgIdentityService) GetUserIDsByRoleID(ctx context.Context, tenantID, roleID string) ([]string, error) {
var userIDs []string
err := s.db.WithContext(ctx).
Table("user_roles").
Where("tenant_id = ? AND role_id = ?", tenantID, roleID).
Pluck("user_id", &userIDs).Error
return userIDs, err
}
// Remaining methods and their purpose:
// GetUserIDsByDepartmentID users by department (dept candidate tasks)
// GetDepartmentManagerUserID department manager (dept candidate tasks)
// GetUserManagerID direct manager (manager candidate tasks)
// GetUserManagerHierarchy manager hierarchy (multi_level_manager candidate tasks)
// GetUserDepartmentID department of a user
// GetRoleIDsByUserID roles of a user (todo visibility for role candidates)
// GetDepartmentIDsByUserID departments of a user (todo visibility for dept candidates)
// GetUserIDsByGroupID users by custom group (reserved extension)
Inject it through the builder:
engine, err := service.NewWorkflowEngineBuilder().
SetName("demo").
SetConfig(cfg).
SetIdentityService(&OrgIdentityService{db: gormDB}).
Build()
Mapping from approver configuration (approver.type) to interface methods:
| approver.type | Resolving methods |
|---|---|
user |
none (user IDs given directly via userIds) |
role |
GetUserIDsByRoleID; todo visibility via GetRoleIDsByUserID |
dept |
GetUserIDsByDepartmentID / GetDepartmentManagerUserID; todo visibility via GetDepartmentIDsByUserID |
manager |
GetUserManagerID |
multiLevelManager |
GetUserManagerHierarchy |
initiatorSelect / initiatorSelf |
none (chosen by initiator / the initiator) |
Optional hardening: if the implementation also implements
TenantMembershipChecker(IsUserInTenant), the engine verifies that transfer/delegation/reassign targets belong to the task's tenant and blocks cross-tenant reassignment; without it the check is skipped (with a warning logged).
Process DSL
A process definition is a RuleGo rule chain: nodes describe the steps, connections describe the flow, and approval configuration lives in each node's configuration. The BPM extension nodes:
| Node type | Description |
|---|---|
startTask |
Start node: marks the process entry point; no auth checks (handled by the initiator layer) |
userTask |
Human approval task: single/countersign, candidates (user/role/department), form (formKey passed through to wf_task.form_key), priority, due date; configuration.taskName/taskDescription override the node name/description |
ccTask |
CC task: creates a CC record and notifies the host app via CCTaskCreatedListener |
serviceTask |
Service task: invokes a Go function (registered via action.Functions) |
automation |
Automation node: invokes a RuleGo rule chain |
subProcess |
Sub-process: starts an independent child instance, then returns to the parent flow |
aiAgent |
AI agent node: invokes an agent rule chain and routes the output |
httpCall |
HTTP call: synchronous external request, response merged into process variables |
startProcess |
Rule-chain-only: starts a BPM process instance from within a rule chain (e.g. scheduled auto-start of approvals) |
Native RuleGo nodes (switch gateways, fork/inclusive/join parallel joins, ...) can be used directly — see the RuleGo standard components.
For the full node reference (configuration fields, approval modes, reject strategies, httpCall SSRF protection) see docs/components.md. The complete documentation set for embedders — task lifecycle, events, persistence model — is indexed in docs/README.md.
Extension points
- Identity: implement
service.IdentityServiceto resolve approvers by role, department, group or manager hierarchy. - SQL dialect: implement
service.DialectProviderto support additional databases — see examples/custom_dialect (Dameng, Kingbase). - Distributed locking: the engine ships a built-in local in-memory lock (
lock.NewLocalLock). For multi-instance deployments, implement thelock.Lockerinterface (e.g. RedisSET NXwith a Lua-script release) and inject it viaWorkflowEngineBuilder.SetLocker. - Task events:
TaskEventListener/CCTaskCreatedListenerreceive task lifecycle events to drive notifications and other side effects — see docs/events.md for the full event catalog, payload fields and integration guide.
Contact & commercial licensing
GFlow Engine is free and open source (Apache-2.0). If you need the Enterprise Edition — GFlow Platform(极风工作流)with source-code delivery (flow/form designers, approval UI, AI review) — or commercial support, see https://gflow.rulego.cc/ or reach us through any of these channels (please mention your purpose when adding):
- QQ: 2215016127
- WeChat:
rulegoteam - Email: rulego@outlook.com
License
GFlow Engine is licensed under Apache 2.0. See the LICENSE file for details.