Golem社区代码规范:Rust风格指南与最佳实践

Golem社区代码规范:Rust风格指南与最佳实践

【免费下载链接】golem Golem: Transparent durable execution for any programming language 【免费下载链接】golem 项目地址: https://gitcode.com/GitHub_Trending/golem2/golem

项目概述

Golem是一个支持多语言透明持久化执行的开源项目,采用Rust语言构建核心组件。本文档旨在提供Golem社区的Rust代码风格规范与最佳实践,帮助开发者编写高质量、一致的代码。

项目logo

基础规范

代码格式化

Golem项目使用rustfmt进行代码格式化,配置文件为项目根目录下的.rustfmt.toml

reorder_imports = true
newline_style = "Unix"

该配置强制按字母顺序重新排序导入项,并使用Unix风格的换行符(LF)。开发者应确保在提交代码前运行cargo fmt

代码检查

项目使用Clippy进行代码质量检查,配置文件为clippy.toml。建议在开发过程中运行cargo clippy以捕获常见的Rust代码问题。

命名规范

类型命名

函数命名

常量命名

模块命名

代码组织

项目结构

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执行的核心逻辑。

文档规范

注释风格

/// 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.

文档测试

错误处理

错误类型

#[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
}

同步原语

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代码规范和最佳实践,涵盖了命名规范、代码组织、错误处理、并发编程等方面。遵循这些规范有助于保持代码库的一致性和可维护性。

更多详细信息,请参考:

希望本文档能帮助新老开发者更好地参与Golem项目的开发,共同打造高质量的开源软件。

【免费下载链接】golem Golem: Transparent durable execution for any programming language 【免费下载链接】golem 项目地址: https://gitcode.com/GitHub_Trending/golem2/golem

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值