shared 教程
本教程展示如何构建和检查执行策略、查询后端声明自己能做什么,以及转换原生状态码。这些是 luna_thread 其他所有包都接受的输入值。
快速开始
导入该包:
import {
"Luna-Flow/luna_thread/shared",
}
构建一个有四个工作线程、块大小为 256 个元素的策略:
test "shared quick start" {
let policy = @shared.make_execution_policy(worker_count=4, chunk_size=256).unwrap()
inspect(@shared.backend_label(policy.backend), content="native")
inspect(@shared.is_parallel(policy), content="true")
}
日常任务
处理被拒绝的策略
make_execution_policy 返回它发现的第一个问题,因此你可以报告它而不必中止:
fn describe(result : Result[@shared.ExecutionPolicy, @shared.PolicyError]) -> String {
match result {
Ok(policy) => "ok with \{policy.worker_count} workers"
Err({ issue: WorkerCountMustBePositive(n) }) => "bad worker count \{n}"
Err({ issue: ChunkSizeMustBePositive(n) }) => "bad chunk size \{n}"
Err({ issue: UnsupportedBackendForV1(_) }) => "backend not available"
Err({ issue: UnsupportedModeForV1(_) }) => "mode not available"
}
}
test "rejected policies" {
inspect(describe(@shared.make_execution_policy(worker_count=2)), content="ok with 2 workers")
inspect(describe(@shared.make_execution_policy(chunk_size=0)), content="bad chunk size 0")
inspect(
describe(@shared.make_execution_policy(mode=@shared.asynchronous_mode())),
content="mode not available",
)
}
重新检查已存储的策略
validate_policy 列出你已有策略的所有问题,例如从工作流中读回的策略:
test "validate a stored policy" {
let policy = @shared.native_policy()
assert_eq(@shared.validate_policy(policy).length(), 0)
}
查询后端的声明
test "capabilities" {
let native = @shared.RuntimeCapabilities::for_backend(@shared.native_target())
inspect(native.supports_async, content="false")
let js = @shared.RuntimeCapabilities::for_backend(@shared.javascript_target())
inspect(js.supports_zero_copy_buffers, content="true")
}
转换状态码
test "status codes" {
let status = @shared.native_status_from_code(6)
debug_inspect(status, content="Overflow")
inspect(@shared.native_status_code(status), content="6")
}
进阶
策略会流入 @plan 的构建函数、@workflow.Workflow::new 以及门面的 make_policy。整数编码的请求记录(NativeBuffer、NativeMapRequest 等)镜像了 C 结构体,在你为 C 运行时编写自己的绑定时很有用;架构指南列出了这些编码。
常见陷阱
ExecutionPolicy::new和javascript_policy在策略被拒绝时会中止;javascript_policy在 v1 中总是中止。参数来自外部时,请使用make_execution_policy。RuntimeCapabilities::for_backend是一张固定的表。JavaScript 一行并不意味着 JavaScript 后端会运行任何东西。native_status_from_code把每个未知编码(包括工作流状态码 8 到 14)映射为InvalidArgument。需要原始编码时请保留它。
下一步
shared API 列出了每个值,shared 设计解释了策略规则和状态码映射。plan 教程在计划中使用策略。