Base: codex-main originale (prima del fork aKode)
This commit is contained in:
78
codex-rs/connectors/src/accessible.rs
Normal file
78
codex-rs/connectors/src/accessible.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::AppInfo;
|
||||
use crate::metadata::connector_install_url;
|
||||
use crate::normalize_connector_value;
|
||||
|
||||
pub struct AccessibleConnectorTool {
|
||||
pub connector_id: String,
|
||||
pub connector_name: Option<String>,
|
||||
pub connector_description: Option<String>,
|
||||
pub plugin_display_names: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn collect_accessible_connectors<I>(tools: I) -> Vec<AppInfo>
|
||||
where
|
||||
I: IntoIterator<Item = AccessibleConnectorTool>,
|
||||
{
|
||||
let mut connectors: HashMap<String, (AppInfo, BTreeSet<String>)> = HashMap::new();
|
||||
for tool in tools {
|
||||
let connector_id = tool.connector_id;
|
||||
let connector_name = normalize_connector_value(tool.connector_name.as_deref())
|
||||
.unwrap_or_else(|| connector_id.clone());
|
||||
let connector_description =
|
||||
normalize_connector_value(tool.connector_description.as_deref());
|
||||
if let Some((existing, existing_plugin_display_names)) = connectors.get_mut(&connector_id) {
|
||||
if existing.name == connector_id && connector_name != connector_id {
|
||||
existing.name = connector_name;
|
||||
}
|
||||
if existing.description.is_none() && connector_description.is_some() {
|
||||
existing.description = connector_description;
|
||||
}
|
||||
existing_plugin_display_names.extend(tool.plugin_display_names);
|
||||
} else {
|
||||
connectors.insert(
|
||||
connector_id.clone(),
|
||||
(
|
||||
AppInfo {
|
||||
id: connector_id.clone(),
|
||||
name: connector_name,
|
||||
description: connector_description,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: None,
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
install_url: None,
|
||||
is_accessible: true,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
},
|
||||
tool.plugin_display_names
|
||||
.into_iter()
|
||||
.collect::<BTreeSet<String>>(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut accessible: Vec<AppInfo> = connectors
|
||||
.into_values()
|
||||
.map(|(mut connector, plugin_display_names)| {
|
||||
connector.plugin_display_names = plugin_display_names.into_iter().collect();
|
||||
connector.install_url = Some(connector_install_url(&connector.name, &connector.id));
|
||||
connector
|
||||
})
|
||||
.collect();
|
||||
accessible.sort_by(|left, right| {
|
||||
right
|
||||
.is_accessible
|
||||
.cmp(&left.is_accessible)
|
||||
.then_with(|| left.name.cmp(&right.name))
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
accessible
|
||||
}
|
||||
111
codex-rs/connectors/src/app_info.rs
Normal file
111
codex-rs/connectors/src/app_info.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
//! Connector-domain app metadata used by directory discovery, caching, and tool selection.
|
||||
//!
|
||||
//! The Serde implementations decode connector-directory response metadata and persist normalized
|
||||
//! app information in the connector-directory disk cache. They do not define the app-server wire
|
||||
//! format; `codex-app-server-protocol` owns separate API types for that boundary.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Branding supplied by the connector directory for an app.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppBranding {
|
||||
pub category: Option<String>,
|
||||
pub developer: Option<String>,
|
||||
pub website: Option<String>,
|
||||
pub privacy_policy: Option<String>,
|
||||
pub terms_of_service: Option<String>,
|
||||
pub is_discoverable_app: bool,
|
||||
}
|
||||
|
||||
/// Review state supplied by the connector directory for an app.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppReview {
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
/// Screenshot metadata supplied by the connector directory for an app.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppScreenshot {
|
||||
pub url: Option<String>,
|
||||
#[serde(alias = "file_id")]
|
||||
pub file_id: Option<String>,
|
||||
#[serde(alias = "user_prompt")]
|
||||
pub user_prompt: String,
|
||||
}
|
||||
|
||||
/// Extended metadata supplied by the connector directory for an app.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppMetadata {
|
||||
pub review: Option<AppReview>,
|
||||
pub categories: Option<Vec<String>>,
|
||||
pub sub_categories: Option<Vec<String>>,
|
||||
pub seo_description: Option<String>,
|
||||
pub screenshots: Option<Vec<AppScreenshot>>,
|
||||
pub developer: Option<String>,
|
||||
pub version: Option<String>,
|
||||
pub version_id: Option<String>,
|
||||
pub version_notes: Option<String>,
|
||||
pub first_party_requires_install: Option<bool>,
|
||||
pub show_in_composer_when_unlinked: Option<bool>,
|
||||
}
|
||||
|
||||
/// Connector metadata used by connector discovery, caching, and tool selection.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub logo_url: Option<String>,
|
||||
pub logo_url_dark: Option<String>,
|
||||
pub icon_assets: Option<HashMap<String, String>>,
|
||||
pub icon_dark_assets: Option<HashMap<String, String>>,
|
||||
pub distribution_channel: Option<String>,
|
||||
pub branding: Option<AppBranding>,
|
||||
pub app_metadata: Option<AppMetadata>,
|
||||
pub labels: Option<HashMap<String, String>>,
|
||||
pub install_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub is_accessible: bool,
|
||||
#[serde(default = "default_enabled")]
|
||||
pub is_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub plugin_display_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl AppInfo {
|
||||
pub fn category(&self) -> Option<String> {
|
||||
self.branding
|
||||
.as_ref()
|
||||
.and_then(|branding| non_empty_category(branding.category.as_deref()))
|
||||
.or_else(|| {
|
||||
self.app_metadata
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.categories.as_ref())
|
||||
.and_then(|categories| {
|
||||
categories
|
||||
.iter()
|
||||
.find_map(|category| non_empty_category(Some(category.as_str())))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn non_empty_category(category: Option<&str>) -> Option<String> {
|
||||
let category = category?.trim();
|
||||
if category.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(category.to_string())
|
||||
}
|
||||
}
|
||||
312
codex-rs/connectors/src/app_tool_policy.rs
Normal file
312
codex-rs/connectors/src/app_tool_policy.rs
Normal file
@@ -0,0 +1,312 @@
|
||||
use codex_config::AppsRequirementsToml;
|
||||
use codex_config::ConfigLayerMetadata;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::TomlValue;
|
||||
use codex_config::merge_toml_values;
|
||||
use codex_config::types::AppToolApproval;
|
||||
use codex_config::types::AppsConfigToml;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::AppInfo;
|
||||
|
||||
/// The effective enablement and approval policy for one app tool.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AppToolPolicy {
|
||||
pub enabled: bool,
|
||||
pub approval: AppToolApproval,
|
||||
}
|
||||
|
||||
impl Default for AppToolPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
approval: AppToolApproval::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// App and account metadata used to evaluate one tool.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AppToolPolicyInput<'a> {
|
||||
pub connector_id: Option<&'a str>,
|
||||
pub link_id: Option<&'a str>,
|
||||
pub tool_name: &'a str,
|
||||
pub tool_title: Option<&'a str>,
|
||||
pub destructive_hint: Option<bool>,
|
||||
pub open_world_hint: Option<bool>,
|
||||
}
|
||||
|
||||
/// Resolves app tool policy against one immutable config snapshot.
|
||||
///
|
||||
/// Callers should construct one evaluator and reuse it for every tool in the
|
||||
/// same exposure build so config layers are merged and decoded only once.
|
||||
pub struct AppToolPolicyEvaluator<'a> {
|
||||
apps_config: Option<AppsConfigToml>,
|
||||
requirements_apps_config: Option<&'a AppsRequirementsToml>,
|
||||
}
|
||||
|
||||
impl<'a> AppToolPolicyEvaluator<'a> {
|
||||
pub fn new(config_layer_stack: &'a ConfigLayerStack) -> Self {
|
||||
let apps_config = apps_config_from_layer_stack(config_layer_stack);
|
||||
let requirements_apps_config = config_layer_stack.requirements_toml().apps.as_ref();
|
||||
Self::from_parts(apps_config, requirements_apps_config)
|
||||
}
|
||||
|
||||
pub fn policy(&self, input: AppToolPolicyInput<'_>) -> AppToolPolicy {
|
||||
let managed_approval = managed_app_tool_approval(
|
||||
self.requirements_apps_config,
|
||||
input.connector_id,
|
||||
input.tool_name,
|
||||
);
|
||||
app_tool_policy_from_apps_config(self.apps_config.as_ref(), input, managed_approval)
|
||||
}
|
||||
|
||||
/// Returns the effective local and managed enablement for one connector.
|
||||
pub fn app_enabled(&self, connector_id: &str) -> bool {
|
||||
self.apps_config
|
||||
.as_ref()
|
||||
.map(|apps_config| app_is_enabled(apps_config, Some(connector_id)))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Applies app policy without overriding source state for unconfigured apps.
|
||||
pub fn apply_app_enabled_state(&self, mut apps: Vec<AppInfo>) -> Vec<AppInfo> {
|
||||
let Some(apps_config) = self.apps_config.as_ref() else {
|
||||
return apps;
|
||||
};
|
||||
|
||||
for app in &mut apps {
|
||||
if apps_config.default.is_some() || apps_config.apps.contains_key(app.id.as_str()) {
|
||||
app.is_enabled = self.app_enabled(app.id.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
apps
|
||||
}
|
||||
|
||||
fn from_parts(
|
||||
apps_config: Option<AppsConfigToml>,
|
||||
requirements_apps_config: Option<&'a AppsRequirementsToml>,
|
||||
) -> Self {
|
||||
Self {
|
||||
apps_config: effective_apps_config(apps_config, requirements_apps_config),
|
||||
requirements_apps_config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the merged, unmanaged Apps configuration from a config-layer stack.
|
||||
///
|
||||
/// App settings from plugins enabled by configuration apply connector-wide.
|
||||
/// Tables use the standard config merge, with earlier plugin names taking
|
||||
/// precedence and explicit top-level app fields applied last.
|
||||
pub fn apps_config_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
) -> Option<AppsConfigToml> {
|
||||
let overlays = apps_config_overlays(&config_layer_stack.effective_config());
|
||||
if overlays.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut apps = TomlValue::Table(Default::default());
|
||||
for (_, overlay) in overlays {
|
||||
// Merge before decoding so omitted fields do not acquire serde defaults.
|
||||
merge_toml_values(&mut apps, &overlay);
|
||||
}
|
||||
AppsConfigToml::deserialize(apps).ok()
|
||||
}
|
||||
|
||||
/// Projects field origins onto the effective `apps.*` paths using Apps precedence.
|
||||
pub fn apps_config_origins_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
) -> HashMap<String, ConfigLayerMetadata> {
|
||||
let source_origins = config_layer_stack.origins();
|
||||
let mut origins = HashMap::new();
|
||||
for (prefix, _) in apps_config_overlays(&config_layer_stack.effective_config()) {
|
||||
let prefix = format!("{prefix}.");
|
||||
for (path, origin) in &source_origins {
|
||||
if let Some(field) = path.strip_prefix(&prefix)
|
||||
&& (prefix == "apps." || !field.starts_with("_default."))
|
||||
{
|
||||
origins.insert(format!("apps.{field}"), origin.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
origins
|
||||
}
|
||||
|
||||
fn apps_config_overlays(config: &TomlValue) -> Vec<(String, TomlValue)> {
|
||||
let mut overlays = Vec::new();
|
||||
if let Some(plugins) = config.get("plugins")
|
||||
&& let Ok(policy) = PluginsConfigToml::deserialize(plugins.clone())
|
||||
&& let Some(plugins) = plugins.as_table()
|
||||
{
|
||||
let mut plugins: Vec<_> = plugins.iter().collect();
|
||||
plugins.sort_unstable_by_key(|(name, _)| *name);
|
||||
for (name, plugin) in plugins.into_iter().rev() {
|
||||
let Some(plugin_config) = policy.plugins.get(name) else {
|
||||
continue;
|
||||
};
|
||||
if !plugin_config.enabled.unwrap_or(true) || !policy.allows_plugin(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(plugin_apps) = plugin.get("apps").and_then(TomlValue::as_table) {
|
||||
let mut plugin_apps = plugin_apps.clone();
|
||||
// Nested tables address connector IDs, not global Apps defaults.
|
||||
plugin_apps.remove("_default");
|
||||
if !plugin_apps.is_empty() {
|
||||
overlays.push((
|
||||
format!("plugins.{name}.apps"),
|
||||
TomlValue::Table(plugin_apps),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(top_level_apps) = config.get("apps") {
|
||||
overlays.push(("apps".to_string(), top_level_apps.clone()));
|
||||
}
|
||||
overlays
|
||||
}
|
||||
|
||||
pub fn app_is_enabled(apps_config: &AppsConfigToml, connector_id: Option<&str>) -> bool {
|
||||
let default_enabled = apps_config
|
||||
.default
|
||||
.as_ref()
|
||||
.map(|defaults| defaults.enabled)
|
||||
.unwrap_or(true);
|
||||
|
||||
connector_id
|
||||
.and_then(|connector_id| apps_config.apps.get(connector_id))
|
||||
.map(|app| app.enabled)
|
||||
.unwrap_or(default_enabled)
|
||||
}
|
||||
|
||||
fn effective_apps_config(
|
||||
apps_config: Option<AppsConfigToml>,
|
||||
requirements_apps_config: Option<&AppsRequirementsToml>,
|
||||
) -> Option<AppsConfigToml> {
|
||||
let had_apps_config = apps_config.is_some();
|
||||
let mut apps_config = apps_config.unwrap_or_default();
|
||||
apply_requirements_apps_constraints(&mut apps_config, requirements_apps_config);
|
||||
if had_apps_config || apps_config.default.is_some() || !apps_config.apps.is_empty() {
|
||||
Some(apps_config)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_requirements_apps_constraints(
|
||||
apps_config: &mut AppsConfigToml,
|
||||
requirements_apps_config: Option<&AppsRequirementsToml>,
|
||||
) {
|
||||
let Some(requirements_apps_config) = requirements_apps_config else {
|
||||
return;
|
||||
};
|
||||
|
||||
for (app_id, requirement) in &requirements_apps_config.apps {
|
||||
if requirement.enabled == Some(false) {
|
||||
let app = apps_config.apps.entry(app_id.clone()).or_default();
|
||||
app.enabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn managed_app_tool_approval(
|
||||
requirements_apps_config: Option<&AppsRequirementsToml>,
|
||||
connector_id: Option<&str>,
|
||||
tool_name: &str,
|
||||
) -> Option<AppToolApproval> {
|
||||
let connector_id = connector_id?;
|
||||
requirements_apps_config?
|
||||
.apps
|
||||
.get(connector_id)?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.tools
|
||||
.get(tool_name)?
|
||||
.approval_mode
|
||||
}
|
||||
|
||||
fn app_tool_policy_from_apps_config(
|
||||
apps_config: Option<&AppsConfigToml>,
|
||||
input: AppToolPolicyInput<'_>,
|
||||
managed_approval: Option<AppToolApproval>,
|
||||
) -> AppToolPolicy {
|
||||
let Some(apps_config) = apps_config else {
|
||||
return AppToolPolicy {
|
||||
approval: managed_approval.unwrap_or(AppToolApproval::Auto),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
|
||||
let app = input
|
||||
.connector_id
|
||||
.and_then(|connector_id| apps_config.apps.get(connector_id));
|
||||
let tools = app.and_then(|app| app.tools.as_ref());
|
||||
let tool_config = tools.and_then(|tools| {
|
||||
tools
|
||||
.tools
|
||||
.get(input.tool_name)
|
||||
.or_else(|| input.tool_title.and_then(|title| tools.tools.get(title)))
|
||||
});
|
||||
let approval = managed_approval
|
||||
.or_else(|| tool_config.and_then(|tool| tool.approval_mode))
|
||||
.or_else(|| {
|
||||
input
|
||||
.link_id
|
||||
.and_then(|link_id| app?.links.as_ref()?.links.get(link_id))
|
||||
.and_then(|link| link.default_tools_approval_mode)
|
||||
})
|
||||
.or_else(|| app.and_then(|app| app.default_tools_approval_mode))
|
||||
.or_else(|| {
|
||||
input
|
||||
.connector_id
|
||||
.and(apps_config.default.as_ref())
|
||||
.and_then(|defaults| defaults.default_tools_approval_mode)
|
||||
})
|
||||
.unwrap_or(AppToolApproval::Auto);
|
||||
|
||||
if !app_is_enabled(apps_config, input.connector_id) {
|
||||
return AppToolPolicy {
|
||||
enabled: false,
|
||||
approval,
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(enabled) = tool_config.and_then(|tool| tool.enabled) {
|
||||
return AppToolPolicy { enabled, approval };
|
||||
}
|
||||
|
||||
if let Some(enabled) = app.and_then(|app| app.default_tools_enabled) {
|
||||
return AppToolPolicy { enabled, approval };
|
||||
}
|
||||
|
||||
let app_defaults = apps_config.default.as_ref();
|
||||
let destructive_enabled = app
|
||||
.and_then(|app| app.destructive_enabled)
|
||||
.unwrap_or_else(|| {
|
||||
app_defaults
|
||||
.map(|defaults| defaults.destructive_enabled)
|
||||
.unwrap_or(true)
|
||||
});
|
||||
let open_world_enabled = app
|
||||
.and_then(|app| app.open_world_enabled)
|
||||
.unwrap_or_else(|| {
|
||||
app_defaults
|
||||
.map(|defaults| defaults.open_world_enabled)
|
||||
.unwrap_or(true)
|
||||
});
|
||||
let destructive_hint = input.destructive_hint.unwrap_or(true);
|
||||
let open_world_hint = input.open_world_hint.unwrap_or(true);
|
||||
let enabled =
|
||||
(destructive_enabled || !destructive_hint) && (open_world_enabled || !open_world_hint);
|
||||
|
||||
AppToolPolicy { enabled, approval }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "app_tool_policy_tests.rs"]
|
||||
mod tests;
|
||||
1049
codex-rs/connectors/src/app_tool_policy_tests.rs
Normal file
1049
codex-rs/connectors/src/app_tool_policy_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
523
codex-rs/connectors/src/connector_runtime/mod.rs
Normal file
523
codex-rs/connectors/src/connector_runtime/mod.rs
Normal file
@@ -0,0 +1,523 @@
|
||||
//! Shared runtime snapshot for connector-backed MCP tools.
|
||||
//!
|
||||
//! Runtime snapshots are process-local live state scoped by account and
|
||||
//! workspace. Disk is best-effort cold-start persistence; a context reads it
|
||||
//! once when created and never rereads it. Full connector metadata is
|
||||
//! owned by the connector metadata store, not by this module.
|
||||
//! Live catalog subscriptions publish only successful fetches from a matching
|
||||
//! discovery scope, never disk snapshots or another scope's discovery winner.
|
||||
//! Equivalent live contexts share one current catalog. Each fetch still contacts
|
||||
//! the server; equal definitions retain their established storage and ordering.
|
||||
//! Providers expire with their last context.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::mcp::McpServerInfo;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use self::persistence::load_cached_codex_apps_server_info;
|
||||
use self::persistence::load_cached_connector_runtime_for_identity;
|
||||
use self::persistence::persist_codex_apps_cache;
|
||||
use self::persistence::server_info_cache_path;
|
||||
use self::persistence::tools_cache_path;
|
||||
|
||||
const MCP_TOOLS_CACHE_PUBLISH_DURATION_METRIC: &str = "codex.mcp.tools.cache_publish.duration_ms";
|
||||
|
||||
/// The current immutable tools for matching discovery inputs.
|
||||
struct CatalogProvider<T> {
|
||||
scope: Vec<String>,
|
||||
updates: watch::Sender<Option<Arc<ConnectorRuntimeSnapshot<T>>>>,
|
||||
}
|
||||
|
||||
/// Values stored in the connector runtime's persisted tool snapshot.
|
||||
///
|
||||
/// The runtime uses the connector-owned Codex Apps cache layout for every
|
||||
/// serializable, cloneable payload. Equality determines whether fresh results can
|
||||
/// retain the previous storage and tool version, so it must include all metadata
|
||||
/// that affects readers or prepared calls.
|
||||
pub trait ConnectorRuntimePayload: Clone + PartialEq + Serialize + DeserializeOwned {}
|
||||
|
||||
impl<T> ConnectorRuntimePayload for T where T: Clone + PartialEq + Serialize + DeserializeOwned {}
|
||||
|
||||
/// The account and workspace identity of a connector runtime catalog.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ConnectorRuntimeContextKey {
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
}
|
||||
|
||||
impl ConnectorRuntimeContextKey {
|
||||
pub fn personal(account_id: Option<String>, chatgpt_user_id: Option<String>) -> Self {
|
||||
Self {
|
||||
account_id,
|
||||
chatgpt_user_id,
|
||||
is_workspace_account: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn workspace(account_id: Option<String>, chatgpt_user_id: Option<String>) -> Self {
|
||||
Self {
|
||||
account_id,
|
||||
chatgpt_user_id,
|
||||
is_workspace_account: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the connector runtime context key for the active Codex auth.
|
||||
pub fn connector_runtime_context_key(auth: Option<&CodexAuth>) -> ConnectorRuntimeContextKey {
|
||||
let account_id = auth.and_then(CodexAuth::get_account_id);
|
||||
let chatgpt_user_id = auth.and_then(CodexAuth::get_chatgpt_user_id);
|
||||
if auth.is_some_and(CodexAuth::is_workspace_account) {
|
||||
ConnectorRuntimeContextKey::workspace(account_id, chatgpt_user_id)
|
||||
} else {
|
||||
ConnectorRuntimeContextKey::personal(account_id, chatgpt_user_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted connector runtime tools cache path for the active auth identity.
|
||||
pub fn connector_runtime_cache_path(codex_home: &Path, auth: Option<&CodexAuth>) -> PathBuf {
|
||||
let identity = ConnectorRuntimeIdentity {
|
||||
codex_home: codex_home.to_path_buf(),
|
||||
key: connector_runtime_context_key(auth),
|
||||
};
|
||||
tools_cache_path(&identity)
|
||||
}
|
||||
|
||||
/// One atomically published connector runtime state.
|
||||
///
|
||||
/// Tools remain raw and in response order. Local and managed configuration is
|
||||
/// intentionally applied by readers rather than persisted in this snapshot.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnectorRuntimeSnapshot<T> {
|
||||
tools: Arc<[T]>,
|
||||
tool_list_meta: Option<Arc<serde_json::Value>>,
|
||||
discovery_scope: Vec<String>,
|
||||
refreshed_at: SystemTime,
|
||||
generation: u64,
|
||||
tools_version: u64,
|
||||
}
|
||||
|
||||
impl<T> ConnectorRuntimeSnapshot<T> {
|
||||
pub fn shared_tool_list_meta(&self) -> Option<Arc<serde_json::Value>> {
|
||||
self.tool_list_meta.as_ref().map(Arc::clone)
|
||||
}
|
||||
|
||||
pub fn tools(&self) -> &[T] {
|
||||
&self.tools
|
||||
}
|
||||
|
||||
pub fn shared_tools(&self) -> Arc<[T]> {
|
||||
Arc::clone(&self.tools)
|
||||
}
|
||||
|
||||
/// Advances only when tool definitions change, so equal refreshes preserve prepared calls.
|
||||
pub fn tools_version(&self) -> u64 {
|
||||
self.tools_version
|
||||
}
|
||||
|
||||
pub fn refreshed_at(&self) -> SystemTime {
|
||||
self.refreshed_at
|
||||
}
|
||||
|
||||
pub fn age(&self) -> Duration {
|
||||
SystemTime::now()
|
||||
.duration_since(self.refreshed_at)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
type RuntimeEntries<T> = HashMap<ConnectorRuntimeIdentity, Arc<ConnectorRuntimeEntry<T>>>;
|
||||
|
||||
/// Process-scoped registry of connector runtime state by account and workspace.
|
||||
///
|
||||
/// Contexts with the same identity share one live entry. Different identities
|
||||
/// remain independently available for clients that already hold their context.
|
||||
pub struct ConnectorRuntimeManager<T: ConnectorRuntimePayload> {
|
||||
entries: Option<Arc<Mutex<RuntimeEntries<T>>>>,
|
||||
disk_cache: ConnectorRuntimeDiskCache,
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> Clone for ConnectorRuntimeManager<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
entries: self.entries.clone(),
|
||||
disk_cache: self.disk_cache,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> Default for ConnectorRuntimeManager<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
entries: Some(Arc::new(Mutex::new(HashMap::new()))),
|
||||
disk_cache: ConnectorRuntimeDiskCache::Enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> ConnectorRuntimeManager<T> {
|
||||
/// Constructs a process-local connector runtime that never reads or writes the disk cache.
|
||||
pub fn new_without_cache() -> Self {
|
||||
Self {
|
||||
entries: Some(Arc::new(Mutex::new(HashMap::new()))),
|
||||
disk_cache: ConnectorRuntimeDiskCache::Disabled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps no snapshots between clients and never reads or writes disk.
|
||||
pub fn without_shared_snapshot() -> Self {
|
||||
Self {
|
||||
entries: None,
|
||||
disk_cache: ConnectorRuntimeDiskCache::Disabled,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shares_snapshot(&self) -> bool {
|
||||
self.entries.is_some()
|
||||
}
|
||||
|
||||
pub fn current_snapshot(
|
||||
&self,
|
||||
codex_home: PathBuf,
|
||||
key: ConnectorRuntimeContextKey,
|
||||
) -> Option<Arc<ConnectorRuntimeSnapshot<T>>> {
|
||||
if !self.shares_snapshot() {
|
||||
return None;
|
||||
}
|
||||
self.context(codex_home, key).current_snapshot()
|
||||
}
|
||||
|
||||
pub fn context(
|
||||
&self,
|
||||
codex_home: PathBuf,
|
||||
key: ConnectorRuntimeContextKey,
|
||||
) -> ConnectorRuntimeContext<T> {
|
||||
let identity = ConnectorRuntimeIdentity { codex_home, key };
|
||||
let Some(entries) = &self.entries else {
|
||||
return ConnectorRuntimeContext {
|
||||
entry: Arc::new(ConnectorRuntimeEntry::new(identity, self.disk_cache)),
|
||||
live_catalog: None,
|
||||
};
|
||||
};
|
||||
let entry = lock_unpoisoned(entries)
|
||||
.entry(identity.clone())
|
||||
.or_insert_with(|| Arc::new(ConnectorRuntimeEntry::new(identity, self.disk_cache)))
|
||||
.clone();
|
||||
ConnectorRuntimeContext {
|
||||
entry,
|
||||
live_catalog: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle to one shared account/workspace connector runtime.
|
||||
pub struct ConnectorRuntimeContext<T: ConnectorRuntimePayload> {
|
||||
entry: Arc<ConnectorRuntimeEntry<T>>,
|
||||
live_catalog: Option<Arc<CatalogProvider<T>>>,
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> Clone for ConnectorRuntimeContext<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
entry: Arc::clone(&self.entry),
|
||||
live_catalog: self.live_catalog.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> ConnectorRuntimeContext<T> {
|
||||
/// Groups executable catalogs by equivalent discovery inputs within this account/home.
|
||||
/// Include transport/auth, requested capabilities, and initialization results.
|
||||
/// Calling this again refines the existing scope; it does not replace it.
|
||||
/// Account-wide discovery reads are unaffected.
|
||||
pub fn with_live_scope(mut self, scope: String) -> Self {
|
||||
let mut scope_parts = self
|
||||
.live_catalog
|
||||
.as_ref()
|
||||
.map(|catalog| catalog.scope.clone())
|
||||
.unwrap_or_default();
|
||||
scope_parts.push(scope);
|
||||
let mut catalogs = lock_unpoisoned(&self.entry.live_catalogs);
|
||||
catalogs.retain(|_, catalog| catalog.strong_count() > 0);
|
||||
let catalog = catalogs.entry(scope_parts.clone()).or_default();
|
||||
self.live_catalog = Some(catalog.upgrade().unwrap_or_else(|| {
|
||||
let provider = Arc::new(CatalogProvider {
|
||||
scope: scope_parts,
|
||||
updates: watch::channel(None).0,
|
||||
});
|
||||
*catalog = Arc::downgrade(&provider);
|
||||
provider
|
||||
}));
|
||||
drop(catalogs);
|
||||
self
|
||||
}
|
||||
|
||||
/// Detaches a server that opts out of live catalog sharing, including publication.
|
||||
pub fn without_live_scope(mut self) -> Self {
|
||||
self.live_catalog = None;
|
||||
self
|
||||
}
|
||||
|
||||
/// Subscribes to accepted live tools without refetching or waiting for other clients.
|
||||
pub fn subscribe(&self) -> Option<watch::Receiver<Option<Arc<ConnectorRuntimeSnapshot<T>>>>> {
|
||||
self.live_catalog
|
||||
.as_ref()
|
||||
.map(|catalog| catalog.updates.subscribe())
|
||||
}
|
||||
|
||||
pub fn current_snapshot(&self) -> Option<Arc<ConnectorRuntimeSnapshot<T>>> {
|
||||
self.entry.current_snapshot.load_full()
|
||||
}
|
||||
|
||||
pub fn current_catalog_snapshot(&self) -> Option<Arc<ConnectorRuntimeSnapshot<T>>> {
|
||||
let catalog = self.live_catalog.as_ref()?;
|
||||
catalog.updates.borrow().clone().or_else(|| {
|
||||
let scope: Vec<_> = catalog
|
||||
.scope
|
||||
.iter()
|
||||
.map(|part| persistence::sha1_hex(part))
|
||||
.collect();
|
||||
self.current_snapshot()
|
||||
.filter(|snapshot| snapshot.discovery_scope.starts_with(&scope))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn has_current_tools(&self) -> bool {
|
||||
self.current_snapshot().is_some()
|
||||
}
|
||||
|
||||
pub fn begin_fetch(&self, source: ConnectorRuntimeFetchSource) -> ConnectorRuntimeFetchTicket {
|
||||
ConnectorRuntimeFetchTicket {
|
||||
generation: self
|
||||
.entry
|
||||
.next_fetch_generation
|
||||
.fetch_add(1, Ordering::Relaxed)
|
||||
+ 1,
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cached_server_info(&self) -> Option<McpServerInfo> {
|
||||
match self.entry.disk_cache {
|
||||
ConnectorRuntimeDiskCache::Enabled => load_cached_codex_apps_server_info(self),
|
||||
ConnectorRuntimeDiskCache::Disabled => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tools_cache_path(&self) -> PathBuf {
|
||||
tools_cache_path(&self.entry.identity)
|
||||
}
|
||||
|
||||
fn server_info_cache_path(&self) -> PathBuf {
|
||||
server_info_cache_path(&self.entry.identity)
|
||||
}
|
||||
|
||||
pub fn current_tools(&self) -> Option<Vec<T>> {
|
||||
self.current_snapshot()
|
||||
.map(|snapshot| snapshot.tools.to_vec())
|
||||
}
|
||||
|
||||
pub fn publish_runtime_if_newest_accepted(
|
||||
&self,
|
||||
ticket: ConnectorRuntimeFetchTicket,
|
||||
server_info: &McpServerInfo,
|
||||
tools: Vec<T>,
|
||||
tool_list_meta: Option<Arc<serde_json::Value>>,
|
||||
) -> Arc<ConnectorRuntimeSnapshot<T>> {
|
||||
match self.entry.disk_cache {
|
||||
ConnectorRuntimeDiskCache::Enabled => self.publish_runtime_if_newest_accepted_with(
|
||||
ticket,
|
||||
server_info,
|
||||
tools,
|
||||
tool_list_meta,
|
||||
persist_codex_apps_cache,
|
||||
),
|
||||
ConnectorRuntimeDiskCache::Disabled => self.publish_runtime_if_newest_accepted_with(
|
||||
ticket,
|
||||
server_info,
|
||||
tools,
|
||||
tool_list_meta,
|
||||
|_, _, _| {},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_runtime_if_newest_accepted_with(
|
||||
&self,
|
||||
ticket: ConnectorRuntimeFetchTicket,
|
||||
server_info: &McpServerInfo,
|
||||
tools: Vec<T>,
|
||||
tool_list_meta: Option<Arc<serde_json::Value>>,
|
||||
persist: impl FnOnce(&ConnectorRuntimeContext<T>, &McpServerInfo, &ConnectorRuntimeSnapshot<T>),
|
||||
) -> Arc<ConnectorRuntimeSnapshot<T>> {
|
||||
let publish_start = Instant::now();
|
||||
let mut last_accepted_generation = lock_unpoisoned(&self.entry.last_accepted_generation);
|
||||
let prior = self
|
||||
.live_catalog
|
||||
.as_ref()
|
||||
.and_then(|catalog| catalog.updates.borrow().clone());
|
||||
let (tools, tools_version) = match prior {
|
||||
Some(prior)
|
||||
if prior.generation < ticket.generation && prior.tools() == tools.as_slice() =>
|
||||
{
|
||||
(prior.shared_tools(), prior.tools_version)
|
||||
}
|
||||
_ => (tools.into(), ticket.generation),
|
||||
};
|
||||
let snapshot = Arc::new(ConnectorRuntimeSnapshot {
|
||||
tool_list_meta,
|
||||
discovery_scope: self
|
||||
.live_catalog
|
||||
.as_ref()
|
||||
.map(|catalog| {
|
||||
catalog
|
||||
.scope
|
||||
.iter()
|
||||
.map(|part| persistence::sha1_hex(part))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
tools,
|
||||
tools_version,
|
||||
refreshed_at: SystemTime::now(),
|
||||
generation: ticket.generation,
|
||||
});
|
||||
if let Some(live_catalog) = &self.live_catalog {
|
||||
live_catalog.updates.send_if_modified(|current| {
|
||||
if current
|
||||
.as_ref()
|
||||
.is_some_and(|current| current.generation >= ticket.generation)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
*current = Some(Arc::clone(&snapshot));
|
||||
true
|
||||
});
|
||||
}
|
||||
if ticket.generation <= *last_accepted_generation
|
||||
&& let Some(snapshot) = self.current_snapshot()
|
||||
{
|
||||
drop(last_accepted_generation);
|
||||
emit_duration(
|
||||
MCP_TOOLS_CACHE_PUBLISH_DURATION_METRIC,
|
||||
publish_start.elapsed(),
|
||||
&[("source", ticket.source.as_str()), ("result", "stale")],
|
||||
);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
*last_accepted_generation = ticket.generation;
|
||||
self.entry
|
||||
.current_snapshot
|
||||
.store(Some(Arc::clone(&snapshot)));
|
||||
// Keep the generation guard through persistence so accepted generations cannot reach disk
|
||||
// out of order.
|
||||
persist(self, server_info, snapshot.as_ref());
|
||||
drop(last_accepted_generation);
|
||||
emit_duration(
|
||||
MCP_TOOLS_CACHE_PUBLISH_DURATION_METRIC,
|
||||
publish_start.elapsed(),
|
||||
&[("source", ticket.source.as_str()), ("result", "published")],
|
||||
);
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ConnectorRuntimeFetchSource {
|
||||
Startup,
|
||||
HardRefresh,
|
||||
}
|
||||
|
||||
impl ConnectorRuntimeFetchSource {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Startup => "startup",
|
||||
Self::HardRefresh => "hard_refresh",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectorRuntimeFetchTicket {
|
||||
generation: u64,
|
||||
source: ConnectorRuntimeFetchSource,
|
||||
}
|
||||
|
||||
/// All live state owned by one connector identity.
|
||||
struct ConnectorRuntimeEntry<T: ConnectorRuntimePayload> {
|
||||
identity: ConnectorRuntimeIdentity,
|
||||
disk_cache: ConnectorRuntimeDiskCache,
|
||||
current_snapshot: ArcSwapOption<ConnectorRuntimeSnapshot<T>>,
|
||||
next_fetch_generation: AtomicU64,
|
||||
last_accepted_generation: Mutex<u64>,
|
||||
live_catalogs: Mutex<HashMap<Vec<String>, Weak<CatalogProvider<T>>>>,
|
||||
}
|
||||
|
||||
impl<T: ConnectorRuntimePayload> ConnectorRuntimeEntry<T> {
|
||||
fn new(identity: ConnectorRuntimeIdentity, disk_cache: ConnectorRuntimeDiskCache) -> Self {
|
||||
let current_snapshot = match disk_cache {
|
||||
ConnectorRuntimeDiskCache::Enabled => {
|
||||
load_cached_connector_runtime_for_identity(&identity).map(Arc::new)
|
||||
}
|
||||
ConnectorRuntimeDiskCache::Disabled => None,
|
||||
};
|
||||
Self {
|
||||
identity,
|
||||
disk_cache,
|
||||
current_snapshot: ArcSwapOption::from(current_snapshot),
|
||||
next_fetch_generation: AtomicU64::new(0),
|
||||
last_accepted_generation: Mutex::new(0),
|
||||
live_catalogs: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ConnectorRuntimeDiskCache {
|
||||
Enabled,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
/// Everything that decides whether two connector runtime clients can share a snapshot.
|
||||
///
|
||||
/// The auth key says whose runtime catalog we are reading. `codex_home` keeps
|
||||
/// the persisted cache under the right home directory.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct ConnectorRuntimeIdentity {
|
||||
codex_home: PathBuf,
|
||||
key: ConnectorRuntimeContextKey,
|
||||
}
|
||||
|
||||
fn emit_duration(metric: &str, duration: Duration, tags: &[(&str, &str)]) {
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(metric, duration, tags);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
mod persistence;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
285
codex-rs/connectors/src/connector_runtime/persistence.rs
Normal file
285
codex-rs/connectors/src/connector_runtime/persistence.rs
Normal file
@@ -0,0 +1,285 @@
|
||||
//! Bounded, atomic persistence for connector runtime snapshots.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::anyhow;
|
||||
use codex_protocol::mcp::McpServerInfo;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha1::Digest;
|
||||
use sha1::Sha1;
|
||||
use tempfile::NamedTempFile;
|
||||
use tracing::instrument;
|
||||
|
||||
use super::ConnectorRuntimeContext;
|
||||
use super::ConnectorRuntimeIdentity;
|
||||
use super::ConnectorRuntimePayload;
|
||||
use super::ConnectorRuntimeSnapshot;
|
||||
use super::emit_duration;
|
||||
|
||||
const MCP_TOOLS_CACHE_WRITE_DURATION_METRIC: &str = "codex.mcp.tools.cache_write.duration_ms";
|
||||
const CODEX_APPS_TOOLS_CACHE_DIR: &str = "cache/codex_apps_tools";
|
||||
pub(crate) const CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION: u8 = 4;
|
||||
const CODEX_APPS_SERVER_INFO_CACHE_DIR: &str = "cache/codex_apps_server_info";
|
||||
const CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION: u8 = 1;
|
||||
pub(crate) const CODEX_APPS_TOOLS_CACHE_MAX_BYTES: u64 = 32 * 1024 * 1024;
|
||||
|
||||
pub(crate) fn tools_cache_path(identity: &ConnectorRuntimeIdentity) -> PathBuf {
|
||||
cache_path_in(identity, CODEX_APPS_TOOLS_CACHE_DIR)
|
||||
}
|
||||
|
||||
pub(crate) fn server_info_cache_path(identity: &ConnectorRuntimeIdentity) -> PathBuf {
|
||||
cache_path_in(identity, CODEX_APPS_SERVER_INFO_CACHE_DIR)
|
||||
}
|
||||
|
||||
fn cache_path_in(identity: &ConnectorRuntimeIdentity, cache_dir: &str) -> PathBuf {
|
||||
// `codex_home` is already the parent directory. Keep it out of the
|
||||
// filename hash so non-UTF-8 Unix paths cannot collapse distinct auth keys.
|
||||
let identity_json = serde_json::to_string(&identity.key).unwrap_or_default();
|
||||
let identity_hash = sha1_hex(&identity_json);
|
||||
identity
|
||||
.codex_home
|
||||
.join(cache_dir)
|
||||
.join(format!("{identity_hash}.json"))
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub(crate) fn load_cached_connector_runtime_for_identity<T: ConnectorRuntimePayload>(
|
||||
identity: &ConnectorRuntimeIdentity,
|
||||
) -> Option<ConnectorRuntimeSnapshot<T>> {
|
||||
let cache_path = tools_cache_path(identity);
|
||||
let (bytes, modified_at) = read_bounded_cache_file(&cache_path).ok()?;
|
||||
let cache: CodexAppsToolsDiskCache<T> = serde_json::from_slice(&bytes).ok()?;
|
||||
(cache.schema_version == CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION).then_some(
|
||||
ConnectorRuntimeSnapshot {
|
||||
tools: cache.tools,
|
||||
tool_list_meta: cache.tool_list_meta.map(Arc::new),
|
||||
discovery_scope: cache.discovery_scope,
|
||||
refreshed_at: modified_at,
|
||||
generation: 0,
|
||||
tools_version: 0,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn write_cached_connector_runtime<T>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
snapshot: &ConnectorRuntimeSnapshot<T>,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
T: ConnectorRuntimePayload,
|
||||
{
|
||||
let cache_path = cache_context.tools_cache_path();
|
||||
let bytes = serde_json::to_vec_pretty(&CodexAppsToolsDiskCache {
|
||||
schema_version: CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION,
|
||||
tools: snapshot.tools.clone(),
|
||||
tool_list_meta: snapshot.tool_list_meta.as_deref().cloned(),
|
||||
discovery_scope: snapshot.discovery_scope.clone(),
|
||||
})
|
||||
.context("failed to serialize connector runtime cache")?;
|
||||
write_codex_apps_cache_file(&cache_path, "runtime", bytes)
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub(crate) fn load_cached_codex_apps_server_info<T: ConnectorRuntimePayload>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
) -> Option<McpServerInfo> {
|
||||
let (bytes, _) = read_bounded_cache_file(&cache_context.server_info_cache_path()).ok()?;
|
||||
let cache: CodexAppsServerInfoDiskCache = serde_json::from_slice(&bytes).ok()?;
|
||||
(cache.schema_version == CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION)
|
||||
.then_some(cache.server_info)
|
||||
}
|
||||
|
||||
fn write_cached_codex_apps_server_info<T: ConnectorRuntimePayload>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
server_info: &McpServerInfo,
|
||||
) -> anyhow::Result<()> {
|
||||
let cache_path = cache_context.server_info_cache_path();
|
||||
let bytes = serde_json::to_vec_pretty(&CodexAppsServerInfoDiskCache {
|
||||
schema_version: CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION,
|
||||
server_info: server_info.clone(),
|
||||
})
|
||||
.context("failed to serialize Codex Apps server info cache")?;
|
||||
write_codex_apps_cache_file(&cache_path, "server info", bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn persist_codex_apps_cache<T>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
server_info: &McpServerInfo,
|
||||
snapshot: &ConnectorRuntimeSnapshot<T>,
|
||||
) where
|
||||
T: ConnectorRuntimePayload,
|
||||
{
|
||||
let cache_write_start = Instant::now();
|
||||
let tools_result = write_cached_connector_runtime(cache_context, snapshot);
|
||||
if let Err(err) = &tools_result {
|
||||
tracing::warn!("failed to write connector runtime cache: {err:#}");
|
||||
}
|
||||
let server_info_result = write_cached_codex_apps_server_info(cache_context, server_info);
|
||||
if let Err(err) = &server_info_result {
|
||||
tracing::warn!("failed to write Codex Apps server info cache: {err:#}");
|
||||
}
|
||||
let status = if tools_result.is_ok() && server_info_result.is_ok() {
|
||||
"success"
|
||||
} else {
|
||||
"failure"
|
||||
};
|
||||
emit_duration(
|
||||
MCP_TOOLS_CACHE_WRITE_DURATION_METRIC,
|
||||
cache_write_start.elapsed(),
|
||||
&[("status", status)],
|
||||
);
|
||||
}
|
||||
|
||||
fn read_bounded_cache_file(cache_path: &Path) -> anyhow::Result<(Vec<u8>, SystemTime)> {
|
||||
let mut file = File::open(cache_path)
|
||||
.with_context(|| format!("failed to open cache `{}`", cache_path.display()))?;
|
||||
let metadata = file
|
||||
.metadata()
|
||||
.with_context(|| format!("failed to stat cache `{}`", cache_path.display()))?;
|
||||
if metadata.len() > CODEX_APPS_TOOLS_CACHE_MAX_BYTES {
|
||||
return Err(anyhow!(
|
||||
"cache `{}` is {} bytes, exceeding the {} byte limit",
|
||||
cache_path.display(),
|
||||
metadata.len(),
|
||||
CODEX_APPS_TOOLS_CACHE_MAX_BYTES
|
||||
));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(metadata.len() as usize);
|
||||
std::io::Read::by_ref(&mut file)
|
||||
.take(CODEX_APPS_TOOLS_CACHE_MAX_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.with_context(|| format!("failed to read cache `{}`", cache_path.display()))?;
|
||||
if bytes.len() as u64 > CODEX_APPS_TOOLS_CACHE_MAX_BYTES {
|
||||
return Err(anyhow!(
|
||||
"cache `{}` grew beyond the {} byte limit while reading",
|
||||
cache_path.display(),
|
||||
CODEX_APPS_TOOLS_CACHE_MAX_BYTES
|
||||
));
|
||||
}
|
||||
Ok((bytes, metadata.modified().unwrap_or(UNIX_EPOCH)))
|
||||
}
|
||||
|
||||
fn write_codex_apps_cache_file(
|
||||
cache_path: &Path,
|
||||
cache_name: &str,
|
||||
bytes: Vec<u8>,
|
||||
) -> anyhow::Result<()> {
|
||||
let parent = cache_path.parent().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Codex Apps {cache_name} cache path `{}` has no parent",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent).with_context(|| {
|
||||
format!(
|
||||
"failed to create Codex Apps {cache_name} cache directory `{}`",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
let mut temporary = NamedTempFile::new_in(parent).with_context(|| {
|
||||
format!(
|
||||
"failed to create temporary Codex Apps {cache_name} cache in `{}`",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
temporary.write_all(&bytes).with_context(|| {
|
||||
format!(
|
||||
"failed to write temporary Codex Apps {cache_name} cache for `{}`",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
temporary.persist(cache_path).map_err(|error| {
|
||||
anyhow!(
|
||||
"failed to atomically replace Codex Apps {cache_name} cache `{}`: {}",
|
||||
cache_path.display(),
|
||||
error.error
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct CodexAppsToolsDiskCache<T> {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
tool_list_meta: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
discovery_scope: Vec<String>,
|
||||
schema_version: u8,
|
||||
tools: Arc<[T]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct CodexAppsServerInfoDiskCache {
|
||||
schema_version: u8,
|
||||
server_info: McpServerInfo,
|
||||
}
|
||||
|
||||
pub(super) fn sha1_hex(s: &str) -> String {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(s.as_bytes());
|
||||
let sha1 = hasher.finalize();
|
||||
format!("{sha1:x}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn write_cached_codex_apps_tools_for_test<T>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
server_info: &McpServerInfo,
|
||||
tools: &[T],
|
||||
) where
|
||||
T: ConnectorRuntimePayload,
|
||||
{
|
||||
let snapshot = ConnectorRuntimeSnapshot {
|
||||
tools: tools.into(),
|
||||
tool_list_meta: None,
|
||||
discovery_scope: Vec::new(),
|
||||
refreshed_at: SystemTime::now(),
|
||||
generation: 0,
|
||||
tools_version: 0,
|
||||
};
|
||||
cache_context
|
||||
.entry
|
||||
.current_snapshot
|
||||
.store(Some(Arc::new(snapshot.clone())));
|
||||
persist_codex_apps_cache(cache_context, server_info, &snapshot);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn read_cached_codex_apps_tools<T>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
) -> Option<Vec<T>>
|
||||
where
|
||||
T: ConnectorRuntimePayload,
|
||||
{
|
||||
load_cached_connector_runtime_for_identity(&cache_context.entry.identity)
|
||||
.map(|snapshot| snapshot.tools.to_vec())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn write_cached_codex_apps_tools<T>(
|
||||
cache_context: &ConnectorRuntimeContext<T>,
|
||||
tools: &[T],
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
T: ConnectorRuntimePayload,
|
||||
{
|
||||
let snapshot = ConnectorRuntimeSnapshot {
|
||||
tools: tools.into(),
|
||||
tool_list_meta: None,
|
||||
discovery_scope: Vec::new(),
|
||||
refreshed_at: SystemTime::now(),
|
||||
generation: 0,
|
||||
tools_version: 0,
|
||||
};
|
||||
write_cached_connector_runtime(cache_context, &snapshot)
|
||||
}
|
||||
917
codex-rs/connectors/src/connector_runtime/tests.rs
Normal file
917
codex-rs/connectors/src/connector_runtime/tests.rs
Normal file
@@ -0,0 +1,917 @@
|
||||
use super::persistence::CODEX_APPS_TOOLS_CACHE_MAX_BYTES;
|
||||
use super::persistence::CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION;
|
||||
use super::persistence::read_cached_codex_apps_tools;
|
||||
use super::persistence::write_cached_codex_apps_tools;
|
||||
use super::persistence::write_cached_codex_apps_tools_for_test;
|
||||
use super::*;
|
||||
use codex_protocol::mcp::McpServerInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tempfile::tempdir;
|
||||
|
||||
const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct TestTool {
|
||||
server_name: String,
|
||||
callable_name: String,
|
||||
connector_id: Option<String>,
|
||||
connector_name: Option<String>,
|
||||
}
|
||||
|
||||
fn create_test_tool(server_name: &str, tool_name: &str) -> TestTool {
|
||||
TestTool {
|
||||
server_name: server_name.to_string(),
|
||||
callable_name: tool_name.to_string(),
|
||||
connector_id: None,
|
||||
connector_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_test_tool_with_connector(
|
||||
server_name: &str,
|
||||
tool_name: &str,
|
||||
connector_id: &str,
|
||||
connector_name: Option<&str>,
|
||||
) -> TestTool {
|
||||
let mut tool = create_test_tool(server_name, tool_name);
|
||||
tool.connector_id = Some(connector_id.to_string());
|
||||
tool.connector_name = connector_name.map(ToOwned::to_owned);
|
||||
tool
|
||||
}
|
||||
|
||||
fn create_codex_apps_tools_cache_context(
|
||||
codex_home: PathBuf,
|
||||
account_id: Option<&str>,
|
||||
chatgpt_user_id: Option<&str>,
|
||||
) -> ConnectorRuntimeContext<TestTool> {
|
||||
ConnectorRuntimeManager::<TestTool>::default().context(
|
||||
codex_home,
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: account_id.map(ToOwned::to_owned),
|
||||
chatgpt_user_id: chatgpt_user_id.map(ToOwned::to_owned),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn create_test_server_info(title: &str) -> McpServerInfo {
|
||||
McpServerInfo {
|
||||
name: "codex-apps".to_string(),
|
||||
title: Some(title.to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
description: None,
|
||||
icons: None,
|
||||
website_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_is_overwritten_by_last_write() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let tools_gateway_1 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")];
|
||||
let tools_gateway_2 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "two")];
|
||||
|
||||
write_cached_codex_apps_tools(&cache_context, &tools_gateway_1).expect("write first cache");
|
||||
let cached_gateway_1 =
|
||||
read_cached_codex_apps_tools(&cache_context).expect("cache entry exists for first write");
|
||||
assert_eq!(cached_gateway_1[0].callable_name, "one");
|
||||
|
||||
write_cached_codex_apps_tools(&cache_context, &tools_gateway_2).expect("write second cache");
|
||||
let cached_gateway_2 =
|
||||
read_cached_codex_apps_tools(&cache_context).expect("cache entry exists for second write");
|
||||
assert_eq!(cached_gateway_2[0].callable_name, "two");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_is_scoped_per_user() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context_user_1 = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cache_context_user_2 = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-two"),
|
||||
Some("user-two"),
|
||||
);
|
||||
let tools_user_1 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")];
|
||||
let tools_user_2 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "two")];
|
||||
|
||||
write_cached_codex_apps_tools(&cache_context_user_1, &tools_user_1)
|
||||
.expect("write user one cache");
|
||||
write_cached_codex_apps_tools(&cache_context_user_2, &tools_user_2)
|
||||
.expect("write user two cache");
|
||||
|
||||
let read_user_1 =
|
||||
read_cached_codex_apps_tools(&cache_context_user_1).expect("cache entry for user one");
|
||||
let read_user_2 =
|
||||
read_cached_codex_apps_tools(&cache_context_user_2).expect("cache entry for user two");
|
||||
|
||||
assert_eq!(read_user_1[0].callable_name, "one");
|
||||
assert_eq!(read_user_2[0].callable_name, "two");
|
||||
assert_ne!(
|
||||
cache_context_user_1.tools_cache_path(),
|
||||
cache_context_user_2.tools_cache_path(),
|
||||
"each user should get an isolated cache file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_preserves_formerly_disallowed_connectors() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let tools = vec![
|
||||
create_test_tool_with_connector(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"formerly_blocked_tool",
|
||||
"connector_2b0a9009c9c64bf9933a3dae3f2b1254",
|
||||
Some("Formerly Blocked"),
|
||||
),
|
||||
create_test_tool_with_connector(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"calendar_tool",
|
||||
"calendar",
|
||||
Some("Calendar"),
|
||||
),
|
||||
];
|
||||
|
||||
write_cached_codex_apps_tools(&cache_context, &tools).expect("write cache");
|
||||
let cached = read_cached_codex_apps_tools(&cache_context).expect("cache entry exists for user");
|
||||
|
||||
assert_eq!(
|
||||
cached
|
||||
.iter()
|
||||
.map(|tool| (tool.callable_name.as_str(), tool.connector_id.as_deref()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(
|
||||
"formerly_blocked_tool",
|
||||
Some("connector_2b0a9009c9c64bf9933a3dae3f2b1254")
|
||||
),
|
||||
("calendar_tool", Some("calendar")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_is_ignored_when_schema_version_mismatches() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cache_path = cache_context.tools_cache_path();
|
||||
if let Some(parent) = cache_path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION + 1,
|
||||
"tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")],
|
||||
}))
|
||||
.expect("serialize");
|
||||
std::fs::write(cache_path, bytes).expect("write");
|
||||
|
||||
assert!(read_cached_codex_apps_tools(&cache_context).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_is_ignored_when_json_is_invalid() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cache_path = cache_context.tools_cache_path();
|
||||
if let Some(parent) = cache_path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::fs::write(cache_path, b"{not json").expect("write");
|
||||
|
||||
assert!(read_cached_codex_apps_tools(&cache_context).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_cached_codex_apps_tools_loads_from_disk_cache() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let writer_cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cached_tools = vec![create_test_tool(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"calendar_search",
|
||||
)];
|
||||
let server_info = create_test_server_info("Codex Apps");
|
||||
write_cached_codex_apps_tools_for_test(&writer_cache_context, &server_info, &cached_tools);
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
|
||||
let startup_tools = cache_context
|
||||
.current_tools()
|
||||
.expect("expected startup snapshot to load from cache");
|
||||
let cached_server_info = cache_context.cached_server_info();
|
||||
|
||||
assert_eq!(startup_tools.len(), 1);
|
||||
assert_eq!(startup_tools[0].server_name, CODEX_APPS_MCP_SERVER_NAME);
|
||||
assert_eq!(startup_tools[0].callable_name, "calendar_search");
|
||||
assert_eq!(cached_server_info, Some(server_info));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_cached_codex_apps_tools_loads_without_server_info_cache() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let writer_cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cache_path = writer_cache_context.tools_cache_path();
|
||||
if let Some(parent) = cache_path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION,
|
||||
"tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "calendar_search")],
|
||||
}))
|
||||
.expect("serialize");
|
||||
std::fs::write(cache_path, bytes).expect("write");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
|
||||
let startup_tools = cache_context
|
||||
.current_tools()
|
||||
.expect("legacy startup snapshot should remain available");
|
||||
let cached_server_info = cache_context.cached_server_info();
|
||||
|
||||
assert_eq!(startup_tools.len(), 1);
|
||||
assert_eq!(startup_tools[0].callable_name, "calendar_search");
|
||||
assert_eq!(cached_server_info, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_server_info_cache_survives_legacy_tools_cache_write() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let server_info = create_test_server_info("Codex Apps");
|
||||
write_cached_codex_apps_tools_for_test(
|
||||
&cache_context,
|
||||
&server_info,
|
||||
&[create_test_tool(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"calendar_search",
|
||||
)],
|
||||
);
|
||||
|
||||
let cache_path = cache_context.tools_cache_path();
|
||||
if let Some(parent) = cache_path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION - 1,
|
||||
"tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "calendar_search")],
|
||||
}))
|
||||
.expect("serialize");
|
||||
std::fs::write(cache_path, bytes).expect("write legacy tools cache");
|
||||
let startup_cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
startup_cache_context.cached_server_info(),
|
||||
Some(server_info)
|
||||
);
|
||||
assert!(startup_cache_context.current_tools().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_context_does_not_reread_disk_after_creation() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let writer_cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cached_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "cached")];
|
||||
write_cached_codex_apps_tools(&writer_cache_context, &cached_tools).expect("write cache");
|
||||
let reader_cache_context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let updated_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "updated")];
|
||||
write_cached_codex_apps_tools(&writer_cache_context, &updated_tools).expect("rewrite cache");
|
||||
|
||||
assert_eq!(
|
||||
reader_cache_context
|
||||
.current_tools()
|
||||
.expect("in-memory tools")[0]
|
||||
.callable_name,
|
||||
"cached"
|
||||
);
|
||||
assert_eq!(
|
||||
read_cached_codex_apps_tools(&writer_cache_context).expect("disk tools")[0].callable_name,
|
||||
"updated"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_publishes_newest_shared_snapshot() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let cache = ConnectorRuntimeManager::<TestTool>::default();
|
||||
let cache_context_1 = cache.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let cache_context_2 = cache.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let older_ticket = cache_context_1.begin_fetch(ConnectorRuntimeFetchSource::Startup);
|
||||
let newer_ticket = cache_context_2.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh);
|
||||
let server_info = create_test_server_info("Codex Apps");
|
||||
let newer_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "newer")];
|
||||
let older_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "older")];
|
||||
|
||||
let published_tools = cache_context_2
|
||||
.publish_runtime_if_newest_accepted(
|
||||
newer_ticket,
|
||||
&server_info,
|
||||
newer_tools,
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
assert_eq!(cache_context_1.current_tools(), Some(published_tools));
|
||||
let current_tools = cache_context_1
|
||||
.publish_runtime_if_newest_accepted(
|
||||
older_ticket,
|
||||
&server_info,
|
||||
older_tools,
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(current_tools[0].callable_name, "newer");
|
||||
assert_eq!(
|
||||
cache_context_2.current_tools().expect("shared snapshot")[0].callable_name,
|
||||
"newer"
|
||||
);
|
||||
assert_eq!(
|
||||
read_cached_codex_apps_tools(&cache_context_1).expect("persisted snapshot")[0]
|
||||
.callable_name,
|
||||
"newer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_keeps_live_publish_when_disk_persistence_fails() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let codex_home_file = codex_home.path().join("not-a-directory");
|
||||
std::fs::write(&codex_home_file, b"occupied").expect("create codex home file");
|
||||
let cache_context = ConnectorRuntimeManager::<TestTool>::default().context(
|
||||
codex_home_file,
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "live")];
|
||||
let published_tools = cache_context
|
||||
.publish_runtime_if_newest_accepted(
|
||||
cache_context.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
tools.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(published_tools, tools);
|
||||
assert_eq!(cache_context.current_tools(), Some(tools));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connector_runtime_without_cache_ignores_disk_state() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let writer = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "cached")];
|
||||
let server_info = create_test_server_info("Codex Apps");
|
||||
write_cached_codex_apps_tools_for_test(&writer, &server_info, &tools);
|
||||
let context = ConnectorRuntimeManager::<TestTool>::new_without_cache().context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(context.current_tools(), None);
|
||||
assert_eq!(context.cached_server_info(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connector_runtime_without_cache_publishes_without_writing() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let codex_home = temp_dir.path().join("codex-home");
|
||||
let context = ConnectorRuntimeManager::<TestTool>::new_without_cache().context(
|
||||
codex_home.clone(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "live")];
|
||||
let published_tools = context
|
||||
.publish_runtime_if_newest_accepted(
|
||||
context.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
tools.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
|
||||
assert_eq!(published_tools, tools);
|
||||
assert_eq!(context.current_tools(), Some(tools));
|
||||
assert!(!codex_home.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn codex_apps_tools_cache_scopes_non_utf8_home_disk_paths() {
|
||||
let codex_home = PathBuf::from(std::ffi::OsString::from_vec(
|
||||
b"/tmp/codex-home-\xff".to_vec(),
|
||||
));
|
||||
let cache = ConnectorRuntimeManager::<TestTool>::default();
|
||||
let user_one_context = cache.context(
|
||||
codex_home.clone(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-one".to_string()),
|
||||
chatgpt_user_id: Some("user-one".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let user_two_context = cache.context(
|
||||
codex_home,
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-two".to_string()),
|
||||
chatgpt_user_id: Some("user-two".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let cache_paths = [
|
||||
user_one_context.tools_cache_path(),
|
||||
user_two_context.tools_cache_path(),
|
||||
];
|
||||
|
||||
assert_ne!(cache_paths[0], cache_paths[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_catalogs_isolate_scopes_and_reject_older_refreshes() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let manager = ConnectorRuntimeManager::<TestTool>::new_without_cache();
|
||||
let context = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey::personal(
|
||||
Some("account".to_string()),
|
||||
/*chatgpt_user_id*/ None,
|
||||
),
|
||||
);
|
||||
let scope_a = context.clone().with_live_scope("endpoint-a".to_string());
|
||||
let scope_b = context.with_live_scope("endpoint-b".to_string());
|
||||
let updates_a = scope_a.subscribe().expect("scope A subscription");
|
||||
let updates_b = scope_b.subscribe().expect("scope B subscription");
|
||||
let server_info = create_test_server_info("Codex Apps");
|
||||
let older_a = scope_a.begin_fetch(ConnectorRuntimeFetchSource::Startup);
|
||||
let newer_a = scope_a.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh);
|
||||
let newest_b = scope_b.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh);
|
||||
let tools_a = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "newer-a")];
|
||||
let tools_b = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "newest-b")];
|
||||
|
||||
scope_b
|
||||
.publish_runtime_if_newest_accepted(
|
||||
newest_b,
|
||||
&server_info,
|
||||
tools_b.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
assert!(updates_a.borrow().is_none());
|
||||
let discovery = scope_a
|
||||
.publish_runtime_if_newest_accepted(
|
||||
newer_a,
|
||||
&server_info,
|
||||
tools_a.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
assert_eq!(discovery, tools_b);
|
||||
scope_a
|
||||
.publish_runtime_if_newest_accepted(
|
||||
older_a,
|
||||
&server_info,
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "stale-a")],
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
.tools()
|
||||
.to_vec();
|
||||
assert_eq!(
|
||||
updates_a.borrow().as_ref().expect("scope A tools").tools(),
|
||||
&tools_a
|
||||
);
|
||||
assert_eq!(
|
||||
updates_b.borrow().as_ref().expect("scope B tools").tools(),
|
||||
&tools_b
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contexts_for_different_identities_keep_isolated_snapshots() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let manager = ConnectorRuntimeManager::<TestTool>::default();
|
||||
let context_a = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-a".to_string()),
|
||||
chatgpt_user_id: Some("user-a".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let context_a = context_a.with_live_scope("same-endpoint".to_string());
|
||||
let updates_a = context_a.subscribe().expect("account A subscription");
|
||||
let tools_a = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "tool-a")];
|
||||
let snapshot_a = context_a.publish_runtime_if_newest_accepted(
|
||||
context_a.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
tools_a.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
let older_ticket_a = context_a.begin_fetch(ConnectorRuntimeFetchSource::Startup);
|
||||
let context_b = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-b".to_string()),
|
||||
chatgpt_user_id: Some("user-b".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let context_b = context_b.with_live_scope("same-endpoint".to_string());
|
||||
let updates_b = context_b.subscribe().expect("account B subscription");
|
||||
let same_context_a = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account-a".to_string()),
|
||||
chatgpt_user_id: Some("user-a".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let same_context_a = same_context_a.with_live_scope("same-endpoint".to_string());
|
||||
|
||||
assert!(Arc::ptr_eq(
|
||||
&snapshot_a,
|
||||
&same_context_a
|
||||
.current_snapshot()
|
||||
.expect("context A snapshot")
|
||||
));
|
||||
assert!(context_b.current_snapshot().is_none());
|
||||
|
||||
let tools_b = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "tool-b")];
|
||||
let snapshot_b = context_b.publish_runtime_if_newest_accepted(
|
||||
context_b.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
tools_b.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
let newer_tools_a = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "newer-a")];
|
||||
let newer_snapshot_a = same_context_a.publish_runtime_if_newest_accepted(
|
||||
same_context_a.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
newer_tools_a.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
let stale_snapshot_a = context_a.publish_runtime_if_newest_accepted(
|
||||
older_ticket_a,
|
||||
&create_test_server_info("Codex Apps"),
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "stale-a")],
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(snapshot_a.tools(), &tools_a);
|
||||
assert_eq!(snapshot_b.tools(), &tools_b);
|
||||
assert_eq!(newer_snapshot_a.tools(), &newer_tools_a);
|
||||
assert!(Arc::ptr_eq(&newer_snapshot_a, &stale_snapshot_a));
|
||||
assert!(Arc::ptr_eq(
|
||||
&newer_snapshot_a,
|
||||
&context_a.current_snapshot().expect("context A snapshot")
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
&snapshot_b,
|
||||
&context_b.current_snapshot().expect("context B snapshot")
|
||||
));
|
||||
assert_eq!(
|
||||
updates_a
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.expect("account A tools")
|
||||
.tools(),
|
||||
&newer_tools_a
|
||||
);
|
||||
assert_eq!(
|
||||
updates_b
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.expect("account B tools")
|
||||
.tools(),
|
||||
&tools_b
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_provider_reuses_equal_tools_only_within_its_scope() {
|
||||
let manager = ConnectorRuntimeManager::<TestTool>::new_without_cache();
|
||||
let context = manager.context(
|
||||
PathBuf::from("unused"),
|
||||
ConnectorRuntimeContextKey::personal(
|
||||
/*account_id*/ None, /*chatgpt_user_id*/ None,
|
||||
),
|
||||
);
|
||||
let first = context
|
||||
.clone()
|
||||
.with_live_scope("endpoint".into())
|
||||
.with_live_scope("capabilities".into());
|
||||
let second = context
|
||||
.clone()
|
||||
.with_live_scope("endpoint".into())
|
||||
.with_live_scope("capabilities".into());
|
||||
let other = context
|
||||
.clone()
|
||||
.with_live_scope("other-endpoint".into())
|
||||
.with_live_scope("capabilities".into());
|
||||
let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "search")];
|
||||
let publish = |context: &ConnectorRuntimeContext<TestTool>| {
|
||||
context.publish_runtime_if_newest_accepted(
|
||||
context.begin_fetch(ConnectorRuntimeFetchSource::Startup),
|
||||
&create_test_server_info("Apps"),
|
||||
tools.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
)
|
||||
};
|
||||
let original = publish(&first);
|
||||
let repeated = publish(&second);
|
||||
let separate = publish(&other);
|
||||
assert!(Arc::ptr_eq(
|
||||
&original.shared_tools(),
|
||||
&repeated.shared_tools()
|
||||
));
|
||||
assert_eq!(original.tools_version(), repeated.tools_version());
|
||||
assert!(!Arc::ptr_eq(
|
||||
&original.shared_tools(),
|
||||
&separate.shared_tools()
|
||||
));
|
||||
drop(first);
|
||||
drop(second);
|
||||
let restarted = context
|
||||
.with_live_scope("endpoint".into())
|
||||
.with_live_scope("capabilities".into());
|
||||
assert!(restarted.current_snapshot().is_some());
|
||||
assert!(restarted.subscribe().unwrap().borrow().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_tools_cache_is_ignored_during_initial_load() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let cache_path = context.tools_cache_path();
|
||||
std::fs::create_dir_all(cache_path.parent().expect("cache parent"))
|
||||
.expect("create cache parent");
|
||||
let file = std::fs::File::create(cache_path).expect("create oversized cache");
|
||||
file.set_len(CODEX_APPS_TOOLS_CACHE_MAX_BYTES + 1)
|
||||
.expect("size oversized cache");
|
||||
|
||||
let reloaded = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
|
||||
assert!(reloaded.current_snapshot().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cold_loaded_snapshot_uses_cache_modification_time() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let writer = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "cached")];
|
||||
write_cached_codex_apps_tools(&writer, &tools).expect("write tools cache");
|
||||
let modified_at = std::fs::metadata(writer.tools_cache_path())
|
||||
.and_then(|metadata| metadata.modified())
|
||||
.expect("cache modification time");
|
||||
|
||||
let reloaded = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let snapshot = reloaded.current_snapshot().expect("cold-loaded snapshot");
|
||||
|
||||
assert_eq!(snapshot.tools(), &tools);
|
||||
assert_eq!(snapshot.refreshed_at(), modified_at);
|
||||
}
|
||||
#[test]
|
||||
fn accepted_generations_finish_persistence_in_order() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let older_ticket = context.begin_fetch(ConnectorRuntimeFetchSource::Startup);
|
||||
let newer_ticket = context.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh);
|
||||
let (older_persisting_tx, older_persisting_rx) = std::sync::mpsc::channel();
|
||||
let (release_older_tx, release_older_rx) = std::sync::mpsc::channel();
|
||||
let older_context = context.clone();
|
||||
let older_publish = std::thread::spawn(move || {
|
||||
older_context.publish_runtime_if_newest_accepted_with(
|
||||
older_ticket,
|
||||
&create_test_server_info("Codex Apps"),
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "older")],
|
||||
/*tool_list_meta*/ None,
|
||||
move |_, _, _| {
|
||||
older_persisting_tx
|
||||
.send(())
|
||||
.expect("signal older persistence");
|
||||
release_older_rx.recv().expect("release older persistence");
|
||||
},
|
||||
)
|
||||
});
|
||||
older_persisting_rx
|
||||
.recv_timeout(Duration::from_secs(1))
|
||||
.expect("older generation should enter persistence");
|
||||
|
||||
let (newer_persisting_tx, newer_persisting_rx) = std::sync::mpsc::channel();
|
||||
let newer_context = context;
|
||||
let newer_publish = std::thread::spawn(move || {
|
||||
newer_context.publish_runtime_if_newest_accepted_with(
|
||||
newer_ticket,
|
||||
&create_test_server_info("Codex Apps"),
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "newer")],
|
||||
/*tool_list_meta*/ None,
|
||||
move |_, _, _| {
|
||||
newer_persisting_tx
|
||||
.send(())
|
||||
.expect("signal newer persistence");
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
assert!(
|
||||
newer_persisting_rx
|
||||
.recv_timeout(Duration::from_millis(20))
|
||||
.is_err()
|
||||
);
|
||||
release_older_tx
|
||||
.send(())
|
||||
.expect("allow older persistence to finish");
|
||||
newer_persisting_rx
|
||||
.recv_timeout(Duration::from_secs(1))
|
||||
.expect("newer generation should persist after older generation");
|
||||
|
||||
older_publish.join().expect("join older publish");
|
||||
let newer_snapshot = newer_publish.join().expect("join newer publish");
|
||||
assert_eq!(newer_snapshot.tools()[0].callable_name, "newer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn personal_and_workspace_contexts_are_distinct_even_with_matching_ids() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let manager = ConnectorRuntimeManager::<TestTool>::default();
|
||||
let personal_context = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account".to_string()),
|
||||
chatgpt_user_id: Some("user".to_string()),
|
||||
is_workspace_account: false,
|
||||
},
|
||||
);
|
||||
let personal_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "personal")];
|
||||
let _ = personal_context.publish_runtime_if_newest_accepted(
|
||||
personal_context.begin_fetch(ConnectorRuntimeFetchSource::Startup),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
personal_tools.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
|
||||
let workspace_context = manager.context(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorRuntimeContextKey {
|
||||
account_id: Some("account".to_string()),
|
||||
chatgpt_user_id: Some("user".to_string()),
|
||||
is_workspace_account: true,
|
||||
},
|
||||
);
|
||||
|
||||
let workspace_tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "workspace")];
|
||||
let _ = workspace_context.publish_runtime_if_newest_accepted(
|
||||
workspace_context.begin_fetch(ConnectorRuntimeFetchSource::Startup),
|
||||
&create_test_server_info("Codex Apps"),
|
||||
workspace_tools.clone(),
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(personal_context.current_tools(), Some(personal_tools));
|
||||
assert_eq!(workspace_context.current_tools(), Some(workspace_tools));
|
||||
assert_ne!(
|
||||
personal_context.tools_cache_path(),
|
||||
workspace_context.tools_cache_path()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_publish_sets_timestamp_and_stale_publish_preserves_it() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let context = create_codex_apps_tools_cache_context(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some("account-one"),
|
||||
Some("user-one"),
|
||||
);
|
||||
let stale_ticket = context.begin_fetch(ConnectorRuntimeFetchSource::Startup);
|
||||
let current_ticket = context.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh);
|
||||
let before = SystemTime::now();
|
||||
let current = context.publish_runtime_if_newest_accepted(
|
||||
current_ticket,
|
||||
&create_test_server_info("Codex Apps"),
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "current")],
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
let after = SystemTime::now();
|
||||
|
||||
assert!(current.refreshed_at() >= before);
|
||||
assert!(current.refreshed_at() <= after);
|
||||
|
||||
let stale = context.publish_runtime_if_newest_accepted(
|
||||
stale_ticket,
|
||||
&create_test_server_info("Codex Apps"),
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "stale")],
|
||||
/*tool_list_meta*/ None,
|
||||
);
|
||||
assert!(Arc::ptr_eq(¤t, &stale));
|
||||
assert_eq!(stale.refreshed_at(), current.refreshed_at());
|
||||
}
|
||||
113
codex-rs/connectors/src/directory_cache.rs
Normal file
113
codex-rs/connectors/src/directory_cache.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha1::Digest;
|
||||
use sha1::Sha1;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::AppInfo;
|
||||
use crate::ConnectorDirectoryCacheKey;
|
||||
|
||||
pub(crate) const CONNECTOR_DIRECTORY_DISK_CACHE_SCHEMA_VERSION: u8 = 1;
|
||||
const CONNECTOR_DIRECTORY_DISK_CACHE_DIR: &str = "cache/codex_app_directory";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ConnectorDirectoryCacheContext {
|
||||
pub(crate) codex_home: PathBuf,
|
||||
pub(crate) cache_key: ConnectorDirectoryCacheKey,
|
||||
}
|
||||
|
||||
impl ConnectorDirectoryCacheContext {
|
||||
pub fn new(codex_home: PathBuf, cache_key: ConnectorDirectoryCacheKey) -> Self {
|
||||
Self {
|
||||
codex_home,
|
||||
cache_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted connector directory cache path for this identity.
|
||||
pub fn cache_path(&self) -> PathBuf {
|
||||
let cache_key_json = serde_json::to_string(&self.cache_key).unwrap_or_default();
|
||||
let cache_key_hash = sha1_hex(&cache_key_json);
|
||||
self.codex_home
|
||||
.join(CONNECTOR_DIRECTORY_DISK_CACHE_DIR)
|
||||
.join(format!("{cache_key_hash}.json"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum CachedConnectorDirectoryDiskLoad {
|
||||
Hit { connectors: Vec<AppInfo> },
|
||||
Missing,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
pub(crate) fn load_cached_directory_connectors_from_disk(
|
||||
cache_context: &ConnectorDirectoryCacheContext,
|
||||
) -> CachedConnectorDirectoryDiskLoad {
|
||||
let cache_path = cache_context.cache_path();
|
||||
let bytes = match std::fs::read(&cache_path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
return CachedConnectorDirectoryDiskLoad::Missing;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to read connector directory disk cache: {err}"
|
||||
);
|
||||
return CachedConnectorDirectoryDiskLoad::Invalid;
|
||||
}
|
||||
};
|
||||
let cache: ConnectorDirectoryDiskCache = match serde_json::from_slice(&bytes) {
|
||||
Ok(cache) => cache,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to parse connector directory disk cache: {err}"
|
||||
);
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return CachedConnectorDirectoryDiskLoad::Invalid;
|
||||
}
|
||||
};
|
||||
if cache.schema_version != CONNECTOR_DIRECTORY_DISK_CACHE_SCHEMA_VERSION {
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return CachedConnectorDirectoryDiskLoad::Invalid;
|
||||
}
|
||||
|
||||
CachedConnectorDirectoryDiskLoad::Hit {
|
||||
connectors: cache.connectors,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_cached_directory_connectors_to_disk(
|
||||
cache_context: &ConnectorDirectoryCacheContext,
|
||||
connectors: &[AppInfo],
|
||||
) {
|
||||
let cache_path = cache_context.cache_path();
|
||||
if let Some(parent) = cache_path.parent()
|
||||
&& std::fs::create_dir_all(parent).is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Ok(bytes) = serde_json::to_vec_pretty(&ConnectorDirectoryDiskCache {
|
||||
schema_version: CONNECTOR_DIRECTORY_DISK_CACHE_SCHEMA_VERSION,
|
||||
connectors: connectors.to_vec(),
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::write(cache_path, bytes);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ConnectorDirectoryDiskCache {
|
||||
schema_version: u8,
|
||||
connectors: Vec<AppInfo>,
|
||||
}
|
||||
|
||||
fn sha1_hex(value: &str) -> String {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(value.as_bytes());
|
||||
let sha1 = hasher.finalize();
|
||||
format!("{sha1:x}")
|
||||
}
|
||||
144
codex-rs/connectors/src/filter.rs
Normal file
144
codex-rs/connectors/src/filter.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::AppInfo;
|
||||
use crate::merge::plugin_connector_to_app_info;
|
||||
|
||||
/// Load the directory only when a candidate still needs to be suggested.
|
||||
pub async fn filter_tool_suggest_discoverable_connectors(
|
||||
directory_connectors: impl Future<Output = Arc<[AppInfo]>>,
|
||||
accessible_connectors: &[AppInfo],
|
||||
mut discoverable_connector_ids: HashSet<String>,
|
||||
) -> Vec<AppInfo> {
|
||||
for connector in accessible_connectors {
|
||||
if connector.is_accessible {
|
||||
discoverable_connector_ids.remove(&connector.id);
|
||||
}
|
||||
}
|
||||
if discoverable_connector_ids.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut connectors = Vec::with_capacity(discoverable_connector_ids.len());
|
||||
connectors.extend(
|
||||
directory_connectors
|
||||
.await
|
||||
.iter()
|
||||
.filter(|connector| discoverable_connector_ids.contains(&connector.id))
|
||||
.cloned(),
|
||||
);
|
||||
for connector in &connectors {
|
||||
discoverable_connector_ids.remove(&connector.id);
|
||||
}
|
||||
connectors.extend(
|
||||
discoverable_connector_ids
|
||||
.into_iter()
|
||||
.map(plugin_connector_to_app_info),
|
||||
);
|
||||
connectors.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
connectors
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::metadata::connector_install_url;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn app(id: &str) -> AppInfo {
|
||||
AppInfo {
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
description: None,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: None,
|
||||
install_url: None,
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
is_accessible: false,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn named_app(id: &str, name: &str) -> AppInfo {
|
||||
AppInfo {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
install_url: Some(connector_install_url(name, id)),
|
||||
..app(id)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn filter_tool_suggest_discoverable_connectors_keeps_only_plugin_backed_uninstalled_apps()
|
||||
{
|
||||
let filtered = filter_tool_suggest_discoverable_connectors(
|
||||
std::future::ready(Arc::from([
|
||||
named_app(
|
||||
"connector_2128aebfecb84f64a069897515042a44",
|
||||
"Google Calendar",
|
||||
),
|
||||
named_app("connector_68df038e0ba48191908c8434991bbac2", "Gmail"),
|
||||
named_app("connector_other", "Other"),
|
||||
])),
|
||||
&[AppInfo {
|
||||
is_accessible: true,
|
||||
..named_app(
|
||||
"connector_2128aebfecb84f64a069897515042a44",
|
||||
"Google Calendar",
|
||||
)
|
||||
}],
|
||||
HashSet::from([
|
||||
"connector_2128aebfecb84f64a069897515042a44".to_string(),
|
||||
"connector_68df038e0ba48191908c8434991bbac2".to_string(),
|
||||
"connector_missing".to_string(),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
filtered,
|
||||
vec![
|
||||
named_app("connector_68df038e0ba48191908c8434991bbac2", "Gmail"),
|
||||
plugin_connector_to_app_info("connector_missing".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skips_directory_when_no_connectors_can_be_suggested() {
|
||||
let accessible = [
|
||||
AppInfo {
|
||||
is_accessible: true,
|
||||
..app("calendar")
|
||||
},
|
||||
AppInfo {
|
||||
is_accessible: true,
|
||||
is_enabled: false,
|
||||
..app("gmail")
|
||||
},
|
||||
];
|
||||
for candidates in [
|
||||
HashSet::new(),
|
||||
HashSet::from(["calendar".to_string(), "gmail".to_string()]),
|
||||
] {
|
||||
let filtered = filter_tool_suggest_discoverable_connectors(
|
||||
async { panic!("unexpected connector directory lookup") },
|
||||
&accessible,
|
||||
candidates,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(filtered, Vec::<AppInfo>::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
996
codex-rs/connectors/src/lib.rs
Normal file
996
codex-rs/connectors/src/lib.rs
Normal file
@@ -0,0 +1,996 @@
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
pub mod accessible;
|
||||
mod app_info;
|
||||
mod app_tool_policy;
|
||||
mod connector_runtime;
|
||||
mod directory_cache;
|
||||
pub mod filter;
|
||||
pub mod merge;
|
||||
pub mod metadata;
|
||||
mod metadata_store;
|
||||
mod plugin_config;
|
||||
mod runtime_projection;
|
||||
mod snapshot;
|
||||
|
||||
pub use app_info::AppBranding;
|
||||
pub use app_info::AppInfo;
|
||||
pub use app_info::AppMetadata;
|
||||
pub use app_info::AppReview;
|
||||
pub use app_info::AppScreenshot;
|
||||
pub use app_tool_policy::AppToolPolicy;
|
||||
pub use app_tool_policy::AppToolPolicyEvaluator;
|
||||
pub use app_tool_policy::AppToolPolicyInput;
|
||||
pub use app_tool_policy::app_is_enabled;
|
||||
pub use app_tool_policy::apps_config_from_layer_stack;
|
||||
pub use app_tool_policy::apps_config_origins_from_layer_stack;
|
||||
pub use connector_runtime::ConnectorRuntimeContext;
|
||||
pub use connector_runtime::ConnectorRuntimeContextKey;
|
||||
pub use connector_runtime::ConnectorRuntimeFetchSource;
|
||||
pub use connector_runtime::ConnectorRuntimeFetchTicket;
|
||||
pub use connector_runtime::ConnectorRuntimeManager;
|
||||
pub use connector_runtime::ConnectorRuntimePayload;
|
||||
pub use connector_runtime::ConnectorRuntimeSnapshot;
|
||||
pub use connector_runtime::connector_runtime_cache_path;
|
||||
pub use connector_runtime::connector_runtime_context_key;
|
||||
pub use directory_cache::ConnectorDirectoryCacheContext;
|
||||
pub use metadata_store::ConnectorMetadata;
|
||||
pub use metadata_store::ConnectorMetadataStore;
|
||||
pub use metadata_store::ConnectorToolSummary;
|
||||
pub use plugin_config::parse_plugin_app_config;
|
||||
pub use plugin_config::parse_plugin_app_config_value;
|
||||
pub use runtime_projection::ConnectorRuntimeTool;
|
||||
pub use runtime_projection::InstalledConnectorRuntime;
|
||||
pub use runtime_projection::connector_tool_is_synthetic;
|
||||
pub use runtime_projection::installed_connector_runtime;
|
||||
pub use snapshot::ConnectorSnapshot;
|
||||
pub use snapshot::PluginConnectorSource;
|
||||
|
||||
pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600);
|
||||
/// TTL for app/read metadata; it starts aligned with the connector directory cache.
|
||||
pub const CONNECTOR_METADATA_CACHE_TTL: Duration = CONNECTORS_CACHE_TTL;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ConnectorDirectoryCacheKey {
|
||||
chatgpt_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
}
|
||||
|
||||
impl ConnectorDirectoryCacheKey {
|
||||
pub fn new(
|
||||
chatgpt_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
chatgpt_base_url,
|
||||
account_id,
|
||||
chatgpt_user_id,
|
||||
is_workspace_account,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedConnectorDirectory {
|
||||
key: ConnectorDirectoryCacheKey,
|
||||
expires_at: Instant,
|
||||
connectors: Arc<[AppInfo]>,
|
||||
}
|
||||
|
||||
static CONNECTOR_DIRECTORY_CACHE: LazyLock<StdMutex<Option<CachedConnectorDirectory>>> =
|
||||
LazyLock::new(|| StdMutex::new(None));
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DirectoryListResponse {
|
||||
apps: Vec<DirectoryApp>,
|
||||
#[serde(alias = "nextToken")]
|
||||
next_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
pub struct DirectoryApp {
|
||||
id: String,
|
||||
name: String,
|
||||
description: Option<String>,
|
||||
#[serde(alias = "appMetadata")]
|
||||
app_metadata: Option<AppMetadata>,
|
||||
branding: Option<AppBranding>,
|
||||
labels: Option<HashMap<String, String>>,
|
||||
#[serde(alias = "logoUrl")]
|
||||
logo_url: Option<String>,
|
||||
#[serde(alias = "logoUrlDark")]
|
||||
logo_url_dark: Option<String>,
|
||||
#[serde(alias = "iconAssets")]
|
||||
icon_assets: Option<HashMap<String, String>>,
|
||||
#[serde(alias = "iconDarkAssets")]
|
||||
icon_dark_assets: Option<HashMap<String, String>>,
|
||||
#[serde(alias = "distributionChannel")]
|
||||
distribution_channel: Option<String>,
|
||||
visibility: Option<String>,
|
||||
}
|
||||
|
||||
pub fn cached_directory_connectors(
|
||||
cache_context: &ConnectorDirectoryCacheContext,
|
||||
) -> Option<Arc<[AppInfo]>> {
|
||||
if let Some(cached_connectors) = cached_directory_connectors_in_memory(&cache_context.cache_key)
|
||||
{
|
||||
return Some(cached_connectors);
|
||||
}
|
||||
|
||||
let directory_cache::CachedConnectorDirectoryDiskLoad::Hit { connectors } =
|
||||
directory_cache::load_cached_directory_connectors_from_disk(cache_context)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let connectors = Arc::from(connectors);
|
||||
write_cached_directory_connectors_in_memory(
|
||||
cache_context.cache_key.clone(),
|
||||
Arc::clone(&connectors),
|
||||
Duration::ZERO,
|
||||
);
|
||||
Some(connectors)
|
||||
}
|
||||
|
||||
fn cached_directory_connectors_in_memory(
|
||||
cache_key: &ConnectorDirectoryCacheKey,
|
||||
) -> Option<Arc<[AppInfo]>> {
|
||||
let cache_guard = CONNECTOR_DIRECTORY_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
cache_guard
|
||||
.as_ref()
|
||||
.filter(|cached| cached.key == *cache_key)
|
||||
.map(|cached| Arc::clone(&cached.connectors))
|
||||
}
|
||||
|
||||
fn unexpired_directory_connectors_in_memory(
|
||||
cache_key: &ConnectorDirectoryCacheKey,
|
||||
) -> Option<Arc<[AppInfo]>> {
|
||||
let cache_guard = CONNECTOR_DIRECTORY_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let cached = cache_guard.as_ref()?;
|
||||
if cached.key == *cache_key && Instant::now() < cached.expires_at {
|
||||
return Some(Arc::clone(&cached.connectors));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn list_all_connectors_with_options<F, Fut>(
|
||||
cache_context: ConnectorDirectoryCacheContext,
|
||||
is_workspace_account: bool,
|
||||
force_refetch: bool,
|
||||
mut fetch_page: F,
|
||||
) -> anyhow::Result<Vec<AppInfo>>
|
||||
where
|
||||
F: FnMut(String) -> Fut,
|
||||
Fut: Future<Output = anyhow::Result<DirectoryListResponse>>,
|
||||
{
|
||||
if !force_refetch
|
||||
&& let Some(cached_connectors) =
|
||||
unexpired_directory_connectors_in_memory(&cache_context.cache_key)
|
||||
{
|
||||
return Ok(cached_connectors.to_vec());
|
||||
}
|
||||
|
||||
let apps = if is_workspace_account {
|
||||
// The workspace directory is independent from the paginated public directory.
|
||||
// Start both before awaiting either so workspace accounts do not pay for the
|
||||
// two request chains back-to-back.
|
||||
let workspace_connectors =
|
||||
fetch_page("/connectors/directory/list_workspace?external_logos=true".to_string());
|
||||
let directory_connectors = list_directory_connectors(&mut fetch_page);
|
||||
let (directory_connectors, workspace_connectors) =
|
||||
tokio::join!(directory_connectors, workspace_connectors);
|
||||
let mut apps = directory_connectors?;
|
||||
if let Ok(response) = workspace_connectors {
|
||||
apps.extend(
|
||||
response
|
||||
.apps
|
||||
.into_iter()
|
||||
.filter(|app| !is_hidden_directory_app(app)),
|
||||
);
|
||||
}
|
||||
apps
|
||||
} else {
|
||||
list_directory_connectors(&mut fetch_page).await?
|
||||
};
|
||||
|
||||
let mut connectors = merge_directory_apps(apps)
|
||||
.into_iter()
|
||||
.map(directory_app_to_app_info)
|
||||
.collect::<Vec<_>>();
|
||||
for connector in &mut connectors {
|
||||
let install_url = match connector.install_url.take() {
|
||||
Some(install_url) => install_url,
|
||||
None => connector_install_url(&connector.name, &connector.id),
|
||||
};
|
||||
connector.name = normalize_connector_name(&connector.name, &connector.id);
|
||||
connector.description = normalize_connector_value(connector.description.as_deref());
|
||||
connector.install_url = Some(install_url);
|
||||
connector.is_accessible = false;
|
||||
}
|
||||
connectors.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
write_cached_directory_connectors(&cache_context, &connectors);
|
||||
Ok(connectors)
|
||||
}
|
||||
|
||||
fn write_cached_directory_connectors(
|
||||
cache_context: &ConnectorDirectoryCacheContext,
|
||||
connectors: &[AppInfo],
|
||||
) {
|
||||
write_cached_directory_connectors_in_memory(
|
||||
cache_context.cache_key.clone(),
|
||||
Arc::from(connectors),
|
||||
CONNECTORS_CACHE_TTL,
|
||||
);
|
||||
directory_cache::write_cached_directory_connectors_to_disk(cache_context, connectors);
|
||||
}
|
||||
|
||||
fn write_cached_directory_connectors_in_memory(
|
||||
cache_key: ConnectorDirectoryCacheKey,
|
||||
connectors: Arc<[AppInfo]>,
|
||||
ttl: Duration,
|
||||
) {
|
||||
let mut cache_guard = CONNECTOR_DIRECTORY_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*cache_guard = Some(CachedConnectorDirectory {
|
||||
key: cache_key,
|
||||
expires_at: Instant::now() + ttl,
|
||||
connectors,
|
||||
});
|
||||
}
|
||||
|
||||
async fn list_directory_connectors<F, Fut>(fetch_page: &mut F) -> anyhow::Result<Vec<DirectoryApp>>
|
||||
where
|
||||
F: FnMut(String) -> Fut,
|
||||
Fut: Future<Output = anyhow::Result<DirectoryListResponse>>,
|
||||
{
|
||||
let mut apps = Vec::new();
|
||||
let mut next_token: Option<String> = None;
|
||||
loop {
|
||||
let path = match next_token.as_deref() {
|
||||
Some(token) => {
|
||||
let encoded_token = urlencoding::encode(token);
|
||||
format!("/connectors/directory/list?token={encoded_token}&external_logos=true")
|
||||
}
|
||||
None => "/connectors/directory/list?external_logos=true".to_string(),
|
||||
};
|
||||
let response = fetch_page(path).await?;
|
||||
apps.extend(
|
||||
response
|
||||
.apps
|
||||
.into_iter()
|
||||
.filter(|app| !is_hidden_directory_app(app)),
|
||||
);
|
||||
next_token = response
|
||||
.next_token
|
||||
.map(|token| token.trim().to_string())
|
||||
.filter(|token| !token.is_empty());
|
||||
if next_token.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn merge_directory_apps(apps: Vec<DirectoryApp>) -> Vec<DirectoryApp> {
|
||||
let mut merged: HashMap<String, DirectoryApp> = HashMap::new();
|
||||
for app in apps {
|
||||
if let Some(existing) = merged.get_mut(&app.id) {
|
||||
merge_directory_app(existing, app);
|
||||
} else {
|
||||
merged.insert(app.id.clone(), app);
|
||||
}
|
||||
}
|
||||
merged.into_values().collect()
|
||||
}
|
||||
|
||||
fn merge_directory_app(existing: &mut DirectoryApp, incoming: DirectoryApp) {
|
||||
let DirectoryApp {
|
||||
id: _,
|
||||
name,
|
||||
description,
|
||||
app_metadata,
|
||||
branding,
|
||||
labels,
|
||||
logo_url,
|
||||
logo_url_dark,
|
||||
icon_assets,
|
||||
icon_dark_assets,
|
||||
distribution_channel,
|
||||
visibility: _,
|
||||
} = incoming;
|
||||
|
||||
let incoming_name_is_empty = name.trim().is_empty();
|
||||
if existing.name.trim().is_empty() && !incoming_name_is_empty {
|
||||
existing.name = name;
|
||||
}
|
||||
|
||||
let incoming_description_present = description
|
||||
.as_deref()
|
||||
.map(|value| !value.trim().is_empty())
|
||||
.unwrap_or(false);
|
||||
if incoming_description_present {
|
||||
existing.description = description;
|
||||
}
|
||||
|
||||
if existing.logo_url.is_none() && logo_url.is_some() {
|
||||
existing.logo_url = logo_url;
|
||||
}
|
||||
if existing.logo_url_dark.is_none() && logo_url_dark.is_some() {
|
||||
existing.logo_url_dark = logo_url_dark;
|
||||
}
|
||||
if existing.icon_assets.as_ref().is_none_or(HashMap::is_empty)
|
||||
&& icon_assets
|
||||
.as_ref()
|
||||
.is_some_and(|assets| !assets.is_empty())
|
||||
{
|
||||
existing.icon_assets = icon_assets;
|
||||
}
|
||||
if existing
|
||||
.icon_dark_assets
|
||||
.as_ref()
|
||||
.is_none_or(HashMap::is_empty)
|
||||
&& icon_dark_assets
|
||||
.as_ref()
|
||||
.is_some_and(|assets| !assets.is_empty())
|
||||
{
|
||||
existing.icon_dark_assets = icon_dark_assets;
|
||||
}
|
||||
if existing.distribution_channel.is_none() && distribution_channel.is_some() {
|
||||
existing.distribution_channel = distribution_channel;
|
||||
}
|
||||
|
||||
if let Some(incoming_branding) = branding {
|
||||
if let Some(existing_branding) = existing.branding.as_mut() {
|
||||
if existing_branding.category.is_none() && incoming_branding.category.is_some() {
|
||||
existing_branding.category = incoming_branding.category;
|
||||
}
|
||||
if existing_branding.developer.is_none() && incoming_branding.developer.is_some() {
|
||||
existing_branding.developer = incoming_branding.developer;
|
||||
}
|
||||
if existing_branding.website.is_none() && incoming_branding.website.is_some() {
|
||||
existing_branding.website = incoming_branding.website;
|
||||
}
|
||||
if existing_branding.privacy_policy.is_none()
|
||||
&& incoming_branding.privacy_policy.is_some()
|
||||
{
|
||||
existing_branding.privacy_policy = incoming_branding.privacy_policy;
|
||||
}
|
||||
if existing_branding.terms_of_service.is_none()
|
||||
&& incoming_branding.terms_of_service.is_some()
|
||||
{
|
||||
existing_branding.terms_of_service = incoming_branding.terms_of_service;
|
||||
}
|
||||
if !existing_branding.is_discoverable_app && incoming_branding.is_discoverable_app {
|
||||
existing_branding.is_discoverable_app = true;
|
||||
}
|
||||
} else {
|
||||
existing.branding = Some(incoming_branding);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(incoming_app_metadata) = app_metadata {
|
||||
if let Some(existing_app_metadata) = existing.app_metadata.as_mut() {
|
||||
if existing_app_metadata.review.is_none() && incoming_app_metadata.review.is_some() {
|
||||
existing_app_metadata.review = incoming_app_metadata.review;
|
||||
}
|
||||
if existing_app_metadata.categories.is_none()
|
||||
&& incoming_app_metadata.categories.is_some()
|
||||
{
|
||||
existing_app_metadata.categories = incoming_app_metadata.categories;
|
||||
}
|
||||
if existing_app_metadata.sub_categories.is_none()
|
||||
&& incoming_app_metadata.sub_categories.is_some()
|
||||
{
|
||||
existing_app_metadata.sub_categories = incoming_app_metadata.sub_categories;
|
||||
}
|
||||
if existing_app_metadata.seo_description.is_none()
|
||||
&& incoming_app_metadata.seo_description.is_some()
|
||||
{
|
||||
existing_app_metadata.seo_description = incoming_app_metadata.seo_description;
|
||||
}
|
||||
if existing_app_metadata.screenshots.is_none()
|
||||
&& incoming_app_metadata.screenshots.is_some()
|
||||
{
|
||||
existing_app_metadata.screenshots = incoming_app_metadata.screenshots;
|
||||
}
|
||||
if existing_app_metadata.developer.is_none()
|
||||
&& incoming_app_metadata.developer.is_some()
|
||||
{
|
||||
existing_app_metadata.developer = incoming_app_metadata.developer;
|
||||
}
|
||||
if existing_app_metadata.version.is_none() && incoming_app_metadata.version.is_some() {
|
||||
existing_app_metadata.version = incoming_app_metadata.version;
|
||||
}
|
||||
if existing_app_metadata.version_id.is_none()
|
||||
&& incoming_app_metadata.version_id.is_some()
|
||||
{
|
||||
existing_app_metadata.version_id = incoming_app_metadata.version_id;
|
||||
}
|
||||
if existing_app_metadata.version_notes.is_none()
|
||||
&& incoming_app_metadata.version_notes.is_some()
|
||||
{
|
||||
existing_app_metadata.version_notes = incoming_app_metadata.version_notes;
|
||||
}
|
||||
if existing_app_metadata.first_party_requires_install.is_none()
|
||||
&& incoming_app_metadata.first_party_requires_install.is_some()
|
||||
{
|
||||
existing_app_metadata.first_party_requires_install =
|
||||
incoming_app_metadata.first_party_requires_install;
|
||||
}
|
||||
if existing_app_metadata
|
||||
.show_in_composer_when_unlinked
|
||||
.is_none()
|
||||
&& incoming_app_metadata
|
||||
.show_in_composer_when_unlinked
|
||||
.is_some()
|
||||
{
|
||||
existing_app_metadata.show_in_composer_when_unlinked =
|
||||
incoming_app_metadata.show_in_composer_when_unlinked;
|
||||
}
|
||||
} else {
|
||||
existing.app_metadata = Some(incoming_app_metadata);
|
||||
}
|
||||
}
|
||||
|
||||
if existing.labels.is_none() && labels.is_some() {
|
||||
existing.labels = labels;
|
||||
}
|
||||
}
|
||||
|
||||
fn is_hidden_directory_app(app: &DirectoryApp) -> bool {
|
||||
matches!(app.visibility.as_deref(), Some("HIDDEN"))
|
||||
}
|
||||
|
||||
fn directory_app_to_app_info(app: DirectoryApp) -> AppInfo {
|
||||
AppInfo {
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
description: app.description,
|
||||
logo_url: app.logo_url,
|
||||
logo_url_dark: app.logo_url_dark,
|
||||
icon_assets: app.icon_assets,
|
||||
icon_dark_assets: app.icon_dark_assets,
|
||||
distribution_channel: app.distribution_channel,
|
||||
branding: app.branding,
|
||||
app_metadata: app.app_metadata,
|
||||
labels: app.labels,
|
||||
install_url: None,
|
||||
is_accessible: false,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_install_url(name: &str, connector_id: &str) -> String {
|
||||
let chatgpt_base_url = std::env::var("CODEX_APP_SERVER_CHATGPT_BASE_URL")
|
||||
.unwrap_or_else(|_| "https://chatgpt.com".to_string());
|
||||
let chatgpt_origin = chatgpt_base_url
|
||||
.trim_end_matches('/')
|
||||
.trim_end_matches("/backend-api");
|
||||
let slug = connector_name_slug(name);
|
||||
format!("{chatgpt_origin}/apps/{slug}/{connector_id}")
|
||||
}
|
||||
|
||||
fn connector_name_slug(name: &str) -> String {
|
||||
let mut normalized = String::with_capacity(name.len());
|
||||
for character in name.chars() {
|
||||
if character.is_ascii_alphanumeric() {
|
||||
normalized.push(character.to_ascii_lowercase());
|
||||
} else {
|
||||
normalized.push('-');
|
||||
}
|
||||
}
|
||||
let normalized = normalized.trim_matches('-');
|
||||
if normalized.is_empty() {
|
||||
"app".to_string()
|
||||
} else {
|
||||
normalized.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_connector_name(name: &str, connector_id: &str) -> String {
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() {
|
||||
connector_id.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_connector_value(value: Option<&str>) -> Option<String> {
|
||||
value
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
static CONNECTOR_DIRECTORY_CACHE_TEST_LOCK: LazyLock<tokio::sync::Mutex<()>> =
|
||||
LazyLock::new(|| tokio::sync::Mutex::new(()));
|
||||
|
||||
fn cache_key(id: &str) -> ConnectorDirectoryCacheKey {
|
||||
ConnectorDirectoryCacheKey::new(
|
||||
"https://chatgpt.example".to_string(),
|
||||
Some(format!("account-{id}")),
|
||||
Some(format!("user-{id}")),
|
||||
/*is_workspace_account*/ true,
|
||||
)
|
||||
}
|
||||
|
||||
fn cache_context(codex_home: &TempDir, id: &str) -> ConnectorDirectoryCacheContext {
|
||||
ConnectorDirectoryCacheContext::new(codex_home.path().to_path_buf(), cache_key(id))
|
||||
}
|
||||
|
||||
fn clear_directory_memory_cache() {
|
||||
let mut cache_guard = CONNECTOR_DIRECTORY_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*cache_guard = None;
|
||||
}
|
||||
|
||||
fn app(id: &str, name: &str) -> DirectoryApp {
|
||||
DirectoryApp {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
description: None,
|
||||
app_metadata: None,
|
||||
branding: None,
|
||||
labels: None,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: None,
|
||||
visibility: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connector_install_url_uses_configured_origin() {
|
||||
let chatgpt_base_url = std::env::var("CODEX_APP_SERVER_CHATGPT_BASE_URL")
|
||||
.unwrap_or_else(|_| "https://chatgpt.com".to_string());
|
||||
let chatgpt_origin = chatgpt_base_url
|
||||
.trim_end_matches('/')
|
||||
.trim_end_matches("/backend-api");
|
||||
assert_eq!(
|
||||
connector_install_url("Google Calendar", "calendar"),
|
||||
format!("{chatgpt_origin}/apps/google-calendar/calendar"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_app_icon_assets_reach_app_info() -> anyhow::Result<()> {
|
||||
let response: DirectoryListResponse = serde_json::from_value(serde_json::json!({
|
||||
"apps": [{
|
||||
"id": "alpha",
|
||||
"name": "Alpha",
|
||||
"icon_assets": {},
|
||||
"icon_dark_assets": {}
|
||||
}, {
|
||||
"id": "alpha",
|
||||
"name": "",
|
||||
"icon_assets": {
|
||||
"256_square": "https://example.com/alpha-square.png"
|
||||
},
|
||||
"icon_dark_assets": {
|
||||
"256_square": "https://example.com/alpha-square-dark.png"
|
||||
}
|
||||
}],
|
||||
"next_token": null
|
||||
}))?;
|
||||
|
||||
let app_info = directory_app_to_app_info(merge_directory_apps(response.apps).remove(0));
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(app_info)?,
|
||||
serde_json::json!({
|
||||
"id": "alpha",
|
||||
"name": "Alpha",
|
||||
"description": null,
|
||||
"logoUrl": null,
|
||||
"logoUrlDark": null,
|
||||
"iconAssets": {
|
||||
"256_square": "https://example.com/alpha-square.png"
|
||||
},
|
||||
"iconDarkAssets": {
|
||||
"256_square": "https://example.com/alpha-square-dark.png"
|
||||
},
|
||||
"distributionChannel": null,
|
||||
"branding": null,
|
||||
"appMetadata": null,
|
||||
"labels": null,
|
||||
"installUrl": null,
|
||||
"isAccessible": false,
|
||||
"isEnabled": true,
|
||||
"pluginDisplayNames": []
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "test serializes access to the shared connector cache for its full duration"
|
||||
)]
|
||||
async fn list_all_connectors_uses_shared_directory_cache() -> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let call_counter = Arc::clone(&calls);
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "shared");
|
||||
|
||||
let first = list_all_connectors_with_options(
|
||||
cache_context.clone(),
|
||||
/*is_workspace_account*/ false,
|
||||
/*force_refetch*/ false,
|
||||
move |_path| {
|
||||
let call_counter = Arc::clone(&call_counter);
|
||||
async move {
|
||||
call_counter.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("alpha", "Alpha")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let second = list_all_connectors_with_options(
|
||||
cache_context,
|
||||
/*is_workspace_account*/ false,
|
||||
/*force_refetch*/ false,
|
||||
move |_path| async move {
|
||||
anyhow::bail!("cache should have been used");
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(first, second);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "test serializes access to the shared connector cache for its full duration"
|
||||
)]
|
||||
async fn list_all_connectors_merges_and_normalizes_directory_apps() -> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "merged");
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let call_counter = Arc::clone(&calls);
|
||||
|
||||
let connectors = list_all_connectors_with_options(
|
||||
cache_context,
|
||||
/*is_workspace_account*/ true,
|
||||
/*force_refetch*/ true,
|
||||
move |path| {
|
||||
let call_counter = Arc::clone(&call_counter);
|
||||
async move {
|
||||
call_counter.fetch_add(1, Ordering::SeqCst);
|
||||
if path.starts_with("/connectors/directory/list_workspace") {
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![
|
||||
DirectoryApp {
|
||||
description: Some("Merged description".to_string()),
|
||||
branding: Some(AppBranding {
|
||||
category: Some("calendar".to_string()),
|
||||
developer: None,
|
||||
website: None,
|
||||
privacy_policy: None,
|
||||
terms_of_service: None,
|
||||
is_discoverable_app: true,
|
||||
}),
|
||||
..app("alpha", "")
|
||||
},
|
||||
DirectoryApp {
|
||||
visibility: Some("HIDDEN".to_string()),
|
||||
..app("hidden", "Hidden")
|
||||
},
|
||||
],
|
||||
next_token: None,
|
||||
})
|
||||
} else {
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("alpha", " Alpha "), app("beta", "Beta")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(connectors.len(), 2);
|
||||
assert_eq!(connectors[0].id, "alpha");
|
||||
assert_eq!(connectors[0].name, "Alpha");
|
||||
assert_eq!(
|
||||
connectors[0].description.as_deref(),
|
||||
Some("Merged description")
|
||||
);
|
||||
assert_eq!(
|
||||
connectors[0].install_url.as_deref(),
|
||||
Some("https://chatgpt.com/apps/alpha/alpha")
|
||||
);
|
||||
assert_eq!(
|
||||
connectors[0]
|
||||
.branding
|
||||
.as_ref()
|
||||
.and_then(|branding| branding.category.as_deref()),
|
||||
Some("calendar")
|
||||
);
|
||||
assert_eq!(connectors[1].id, "beta");
|
||||
assert_eq!(connectors[1].name, "Beta");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "test serializes access to the shared connector cache for its full duration"
|
||||
)]
|
||||
async fn list_all_connectors_overlaps_workspace_and_directory_requests() -> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "overlap");
|
||||
let workspace_started = Arc::new(Notify::new());
|
||||
|
||||
// The public directory response waits until the workspace request is polled.
|
||||
// Without overlap this future cannot complete; the timeout only bounds a
|
||||
// regression instead of supplying the ordering.
|
||||
let connectors = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
list_all_connectors_with_options(
|
||||
cache_context,
|
||||
/*is_workspace_account*/ true,
|
||||
/*force_refetch*/ true,
|
||||
move |path| {
|
||||
let workspace_started = Arc::clone(&workspace_started);
|
||||
async move {
|
||||
if path.starts_with("/connectors/directory/list_workspace") {
|
||||
workspace_started.notify_one();
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("workspace", "Workspace")],
|
||||
next_token: None,
|
||||
})
|
||||
} else {
|
||||
workspace_started.notified().await;
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("directory", "Directory")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("workspace request should start while directory request is pending")?;
|
||||
|
||||
assert_eq!(
|
||||
connectors
|
||||
.into_iter()
|
||||
.map(|connector| connector.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["directory".to_string(), "workspace".to_string()]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "test serializes access to the shared connector cache for its full duration"
|
||||
)]
|
||||
async fn cached_directory_connectors_reads_directory_disk_cache() -> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "disk");
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let call_counter = Arc::clone(&calls);
|
||||
|
||||
let first = list_all_connectors_with_options(
|
||||
cache_context.clone(),
|
||||
/*is_workspace_account*/ false,
|
||||
/*force_refetch*/ false,
|
||||
move |_path| {
|
||||
let call_counter = Arc::clone(&call_counter);
|
||||
async move {
|
||||
call_counter.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("alpha", "Alpha")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
clear_directory_memory_cache();
|
||||
|
||||
let second = cached_directory_connectors(&cache_context).expect("disk cache should load");
|
||||
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(first.as_slice(), second.as_ref());
|
||||
let cached = cached_directory_connectors(&cache_context).expect("memory cache should hit");
|
||||
assert!(Arc::ptr_eq(&second, &cached));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "test serializes access to the shared connector cache for its full duration"
|
||||
)]
|
||||
async fn list_all_connectors_refreshes_when_only_directory_disk_cache_exists()
|
||||
-> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "disk-refresh");
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let call_counter = Arc::clone(&calls);
|
||||
|
||||
list_all_connectors_with_options(
|
||||
cache_context.clone(),
|
||||
/*is_workspace_account*/ false,
|
||||
/*force_refetch*/ false,
|
||||
move |_path| {
|
||||
let call_counter = Arc::clone(&call_counter);
|
||||
async move {
|
||||
call_counter.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("alpha", "Alpha")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
clear_directory_memory_cache();
|
||||
let mut cached_expected = directory_app_to_app_info(app("alpha", "Alpha"));
|
||||
cached_expected.install_url = Some(connector_install_url(
|
||||
&cached_expected.name,
|
||||
&cached_expected.id,
|
||||
));
|
||||
assert_eq!(
|
||||
cached_directory_connectors(&cache_context).as_deref(),
|
||||
Some([cached_expected].as_slice())
|
||||
);
|
||||
let refreshed_calls = Arc::clone(&calls);
|
||||
|
||||
let refreshed = list_all_connectors_with_options(
|
||||
cache_context,
|
||||
/*is_workspace_account*/ false,
|
||||
/*force_refetch*/ false,
|
||||
move |_path| {
|
||||
let call_counter = Arc::clone(&refreshed_calls);
|
||||
async move {
|
||||
call_counter.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("beta", "Beta")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut expected = directory_app_to_app_info(app("beta", "Beta"));
|
||||
expected.install_url = Some(connector_install_url(&expected.name, &expected.id));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(refreshed, vec![expected]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_directory_connectors_drops_stale_disk_schema() -> anyhow::Result<()> {
|
||||
let _cache_guard = CONNECTOR_DIRECTORY_CACHE_TEST_LOCK.lock().await;
|
||||
|
||||
clear_directory_memory_cache();
|
||||
let codex_home = TempDir::new()?;
|
||||
let cache_context = cache_context(&codex_home, "stale-schema");
|
||||
let cache_path = cache_context.cache_path();
|
||||
std::fs::create_dir_all(cache_path.parent().expect("cache parent"))?;
|
||||
std::fs::write(
|
||||
&cache_path,
|
||||
serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"schema_version": 0,
|
||||
"connectors": [],
|
||||
}))?,
|
||||
)?;
|
||||
|
||||
assert_eq!(cached_directory_connectors(&cache_context), None);
|
||||
assert!(!cache_path.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_directory_connectors_omits_tier_for_all_pages() -> anyhow::Result<()> {
|
||||
let requested_paths: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
let paths = Arc::clone(&requested_paths);
|
||||
|
||||
let apps = list_directory_connectors(&mut move |path| {
|
||||
let paths = Arc::clone(&paths);
|
||||
async move {
|
||||
paths
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(path.clone());
|
||||
if path == "/connectors/directory/list?external_logos=true" {
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("alpha", "Alpha")],
|
||||
next_token: Some("page 2".to_string()),
|
||||
})
|
||||
} else {
|
||||
assert_eq!(
|
||||
path,
|
||||
"/connectors/directory/list?token=page%202&external_logos=true"
|
||||
);
|
||||
Ok(DirectoryListResponse {
|
||||
apps: vec![app("beta", "Beta")],
|
||||
next_token: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
apps.iter().map(|app| app.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["alpha", "beta"]
|
||||
);
|
||||
assert_eq!(
|
||||
requested_paths
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_slice(),
|
||||
&[
|
||||
"/connectors/directory/list?external_logos=true".to_string(),
|
||||
"/connectors/directory/list?token=page%202&external_logos=true".to_string(),
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
220
codex-rs/connectors/src/merge.rs
Normal file
220
codex-rs/connectors/src/merge.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::AppInfo;
|
||||
use crate::metadata::connector_install_url;
|
||||
use crate::metadata::sort_connectors_by_accessibility_and_name;
|
||||
|
||||
pub fn merge_connectors(
|
||||
connectors: Vec<AppInfo>,
|
||||
accessible_connectors: Vec<AppInfo>,
|
||||
) -> Vec<AppInfo> {
|
||||
let mut merged: HashMap<String, AppInfo> = connectors
|
||||
.into_iter()
|
||||
.map(|mut connector| {
|
||||
connector.is_accessible = false;
|
||||
(connector.id.clone(), connector)
|
||||
})
|
||||
.collect();
|
||||
|
||||
for mut connector in accessible_connectors {
|
||||
connector.is_accessible = true;
|
||||
let connector_id = connector.id.clone();
|
||||
if let Some(existing) = merged.get_mut(&connector_id) {
|
||||
existing.is_accessible = true;
|
||||
if existing.name == existing.id && connector.name != connector.id {
|
||||
existing.name = connector.name;
|
||||
}
|
||||
if existing.description.is_none() && connector.description.is_some() {
|
||||
existing.description = connector.description;
|
||||
}
|
||||
if existing.logo_url.is_none() && connector.logo_url.is_some() {
|
||||
existing.logo_url = connector.logo_url;
|
||||
}
|
||||
if existing.logo_url_dark.is_none() && connector.logo_url_dark.is_some() {
|
||||
existing.logo_url_dark = connector.logo_url_dark;
|
||||
}
|
||||
if existing.icon_assets.is_none() && connector.icon_assets.is_some() {
|
||||
existing.icon_assets = connector.icon_assets;
|
||||
}
|
||||
if existing.icon_dark_assets.is_none() && connector.icon_dark_assets.is_some() {
|
||||
existing.icon_dark_assets = connector.icon_dark_assets;
|
||||
}
|
||||
if existing.distribution_channel.is_none() && connector.distribution_channel.is_some() {
|
||||
existing.distribution_channel = connector.distribution_channel;
|
||||
}
|
||||
existing
|
||||
.plugin_display_names
|
||||
.extend(connector.plugin_display_names);
|
||||
} else {
|
||||
merged.insert(connector_id, connector);
|
||||
}
|
||||
}
|
||||
|
||||
let mut merged = merged.into_values().collect::<Vec<_>>();
|
||||
for connector in &mut merged {
|
||||
if connector.install_url.is_none() {
|
||||
connector.install_url = Some(connector_install_url(&connector.name, &connector.id));
|
||||
}
|
||||
connector.plugin_display_names.sort_unstable();
|
||||
connector.plugin_display_names.dedup();
|
||||
}
|
||||
sort_connectors_by_accessibility_and_name(&mut merged);
|
||||
merged
|
||||
}
|
||||
|
||||
pub fn merge_plugin_connectors<I>(connectors: Vec<AppInfo>, plugin_app_ids: I) -> Vec<AppInfo>
|
||||
where
|
||||
I: IntoIterator<Item = String>,
|
||||
{
|
||||
let mut merged = connectors;
|
||||
let mut connector_ids = merged
|
||||
.iter()
|
||||
.map(|connector| connector.id.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for connector_id in plugin_app_ids {
|
||||
if connector_ids.insert(connector_id.clone()) {
|
||||
merged.push(plugin_connector_to_app_info(connector_id));
|
||||
}
|
||||
}
|
||||
|
||||
sort_connectors_by_accessibility_and_name(&mut merged);
|
||||
merged
|
||||
}
|
||||
|
||||
pub fn merge_plugin_connectors_with_accessible<I>(
|
||||
plugin_app_ids: I,
|
||||
accessible_connectors: Vec<AppInfo>,
|
||||
) -> Vec<AppInfo>
|
||||
where
|
||||
I: IntoIterator<Item = String>,
|
||||
{
|
||||
let accessible_connector_ids: HashSet<&str> = accessible_connectors
|
||||
.iter()
|
||||
.map(|connector| connector.id.as_str())
|
||||
.collect();
|
||||
let plugin_connectors = plugin_app_ids
|
||||
.into_iter()
|
||||
.filter(|connector_id| accessible_connector_ids.contains(connector_id.as_str()))
|
||||
.map(plugin_connector_to_app_info)
|
||||
.collect::<Vec<_>>();
|
||||
merge_connectors(plugin_connectors, accessible_connectors)
|
||||
}
|
||||
|
||||
pub fn plugin_connector_to_app_info(connector_id: String) -> AppInfo {
|
||||
// Leave the placeholder name as the connector id so merge_connectors() can
|
||||
// replace it with canonical app metadata from directory fetches or
|
||||
// connector_name values from codex_apps tool discovery.
|
||||
let name = connector_id.clone();
|
||||
AppInfo {
|
||||
id: connector_id.clone(),
|
||||
name: name.clone(),
|
||||
description: None,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: None,
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
install_url: Some(connector_install_url(&name, &connector_id)),
|
||||
is_accessible: false,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::metadata::connector_install_url;
|
||||
use crate::metadata::connector_mention_slug;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn plugin_names(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
fn google_calendar_accessible_connector(plugin_display_names: &[&str]) -> AppInfo {
|
||||
AppInfo {
|
||||
id: "calendar".to_string(),
|
||||
name: "Google Calendar".to_string(),
|
||||
description: Some("Plan events".to_string()),
|
||||
logo_url: Some("https://example.com/logo.png".to_string()),
|
||||
logo_url_dark: Some("https://example.com/logo-dark.png".to_string()),
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: Some("workspace".to_string()),
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
install_url: None,
|
||||
is_accessible: true,
|
||||
is_enabled: true,
|
||||
plugin_display_names: plugin_names(plugin_display_names),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_connectors_replaces_plugin_placeholder_name_with_accessible_name() {
|
||||
let plugin = plugin_connector_to_app_info("calendar".to_string());
|
||||
let accessible = google_calendar_accessible_connector(&[]);
|
||||
|
||||
let merged = merge_connectors(vec![plugin], vec![accessible]);
|
||||
|
||||
assert_eq!(
|
||||
merged,
|
||||
vec![AppInfo {
|
||||
id: "calendar".to_string(),
|
||||
name: "Google Calendar".to_string(),
|
||||
description: Some("Plan events".to_string()),
|
||||
logo_url: Some("https://example.com/logo.png".to_string()),
|
||||
logo_url_dark: Some("https://example.com/logo-dark.png".to_string()),
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: Some("workspace".to_string()),
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
install_url: Some(connector_install_url("calendar", "calendar")),
|
||||
is_accessible: true,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
}]
|
||||
);
|
||||
assert_eq!(connector_mention_slug(&merged[0]), "google-calendar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_connectors_unions_and_dedupes_plugin_display_names() {
|
||||
let mut plugin = plugin_connector_to_app_info("calendar".to_string());
|
||||
plugin.plugin_display_names = plugin_names(&["sample", "alpha", "sample"]);
|
||||
|
||||
let accessible = google_calendar_accessible_connector(&["beta", "alpha"]);
|
||||
|
||||
let merged = merge_connectors(vec![plugin], vec![accessible]);
|
||||
|
||||
assert_eq!(
|
||||
merged,
|
||||
vec![AppInfo {
|
||||
id: "calendar".to_string(),
|
||||
name: "Google Calendar".to_string(),
|
||||
description: Some("Plan events".to_string()),
|
||||
logo_url: Some("https://example.com/logo.png".to_string()),
|
||||
logo_url_dark: Some("https://example.com/logo-dark.png".to_string()),
|
||||
icon_assets: None,
|
||||
icon_dark_assets: None,
|
||||
distribution_channel: Some("workspace".to_string()),
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
labels: None,
|
||||
install_url: Some(connector_install_url("calendar", "calendar")),
|
||||
is_accessible: true,
|
||||
is_enabled: true,
|
||||
plugin_display_names: plugin_names(&["alpha", "beta", "sample"]),
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
31
codex-rs/connectors/src/metadata.rs
Normal file
31
codex-rs/connectors/src/metadata.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use crate::AppInfo;
|
||||
|
||||
pub fn connector_display_label(connector: &AppInfo) -> String {
|
||||
connector.name.clone()
|
||||
}
|
||||
|
||||
pub fn connector_mention_slug(connector: &AppInfo) -> String {
|
||||
connector_mention_slug_from_name(&connector_display_label(connector))
|
||||
}
|
||||
|
||||
pub fn connector_mention_slug_from_name(name: &str) -> String {
|
||||
crate::connector_name_slug(name)
|
||||
}
|
||||
|
||||
pub fn connector_install_url(name: &str, connector_id: &str) -> String {
|
||||
crate::connector_install_url(name, connector_id)
|
||||
}
|
||||
|
||||
pub fn sanitize_name(name: &str) -> String {
|
||||
crate::connector_name_slug(name).replace("-", "_")
|
||||
}
|
||||
|
||||
pub(crate) fn sort_connectors_by_accessibility_and_name(connectors: &mut [AppInfo]) {
|
||||
connectors.sort_by(|left, right| {
|
||||
right
|
||||
.is_accessible
|
||||
.cmp(&left.is_accessible)
|
||||
.then_with(|| left.name.cmp(&right.name))
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
}
|
||||
144
codex-rs/connectors/src/metadata_store.rs
Normal file
144
codex-rs/connectors/src/metadata_store.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::CONNECTOR_METADATA_CACHE_TTL;
|
||||
|
||||
/// Display-only summary of one app tool returned by the app batch-read API.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConnectorToolSummary {
|
||||
pub name: String,
|
||||
pub title: Option<String>,
|
||||
pub description: String,
|
||||
pub is_enabled: bool,
|
||||
pub disabled_reason: Option<String>,
|
||||
pub is_read_only: bool,
|
||||
}
|
||||
|
||||
/// Metadata returned by the app batch-read API.
|
||||
///
|
||||
/// This intentionally excludes connector runtime state, full actions, and model descriptions.
|
||||
/// Tool summaries contain display text and enabled/read-only state only, and icon URLs are already
|
||||
/// projected as public URLs by the backend.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConnectorMetadata {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub icon_url: Option<String>,
|
||||
pub icon_url_dark: Option<String>,
|
||||
pub distribution_channel: Option<String>,
|
||||
pub tool_summaries: Option<Vec<ConnectorToolSummary>>,
|
||||
}
|
||||
|
||||
/// A view of the process-wide metadata cache bound to one backend and auth identity.
|
||||
///
|
||||
/// The active ChatGPT account id represents the selected personal account or workspace, while the
|
||||
/// ChatGPT user id identifies the account principal. Keeping both plus workspace classification
|
||||
/// matches the existing connector-directory cache partition.
|
||||
pub struct ConnectorMetadataStore {
|
||||
scope: ConnectorMetadataStoreScope,
|
||||
}
|
||||
|
||||
impl ConnectorMetadataStore {
|
||||
pub fn new(
|
||||
backend_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
scope: ConnectorMetadataStoreScope {
|
||||
backend_base_url,
|
||||
account_id,
|
||||
chatgpt_user_id,
|
||||
is_workspace_account,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns only unexpired records for the requested ids, requiring tool summaries when asked.
|
||||
///
|
||||
/// Expired entries are deliberately left in place so a failed refresh cannot mutate prior
|
||||
/// cache state.
|
||||
pub fn fresh_records(
|
||||
&self,
|
||||
ids: &[String],
|
||||
include_tools: bool,
|
||||
) -> HashMap<String, ConnectorMetadata> {
|
||||
let cache = CONNECTOR_METADATA_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some(records) = cache.get(&self.scope) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let now = Instant::now();
|
||||
ids.iter()
|
||||
.filter_map(|id| {
|
||||
records
|
||||
.get(id)
|
||||
.filter(|record| {
|
||||
now < record.expires_at
|
||||
&& (!include_tools || record.metadata.tool_summaries.is_some())
|
||||
})
|
||||
.map(|record| (id.clone(), record.metadata.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Commits successfully fetched records without letting a late metadata-only response
|
||||
/// replace fresh tool summaries.
|
||||
pub fn commit(&self, records: &[ConnectorMetadata]) {
|
||||
if records.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
let expires_at = now + CONNECTOR_METADATA_CACHE_TTL;
|
||||
let mut cache = CONNECTOR_METADATA_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let scoped_records = cache.entry(self.scope.clone()).or_default();
|
||||
for metadata in records {
|
||||
if metadata.tool_summaries.is_none()
|
||||
&& scoped_records.get(&metadata.id).is_some_and(|record| {
|
||||
now < record.expires_at && record.metadata.tool_summaries.is_some()
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
scoped_records.insert(
|
||||
metadata.id.clone(),
|
||||
CachedConnectorMetadata {
|
||||
metadata: metadata.clone(),
|
||||
expires_at,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `apps_mcp_product_sku` affects which tools the batch API returns, but is intentionally omitted
|
||||
// from this key because we assume an app-server does not change its product SKU after launch.
|
||||
// If that assumption changes, the SKU must be included in the cache scope.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct ConnectorMetadataStoreScope {
|
||||
backend_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
}
|
||||
|
||||
struct CachedConnectorMetadata {
|
||||
metadata: ConnectorMetadata,
|
||||
expires_at: Instant,
|
||||
}
|
||||
|
||||
static CONNECTOR_METADATA_CACHE: LazyLock<
|
||||
StdMutex<HashMap<ConnectorMetadataStoreScope, HashMap<String, CachedConnectorMetadata>>>,
|
||||
> = LazyLock::new(|| StdMutex::new(HashMap::new()));
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "metadata_store_tests.rs"]
|
||||
mod tests;
|
||||
152
codex-rs/connectors/src/metadata_store_tests.rs
Normal file
152
codex-rs/connectors/src/metadata_store_tests.rs
Normal file
@@ -0,0 +1,152 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ConnectorMetadata;
|
||||
use super::ConnectorMetadataStore;
|
||||
use super::ConnectorToolSummary;
|
||||
|
||||
fn metadata(id: &str) -> ConnectorMetadata {
|
||||
ConnectorMetadata {
|
||||
id: id.to_string(),
|
||||
name: format!("{id} name"),
|
||||
description: None,
|
||||
icon_url: None,
|
||||
icon_url_dark: None,
|
||||
distribution_channel: None,
|
||||
tool_summaries: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_are_isolated_by_backend_account_user_and_workspace_scope() {
|
||||
let requested_scope = ConnectorMetadataStore::new(
|
||||
"https://backend-a.example".to_string(),
|
||||
Some("account-a".to_string()),
|
||||
Some("user-a".to_string()),
|
||||
/*is_workspace_account*/ true,
|
||||
);
|
||||
let other_backend = ConnectorMetadataStore::new(
|
||||
"https://backend-b.example".to_string(),
|
||||
Some("account-a".to_string()),
|
||||
Some("user-a".to_string()),
|
||||
/*is_workspace_account*/ true,
|
||||
);
|
||||
let other_account = ConnectorMetadataStore::new(
|
||||
"https://backend-a.example".to_string(),
|
||||
Some("account-b".to_string()),
|
||||
Some("user-a".to_string()),
|
||||
/*is_workspace_account*/ true,
|
||||
);
|
||||
let other_user = ConnectorMetadataStore::new(
|
||||
"https://backend-a.example".to_string(),
|
||||
Some("account-a".to_string()),
|
||||
Some("user-b".to_string()),
|
||||
/*is_workspace_account*/ true,
|
||||
);
|
||||
let personal_account = ConnectorMetadataStore::new(
|
||||
"https://backend-a.example".to_string(),
|
||||
Some("account-a".to_string()),
|
||||
Some("user-a".to_string()),
|
||||
/*is_workspace_account*/ false,
|
||||
);
|
||||
let ids = vec!["scoped-app".to_string()];
|
||||
|
||||
requested_scope.commit(&[metadata("scoped-app")]);
|
||||
|
||||
assert_eq!(
|
||||
requested_scope.fresh_records(&ids, /*include_tools*/ false),
|
||||
std::collections::HashMap::from([("scoped-app".to_string(), metadata("scoped-app"))])
|
||||
);
|
||||
assert_eq!(
|
||||
other_backend.fresh_records(&ids, /*include_tools*/ false),
|
||||
Default::default()
|
||||
);
|
||||
assert_eq!(
|
||||
other_account.fresh_records(&ids, /*include_tools*/ false),
|
||||
Default::default()
|
||||
);
|
||||
assert_eq!(
|
||||
other_user.fresh_records(&ids, /*include_tools*/ false),
|
||||
Default::default()
|
||||
);
|
||||
assert_eq!(
|
||||
personal_account.fresh_records(&ids, /*include_tools*/ false),
|
||||
Default::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_inclusive_reads_require_cached_tool_summaries() {
|
||||
let store = ConnectorMetadataStore::new(
|
||||
"https://backend-tools.example".to_string(),
|
||||
Some("account-tools".to_string()),
|
||||
Some("user-tools".to_string()),
|
||||
/*is_workspace_account*/ false,
|
||||
);
|
||||
let metadata_only = metadata("metadata-only");
|
||||
let mut empty_tools = metadata("empty-tools");
|
||||
empty_tools.tool_summaries = Some(Vec::new());
|
||||
let mut with_tools = metadata("with-tools");
|
||||
with_tools.tool_summaries = Some(vec![ConnectorToolSummary {
|
||||
name: "search".to_string(),
|
||||
title: Some("Search".to_string()),
|
||||
description: "Search the app".to_string(),
|
||||
is_enabled: true,
|
||||
disabled_reason: None,
|
||||
is_read_only: true,
|
||||
}]);
|
||||
let ids = vec![
|
||||
"metadata-only".to_string(),
|
||||
"empty-tools".to_string(),
|
||||
"with-tools".to_string(),
|
||||
];
|
||||
|
||||
store.commit(&[
|
||||
metadata_only.clone(),
|
||||
empty_tools.clone(),
|
||||
with_tools.clone(),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
store.fresh_records(&ids, /*include_tools*/ false),
|
||||
std::collections::HashMap::from([
|
||||
("metadata-only".to_string(), metadata_only),
|
||||
("empty-tools".to_string(), empty_tools.clone()),
|
||||
("with-tools".to_string(), with_tools.clone()),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
store.fresh_records(&ids, /*include_tools*/ true),
|
||||
std::collections::HashMap::from([
|
||||
("empty-tools".to_string(), empty_tools),
|
||||
("with-tools".to_string(), with_tools),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_only_commit_does_not_replace_fresh_tool_summaries() {
|
||||
let store = ConnectorMetadataStore::new(
|
||||
"https://backend-tools-race.example".to_string(),
|
||||
Some("account-tools-race".to_string()),
|
||||
Some("user-tools-race".to_string()),
|
||||
/*is_workspace_account*/ false,
|
||||
);
|
||||
let mut with_tools = metadata("with-tools");
|
||||
with_tools.tool_summaries = Some(vec![ConnectorToolSummary {
|
||||
name: "search".to_string(),
|
||||
title: Some("Search".to_string()),
|
||||
description: "Search the app".to_string(),
|
||||
is_enabled: true,
|
||||
disabled_reason: None,
|
||||
is_read_only: true,
|
||||
}]);
|
||||
let ids = vec!["with-tools".to_string()];
|
||||
|
||||
store.commit(&[with_tools.clone()]);
|
||||
store.commit(&[metadata("with-tools")]);
|
||||
|
||||
assert_eq!(
|
||||
store.fresh_records(&ids, /*include_tools*/ true),
|
||||
std::collections::HashMap::from([("with-tools".to_string(), with_tools)])
|
||||
);
|
||||
}
|
||||
50
codex-rs/connectors/src/plugin_config.rs
Normal file
50
codex-rs/connectors/src/plugin_config.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use indexmap::IndexMap;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PluginAppFile {
|
||||
#[serde(default)]
|
||||
apps: IndexMap<String, PluginAppConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct PluginAppConfig {
|
||||
id: String,
|
||||
category: Option<String>,
|
||||
}
|
||||
|
||||
/// Parses connector declarations from a plugin app configuration file.
|
||||
pub fn parse_plugin_app_config(contents: &str) -> serde_json::Result<Vec<AppDeclaration>> {
|
||||
serde_json::from_str(contents).map(app_declarations_from_file)
|
||||
}
|
||||
|
||||
/// Parses connector declarations from an already-decoded plugin app configuration.
|
||||
pub fn parse_plugin_app_config_value(value: Value) -> serde_json::Result<Vec<AppDeclaration>> {
|
||||
serde_json::from_value(value).map(app_declarations_from_file)
|
||||
}
|
||||
|
||||
fn app_declarations_from_file(parsed: PluginAppFile) -> Vec<AppDeclaration> {
|
||||
parsed
|
||||
.apps
|
||||
.into_iter()
|
||||
.map(|(name, app)| AppDeclaration {
|
||||
name,
|
||||
connector_id: AppConnectorId(app.id),
|
||||
category: cleaned_category(app.category),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn cleaned_category(category: Option<String>) -> Option<String> {
|
||||
category
|
||||
.map(|category| category.trim().to_string())
|
||||
.filter(|category| !category.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_config_tests.rs"]
|
||||
mod tests;
|
||||
53
codex-rs/connectors/src/plugin_config_tests.rs
Normal file
53
codex-rs/connectors/src/plugin_config_tests.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::parse_plugin_app_config;
|
||||
|
||||
#[test]
|
||||
fn parses_plugin_app_config_in_order_without_validating_connector_ids() {
|
||||
let parsed = parse_plugin_app_config(
|
||||
r#"{
|
||||
"apps": {
|
||||
"calendar": {
|
||||
"id": "connector_calendar",
|
||||
"category": " productivity "
|
||||
},
|
||||
"drive": {
|
||||
"id": "connector_calendar",
|
||||
"category": " "
|
||||
},
|
||||
"blank": {
|
||||
"id": " "
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("plugin app config should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
vec![
|
||||
AppDeclaration {
|
||||
name: "calendar".to_string(),
|
||||
connector_id: AppConnectorId("connector_calendar".to_string()),
|
||||
category: Some("productivity".to_string()),
|
||||
},
|
||||
AppDeclaration {
|
||||
name: "drive".to_string(),
|
||||
connector_id: AppConnectorId("connector_calendar".to_string()),
|
||||
category: None,
|
||||
},
|
||||
AppDeclaration {
|
||||
name: "blank".to_string(),
|
||||
connector_id: AppConnectorId(" ".to_string()),
|
||||
category: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_plugin_app_config() {
|
||||
assert!(parse_plugin_app_config("not json").is_err());
|
||||
}
|
||||
103
codex-rs/connectors/src/runtime_projection.rs
Normal file
103
codex-rs/connectors/src/runtime_projection.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Connector-owned projection of raw runtime tools into installed app state.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
|
||||
use crate::AppToolPolicyEvaluator;
|
||||
use crate::AppToolPolicyInput;
|
||||
|
||||
/// Connector-relevant fields from one runtime tool.
|
||||
///
|
||||
/// MCP owns the raw tool type and computes generic visibility/filter decisions. Connector
|
||||
/// consumers adapt those fields into this view so connector policy stays out of MCP modules.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ConnectorRuntimeTool<'a> {
|
||||
pub connector_id: Option<&'a str>,
|
||||
pub connector_name: Option<&'a str>,
|
||||
pub tool_name: &'a str,
|
||||
pub tool_title: Option<&'a str>,
|
||||
pub destructive_hint: Option<bool>,
|
||||
pub open_world_hint: Option<bool>,
|
||||
pub synthetic: bool,
|
||||
pub model_visible: bool,
|
||||
}
|
||||
|
||||
/// Installed state derived from one committed connector runtime snapshot.
|
||||
///
|
||||
/// `enabled` and `callable` include local and managed app/tool configuration. Global feature and
|
||||
/// workspace policy remain host concerns and are applied by the caller.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InstalledConnectorRuntime {
|
||||
pub id: String,
|
||||
pub runtime_name: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub callable: bool,
|
||||
}
|
||||
|
||||
/// Projects raw runtime tools into one row per installed connector.
|
||||
pub fn installed_connector_runtime<'a>(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
tools: impl IntoIterator<Item = ConnectorRuntimeTool<'a>>,
|
||||
) -> Vec<InstalledConnectorRuntime> {
|
||||
let policy = AppToolPolicyEvaluator::new(config_layer_stack);
|
||||
let mut apps = BTreeMap::<String, (Option<String>, bool)>::new();
|
||||
|
||||
for tool in tools {
|
||||
if tool.synthetic {
|
||||
continue;
|
||||
}
|
||||
let Some(connector_id) = tool.connector_id.map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if connector_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let runtime_name = tool
|
||||
.connector_name
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string);
|
||||
let entry = apps
|
||||
.entry(connector_id.to_string())
|
||||
.or_insert((None, false));
|
||||
if entry.0.is_none() {
|
||||
entry.0 = runtime_name;
|
||||
}
|
||||
|
||||
let policy_allows_tool = policy
|
||||
.policy(AppToolPolicyInput {
|
||||
connector_id: Some(connector_id),
|
||||
link_id: None,
|
||||
tool_name: tool.tool_name,
|
||||
tool_title: tool.tool_title,
|
||||
destructive_hint: tool.destructive_hint,
|
||||
open_world_hint: tool.open_world_hint,
|
||||
})
|
||||
.enabled;
|
||||
entry.1 |= tool.model_visible && policy_allows_tool;
|
||||
}
|
||||
|
||||
apps.into_iter()
|
||||
.map(|(id, (runtime_name, callable))| InstalledConnectorRuntime {
|
||||
enabled: policy.app_enabled(&id),
|
||||
id,
|
||||
runtime_name,
|
||||
callable,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns whether connector metadata marks a runtime tool as a synthetic link helper.
|
||||
pub fn connector_tool_is_synthetic(connector_meta: Option<&serde_json::Value>) -> bool {
|
||||
connector_meta
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.and_then(|meta| meta.get("synthetic_link"))
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
== Some(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_projection_tests.rs"]
|
||||
mod tests;
|
||||
113
codex-rs/connectors/src/runtime_projection_tests.rs
Normal file
113
codex-rs/connectors/src/runtime_projection_tests.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use codex_config::AppRequirementToml;
|
||||
use codex_config::AppsRequirementsToml;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn projection_deduplicates_apps_and_ignores_non_runtime_tools() {
|
||||
let config = ConfigLayerStack::new(
|
||||
Vec::new(),
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("config layer stack");
|
||||
let apps = installed_connector_runtime(
|
||||
&config,
|
||||
[
|
||||
tool(Some(" drive "), /*connector_name*/ None, "files/list"),
|
||||
tool(Some("drive"), Some(" Drive "), "files/get"),
|
||||
ConnectorRuntimeTool {
|
||||
synthetic: true,
|
||||
..tool(Some("synthetic"), Some("Synthetic"), "link")
|
||||
},
|
||||
tool(Some(" "), Some("Empty"), "empty"),
|
||||
tool(/*connector_id*/ None, Some("Missing"), "missing"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
apps,
|
||||
vec![InstalledConnectorRuntime {
|
||||
id: "drive".to_string(),
|
||||
runtime_name: Some("Drive".to_string()),
|
||||
enabled: true,
|
||||
callable: true,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_applies_managed_app_policy_and_model_visibility() {
|
||||
let requirements = ConfigRequirementsToml {
|
||||
apps: Some(AppsRequirementsToml {
|
||||
apps: BTreeMap::from([(
|
||||
"disabled".to_string(),
|
||||
AppRequirementToml {
|
||||
enabled: Some(false),
|
||||
tools: None,
|
||||
},
|
||||
)]),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let config = ConfigLayerStack::new(Vec::new(), ConfigRequirements::default(), requirements)
|
||||
.expect("config layer stack");
|
||||
let apps = installed_connector_runtime(
|
||||
&config,
|
||||
[
|
||||
tool(Some("disabled"), Some("Disabled"), "disabled/tool"),
|
||||
ConnectorRuntimeTool {
|
||||
model_visible: false,
|
||||
..tool(Some("hidden"), Some("Hidden"), "hidden/tool")
|
||||
},
|
||||
tool(Some("callable"), Some("Callable"), "callable/tool"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
apps,
|
||||
vec![
|
||||
InstalledConnectorRuntime {
|
||||
id: "callable".to_string(),
|
||||
runtime_name: Some("Callable".to_string()),
|
||||
enabled: true,
|
||||
callable: true,
|
||||
},
|
||||
InstalledConnectorRuntime {
|
||||
id: "disabled".to_string(),
|
||||
runtime_name: Some("Disabled".to_string()),
|
||||
enabled: false,
|
||||
callable: false,
|
||||
},
|
||||
InstalledConnectorRuntime {
|
||||
id: "hidden".to_string(),
|
||||
runtime_name: Some("Hidden".to_string()),
|
||||
enabled: true,
|
||||
callable: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn tool<'a>(
|
||||
connector_id: Option<&'a str>,
|
||||
connector_name: Option<&'a str>,
|
||||
tool_name: &'a str,
|
||||
) -> ConnectorRuntimeTool<'a> {
|
||||
ConnectorRuntimeTool {
|
||||
connector_id,
|
||||
connector_name,
|
||||
tool_name,
|
||||
tool_title: None,
|
||||
destructive_hint: None,
|
||||
open_world_hint: None,
|
||||
synthetic: false,
|
||||
model_visible: true,
|
||||
}
|
||||
}
|
||||
155
codex-rs/connectors/src/snapshot.rs
Normal file
155
codex-rs/connectors/src/snapshot.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
|
||||
/// Connector declarations contributed by one plugin package.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginConnectorSource {
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
connector_ids: Vec<AppConnectorId>,
|
||||
}
|
||||
|
||||
impl PluginConnectorSource {
|
||||
/// Creates one plugin source from parsed app declarations.
|
||||
pub fn new(
|
||||
plugin_id: impl Into<String>,
|
||||
plugin_display_name: impl Into<String>,
|
||||
declarations: impl IntoIterator<Item = AppDeclaration>,
|
||||
) -> Self {
|
||||
Self::from_connector_ids(
|
||||
plugin_id,
|
||||
plugin_display_name,
|
||||
declarations
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.connector_id),
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates one plugin source from connector IDs that were already parsed.
|
||||
pub fn from_connector_ids(
|
||||
plugin_id: impl Into<String>,
|
||||
plugin_display_name: impl Into<String>,
|
||||
connector_ids: impl IntoIterator<Item = AppConnectorId>,
|
||||
) -> Self {
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
let connector_ids = connector_ids
|
||||
.into_iter()
|
||||
.filter(|connector_id| !connector_id.0.trim().is_empty())
|
||||
.filter(|connector_id| seen_connector_ids.insert(connector_id.clone()))
|
||||
.collect();
|
||||
Self {
|
||||
plugin_id: plugin_id.into(),
|
||||
plugin_display_name: plugin_display_name.into(),
|
||||
connector_ids,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the package name shown in connector provenance.
|
||||
pub fn plugin_display_name(&self) -> &str {
|
||||
&self.plugin_display_name
|
||||
}
|
||||
|
||||
/// Returns the connector IDs contributed by this package.
|
||||
pub fn connector_ids(&self) -> &[AppConnectorId] {
|
||||
&self.connector_ids
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&PluginCapabilitySummary> for PluginConnectorSource {
|
||||
fn from(summary: &PluginCapabilitySummary) -> Self {
|
||||
Self::from_connector_ids(
|
||||
summary.config_name.clone(),
|
||||
summary.display_name.clone(),
|
||||
summary.app_connector_ids.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable connector selection and provenance after applying disabled plugins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ConnectorSnapshot {
|
||||
connector_ids: Vec<AppConnectorId>,
|
||||
plugin_display_names_by_connector_id: HashMap<String, Vec<String>>,
|
||||
disabled_connector_ids: HashSet<String>,
|
||||
}
|
||||
|
||||
impl ConnectorSnapshot {
|
||||
/// Builds the final selection from all plugin sources, preserving contribution order.
|
||||
/// An enabled contributor preserves a shared connector unless its canonical owner is disabled.
|
||||
pub fn from_plugin_sources(
|
||||
sources: impl IntoIterator<Item = PluginConnectorSource>,
|
||||
disabled_plugin_ids: &[String],
|
||||
canonical_disabled_connector_ids: HashSet<String>,
|
||||
) -> Self {
|
||||
let mut connector_ids = Vec::new();
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
let mut plugin_display_names_by_connector_id: HashMap<String, Vec<String>> = HashMap::new();
|
||||
let mut disabled_connector_ids = HashSet::new();
|
||||
|
||||
for source in sources {
|
||||
if disabled_plugin_ids.contains(&source.plugin_id) {
|
||||
disabled_connector_ids.extend(source.connector_ids.into_iter().map(|id| id.0));
|
||||
continue;
|
||||
}
|
||||
for connector_id in source.connector_ids() {
|
||||
if canonical_disabled_connector_ids.contains(&connector_id.0) {
|
||||
continue;
|
||||
}
|
||||
if seen_connector_ids.insert(connector_id.0.clone()) {
|
||||
connector_ids.push(connector_id.clone());
|
||||
}
|
||||
plugin_display_names_by_connector_id
|
||||
.entry(connector_id.0.clone())
|
||||
.or_default()
|
||||
.push(source.plugin_display_name().to_string());
|
||||
}
|
||||
}
|
||||
for plugin_names in plugin_display_names_by_connector_id.values_mut() {
|
||||
plugin_names.sort_unstable();
|
||||
plugin_names.dedup();
|
||||
}
|
||||
disabled_connector_ids.retain(|id| !seen_connector_ids.contains(id));
|
||||
disabled_connector_ids.extend(canonical_disabled_connector_ids);
|
||||
|
||||
Self {
|
||||
connector_ids,
|
||||
plugin_display_names_by_connector_id,
|
||||
disabled_connector_ids,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapts the current host plugin summaries to the connector-owned snapshot.
|
||||
pub fn from_plugin_capability_summaries(summaries: &[PluginCapabilitySummary]) -> Self {
|
||||
Self::from_plugin_sources(
|
||||
summaries.iter().map(PluginConnectorSource::from),
|
||||
&[],
|
||||
HashSet::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the connector IDs in source contribution order.
|
||||
pub fn connector_ids(&self) -> &[AppConnectorId] {
|
||||
&self.connector_ids
|
||||
}
|
||||
|
||||
/// Connector tools explicitly excluded or excluded by all contributing plugins.
|
||||
pub fn disabled_connector_ids(&self) -> &HashSet<String> {
|
||||
&self.disabled_connector_ids
|
||||
}
|
||||
|
||||
/// Returns the package display names associated with one connector.
|
||||
pub fn plugin_display_names_for_connector_id(&self, connector_id: &str) -> &[String] {
|
||||
self.plugin_display_names_by_connector_id
|
||||
.get(connector_id)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "snapshot_tests.rs"]
|
||||
mod tests;
|
||||
97
codex-rs/connectors/src/snapshot_tests.rs
Normal file
97
codex-rs/connectors/src/snapshot_tests.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use codex_plugin::AppConnectorId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ConnectorSnapshot;
|
||||
use super::PluginConnectorSource;
|
||||
|
||||
#[test]
|
||||
fn snapshot_merges_sources_in_order_and_dedupes_provenance() {
|
||||
let host = [
|
||||
source("skills", "Skills only", &[]),
|
||||
source("host", "Zulu", &["calendar", "calendar"]),
|
||||
];
|
||||
let selected = [
|
||||
source("selected-a", "Alpha", &["drive", "calendar"]),
|
||||
source("selected-b", "Alpha", &["calendar"]),
|
||||
];
|
||||
|
||||
let merged = ConnectorSnapshot::from_plugin_sources(
|
||||
host.into_iter().chain(selected),
|
||||
&[],
|
||||
HashSet::new(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
merged.connector_ids(),
|
||||
&[
|
||||
AppConnectorId("calendar".to_string()),
|
||||
AppConnectorId("drive".to_string()),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
merged.plugin_display_names_for_connector_id("calendar"),
|
||||
&["Alpha".to_string(), "Zulu".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
merged.plugin_display_names_for_connector_id("missing"),
|
||||
&[] as &[String]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_plugins_preserve_shared_connectors() {
|
||||
let sources = [
|
||||
source("alpha", "Alpha", &["exclusive", "shared"]),
|
||||
source("beta", "Beta", &["other", "shared"]),
|
||||
];
|
||||
let filtered = ConnectorSnapshot::from_plugin_sources(
|
||||
sources.clone(),
|
||||
&["alpha".to_string()],
|
||||
HashSet::new(),
|
||||
);
|
||||
|
||||
let expected = ConnectorSnapshot {
|
||||
disabled_connector_ids: HashSet::from(["exclusive".to_string()]),
|
||||
..ConnectorSnapshot::from_plugin_sources(
|
||||
[source("beta", "Beta", &["other", "shared"])],
|
||||
&[],
|
||||
HashSet::new(),
|
||||
)
|
||||
};
|
||||
assert_eq!(filtered, expected);
|
||||
assert_eq!(
|
||||
ConnectorSnapshot::from_plugin_sources(
|
||||
sources.iter().rev().cloned(),
|
||||
&["alpha".to_string()],
|
||||
HashSet::new(),
|
||||
),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
ConnectorSnapshot::from_plugin_sources(
|
||||
sources,
|
||||
&["alpha".to_string(), "beta".to_string()],
|
||||
HashSet::new(),
|
||||
),
|
||||
ConnectorSnapshot {
|
||||
disabled_connector_ids: HashSet::from([
|
||||
"exclusive".to_string(),
|
||||
"other".to_string(),
|
||||
"shared".to_string(),
|
||||
]),
|
||||
..ConnectorSnapshot::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn source(id: &str, display_name: &str, connector_ids: &[&str]) -> PluginConnectorSource {
|
||||
PluginConnectorSource::from_connector_ids(
|
||||
id,
|
||||
display_name,
|
||||
connector_ids
|
||||
.iter()
|
||||
.map(|id| AppConnectorId((*id).to_string())),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user