Skip to main content

verhub_sdk/
lib.rs

1//! Verhub Rust SDK。
2//!
3//! 接口面与 Python / TypeScript / 纯 JS 版一一对应,方法名按 Rust 习惯写成
4//! snake_case。契约以仓库根目录的 `verhub.openapi.yaml` 为准。
5//!
6//! ```no_run
7//! use verhub_sdk::{models::CheckUpdateInput, VerhubClient};
8//!
9//! # async fn demo() -> verhub_sdk::Result<()> {
10//! let client = VerhubClient::builder("https://verhub.example.com/api/v1")
11//!     .project_key("verhub")
12//!     .build()?;
13//!
14//! let result = client
15//!     .public()
16//!     .check_update(&CheckUpdateInput {
17//!         current_version: Some("1.1.0".into()),
18//!         ..Default::default()
19//!     })
20//!     .await?;
21//!
22//! if result.should_update {
23//!     println!("{}", result.latest_version.version);
24//! }
25//! # Ok(())
26//! # }
27//! ```
28
29#![forbid(unsafe_code)]
30#![warn(missing_debug_implementations)]
31
32mod admin_api;
33mod analytics;
34mod error;
35mod http;
36mod public_api;
37
38pub mod models;
39
40pub use admin_api::AdminApi;
41pub use analytics::{
42    analytics_namespace, fnv1a32_hex, origin_of, AnalyticsOptions, AnalyticsPersistence,
43    EventBatch, EventQueue, QueuedEvent,
44};
45pub use error::{Error, Result};
46pub use http::{
47    detect_platform, detect_platform_version, VerhubClientBuilder, CLIENT_TIME_HEADER,
48    PLATFORM_HEADER, PLATFORM_VERSION_HEADER,
49};
50// 这两个枚举出现在几乎每个调用点上,提到 crate 根省得调用方到处写 models::。
51pub use models::{LogLevel, Platform, TermsDocumentSlug};
52pub use public_api::PublicApi;
53
54use std::sync::Arc;
55
56use reqwest::Method;
57
58use crate::http::Inner;
59use crate::models::HealthResponse;
60
61/// SDK 版本号,跟随主仓库版本。
62pub const VERHUB_SDK_VERSION: &str = "0.2.10";
63
64/// Verhub SDK 入口。
65///
66/// 两个命名空间共用一份连接与凭据:[`VerhubClient::public`] 不需要凭据,
67/// [`VerhubClient::admin`] 需要管理员 JWT 或 API Key。
68///
69/// 克隆开销等同于克隆一个 [`Arc`],跨任务共享直接 clone 即可。
70#[derive(Debug, Clone)]
71pub struct VerhubClient {
72    inner: Arc<Inner>,
73}
74
75impl VerhubClient {
76    /// 用默认配置建客户端(不绑定项目)。
77    ///
78    /// `base_url` 须包含 `/api/v1` 前缀,也就是能直接打开 `/health` 的那个地址。
79    /// 要绑定项目、设置凭据/平台/超时,用 [`VerhubClient::builder`]。
80    pub fn new(base_url: impl Into<String>) -> Result<Self> {
81        Self::builder(base_url).build()
82    }
83
84    /// 需要绑定项目或设置凭据、平台、超时时用构建器。
85    pub fn builder(base_url: impl Into<String>) -> VerhubClientBuilder {
86        VerhubClientBuilder::new(base_url)
87    }
88    pub(crate) fn from_inner(inner: Inner) -> Self {
89        Self {
90            inner: Arc::new(inner),
91        }
92    }
93
94    /// 公开接口,不需要凭据。
95    pub fn public(&self) -> PublicApi<'_> {
96        PublicApi { inner: &self.inner }
97    }
98
99    /// 管理接口,需要管理员 JWT 或 API Key。
100    pub fn admin(&self) -> AdminApi<'_> {
101        AdminApi { inner: &self.inner }
102    }
103
104    /// 当前绑定的项目标识。
105    pub fn project_key(&self) -> Option<String> {
106        self.inner.project_key()
107    }
108
109    /// 更换绑定的项目。所有克隆出去的实例都会看到新值。
110    pub fn set_project_key(&self, project_key: impl Into<String>) {
111        self.inner.set_project_key(project_key);
112    }
113
114    /// 设置凭据。所有克隆出去的实例都会看到新值。
115    pub fn set_token(&self, token: impl Into<String>) {
116        self.inner.set_token(token);
117    }
118
119    /// 清除当前凭据,之后调用 admin 接口会直接返回 [`Error::MissingToken`]。
120    pub fn clear_token(&self) {
121        self.inner.clear_token();
122    }
123
124    /// 更新平台声明。传 `None` 则不再声明平台。
125    pub fn set_platform(&self, platform: Option<Platform>) {
126        self.inner.set_platform(platform);
127    }
128
129    /// 更新系统版本明细。传 `None` 则不再声明。
130    pub fn set_platform_version(&self, version: Option<String>) {
131        self.inner.set_platform_version(version);
132    }
133
134    /// 查服务健康状态。
135    pub async fn health(&self) -> Result<HealthResponse> {
136        self.inner
137            .request::<_, ()>(Method::GET, "/health", &[], None, false)
138            .await
139    }
140}
141
142impl VerhubClientBuilder {
143    /// 建出客户端。`base_url` 不是合法 http(s) 地址时返回
144    /// [`Error::InvalidBaseUrl`]。
145    pub fn build(self) -> Result<VerhubClient> {
146        Ok(VerhubClient::from_inner(self.build_inner()?))
147    }
148}