mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-08-04 11:43:57 +08:00
refactor(provider): certify typed write ownership
Freeze prerequisite A as a component-level certification unit. Add the immutable v5 certification suite, split create/update row DTOs, preserve immutable creation time, map strict-create races to AppError::Conflict, make aggregate compensation insert-or-restore, and enforce reconcile preconditions through a single-lock transaction primitive. Old save_provider callsite classification remains exhaustively recorded in 4f78451405575158ff6562c7021c7f31f2860780; this checkpoint does not add or reclassify an omitted legacy callsite. It tightens the remaining reconciliation classifications there: default live import is [create]; OpenCode/OpenClaw/Hermes existing branches are [update] and absent branches are [create]; universal Claude/Codex/Gemini branches are [create/update] selected from an observed fingerprint. The sealed compensation helper remains the only [restore] path. The old reconcile_provider_record symbol is deleted. Remaining update_provider_settings_config callsites are classified as [update]: codex_history_migration updates an already-read Codex row; proxy token synchronization updates already-read Claude, Codex, Gemini, and GrokBuild rows. Each now uses ProviderKey plus ProviderRowUpdate, explicitly removes hydrated endpoint projections, preserves endpoint authority, and fails on a missing row instead of silently succeeding.
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use regex::Regex;
|
||||
use serde_json::json;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -298,6 +300,11 @@ fn scan_source(path: &str, source: &str) -> (Vec<Violation>, BTreeSet<String>) {
|
||||
)
|
||||
}
|
||||
};
|
||||
// 文件级 #![cfg(test)] 的文件(认证套件等)不进入任何构建的生产目标,
|
||||
// 不参与生产扫描;该属性的存在性由认证套件的注册元测试强制。
|
||||
if is_cfg_test(&syntax.attrs) {
|
||||
return (Vec::new(), BTreeSet::new());
|
||||
}
|
||||
let mut visitor = ArchitectureVisitor {
|
||||
path,
|
||||
violations: Vec::new(),
|
||||
@@ -345,6 +352,7 @@ fn provider_write_api_snapshot(source: &str) -> serde_json::Value {
|
||||
let syntax = syn::parse_file(source).expect("parse provider write authority");
|
||||
let type_names = [
|
||||
"ProviderKey",
|
||||
"ProviderRowCreate",
|
||||
"ProviderRowUpdate",
|
||||
"NewEndpoint",
|
||||
"NewProviderAggregate",
|
||||
|
||||
@@ -8,8 +8,9 @@ use crate::codex_config::{
|
||||
};
|
||||
use crate::codex_state_db::codex_state_db_paths;
|
||||
use crate::config::{atomic_write, copy_file, get_app_config_dir};
|
||||
use crate::database::{is_official_seed_id, Database};
|
||||
use crate::database::{is_official_seed_id, Database, ProviderKey, ProviderRowUpdate};
|
||||
use crate::error::AppError;
|
||||
use crate::services::provider::provider_to_mutation_input;
|
||||
use crate::settings::{
|
||||
CodexOfficialHistoryUnifyMigration, CodexProviderTemplateMigration,
|
||||
CodexThirdPartyHistoryProviderBucketMigration,
|
||||
@@ -663,7 +664,7 @@ fn migrate_codex_provider_templates_to_custom(
|
||||
let providers = db.get_all_providers("codex")?;
|
||||
let mut migrated_provider_ids = Vec::new();
|
||||
|
||||
for (_, provider) in providers {
|
||||
for (_, mut provider) in providers {
|
||||
if provider.category.as_deref() == Some("official")
|
||||
|| is_official_seed_id(&provider.id)
|
||||
|| provider.is_codex_oauth()
|
||||
@@ -694,8 +695,16 @@ fn migrate_codex_provider_templates_to_custom(
|
||||
};
|
||||
backup_provider_settings_config(&provider.id, &provider.settings_config, backup_root)?;
|
||||
obj.insert("config".to_string(), Value::String(migrated_config_text));
|
||||
db.update_provider_settings_config("codex", &provider.id, &settings)?;
|
||||
migrated_provider_ids.push(provider.id);
|
||||
let provider_id = provider.id.clone();
|
||||
provider.settings_config = settings;
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
let input = provider_to_mutation_input(provider);
|
||||
let key = ProviderKey::new("codex", &provider_id)?;
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
db.update_provider(&key, &row)?;
|
||||
migrated_provider_ids.push(provider_id);
|
||||
}
|
||||
|
||||
Ok(CodexProviderTemplateBucketMigrationOutcome {
|
||||
|
||||
@@ -8,6 +8,8 @@ pub mod pi_projections;
|
||||
pub mod profiles;
|
||||
pub mod prompts;
|
||||
pub mod provider_write;
|
||||
#[cfg(test)]
|
||||
mod provider_write_certification;
|
||||
pub mod providers;
|
||||
pub mod providers_seed;
|
||||
pub mod proxy;
|
||||
|
||||
@@ -6,6 +6,8 @@ use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::providers::{StoredProviderRow, PROVIDER_SELECT};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderKey {
|
||||
app_type: String,
|
||||
@@ -39,7 +41,6 @@ pub struct ProviderRowUpdate {
|
||||
settings_config: Value,
|
||||
website_url: Option<String>,
|
||||
category: Option<String>,
|
||||
created_at: Option<i64>,
|
||||
notes: Option<String>,
|
||||
meta: ProviderMeta,
|
||||
icon: Option<String>,
|
||||
@@ -60,7 +61,6 @@ impl ProviderRowUpdate {
|
||||
settings_config: input.settings_config.clone(),
|
||||
website_url: input.website_url.clone(),
|
||||
category: input.category.clone(),
|
||||
created_at: input.created_at,
|
||||
notes: input.notes.clone(),
|
||||
meta,
|
||||
icon: input.icon.clone(),
|
||||
@@ -69,6 +69,12 @@ impl ProviderRowUpdate {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProviderRowCreate {
|
||||
content: ProviderRowUpdate,
|
||||
created_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NewEndpoint {
|
||||
url: String,
|
||||
@@ -111,7 +117,7 @@ impl TryFrom<CustomEndpoint> for NewEndpoint {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NewProviderAggregate {
|
||||
key: ProviderKey,
|
||||
row: ProviderRowUpdate,
|
||||
row: ProviderRowCreate,
|
||||
sort_index: Option<usize>,
|
||||
in_failover_queue: bool,
|
||||
initial_endpoints: Vec<NewEndpoint>,
|
||||
@@ -142,7 +148,10 @@ impl NewProviderAggregate {
|
||||
initial_endpoints.push(endpoint.try_into()?);
|
||||
}
|
||||
let key = ProviderKey::new(app_type, input.id.clone())?;
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
let row = ProviderRowCreate {
|
||||
content: ProviderRowUpdate::from_input(&input)?,
|
||||
created_at: input.created_at,
|
||||
};
|
||||
Ok(Self {
|
||||
key,
|
||||
row,
|
||||
@@ -203,6 +212,7 @@ fn insert_row(
|
||||
tx: &Transaction<'_>,
|
||||
key: &ProviderKey,
|
||||
row: &ProviderRowUpdate,
|
||||
created_at: Option<i64>,
|
||||
sort_index: Option<usize>,
|
||||
is_current: bool,
|
||||
in_failover_queue: bool,
|
||||
@@ -223,7 +233,7 @@ fn insert_row(
|
||||
settings_config,
|
||||
row.website_url,
|
||||
row.category,
|
||||
row.created_at,
|
||||
created_at,
|
||||
sort_index,
|
||||
row.notes,
|
||||
row.icon,
|
||||
@@ -233,7 +243,21 @@ fn insert_row(
|
||||
in_failover_queue,
|
||||
],
|
||||
)
|
||||
.map_err(|error| AppError::Database(error.to_string()))?;
|
||||
.map_err(|error| match &error {
|
||||
rusqlite::Error::SqliteFailure(code, _)
|
||||
if matches!(
|
||||
code.extended_code,
|
||||
rusqlite::ffi::SQLITE_CONSTRAINT_PRIMARYKEY
|
||||
| rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
|
||||
) =>
|
||||
{
|
||||
AppError::Conflict(format!(
|
||||
"provider '{}/{}' already exists",
|
||||
key.app_type, key.id
|
||||
))
|
||||
}
|
||||
_ => AppError::Database(error.to_string()),
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -262,21 +286,38 @@ fn insert_endpoint(
|
||||
/// catalog compensation coordinator introduced with the ordered mutation
|
||||
/// pipeline is the only intended caller.
|
||||
#[allow(dead_code)]
|
||||
// The certification contract keeps immutable creation time separate from the
|
||||
// mutable row DTO and calls this sealed helper directly with the full snapshot.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn restore_provider_aggregate_on_tx(
|
||||
tx: &Transaction<'_>,
|
||||
key: &ProviderKey,
|
||||
row: &ProviderRowUpdate,
|
||||
created_at: Option<i64>,
|
||||
sort_index: Option<usize>,
|
||||
is_current: bool,
|
||||
in_failover_queue: bool,
|
||||
endpoints: &[NewEndpoint],
|
||||
) -> Result<(), AppError> {
|
||||
let updated = update_row(tx, key, row)?;
|
||||
if updated != 1 {
|
||||
return Err(AppError::NotFound(format!(
|
||||
"provider '{}/{}'",
|
||||
key.app_type, key.id
|
||||
)));
|
||||
if updated == 0 {
|
||||
insert_row(
|
||||
tx,
|
||||
key,
|
||||
row,
|
||||
created_at,
|
||||
sort_index,
|
||||
is_current,
|
||||
in_failover_queue,
|
||||
)?;
|
||||
} else {
|
||||
// Exact compensation is the only path allowed to restore immutable
|
||||
// creation time after a prior aggregate mutation.
|
||||
tx.execute(
|
||||
"UPDATE providers SET created_at = ?1 WHERE id = ?2 AND app_type = ?3",
|
||||
params![created_at, key.id, key.app_type],
|
||||
)
|
||||
.map_err(|error| AppError::Database(error.to_string()))?;
|
||||
}
|
||||
tx.execute(
|
||||
"DELETE FROM provider_endpoints WHERE provider_id = ?1 AND app_type = ?2",
|
||||
@@ -317,18 +358,16 @@ fn update_row(
|
||||
settings_config = ?2,
|
||||
website_url = ?3,
|
||||
category = ?4,
|
||||
created_at = ?5,
|
||||
notes = ?6,
|
||||
icon = ?7,
|
||||
icon_color = ?8,
|
||||
meta = ?9
|
||||
WHERE id = ?10 AND app_type = ?11",
|
||||
notes = ?5,
|
||||
icon = ?6,
|
||||
icon_color = ?7,
|
||||
meta = ?8
|
||||
WHERE id = ?9 AND app_type = ?10",
|
||||
params![
|
||||
row.name,
|
||||
settings_config,
|
||||
row.website_url,
|
||||
row.category,
|
||||
row.created_at,
|
||||
row.notes,
|
||||
row.icon,
|
||||
row.icon_color,
|
||||
@@ -349,7 +388,8 @@ impl Database {
|
||||
insert_row(
|
||||
&tx,
|
||||
&input.key,
|
||||
&input.row,
|
||||
&input.row.content,
|
||||
input.row.created_at,
|
||||
input.sort_index,
|
||||
false,
|
||||
input.in_failover_queue,
|
||||
@@ -380,6 +420,42 @@ impl Database {
|
||||
.map_err(|error| AppError::Database(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn update_provider_if_content_fingerprint(
|
||||
&self,
|
||||
key: &ProviderKey,
|
||||
expected_fingerprint: &str,
|
||||
row: &ProviderRowUpdate,
|
||||
) -> Result<(), AppError> {
|
||||
let mut conn = lock_conn!(self.conn);
|
||||
let tx = conn
|
||||
.transaction()
|
||||
.map_err(|error| AppError::Database(error.to_string()))?;
|
||||
let current = tx
|
||||
.query_row(
|
||||
&format!("{PROVIDER_SELECT} WHERE id = ?1 AND app_type = ?2"),
|
||||
params![key.id, key.app_type],
|
||||
StoredProviderRow::from_row,
|
||||
)
|
||||
.optional()
|
||||
.map_err(|error| AppError::Database(error.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFound(format!("provider '{}/{}'", key.app_type, key.id)))?
|
||||
.decode(key.app_type())?;
|
||||
if current.row_content_fingerprint() != expected_fingerprint {
|
||||
return Err(AppError::Conflict(format!(
|
||||
"provider '{}/{}' changed since it was read",
|
||||
key.app_type, key.id
|
||||
)));
|
||||
}
|
||||
if update_row(&tx, key, row)? != 1 {
|
||||
return Err(AppError::NotFound(format!(
|
||||
"provider '{}/{}'",
|
||||
key.app_type, key.id
|
||||
)));
|
||||
}
|
||||
tx.commit()
|
||||
.map_err(|error| AppError::Database(error.to_string()))
|
||||
}
|
||||
|
||||
pub fn rename_db_only_additive_provider(&self, input: RenameProvider) -> Result<(), AppError> {
|
||||
let mut conn = lock_conn!(self.conn);
|
||||
let tx = conn
|
||||
@@ -387,7 +463,7 @@ impl Database {
|
||||
.map_err(|error| AppError::Database(error.to_string()))?;
|
||||
let source_state = tx
|
||||
.query_row(
|
||||
"SELECT sort_index, is_current, in_failover_queue, category
|
||||
"SELECT sort_index, is_current, in_failover_queue, category, created_at
|
||||
FROM providers
|
||||
WHERE id = ?1 AND app_type = ?2",
|
||||
params![input.source.id, input.source.app_type],
|
||||
@@ -397,6 +473,7 @@ impl Database {
|
||||
row.get::<_, bool>(1)?,
|
||||
row.get::<_, bool>(2)?,
|
||||
row.get::<_, Option<String>>(3)?,
|
||||
row.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
@@ -418,6 +495,7 @@ impl Database {
|
||||
&tx,
|
||||
&target,
|
||||
&input.row,
|
||||
source_state.4,
|
||||
source_state.0,
|
||||
source_state.1,
|
||||
source_state.2,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@ use indexmap::IndexMap;
|
||||
use rusqlite::{params, OptionalExtension, Row};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
struct StoredProviderRow {
|
||||
pub(super) struct StoredProviderRow {
|
||||
id: String,
|
||||
name: String,
|
||||
settings_config: String,
|
||||
@@ -22,7 +22,7 @@ struct StoredProviderRow {
|
||||
}
|
||||
|
||||
impl StoredProviderRow {
|
||||
fn from_row(row: &Row<'_>) -> rusqlite::Result<Self> {
|
||||
pub(super) fn from_row(row: &Row<'_>) -> rusqlite::Result<Self> {
|
||||
Ok(Self {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
@@ -39,7 +39,7 @@ impl StoredProviderRow {
|
||||
})
|
||||
}
|
||||
|
||||
fn decode(self, app_type: &str) -> Result<Provider, AppError> {
|
||||
pub(super) fn decode(self, app_type: &str) -> Result<Provider, AppError> {
|
||||
let (settings_config, mut meta) =
|
||||
decode_provider_json(app_type, &self.id, &self.settings_config, &self.meta)?;
|
||||
// Child rows are the sole endpoint authority. Do not expose a stale
|
||||
@@ -96,7 +96,7 @@ pub(crate) fn validate_provider_storage_json(
|
||||
decode_provider_json(app_type, provider_id, settings_config, meta).map(|_| ())
|
||||
}
|
||||
|
||||
const PROVIDER_SELECT: &str =
|
||||
pub(super) const PROVIDER_SELECT: &str =
|
||||
"SELECT id, name, settings_config, website_url, category, created_at, sort_index,
|
||||
notes, icon, icon_color, meta, in_failover_queue
|
||||
FROM providers";
|
||||
@@ -306,27 +306,6 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_provider_settings_config(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
settings_config: &serde_json::Value,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE providers SET settings_config = ?1 WHERE id = ?2 AND app_type = ?3",
|
||||
params![
|
||||
serde_json::to_string(settings_config).map_err(|e| AppError::Database(format!(
|
||||
"Failed to serialize settings_config: {e}"
|
||||
)))?,
|
||||
provider_id,
|
||||
app_type
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_omo_provider_current(
|
||||
&self,
|
||||
app_type: &str,
|
||||
@@ -1034,6 +1013,7 @@ mod aggregate_tests {
|
||||
&tx,
|
||||
&key,
|
||||
&row,
|
||||
snapshot.provider.created_at,
|
||||
snapshot.provider.sort_index,
|
||||
false,
|
||||
snapshot.provider.in_failover_queue,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! 数据库模块测试
|
||||
//!
|
||||
//! 包含 Schema 迁移和基本功能的测试。
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Deep link module tests
|
||||
|
||||
use super::mcp::parse_mcp_apps;
|
||||
|
||||
@@ -11,6 +11,11 @@ pub enum AppError {
|
||||
InvalidInput(String),
|
||||
#[error("未找到: {0}")]
|
||||
NotFound(String),
|
||||
/// 结构化冲突:并发前置期望失败(如 reconcile 的 ExpectAbsent 撞上竞争
|
||||
/// 创建、ExpectPresent 的指纹过期)。调用方据此重读重试或上浮,不得解析
|
||||
/// Database(String) 文本。由前置工程 A 认证契约引入(T9)。
|
||||
#[error("并发冲突: {0}")]
|
||||
Conflict(String),
|
||||
#[error("IO 错误: {path}: {source}")]
|
||||
Io {
|
||||
path: String,
|
||||
|
||||
@@ -145,6 +145,72 @@ impl Provider {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn row_content_fingerprint(&self) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn hash_canonical(value: &serde_json::Value, hasher: &mut Sha256) {
|
||||
match value {
|
||||
serde_json::Value::Null => hasher.update(b"n"),
|
||||
serde_json::Value::Bool(value) => {
|
||||
hasher.update(b"b");
|
||||
hasher.update([*value as u8]);
|
||||
}
|
||||
serde_json::Value::Number(value) => {
|
||||
let text = value.to_string();
|
||||
hasher.update(b"#");
|
||||
hasher.update((text.len() as u64).to_le_bytes());
|
||||
hasher.update(text.as_bytes());
|
||||
}
|
||||
serde_json::Value::String(value) => {
|
||||
hasher.update(b"s");
|
||||
hasher.update((value.len() as u64).to_le_bytes());
|
||||
hasher.update(value.as_bytes());
|
||||
}
|
||||
serde_json::Value::Array(items) => {
|
||||
hasher.update(b"[");
|
||||
hasher.update((items.len() as u64).to_le_bytes());
|
||||
for item in items {
|
||||
hash_canonical(item, hasher);
|
||||
}
|
||||
hasher.update(b"]");
|
||||
}
|
||||
serde_json::Value::Object(map) => {
|
||||
hasher.update(b"{");
|
||||
hasher.update((map.len() as u64).to_le_bytes());
|
||||
let mut keys: Vec<&String> = map.keys().collect();
|
||||
keys.sort();
|
||||
for key in keys {
|
||||
hasher.update((key.len() as u64).to_le_bytes());
|
||||
hasher.update(key.as_bytes());
|
||||
hash_canonical(&map[key.as_str()], hasher);
|
||||
}
|
||||
hasher.update(b"}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut meta = serde_json::to_value(&self.meta).unwrap_or(serde_json::Value::Null);
|
||||
if let serde_json::Value::Object(map) = &mut meta {
|
||||
map.remove("custom_endpoints");
|
||||
map.remove("customEndpoints");
|
||||
}
|
||||
let mut hasher = Sha256::new();
|
||||
for part in [
|
||||
serde_json::Value::String(self.name.clone()),
|
||||
self.settings_config.clone(),
|
||||
serde_json::to_value(&self.website_url).unwrap_or(serde_json::Value::Null),
|
||||
serde_json::to_value(&self.category).unwrap_or(serde_json::Value::Null),
|
||||
serde_json::to_value(&self.notes).unwrap_or(serde_json::Value::Null),
|
||||
serde_json::to_value(&self.icon).unwrap_or(serde_json::Value::Null),
|
||||
serde_json::to_value(&self.icon_color).unwrap_or(serde_json::Value::Null),
|
||||
meta,
|
||||
] {
|
||||
hash_canonical(&part, &mut hasher);
|
||||
hasher.update([0u8]);
|
||||
}
|
||||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
pub fn is_codex_oauth(&self) -> bool {
|
||||
self.provider_type() == Some("codex_oauth")
|
||||
}
|
||||
|
||||
@@ -20,7 +20,8 @@ use super::gemini_auth::{
|
||||
detect_gemini_auth_type, ensure_google_oauth_security_flag, GeminiAuthType,
|
||||
};
|
||||
use super::{
|
||||
normalize_claude_models_in_value, provider_to_mutation_input, reconcile_provider_record,
|
||||
normalize_claude_models_in_value, provider_row_fingerprint, provider_to_mutation_input,
|
||||
reconcile_provider_record_with_precondition, ReconcilePrecondition,
|
||||
};
|
||||
|
||||
/// ChatGPT Codex catalogs gpt-5.6 at a 372K context window with a ~353K
|
||||
@@ -1566,10 +1567,11 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
reconcile_provider_record(
|
||||
reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
app_type.as_str(),
|
||||
provider_to_mutation_input(provider.clone()),
|
||||
ReconcilePrecondition::ExpectAbsent,
|
||||
)?;
|
||||
state
|
||||
.db
|
||||
@@ -1744,13 +1746,18 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
let display_name = config.name.clone().unwrap_or_else(|| existing.name.clone());
|
||||
if existing.settings_config != settings_config || existing.name != display_name
|
||||
{
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut provider = existing;
|
||||
provider.name = display_name;
|
||||
provider.settings_config = settings_config;
|
||||
if let Err(e) = reconcile_provider_record(
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"opencode",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint },
|
||||
) {
|
||||
log::warn!(
|
||||
"Failed to update OpenCode provider '{id}' from live config: {e}"
|
||||
@@ -1778,9 +1785,12 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) =
|
||||
reconcile_provider_record(&state.db, "opencode", provider_to_mutation_input(provider))
|
||||
{
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"opencode",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectAbsent,
|
||||
) {
|
||||
log::warn!("Failed to import OpenCode provider '{id}': {e}");
|
||||
continue;
|
||||
}
|
||||
@@ -1834,12 +1844,17 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
Ok(Some(existing)) => {
|
||||
let existing = existing.provider;
|
||||
if existing.settings_config != settings_config {
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut provider = existing;
|
||||
provider.settings_config = settings_config;
|
||||
if let Err(e) = reconcile_provider_record(
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"openclaw",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint },
|
||||
) {
|
||||
log::warn!(
|
||||
"Failed to update OpenClaw provider '{id}' from live config: {e}"
|
||||
@@ -1873,9 +1888,12 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) =
|
||||
reconcile_provider_record(&state.db, "openclaw", provider_to_mutation_input(provider))
|
||||
{
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"openclaw",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectAbsent,
|
||||
) {
|
||||
log::warn!("Failed to import OpenClaw provider '{id}': {e}");
|
||||
continue;
|
||||
}
|
||||
@@ -1916,12 +1934,17 @@ pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppE
|
||||
Ok(Some(existing)) => {
|
||||
let existing = existing.provider;
|
||||
if existing.settings_config != config {
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut provider = existing;
|
||||
provider.settings_config = config;
|
||||
if let Err(e) = reconcile_provider_record(
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"hermes",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint },
|
||||
) {
|
||||
log::warn!(
|
||||
"Failed to update Hermes provider '{name}' from live config: {e}"
|
||||
@@ -1948,9 +1971,12 @@ pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppE
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) =
|
||||
reconcile_provider_record(&state.db, "hermes", provider_to_mutation_input(provider))
|
||||
{
|
||||
if let Err(e) = reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"hermes",
|
||||
provider_to_mutation_input(provider),
|
||||
ReconcilePrecondition::ExpectAbsent,
|
||||
) {
|
||||
log::warn!("Failed to import Hermes provider '{name}': {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -151,19 +151,46 @@ fn update_provider_record(
|
||||
state.db.update_provider(&key, &row)
|
||||
}
|
||||
|
||||
/// Reconciliation paths must state their intent explicitly: inspect first,
|
||||
/// then perform either strict create or strict one-row update.
|
||||
pub(crate) fn reconcile_provider_record(
|
||||
/// Reconcile 的显式前置期望(前置工程 A 认证契约 T9)。
|
||||
/// check-then-branch 的 TOCTOU 由调用方在观察时声明期望、由本层强制。
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum ReconcilePrecondition {
|
||||
/// 调用方观察到目标不存在;若已被竞争者创建,必须返回
|
||||
/// [`AppError::Conflict`],绝不退化为覆盖更新。
|
||||
ExpectAbsent,
|
||||
/// 调用方观察到目标存在且内容指纹为 `fingerprint`;指纹过期必须返回
|
||||
/// [`AppError::Conflict`],由调用方重读重试。
|
||||
ExpectPresent { fingerprint: String },
|
||||
}
|
||||
|
||||
/// 行内容指纹:并发前置期望的版本标记(纯函数,不含状态列与 endpoint)。
|
||||
///
|
||||
/// 决定性要求:仓库启用了 serde_json `preserve_order`,且 `ProviderMeta`
|
||||
/// 内含 HashMap——直接序列化的键序随机,会产生伪 Conflict。因此必须走
|
||||
/// 递归排序的规范化哈希;`meta.custom_endpoints` 属 endpoint authority,
|
||||
/// 不参与内容指纹(不同读 API 对其填充不一致)。
|
||||
pub(crate) fn provider_row_fingerprint(provider: &crate::provider::Provider) -> String {
|
||||
provider.row_content_fingerprint()
|
||||
}
|
||||
|
||||
/// Reconcile paths must carry the caller's observed state into the write.
|
||||
/// Creation is strict, while updates compare the observed row fingerprint and
|
||||
/// write under one database lock and transaction.
|
||||
pub(crate) fn reconcile_provider_record_with_precondition(
|
||||
db: &crate::database::Database,
|
||||
app_type: &str,
|
||||
input: ProviderMutationInput,
|
||||
precondition: ReconcilePrecondition,
|
||||
) -> Result<(), AppError> {
|
||||
let key = ProviderKey::new(app_type, input.id.clone())?;
|
||||
if db.get_provider_aggregate(app_type, key.id())?.is_some() {
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
db.update_provider(&key, &row)
|
||||
} else {
|
||||
db.create_provider(NewProviderAggregate::from_input(app_type, input)?)
|
||||
match precondition {
|
||||
ReconcilePrecondition::ExpectAbsent => {
|
||||
db.create_provider(NewProviderAggregate::from_input(app_type, input)?)
|
||||
}
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint } => {
|
||||
let key = ProviderKey::new(app_type, input.id.clone())?;
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
db.update_provider_if_content_fingerprint(&key, &fingerprint, &row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5149,15 +5176,22 @@ impl ProviderService {
|
||||
// 同步到 Claude
|
||||
if let Some(mut claude_provider) = provider.to_claude_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&claude_provider.id, "claude")? {
|
||||
let precondition = if let Some(existing) =
|
||||
state.db.get_provider_by_id(&claude_provider.id, "claude")?
|
||||
{
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &claude_provider.settings_config);
|
||||
claude_provider.settings_config = merged;
|
||||
}
|
||||
reconcile_provider_record(
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint }
|
||||
} else {
|
||||
ReconcilePrecondition::ExpectAbsent
|
||||
};
|
||||
reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"claude",
|
||||
provider_to_mutation_input(claude_provider),
|
||||
precondition,
|
||||
)?;
|
||||
} else {
|
||||
// 如果禁用了 Claude,删除对应的子供应商
|
||||
@@ -5168,15 +5202,21 @@ impl ProviderService {
|
||||
// 同步到 Codex
|
||||
if let Some(mut codex_provider) = provider.to_codex_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&codex_provider.id, "codex")? {
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &codex_provider.settings_config);
|
||||
codex_provider.settings_config = merged;
|
||||
}
|
||||
reconcile_provider_record(
|
||||
let precondition =
|
||||
if let Some(existing) = state.db.get_provider_by_id(&codex_provider.id, "codex")? {
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &codex_provider.settings_config);
|
||||
codex_provider.settings_config = merged;
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint }
|
||||
} else {
|
||||
ReconcilePrecondition::ExpectAbsent
|
||||
};
|
||||
reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"codex",
|
||||
provider_to_mutation_input(codex_provider),
|
||||
precondition,
|
||||
)?;
|
||||
} else {
|
||||
let codex_id = format!("universal-codex-{id}");
|
||||
@@ -5186,15 +5226,22 @@ impl ProviderService {
|
||||
// 同步到 Gemini
|
||||
if let Some(mut gemini_provider) = provider.to_gemini_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&gemini_provider.id, "gemini")? {
|
||||
let precondition = if let Some(existing) =
|
||||
state.db.get_provider_by_id(&gemini_provider.id, "gemini")?
|
||||
{
|
||||
let fingerprint = provider_row_fingerprint(&existing);
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &gemini_provider.settings_config);
|
||||
gemini_provider.settings_config = merged;
|
||||
}
|
||||
reconcile_provider_record(
|
||||
ReconcilePrecondition::ExpectPresent { fingerprint }
|
||||
} else {
|
||||
ReconcilePrecondition::ExpectAbsent
|
||||
};
|
||||
reconcile_provider_record_with_precondition(
|
||||
&state.db,
|
||||
"gemini",
|
||||
provider_to_mutation_input(gemini_provider),
|
||||
precondition,
|
||||
)?;
|
||||
} else {
|
||||
let gemini_id = format!("universal-gemini-{id}");
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::config::{get_claude_settings_path, read_json_file, write_json_file};
|
||||
use crate::database::Database;
|
||||
use crate::database::{Database, ProviderKey, ProviderRowUpdate};
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::server::ProxyServer;
|
||||
use crate::proxy::switch_lock::SwitchLockManager;
|
||||
use crate::proxy::types::*;
|
||||
use crate::services::provider::{
|
||||
build_effective_settings_with_common_config, write_live_with_common_config,
|
||||
build_effective_settings_with_common_config, provider_to_mutation_input,
|
||||
write_live_with_common_config,
|
||||
};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::str::FromStr;
|
||||
@@ -1055,11 +1056,16 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"claude",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
let input = provider_to_mutation_input(provider);
|
||||
let result =
|
||||
ProviderKey::new("claude", &provider_id).and_then(|key| {
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
self.db.update_provider(&key, &row)
|
||||
});
|
||||
if let Err(e) = result {
|
||||
log::warn!("同步 Claude Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
@@ -1116,11 +1122,15 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"codex",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
let input = provider_to_mutation_input(provider);
|
||||
let result = ProviderKey::new("codex", &provider_id).and_then(|key| {
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
self.db.update_provider(&key, &row)
|
||||
});
|
||||
if let Err(e) = result {
|
||||
log::warn!("同步 Codex Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!("已同步 Codex Token 到数据库 (provider: {provider_id})");
|
||||
@@ -1168,11 +1178,15 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"gemini",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
let input = provider_to_mutation_input(provider);
|
||||
let result = ProviderKey::new("gemini", &provider_id).and_then(|key| {
|
||||
let row = ProviderRowUpdate::from_input(&input)?;
|
||||
self.db.update_provider(&key, &row)
|
||||
});
|
||||
if let Err(e) = result {
|
||||
log::warn!("同步 Gemini Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
@@ -1211,15 +1225,20 @@ impl ProxyService {
|
||||
format!("更新 Grok Build API Key 失败: {e}")
|
||||
})?;
|
||||
provider.settings_config["config"] = json!(updated);
|
||||
self.db
|
||||
.update_provider_settings_config(
|
||||
"grokbuild",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
)
|
||||
.map_err(|e| {
|
||||
if let Some(meta) = provider.meta.as_mut() {
|
||||
meta.custom_endpoints.clear();
|
||||
}
|
||||
let input = provider_to_mutation_input(provider);
|
||||
let key = ProviderKey::new("grokbuild", &provider_id).map_err(
|
||||
|e| format!("同步 Grok Build Token 到数据库失败: {e}"),
|
||||
)?;
|
||||
let row =
|
||||
ProviderRowUpdate::from_input(&input).map_err(|e| {
|
||||
format!("同步 Grok Build Token 到数据库失败: {e}")
|
||||
})?;
|
||||
self.db.update_provider(&key, &row).map_err(|e| {
|
||||
format!("同步 Grok Build Token 到数据库失败: {e}")
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user