Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
开始任务前先读取 /dm/AGENTS.md,再读取目标路径适用的子级规则。
本目录是业务合同夹具。语言语法以[语言参考](../../../LANGUAGE.md)为准,运行条件和测试入口见 [README](README.md)。编写 Dever 应用时遵循[随包开发说明](../../../skills/dever/SKILL.md)。
明确外部输入、可信身份、事务和外部调用边界。生产支付、通知和筛选由实际 Adapter 接入;测试中的 Port fake 不用于生产,也不作为外部服务的验收依据。
+79
View File
@@ -0,0 +1,79 @@
# 业务工作流示例
这些示例演示如何用 Dever 处理支付、审批、导入和登录。支付、通知和外部筛选只声明了 Port,没有绑定 Adapter,因此整个示例目录不能直接构建。要运行这些功能,需为相应的 Port 配置服务实现。
| 业务 | 源码 | 看点 |
| --- | --- | --- |
| 订单支付 | module/demo/order/flow/order.dv | long HTTP 读所属订单、调用支付、显式事务确认状态并入队通知;支付不放在数据库事务里 |
| 审批 | module/demo/approval/flow/approval.dv | 创建时默认 Pending,rule 选择决定,一次条件写转换状态;没有可绕过审批状态的通用 REST replace |
| 组织树/关系图 | module/demo/tree/flow/tree.dv | walk 广度优先遍历;业务明确去重,遇重复边/环只访问一次;无效节点引用报错,不自动补节点 |
| 租户批量导入 | module/demo/importer/flow/importer.dv | 受保护入口事务入队,Job 在执行租户中逐项写入;唯一性和字段规范化由数据模型完成 |
| 会话与成员验证 | module/demo/account/flow/account.dv | Provider 读取控制库,校验会话、用户、租户和成员状态,返回可信身份;不返回权限列表 |
| 分页、关系与私有字段 | module/demo/catalog/flow/catalog.dv | Category 直接 REST;Item 列表显式加载分类,仅公开需要的字段;SQL 使用具体结果 type 和参数绑定 |
| 调用外部服务筛选 | module/demo/selection/flow/selection.dv | 每个元素调用一次 Port;`find` 命中后停止,调用失败则返回错误 |
## 身份和数据库前提
真实集成时按[语言参考的 HTTP 与租户配置](../../../LANGUAGE.md#http-入口)设置控制连接、租户数据库、认证和站点。Provider 的 `verify` 绑定 `demo.account.verify`,`admin` 站点选择该 Provider。密钥和地址由实际环境提供,租户数据库通过显式命令准备。
`account` 在控制库保存用户、凭据、会话、租户和成员关系。`login` 先在事务外验证密码。验证期间用户可能改密或被停用,因此建立会话前,要在事务内核对密码哈希、凭据状态和成员资格。事务提交后才签发 Cookie。后续请求由核心先验签,再调用 `verify`。
示例只处理登录和会话,不提供注册入口。Cookie 登录须在 `sites` 中配置可信来源。会话有效期为一小时,Provider 的签名有效期应与之对应。登录成功只返回账号 ID。
业务函数从请求上下文获取用户和租户。订单的查询和更新都检查订单归属;审批入口则按审批权限授权,不限制管理员只能处理自己发起的申请。
## 支付与事务
`pay` 只允许用户支付自己的待付款订单。金额取自数据库。调用支付服务时,使用订单 UUID 作为幂等键:同一个键和金额必须返回同一收据;同一个键配不同金额必须报错。只有支付服务提供这项保证,才可以安全重试。
支付成功后,`markPaid` 在同一个事务中将订单改为已支付,并把通知加入队列。更新时再次核对订单归属、金额和待付款状态。如果条件不再满足,事务回滚并返回错误。此时外部扣款已经发生,数据库回滚不会退款。
`notifyPaid` 在数据库事务外发送通知。执行前,Worker 重新检查用户、成员资格、权限和队列所属租户。通知使用订单 UUID 去重;如果通知服务不支持幂等键,收件人可能收到重复通知。
测试用 Port 的替代实现检查调用顺序和错误处理。要验证实际扣款和通知送达,需接入对应服务。
## 遍历与导入
组织树按广度优先遍历。开始时按节点 ID 建立索引,重复 ID 或引用不存在的节点都会报错。节点第一次入队时就记为已访问,因此环和共享子节点都不会让同一节点被处理两次。
遍历时复用节点索引和队列。示例返回所有节点的名称,节点越多,结果列表占用的内存越大。只需逐项处理时,可使用 `Stream` 或无输出的 `loop`。
导入 Job 在一个事务中写入整批数据。编号重复或格式错误时整批回滚。相同的入队键只会复用活跃任务;已完成的批次再次提交,仍可能因编号重复而失败。
导入不使用 `create` 返回的记录,通知入队也不使用任务 ID。订单更新则要检查受影响的行数:只有一条记录从待付款改为已支付,才能继续入队。
有 I/O 或失败的筛选条件放在 flow 中,交给 fold/foldUntil 推进,不放进要求纯且不失败的过滤列。`find` 找到匹配项就返回该项,遍历结束仍未找到才返回 `null`。读取失败会中断查找并返回错误。
## 分页、关系与公开结果
分类使用 `rest data.category` 提供增删改查。商品含有私有成本字段 `supplier_cost`,因此列表只返回公开字段和总数。查询显式加载分类:`Loaded(null)` 表示商品未分组,`Unloaded` 表示尚未加载,示例会返回 `CategoryNotLoaded`。具名 SQL 直接返回 `List<app.Title>`。
示例覆盖空页、总数、分类加载状态,以及 SQLite 和 PostgreSQL 两种 SQL 方言的参数绑定。若直接返回含私有字段的数据模型分页结果,编译器会拒绝公开编码。使用游标分页时,也要为公开响应选择字段。
## 测试入口
- [业务合同测试](../../../test/rust/build/project/testing.rs)使用实际的审批、目录和筛选源码。审批状态、SQLite 分页、关系和具名 SQL 走真实实现;外部筛选调用使用显式 Port fake。
- [导入测试](../../../test/rust/build/project/testing_jobs.rs)使用实际的导入源码,在隔离数据库中验证队列、活跃任务去重、空批次、重复编号触发的整批回滚,以及失败后继续处理。
- [组织树用例](test/demo/tree/traversal.dv)覆盖广度优先、有环和共享子节点时的去重。单独使用树领域及其测试时,无需接入支付、通知或筛选服务。
在核心仓库根目录可运行两个集成测试:
```sh
cargo test --manifest-path rust/Cargo.toml --test build workflow_examples_use_real_models_and_explicit_external_fakes
cargo test --manifest-path rust/Cargo.toml --test build importer_example_runs_real_jobs_and_rolls_back_partial_batches
```
## 集成验收场景
| 场景 | 必须观察 |
| --- | --- |
| 重复支付、金额在支付间隙变化、通知入队失败 | 相同提供方键;状态写条件生效;数据库回滚;不重复扣款、不伪造退款 |
| Pending 审批成功,两次同时审批、修改已审批记录 | 恰好一次状态转换,其余 Conflict;不存在 REST 绕过路径 |
| 重复节点 ID、缺失子节点、重复边、环、深/宽图 | 重复键/缺失引用失败,其他按每节点一次结束;无递归和无全图逐轮复制 |
| 导入空批、重复 code、中途失败、取消、事务回滚 | 空批零次写入,失败不部分提交,真实连接可复用 |
| 两租户同号记录、入队后撤销会话/成员/权限、伪造租户 | 运行库拒绝越权/错配,不能回退控制库;不是只测编译和签名 |
| select/find 的成功、未命中、第三项失败、第二项命中 | 逐项一次,无提前全量求值;find 命中后不调用第三项;失败不返回默认结果 |
| 遍历一半取消、AsyncStream 短路 | 停止拉取,关闭来源,等待已启动工作结束;不把发出取消信号当完成 |
| inspect 与编辑器 | HTTP/Job、认证/租户/事务、Port、rule 分支与 loop 停止关系均来自实际语义模型 |
两租户队列和实时撤权已有独立的 SQLite、PostgreSQL 入口测试。接入实际 Provider 和外部服务后,仍需验证相关场景。分页、关系及私有字段以[语言参考](../../../LANGUAGE.md)为准。
@@ -0,0 +1,3 @@
public long post login = app.login
authenticated get current = app.userId
@@ -0,0 +1,6 @@
global type Credential {
username: Text(1, 80) lower unique
user_id: data.user.id
private password_hash: Text
active: Bool default true
}
@@ -0,0 +1,7 @@
global type Membership {
user_id: data.user.id
tenant_id: data.tenant.id
active: Bool default true
}
unique(user_id, tenant_id)
@@ -0,0 +1,10 @@
global type Session {
uuid: Uuid generated unique
subject: Text
user_id: data.user.id
tenant_id: data.tenant.id
tenant_key: Text
site: Text
expires_at: DateTime
revoked: Bool default false
}
@@ -0,0 +1,4 @@
global type Tenant {
key: Text unique
active: Bool default true
}
@@ -0,0 +1,4 @@
global type User {
uuid: Uuid generated unique
active: Bool default true
}
@@ -0,0 +1,28 @@
type Identity {
id: Text
user_id: data.user.id?
tenant_id: data.tenant.id?
}
flow verify(claims: dever.auth.Claims) (identity: Identity) {
session_id = uuid.parse(claims.session)
check session_id != null else Unauthorized
selected_key = claims.tenant
check selected_key != null else Unauthorized
now = dever.time.now()
session = data.session.first(uuid == session_id and subject == claims.subject and site == claims.site and tenant_key == selected_key and revoked == false and expires_at > now)
check session != null else Unauthorized
user_active = data.user.exists(id == session.user_id and active == true)
check user_active else Unauthorized
tenant_active = data.tenant.exists(id == session.tenant_id and key == session.tenant_key and active == true)
check tenant_active else Unauthorized
member_active = data.membership.exists(user_id == session.user_id and tenant_id == session.tenant_id and active == true)
check member_active else Unauthorized
identity = Identity { id = session.subject, user_id = session.user_id, tenant_id = session.tenant_id }
}
flow userId() (user_id: data.user.id) {
current: data.user.id? = dever.auth.userId()
check current != null else Unauthorized
user_id = current
}
@@ -0,0 +1,31 @@
flow login(username: Text, password: Secret, tenant: Text) (user_id: data.user.id) {
normalized = text.lower(text.trim(username))
credential = data.credential.first(username == normalized and active == true)
check credential != null else Unauthorized
valid = blocking(dever.crypto.passwordVerify(password, credential.password_hash))
check valid else Unauthorized
site = dever.site.key()
session = app.establishLogin(credential.id, credential.password_hash, tenant, site)
dever.auth.issueCookie(session.subject, uuid.toText(session.uuid), session.tenant_key)
user_id = session.user_id
}
transaction flow establishLogin(credential_id: data.credential.id, verified_hash: Text, selected_key: Text, site_key: Text) (session: data.session.Session) {
credential = data.credential.first(id == credential_id and password_hash == verified_hash and active == true)
check credential != null else Unauthorized
user = data.user.first(id == credential.user_id and active == true)
check user != null else Unauthorized
tenant = data.tenant.first(key == selected_key and active == true)
check tenant != null else Unauthorized
member_active = data.membership.exists(user_id == user.id and tenant_id == tenant.id and active == true)
check member_active else Unauthorized
now = dever.time.now()
session = data.session.create({
subject = uuid.toText(user.uuid)
user_id = user.id
tenant_id = tenant.id
tenant_key = tenant.key
site = site_key
expires_at = dever.time.add(now, dever.time.duration(3600000))
})
}
@@ -0,0 +1,3 @@
post create = app.create
post review = app.review
@@ -0,0 +1,10 @@
type Status {
Pending
Approved
Rejected
}
type Request {
title: Text(1, 120)
status: Status default Pending
}
@@ -0,0 +1,9 @@
flow create(title: Text) (request: data.request.Request) {
request = data.request.create({ title = title })
}
transaction flow review(request_id: data.request.id, approve: Bool) () {
chosen = app.decision(approve)
changed = data.request.update({ where = id == request_id and status == Pending }, { status = chosen })
check changed == 1 else Conflict
}
@@ -0,0 +1,5 @@
rule decision(approve: Bool) (status: data.request.Status)
approve {
true => Approved
false => Rejected
}
@@ -0,0 +1 @@
rest data.category
@@ -0,0 +1,3 @@
get list = app.list
get titles = app.titles
@@ -0,0 +1,3 @@
type Category {
name: Text(1, 80) unique
}
@@ -0,0 +1,10 @@
type Item {
title: Text(1, 120)
category_id: data.category.id?
private supplier_cost: Decimal(12, 2)
}
sql titles(limit: Int >= 1 and <= 100) (rows: List<app.Title>) {
sqlite = "SELECT title FROM demo_catalog_item ORDER BY id LIMIT ?1"
postgres = "SELECT title FROM demo_catalog_item ORDER BY id LIMIT $1"
}
@@ -0,0 +1,28 @@
type Title {
title: Text
}
type Item {
id: data.item.id
title: Text
category: Text?
}
type Page {
items: List<Item>
total: Int
}
type Error {
error CategoryNotLoaded
}
flow list(page: Int >= 1) (result: Page) {
found = data.item.page(order = id.asc, with = [category], page = page, size = 20)
items = app.summaries(found.items)
result = Page { items = items, total = found.total }
}
flow titles(limit: Int >= 1 and <= 100) (rows: List<Title>) {
rows = data.item.titles(limit)
}
@@ -0,0 +1,4 @@
loop summaries(rows: List<data.item.Item>) (items: List<Item>)
row in rows {
list Item { id = row.id, title = row.title, category = app.loadedName(row.category) }
}
@@ -0,0 +1,11 @@
rule loadedName(value: Related<data.category.Category?>) (name: Text?)
value {
Loaded(category) => app.categoryName(category)
Unloaded => fail(Error.CategoryNotLoaded)
}
rule categoryName(value: data.category.Category?) (name: Text?)
value {
null => null
other => value.name
}
@@ -0,0 +1 @@
post submit = app.submit
@@ -0,0 +1,3 @@
database default
job importRows(input: app.Request) retry(1) timeout(30000) = app.importRows
@@ -0,0 +1,4 @@
type Item {
code: Text(1, 40) unique
title: Text(1, 120)
}
@@ -0,0 +1,13 @@
type Row {
code: Text
title: Text
}
type Request {
key: Text
rows: List<Row>
}
transaction flow submit(input: Request) (task_id: Id) {
task_id = enqueue(job.importRows, input, input.key)
}
@@ -0,0 +1,4 @@
loop importRows(input: Request) ()
row in input.rows {
do data.item.create({ code = row.code, title = row.title })
}
@@ -0,0 +1 @@
long post pay = app.pay
@@ -0,0 +1,3 @@
database default
long job notifyPaid(input: app.Notice) retry(3) timeout(30000) = app.notifyPaid
@@ -0,0 +1,12 @@
type Status {
Pending
Paid
}
type Order {
uuid: Uuid generated unique
private owner owner_id: demo.account.data.user.id = dever.auth.userId()
amount: Decimal(12, 2)
status: Status default Pending
receipt: Text?
}
@@ -0,0 +1,23 @@
type Notice {
key: Uuid
receipt: Text
}
flow pay(order_id: data.id) () {
user_id = demo.account.userId()
order = data.first(id == order_id and owner_id == user_id and status == Pending)
check order != null else Conflict
receipt = port.pay(order.uuid, order.amount)
app.markPaid(order, receipt)
}
transaction flow markPaid(order: data.Order, receipt: Text) () {
user_id = demo.account.userId()
changed = data.update({ where = id == order.id and owner_id == user_id and status == Pending and amount == order.amount }, { status = Paid, receipt = receipt })
check changed == 1 else Conflict
enqueue(job.notifyPaid, Notice { key = order.uuid, receipt = receipt }, uuid.toText(order.uuid))
}
flow notifyPaid(input: Notice) () {
port.notify(input.key, input.receipt)
}
@@ -0,0 +1,3 @@
pay(key: Uuid, amount: Decimal) (receipt: Text) fails dever.process.Error
notify(key: Uuid, receipt: Text) () fails dever.process.Error
@@ -0,0 +1,9 @@
flow checkOne(value: Text, kept: List<Text>) (selected: List<Text>) {
accepted = port.accept(value)
selected = app.keep(accepted, value, kept)
}
flow findOne(value: Text) (acc: Text?, stop: Bool) {
stop = port.accept(value)
acc = app.foundValue(stop, value)
}
@@ -0,0 +1,9 @@
loop select(values: List<Text>) (selected: List<Text>)
value in values {
fold(kept = [], app.checkOne(value, kept))
}
loop find(values: List<Text>) (found: Text?)
value in values {
foldUntil(previous = null, app.findOne(value))
}
@@ -0,0 +1 @@
accept(value: Text) (accepted: Bool) fails dever.process.Error
@@ -0,0 +1,11 @@
rule keep(accepted: Bool, value: Text, kept: List<Text>) (selected: List<Text>)
accepted {
true => append(kept, value)
false => kept
}
rule foundValue(accepted: Bool, value: Text) (found: Text?)
accepted {
true => value
false => null
}
@@ -0,0 +1 @@
public post names = app.names
@@ -0,0 +1,33 @@
type Node {
id: Int
name: Text
children: List<Int>
}
type Cursor {
nodes: Map<Int, Node>
pending: List<Int>
position: Int
seen: Map<Int, Bool>
}
start(nodes: List<Node>, root: Int) (cursor: Cursor) {
cursor = Cursor { nodes = app.indexNodes(nodes), pending = [root], position = 0, seen = put({}, root, true) }
}
nextNode(cursor: Cursor) (step: Walk<Node, Cursor>) {
step = app.visit(get(cursor.pending, cursor.position), cursor)
}
expand(node_id: Int, cursor: Cursor) (step: Walk<Node, Cursor>) {
node = get(cursor.nodes, node_id)
check node != null else Invalid
next = cursor
next.position = next.position + 1
next = app.enqueueChildren(node.children, next)
step = Next(node, next)
}
enqueueChild(child: Int, cursor: Cursor) (next: Cursor) {
next = app.enqueue(get(cursor.seen, child) != null, child, cursor)
}
@@ -0,0 +1,14 @@
loop names(nodes: List<Node>, root: Int) (names: List<Text>)
node in walk(app.start(nodes, root), app.nextNode) {
list node.name
}
loop indexNodes(nodes: List<Node>) (indexed: Map<Int, Node>)
node in nodes {
index node.id
}
loop enqueueChildren(children: List<Int>, cursor: Cursor) (next: Cursor)
child in children {
fold(queue = cursor, app.enqueueChild(child, queue))
}
@@ -0,0 +1,16 @@
rule visit(node_id: Int?, cursor: Cursor) (step: Walk<Node, Cursor>)
node_id {
null => Done
other => app.expand(node_id, cursor)
}
rule enqueue(seen: Bool, child: Int, cursor: Cursor) (next: Cursor)
seen {
true => cursor
false => Cursor {
nodes = cursor.nodes
pending = append(cursor.pending, child)
position = cursor.position
seen = put(cursor.seen, child, true)
}
}
@@ -0,0 +1,12 @@
flow shortCircuit() ()
| step | kind | do |
| selected | loop | app.select(["no", "yes"]) |
| - | calc | assertEq(selected, ["yes"]) |
| found | loop | app.find(["no", "yes", "explode"]) |
| - | calc | assertEq(found, "yes") |
rule port.accept(value: Text) (accepted: Bool)
| value | accepted |
| "yes" | true |
| "explode" | fail(dever.process.Error.Failed("不应继续调用命中之后的元素")) |
| other | false |
@@ -0,0 +1,4 @@
traversal() () {
nodes = [app.Node { id = 1, name = "总部", children = [2, 3] }, app.Node { id = 2, name = "开发", children = [4] }, app.Node { id = 3, name = "测试", children = [4] }, app.Node { id = 4, name = "共享小组", children = [1] }]
assertEq(app.names(nodes, 1), ["总部", "开发", "测试", "共享小组"])
}