Golem社区代码规范:Rust风格指南与最佳实践
项目概述
Golem是一个支持多语言透明持久化执行的开源项目,采用Rust语言构建核心组件。本文档旨在提供Golem社区的Rust代码风格规范与最佳实践,帮助开发者编写高质量、一致的代码。
基础规范
代码格式化
Golem项目使用rustfmt进行代码格式化,配置文件为项目根目录下的.rustfmt.toml:
reorder_imports = true
newline_style = "Unix"
该配置强制按字母顺序重新排序导入项,并使用Unix风格的换行符(LF)。开发者应确保在提交代码前运行cargo fmt。
代码检查
项目使用Clippy进行代码质量检查,配置文件为clippy.toml。建议在开发过程中运行cargo clippy以捕获常见的Rust代码问题。
命名规范
类型命名
- 使用PascalCase(帕斯卡命名法)命名结构体、枚举、特质(trait)等类型。
- 例如:WorkerMetadata、ComponentMetadata
函数命名
- 使用snake_case(蛇形命名法)命名函数和方法。
- 例如:get_delay、start_if_needed
常量命名
- 使用SCREAMING_SNAKE_CASE(全大写蛇形命名法)命名常量。
- 例如:ENV_VAR_PREFIX、MAX_JITTER_FACTOR
模块命名
- 使用snake_case命名模块。
- 例如:golem_common、golem_worker_executor
代码组织
项目结构
Golem采用工作区(workspace)结构组织多个相关的Rust crate,主配置文件为Cargo.toml。每个子crate负责项目的不同功能模块:
[workspace]
members = [
"golem-api-grpc",
"golem-cli",
"golem-common",
"golem-component-compilation-service",
# 其他crate...
]
模块划分
- 遵循单一职责原则,每个模块应专注于特定功能。
- 例如,golem-common包含项目通用的配置、模型和工具函数。
- golem-worker-executor-base实现Worker执行的核心逻辑。
文档规范
注释风格
- 使用
///为公共API添加文档注释。 - 使用
//为非公共代码添加单行注释。 - 示例:golem-shard-manager/src/rebalancing.rs
/// Constructs a rebalance plan from the current state of the routing table.
///
/// The `threshold` parameter is used to reduce the number of shard reassignments by
/// allowing a given number of shards to be over or under the optimal count per pod.
///
/// The optimal count (balanced state) is number_of_shards/pod_count.
/// Threshold is a percentage of the optimal count, so for 10 pods with 1000 shards,
/// and a threshold of 10%, pods with shard count between 90 and 110 will be considered
/// balanced.
文档测试
- 为关键函数和方法添加文档测试,确保示例代码可运行。
- 示例:golem-common/src/retries.rs中的测试函数。
错误处理
错误类型
- 使用
thiserrorcrate定义自定义错误类型。 - 示例:golem-worker-executor-base/src/error.rs
#[derive(Debug, thiserror::Error)]
pub enum GolemError {
#[error("Worker out of memory: {0}")]
WorkerOutOfMemory(#[from] WorkerOutOfMemory),
#[error("Unknown error: {0}")]
Unknown(String),
// 其他错误变体...
}
错误传播
- 使用
?操作符传播错误,避免深层嵌套的match语句。 - 为公共API返回
Result类型,确保错误可被调用者妥善处理。
并发编程
异步编程
Golem大量使用异步编程处理并发任务,主要依赖tokio运行时:
// [golem-worker-executor-base/src/worker.rs]
pub async fn start_if_needed(this: Arc<Worker<Ctx>>) -> Result<bool, GolemError> {
Self::start_if_needed_internal(this, 0).await
}
同步原语
- 使用
Arc和RwLock实现共享状态的线程安全访问。 - 示例:golem-worker-executor-base/src/worker.rs
queue: Arc<RwLock<VecDeque<TimestampedWorkerInvocation>>>,
pending_updates: Arc<RwLock<VecDeque<TimestampedUpdateDescription>>>,
invocation_results: Arc<RwLock<HashMap<IdempotencyKey, InvocationResult>>>,
配置管理
Golem使用figment crate进行配置管理,支持从TOML文件和环境变量加载配置:
// [golem-common/src/config.rs]
pub fn env_config_provider() -> Env {
Env::prefixed(ENV_VAR_PREFIX).split(ENV_VAR_NESTED_SEPARATOR)
}
配置示例:
[retry_config]
max_attempts = 5
min_delay = "100ms"
max_delay = "2s"
multiplier = 2.0
max_jitter_factor = 0.15
数据库交互
Golem支持PostgreSQL和SQLite数据库,使用sqlx crate进行数据库访问:
// [golem-service-base/src/db/mod.rs]
pub async fn create_postgres_pool(
config: &DbPostgresConfig,
) -> Result<Pool<Postgres>, Box<dyn Error>> {
// 数据库连接池创建逻辑...
}
测试规范
单元测试
每个模块应包含单元测试,测试代码放在#[cfg(test)]模块中:
// [golem-common/src/retries.rs]
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
pub fn get_delay_example_without_jitter() {
// 测试逻辑...
}
}
集成测试
集成测试放在每个crate的tests目录下,例如golem-component-service-base/tests/services_tests.rs。
测试组件
Golem提供专门的测试组件,位于test-components/目录,用于测试不同语言编写的Wasm组件。
贡献指南
提交规范
- 提交信息应简洁明了,描述代码变更的目的。
- 例如:"fix: 修复Worker状态更新逻辑"
代码审查
提交PR前应确保:
- 代码通过
cargo fmt格式化 - 代码通过
cargo clippy检查 - 所有测试通过
持续集成
Golem使用GitHub Actions进行持续集成,配置文件位于.github/workflows目录。PR提交后会自动运行测试和代码质量检查。
总结
本文档介绍了Golem社区的Rust代码规范和最佳实践,涵盖了命名规范、代码组织、错误处理、并发编程等方面。遵循这些规范有助于保持代码库的一致性和可维护性。
更多详细信息,请参考:
- 项目README:README.md
- 贡献指南:CONTRIBUTING.md
- 测试组件:test-components/
希望本文档能帮助新老开发者更好地参与Golem项目的开发,共同打造高质量的开源软件。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考




